[PATCH] D89664: [X86] Add missing code in D89102 [X86] Add HRESET instruction.

2020-10-20 Thread Pengfei Wang via Phabricator via cfe-commits
pengfei abandoned this revision.
pengfei added a comment.

HRESET is not supported on Sapphire Rapids. Thanks for pointing it out.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89664

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


[PATCH] D89844: [Clang][OpenMP][WIP] Fixed an issue of segment fault when using target nowait

2020-10-20 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert added a comment.

Generally OK. Unclear if we want to keep a flag so we don't need to test the 
pointer, but I guess it is fine too.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89844

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


[PATCH] D88978: [WIP] Attach debug intrinsics to allocas, and use correct address space

2020-10-20 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert added a comment.

I have no idea what from the commit message what this has to do with the OpenMP 
code gen but I saw this randomly while looking for something else so here we go:

In D88978#2326036 , @scott.linder 
wrote:

> In D88978#2325991 , @ABataev wrote:
>
>> In D88978#2325982 , @scott.linder 
>> wrote:
>>
>>> @ABataev Sorry if I'm pulling you in without enough context/work on my end, 
>>> but I wanted to ask how the Clang codegen for OpenMP locals works at a high 
>>> level?
>>>
>>> Is the idea that instead of an `alloc` the frontend can insert calls into 
>>> the runtime in some cases, like `__kmpc_alloc` (e.g. for `firstprivate` as 
>>> in https://reviews.llvm.org/D5140)?
>>
>> Yes, right.

The frontend does *not* insert `__kmpc_alloc` calls for `firstprivate`, or 
almost anything else for that matter. Grep `clang/lib` and you can find 2 uses, 
both in very specialized cases not related to "regular" user allocations". 
`alloca` is used as with basically everything else: 
https://clang.godbolt.org/z/z8fEqG

>>> If that is the case, I assume there is no equivalent to SROA/Mem2Reg here?
>>
>> I assume, no.
>>
>>> I am trying to understand conceptually where the debug info for the source 
>>> level local should be tied to in the IR, and at least for locals which use 
>>> `alloc` it has turned out to be much simpler to tie the variable directly 
>>> to the `alloc` itself rather than bitcasts and things which obscure the 
>>> relationship.
>
> Ok, thank you! I think the simplest thing is for me to update the patch to 
> tie the debug info to the call to the runtime allocator, then.

SROA/mem2reg is happening as you expect it to. FWIW, we also have heap2stack 
and argument-promotion + constant prop for parallel regions implemented in the 
Attributor. That means we would/will apply SROA/mem2reg even if you have a 
runtime alloca and if the value is nominally "shared" but could be made 
firtprivate.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88978

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


[PATCH] D87956: [IR] add fn attr for no_stack_protector; prevent inlining ssp into nossp

2020-10-20 Thread Bill Wendling via Phabricator via cfe-commits
void added inline comments.



Comment at: llvm/docs/LangRef.rst:1829
+
+If a function with the ``nossp`` attribute calls a callee function that has
+a stack protector function attribute, such as ``ssp``, ``sspreq``, or

Do we care about the opposite situation where a function requiring a stack 
protector doesn't inline a function with the `nossp` attribute?



Comment at: llvm/lib/IR/Attributes.cpp:1901-1902
+  // caller was explicitly annotated as nossp.
+  if (Caller.hasFnAttribute(Attribute::NoStackProtect))
+return;
   // If upgrading the SSP attribute, clear out the old SSP Attributes first.

nickdesaulniers wrote:
> This should be an anomalous situation due to the added verifier check. Should 
> I make it an assert instead?
If it should never happen, then please make it an assert.



Comment at: llvm/lib/IR/Verifier.cpp:1986
+Assert(N < 2,
+   "nossp, ssp, sspreq, sspstrong fn attrs should be mutually "
+   "exclusive",

Could use stronger language here. :-)

"nssp, ssp, sspreq, and sspstrong fn attrs are mutually exclusive."



Comment at: llvm/lib/IR/Verifier.cpp:1977-1984
+if (Attrs.hasFnAttribute(Attribute::NoStackProtect))
+  ++N;
+if (Attrs.hasFnAttribute(Attribute::StackProtect))
+  ++N;
+if (Attrs.hasFnAttribute(Attribute::StackProtectReq))
+  ++N;
+if (Attrs.hasFnAttribute(Attribute::StackProtectStrong))

nickdesaulniers wrote:
> I'd love to cast these booleans to `unsigned` and add them, but I find that 
> all of the `static_casts` don't really make this more concise.  Thoughts?
I think what you have is fine.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87956

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


[PATCH] D89844: [Clang][OpenMP][WIP] Fixed an issue of segment fault when using target nowait

2020-10-20 Thread Shilei Tian via Phabricator via cfe-commits
tianshilei1992 created this revision.
tianshilei1992 added reviewers: jdoerfert, grokos, ye-luo.
Herald added subscribers: cfe-commits, guansong, yaxunl.
Herald added a project: clang.
tianshilei1992 requested review of this revision.
Herald added a subscriber: sstefan1.

The implementation of target nowait just wraps the target region into a
task. The essential four parameters (base ptr, ptr, size, mapper) are taken as
firstprivate such that they will be copied to the private location. When there
is no user-defined mapper, the mapper variable will be nullptr. However, it will
be still copied to the corresponding place. Therefore, a memcpy will be 
generated
and the source pointer will be nullptr, causing a segmentation fault.

In this patch, it will first checks whether the mapper is a constant nullptr. If
so, the firstprivate field and corresponding copy will not be generated.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D89844

Files:
  clang/lib/CodeGen/CGStmtOpenMP.cpp


Index: clang/lib/CodeGen/CGStmtOpenMP.cpp
===
--- clang/lib/CodeGen/CGStmtOpenMP.cpp
+++ clang/lib/CodeGen/CGStmtOpenMP.cpp
@@ -4210,16 +4210,24 @@
 /*IndexTypeQuals=*/0);
 SVD = createImplicitFirstprivateForType(getContext(), Data, SizesType, CD,
 S.getBeginLoc());
-MVD = createImplicitFirstprivateForType(
-getContext(), Data, BaseAndPointerAndMapperType, CD, S.getBeginLoc());
 TargetScope.addPrivate(
 BPVD, []() { return InputInfo.BasePointersArray; });
 TargetScope.addPrivate(PVD,
[]() { return InputInfo.PointersArray; });
 TargetScope.addPrivate(SVD,
[]() { return InputInfo.SizesArray; });
-TargetScope.addPrivate(MVD,
-   []() { return InputInfo.MappersArray; });
+// Mapper can be nullptr if user doesn't provide any. We will not take it
+// into account in this case.
+if (auto *Ptr = dyn_cast_or_null(
+InputInfo.MappersArray.getPointer())) {
+  if (!Ptr->isNullValue()) {
+MVD = createImplicitFirstprivateForType(getContext(), Data,
+BaseAndPointerAndMapperType, 
CD,
+S.getBeginLoc());
+TargetScope.addPrivate(
+MVD, []() { return InputInfo.MappersArray; });
+  }
+}
   }
   (void)TargetScope.Privatize();
   // Build list of dependences.
@@ -4269,8 +4277,10 @@
   CGF.GetAddrOfLocalVar(PVD), /*Index=*/0);
   InputInfo.SizesArray = CGF.Builder.CreateConstArrayGEP(
   CGF.GetAddrOfLocalVar(SVD), /*Index=*/0);
-  InputInfo.MappersArray = CGF.Builder.CreateConstArrayGEP(
-  CGF.GetAddrOfLocalVar(MVD), /*Index=*/0);
+  // MVD can be nullptr if there is no user-defined mapper
+  if (MVD)
+InputInfo.MappersArray = CGF.Builder.CreateConstArrayGEP(
+CGF.GetAddrOfLocalVar(MVD), /*Index=*/0);
 }
 
 Action.Enter(CGF);


Index: clang/lib/CodeGen/CGStmtOpenMP.cpp
===
--- clang/lib/CodeGen/CGStmtOpenMP.cpp
+++ clang/lib/CodeGen/CGStmtOpenMP.cpp
@@ -4210,16 +4210,24 @@
 /*IndexTypeQuals=*/0);
 SVD = createImplicitFirstprivateForType(getContext(), Data, SizesType, CD,
 S.getBeginLoc());
-MVD = createImplicitFirstprivateForType(
-getContext(), Data, BaseAndPointerAndMapperType, CD, S.getBeginLoc());
 TargetScope.addPrivate(
 BPVD, []() { return InputInfo.BasePointersArray; });
 TargetScope.addPrivate(PVD,
[]() { return InputInfo.PointersArray; });
 TargetScope.addPrivate(SVD,
[]() { return InputInfo.SizesArray; });
-TargetScope.addPrivate(MVD,
-   []() { return InputInfo.MappersArray; });
+// Mapper can be nullptr if user doesn't provide any. We will not take it
+// into account in this case.
+if (auto *Ptr = dyn_cast_or_null(
+InputInfo.MappersArray.getPointer())) {
+  if (!Ptr->isNullValue()) {
+MVD = createImplicitFirstprivateForType(getContext(), Data,
+BaseAndPointerAndMapperType, CD,
+S.getBeginLoc());
+TargetScope.addPrivate(
+MVD, []() { return InputInfo.MappersArray; });
+  }
+}
   }
   (void)TargetScope.Privatize();
   // Build list of dependences.
@@ -4269,8 +4277,10 @@
   CGF.GetAddrOfLocalVar(PVD), /*Index=*/0);
   InputInfo.SizesArray = CGF.Builder.CreateConstArrayGEP(
   CGF.GetAddrOfLocalVar(SVD), /*Index=*/0);
-  InputInfo.MappersArray = CGF.Builder.CreateConstArrayGEP(
-  CGF.GetAddrOfLocalVar(MVD), /*Index=*/0);
+  // MVD can be 

[PATCH] D89301: [X86] Add User Interrupts(UINTR) instructions

2020-10-20 Thread Craig Topper via Phabricator via cfe-commits
craig.topper accepted this revision.
craig.topper added a comment.
This revision is now accepted and ready to land.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89301

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


[PATCH] D85474: Add -fbinutils-version= to gate ELF features on the specified binutils version

2020-10-20 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

In D85474#2343356 , @dexonsmith wrote:

> In D85474#2343326 , @MaskRay wrote:
>
>> In D85474#2342365 , @compnerd wrote:
>>
>>> Is there a reason to not use the existing `-mlinker-version=` option and 
>>> expanding that beyond just Darwin targets?  I feel like having the same 
>>> option would be much nicer.
>
> I agree with @compnerd that it seems better to reuse this if possible. I 
> wasn't around back then, but I have to assume it was named generically in 
> order to enable that.
>
>> `-mlinker-version` is currently a macOS option. We could reuse it but that 
>> would be confusing: when -fuse-ld=lld is specified, does it specify the lld 
>> version? (No)
>
> Maybe it should?

Then there is an expanded use case, -fuse-ld= which is just a driver option for 
linking, will now affect code generation.

>> There are also GNU as related issues.
>
> I don't understand this bit.

This is the main point. Many feature are also related to the version of GNU 
assembler when -fno-integrated-as is specified.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D85474

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


[PATCH] D89749: SourceManager: Don't allocate an SLocEntry until it's loaded

2020-10-20 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith added a comment.

This should be complementary to https://reviews.llvm.org/D89580, but I think 
it's independent.


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

https://reviews.llvm.org/D89749

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


[PATCH] D85474: Add -fbinutils-version= to gate ELF features on the specified binutils version

2020-10-20 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith added a comment.

In D85474#2343326 , @MaskRay wrote:

> In D85474#2342365 , @compnerd wrote:
>
>> Is there a reason to not use the existing `-mlinker-version=` option and 
>> expanding that beyond just Darwin targets?  I feel like having the same 
>> option would be much nicer.

I agree with @compnerd that it seems better to reuse this if possible. I wasn't 
around back then, but I have to assume it was named generically in order to 
enable that.

> `-mlinker-version` is currently a macOS option. We could reuse it but that 
> would be confusing: when -fuse-ld=lld is specified, does it specify the lld 
> version? (No)

Maybe it should?

> There are also GNU as related issues.

I don't understand this bit.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D85474

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


Re: [PATCH] D89500: Fix the error message with -fbasic-block-sections=list=

2020-10-20 Thread Sriraman Tallam via cfe-commits
On Tue, Oct 20, 2020 at 6:19 PM Nico Weber via Phabricator
 wrote:
>
> thakis added a comment.
>
> Looks like this breaks tests on windows: 
> http://45.33.8.238/win/26253/step_7.txt
>
> Please take a look and revert for now if it takes a while to fix.

Sorry I saw this message late.
Looks like Fangrui already fixed it.

Thanks
Sri

>
>
> Repository:
>   rG LLVM Github Monorepo
>
> CHANGES SINCE LAST ACTION
>   https://reviews.llvm.org/D89500/new/
>
> https://reviews.llvm.org/D89500
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D89684: [AIX] Add mvecnvol and mnovecnvol options to enable the AIX extended and default vector ABIs.

2020-10-20 Thread Hubert Tong via Phabricator via cfe-commits
hubert.reinterpretcast added a comment.

In D89684#2341922 , 
@hubert.reinterpretcast wrote:

> `-mabi=aixvecextabi` was suggested when I discussed this with someone who is 
> familiar with GCC. The choice of `extabi` at the end is to match the spelling 
> of the `__EXTABI__` macro.

To reduce the length of the option, and with the hopes that future 
vector-related ABI extensions on Power have more specific naming than just 
being the "extended" ABI, the updated suggestion is `-mabi=vec-extabi`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89684

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


[PATCH] D89799: [clang][driver] Rename DriverOption as NoXarchOption (NFC)

2020-10-20 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a subscriber: yaxunl.
MaskRay added a comment.

@yaxunl


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89799

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


[clang] 829b9f6 - [test] Fix -fbasic-block-sections= test on Windows after D89500

2020-10-20 Thread Fangrui Song via cfe-commits

Author: Fangrui Song
Date: 2020-10-20T18:31:28-07:00
New Revision: 829b9f6606af03e24d7715712e05c941d1c661ce

URL: 
https://github.com/llvm/llvm-project/commit/829b9f6606af03e24d7715712e05c941d1c661ce
DIFF: 
https://github.com/llvm/llvm-project/commit/829b9f6606af03e24d7715712e05c941d1c661ce.diff

LOG: [test] Fix -fbasic-block-sections= test on Windows after D89500

Added: 


Modified: 
clang/test/CodeGen/basic-block-sections.c

Removed: 




diff  --git a/clang/test/CodeGen/basic-block-sections.c 
b/clang/test/CodeGen/basic-block-sections.c
index f07a387685c86..3d68394bb78eb 100644
--- a/clang/test/CodeGen/basic-block-sections.c
+++ b/clang/test/CodeGen/basic-block-sections.c
@@ -39,4 +39,4 @@ int another(int a) {
 //
 // UNIQUE: .section .text.world.world.1,
 // UNIQUE: .section .text.another.another.1,
-// ERROR: error:  unable to load basic block sections function list: 'No such 
file or directory'
+// ERROR: error:  unable to load basic block sections function list: 
'{{[Nn]}}o such file or directory'



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


[PATCH] D85474: Add -fbinutils-version= to gate ELF features on the specified binutils version

2020-10-20 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

In D85474#2342365 , @compnerd wrote:

> Is there a reason to not use the existing `-mlinker-version=` option and 
> expanding that beyond just Darwin targets?  I feel like having the same 
> option would be much nicer.

`-mlinker-version` is currently a macOS option. We could reuse it but that 
would be confusing: when -fuse-ld=lld is specified, does it specify the lld 
version? (No)
There are also GNU as related issues.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D85474

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


[clang] 4aa97e3 - SourceManager: Simplify early returns in ContentCache::getBufferOrNone, NFC

2020-10-20 Thread Duncan P . N . Exon Smith via cfe-commits

Author: Duncan P. N. Exon Smith
Date: 2020-10-20T21:26:37-04:00
New Revision: 4aa97e3dacf3bdf5636fbf89dd8c64f1e4648065

URL: 
https://github.com/llvm/llvm-project/commit/4aa97e3dacf3bdf5636fbf89dd8c64f1e4648065
DIFF: 
https://github.com/llvm/llvm-project/commit/4aa97e3dacf3bdf5636fbf89dd8c64f1e4648065.diff

LOG: SourceManager: Simplify early returns in ContentCache::getBufferOrNone, NFC

As suggested in the review for https://reviews.llvm.org/D89430, simplify
the logic for marking the buffer as invalid in the early return paths.

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

Added: 


Modified: 
clang/lib/Basic/SourceManager.cpp

Removed: 




diff  --git a/clang/lib/Basic/SourceManager.cpp 
b/clang/lib/Basic/SourceManager.cpp
index 84315bf3f8ae..f61b4e2a2281 100644
--- a/clang/lib/Basic/SourceManager.cpp
+++ b/clang/lib/Basic/SourceManager.cpp
@@ -111,6 +111,10 @@ ContentCache::getBufferOrNone(DiagnosticsEngine , 
FileManager ,
   if (!ContentsEntry)
 return None;
 
+  // Start with the assumption that the buffer is invalid to simplify early
+  // return paths.
+  IsBufferInvalid = true;
+
   // Check that the file's size fits in an 'unsigned' (with room for a
   // past-the-end value). This is deeply regrettable, but various parts of
   // Clang (including elsewhere in this file!) use 'unsigned' to represent file
@@ -125,7 +129,6 @@ ContentCache::getBufferOrNone(DiagnosticsEngine , 
FileManager ,
   Diag.Report(Loc, diag::err_file_too_large)
 << ContentsEntry->getName();
 
-IsBufferInvalid = true;
 return None;
   }
 
@@ -145,7 +148,6 @@ ContentCache::getBufferOrNone(DiagnosticsEngine , 
FileManager ,
   Diag.Report(Loc, diag::err_cannot_open_file)
   << ContentsEntry->getName() << BufferOrError.getError().message();
 
-IsBufferInvalid = true;
 return None;
   }
 
@@ -161,7 +163,6 @@ ContentCache::getBufferOrNone(DiagnosticsEngine , 
FileManager ,
   Diag.Report(Loc, diag::err_file_modified)
 << ContentsEntry->getName();
 
-IsBufferInvalid = true;
 return None;
   }
 
@@ -174,10 +175,11 @@ ContentCache::getBufferOrNone(DiagnosticsEngine , 
FileManager ,
   if (InvalidBOM) {
 Diag.Report(Loc, diag::err_unsupported_bom)
   << InvalidBOM << ContentsEntry->getName();
-IsBufferInvalid = true;
 return None;
   }
 
+  // Buffer has been validated.
+  IsBufferInvalid = false;
   return Buffer->getMemBufferRef();
 }
 



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


[PATCH] D89722: SourceManager: Simplify early returns in ContentCache::getBufferOrNone, NFC

2020-10-20 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG4aa97e3dacf3: SourceManager: Simplify early returns in 
ContentCache::getBufferOrNone, NFC (authored by dexonsmith).
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89722

Files:
  clang/lib/Basic/SourceManager.cpp


Index: clang/lib/Basic/SourceManager.cpp
===
--- clang/lib/Basic/SourceManager.cpp
+++ clang/lib/Basic/SourceManager.cpp
@@ -111,6 +111,10 @@
   if (!ContentsEntry)
 return None;
 
+  // Start with the assumption that the buffer is invalid to simplify early
+  // return paths.
+  IsBufferInvalid = true;
+
   // Check that the file's size fits in an 'unsigned' (with room for a
   // past-the-end value). This is deeply regrettable, but various parts of
   // Clang (including elsewhere in this file!) use 'unsigned' to represent file
@@ -125,7 +129,6 @@
   Diag.Report(Loc, diag::err_file_too_large)
 << ContentsEntry->getName();
 
-IsBufferInvalid = true;
 return None;
   }
 
@@ -145,7 +148,6 @@
   Diag.Report(Loc, diag::err_cannot_open_file)
   << ContentsEntry->getName() << BufferOrError.getError().message();
 
-IsBufferInvalid = true;
 return None;
   }
 
@@ -161,7 +163,6 @@
   Diag.Report(Loc, diag::err_file_modified)
 << ContentsEntry->getName();
 
-IsBufferInvalid = true;
 return None;
   }
 
@@ -174,10 +175,11 @@
   if (InvalidBOM) {
 Diag.Report(Loc, diag::err_unsupported_bom)
   << InvalidBOM << ContentsEntry->getName();
-IsBufferInvalid = true;
 return None;
   }
 
+  // Buffer has been validated.
+  IsBufferInvalid = false;
   return Buffer->getMemBufferRef();
 }
 


Index: clang/lib/Basic/SourceManager.cpp
===
--- clang/lib/Basic/SourceManager.cpp
+++ clang/lib/Basic/SourceManager.cpp
@@ -111,6 +111,10 @@
   if (!ContentsEntry)
 return None;
 
+  // Start with the assumption that the buffer is invalid to simplify early
+  // return paths.
+  IsBufferInvalid = true;
+
   // Check that the file's size fits in an 'unsigned' (with room for a
   // past-the-end value). This is deeply regrettable, but various parts of
   // Clang (including elsewhere in this file!) use 'unsigned' to represent file
@@ -125,7 +129,6 @@
   Diag.Report(Loc, diag::err_file_too_large)
 << ContentsEntry->getName();
 
-IsBufferInvalid = true;
 return None;
   }
 
@@ -145,7 +148,6 @@
   Diag.Report(Loc, diag::err_cannot_open_file)
   << ContentsEntry->getName() << BufferOrError.getError().message();
 
-IsBufferInvalid = true;
 return None;
   }
 
@@ -161,7 +163,6 @@
   Diag.Report(Loc, diag::err_file_modified)
 << ContentsEntry->getName();
 
-IsBufferInvalid = true;
 return None;
   }
 
@@ -174,10 +175,11 @@
   if (InvalidBOM) {
 Diag.Report(Loc, diag::err_unsupported_bom)
   << InvalidBOM << ContentsEntry->getName();
-IsBufferInvalid = true;
 return None;
   }
 
+  // Buffer has been validated.
+  IsBufferInvalid = false;
   return Buffer->getMemBufferRef();
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D79773: [clang-format] Improve clang-formats handling of concepts

2020-10-20 Thread Johel Ernesto Guerrero Peña via Phabricator via cfe-commits
JohelEGP added a comment.

Could you do a rebase? The patch no longer applies:

  error: patch failed: clang/docs/ClangFormatStyleOptions.rst:2711
  error: clang/docs/ClangFormatStyleOptions.rst: patch does not apply
  error: patch failed: clang/docs/ReleaseNotes.rst:398
  error: clang/docs/ReleaseNotes.rst: patch does not apply
  error: patch failed: clang/lib/Format/FormatToken.h:470
  error: clang/lib/Format/FormatToken.h: patch does not apply
  error: patch failed: clang/lib/Format/TokenAnnotator.cpp:1337
  error: clang/lib/Format/TokenAnnotator.cpp: patch does not apply


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

https://reviews.llvm.org/D79773

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


[PATCH] D89500: Fix the error message with -fbasic-block-sections=list=

2020-10-20 Thread Nico Weber via Phabricator via cfe-commits
thakis added a comment.

Looks like this breaks tests on windows: http://45.33.8.238/win/26253/step_7.txt

Please take a look and revert for now if it takes a while to fix.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89500

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


[clang] 2963145 - ContentCache: Simplify by always owning the MemoryBuffer

2020-10-20 Thread Duncan P . N . Exon Smith via cfe-commits

Author: Duncan P. N. Exon Smith
Date: 2020-10-20T21:03:53-04:00
New Revision: 296314516d103f8eeb987a08b509c1381cfeef89

URL: 
https://github.com/llvm/llvm-project/commit/296314516d103f8eeb987a08b509c1381cfeef89
DIFF: 
https://github.com/llvm/llvm-project/commit/296314516d103f8eeb987a08b509c1381cfeef89.diff

LOG: ContentCache: Simplify by always owning the MemoryBuffer

This changes `ContentCache::Buffer` to use
`std::unique_ptr` instead of the `PointerIntPair`. It
drops the (mostly unused) `DoNotFree` bit, instead creating a (new)
non-owning `MemoryBuffer` instance when passed a `MemoryBufferRef`.

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

Added: 


Modified: 
clang/include/clang/Basic/SourceManager.h
clang/lib/Basic/SourceManager.cpp
clang/lib/Frontend/CompilerInstance.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/SourceManager.h 
b/clang/include/clang/Basic/SourceManager.h
index 569ef002d387..65c3de5a1e41 100644
--- a/clang/include/clang/Basic/SourceManager.h
+++ b/clang/include/clang/Basic/SourceManager.h
@@ -94,17 +94,9 @@ namespace SrcMgr {
   ///
   /// This object owns the MemoryBuffer object.
   class alignas(8) ContentCache {
-enum CCFlags {
-  /// Whether the buffer should not be freed on destruction.
-  DoNotFreeFlag = 0x02
-};
-
 /// The actual buffer containing the characters from the input
 /// file.
-///
-/// This is owned by the ContentCache object.  The bits indicate
-/// whether the buffer is invalid.
-mutable llvm::PointerIntPair Buffer;
+mutable std::unique_ptr Buffer;
 
   public:
 /// Reference to the file entry representing this ContentCache.
@@ -153,21 +145,19 @@ namespace SrcMgr {
 ContentCache(const FileEntry *Ent = nullptr) : ContentCache(Ent, Ent) {}
 
 ContentCache(const FileEntry *Ent, const FileEntry *contentEnt)
-: Buffer(nullptr, false), OrigEntry(Ent), ContentsEntry(contentEnt),
-  BufferOverridden(false), IsFileVolatile(false), IsTransient(false),
-  IsBufferInvalid(false) {}
+: OrigEntry(Ent), ContentsEntry(contentEnt), BufferOverridden(false),
+  IsFileVolatile(false), IsTransient(false), IsBufferInvalid(false) {}
 
 /// The copy ctor does not allow copies where source object has either
 /// a non-NULL Buffer or SourceLineCache.  Ownership of allocated memory
 /// is not transferred, so this is a logical error.
 ContentCache(const ContentCache )
-: Buffer(nullptr, false), BufferOverridden(false),
-  IsFileVolatile(false), IsTransient(false), IsBufferInvalid(false) {
+: BufferOverridden(false), IsFileVolatile(false), IsTransient(false),
+  IsBufferInvalid(false) {
   OrigEntry = RHS.OrigEntry;
   ContentsEntry = RHS.ContentsEntry;
 
-  assert(RHS.Buffer.getPointer() == nullptr &&
- RHS.SourceLineCache == nullptr &&
+  assert(!RHS.Buffer && RHS.SourceLineCache == nullptr &&
  "Passed ContentCache object cannot own a buffer.");
 
   NumLines = RHS.NumLines;
@@ -175,8 +165,6 @@ namespace SrcMgr {
 
 ContentCache =(const ContentCache& RHS) = delete;
 
-~ContentCache();
-
 /// Returns the memory buffer for the associated content.
 ///
 /// \param Diag Object through which diagnostics will be emitted if the
@@ -208,17 +196,21 @@ namespace SrcMgr {
 
 /// Get the underlying buffer, returning NULL if the buffer is not
 /// yet available.
-const llvm::MemoryBuffer *getRawBuffer() const {
-  return Buffer.getPointer();
-}
+const llvm::MemoryBuffer *getRawBuffer() const { return Buffer.get(); }
 
-/// Replace the existing buffer (which will be deleted)
-/// with the given buffer.
-void replaceBuffer(const llvm::MemoryBuffer *B, bool DoNotFree = false);
+/// Set the buffer.
+void setBuffer(std::unique_ptr B) {
+  IsBufferInvalid = false;
+  Buffer = std::move(B);
+}
 
-/// Determine whether the buffer should be freed.
-bool shouldFreeBuffer() const {
-  return (Buffer.getInt() & DoNotFreeFlag) == 0;
+/// Set the buffer to one that's not owned (or to nullptr).
+///
+/// \pre Buffer cannot already be set.
+void setUnownedBuffer(const llvm::MemoryBuffer *B) {
+  assert(!Buffer && "Expected to be called right after construction");
+  if (B)
+setBuffer(llvm::MemoryBuffer::getMemBuffer(B->getMemBufferRef()));
 }
 
 // If BufStr has an invalid BOM, returns the BOM name; otherwise, returns
@@ -905,16 +897,21 @@ class SourceManager : public 
RefCountedBase {
   ///
   /// \param Buffer the memory buffer whose contents will be used as the
   /// data in the given source file.
-  ///
-  /// \param DoNotFree If true, then the buffer will not be freed when the
-  /// source manager is destroyed.
-  void overrideFileContents(const FileEntry *SourceFile,
-  

[PATCH] D67030: ContentCache: Simplify by always owning the MemoryBuffer

2020-10-20 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG296314516d10: ContentCache: Simplify by always owning the 
MemoryBuffer (authored by dexonsmith).
Herald added a project: clang.

Changed prior to commit:
  https://reviews.llvm.org/D67030?vs=298257=299529#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D67030

Files:
  clang/include/clang/Basic/SourceManager.h
  clang/lib/Basic/SourceManager.cpp
  clang/lib/Frontend/CompilerInstance.cpp

Index: clang/lib/Frontend/CompilerInstance.cpp
===
--- clang/lib/Frontend/CompilerInstance.cpp
+++ clang/lib/Frontend/CompilerInstance.cpp
@@ -346,10 +346,16 @@
   continue;
 }
 
-// Override the contents of the "from" file with the contents of
-// the "to" file.
-SourceMgr.overrideFileContents(FromFile, RB.second,
-   InitOpts.RetainRemappedFileBuffers);
+// Override the contents of the "from" file with the contents of the
+// "to" file. If the caller owns the buffers, then pass a MemoryBufferRef;
+// otherwise, pass as a std::unique_ptr to transfer ownership
+// to the SourceManager.
+if (InitOpts.RetainRemappedFileBuffers)
+  SourceMgr.overrideFileContents(FromFile, RB.second->getMemBufferRef());
+else
+  SourceMgr.overrideFileContents(
+  FromFile, std::unique_ptr(
+const_cast(RB.second)));
   }
 
   // Remap files in the source manager (with other files).
Index: clang/lib/Basic/SourceManager.cpp
===
--- clang/lib/Basic/SourceManager.cpp
+++ clang/lib/Basic/SourceManager.cpp
@@ -49,28 +49,22 @@
 // SourceManager Helper Classes
 //===--===//
 
-ContentCache::~ContentCache() {
-  if (shouldFreeBuffer())
-delete Buffer.getPointer();
-}
-
 /// getSizeBytesMapped - Returns the number of bytes actually mapped for this
 /// ContentCache. This can be 0 if the MemBuffer was not actually expanded.
 unsigned ContentCache::getSizeBytesMapped() const {
-  return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0;
+  return Buffer ? Buffer->getBufferSize() : 0;
 }
 
 /// Returns the kind of memory used to back the memory buffer for
 /// this content cache.  This is used for performance analysis.
 llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const {
-  assert(Buffer.getPointer());
+  assert(Buffer);
 
   // Should be unreachable, but keep for sanity.
-  if (!Buffer.getPointer())
+  if (!Buffer)
 return llvm::MemoryBuffer::MemoryBuffer_Malloc;
 
-  const llvm::MemoryBuffer *buf = Buffer.getPointer();
-  return buf->getBufferKind();
+  return Buffer->getBufferKind();
 }
 
 /// getSize - Returns the size of the content encapsulated by this ContentCache.
@@ -78,21 +72,8 @@
 ///  scratch buffer.  If the ContentCache encapsulates a source file, that
 ///  file is not lazily brought in from disk to satisfy this query.
 unsigned ContentCache::getSize() const {
-  return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize()
- : (unsigned) ContentsEntry->getSize();
-}
-
-void ContentCache::replaceBuffer(const llvm::MemoryBuffer *B, bool DoNotFree) {
-  if (B && B == Buffer.getPointer()) {
-assert(0 && "Replacing with the same buffer");
-Buffer.setInt(DoNotFree? DoNotFreeFlag : 0);
-return;
-  }
-
-  if (shouldFreeBuffer())
-delete Buffer.getPointer();
-  Buffer.setPointer(B);
-  Buffer.setInt((B && DoNotFree) ? DoNotFreeFlag : 0);
+  return Buffer ? (unsigned)Buffer->getBufferSize()
+: (unsigned)ContentsEntry->getSize();
 }
 
 const char *ContentCache::getInvalidBOM(StringRef BufStr) {
@@ -125,8 +106,8 @@
   // computed it, just return what we have.
   if (IsBufferInvalid)
 return None;
-  if (auto *B = Buffer.getPointer())
-return B->getMemBufferRef();
+  if (Buffer)
+return Buffer->getMemBufferRef();
   if (!ContentsEntry)
 return None;
 
@@ -168,7 +149,7 @@
 return None;
   }
 
-  Buffer.setPointer(BufferOrError->release());
+  Buffer = std::move(*BufferOrError);
 
   // Check that the file's size is the same as in the file entry (which may
   // have come from a stat cache).
@@ -187,7 +168,7 @@
   // If the buffer is valid, check to see if it has a UTF Byte Order Mark
   // (BOM).  We only support UTF-8 with and without a BOM right now.  See
   // http://en.wikipedia.org/wiki/Byte_order_mark for more information.
-  StringRef BufStr = Buffer.getPointer()->getBuffer();
+  StringRef BufStr = Buffer->getBuffer();
   const char *InvalidBOM = getInvalidBOM(BufStr);
 
   if (InvalidBOM) {
@@ -197,7 +178,7 @@
 return None;
   }
 
-  return Buffer.getPointer()->getMemBufferRef();
+  return Buffer->getMemBufferRef();
 }
 
 

[PATCH] D89612: NFC: Fix -Wsign-compare warnings on 32-bit builds

2020-10-20 Thread Hubert Tong via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG134ffa8138c3: NFC: Fix -Wsign-compare warnings on 32-bit 
builds (authored by hubert.reinterpretcast).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89612

Files:
  clang/lib/Serialization/ASTReaderStmt.cpp
  llvm/lib/CodeGen/StackMaps.cpp


Index: llvm/lib/CodeGen/StackMaps.cpp
===
--- llvm/lib/CodeGen/StackMaps.cpp
+++ llvm/lib/CodeGen/StackMaps.cpp
@@ -401,7 +401,7 @@
 SmallVector GCPtrIndices;
 unsigned GCPtrIdx = (unsigned)SO.getFirstGCPtrIdx();
 assert((int)GCPtrIdx != -1);
-assert(MOI - MI.operands_begin() == GCPtrIdx);
+assert(MOI - MI.operands_begin() == GCPtrIdx + 0LL);
 while (NumGCPointers--) {
   GCPtrIndices.push_back(GCPtrIdx);
   GCPtrIdx = StackMaps::getNextMetaArgIdx(, GCPtrIdx);
Index: clang/lib/Serialization/ASTReaderStmt.cpp
===
--- clang/lib/Serialization/ASTReaderStmt.cpp
+++ clang/lib/Serialization/ASTReaderStmt.cpp
@@ -2186,9 +2186,9 @@
   unsigned NumArgs = Record.readInt();
   E->BeginLoc = readSourceLocation();
   E->EndLoc = readSourceLocation();
-  assert(
-  (NumArgs == std::distance(E->children().begin(), E->children().end())) &&
-  "Wrong NumArgs!");
+  assert((NumArgs + 0LL ==
+  std::distance(E->children().begin(), E->children().end())) &&
+ "Wrong NumArgs!");
   (void)NumArgs;
   for (Stmt * : E->children())
 Child = Record.readSubStmt();


Index: llvm/lib/CodeGen/StackMaps.cpp
===
--- llvm/lib/CodeGen/StackMaps.cpp
+++ llvm/lib/CodeGen/StackMaps.cpp
@@ -401,7 +401,7 @@
 SmallVector GCPtrIndices;
 unsigned GCPtrIdx = (unsigned)SO.getFirstGCPtrIdx();
 assert((int)GCPtrIdx != -1);
-assert(MOI - MI.operands_begin() == GCPtrIdx);
+assert(MOI - MI.operands_begin() == GCPtrIdx + 0LL);
 while (NumGCPointers--) {
   GCPtrIndices.push_back(GCPtrIdx);
   GCPtrIdx = StackMaps::getNextMetaArgIdx(, GCPtrIdx);
Index: clang/lib/Serialization/ASTReaderStmt.cpp
===
--- clang/lib/Serialization/ASTReaderStmt.cpp
+++ clang/lib/Serialization/ASTReaderStmt.cpp
@@ -2186,9 +2186,9 @@
   unsigned NumArgs = Record.readInt();
   E->BeginLoc = readSourceLocation();
   E->EndLoc = readSourceLocation();
-  assert(
-  (NumArgs == std::distance(E->children().begin(), E->children().end())) &&
-  "Wrong NumArgs!");
+  assert((NumArgs + 0LL ==
+  std::distance(E->children().begin(), E->children().end())) &&
+ "Wrong NumArgs!");
   (void)NumArgs;
   for (Stmt * : E->children())
 Child = Record.readSubStmt();
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 134ffa8 - NFC: Fix -Wsign-compare warnings on 32-bit builds

2020-10-20 Thread Hubert Tong via cfe-commits

Author: Hubert Tong
Date: 2020-10-20T20:52:10-04:00
New Revision: 134ffa8138c31444685013e10f592cd7c88d675b

URL: 
https://github.com/llvm/llvm-project/commit/134ffa8138c31444685013e10f592cd7c88d675b
DIFF: 
https://github.com/llvm/llvm-project/commit/134ffa8138c31444685013e10f592cd7c88d675b.diff

LOG: NFC: Fix -Wsign-compare warnings on 32-bit builds

Comparing 32-bit `ptrdiff_t` against 32-bit `unsigned` results in
`-Wsign-compare` warnings for both GCC and Clang.

The warning for the cases in question appear to identify an issue
where the `ptrdiff_t` value would be mutated via conversion to an
unsigned type.

The warning is resolved by using the usual arithmetic conversions to
safely preserve the value of the `unsigned` operand while trying to
convert to a signed type. Host platforms where `unsigned` has the same
width as `unsigned long long` will need to make a different change, but
using an explicit cast has disadvantages that can be avoided for now.

Reviewed By: dantrushin

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

Added: 


Modified: 
clang/lib/Serialization/ASTReaderStmt.cpp
llvm/lib/CodeGen/StackMaps.cpp

Removed: 




diff  --git a/clang/lib/Serialization/ASTReaderStmt.cpp 
b/clang/lib/Serialization/ASTReaderStmt.cpp
index c154c146727e..363527f884b3 100644
--- a/clang/lib/Serialization/ASTReaderStmt.cpp
+++ b/clang/lib/Serialization/ASTReaderStmt.cpp
@@ -2186,9 +2186,9 @@ void ASTStmtReader::VisitRecoveryExpr(RecoveryExpr *E) {
   unsigned NumArgs = Record.readInt();
   E->BeginLoc = readSourceLocation();
   E->EndLoc = readSourceLocation();
-  assert(
-  (NumArgs == std::distance(E->children().begin(), E->children().end())) &&
-  "Wrong NumArgs!");
+  assert((NumArgs + 0LL ==
+  std::distance(E->children().begin(), E->children().end())) &&
+ "Wrong NumArgs!");
   (void)NumArgs;
   for (Stmt * : E->children())
 Child = Record.readSubStmt();

diff  --git a/llvm/lib/CodeGen/StackMaps.cpp b/llvm/lib/CodeGen/StackMaps.cpp
index f7fb2e824bb9..ee1a4a47b4cc 100644
--- a/llvm/lib/CodeGen/StackMaps.cpp
+++ b/llvm/lib/CodeGen/StackMaps.cpp
@@ -401,7 +401,7 @@ void StackMaps::parseStatepointOpers(const MachineInstr ,
 SmallVector GCPtrIndices;
 unsigned GCPtrIdx = (unsigned)SO.getFirstGCPtrIdx();
 assert((int)GCPtrIdx != -1);
-assert(MOI - MI.operands_begin() == GCPtrIdx);
+assert(MOI - MI.operands_begin() == GCPtrIdx + 0LL);
 while (NumGCPointers--) {
   GCPtrIndices.push_back(GCPtrIdx);
   GCPtrIdx = StackMaps::getNextMetaArgIdx(, GCPtrIdx);



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


[PATCH] D89297: [clangd] Add a TestWorkspace utility

2020-10-20 Thread Nathan Ridge via Phabricator via cfe-commits
nridge updated this revision to Diff 299526.
nridge marked 8 inline comments as done.
nridge added a comment.
Herald added subscribers: llvm-commits, mgorny.
Herald added a project: LLVM.

Address review comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89297

Files:
  clang-tools-extra/clangd/unittests/BackgroundIndexTests.cpp
  clang-tools-extra/clangd/unittests/CMakeLists.txt
  clang-tools-extra/clangd/unittests/FileIndexTests.cpp
  clang-tools-extra/clangd/unittests/TestTU.cpp
  clang-tools-extra/clangd/unittests/TestTU.h
  clang-tools-extra/clangd/unittests/TestWorkspace.cpp
  clang-tools-extra/clangd/unittests/TestWorkspace.h
  llvm/utils/gn/secondary/clang-tools-extra/clangd/unittests/BUILD.gn

Index: llvm/utils/gn/secondary/clang-tools-extra/clangd/unittests/BUILD.gn
===
--- llvm/utils/gn/secondary/clang-tools-extra/clangd/unittests/BUILD.gn
+++ llvm/utils/gn/secondary/clang-tools-extra/clangd/unittests/BUILD.gn
@@ -96,6 +96,7 @@
 "TestFS.cpp",
 "TestIndex.cpp",
 "TestTU.cpp",
+"TestWorkspace.cpp",
 "TweakTesting.cpp",
 "TweakTests.cpp",
 "TypeHierarchyTests.cpp",
Index: clang-tools-extra/clangd/unittests/TestWorkspace.h
===
--- /dev/null
+++ clang-tools-extra/clangd/unittests/TestWorkspace.h
@@ -0,0 +1,63 @@
+//===--- TestWorkspace.h - Utility for writing multi-file tests --*- C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// TestWorkspace builds on TestTU to provide a way to write tests involving
+// several related files with inclusion relationships between them.
+//
+// The tests can exercise both index and AST based operations.
+//
+//===-===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_UNITTESTS_CLANGD_TESTWORKSPACE_H
+#define LLVM_CLANG_TOOLS_EXTRA_UNITTESTS_CLANGD_TESTWORKSPACE_H
+
+#include "TestFS.h"
+#include "TestTU.h"
+#include "index/FileIndex.h"
+#include "index/Index.h"
+#include "llvm/ADT/StringRef.h"
+#include 
+#include 
+
+namespace clang {
+namespace clangd {
+
+class TestWorkspace {
+private:
+  struct SourceFile {
+std::string Code;
+bool IsMainFile = false;
+  };
+
+public:
+  TestWorkspace() {}
+
+  // The difference between addSource() and addMainFile() is that only main
+  // files will be indexed.
+  void addSource(llvm::StringRef Filename, llvm::StringRef Code) {
+addInput(Filename.str(), {Code.str(), /*IsMainFile=*/false});
+  }
+  void addMainFile(llvm::StringRef Filename, llvm::StringRef Code) {
+addInput(Filename.str(), {Code.str(), /*IsMainFile=*/true});
+  }
+
+  std::unique_ptr index();
+
+  Optional openFile(llvm::StringRef Filename);
+
+private:
+  llvm::StringMap Inputs;
+  TestTU TU;
+
+  void addInput(llvm::StringRef Filename, const SourceFile );
+};
+
+} // namespace clangd
+} // namespace clang
+
+#endif // LLVM_CLANG_TOOLS_EXTRA_UNITTESTS_CLANGD_TESTWORKSPACE_H
Index: clang-tools-extra/clangd/unittests/TestWorkspace.cpp
===
--- /dev/null
+++ clang-tools-extra/clangd/unittests/TestWorkspace.cpp
@@ -0,0 +1,50 @@
+//===--- TestWorkspace.cpp - Utility for writing multi-file tests -*- C++-*===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "TestWorkspace.h"
+
+namespace clang {
+namespace clangd {
+
+std::unique_ptr TestWorkspace::index() {
+  auto Index = std::make_unique();
+  for (const auto  : Inputs) {
+if (!Input.second.IsMainFile) {
+  continue;
+}
+TU.Code = Input.second.Code;
+TU.Filename = Input.first().str();
+TU.preamble([&](ASTContext , std::shared_ptr PP,
+const CanonicalIncludes ) {
+  Index->updatePreamble(testPath(Input.first()), "null", Ctx, PP,
+CanonIncludes);
+});
+ParsedAST MainAST = TU.build();
+Index->updateMain(testPath(Input.first()), MainAST);
+  }
+  return Index;
+}
+
+Optional TestWorkspace::openFile(llvm::StringRef Filename) {
+  auto It = Inputs.find(Filename);
+  if (It == Inputs.end()) {
+ADD_FAILURE() << "Accessing non-existing file: " << Filename;
+return llvm::None;
+  }
+  TU.Code = It->second.Code;
+  TU.Filename = It->first().str();
+  return TU.build();
+}
+
+void TestWorkspace::addInput(llvm::StringRef Filename,
+ 

[clang] 15e772e - Don't instantiate lambda closure types in default member initializers

2020-10-20 Thread Richard Smith via cfe-commits

Author: Richard Smith
Date: 2020-10-20T17:37:07-07:00
New Revision: 15e772e8dc39f609115430f39078fbe58812fddb

URL: 
https://github.com/llvm/llvm-project/commit/15e772e8dc39f609115430f39078fbe58812fddb
DIFF: 
https://github.com/llvm/llvm-project/commit/15e772e8dc39f609115430f39078fbe58812fddb.diff

LOG: Don't instantiate lambda closure types in default member initializers
when instantiating the enclosing class.

We'll build new lambda closure types if and when we instantiate the
default member initializer, and instantiating the closure type by itself
can go wrong in cases where we fully-instantiate nested classes (in
explicit instantiations of the enclosing class and when the enclosing
class is a local class) -- we will instantiate the 'operator()' as a
regular function rather than as a lambda call operator, so it doesn't
get to use its captures, has the wrong 'this' type, etc.

Added: 


Modified: 
clang/lib/Sema/SemaTemplateInstantiate.cpp
clang/test/SemaTemplate/explicit-instantiation.cpp
clang/test/SemaTemplate/instantiate-local-class.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index 2e96eaa7df1a..a13118839036 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -2696,7 +2696,10 @@ Sema::InstantiateClass(SourceLocation 
PointOfInstantiation,
 
 // BlockDecls can appear in a default-member-initializer. They must be the
 // child of a BlockExpr, so we only know how to instantiate them from 
there.
-if (isa(Member))
+// Similarly, lambda closure types are recreated when instantiating the
+// corresponding LambdaExpr.
+if (isa(Member) ||
+(isa(Member) && 
cast(Member)->isLambda()))
   continue;
 
 if (Member->isInvalidDecl()) {

diff  --git a/clang/test/SemaTemplate/explicit-instantiation.cpp 
b/clang/test/SemaTemplate/explicit-instantiation.cpp
index d88c50bc29de..73f07ef41347 100644
--- a/clang/test/SemaTemplate/explicit-instantiation.cpp
+++ b/clang/test/SemaTemplate/explicit-instantiation.cpp
@@ -179,4 +179,10 @@ struct B : A<0> {
   virtual void foo() override; // expected-error{{declaration of 'foo' 
overrides a 'final' function}}
 };
 }
+
+template struct LambdaInDefaultMemberInitInExplicitInstantiation {
+  int a = [this] { return a; }();
+};
+template struct LambdaInDefaultMemberInitInExplicitInstantiation;
+LambdaInDefaultMemberInitInExplicitInstantiation x;
 #endif

diff  --git a/clang/test/SemaTemplate/instantiate-local-class.cpp 
b/clang/test/SemaTemplate/instantiate-local-class.cpp
index 15b455f62569..65caaa1a43e8 100644
--- a/clang/test/SemaTemplate/instantiate-local-class.cpp
+++ b/clang/test/SemaTemplate/instantiate-local-class.cpp
@@ -495,3 +495,12 @@ namespace PR45000 {
   void g() { f(); }
   // expected-note@-1 {{in instantiation of default function argument 
expression for 'f' required here}}
 }
+
+namespace LambdaInDefaultMemberInitializer {
+  template void f() {
+struct S {
+  void *p = [this] { return  }();
+};
+  }
+  template void f();
+}



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


[PATCH] D89520: Don't permit array bound constant folding in OpenCL.

2020-10-20 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG6781fee08505: Dont permit array bound constant folding 
in OpenCL. (authored by rsmith).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89520

Files:
  clang/lib/AST/Decl.cpp
  clang/lib/AST/ExprConstant.cpp
  clang/lib/Sema/SemaType.cpp
  clang/test/CodeGenOpenCL/amdgpu-nullptr.cl
  clang/test/SemaOpenCL/address-spaces.cl

Index: clang/test/SemaOpenCL/address-spaces.cl
===
--- clang/test/SemaOpenCL/address-spaces.cl
+++ clang/test/SemaOpenCL/address-spaces.cl
@@ -4,6 +4,13 @@
 
 __constant int ci = 1;
 
+// __constant ints are allowed in constant expressions.
+enum use_ci_in_enum { enumerator = ci };
+typedef int use_ci_in_array_bound[ci];
+
+// general constant folding of array bounds is not permitted
+typedef int folding_in_array_bounds[ + 3 - ]; // expected-error-re variable length arrays are not supported in OpenCL|array size is not a constant expression expected-note {{cannot refer to element 3}}
+
 __kernel void foo(__global int *gip) {
   __local int li;
   __local int lj = 2; // expected-error {{'__local' variable cannot have an initializer}}
Index: clang/test/CodeGenOpenCL/amdgpu-nullptr.cl
===
--- clang/test/CodeGenOpenCL/amdgpu-nullptr.cl
+++ clang/test/CodeGenOpenCL/amdgpu-nullptr.cl
@@ -104,7 +104,7 @@
 // NOOPT: @test_static_var_private.sp2 = internal addrspace(1) global i8 addrspace(5)* addrspacecast (i8* null to i8 addrspace(5)*), align 4
 // NOOPT: @test_static_var_private.sp3 = internal addrspace(1) global i8 addrspace(5)* addrspacecast (i8* null to i8 addrspace(5)*), align 4
 // NOOPT: @test_static_var_private.sp4 = internal addrspace(1) global i8 addrspace(5)* null, align 4
-// NOOPT: @test_static_var_private.sp5 = internal addrspace(1) global i8 addrspace(5)* null, align 4
+// NOOPT: @test_static_var_private.sp5 = internal addrspace(1) global i8 addrspace(5)* addrspacecast (i8* null to i8 addrspace(5)*), align 4
 // NOOPT: @test_static_var_private.SS1 = internal addrspace(1) global %struct.StructTy1 { i8 addrspace(5)* addrspacecast (i8* null to i8 addrspace(5)*), i8 addrspace(3)* addrspacecast (i8* null to i8 addrspace(3)*), i8 addrspace(4)* null, i8 addrspace(1)* null, i8* null }, align 8
 // NOOPT: @test_static_var_private.SS2 = internal addrspace(1) global %struct.StructTy2 zeroinitializer, align 8
 
@@ -123,7 +123,7 @@
 // NOOPT: @test_static_var_local.sp2 = internal addrspace(1) global i8 addrspace(3)* addrspacecast (i8* null to i8 addrspace(3)*), align 4
 // NOOPT: @test_static_var_local.sp3 = internal addrspace(1) global i8 addrspace(3)* addrspacecast (i8* null to i8 addrspace(3)*), align 4
 // NOOPT: @test_static_var_local.sp4 = internal addrspace(1) global i8 addrspace(3)* null, align 4
-// NOOPT: @test_static_var_local.sp5 = internal addrspace(1) global i8 addrspace(3)* null, align 4
+// NOOPT: @test_static_var_local.sp5 = internal addrspace(1) global i8 addrspace(3)* addrspacecast (i8* null to i8 addrspace(3)*), align 4
 // NOOPT: @test_static_var_local.SS1 = internal addrspace(1) global %struct.StructTy1 { i8 addrspace(5)* addrspacecast (i8* null to i8 addrspace(5)*), i8 addrspace(3)* addrspacecast (i8* null to i8 addrspace(3)*), i8 addrspace(4)* null, i8 addrspace(1)* null, i8* null }, align 8
 // NOOPT: @test_static_var_local.SS2 = internal addrspace(1) global %struct.StructTy2 zeroinitializer, align 8
 void test_static_var_local(void) {
@@ -142,7 +142,7 @@
 // NOOPT: store i8 addrspace(5)* addrspacecast (i8* null to i8 addrspace(5)*), i8 addrspace(5)* addrspace(5)* %sp1, align 4
 // NOOPT: store i8 addrspace(5)* addrspacecast (i8* null to i8 addrspace(5)*), i8 addrspace(5)* addrspace(5)* %sp2, align 4
 // NOOPT: store i8 addrspace(5)* null, i8 addrspace(5)* addrspace(5)* %sp3, align 4
-// NOOPT: store i8 addrspace(5)* null, i8 addrspace(5)* addrspace(5)* %sp4, align 4
+// NOOPT: store i8 addrspace(5)* addrspacecast (i8* null to i8 addrspace(5)*), i8 addrspace(5)* addrspace(5)* %sp4, align 4
 // NOOPT: %[[SS1:.*]] = bitcast %struct.StructTy1 addrspace(5)* %SS1 to i8 addrspace(5)*
 // NOOPT: call void @llvm.memcpy.p5i8.p4i8.i64(i8 addrspace(5)* align 8 %[[SS1]], i8 addrspace(4)* align 8 bitcast (%struct.StructTy1 addrspace(4)* @__const.test_func_scope_var_private.SS1 to i8 addrspace(4)*), i64 32, i1 false)
 // NOOPT: %[[SS2:.*]] = bitcast %struct.StructTy2 addrspace(5)* %SS2 to i8 addrspace(5)*
@@ -162,7 +162,7 @@
 // NOOPT: store i8 addrspace(3)* addrspacecast (i8* null to i8 addrspace(3)*), i8 addrspace(3)* addrspace(5)* %sp1, align 4
 // NOOPT: store i8 addrspace(3)* addrspacecast (i8* null to i8 addrspace(3)*), i8 addrspace(3)* addrspace(5)* %sp2, align 4
 // NOOPT: store i8 addrspace(3)* null, i8 

[clang] 6781fee - Don't permit array bound constant folding in OpenCL.

2020-10-20 Thread Richard Smith via cfe-commits

Author: Richard Smith
Date: 2020-10-20T16:52:28-07:00
New Revision: 6781fee085058913444e0c5937da9c0e7e928db5

URL: 
https://github.com/llvm/llvm-project/commit/6781fee085058913444e0c5937da9c0e7e928db5
DIFF: 
https://github.com/llvm/llvm-project/commit/6781fee085058913444e0c5937da9c0e7e928db5.diff

LOG: Don't permit array bound constant folding in OpenCL.

Permitting non-standards-driven "do the best you can" constant-folding
of array bounds is permitted solely as a GNU compatibility feature. We
should not be doing it in any language mode that is attempting to be
conforming.

>From https://reviews.llvm.org/D20090 it appears the intent here was to
permit `__constant int` globals to be used in array bounds, but the
change in that patch only added half of the functionality necessary to
support that in the constant evaluator. This patch adds the other half
of the functionality and turns off constant folding for array bounds in
OpenCL.

I couldn't find any spec justification for accepting the kinds of cases
that D20090 accepts, so a reference to where in the OpenCL specification
this is permitted would be useful.

Note that this change also affects the code generation in one test:
because after 'const int n = 0' we now treat 'n' as a constant
expression with value 0, it's now a null pointer, so '(local int *)n'
forms a null pointer rather than a zero pointer.

Reviewed By: Anastasia

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

Added: 


Modified: 
clang/lib/AST/Decl.cpp
clang/lib/AST/ExprConstant.cpp
clang/lib/Sema/SemaType.cpp
clang/test/CodeGenOpenCL/amdgpu-nullptr.cl
clang/test/SemaOpenCL/address-spaces.cl

Removed: 




diff  --git a/clang/lib/AST/Decl.cpp b/clang/lib/AST/Decl.cpp
index b3a67715d604..80bc22b61b70 100644
--- a/clang/lib/AST/Decl.cpp
+++ b/clang/lib/AST/Decl.cpp
@@ -2280,7 +2280,9 @@ void VarDecl::setInit(Expr *I) {
 bool VarDecl::mightBeUsableInConstantExpressions(const ASTContext ) const {
   const LangOptions  = C.getLangOpts();
 
-  if (!Lang.CPlusPlus)
+  // OpenCL permits const integral variables to be used in constant
+  // expressions, like in C++98.
+  if (!Lang.CPlusPlus && !Lang.OpenCL)
 return false;
 
   // Function parameters are never usable in constant expressions.
@@ -2299,7 +2301,7 @@ bool VarDecl::mightBeUsableInConstantExpressions(const 
ASTContext ) const {
   // Only const objects can be used in constant expressions in C++. C++98 does
   // not require the variable to be non-volatile, but we consider this to be a
   // defect.
-  if (!getType().isConstQualified() || getType().isVolatileQualified())
+  if (!getType().isConstant(C) || getType().isVolatileQualified())
 return false;
 
   // In C++, const, non-volatile variables of integral or enumeration types
@@ -2325,14 +2327,14 @@ bool VarDecl::isUsableInConstantExpressions(const 
ASTContext ) const {
   if (!DefVD->mightBeUsableInConstantExpressions(Context))
 return false;
   //   ... and its initializer is a constant initializer.
-  if (!DefVD->hasConstantInitialization())
+  if (Context.getLangOpts().CPlusPlus && !DefVD->hasConstantInitialization())
 return false;
   // C++98 [expr.const]p1:
   //   An integral constant-expression can involve only [...] const variables
   //   or static data members of integral or enumeration types initialized with
   //   [integer] constant expressions (dcl.init)
-  if (Context.getLangOpts().CPlusPlus && !Context.getLangOpts().CPlusPlus11 &&
-  !DefVD->hasICEInitializer(Context))
+  if ((Context.getLangOpts().CPlusPlus || Context.getLangOpts().OpenCL) &&
+  !Context.getLangOpts().CPlusPlus11 && !DefVD->hasICEInitializer(Context))
 return false;
   return true;
 }

diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index f4664bb62414..b2ddca7f7ce0 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -3284,10 +3284,10 @@ static bool evaluateVarDeclInit(EvalInfo , const 
Expr *E,
   // FIXME: We don't diagnose cases that aren't potentially usable in constant
   // expressions here; doing so would regress diagnostics for things like
   // reading from a volatile constexpr variable.
-  if ((!VD->hasConstantInitialization() &&
+  if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
-  (Info.getLangOpts().CPlusPlus && !Info.getLangOpts().CPlusPlus11 &&
-   !VD->hasICEInitializer(Info.Ctx))) {
+  ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
+   !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
 NoteLValueLocation(Info, Base);
   }
@@ -3997,10 +3997,7 @@ static CompleteObject findCompleteObject(EvalInfo , 
const Expr *E,
   return CompleteObject();
 }
 
-// In 

[PATCH] D89520: Don't permit array bound constant folding in OpenCL.

2020-10-20 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith updated this revision to Diff 299515.
rsmith added a comment.

Rebase.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89520

Files:
  clang/lib/AST/Decl.cpp
  clang/lib/AST/ExprConstant.cpp
  clang/lib/Sema/SemaType.cpp
  clang/test/CodeGenOpenCL/amdgpu-nullptr.cl
  clang/test/SemaOpenCL/address-spaces.cl

Index: clang/test/SemaOpenCL/address-spaces.cl
===
--- clang/test/SemaOpenCL/address-spaces.cl
+++ clang/test/SemaOpenCL/address-spaces.cl
@@ -4,6 +4,13 @@
 
 __constant int ci = 1;
 
+// __constant ints are allowed in constant expressions.
+enum use_ci_in_enum { enumerator = ci };
+typedef int use_ci_in_array_bound[ci];
+
+// general constant folding of array bounds is not permitted
+typedef int folding_in_array_bounds[ + 3 - ]; // expected-error-re variable length arrays are not supported in OpenCL|array size is not a constant expression expected-note {{cannot refer to element 3}}
+
 __kernel void foo(__global int *gip) {
   __local int li;
   __local int lj = 2; // expected-error {{'__local' variable cannot have an initializer}}
Index: clang/test/CodeGenOpenCL/amdgpu-nullptr.cl
===
--- clang/test/CodeGenOpenCL/amdgpu-nullptr.cl
+++ clang/test/CodeGenOpenCL/amdgpu-nullptr.cl
@@ -104,7 +104,7 @@
 // NOOPT: @test_static_var_private.sp2 = internal addrspace(1) global i8 addrspace(5)* addrspacecast (i8* null to i8 addrspace(5)*), align 4
 // NOOPT: @test_static_var_private.sp3 = internal addrspace(1) global i8 addrspace(5)* addrspacecast (i8* null to i8 addrspace(5)*), align 4
 // NOOPT: @test_static_var_private.sp4 = internal addrspace(1) global i8 addrspace(5)* null, align 4
-// NOOPT: @test_static_var_private.sp5 = internal addrspace(1) global i8 addrspace(5)* null, align 4
+// NOOPT: @test_static_var_private.sp5 = internal addrspace(1) global i8 addrspace(5)* addrspacecast (i8* null to i8 addrspace(5)*), align 4
 // NOOPT: @test_static_var_private.SS1 = internal addrspace(1) global %struct.StructTy1 { i8 addrspace(5)* addrspacecast (i8* null to i8 addrspace(5)*), i8 addrspace(3)* addrspacecast (i8* null to i8 addrspace(3)*), i8 addrspace(4)* null, i8 addrspace(1)* null, i8* null }, align 8
 // NOOPT: @test_static_var_private.SS2 = internal addrspace(1) global %struct.StructTy2 zeroinitializer, align 8
 
@@ -123,7 +123,7 @@
 // NOOPT: @test_static_var_local.sp2 = internal addrspace(1) global i8 addrspace(3)* addrspacecast (i8* null to i8 addrspace(3)*), align 4
 // NOOPT: @test_static_var_local.sp3 = internal addrspace(1) global i8 addrspace(3)* addrspacecast (i8* null to i8 addrspace(3)*), align 4
 // NOOPT: @test_static_var_local.sp4 = internal addrspace(1) global i8 addrspace(3)* null, align 4
-// NOOPT: @test_static_var_local.sp5 = internal addrspace(1) global i8 addrspace(3)* null, align 4
+// NOOPT: @test_static_var_local.sp5 = internal addrspace(1) global i8 addrspace(3)* addrspacecast (i8* null to i8 addrspace(3)*), align 4
 // NOOPT: @test_static_var_local.SS1 = internal addrspace(1) global %struct.StructTy1 { i8 addrspace(5)* addrspacecast (i8* null to i8 addrspace(5)*), i8 addrspace(3)* addrspacecast (i8* null to i8 addrspace(3)*), i8 addrspace(4)* null, i8 addrspace(1)* null, i8* null }, align 8
 // NOOPT: @test_static_var_local.SS2 = internal addrspace(1) global %struct.StructTy2 zeroinitializer, align 8
 void test_static_var_local(void) {
@@ -142,7 +142,7 @@
 // NOOPT: store i8 addrspace(5)* addrspacecast (i8* null to i8 addrspace(5)*), i8 addrspace(5)* addrspace(5)* %sp1, align 4
 // NOOPT: store i8 addrspace(5)* addrspacecast (i8* null to i8 addrspace(5)*), i8 addrspace(5)* addrspace(5)* %sp2, align 4
 // NOOPT: store i8 addrspace(5)* null, i8 addrspace(5)* addrspace(5)* %sp3, align 4
-// NOOPT: store i8 addrspace(5)* null, i8 addrspace(5)* addrspace(5)* %sp4, align 4
+// NOOPT: store i8 addrspace(5)* addrspacecast (i8* null to i8 addrspace(5)*), i8 addrspace(5)* addrspace(5)* %sp4, align 4
 // NOOPT: %[[SS1:.*]] = bitcast %struct.StructTy1 addrspace(5)* %SS1 to i8 addrspace(5)*
 // NOOPT: call void @llvm.memcpy.p5i8.p4i8.i64(i8 addrspace(5)* align 8 %[[SS1]], i8 addrspace(4)* align 8 bitcast (%struct.StructTy1 addrspace(4)* @__const.test_func_scope_var_private.SS1 to i8 addrspace(4)*), i64 32, i1 false)
 // NOOPT: %[[SS2:.*]] = bitcast %struct.StructTy2 addrspace(5)* %SS2 to i8 addrspace(5)*
@@ -162,7 +162,7 @@
 // NOOPT: store i8 addrspace(3)* addrspacecast (i8* null to i8 addrspace(3)*), i8 addrspace(3)* addrspace(5)* %sp1, align 4
 // NOOPT: store i8 addrspace(3)* addrspacecast (i8* null to i8 addrspace(3)*), i8 addrspace(3)* addrspace(5)* %sp2, align 4
 // NOOPT: store i8 addrspace(3)* null, i8 addrspace(3)* addrspace(5)* %sp3, align 4
-// NOOPT: store i8 addrspace(3)* null, i8 addrspace(3)* addrspace(5)* %sp4, align 4
+// NOOPT: store i8 addrspace(3)* 

[PATCH] D89500: Fix the error message with -fbasic-block-sections=list=

2020-10-20 Thread Sriraman Tallam via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGf88785460ecf: Improve file doesnt exist error with 
-fbasic-block-sections= (authored by tmsriram).
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89500

Files:
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/CodeGen/basic-block-sections.c
  clang/test/Driver/fbasic-block-sections.c


Index: clang/test/Driver/fbasic-block-sections.c
===
--- clang/test/Driver/fbasic-block-sections.c
+++ clang/test/Driver/fbasic-block-sections.c
@@ -4,9 +4,14 @@
 // RUN: %clang -### -target x86_64 -fbasic-block-sections=labels %s -S 2>&1 | 
FileCheck -check-prefix=CHECK-OPT-LABELS %s
 // RUN: not %clang -c -target arm-unknown-linux -fbasic-block-sections=all %s 
-S 2>&1 | FileCheck -check-prefix=CHECK-TRIPLE %s
 // RUN: not %clang -c -target x86_64-apple-darwin10 -fbasic-block-sections=all 
%s -S 2>&1 | FileCheck -check-prefix=CHECK-TRIPLE %s
+// RUN: %clang -### -target x86_64 -fbasic-block-sections=alll %s -S 2>&1 | 
FileCheck -check-prefix=CHECK-INVALID-VALUE %s
+// RUN: %clang -### -target x86_64 -fbasic-block-sections=list %s -S 2>&1 | 
FileCheck -check-prefix=CHECK-INVALID-VALUE %s
+// RUN: %clang -### -target x86_64 -fbasic-block-sections=list= %s -S 2>&1 | 
FileCheck -check-prefix=CHECK-OPT-NULL-LIST %s
 //
 // CHECK-OPT-NONE:   "-fbasic-block-sections=none"
 // CHECK-OPT-ALL:"-fbasic-block-sections=all"
 // CHECK-OPT-LIST:   "-fbasic-block-sections={{[^ ]*}}fbasic-block-sections.c"
 // CHECK-OPT-LABELS: "-fbasic-block-sections=labels"
 // CHECK-TRIPLE: error: unsupported option '-fbasic-block-sections=all' 
for target
+// CHECK-INVALID-VALUE: error: invalid value {{[^ ]*}} in 
'-fbasic-block-sections={{.*}}'
+// CHECK-OPT-NULL-LIST: "-fbasic-block-sections=list="
Index: clang/test/CodeGen/basic-block-sections.c
===
--- clang/test/CodeGen/basic-block-sections.c
+++ clang/test/CodeGen/basic-block-sections.c
@@ -6,6 +6,7 @@
 // RUN: %clang_cc1 -triple x86_64 -S -fbasic-block-sections=all -o - < %s | 
FileCheck %s --check-prefix=BB_WORLD --check-prefix=BB_ALL
 // RUN: %clang_cc1 -triple x86_64 -S 
-fbasic-block-sections=list=%S/Inputs/basic-block-sections.funcnames -o - < %s 
| FileCheck %s --check-prefix=BB_WORLD --check-prefix=BB_LIST
 // RUN: %clang_cc1 -triple x86_64 -S -fbasic-block-sections=all 
-funique-basic-block-section-names -o - < %s | FileCheck %s 
--check-prefix=UNIQUE
+// RUN: not %clang_cc1 -fbasic-block-sections=list= -emit-obj %s 2>&1 | 
FileCheck %s --check-prefix=ERROR
 
 int world(int a) {
   if (a > 10)
@@ -38,3 +39,4 @@
 //
 // UNIQUE: .section .text.world.world.1,
 // UNIQUE: .section .text.another.another.1,
+// ERROR: error:  unable to load basic block sections function list: 'No such 
file or directory'
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -4924,7 +4924,7 @@
 if (Triple.isX86() && Triple.isOSBinFormatELF()) {
   StringRef Val = A->getValue();
   if (Val != "all" && Val != "labels" && Val != "none" &&
-  !(Val.startswith("list=") && llvm::sys::fs::exists(Val.substr(5
+  !Val.startswith("list="))
 D.Diag(diag::err_drv_invalid_value)
 << A->getAsString(Args) << A->getValue();
   else


Index: clang/test/Driver/fbasic-block-sections.c
===
--- clang/test/Driver/fbasic-block-sections.c
+++ clang/test/Driver/fbasic-block-sections.c
@@ -4,9 +4,14 @@
 // RUN: %clang -### -target x86_64 -fbasic-block-sections=labels %s -S 2>&1 | FileCheck -check-prefix=CHECK-OPT-LABELS %s
 // RUN: not %clang -c -target arm-unknown-linux -fbasic-block-sections=all %s -S 2>&1 | FileCheck -check-prefix=CHECK-TRIPLE %s
 // RUN: not %clang -c -target x86_64-apple-darwin10 -fbasic-block-sections=all %s -S 2>&1 | FileCheck -check-prefix=CHECK-TRIPLE %s
+// RUN: %clang -### -target x86_64 -fbasic-block-sections=alll %s -S 2>&1 | FileCheck -check-prefix=CHECK-INVALID-VALUE %s
+// RUN: %clang -### -target x86_64 -fbasic-block-sections=list %s -S 2>&1 | FileCheck -check-prefix=CHECK-INVALID-VALUE %s
+// RUN: %clang -### -target x86_64 -fbasic-block-sections=list= %s -S 2>&1 | FileCheck -check-prefix=CHECK-OPT-NULL-LIST %s
 //
 // CHECK-OPT-NONE:   "-fbasic-block-sections=none"
 // CHECK-OPT-ALL:"-fbasic-block-sections=all"
 // CHECK-OPT-LIST:   "-fbasic-block-sections={{[^ ]*}}fbasic-block-sections.c"
 // CHECK-OPT-LABELS: "-fbasic-block-sections=labels"
 // CHECK-TRIPLE: error: unsupported option '-fbasic-block-sections=all' for target
+// CHECK-INVALID-VALUE: error: invalid value {{[^ ]*}} 

[clang] f887854 - Improve file doesnt exist error with -fbasic-block-sections=

2020-10-20 Thread Sriraman Tallam via cfe-commits

Author: Sriraman Tallam
Date: 2020-10-20T16:41:56-07:00
New Revision: f88785460ecf40a9176f58637d38fb785eb91ac4

URL: 
https://github.com/llvm/llvm-project/commit/f88785460ecf40a9176f58637d38fb785eb91ac4
DIFF: 
https://github.com/llvm/llvm-project/commit/f88785460ecf40a9176f58637d38fb785eb91ac4.diff

LOG: Improve file doesnt exist error with -fbasic-block-sections=

With -fbasicblock-sections=, let the front-end handle the case where the file
doesnt exist. The driver only checks if the option syntax is right.

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

Added: 


Modified: 
clang/lib/Driver/ToolChains/Clang.cpp
clang/test/CodeGen/basic-block-sections.c
clang/test/Driver/fbasic-block-sections.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 9cdee130af431..34ccc8cffb799 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -4924,7 +4924,7 @@ void Clang::ConstructJob(Compilation , const JobAction 
,
 if (Triple.isX86() && Triple.isOSBinFormatELF()) {
   StringRef Val = A->getValue();
   if (Val != "all" && Val != "labels" && Val != "none" &&
-  !(Val.startswith("list=") && llvm::sys::fs::exists(Val.substr(5
+  !Val.startswith("list="))
 D.Diag(diag::err_drv_invalid_value)
 << A->getAsString(Args) << A->getValue();
   else

diff  --git a/clang/test/CodeGen/basic-block-sections.c 
b/clang/test/CodeGen/basic-block-sections.c
index dc414d70ba5f9..f07a387685c86 100644
--- a/clang/test/CodeGen/basic-block-sections.c
+++ b/clang/test/CodeGen/basic-block-sections.c
@@ -6,6 +6,7 @@
 // RUN: %clang_cc1 -triple x86_64 -S -fbasic-block-sections=all -o - < %s | 
FileCheck %s --check-prefix=BB_WORLD --check-prefix=BB_ALL
 // RUN: %clang_cc1 -triple x86_64 -S 
-fbasic-block-sections=list=%S/Inputs/basic-block-sections.funcnames -o - < %s 
| FileCheck %s --check-prefix=BB_WORLD --check-prefix=BB_LIST
 // RUN: %clang_cc1 -triple x86_64 -S -fbasic-block-sections=all 
-funique-basic-block-section-names -o - < %s | FileCheck %s 
--check-prefix=UNIQUE
+// RUN: not %clang_cc1 -fbasic-block-sections=list= -emit-obj %s 2>&1 | 
FileCheck %s --check-prefix=ERROR
 
 int world(int a) {
   if (a > 10)
@@ -38,3 +39,4 @@ int another(int a) {
 //
 // UNIQUE: .section .text.world.world.1,
 // UNIQUE: .section .text.another.another.1,
+// ERROR: error:  unable to load basic block sections function list: 'No such 
file or directory'

diff  --git a/clang/test/Driver/fbasic-block-sections.c 
b/clang/test/Driver/fbasic-block-sections.c
index 93c7fe9fc0699..6aa030bf27ca5 100644
--- a/clang/test/Driver/fbasic-block-sections.c
+++ b/clang/test/Driver/fbasic-block-sections.c
@@ -4,9 +4,14 @@
 // RUN: %clang -### -target x86_64 -fbasic-block-sections=labels %s -S 2>&1 | 
FileCheck -check-prefix=CHECK-OPT-LABELS %s
 // RUN: not %clang -c -target arm-unknown-linux -fbasic-block-sections=all %s 
-S 2>&1 | FileCheck -check-prefix=CHECK-TRIPLE %s
 // RUN: not %clang -c -target x86_64-apple-darwin10 -fbasic-block-sections=all 
%s -S 2>&1 | FileCheck -check-prefix=CHECK-TRIPLE %s
+// RUN: %clang -### -target x86_64 -fbasic-block-sections=alll %s -S 2>&1 | 
FileCheck -check-prefix=CHECK-INVALID-VALUE %s
+// RUN: %clang -### -target x86_64 -fbasic-block-sections=list %s -S 2>&1 | 
FileCheck -check-prefix=CHECK-INVALID-VALUE %s
+// RUN: %clang -### -target x86_64 -fbasic-block-sections=list= %s -S 2>&1 | 
FileCheck -check-prefix=CHECK-OPT-NULL-LIST %s
 //
 // CHECK-OPT-NONE:   "-fbasic-block-sections=none"
 // CHECK-OPT-ALL:"-fbasic-block-sections=all"
 // CHECK-OPT-LIST:   "-fbasic-block-sections={{[^ ]*}}fbasic-block-sections.c"
 // CHECK-OPT-LABELS: "-fbasic-block-sections=labels"
 // CHECK-TRIPLE: error: unsupported option '-fbasic-block-sections=all' 
for target
+// CHECK-INVALID-VALUE: error: invalid value {{[^ ]*}} in 
'-fbasic-block-sections={{.*}}'
+// CHECK-OPT-NULL-LIST: "-fbasic-block-sections=list="



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


[PATCH] D86671: [clang-tidy] Add new case type to check variables with Hungarian notation

2020-10-20 Thread Douglas Chen via Phabricator via cfe-commits
dougpuob added a comment.

In D86671#2342016 , @njames93 wrote:

> In D86671#2341838 , @dougpuob wrote:
>
>> Hi @njames93,
>>
>> It's a smart idea, the rework for it is worth. There is a special case if 
>> lowercase name with Hungarian prefix, it possibly makes variable ambiguous, 
>> like the `Case1`. How about separating them and `aNy_CasE` with an 
>> underscore, like `Case2` ?
>>
>>   // Case1
>>   bool bRIGHT_LEVEL; // UPPER_CASE
>>   bool bRightLevel;  // CamelCase
>>   bool bRight_Level; // Camel_Snake_Case
>>   bool baNy_CasE;// aNy_CasE
>>   bool bright_level; // lower_case
>>   bool brightLevel;  // camelBack
>>   bool bright_Level; // camel_Snake_Back
>>   .^^ <-- right? bright?
>>   
>>   // Case2
>>   bool bRIGHT_LEVEL; // UPPER_CASE
>>   bool bRightLevel;  // CamelCase
>>   bool bRight_Level; // Camel_Snake_Case
>>   bool b_aNy_CasE;   // aNy_CasE
>>   bool b_right_level;// lower_case
>>   bool b_rightLevel; // camelBack
>>   bool b_right_Level;// camel_Snake_Back
>>   .^^^ <-- add an underscore
>
> That still has hidden surprises. Maybe instead of a bool, an enum is used for 
> controlling hungarian prefix (Off|On|...).
> Can't think of a good name for the third option but it would do the inserting 
> of '_' (bright_level ->b_right_level) or capitalising the first word of the 
> identifier (brightLevel -> bRightLevel).

Maybe it doesn't need a new name, how about (`Off|On|lower_case|camelBack`) or 
(`Off|On|sz_lower_case|szCamelBack`)?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D86671

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


[PATCH] D89696: [OpenMP] Fixing OpenMP/driver.c failing on 32-bit hosts

2020-10-20 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added inline comments.



Comment at: clang/test/OpenMP/driver-openmp-target.c:2
+// REQUIRES: x86-registered-target
+// REQUIRES: clang-64-bits
+// RUN: %clang %s -c -E -dM -fopenmp=libomp -fopenmp-version=45 
-fopenmp-targets=x86_64-unknown-unknown -o - | FileCheck 
--check-prefix=CHECK-45-VERSION --check-prefix=CHECK-45-VERSION2 %s

daltenty wrote:
> This tests still fails on AIX, presumably because we have a 64-bit host but 
> the compiler is targeting 32-bit by default:
> 
> ```
> error: OpenMP target architecture 'x86_64-unknown-unknown' pointer size is 
> incompatible with host 'powerpc-ibm-aix7.2.0.0'
> ```
> 
> Maybe adjust the test to check the default target instead of just the host?
I'm not aware of any easy methods to do that, though one might exist. Easiest 
solution is just add a check that doesn't run this test on AIX, more complex 
would probably require taking the default target from the clang executable and 
parsing it using the same methods that Triple.cpp uses to get the architecture 
size. I'm not familiar with anything about AIX, any suggestions?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89696

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


[clang] 1d78e21 - clang/Basic: ContentCache::InvalidFlag => ContentCache::IsBufferInvalid, NFC

2020-10-20 Thread Duncan P . N . Exon Smith via cfe-commits

Author: Duncan P. N. Exon Smith
Date: 2020-10-20T19:28:17-04:00
New Revision: 1d78e2101ab75f01615a45467c44da7181cccedb

URL: 
https://github.com/llvm/llvm-project/commit/1d78e2101ab75f01615a45467c44da7181cccedb
DIFF: 
https://github.com/llvm/llvm-project/commit/1d78e2101ab75f01615a45467c44da7181cccedb.diff

LOG: clang/Basic: ContentCache::InvalidFlag => ContentCache::IsBufferInvalid, 
NFC

Move a flag out of the `MemoryBuffer*` to unblock changing it to a
`unique_ptr`. There are plenty of bits available in the bitfield below.

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

Added: 


Modified: 
clang/include/clang/Basic/SourceManager.h
clang/lib/Basic/SourceManager.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/SourceManager.h 
b/clang/include/clang/Basic/SourceManager.h
index 480fa51d6889..569ef002d387 100644
--- a/clang/include/clang/Basic/SourceManager.h
+++ b/clang/include/clang/Basic/SourceManager.h
@@ -95,9 +95,6 @@ namespace SrcMgr {
   /// This object owns the MemoryBuffer object.
   class alignas(8) ContentCache {
 enum CCFlags {
-  /// Whether the buffer is invalid.
-  InvalidFlag = 0x01,
-
   /// Whether the buffer should not be freed on destruction.
   DoNotFreeFlag = 0x02
 };
@@ -151,18 +148,21 @@ namespace SrcMgr {
 /// after serialization and deserialization.
 unsigned IsTransient : 1;
 
+mutable unsigned IsBufferInvalid : 1;
+
 ContentCache(const FileEntry *Ent = nullptr) : ContentCache(Ent, Ent) {}
 
 ContentCache(const FileEntry *Ent, const FileEntry *contentEnt)
 : Buffer(nullptr, false), OrigEntry(Ent), ContentsEntry(contentEnt),
-  BufferOverridden(false), IsFileVolatile(false), IsTransient(false) {}
+  BufferOverridden(false), IsFileVolatile(false), IsTransient(false),
+  IsBufferInvalid(false) {}
 
 /// The copy ctor does not allow copies where source object has either
 /// a non-NULL Buffer or SourceLineCache.  Ownership of allocated memory
 /// is not transferred, so this is a logical error.
 ContentCache(const ContentCache )
 : Buffer(nullptr, false), BufferOverridden(false),
-  IsFileVolatile(false), IsTransient(false) {
+  IsFileVolatile(false), IsTransient(false), IsBufferInvalid(false) {
   OrigEntry = RHS.OrigEntry;
   ContentsEntry = RHS.ContentsEntry;
 
@@ -216,11 +216,6 @@ namespace SrcMgr {
 /// with the given buffer.
 void replaceBuffer(const llvm::MemoryBuffer *B, bool DoNotFree = false);
 
-/// Determine whether the buffer itself is invalid.
-bool isBufferInvalid() const {
-  return Buffer.getInt() & InvalidFlag;
-}
-
 /// Determine whether the buffer should be freed.
 bool shouldFreeBuffer() const {
   return (Buffer.getInt() & DoNotFreeFlag) == 0;

diff  --git a/clang/lib/Basic/SourceManager.cpp 
b/clang/lib/Basic/SourceManager.cpp
index 27d2f398f3c6..c831d26c380c 100644
--- a/clang/lib/Basic/SourceManager.cpp
+++ b/clang/lib/Basic/SourceManager.cpp
@@ -123,7 +123,7 @@ ContentCache::getBufferOrNone(DiagnosticsEngine , 
FileManager ,
   SourceLocation Loc) const {
   // Lazily create the Buffer for ContentCaches that wrap files.  If we already
   // computed it, just return what we have.
-  if (isBufferInvalid())
+  if (IsBufferInvalid)
 return None;
   if (auto *B = Buffer.getPointer())
 return B->getMemBufferRef();
@@ -144,7 +144,7 @@ ContentCache::getBufferOrNone(DiagnosticsEngine , 
FileManager ,
   Diag.Report(Loc, diag::err_file_too_large)
 << ContentsEntry->getName();
 
-Buffer.setInt(Buffer.getInt() | InvalidFlag);
+IsBufferInvalid = true;
 return None;
   }
 
@@ -164,7 +164,7 @@ ContentCache::getBufferOrNone(DiagnosticsEngine , 
FileManager ,
   Diag.Report(Loc, diag::err_cannot_open_file)
   << ContentsEntry->getName() << BufferOrError.getError().message();
 
-Buffer.setInt(Buffer.getInt() | InvalidFlag);
+IsBufferInvalid = true;
 return None;
   }
 
@@ -180,7 +180,7 @@ ContentCache::getBufferOrNone(DiagnosticsEngine , 
FileManager ,
   Diag.Report(Loc, diag::err_file_modified)
 << ContentsEntry->getName();
 
-Buffer.setInt(Buffer.getInt() | InvalidFlag);
+IsBufferInvalid = true;
 return None;
   }
 
@@ -193,7 +193,7 @@ ContentCache::getBufferOrNone(DiagnosticsEngine , 
FileManager ,
   if (InvalidBOM) {
 Diag.Report(Loc, diag::err_unsupported_bom)
   << InvalidBOM << ContentsEntry->getName();
-Buffer.setInt(Buffer.getInt() | InvalidFlag);
+IsBufferInvalid = true;
 return None;
   }
 



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


[PATCH] D89431: clang/Basic: ContentCache::InvalidFlag => ContentCache::IsBufferInvalid, NFC

2020-10-20 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG1d78e2101ab7: clang/Basic: ContentCache::InvalidFlag = 
ContentCache::IsBufferInvalid, NFC (authored by dexonsmith).
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89431

Files:
  clang/include/clang/Basic/SourceManager.h
  clang/lib/Basic/SourceManager.cpp


Index: clang/lib/Basic/SourceManager.cpp
===
--- clang/lib/Basic/SourceManager.cpp
+++ clang/lib/Basic/SourceManager.cpp
@@ -123,7 +123,7 @@
   SourceLocation Loc) const {
   // Lazily create the Buffer for ContentCaches that wrap files.  If we already
   // computed it, just return what we have.
-  if (isBufferInvalid())
+  if (IsBufferInvalid)
 return None;
   if (auto *B = Buffer.getPointer())
 return B->getMemBufferRef();
@@ -144,7 +144,7 @@
   Diag.Report(Loc, diag::err_file_too_large)
 << ContentsEntry->getName();
 
-Buffer.setInt(Buffer.getInt() | InvalidFlag);
+IsBufferInvalid = true;
 return None;
   }
 
@@ -164,7 +164,7 @@
   Diag.Report(Loc, diag::err_cannot_open_file)
   << ContentsEntry->getName() << BufferOrError.getError().message();
 
-Buffer.setInt(Buffer.getInt() | InvalidFlag);
+IsBufferInvalid = true;
 return None;
   }
 
@@ -180,7 +180,7 @@
   Diag.Report(Loc, diag::err_file_modified)
 << ContentsEntry->getName();
 
-Buffer.setInt(Buffer.getInt() | InvalidFlag);
+IsBufferInvalid = true;
 return None;
   }
 
@@ -193,7 +193,7 @@
   if (InvalidBOM) {
 Diag.Report(Loc, diag::err_unsupported_bom)
   << InvalidBOM << ContentsEntry->getName();
-Buffer.setInt(Buffer.getInt() | InvalidFlag);
+IsBufferInvalid = true;
 return None;
   }
 
Index: clang/include/clang/Basic/SourceManager.h
===
--- clang/include/clang/Basic/SourceManager.h
+++ clang/include/clang/Basic/SourceManager.h
@@ -95,9 +95,6 @@
   /// This object owns the MemoryBuffer object.
   class alignas(8) ContentCache {
 enum CCFlags {
-  /// Whether the buffer is invalid.
-  InvalidFlag = 0x01,
-
   /// Whether the buffer should not be freed on destruction.
   DoNotFreeFlag = 0x02
 };
@@ -151,18 +148,21 @@
 /// after serialization and deserialization.
 unsigned IsTransient : 1;
 
+mutable unsigned IsBufferInvalid : 1;
+
 ContentCache(const FileEntry *Ent = nullptr) : ContentCache(Ent, Ent) {}
 
 ContentCache(const FileEntry *Ent, const FileEntry *contentEnt)
 : Buffer(nullptr, false), OrigEntry(Ent), ContentsEntry(contentEnt),
-  BufferOverridden(false), IsFileVolatile(false), IsTransient(false) {}
+  BufferOverridden(false), IsFileVolatile(false), IsTransient(false),
+  IsBufferInvalid(false) {}
 
 /// The copy ctor does not allow copies where source object has either
 /// a non-NULL Buffer or SourceLineCache.  Ownership of allocated memory
 /// is not transferred, so this is a logical error.
 ContentCache(const ContentCache )
 : Buffer(nullptr, false), BufferOverridden(false),
-  IsFileVolatile(false), IsTransient(false) {
+  IsFileVolatile(false), IsTransient(false), IsBufferInvalid(false) {
   OrigEntry = RHS.OrigEntry;
   ContentsEntry = RHS.ContentsEntry;
 
@@ -216,11 +216,6 @@
 /// with the given buffer.
 void replaceBuffer(const llvm::MemoryBuffer *B, bool DoNotFree = false);
 
-/// Determine whether the buffer itself is invalid.
-bool isBufferInvalid() const {
-  return Buffer.getInt() & InvalidFlag;
-}
-
 /// Determine whether the buffer should be freed.
 bool shouldFreeBuffer() const {
   return (Buffer.getInt() & DoNotFreeFlag) == 0;


Index: clang/lib/Basic/SourceManager.cpp
===
--- clang/lib/Basic/SourceManager.cpp
+++ clang/lib/Basic/SourceManager.cpp
@@ -123,7 +123,7 @@
   SourceLocation Loc) const {
   // Lazily create the Buffer for ContentCaches that wrap files.  If we already
   // computed it, just return what we have.
-  if (isBufferInvalid())
+  if (IsBufferInvalid)
 return None;
   if (auto *B = Buffer.getPointer())
 return B->getMemBufferRef();
@@ -144,7 +144,7 @@
   Diag.Report(Loc, diag::err_file_too_large)
 << ContentsEntry->getName();
 
-Buffer.setInt(Buffer.getInt() | InvalidFlag);
+IsBufferInvalid = true;
 return None;
   }
 
@@ -164,7 +164,7 @@
   Diag.Report(Loc, diag::err_cannot_open_file)
   << ContentsEntry->getName() << BufferOrError.getError().message();
 
-Buffer.setInt(Buffer.getInt() | InvalidFlag);
+IsBufferInvalid = true;
 return None;
   }
 
@@ -180,7 +180,7 @@
   

[PATCH] D89834: FileManager: Improve the FileEntryRef API and add MaybeFileEntryRef

2020-10-20 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith added a comment.

Note that https://reviews.llvm.org/D89836 is an example of a follow-up patch 
that leverages these API changes. The original version of that patch was much, 
much noisier.


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

https://reviews.llvm.org/D89834

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


[PATCH] D89836: Change Module::ASTFile and ModuleFile::File => MaybeFileEntryRef, NFC

2020-10-20 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith created this revision.
dexonsmith added reviewers: arphaman, JDevlieghere, teemperor.
Herald added a subscriber: ributzka.
dexonsmith requested review of this revision.

Change `Module::ASTFile` and `ModuleFile::File` to use `MayeFileEntryRef`
instead of `const FileEntry *`. One of many steps toward removing
`FileEntry::getName`.


https://reviews.llvm.org/D89836

Files:
  clang/include/clang/Basic/FileEntry.h
  clang/include/clang/Basic/Module.h
  clang/include/clang/Serialization/ModuleFile.h
  clang/include/clang/Serialization/ModuleManager.h
  clang/lib/Basic/Module.cpp
  clang/lib/Sema/SemaModule.cpp
  clang/lib/Serialization/ModuleManager.cpp
  clang/tools/libclang/CIndex.cpp
  clang/tools/libclang/CXIndexDataConsumer.cpp

Index: clang/tools/libclang/CXIndexDataConsumer.cpp
===
--- clang/tools/libclang/CXIndexDataConsumer.cpp
+++ clang/tools/libclang/CXIndexDataConsumer.cpp
@@ -491,13 +491,10 @@
 if (SrcMod->getTopLevelModule() == Mod->getTopLevelModule())
   return;
 
-  CXIdxImportedASTFileInfo Info = {
-static_cast(
-const_cast(Mod->getASTFile())),
-Mod,
-getIndexLoc(ImportD->getLocation()),
-ImportD->isImplicit()
-  };
+  CXIdxImportedASTFileInfo Info = {static_cast(const_cast(
+   Mod->getASTFile().getFileEntry())),
+   Mod, getIndexLoc(ImportD->getLocation()),
+   ImportD->isImplicit()};
   CXIdxClientASTFile astFile = CB.importedASTFile(ClientData, );
   (void)astFile;
 }
Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -8397,7 +8397,7 @@
   if (!CXMod)
 return nullptr;
   Module *Mod = static_cast(CXMod);
-  return const_cast(Mod->getASTFile());
+  return const_cast(Mod->getASTFile().getFileEntry());
 }
 
 CXModule clang_Module_getParent(CXModule CXMod) {
Index: clang/lib/Serialization/ModuleManager.cpp
===
--- clang/lib/Serialization/ModuleManager.cpp
+++ clang/lib/Serialization/ModuleManager.cpp
@@ -112,7 +112,7 @@
 
   // Look for the file entry. This only fails if the expected size or
   // modification time differ.
-  const FileEntry *Entry;
+  MaybeFileEntryRef Entry;
   if (Type == MK_ExplicitModule || Type == MK_PrebuiltModule) {
 // If we're not expecting to pull this file out of the module cache, it
 // might have a different mtime due to being moved across filesystems in
@@ -288,7 +288,7 @@
 if (modMap) {
   StringRef ModuleName = victim->ModuleName;
   if (Module *mod = modMap->findModule(ModuleName)) {
-mod->setASTFile(nullptr);
+mod->setASTFile(None);
   }
 }
   }
@@ -458,18 +458,18 @@
   returnVisitState(State);
 }
 
-bool ModuleManager::lookupModuleFile(StringRef FileName,
- off_t ExpectedSize,
+bool ModuleManager::lookupModuleFile(StringRef FileName, off_t ExpectedSize,
  time_t ExpectedModTime,
- const FileEntry *) {
-  File = nullptr;
+ MaybeFileEntryRef ) {
+  File = None;
   if (FileName == "-")
 return false;
 
   // Open the file immediately to ensure there is no race between stat'ing and
   // opening the file.
-  auto FileOrErr = FileMgr.getFile(FileName, /*OpenFile=*/true,
-   /*CacheFailure=*/false);
+  MaybeFileEntryRef FileOrErr =
+  expectedToOptional(FileMgr.getFileRef(FileName, /*OpenFile=*/true,
+/*CacheFailure=*/false));
   if (!FileOrErr)
 return false;
 
Index: clang/lib/Sema/SemaModule.cpp
===
--- clang/lib/Sema/SemaModule.cpp
+++ clang/lib/Sema/SemaModule.cpp
@@ -187,7 +187,7 @@
   Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
   if (M->DefinitionLoc.isValid())
 Diag(M->DefinitionLoc, diag::note_prev_module_definition);
-  else if (const auto *FE = M->getASTFile())
+  else if (MaybeFileEntryRef FE = M->getASTFile())
 Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
 << FE->getName();
   Mod = M;
Index: clang/lib/Basic/Module.cpp
===
--- clang/lib/Basic/Module.cpp
+++ clang/lib/Basic/Module.cpp
@@ -671,7 +671,7 @@
 : Signature(M.Signature), ClangModule() {
   if (M.Directory)
 Path = M.Directory->getName();
-  if (auto *File = M.getASTFile())
+  if (auto File = M.getASTFile())

[PATCH] D89835: ModuleManager: Simplify lookupModuleFile by only setting the out parameter once, NFC

2020-10-20 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith created this revision.
dexonsmith added a reviewer: JDevlieghere.
Herald added a subscriber: ributzka.
dexonsmith requested review of this revision.

https://reviews.llvm.org/D89835

Files:
  clang/lib/Serialization/ModuleManager.cpp


Index: clang/lib/Serialization/ModuleManager.cpp
===
--- clang/lib/Serialization/ModuleManager.cpp
+++ clang/lib/Serialization/ModuleManager.cpp
@@ -462,19 +462,17 @@
  off_t ExpectedSize,
  time_t ExpectedModTime,
  const FileEntry *) {
-  if (FileName == "-") {
-File = nullptr;
+  File = nullptr;
+  if (FileName == "-")
 return false;
-  }
 
   // Open the file immediately to ensure there is no race between stat'ing and
   // opening the file.
   auto FileOrErr = FileMgr.getFile(FileName, /*OpenFile=*/true,
/*CacheFailure=*/false);
-  if (!FileOrErr) {
-File = nullptr;
+  if (!FileOrErr)
 return false;
-  }
+
   File = *FileOrErr;
 
   if ((ExpectedSize && ExpectedSize != File->getSize()) ||


Index: clang/lib/Serialization/ModuleManager.cpp
===
--- clang/lib/Serialization/ModuleManager.cpp
+++ clang/lib/Serialization/ModuleManager.cpp
@@ -462,19 +462,17 @@
  off_t ExpectedSize,
  time_t ExpectedModTime,
  const FileEntry *) {
-  if (FileName == "-") {
-File = nullptr;
+  File = nullptr;
+  if (FileName == "-")
 return false;
-  }
 
   // Open the file immediately to ensure there is no race between stat'ing and
   // opening the file.
   auto FileOrErr = FileMgr.getFile(FileName, /*OpenFile=*/true,
/*CacheFailure=*/false);
-  if (!FileOrErr) {
-File = nullptr;
+  if (!FileOrErr)
 return false;
-  }
+
   File = *FileOrErr;
 
   if ((ExpectedSize && ExpectedSize != File->getSize()) ||
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D89834: FileManager: Improve the FileEntryRef API and add MaybeFileEntryRef

2020-10-20 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith updated this revision to Diff 299506.
dexonsmith added a comment.

Attaching the correct diff :/.


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

https://reviews.llvm.org/D89834

Files:
  clang/include/clang/Basic/FileEntry.h
  clang/unittests/Basic/CMakeLists.txt
  clang/unittests/Basic/FileEntryTest.cpp
  clang/unittests/Basic/FileManagerTest.cpp

Index: clang/unittests/Basic/FileManagerTest.cpp
===
--- clang/unittests/Basic/FileManagerTest.cpp
+++ clang/unittests/Basic/FileManagerTest.cpp
@@ -334,6 +334,58 @@
 f2 ? *f2 : nullptr);
 }
 
+TEST_F(FileManagerTest, getFileRefEquality) {
+  auto StatCache = std::make_unique();
+  StatCache->InjectDirectory("dir", 40);
+  StatCache->InjectFile("dir/f1.cpp", 41);
+  StatCache->InjectFile("dir/f1-also.cpp", 41);
+  StatCache->InjectFile("dir/f1-redirect.cpp", 41, "dir/f1.cpp");
+  StatCache->InjectFile("dir/f2.cpp", 42);
+  manager.setStatCache(std::move(StatCache));
+
+  auto F1 = manager.getFileRef("dir/f1.cpp");
+  auto F1Again = manager.getFileRef("dir/f1.cpp");
+  auto F1Also = manager.getFileRef("dir/f1-also.cpp");
+  auto F1Redirect = manager.getFileRef("dir/f1-redirect.cpp");
+  auto F2 = manager.getFileRef("dir/f2.cpp");
+
+  // Check Expected for error.
+  ASSERT_FALSE(!F1);
+  ASSERT_FALSE(!F1Also);
+  ASSERT_FALSE(!F1Again);
+  ASSERT_FALSE(!F1Redirect);
+  ASSERT_FALSE(!F2);
+
+  // Check names.
+  EXPECT_EQ("dir/f1.cpp", F1->getName());
+  EXPECT_EQ("dir/f1.cpp", F1Again->getName());
+  EXPECT_EQ("dir/f1-also.cpp", F1Also->getName());
+  EXPECT_EQ("dir/f1.cpp", F1Redirect->getName());
+  EXPECT_EQ("dir/f2.cpp", F2->getName());
+
+  // Compare against FileEntry*.
+  EXPECT_EQ(>getFileEntry(), *F1);
+  EXPECT_EQ(*F1, >getFileEntry());
+  EXPECT_NE(>getFileEntry(), *F1);
+  EXPECT_NE(*F1, >getFileEntry());
+
+  // Compare using ==.
+  EXPECT_EQ(*F1, *F1Also);
+  EXPECT_EQ(*F1, *F1Again);
+  EXPECT_EQ(*F1, *F1Redirect);
+  EXPECT_EQ(*F1Also, *F1Redirect);
+  EXPECT_NE(*F2, *F1);
+  EXPECT_NE(*F2, *F1Also);
+  EXPECT_NE(*F2, *F1Again);
+  EXPECT_NE(*F2, *F1Redirect);
+
+  // Compare using isSameRef.
+  EXPECT_TRUE(F1->isSameRef(*F1Again));
+  EXPECT_TRUE(F1->isSameRef(*F1Redirect));
+  EXPECT_FALSE(F1->isSameRef(*F1Also));
+  EXPECT_FALSE(F1->isSameRef(*F2));
+}
+
 // getFile() Should return the same entry as getVirtualFile if the file actually
 // is a virtual file, even if the name is not exactly the same (but is after
 // normalisation done by the file system, like on Windows). This can be checked
Index: clang/unittests/Basic/FileEntryTest.cpp
===
--- /dev/null
+++ clang/unittests/Basic/FileEntryTest.cpp
@@ -0,0 +1,131 @@
+//===- unittests/Basic/FileEntryTest.cpp - Test FileEntry/FileEntryRef ===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/Basic/FileEntry.h"
+#include "llvm/ADT/StringMap.h"
+#include "gtest/gtest.h"
+
+using namespace llvm;
+using namespace clang;
+
+namespace {
+
+using MapEntry = FileEntryRef::MapEntry;
+using MapValue = FileEntryRef::MapValue;
+using MapType = StringMap>;
+
+FileEntryRef addRef(MapType , StringRef Name, FileEntry ) {
+  return FileEntryRef(*M.insert({Name, MapValue(E)}).first);
+}
+
+TEST(FileEntryTest, FileEntryRef) {
+  MapType Refs;
+  FileEntry E1, E2;
+  FileEntryRef R1 = addRef(Refs, "1", E1);
+  FileEntryRef R2 = addRef(Refs, "2", E2);
+  FileEntryRef R1Also = addRef(Refs, "1-also", E1);
+
+  EXPECT_EQ("1", R1.getName());
+  EXPECT_EQ("2", R2.getName());
+  EXPECT_EQ("1-also", R1Also.getName());
+
+  EXPECT_EQ(, ());
+  EXPECT_EQ(, ());
+  EXPECT_EQ(, ());
+
+  const FileEntry *CE1 = R1;
+  EXPECT_EQ(CE1, );
+}
+
+TEST(FileEntryTest, MaybeFileEntryRef) {
+  MapType Refs;
+  FileEntry E1, E2;
+  MaybeFileEntryRef M0;
+  MaybeFileEntryRef M1 = addRef(Refs, "1", E1);
+  MaybeFileEntryRef M2 = addRef(Refs, "2", E2);
+  MaybeFileEntryRef M1Also = addRef(Refs, "1-also", E1);
+
+  EXPECT_EQ(None, M0.getName());
+  EXPECT_EQ(StringRef("1"), M1.getName());
+  EXPECT_EQ(StringRef("2"), M2.getName());
+  EXPECT_EQ(StringRef("1-also"), M1Also.getName());
+  EXPECT_NE(None, M1.getName());
+  EXPECT_NE(StringRef("1"), M2.getName());
+
+  EXPECT_EQ(, M1.getFileEntry());
+  EXPECT_EQ(, M2.getFileEntry());
+  EXPECT_EQ(, M1Also.getFileEntry());
+
+  const FileEntry *CE1 = M1;
+  EXPECT_EQ(CE1, );
+}
+
+TEST(FileEntryTest, equals) {
+  MapType Refs;
+  FileEntry E1, E2;
+  FileEntryRef R1 = addRef(Refs, "1", E1);
+  FileEntryRef R2 = addRef(Refs, "2", E2);
+  FileEntryRef R1Also = addRef(Refs, "1-also", E1);
+
+  EXPECT_EQ(R1, );
+  EXPECT_EQ(, R1);
+  EXPECT_EQ(R1, R1Also);
+  

[PATCH] D89834: FileManager: Improve the FileEntryRef API and add MaybeFileEntryRef

2020-10-20 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith created this revision.
dexonsmith added reviewers: JDevlieghere, arphaman, teemperor.
Herald added subscribers: llvm-commits, ributzka, mgorny.
Herald added a project: LLVM.
dexonsmith requested review of this revision.

Make a few changes to the `FileEntryRef` API in preparation for
propagating it enough to remove `FileEntry::getName()`.

- Change `operator==` to compare the underlying `FileEntry*`, ignoring any 
difference to the spelling of the name. There were 0 users of the existing 
function because it's not useful. This avoids adding noisy code where 
`getFileEntry()` is used pervasively to compare equality. In case comparing the 
named reference becomes important, add (and test) the API now called 
`isSameRef`.
- Add `MaybeFileEntryRef`, which is a pointer-sized version of 
`Optional` that is designed to replace fields that are currently 
`FileEntry*`. To avoid code duplication, the guts of `FileEntryRef` were moved 
to a common base class, `FileEntryRefBase`. Besides interoperation with 
`Optional`, this calls exposes `getName()` (`Optional` version) and 
`getFileEntry()` (pointer version).
- Add implicit conversions to `FileEntry*` to allow functions currently 
returning `const FileEntry*` to be updated to `FileEntryRef` or 
`MaybeFileEntryRef` without requiring all callers to be updated in the same 
step. This helps avoid both (a) massive patches where many fields and locals 
are updated simultaneously and (b) noisy incremental patches where the first 
patch adds `getFileEntry()` at call sites and the second patch removes it.
- Add various `operator==` for easy interoperation.
- Remove the `const` from the return of `FileEntryRef::getName`.
- As a drive-by cleanup, delete the unused `FileEntry::isOpenForTests`.

Note that there are still `FileEntry` APIs that aren't wrapped and I
plan to deal with these separately / incrementally, as they are needed.


https://reviews.llvm.org/D89834

Files:
  clang/include/clang/Basic/FileEntry.h
  clang/include/clang/Basic/FileManager.h
  clang/lib/Basic/CMakeLists.txt
  clang/lib/Basic/FileEntry.cpp
  llvm/include/llvm/Support/FileSystem.h
  llvm/include/llvm/Support/FileSystem/UniqueID.h

Index: llvm/include/llvm/Support/FileSystem/UniqueID.h
===
--- /dev/null
+++ llvm/include/llvm/Support/FileSystem/UniqueID.h
@@ -0,0 +1,47 @@
+//===- llvm/Support/FileSystem/UniqueID.h - UniqueID for files --*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This file is cut out of llvm/Support/FileSystem.h to allow UniqueID to be
+// reused without bloating the includes.
+//
+//===--===//
+
+#ifndef LLVM_SUPPORT_FILESYSTEM_UNIQUEID_H
+#define LLVM_SUPPORT_FILESYSTEM_UNIQUEID_H
+
+#include 
+
+namespace llvm {
+namespace sys {
+namespace fs {
+
+class UniqueID {
+  uint64_t Device;
+  uint64_t File;
+
+public:
+  UniqueID() = default;
+  UniqueID(uint64_t Device, uint64_t File) : Device(Device), File(File) {}
+
+  bool operator==(const UniqueID ) const {
+return Device == Other.Device && File == Other.File;
+  }
+  bool operator!=(const UniqueID ) const { return !(*this == Other); }
+  bool operator<(const UniqueID ) const {
+return std::tie(Device, File) < std::tie(Other.Device, Other.File);
+  }
+
+  uint64_t getDevice() const { return Device; }
+  uint64_t getFile() const { return File; }
+};
+
+} // end namespace fs
+} // end namespace sys
+} // end namespace llvm
+
+#endif // LLVM_SUPPORT_FILESYSTEM_UNIQUEID_H
Index: llvm/include/llvm/Support/FileSystem.h
===
--- llvm/include/llvm/Support/FileSystem.h
+++ llvm/include/llvm/Support/FileSystem.h
@@ -34,6 +34,7 @@
 #include "llvm/Support/Error.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/ErrorOr.h"
+#include "llvm/Support/FileSystem/UniqueID.h"
 #include "llvm/Support/MD5.h"
 #include 
 #include 
@@ -131,26 +132,6 @@
   static_cast(~static_cast(x)));
 }
 
-class UniqueID {
-  uint64_t Device;
-  uint64_t File;
-
-public:
-  UniqueID() = default;
-  UniqueID(uint64_t Device, uint64_t File) : Device(Device), File(File) {}
-
-  bool operator==(const UniqueID ) const {
-return Device == Other.Device && File == Other.File;
-  }
-  bool operator!=(const UniqueID ) const { return !(*this == Other); }
-  bool operator<(const UniqueID ) const {
-return std::tie(Device, File) < std::tie(Other.Device, Other.File);
-  }
-
-  uint64_t getDevice() const { return Device; }
-  uint64_t getFile() const { return File; }
-};
-
 /// Represents the result of a call to directory_iterator::status(). This is a
 /// subset of the 

[PATCH] D89832: [CUDA] Extract CUDA version from cuda.h if version.txt is not found

2020-10-20 Thread Artem Belevich via Phabricator via cfe-commits
tra updated this revision to Diff 299501.
tra edited the summary of this revision.
tra added a comment.

Added more tests.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89832

Files:
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/lib/Driver/ToolChains/Cuda.cpp
  clang/lib/Driver/ToolChains/Cuda.h
  clang/test/Driver/Inputs/CUDA_102/usr/local/cuda/bin/.keep
  clang/test/Driver/Inputs/CUDA_102/usr/local/cuda/include/.keep
  clang/test/Driver/Inputs/CUDA_102/usr/local/cuda/lib/.keep
  clang/test/Driver/Inputs/CUDA_102/usr/local/cuda/lib64/.keep
  
clang/test/Driver/Inputs/CUDA_102/usr/local/cuda/nvvm/libdevice/libdevice.10.bc
  clang/test/Driver/Inputs/CUDA_102/usr/local/cuda/version.txt
  clang/test/Driver/Inputs/CUDA_111/usr/local/cuda/include/cuda.h
  clang/test/Driver/cuda-version-check.cu

Index: clang/test/Driver/cuda-version-check.cu
===
--- clang/test/Driver/cuda-version-check.cu
+++ clang/test/Driver/cuda-version-check.cu
@@ -8,13 +8,15 @@
 // RUN:FileCheck %s --check-prefix=OK
 // RUN: %clang --target=x86_64-linux -v -### --cuda-gpu-arch=sm_60 --cuda-path=%S/Inputs/CUDA_80/usr/local/cuda 2>&1 %s | \
 // RUN:FileCheck %s --check-prefix=OK
+// Test version guess when no version.txt or cuda.h are found
 // RUN: %clang --target=x86_64-linux -v -### --cuda-gpu-arch=sm_60 --cuda-path=%S/Inputs/CUDA-unknown/usr/local/cuda 2>&1 %s | \
 // RUN:FileCheck %s --check-prefix=UNKNOWN_VERSION
-// CUDA versions after 11.0 (update 1) do not carry version.txt file. Make sure
-// we still detect them as a new version and handle them the same as we handle
-// other new CUDA versions.
+// Unknown version with version.txt present
+// RUN: %clang --target=x86_64-linux -v -### --cuda-gpu-arch=sm_60 --cuda-path=%S/Inputs/CUDA_102/usr/local/cuda 2>&1 %s | \
+// RUN:FileCheck %s --check-prefix=UNKNOWN_VERSION_V
+// Unknown version with no version.txt but with version info present in cuda.h
 // RUN: %clang --target=x86_64-linux -v -### --cuda-gpu-arch=sm_60 --cuda-path=%S/Inputs/CUDA_111/usr/local/cuda 2>&1 %s | \
-// RUN:FileCheck %s --check-prefix=UNKNOWN_VERSION
+// RUN:FileCheck %s --check-prefix=UNKNOWN_VERSION_H
 // Make sure that we don't warn about CUDA version during C++ compilation.
 // RUN: %clang --target=x86_64-linux -v -### -x c++ --cuda-gpu-arch=sm_60 \
 // RUN:--cuda-path=%S/Inputs/CUDA-unknown/usr/local/cuda 2>&1 %s | \
@@ -70,5 +72,7 @@
 // ERR_SM61: error: GPU arch sm_61 {{.*}}
 // ERR_SM61-NOT: error: GPU arch sm_61
 
-// UNKNOWN_VERSION: Unknown CUDA version {{.*}}. Assuming the latest supported version
+// UNKNOWN_VERSION_V: Unknown CUDA version. version.txt:{{.*}}. Assuming the latest supported version
+// UNKNOWN_VERSION_H: Unknown CUDA version. cuda.h: CUDA_VERSION={{.*}}. Assuming the latest supported version
+// UNKNOWN_VERSION: Unknown CUDA version. No version found in version.txt or cuda.h. Assuming the latest supported version
 // UNKNOWN_VERSION_CXX-NOT: Unknown CUDA version
Index: clang/test/Driver/Inputs/CUDA_111/usr/local/cuda/include/cuda.h
===
--- /dev/null
+++ clang/test/Driver/Inputs/CUDA_111/usr/local/cuda/include/cuda.h
@@ -0,0 +1,7 @@
+//
+// Placeholder file for testing CUDA version detection
+//
+
+#define CUDA_VERSION 11010
+
+//
Index: clang/test/Driver/Inputs/CUDA_102/usr/local/cuda/version.txt
===
--- /dev/null
+++ clang/test/Driver/Inputs/CUDA_102/usr/local/cuda/version.txt
@@ -0,0 +1 @@
+CUDA Version 10.2.333
Index: clang/lib/Driver/ToolChains/Cuda.h
===
--- clang/lib/Driver/ToolChains/Cuda.h
+++ clang/lib/Driver/ToolChains/Cuda.h
@@ -78,9 +78,6 @@
 return LibDeviceMap.lookup(Gpu);
   }
   void WarnIfUnsupportedVersion();
-
-private:
-  void ParseCudaVersionFile(llvm::StringRef V);
 };
 
 namespace tools {
Index: clang/lib/Driver/ToolChains/Cuda.cpp
===
--- clang/lib/Driver/ToolChains/Cuda.cpp
+++ clang/lib/Driver/ToolChains/Cuda.cpp
@@ -16,6 +16,7 @@
 #include "clang/Driver/Driver.h"
 #include "clang/Driver/DriverDiagnostic.h"
 #include "clang/Driver/Options.h"
+#include "llvm/ADT/Optional.h"
 #include "llvm/Option/ArgList.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/Host.h"
@@ -32,29 +33,80 @@
 using namespace clang;
 using namespace llvm::opt;
 
+namespace {
+struct CudaVersionInfo {
+  std::string DetectedVersion;
+  CudaVersion Version;
+};
 // Parses the contents of version.txt in an CUDA installation.  It should
 // contain one line of the from e.g. "CUDA Version 7.5.2".
-void CudaInstallationDetector::ParseCudaVersionFile(llvm::StringRef V) {
-  Version = CudaVersion::UNKNOWN;
+CudaVersionInfo 

[PATCH] D87956: [IR] add fn attr for no_stack_protector; prevent inlining ssp into nossp

2020-10-20 Thread Nick Desaulniers via Phabricator via cfe-commits
nickdesaulniers added a comment.

bumping for review


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87956

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


[PATCH] D89696: [OpenMP] Fixing OpenMP/driver.c failing on 32-bit hosts

2020-10-20 Thread David Tenty via Phabricator via cfe-commits
daltenty added inline comments.



Comment at: clang/test/OpenMP/driver-openmp-target.c:2
+// REQUIRES: x86-registered-target
+// REQUIRES: clang-64-bits
+// RUN: %clang %s -c -E -dM -fopenmp=libomp -fopenmp-version=45 
-fopenmp-targets=x86_64-unknown-unknown -o - | FileCheck 
--check-prefix=CHECK-45-VERSION --check-prefix=CHECK-45-VERSION2 %s

This tests still fails on AIX, presumably because we have a 64-bit host but the 
compiler is targeting 32-bit by default:

```
error: OpenMP target architecture 'x86_64-unknown-unknown' pointer size is 
incompatible with host 'powerpc-ibm-aix7.2.0.0'
```

Maybe adjust the test to check the default target instead of just the host?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89696

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


[PATCH] D87528: Enable '#pragma STDC FENV_ACCESS' in frontend cf. D69272 - Work in Progress

2020-10-20 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith accepted this revision.
rsmith added a comment.
This revision is now accepted and ready to land.

Thanks, I'm happy with this, though please wait a day or two for comments from 
the other reviewers.

We should also add some documentation covering the rules we're using for the 
floating-point environment in C++, particularly around initializers for 
variables with static storage duration, given that that's not governed by any 
language standard.




Comment at: clang/test/CodeGen/fp-floatcontrol-pragma.cpp:159
+  //CHECK: store float 3.0{{.*}}retval{{.*}}
+  static double v = 1.0 / 3.0;
+  //CHECK-FENV: llvm.experimental.constrained.fptrunc.f32.f64{{.*}}

mibintc wrote:
> @rsmith - the division is constant folded.  is that right? 
Yes, that's in line with our new expectations for C++. Specifically: for static 
/ thread-local variables, first try evaluating the initializer in a constant 
context, including in the constant floating point environment (just like in C), 
and then, if that fails, fall back to emitting runtime code to perform the 
initialization (which might in general be in a different FP environment). Given 
that `1.0 / 3.0` is a constant initializer, it should get folded using the 
constant rounding mode. But, for example:

```
double f() {
  int n = 0;
  static double v = 1.0 / 3.0 + 0 * n;
  return v;
}
```

... should emit a constrained `fdiv` at runtime, because the read of `n` causes 
the initializer to not be a constant initializer. And similarly:

```
double f() {
  double v = 1.0 / 3.0 + 0 * n;
  return v;
}
```

... should emit a constrained `fdiv`, because `v` is not a static storage 
duration variable, so there is formally no "first try evaluating the 
initializer as a constant" step.



Comment at: clang/test/Parser/pragma-fenv_access.c:28
+#if defined(CPP) & defined(STRICT)
+//not-expected-error@+3 {{constexpr variable 'frac' must be initialized by a 
constant expression}}
+//not-expected-note@+2 {{compile time floating point arithmetic suppressed in 
strict evaluation modes}}

mibintc wrote:
> @rsmith no diagnostic, is this OK?
Under the new approach from D89360, I would expect no diagnostic with `CONST` 
defined as `constexpr`, because the initializer is then manifestly 
constant-evaluated, so should be evaluated in the constant rounding mode.

With `CONST` defined as merely `const`, I'd expect that we emit a constrained 
floating-point operation using the runtime rounding mode here. You can test 
that we don't constant-evaluate the value of a (non-`constexpr`) `const float` 
variable by using this hack (with `CONST` defined as `const`):

```
enum {
  e1 = (int)one, e3 = (int)three, e4 = (int)four, e_four_quarters = 
(int)(frac_ok * 4)
};
static_assert(e1 == 1  && e3 == 3 && e4 == 4 && e_four_quarters == 1, "");
enum {
  e_three_thirds = (int)(frac * 3) // expected-error {{not an integral constant 
expression}}
};
```

(The hack here is that we permit constant folding in the values of enumerators, 
and we allow constant folding to look at the evaluated values of `const float` 
variables. This should not be allowed for `frac`, because attempting to 
evaluate its initializer should fail.)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87528

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


[PATCH] D89832: [CUDA] Extract CUDA version from cuda.h if version.txt is not found

2020-10-20 Thread Artem Belevich via Phabricator via cfe-commits
tra created this revision.
tra added reviewers: jlebar, yaxunl, emankov.
Herald added subscribers: dexonsmith, bixia.
Herald added a project: clang.
tra requested review of this revision.

This is a follow-up to D89752 ,

If CUDA version can not be determined based on version.txt file, attempt to 
find CUDA_VERSION macro in cuda.h.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D89832

Files:
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/lib/Driver/ToolChains/Cuda.cpp
  clang/lib/Driver/ToolChains/Cuda.h
  clang/test/Driver/Inputs/CUDA_111/usr/local/cuda/include/cuda.h
  clang/test/Driver/cuda-version-check.cu

Index: clang/test/Driver/cuda-version-check.cu
===
--- clang/test/Driver/cuda-version-check.cu
+++ clang/test/Driver/cuda-version-check.cu
@@ -70,5 +70,5 @@
 // ERR_SM61: error: GPU arch sm_61 {{.*}}
 // ERR_SM61-NOT: error: GPU arch sm_61
 
-// UNKNOWN_VERSION: Unknown CUDA version {{.*}}. Assuming the latest supported version
+// UNKNOWN_VERSION: Unknown CUDA version. {{.*}}. Assuming the latest supported version
 // UNKNOWN_VERSION_CXX-NOT: Unknown CUDA version
Index: clang/test/Driver/Inputs/CUDA_111/usr/local/cuda/include/cuda.h
===
--- /dev/null
+++ clang/test/Driver/Inputs/CUDA_111/usr/local/cuda/include/cuda.h
@@ -0,0 +1,7 @@
+//
+// Placeholder file for testing CUDA version detection
+//
+
+#define CUDA_VERSION 11010
+
+//
Index: clang/lib/Driver/ToolChains/Cuda.h
===
--- clang/lib/Driver/ToolChains/Cuda.h
+++ clang/lib/Driver/ToolChains/Cuda.h
@@ -78,9 +78,6 @@
 return LibDeviceMap.lookup(Gpu);
   }
   void WarnIfUnsupportedVersion();
-
-private:
-  void ParseCudaVersionFile(llvm::StringRef V);
 };
 
 namespace tools {
Index: clang/lib/Driver/ToolChains/Cuda.cpp
===
--- clang/lib/Driver/ToolChains/Cuda.cpp
+++ clang/lib/Driver/ToolChains/Cuda.cpp
@@ -16,6 +16,7 @@
 #include "clang/Driver/Driver.h"
 #include "clang/Driver/DriverDiagnostic.h"
 #include "clang/Driver/Options.h"
+#include "llvm/ADT/Optional.h"
 #include "llvm/Option/ArgList.h"
 #include "llvm/Support/FileSystem.h"
 #include "llvm/Support/Host.h"
@@ -32,29 +33,80 @@
 using namespace clang;
 using namespace llvm::opt;
 
+namespace {
+struct CudaVersionInfo {
+  std::string DetectedVersion;
+  CudaVersion Version;
+};
 // Parses the contents of version.txt in an CUDA installation.  It should
 // contain one line of the from e.g. "CUDA Version 7.5.2".
-void CudaInstallationDetector::ParseCudaVersionFile(llvm::StringRef V) {
-  Version = CudaVersion::UNKNOWN;
+CudaVersionInfo parseCudaVersionFile(llvm::StringRef V) {
+  V = V.trim();
   if (!V.startswith("CUDA Version "))
-return;
+return {V.str(), CudaVersion::UNKNOWN};
   V = V.substr(strlen("CUDA Version "));
   SmallVector VersionParts;
   V.split(VersionParts, '.');
-  if (VersionParts.size() < 2)
-return;
-  DetectedVersion = join_items(".", VersionParts[0], VersionParts[1]);
-  Version = CudaStringToVersion(DetectedVersion);
-  if (Version != CudaVersion::UNKNOWN) {
-// TODO(tra): remove the warning once we have all features of 10.2 and 11.0
-// implemented.
-DetectedVersionIsNotSupported = Version > CudaVersion::LATEST_SUPPORTED;
-return;
+  return {"version.txt: " + V.str(),
+  VersionParts.size() < 2
+  ? CudaVersion::UNKNOWN
+  : CudaStringToVersion(
+join_items(".", VersionParts[0], VersionParts[1]))};
+}
+
+CudaVersion getCudaVersion(uint32_t raw_version) {
+  if (raw_version < 7050)
+return CudaVersion::CUDA_70;
+  if (raw_version < 8000)
+return CudaVersion::CUDA_75;
+  if (raw_version < 9000)
+return CudaVersion::CUDA_80;
+  if (raw_version < 9010)
+return CudaVersion::CUDA_90;
+  if (raw_version < 9020)
+return CudaVersion::CUDA_91;
+  if (raw_version < 1)
+return CudaVersion::CUDA_92;
+  if (raw_version < 10010)
+return CudaVersion::CUDA_100;
+  if (raw_version < 10020)
+return CudaVersion::CUDA_101;
+  if (raw_version < 11000)
+return CudaVersion::CUDA_102;
+  if (raw_version < 11010)
+return CudaVersion::CUDA_110;
+  return CudaVersion::LATEST;
+}
+
+CudaVersionInfo parseCudaHFile(llvm::StringRef Input) {
+  // Helper lambda which skips the words if the line starts with them or returns
+  // None otherwise.
+  auto StartsWithWords =
+  [](llvm::StringRef Line,
+ const SmallVector words) -> llvm::Optional {
+for (StringRef word : words) {
+  if (!Line.consume_front(word))
+return {};
+  Line = Line.ltrim();
+}
+return Line;
+  };
+
+  Input = Input.ltrim();
+  while (!Input.empty()) {
+if (auto Line =
+StartsWithWords(Input.ltrim(), {"#", "define", 

[PATCH] D89752: [CUDA] Improve clang's ability to detect recent CUDA versions.

2020-10-20 Thread Artem Belevich via Phabricator via cfe-commits
tra added inline comments.



Comment at: clang/test/Driver/cuda-version-check.cu:13
 // RUN:FileCheck %s --check-prefix=UNKNOWN_VERSION
+// CUDA-11.1 does not carry version.txt file. Make sure we still detect it as a
+// new version and handle it the same as we handle other new CUDA versions.

emankov wrote:
> CUDA-11.0 Update 1 doesn't carry version.txt as well.
> CUDA-11.0 Update 1 doesn't carry version.txt as well.

This assertion appears to be incorrect. I've just installed 11.0 update1 using 
Ubuntu [[ 
https://developer.download.nvidia.com/compute/cuda/11.0.3/local_installers/cuda_11.0.3_450.51.06_linux.run
 | .run ]] installer I've got from 
https://developer.nvidia.com/cuda-11.0-update1-download-archive  and the 
installed version does have version.txt saying 

```
CUDA Version 11.0.228
```

Did you use some other installer variant?



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89752

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


[clang] 747b134 - clang/Basic: Remove SourceManager::getBufferPointer, NFC

2020-10-20 Thread Duncan P . N . Exon Smith via cfe-commits

Author: Duncan P. N. Exon Smith
Date: 2020-10-20T18:02:42-04:00
New Revision: 747b134d019ce99bc4463d09992634965ee95031

URL: 
https://github.com/llvm/llvm-project/commit/747b134d019ce99bc4463d09992634965ee95031
DIFF: 
https://github.com/llvm/llvm-project/commit/747b134d019ce99bc4463d09992634965ee95031.diff

LOG: clang/Basic: Remove SourceManager::getBufferPointer, NFC

Inline `Source::getBufferPointer` into its only remaining caller,
`getBufferOrNone`. No functionality change.

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

Added: 


Modified: 
clang/include/clang/Basic/SourceManager.h
clang/lib/Basic/SourceManager.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/SourceManager.h 
b/clang/include/clang/Basic/SourceManager.h
index 905b706971d5..480fa51d6889 100644
--- a/clang/include/clang/Basic/SourceManager.h
+++ b/clang/include/clang/Basic/SourceManager.h
@@ -188,17 +188,6 @@ namespace SrcMgr {
 getBufferOrNone(DiagnosticsEngine , FileManager ,
 SourceLocation Loc = SourceLocation()) const;
 
-  private:
-/// Returns pointer to memory buffer.
-///
-/// TODO: SourceManager needs access to this for now, but once that's done
-/// we should remove this API.
-const llvm::MemoryBuffer *getBufferPointer(DiagnosticsEngine ,
-   FileManager ,
-   SourceLocation Loc) const;
-friend class clang::SourceManager;
-
-  public:
 /// Returns the size of the content encapsulated by this
 /// ContentCache.
 ///

diff  --git a/clang/lib/Basic/SourceManager.cpp 
b/clang/lib/Basic/SourceManager.cpp
index 51772d5aa335..27d2f398f3c6 100644
--- a/clang/lib/Basic/SourceManager.cpp
+++ b/clang/lib/Basic/SourceManager.cpp
@@ -121,22 +121,14 @@ const char *ContentCache::getInvalidBOM(StringRef BufStr) 
{
 llvm::Optional
 ContentCache::getBufferOrNone(DiagnosticsEngine , FileManager ,
   SourceLocation Loc) const {
-  if (auto *B = getBufferPointer(Diag, FM, Loc))
-return B->getMemBufferRef();
-  return None;
-}
-
-const llvm::MemoryBuffer *
-ContentCache::getBufferPointer(DiagnosticsEngine , FileManager ,
-   SourceLocation Loc) const {
   // Lazily create the Buffer for ContentCaches that wrap files.  If we already
   // computed it, just return what we have.
   if (isBufferInvalid())
-return nullptr;
+return None;
   if (auto *B = Buffer.getPointer())
-return B;
+return B->getMemBufferRef();
   if (!ContentsEntry)
-return nullptr;
+return None;
 
   // Check that the file's size fits in an 'unsigned' (with room for a
   // past-the-end value). This is deeply regrettable, but various parts of
@@ -153,7 +145,7 @@ ContentCache::getBufferPointer(DiagnosticsEngine , 
FileManager ,
 << ContentsEntry->getName();
 
 Buffer.setInt(Buffer.getInt() | InvalidFlag);
-return nullptr;
+return None;
   }
 
   auto BufferOrError = FM.getBufferForFile(ContentsEntry, IsFileVolatile);
@@ -173,7 +165,7 @@ ContentCache::getBufferPointer(DiagnosticsEngine , 
FileManager ,
   << ContentsEntry->getName() << BufferOrError.getError().message();
 
 Buffer.setInt(Buffer.getInt() | InvalidFlag);
-return nullptr;
+return None;
   }
 
   Buffer.setPointer(BufferOrError->release());
@@ -189,7 +181,7 @@ ContentCache::getBufferPointer(DiagnosticsEngine , 
FileManager ,
 << ContentsEntry->getName();
 
 Buffer.setInt(Buffer.getInt() | InvalidFlag);
-return nullptr;
+return None;
   }
 
   // If the buffer is valid, check to see if it has a UTF Byte Order Mark
@@ -202,10 +194,10 @@ ContentCache::getBufferPointer(DiagnosticsEngine , 
FileManager ,
 Diag.Report(Loc, diag::err_unsupported_bom)
   << InvalidBOM << ContentsEntry->getName();
 Buffer.setInt(Buffer.getInt() | InvalidFlag);
-return nullptr;
+return None;
   }
 
-  return Buffer.getPointer();
+  return Buffer.getPointer()->getMemBufferRef();
 }
 
 unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {



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


[PATCH] D89430: clang/Basic: Remove SourceManager::getBufferPointer, NFC

2020-10-20 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG747b134d019c: clang/Basic: Remove 
SourceManager::getBufferPointer, NFC (authored by dexonsmith).
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89430

Files:
  clang/include/clang/Basic/SourceManager.h
  clang/lib/Basic/SourceManager.cpp


Index: clang/lib/Basic/SourceManager.cpp
===
--- clang/lib/Basic/SourceManager.cpp
+++ clang/lib/Basic/SourceManager.cpp
@@ -121,22 +121,14 @@
 llvm::Optional
 ContentCache::getBufferOrNone(DiagnosticsEngine , FileManager ,
   SourceLocation Loc) const {
-  if (auto *B = getBufferPointer(Diag, FM, Loc))
-return B->getMemBufferRef();
-  return None;
-}
-
-const llvm::MemoryBuffer *
-ContentCache::getBufferPointer(DiagnosticsEngine , FileManager ,
-   SourceLocation Loc) const {
   // Lazily create the Buffer for ContentCaches that wrap files.  If we already
   // computed it, just return what we have.
   if (isBufferInvalid())
-return nullptr;
+return None;
   if (auto *B = Buffer.getPointer())
-return B;
+return B->getMemBufferRef();
   if (!ContentsEntry)
-return nullptr;
+return None;
 
   // Check that the file's size fits in an 'unsigned' (with room for a
   // past-the-end value). This is deeply regrettable, but various parts of
@@ -153,7 +145,7 @@
 << ContentsEntry->getName();
 
 Buffer.setInt(Buffer.getInt() | InvalidFlag);
-return nullptr;
+return None;
   }
 
   auto BufferOrError = FM.getBufferForFile(ContentsEntry, IsFileVolatile);
@@ -173,7 +165,7 @@
   << ContentsEntry->getName() << BufferOrError.getError().message();
 
 Buffer.setInt(Buffer.getInt() | InvalidFlag);
-return nullptr;
+return None;
   }
 
   Buffer.setPointer(BufferOrError->release());
@@ -189,7 +181,7 @@
 << ContentsEntry->getName();
 
 Buffer.setInt(Buffer.getInt() | InvalidFlag);
-return nullptr;
+return None;
   }
 
   // If the buffer is valid, check to see if it has a UTF Byte Order Mark
@@ -202,10 +194,10 @@
 Diag.Report(Loc, diag::err_unsupported_bom)
   << InvalidBOM << ContentsEntry->getName();
 Buffer.setInt(Buffer.getInt() | InvalidFlag);
-return nullptr;
+return None;
   }
 
-  return Buffer.getPointer();
+  return Buffer.getPointer()->getMemBufferRef();
 }
 
 unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) {
Index: clang/include/clang/Basic/SourceManager.h
===
--- clang/include/clang/Basic/SourceManager.h
+++ clang/include/clang/Basic/SourceManager.h
@@ -188,17 +188,6 @@
 getBufferOrNone(DiagnosticsEngine , FileManager ,
 SourceLocation Loc = SourceLocation()) const;
 
-  private:
-/// Returns pointer to memory buffer.
-///
-/// TODO: SourceManager needs access to this for now, but once that's done
-/// we should remove this API.
-const llvm::MemoryBuffer *getBufferPointer(DiagnosticsEngine ,
-   FileManager ,
-   SourceLocation Loc) const;
-friend class clang::SourceManager;
-
-  public:
 /// Returns the size of the content encapsulated by this
 /// ContentCache.
 ///


Index: clang/lib/Basic/SourceManager.cpp
===
--- clang/lib/Basic/SourceManager.cpp
+++ clang/lib/Basic/SourceManager.cpp
@@ -121,22 +121,14 @@
 llvm::Optional
 ContentCache::getBufferOrNone(DiagnosticsEngine , FileManager ,
   SourceLocation Loc) const {
-  if (auto *B = getBufferPointer(Diag, FM, Loc))
-return B->getMemBufferRef();
-  return None;
-}
-
-const llvm::MemoryBuffer *
-ContentCache::getBufferPointer(DiagnosticsEngine , FileManager ,
-   SourceLocation Loc) const {
   // Lazily create the Buffer for ContentCaches that wrap files.  If we already
   // computed it, just return what we have.
   if (isBufferInvalid())
-return nullptr;
+return None;
   if (auto *B = Buffer.getPointer())
-return B;
+return B->getMemBufferRef();
   if (!ContentsEntry)
-return nullptr;
+return None;
 
   // Check that the file's size fits in an 'unsigned' (with room for a
   // past-the-end value). This is deeply regrettable, but various parts of
@@ -153,7 +145,7 @@
 << ContentsEntry->getName();
 
 Buffer.setInt(Buffer.getInt() | InvalidFlag);
-return nullptr;
+return None;
   }
 
   auto BufferOrError = FM.getBufferForFile(ContentsEntry, IsFileVolatile);
@@ -173,7 +165,7 @@
   << ContentsEntry->getName() << BufferOrError.getError().message();
 
 Buffer.setInt(Buffer.getInt() | InvalidFlag);
-

[PATCH] D89579: [clangd][ObjC] Support nullability annotations

2020-10-20 Thread David Goldman via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGd5c022d84699: [clangd][ObjC] Support nullability annotations 
(authored by dgoldman).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89579

Files:
  clang-tools-extra/clangd/Selection.cpp
  clang-tools-extra/clangd/unittests/FindTargetTests.cpp
  clang-tools-extra/clangd/unittests/HoverTests.cpp
  clang-tools-extra/clangd/unittests/SelectionTests.cpp

Index: clang-tools-extra/clangd/unittests/SelectionTests.cpp
===
--- clang-tools-extra/clangd/unittests/SelectionTests.cpp
+++ clang-tools-extra/clangd/unittests/SelectionTests.cpp
@@ -356,6 +356,22 @@
 )cpp",
   "DeclRefExpr"},
 
+  // Objective-C nullability attributes.
+  {
+  R"cpp(
+@interface I{}
+@property(nullable) [[^I]] *x;
+@end
+  )cpp",
+  "ObjCInterfaceTypeLoc"},
+  {
+  R"cpp(
+@interface I{}
+- (void)doSomething:(nonnull [[i^d]])argument;
+@end
+  )cpp",
+  "TypedefTypeLoc"},
+
   // Objective-C OpaqueValueExpr/PseudoObjectExpr has weird ASTs.
   // Need to traverse the contents of the OpaqueValueExpr to the POE,
   // and ensure we traverse only the syntactic form of the PseudoObjectExpr.
Index: clang-tools-extra/clangd/unittests/HoverTests.cpp
===
--- clang-tools-extra/clangd/unittests/HoverTests.cpp
+++ clang-tools-extra/clangd/unittests/HoverTests.cpp
@@ -1991,6 +1991,34 @@
 HI.NamespaceScope = "ObjC::"; // FIXME: fix it
 HI.Definition = "char data";
   }},
+  {
+  R"cpp(
+  @interface MYObject
+  @end
+  @interface Interface
+  @property(retain) [[MYOb^ject]] *x;
+  @end
+  )cpp",
+  [](HoverInfo ) {
+HI.Name = "MYObject";
+HI.Kind = index::SymbolKind::Class;
+HI.NamespaceScope = "";
+HI.Definition = "@interface MYObject\n@end";
+  }},
+  {
+  R"cpp(
+  @interface MYObject
+  @end
+  @interface Interface
+  - (void)doWith:([[MYOb^ject]] *)object;
+  @end
+  )cpp",
+  [](HoverInfo ) {
+HI.Name = "MYObject";
+HI.Kind = index::SymbolKind::Class;
+HI.NamespaceScope = "";
+HI.Definition = "@interface MYObject\n@end";
+  }},
   };
 
   // Create a tiny index, so tests above can verify documentation is fetched.
Index: clang-tools-extra/clangd/unittests/FindTargetTests.cpp
===
--- clang-tools-extra/clangd/unittests/FindTargetTests.cpp
+++ clang-tools-extra/clangd/unittests/FindTargetTests.cpp
@@ -831,6 +831,24 @@
   EXPECT_DECLS("ObjCPropertyRefExpr",
"@property(atomic, retain, readwrite) I *x");
 
+  Code = R"cpp(
+@interface MYObject
+@end
+@interface Interface
+@property(retain) [[MYObject]] *x;
+@end
+  )cpp";
+  EXPECT_DECLS("ObjCInterfaceTypeLoc", "@interface MYObject");
+
+  Code = R"cpp(
+@interface MYObject2
+@end
+@interface Interface
+@property(retain, nonnull) [[MYObject2]] *x;
+@end
+  )cpp";
+  EXPECT_DECLS("ObjCInterfaceTypeLoc", "@interface MYObject2");
+
   Code = R"cpp(
 @protocol Foo
 @end
Index: clang-tools-extra/clangd/Selection.cpp
===
--- clang-tools-extra/clangd/Selection.cpp
+++ clang-tools-extra/clangd/Selection.cpp
@@ -605,6 +605,10 @@
   bool canSafelySkipNode(const DynTypedNode ) {
 SourceRange S = N.getSourceRange();
 if (auto *TL = N.get()) {
+  // FIXME: TypeLoc::getBeginLoc()/getEndLoc() are pretty fragile
+  // heuristics. We should consider only pruning critical TypeLoc nodes, to
+  // be more robust.
+
   // DeclTypeTypeLoc::getSourceRange() is incomplete, which would lead to
   // failing
   // to descend into the child expression.
@@ -616,6 +620,10 @@
   // rid of this patch.
   if (auto DT = TL->getAs())
 S.setEnd(DT.getUnderlyingExpr()->getEndLoc());
+  // AttributedTypeLoc may point to the attribute's range, NOT the modified
+  // type's range.
+  if (auto AT = TL->getAs())
+S = AT.getModifiedLoc().getSourceRange();
 }
 if (!SelChecker.mayHit(S)) {
   dlog("{1}skip: {0}", printNodeToString(N, PrintPolicy), indent());
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] d5c022d - [clangd][ObjC] Support nullability annotations

2020-10-20 Thread David Goldman via cfe-commits

Author: David Goldman
Date: 2020-10-20T17:36:32-04:00
New Revision: d5c022d846999127352aa3c08c0f81418a942aab

URL: 
https://github.com/llvm/llvm-project/commit/d5c022d846999127352aa3c08c0f81418a942aab
DIFF: 
https://github.com/llvm/llvm-project/commit/d5c022d846999127352aa3c08c0f81418a942aab.diff

LOG: [clangd][ObjC] Support nullability annotations

Nullability annotations are implmented using attributes; previusly
clangd would skip over AttributedTypeLoc since their location
points to the attribute instead of the modified type.

Also add some test cases for this.

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

Added: 


Modified: 
clang-tools-extra/clangd/Selection.cpp
clang-tools-extra/clangd/unittests/FindTargetTests.cpp
clang-tools-extra/clangd/unittests/HoverTests.cpp
clang-tools-extra/clangd/unittests/SelectionTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/Selection.cpp 
b/clang-tools-extra/clangd/Selection.cpp
index 5c08485d8b92..fbd72be320a7 100644
--- a/clang-tools-extra/clangd/Selection.cpp
+++ b/clang-tools-extra/clangd/Selection.cpp
@@ -605,6 +605,10 @@ class SelectionVisitor : public 
RecursiveASTVisitor {
   bool canSafelySkipNode(const DynTypedNode ) {
 SourceRange S = N.getSourceRange();
 if (auto *TL = N.get()) {
+  // FIXME: TypeLoc::getBeginLoc()/getEndLoc() are pretty fragile
+  // heuristics. We should consider only pruning critical TypeLoc nodes, to
+  // be more robust.
+
   // DeclTypeTypeLoc::getSourceRange() is incomplete, which would lead to
   // failing
   // to descend into the child expression.
@@ -616,6 +620,10 @@ class SelectionVisitor : public 
RecursiveASTVisitor {
   // rid of this patch.
   if (auto DT = TL->getAs())
 S.setEnd(DT.getUnderlyingExpr()->getEndLoc());
+  // AttributedTypeLoc may point to the attribute's range, NOT the modified
+  // type's range.
+  if (auto AT = TL->getAs())
+S = AT.getModifiedLoc().getSourceRange();
 }
 if (!SelChecker.mayHit(S)) {
   dlog("{1}skip: {0}", printNodeToString(N, PrintPolicy), indent());

diff  --git a/clang-tools-extra/clangd/unittests/FindTargetTests.cpp 
b/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
index a68ea1d6a3dc..dd7e9878a6d5 100644
--- a/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
+++ b/clang-tools-extra/clangd/unittests/FindTargetTests.cpp
@@ -831,6 +831,24 @@ TEST_F(TargetDeclTest, ObjC) {
   EXPECT_DECLS("ObjCPropertyRefExpr",
"@property(atomic, retain, readwrite) I *x");
 
+  Code = R"cpp(
+@interface MYObject
+@end
+@interface Interface
+@property(retain) [[MYObject]] *x;
+@end
+  )cpp";
+  EXPECT_DECLS("ObjCInterfaceTypeLoc", "@interface MYObject");
+
+  Code = R"cpp(
+@interface MYObject2
+@end
+@interface Interface
+@property(retain, nonnull) [[MYObject2]] *x;
+@end
+  )cpp";
+  EXPECT_DECLS("ObjCInterfaceTypeLoc", "@interface MYObject2");
+
   Code = R"cpp(
 @protocol Foo
 @end

diff  --git a/clang-tools-extra/clangd/unittests/HoverTests.cpp 
b/clang-tools-extra/clangd/unittests/HoverTests.cpp
index 48c0fef45ab8..87a1b42315b3 100644
--- a/clang-tools-extra/clangd/unittests/HoverTests.cpp
+++ b/clang-tools-extra/clangd/unittests/HoverTests.cpp
@@ -1991,6 +1991,34 @@ TEST(Hover, All) {
 HI.NamespaceScope = "ObjC::"; // FIXME: fix it
 HI.Definition = "char data";
   }},
+  {
+  R"cpp(
+  @interface MYObject
+  @end
+  @interface Interface
+  @property(retain) [[MYOb^ject]] *x;
+  @end
+  )cpp",
+  [](HoverInfo ) {
+HI.Name = "MYObject";
+HI.Kind = index::SymbolKind::Class;
+HI.NamespaceScope = "";
+HI.Definition = "@interface MYObject\n@end";
+  }},
+  {
+  R"cpp(
+  @interface MYObject
+  @end
+  @interface Interface
+  - (void)doWith:([[MYOb^ject]] *)object;
+  @end
+  )cpp",
+  [](HoverInfo ) {
+HI.Name = "MYObject";
+HI.Kind = index::SymbolKind::Class;
+HI.NamespaceScope = "";
+HI.Definition = "@interface MYObject\n@end";
+  }},
   };
 
   // Create a tiny index, so tests above can verify documentation is fetched.

diff  --git a/clang-tools-extra/clangd/unittests/SelectionTests.cpp 
b/clang-tools-extra/clangd/unittests/SelectionTests.cpp
index 2026292bc6f3..55b05ebe11ab 100644
--- a/clang-tools-extra/clangd/unittests/SelectionTests.cpp
+++ b/clang-tools-extra/clangd/unittests/SelectionTests.cpp
@@ -356,6 +356,22 @@ TEST(SelectionTest, CommonAncestor) {
 )cpp",
   "DeclRefExpr"},
 
+  // Objective-C nullability attributes.
+  {
+  R"cpp(
+@interface I{}
+@property(nullable) [[^I]] *x;

[PATCH] D89332: [clang-tidy] performance-unnecessary-copy-initialization: Always allow std::function to be copied.

2020-10-20 Thread Felix Berger via Phabricator via cfe-commits
flx marked 2 inline comments as done.
flx added a comment.

Thank you all for the input!

In D89332#2336566 , @njames93 wrote:

> How does this type alias and typedef, In theory that should also be handled.
>
>   using Functor = std::function<...>;
>   Functor Copy = Orig; // No warning.

Good point. I added test cases that cover this and motivated the use of the 
`hasName()` matcher on the canonical type.

In D89332#2338319 , @njames93 wrote:

> Come to think of it, this is a pretty illogical way to solve this problem, 
> just append `::std::function` to the AllowedTypes vector in 
> `registerMatchers` and be do with it. Will require dropping the const 
> Qualifier on AllowedTypes, but aside from that it is a much simpler fix.
> The has(Any)Name matcher has logic for skipping inline namespaces.

`AllowedTypes` is currently matched using a regular expression on only the not 
fully qualified name of the NamedDecl:

https://github.com/llvm/llvm-project/blob/343410d1cc154db99b7858e0a9c3ffd86ad94e45/clang-tools-extra/clang-tidy/utils/Matchers.h#L49

This is why this approach didn't work.




Comment at: 
clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp:39-44
+AST_MATCHER(NamedDecl, isStdFunction) {
+  // First use the fast getName() method to avoid unnecessary calls to the
+  // slow getQualifiedNameAsString().
+  return Node.getName() == "function" &&
+ Node.getQualifiedNameAsString() == "std::function";
+}

aaron.ballman wrote:
> njames93 wrote:
> > It's better to use `node.isInStdNamespace()` instead of checking the 
> > qualified name as its designed for that very purpose. Is should probably 
> > take a `CXXRecordDecl` instead of a `NamedDecl` aswell.
> There's no need for this matcher -- `hasName("::std::function")` is the 
> correct way to test for this.
hasName() on the canonical type worked and handled type aliases as well.



Comment at: 
clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-copy-initialization.cpp:409
+
+namespace std {
+

njames93 wrote:
> gribozavr2 wrote:
> > flx wrote:
> > > gribozavr2 wrote:
> > > > Could you add a nested inline namespace to better imitate what 
> > > > declarations look like in libc++?
> > > I'm not sure I follow.  I looked through the other tests that declare a 
> > > std function and copied the declaration from modernize-avoid-bind.cpp.
> > libc++ declarations look like this:
> > 
> > ```
> > namespace std {
> > inline namespace __1 {
> > template<...> struct function...
> > } // __1
> > } // std
> > ```
> > 
> > The inline namespace in the middle often trips up declaration matching in 
> > checkers. And yes, many other tests don't imitate this pattern, and are 
> > often broken with libc++. Those tests should be improved.
> @flx Thats the reason why its advisable to use `Decl::isInStdNamespace` as it 
> will handle inline namespaces.
Thanks for the extra explanation and sample code. This is done now and works.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89332

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


[PATCH] D89332: [clang-tidy] performance-unnecessary-copy-initialization: Always allow std::function to be copied.

2020-10-20 Thread Felix Berger via Phabricator via cfe-commits
flx updated this revision to Diff 299471.
flx added a comment.

Use hasName matcher on the declaration of the canonical type.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89332

Files:
  clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp
  
clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-copy-initialization.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-copy-initialization.cpp
===
--- 
clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-copy-initialization.cpp
+++ 
clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-copy-initialization.cpp
@@ -405,3 +405,41 @@
   ExpensiveToCopyType Orig;
   const ExpensiveToCopyType Copy = freeFunctionWithDefaultArg();
 }
+
+namespace std {
+inline namespace __1 {
+
+template 
+class function;
+template 
+class function {
+public:
+  function();
+  function(const function );
+  R operator()(Args &&...args) const;
+};
+
+} // namespace __1
+} // namespace std
+
+void negativeStdFunction() {
+  std::function Orig;
+  std::function Copy = Orig;
+  int i = Orig();
+}
+
+using Functor = std::function;
+
+void negativeAliasedStdFunction() {
+  Functor Orig;
+  Functor Copy = Orig;
+  int i = Orig();
+}
+
+typedef std::function TypedefFunc;
+
+void negativeTypedefedStdFunction() {
+  TypedefFunc Orig;
+  TypedefFunc Copy = Orig;
+  int i = Orig();
+}
Index: 
clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp
===
--- clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp
+++ clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp
@@ -40,7 +40,8 @@
   AllowedTypes(
   utils::options::parseStringList(Options.get("AllowedTypes", ""))) {}
 
-void UnnecessaryCopyInitialization::registerMatchers(MatchFinder *Finder) {
+void UnnecessaryCopyInitialization::registerMatchers(
+internal::MatchFinder *Finder) {
   auto ConstReference = referenceType(pointee(qualType(isConstQualified(;
 
   // Match method call expressions where the `this` argument is only used as
@@ -57,17 +58,20 @@
unless(callee(cxxMethodDecl(
   .bind("initFunctionCall");
 
-  auto localVarCopiedFrom = [this](const internal::Matcher ) 
{
+  auto localVarCopiedFrom = [this](const Matcher ) {
 return compoundStmt(
forEachDescendant(
declStmt(
has(varDecl(hasLocalStorage(),
hasType(qualType(
-   hasCanonicalType(
-   matchers::isExpensiveToCopy()),
+   hasCanonicalType(allOf(
+   matchers::isExpensiveToCopy(),
+   unless(hasDeclaration(namedDecl(
+   hasName("::std::function")),
unless(hasDeclaration(namedDecl(
-   matchers::matchesAnyListedName(
-   AllowedTypes)),
+   
anyOf(matchers::matchesAnyListedName(
+ AllowedTypes),
+ isStdFunction())),
unless(isImplicit()),
hasInitializer(traverse(
ast_type_traits::TK_AsIs,


Index: clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-copy-initialization.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-copy-initialization.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/performance-unnecessary-copy-initialization.cpp
@@ -405,3 +405,41 @@
   ExpensiveToCopyType Orig;
   const ExpensiveToCopyType Copy = freeFunctionWithDefaultArg();
 }
+
+namespace std {
+inline namespace __1 {
+
+template 
+class function;
+template 
+class function {
+public:
+  function();
+  function(const function );
+  R operator()(Args &&...args) const;
+};
+
+} // namespace __1
+} // namespace std
+
+void negativeStdFunction() {
+  std::function Orig;
+  std::function Copy = Orig;
+  int i = Orig();
+}
+
+using Functor = std::function;
+
+void negativeAliasedStdFunction() {
+  Functor Orig;
+  Functor Copy = Orig;
+  int i = Orig();
+}
+
+typedef std::function TypedefFunc;
+
+void negativeTypedefedStdFunction() {
+  TypedefFunc Orig;
+  TypedefFunc Copy = Orig;
+  int i = Orig();
+}
Index: clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp

[PATCH] D89765: [LibTooling][Clang-cast] A Clang LibTool to convert C-style casts to C++ style casts and more.

2020-10-20 Thread Ray Zhang via Phabricator via cfe-commits
oneraynyday updated this revision to Diff 299470.
oneraynyday added a comment.

- Address clang-tidy
- Address using C++17 left-fold expression in C++14
- Address minor style issues


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89765

Files:
  clang-tools-extra/CMakeLists.txt
  clang-tools-extra/clang-cast/CMakeLists.txt
  clang-tools-extra/clang-cast/Cast.h
  clang-tools-extra/clang-cast/CastOptions.h
  clang-tools-extra/clang-cast/CastUtils.h
  clang-tools-extra/clang-cast/ClangCast.cpp
  clang-tools-extra/clang-cast/Consumer.h
  clang-tools-extra/clang-cast/Matcher.h
  clang-tools-extra/unittests/CMakeLists.txt
  clang-tools-extra/unittests/clang-cast/CMakeLists.txt
  clang-tools-extra/unittests/clang-cast/ClangCXXCastTestCases.h
  clang-tools-extra/unittests/clang-cast/ClangCastTests.cpp
  clang-tools-extra/unittests/clang-cast/ClangChangeQualifierTestCases.h
  clang-tools-extra/unittests/clang-cast/ClangFunctionPtrTestCases.h
  clang-tools-extra/unittests/clang-cast/ClangQualifierTestCases.h

Index: clang-tools-extra/unittests/clang-cast/ClangQualifierTestCases.h
===
--- /dev/null
+++ clang-tools-extra/unittests/clang-cast/ClangQualifierTestCases.h
@@ -0,0 +1,603 @@
+//===-- ClangQualifierTestCases.h - clang-cast --*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+///
+/// \file
+/// This file contains test cases for
+/// CStyleCastOperation::requireConstCast (defined in Cast.h)
+///
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_UNITTESTS_CLANG_CAST_CLANGQUALIFIERTESTCASES_H
+#define LLVM_CLANG_TOOLS_EXTRA_UNITTESTS_CLANG_CAST_CLANGQUALIFIERTESTCASES_H
+
+namespace testcases {
+
+namespace constcheck {
+/// No-op
+static const char QualNoOp[] = R"(
+void f() {
+  (bool) 0;
+}
+)";
+
+/// Const
+/// Adding const doesn't require const_cast
+static const char QualAddConst[] = R"(
+void f() {
+  int x = 0;
+  (const int) x;
+}
+)";
+static const char QualAddPtrToConst[] = R"(
+void f() {
+  int* x = nullptr;
+  const int* y = (const int*) x;
+}
+)";
+static const char QualAddConstPtr[] = R"(
+void f() {
+  int* x = nullptr;
+  int* const y = (int* const) x;
+}
+)";
+static const char QualAddConstDoublePtr[] = R"(
+void f() {
+  int** x = nullptr;
+  int* const * const y = (int* const * const) x;
+}
+)";
+static const char QualAddConstDiffLevelPtr[] = R"(
+void f() {
+  int*** x = nullptr;
+  const int** y = (const int**) x;
+}
+)";
+static const char QualAddMemberPtrToConst[] = R"(
+struct t{};
+void f() {
+  int t::* x = nullptr;
+  const int t::* y = (const int t::*) x;
+}
+)";
+static const char QualAddConstMemberPtr[] = R"(
+struct t{};
+void f() {
+  int t::* x = nullptr;
+  int t::* const y = (int t::* const) x;
+}
+)";
+static const char QualAddConstDoubleMemberPtr[] = R"(
+struct t{};
+void f() {
+  int t::* t::* x = nullptr;
+  int t::* const t::* const y = (int t::* const t::* const) x;
+}
+)";
+static const char QualAddConstDiffLevelMemberPtr[] = R"(
+struct t{};
+void f() {
+  int t::* t::* t::* x = nullptr;
+  const int t::* t::* y = (const int t::* t::*) x;
+}
+)";
+static const char QualAddConstRef[] = R"(
+void f() {
+  int x = 1;
+  int& y = x;
+  const int& z = (const int&) y;
+}
+)";
+static const char QualAddConstArr[] = R"(
+void f() {
+  double a[2] {1, 2};
+  const double* ca = (const double*) a;
+}
+)";
+static const char QualAddConstPtrToArr[] = R"(
+void f() {
+  double (*a)[2] {};
+  (double(* const)[2]) a;
+}
+)";
+static const char QualAddConstPtrToArrOfConstPtrs[] = R"(
+void f() {
+  double* (*a)[2] {};
+  (double * const (* const)[2]) a;
+}
+)";
+static const char QualAddArrPtrConstData[] = R"(
+void f() {
+  double (*a)[2] {};
+  (const double(*)[2]) a;
+}
+)";
+static const char QualAddDiffLevelArrPtrConstData[] = R"(
+void f() {
+  double (*a)[2] {};
+  (const double* (*)[2]) a;
+}
+)";
+static const char QualAddConstMixedPtrTypes[] = R"(
+struct t {};
+void f() {
+  double * t::* (t::* *a) [2];
+  (const double * const t::* const (t::* const * const) [2]) a;
+}
+)";
+static const char QualAddConstUnknownArrPtr[] = R"(
+void f() {
+  int* (*x) [] {};
+  (const int* const (*)[]) x;
+}
+)";
+static const char QualAddConstUnknownArrPtrToKnownArrPtr[] = R"(
+void f() {
+  int* (*x) [] {};
+  (const int* const (*)[2]) x;
+}
+)";
+
+/// Removing const MIGHT require const_cast
+static const char QualRemoveConst[] = R"(
+void f() {
+  const int x = 0;
+  (int) x;
+}
+)";
+static const char QualRemovePtrToConst[] = R"(
+void f() {
+  const int* x = nullptr;
+  int* y = (int*) x;
+}
+)";

[PATCH] D89429: clang/Basic: Replace SourceManager::getMemoryBufferForFile, NFC

2020-10-20 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG2dc7e0c6a586: clang/Basic: Replace 
SourceManager::getMemoryBufferForFile, NFC (authored by dexonsmith).
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89429

Files:
  clang/include/clang/Basic/SourceManager.h
  clang/include/clang/Frontend/PrecompiledPreamble.h
  clang/lib/Basic/SourceManager.cpp
  clang/lib/Frontend/PrecompiledPreamble.cpp
  clang/lib/Lex/Preprocessor.cpp

Index: clang/lib/Lex/Preprocessor.cpp
===
--- clang/lib/Lex/Preprocessor.cpp
+++ clang/lib/Lex/Preprocessor.cpp
@@ -395,12 +395,10 @@
   assert(CompleteLine && CompleteColumn && "Starts from 1:1");
   assert(!CodeCompletionFile && "Already set");
 
-  using llvm::MemoryBuffer;
-
   // Load the actual file's contents.
-  bool Invalid = false;
-  const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, );
-  if (Invalid)
+  Optional Buffer =
+  SourceMgr.getMemoryBufferForFileOrNone(File);
+  if (!Buffer)
 return true;
 
   // Find the byte position of the truncation point.
Index: clang/lib/Frontend/PrecompiledPreamble.cpp
===
--- clang/lib/Frontend/PrecompiledPreamble.cpp
+++ clang/lib/Frontend/PrecompiledPreamble.cpp
@@ -463,7 +463,8 @@
   PrecompiledPreamble::PreambleFileHash::createForFile(File->getSize(),
ModTime);
 } else {
-  const llvm::MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File);
+  llvm::MemoryBufferRef Buffer =
+  SourceMgr.getMemoryBufferForFileOrFake(File);
   FilesInPreamble[File->getName()] =
   PrecompiledPreamble::PreambleFileHash::createForMemoryBuffer(Buffer);
 }
@@ -549,7 +550,7 @@
   llvm::StringMap OverridenFileBuffers;
   for (const auto  : PreprocessorOpts.RemappedFileBuffers) {
 const PrecompiledPreamble::PreambleFileHash PreambleHash =
-PreambleFileHash::createForMemoryBuffer(RB.second);
+PreambleFileHash::createForMemoryBuffer(RB.second->getMemBufferRef());
 llvm::vfs::Status Status;
 if (moveOnNoError(VFS->status(RB.first), Status))
   OverriddenFiles[Status.getUniqueID()] = PreambleHash;
@@ -783,13 +784,13 @@
 
 PrecompiledPreamble::PreambleFileHash
 PrecompiledPreamble::PreambleFileHash::createForMemoryBuffer(
-const llvm::MemoryBuffer *Buffer) {
+const llvm::MemoryBufferRef ) {
   PreambleFileHash Result;
-  Result.Size = Buffer->getBufferSize();
+  Result.Size = Buffer.getBufferSize();
   Result.ModTime = 0;
 
   llvm::MD5 MD5Ctx;
-  MD5Ctx.update(Buffer->getBuffer().data());
+  MD5Ctx.update(Buffer.getBuffer().data());
   MD5Ctx.final(Result.MD5);
 
   return Result;
Index: clang/lib/Basic/SourceManager.cpp
===
--- clang/lib/Basic/SourceManager.cpp
+++ clang/lib/Basic/SourceManager.cpp
@@ -701,14 +701,11 @@
   return SourceLocation::getMacroLoc(NextLocalOffset - (TokLength + 1));
 }
 
-const llvm::MemoryBuffer *
-SourceManager::getMemoryBufferForFile(const FileEntry *File, bool *Invalid) {
+llvm::Optional
+SourceManager::getMemoryBufferForFileOrNone(const FileEntry *File) {
   const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
   assert(IR && "getOrCreateContentCache() cannot return NULL");
-  auto *B = IR->getBufferPointer(Diag, getFileManager(), SourceLocation());
-  if (Invalid)
-*Invalid = !B;
-  return B ? B : getFakeBufferForRecovery();
+  return IR->getBufferOrNone(Diag, getFileManager(), SourceLocation());
 }
 
 void SourceManager::overrideFileContents(const FileEntry *SourceFile,
Index: clang/include/clang/Frontend/PrecompiledPreamble.h
===
--- clang/include/clang/Frontend/PrecompiledPreamble.h
+++ clang/include/clang/Frontend/PrecompiledPreamble.h
@@ -26,6 +26,7 @@
 
 namespace llvm {
 class MemoryBuffer;
+class MemoryBufferRef;
 namespace vfs {
 class FileSystem;
 }
@@ -216,7 +217,7 @@
 
 static PreambleFileHash createForFile(off_t Size, time_t ModTime);
 static PreambleFileHash
-createForMemoryBuffer(const llvm::MemoryBuffer *Buffer);
+createForMemoryBuffer(const llvm::MemoryBufferRef );
 
 friend bool operator==(const PreambleFileHash ,
const PreambleFileHash ) {
Index: clang/include/clang/Basic/SourceManager.h
===
--- clang/include/clang/Basic/SourceManager.h
+++ clang/include/clang/Basic/SourceManager.h
@@ -901,10 +901,18 @@
 
   /// Retrieve the memory buffer associated with the given file.
   ///
-  /// \param Invalid If non-NULL, will be set \c true if an error
-  /// occurs while retrieving the memory buffer.
-  const 

[clang] 2dc7e0c - clang/Basic: Replace SourceManager::getMemoryBufferForFile, NFC

2020-10-20 Thread Duncan P . N . Exon Smith via cfe-commits

Author: Duncan P. N. Exon Smith
Date: 2020-10-20T17:01:23-04:00
New Revision: 2dc7e0c6a586135fe236cd7ebf065617a7638bdb

URL: 
https://github.com/llvm/llvm-project/commit/2dc7e0c6a586135fe236cd7ebf065617a7638bdb
DIFF: 
https://github.com/llvm/llvm-project/commit/2dc7e0c6a586135fe236cd7ebf065617a7638bdb.diff

LOG: clang/Basic: Replace SourceManager::getMemoryBufferForFile, NFC

Replace `SourceManager::getMemoryBufferForFile`, which returned a
dereferenceable `MemoryBuffer*` and had a `bool*Invalid` out parameter,
with `getMemoryBufferForFileOrNone` (returning
`Optional`) and `getMemoryBufferForFileOrFake`
(returning `MemoryBufferRef`).

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

Added: 


Modified: 
clang/include/clang/Basic/SourceManager.h
clang/include/clang/Frontend/PrecompiledPreamble.h
clang/lib/Basic/SourceManager.cpp
clang/lib/Frontend/PrecompiledPreamble.cpp
clang/lib/Lex/Preprocessor.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/SourceManager.h 
b/clang/include/clang/Basic/SourceManager.h
index e1b510bab07c..905b706971d5 100644
--- a/clang/include/clang/Basic/SourceManager.h
+++ b/clang/include/clang/Basic/SourceManager.h
@@ -901,10 +901,18 @@ class SourceManager : public 
RefCountedBase {
 
   /// Retrieve the memory buffer associated with the given file.
   ///
-  /// \param Invalid If non-NULL, will be set \c true if an error
-  /// occurs while retrieving the memory buffer.
-  const llvm::MemoryBuffer *getMemoryBufferForFile(const FileEntry *File,
-   bool *Invalid = nullptr);
+  /// Returns None if the buffer is not valid.
+  llvm::Optional
+  getMemoryBufferForFileOrNone(const FileEntry *File);
+
+  /// Retrieve the memory buffer associated with the given file.
+  ///
+  /// Returns a fake buffer if there isn't a real one.
+  llvm::MemoryBufferRef getMemoryBufferForFileOrFake(const FileEntry *File) {
+if (auto B = getMemoryBufferForFileOrNone(File))
+  return *B;
+return getFakeBufferForRecovery()->getMemBufferRef();
+  }
 
   /// Override the contents of the given source file by providing an
   /// already-allocated buffer.

diff  --git a/clang/include/clang/Frontend/PrecompiledPreamble.h 
b/clang/include/clang/Frontend/PrecompiledPreamble.h
index 0f7e9d895a00..99faf60f1a44 100644
--- a/clang/include/clang/Frontend/PrecompiledPreamble.h
+++ b/clang/include/clang/Frontend/PrecompiledPreamble.h
@@ -26,6 +26,7 @@
 
 namespace llvm {
 class MemoryBuffer;
+class MemoryBufferRef;
 namespace vfs {
 class FileSystem;
 }
@@ -216,7 +217,7 @@ class PrecompiledPreamble {
 
 static PreambleFileHash createForFile(off_t Size, time_t ModTime);
 static PreambleFileHash
-createForMemoryBuffer(const llvm::MemoryBuffer *Buffer);
+createForMemoryBuffer(const llvm::MemoryBufferRef );
 
 friend bool operator==(const PreambleFileHash ,
const PreambleFileHash ) {

diff  --git a/clang/lib/Basic/SourceManager.cpp 
b/clang/lib/Basic/SourceManager.cpp
index 9902709c4e63..51772d5aa335 100644
--- a/clang/lib/Basic/SourceManager.cpp
+++ b/clang/lib/Basic/SourceManager.cpp
@@ -701,14 +701,11 @@ SourceManager::createExpansionLocImpl(const ExpansionInfo 
,
   return SourceLocation::getMacroLoc(NextLocalOffset - (TokLength + 1));
 }
 
-const llvm::MemoryBuffer *
-SourceManager::getMemoryBufferForFile(const FileEntry *File, bool *Invalid) {
+llvm::Optional
+SourceManager::getMemoryBufferForFileOrNone(const FileEntry *File) {
   const SrcMgr::ContentCache *IR = getOrCreateContentCache(File);
   assert(IR && "getOrCreateContentCache() cannot return NULL");
-  auto *B = IR->getBufferPointer(Diag, getFileManager(), SourceLocation());
-  if (Invalid)
-*Invalid = !B;
-  return B ? B : getFakeBufferForRecovery();
+  return IR->getBufferOrNone(Diag, getFileManager(), SourceLocation());
 }
 
 void SourceManager::overrideFileContents(const FileEntry *SourceFile,

diff  --git a/clang/lib/Frontend/PrecompiledPreamble.cpp 
b/clang/lib/Frontend/PrecompiledPreamble.cpp
index 3fb61f37ae2b..87cd9169c78c 100644
--- a/clang/lib/Frontend/PrecompiledPreamble.cpp
+++ b/clang/lib/Frontend/PrecompiledPreamble.cpp
@@ -463,7 +463,8 @@ llvm::ErrorOr 
PrecompiledPreamble::Build(
   PrecompiledPreamble::PreambleFileHash::createForFile(File->getSize(),
ModTime);
 } else {
-  const llvm::MemoryBuffer *Buffer = 
SourceMgr.getMemoryBufferForFile(File);
+  llvm::MemoryBufferRef Buffer =
+  SourceMgr.getMemoryBufferForFileOrFake(File);
   FilesInPreamble[File->getName()] =
   PrecompiledPreamble::PreambleFileHash::createForMemoryBuffer(Buffer);
 }
@@ -549,7 +550,7 @@ bool PrecompiledPreamble::CanReuse(const CompilerInvocation 
,
   llvm::StringMap OverridenFileBuffers;
   for (const auto  : 

[PATCH] D83088: Introduce CfgTraits abstraction

2020-10-20 Thread David Blaikie via Phabricator via cfe-commits
dblaikie reopened this revision.
dblaikie added a comment.
This revision is now accepted and ready to land.

Sorry about the delays in review - but please revert this patch until we can 
hash out a few more details. I really don't think this is the best direction 
forward for a core abstraction & I'll do my best to explain why & try to 
understand where you're coming from.

In D83088#2232893 , @nhaehnle wrote:

> The most immediate problem is divergence analysis, which is extremely 
> complex and difficult to get right. If I had tried to fight the 
> accidental complexity that comes with attempting to write such an 
> algorithm as C++ templates in addition to the inherent complexity of the 
> algorithm at the same time, I'm not sure I would have been able to 
> produce anything workable at all.
>
> Frankly, I suspect that our dominator tree implementation also suffer 
> because of this, though at least dominator trees are much more well 
> studied in the academic literature, so that helps keep the inherent 
> complexity under control.

 I'm totally open to discussing making APIs more usable, for sure - though 
 I'm thinking it's likely a concept (like containers in the C++ standard 
 library) might be the better direction.

 Perhaps some code samples showing how one would interact (probably not 
 whole algorithms - maybe something simple like generating a dot diagram 
 for a graph) with these things given different APIs (traits, concepts, and 
 runtime polymorphism) - and implementations of each kind too.
>>>
>>> Take a look here for example: 
>>> https://github.com/nhaehnle/llvm-project/blob/715450fa7f968ceefaf9c3b04b47066866c97206/llvm/lib/Analysis/GenericConvergenceUtils.cpp#L499
>>>  -- this is obviously still fairly simple, but it's an example of printing 
>>> out the results of an analysis in a way that's generic over the underlying 
>>> CFG and SSA form.
>>
>> I'm having trouble following this example - I'm not sure what the CfgPrinter 
>> abstraction is/why it's first-class, and why this "print" function is 
>> calling what look like mutation operations like "appendBlocks". I guess 
>> perhaps the question is - what's it printing from and what's it printing to?
>>
>> Ah, I see, the "append" functions are accessors, of a sort. Returning a 
>> container might be more clear than using an out parameter - alternatively, a 
>> functor parameter (ala std::for_each) that is called for each element, that 
>> can then be used to populate an existing container if desired, or to do 
>> immediate processing without the need for an intermediate container.
>
> The code is trying to strike a balance here in terms of performance. Since 
> dynamic polymorphism is used, a functor-based traversal can't be inlined and 
> so the number of indirect function calls increases quite a bit. There are a 
> number of use cases where you really do want to just append successors or 
> predecessors to a vectors, like during a graph traversal. An example graph 
> traversal is here: 
> https://github.com/nhaehnle/llvm-project/blob/controlflow-wip-v7/llvm/lib/Analysis/GenericConvergenceUtils.cpp#L329

One way to simplify the dynamic polymorphism overhead of iteration would be to 
invert/limit the API - such as having a "node.forEachEdge([](const Edge& E) { 
... });" or the like.

>> Though the printer abstraction still strikes me as a bit strange - 
>> especially since it doesn't seem to be printing itself. This function was 
>> passed a printer and a stream - the printer prints to the stream (perhaps 
>> it'd make more sense for the printer to take the stream on construction) and 
>> the function isn't passed the thing to print at all - that thing is accessed 
>> from the printer. That seems fairly awkward to me - I'd expect a printing 
>> operation to take a thing to be printed and a thing to print to.
>
> Keep in mind that where those `printBlockName` / `printValue` methods are 
> used, they will always be mixed in with printing of other things. So the 
> alternative you're describing would result in code like:
>
>   dbgs() << " currently at: ";  // explicit stream
>   printer.printBlockName(block); // implicit stream
>   dbgs() << '\n'; // explicit stream
>
> I would argue that that ends up being more awkward because it mixes implicit 
> streams with explicitly given streams.
>
> We could perhaps add versions of the methods that return a `Printable` 
> object, so that we can write:
>
>   dbgs() << "currently at: " << printer.printableBlockName(block) << '\n';
>
> By the way, the main motivation for making the CfgPrinter a separate object 
> is that printing LLVM IR efficiently requires keeping a ModuleSlotTracker 
> around. Splitting the CfgPrinter off from the CfgInterface allows the 
> fast-path of code that doesn't want debug prints to not have to carry a 
> reference to a ModuleSlotTracker around, even if 

[PATCH] D89573: [Driver] Incorporate -mfloat-abi in the computed triple on ARM

2020-10-20 Thread Eli Friedman via Phabricator via cfe-commits
efriedma accepted this revision.
efriedma added a comment.
This revision is now accepted and ready to land.

LGTM


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

https://reviews.llvm.org/D89573

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


[PATCH] D89765: [LibTooling][Clang-cast] A Clang LibTool to convert C-style casts to C++ style casts and more.

2020-10-20 Thread Ray Zhang via Phabricator via cfe-commits
oneraynyday added a comment.

In D89765#2342624 , @awarzynski wrote:

> 



> - Have you considered sending an RFC to cfe-dev regarding this tool?  I think 
> that it would be a great way of attracting peoples attention. More 
> importantly, should we add another tool to clang-tools-extra?

Hi @awarzynski, thank you so much for taking a look! I was considering sending 
an RFC but haven't gotten around to it yet. Funny enough, how I started the 
development on this tool was because of this page: 
https://clang.llvm.org/docs/ClangTools.html which encourages newcomers to clang 
to create new tools. Specifically this line:

> C++ cast conversion tool. Will convert C-style casts ((type) value) to 
> appropriate C++ cast (static_cast, const_cast or reinterpret_cast).

I did exactly this project(was much bigger of an undertaking than I had first 
imagined) and was hoping to contribute back, assuming that everyone would be 
fairly receptive to having an extra tool that helps the community :) In 
retrospect, I do realize that this could be a feature in clang-tidy and I noted 
in the `NOTES` section that I can contribute a subset of the functionalities 
into clang-tidy as well.

> - [This] is a rather large patch - could you split it into separate chunks? 
> Otherwise it's quite tricky to review.

Of course, I'd be glad to make the review experience better for you. How do you 
want me to split it into chunks? I had the following in mind:

- First patch: `CStyleCastOperator` class in Cast.h (with all the unit tests)
- Second patch: Creating the minimal matcher, consumer, action and necessary 
CLI options
- Third patch: Adding in the matcher implementation which emits diagnostics.

Let me know what you think.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89765

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


[clang] 27a909a - [Apple-stage2] Install FileCheck and yaml2obj in the toolchain

2020-10-20 Thread Jonas Devlieghere via cfe-commits

Author: Jonas Devlieghere
Date: 2020-10-20T13:46:44-07:00
New Revision: 27a909a24f99d4de40c4ce6553b9cd420b11c056

URL: 
https://github.com/llvm/llvm-project/commit/27a909a24f99d4de40c4ce6553b9cd420b11c056
DIFF: 
https://github.com/llvm/llvm-project/commit/27a909a24f99d4de40c4ce6553b9cd420b11c056.diff

LOG: [Apple-stage2] Install FileCheck and yaml2obj in the toolchain

rdar://70274446

Differential revision: https://reviews.llvm.org/D89763

Added: 


Modified: 
clang/cmake/caches/Apple-stage2.cmake

Removed: 




diff  --git a/clang/cmake/caches/Apple-stage2.cmake 
b/clang/cmake/caches/Apple-stage2.cmake
index b24ec558c071..ff9c612b9808 100644
--- a/clang/cmake/caches/Apple-stage2.cmake
+++ b/clang/cmake/caches/Apple-stage2.cmake
@@ -58,6 +58,13 @@ set(LLVM_TOOLCHAIN_TOOLS
   llvm-size
   CACHE STRING "")
 
+set(LLVM_BUILD_UTILS ON CACHE BOOL "")
+set(LLVM_INSTALL_UTILS ON CACHE BOOL "")
+set(LLVM_TOOLCHAIN_UTILITIES
+  FileCheck
+  yaml2obj
+  CACHE STRING "")
+
 set(LLVM_DISTRIBUTION_COMPONENTS
   clang
   LTO
@@ -66,6 +73,7 @@ set(LLVM_DISTRIBUTION_COMPONENTS
   cxx-headers
   Remarks
   ${LLVM_TOOLCHAIN_TOOLS}
+  ${LLVM_TOOLCHAIN_UTILITIES}
   CACHE STRING "")
 
 # test args



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


[PATCH] D89763: [Apple-stage2] Install FileCheck and yaml2obj in the toolchain

2020-10-20 Thread Jonas Devlieghere via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG27a909a24f99: [Apple-stage2] Install FileCheck and yaml2obj 
in the toolchain (authored by JDevlieghere).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D89763?vs=299370=299460#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89763

Files:
  clang/cmake/caches/Apple-stage2.cmake


Index: clang/cmake/caches/Apple-stage2.cmake
===
--- clang/cmake/caches/Apple-stage2.cmake
+++ clang/cmake/caches/Apple-stage2.cmake
@@ -58,6 +58,13 @@
   llvm-size
   CACHE STRING "")
 
+set(LLVM_BUILD_UTILS ON CACHE BOOL "")
+set(LLVM_INSTALL_UTILS ON CACHE BOOL "")
+set(LLVM_TOOLCHAIN_UTILITIES
+  FileCheck
+  yaml2obj
+  CACHE STRING "")
+
 set(LLVM_DISTRIBUTION_COMPONENTS
   clang
   LTO
@@ -66,6 +73,7 @@
   cxx-headers
   Remarks
   ${LLVM_TOOLCHAIN_TOOLS}
+  ${LLVM_TOOLCHAIN_UTILITIES}
   CACHE STRING "")
 
 # test args


Index: clang/cmake/caches/Apple-stage2.cmake
===
--- clang/cmake/caches/Apple-stage2.cmake
+++ clang/cmake/caches/Apple-stage2.cmake
@@ -58,6 +58,13 @@
   llvm-size
   CACHE STRING "")
 
+set(LLVM_BUILD_UTILS ON CACHE BOOL "")
+set(LLVM_INSTALL_UTILS ON CACHE BOOL "")
+set(LLVM_TOOLCHAIN_UTILITIES
+  FileCheck
+  yaml2obj
+  CACHE STRING "")
+
 set(LLVM_DISTRIBUTION_COMPONENTS
   clang
   LTO
@@ -66,6 +73,7 @@
   cxx-headers
   Remarks
   ${LLVM_TOOLCHAIN_TOOLS}
+  ${LLVM_TOOLCHAIN_UTILITIES}
   CACHE STRING "")
 
 # test args
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D89766: Driver: Add integer sanitizers to trapping group automatically.

2020-10-20 Thread Peter Collingbourne via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGc5acd3490b79: Driver: Add integer sanitizers to trapping 
group automatically. (authored by pcc).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89766

Files:
  clang/lib/Driver/SanitizerArgs.cpp
  clang/test/Driver/fsanitize.c


Index: clang/test/Driver/fsanitize.c
===
--- clang/test/Driver/fsanitize.c
+++ clang/test/Driver/fsanitize.c
@@ -786,6 +786,13 @@
 // CHECK-UBSAN-MINIMAL: 
"-fsanitize={{((signed-integer-overflow|integer-divide-by-zero|shift-base|shift-exponent|unreachable|return|vla-bound|alignment|null|pointer-overflow|float-cast-overflow|array-bounds|enum|bool|builtin|returns-nonnull-attribute|nonnull-attribute),?){17}"}}
 // CHECK-UBSAN-MINIMAL: "-fsanitize-minimal-runtime"
 
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=integer 
-fsanitize-trap=integer %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-INTSAN-TRAP
+// CHECK-INTSAN-TRAP: 
"-fsanitize-trap=integer-divide-by-zero,shift-base,shift-exponent,signed-integer-overflow,unsigned-integer-overflow,unsigned-shift-base,implicit-unsigned-integer-truncation,implicit-signed-integer-truncation,implicit-integer-sign-change"
+
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=integer 
-fsanitize-minimal-runtime %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-INTSAN-MINIMAL
+// CHECK-INTSAN-MINIMAL: 
"-fsanitize=integer-divide-by-zero,shift-base,shift-exponent,signed-integer-overflow,unsigned-integer-overflow,unsigned-shift-base,implicit-unsigned-integer-truncation,implicit-signed-integer-truncation,implicit-integer-sign-change"
+// CHECK-INTSAN-MINIMAL: "-fsanitize-minimal-runtime"
+
 // RUN: %clang -target aarch64-linux-android -march=armv8-a+memtag 
-fsanitize=memtag -fsanitize-minimal-runtime %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-MEMTAG-MINIMAL
 // CHECK-MEMTAG-MINIMAL: "-fsanitize=memtag"
 // CHECK-MEMTAG-MINIMAL: "-fsanitize-minimal-runtime"
Index: clang/lib/Driver/SanitizerArgs.cpp
===
--- clang/lib/Driver/SanitizerArgs.cpp
+++ clang/lib/Driver/SanitizerArgs.cpp
@@ -60,8 +60,7 @@
 SanitizerKind::KernelAddress | SanitizerKind::KernelHWAddress;
 static const SanitizerMask NeedsLTO = SanitizerKind::CFI;
 static const SanitizerMask TrappingSupported =
-(SanitizerKind::Undefined & ~SanitizerKind::Vptr) |
-SanitizerKind::UnsignedIntegerOverflow | SanitizerKind::ImplicitConversion 
|
+(SanitizerKind::Undefined & ~SanitizerKind::Vptr) | SanitizerKind::Integer 
|
 SanitizerKind::Nullability | SanitizerKind::LocalBounds |
 SanitizerKind::CFI | SanitizerKind::FloatDivideByZero |
 SanitizerKind::ObjCCast;


Index: clang/test/Driver/fsanitize.c
===
--- clang/test/Driver/fsanitize.c
+++ clang/test/Driver/fsanitize.c
@@ -786,6 +786,13 @@
 // CHECK-UBSAN-MINIMAL: "-fsanitize={{((signed-integer-overflow|integer-divide-by-zero|shift-base|shift-exponent|unreachable|return|vla-bound|alignment|null|pointer-overflow|float-cast-overflow|array-bounds|enum|bool|builtin|returns-nonnull-attribute|nonnull-attribute),?){17}"}}
 // CHECK-UBSAN-MINIMAL: "-fsanitize-minimal-runtime"
 
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=integer -fsanitize-trap=integer %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-INTSAN-TRAP
+// CHECK-INTSAN-TRAP: "-fsanitize-trap=integer-divide-by-zero,shift-base,shift-exponent,signed-integer-overflow,unsigned-integer-overflow,unsigned-shift-base,implicit-unsigned-integer-truncation,implicit-signed-integer-truncation,implicit-integer-sign-change"
+
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=integer -fsanitize-minimal-runtime %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-INTSAN-MINIMAL
+// CHECK-INTSAN-MINIMAL: "-fsanitize=integer-divide-by-zero,shift-base,shift-exponent,signed-integer-overflow,unsigned-integer-overflow,unsigned-shift-base,implicit-unsigned-integer-truncation,implicit-signed-integer-truncation,implicit-integer-sign-change"
+// CHECK-INTSAN-MINIMAL: "-fsanitize-minimal-runtime"
+
 // RUN: %clang -target aarch64-linux-android -march=armv8-a+memtag -fsanitize=memtag -fsanitize-minimal-runtime %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-MEMTAG-MINIMAL
 // CHECK-MEMTAG-MINIMAL: "-fsanitize=memtag"
 // CHECK-MEMTAG-MINIMAL: "-fsanitize-minimal-runtime"
Index: clang/lib/Driver/SanitizerArgs.cpp
===
--- clang/lib/Driver/SanitizerArgs.cpp
+++ clang/lib/Driver/SanitizerArgs.cpp
@@ -60,8 +60,7 @@
 SanitizerKind::KernelAddress | SanitizerKind::KernelHWAddress;
 static const SanitizerMask NeedsLTO = SanitizerKind::CFI;
 static const SanitizerMask TrappingSupported =
-

[clang] c5acd34 - Driver: Add integer sanitizers to trapping group automatically.

2020-10-20 Thread Peter Collingbourne via cfe-commits

Author: Peter Collingbourne
Date: 2020-10-20T13:45:39-07:00
New Revision: c5acd3490b79703426931f7b88b544fe7c6e1ef2

URL: 
https://github.com/llvm/llvm-project/commit/c5acd3490b79703426931f7b88b544fe7c6e1ef2
DIFF: 
https://github.com/llvm/llvm-project/commit/c5acd3490b79703426931f7b88b544fe7c6e1ef2.diff

LOG: Driver: Add integer sanitizers to trapping group automatically.

In D86000 we added a new sanitizer to the integer group
without adding it to the trapping group. This broke usage of
-fsanitize=integer -fsanitize-trap=integer or -fsanitize=integer
-fsanitize-minimal-runtime.

I think we can reasonably expect any new integer sanitizers to be
compatible with trapping and the minimal runtime, so add them to the
trapping group automatically.

Also add a test to ensure that any future additions of sanitizers
to the integer group will most likely result in test failures which
would lead to updates to the minimal runtime if necessary. For this
particular sanitizer no updates are required because it uses the
existing shift_out_of_bounds callback function.

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

Added: 


Modified: 
clang/lib/Driver/SanitizerArgs.cpp
clang/test/Driver/fsanitize.c

Removed: 




diff  --git a/clang/lib/Driver/SanitizerArgs.cpp 
b/clang/lib/Driver/SanitizerArgs.cpp
index 90dbced3240d..68ae25e9cc20 100644
--- a/clang/lib/Driver/SanitizerArgs.cpp
+++ b/clang/lib/Driver/SanitizerArgs.cpp
@@ -60,8 +60,7 @@ static const SanitizerMask AlwaysRecoverable =
 SanitizerKind::KernelAddress | SanitizerKind::KernelHWAddress;
 static const SanitizerMask NeedsLTO = SanitizerKind::CFI;
 static const SanitizerMask TrappingSupported =
-(SanitizerKind::Undefined & ~SanitizerKind::Vptr) |
-SanitizerKind::UnsignedIntegerOverflow | SanitizerKind::ImplicitConversion 
|
+(SanitizerKind::Undefined & ~SanitizerKind::Vptr) | SanitizerKind::Integer 
|
 SanitizerKind::Nullability | SanitizerKind::LocalBounds |
 SanitizerKind::CFI | SanitizerKind::FloatDivideByZero |
 SanitizerKind::ObjCCast;

diff  --git a/clang/test/Driver/fsanitize.c b/clang/test/Driver/fsanitize.c
index bad519fcef24..0ecf656f292c 100644
--- a/clang/test/Driver/fsanitize.c
+++ b/clang/test/Driver/fsanitize.c
@@ -786,6 +786,13 @@
 // CHECK-UBSAN-MINIMAL: 
"-fsanitize={{((signed-integer-overflow|integer-divide-by-zero|shift-base|shift-exponent|unreachable|return|vla-bound|alignment|null|pointer-overflow|float-cast-overflow|array-bounds|enum|bool|builtin|returns-nonnull-attribute|nonnull-attribute),?){17}"}}
 // CHECK-UBSAN-MINIMAL: "-fsanitize-minimal-runtime"
 
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=integer 
-fsanitize-trap=integer %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-INTSAN-TRAP
+// CHECK-INTSAN-TRAP: 
"-fsanitize-trap=integer-divide-by-zero,shift-base,shift-exponent,signed-integer-overflow,unsigned-integer-overflow,unsigned-shift-base,implicit-unsigned-integer-truncation,implicit-signed-integer-truncation,implicit-integer-sign-change"
+
+// RUN: %clang -target x86_64-linux-gnu -fsanitize=integer 
-fsanitize-minimal-runtime %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-INTSAN-MINIMAL
+// CHECK-INTSAN-MINIMAL: 
"-fsanitize=integer-divide-by-zero,shift-base,shift-exponent,signed-integer-overflow,unsigned-integer-overflow,unsigned-shift-base,implicit-unsigned-integer-truncation,implicit-signed-integer-truncation,implicit-integer-sign-change"
+// CHECK-INTSAN-MINIMAL: "-fsanitize-minimal-runtime"
+
 // RUN: %clang -target aarch64-linux-android -march=armv8-a+memtag 
-fsanitize=memtag -fsanitize-minimal-runtime %s -### 2>&1 | FileCheck %s 
--check-prefix=CHECK-MEMTAG-MINIMAL
 // CHECK-MEMTAG-MINIMAL: "-fsanitize=memtag"
 // CHECK-MEMTAG-MINIMAL: "-fsanitize-minimal-runtime"



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


[PATCH] D89766: Driver: Add integer sanitizers to trapping group automatically.

2020-10-20 Thread Evgenii Stepanov via Phabricator via cfe-commits
eugenis accepted this revision.
eugenis added a comment.
This revision is now accepted and ready to land.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89766

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


[PATCH] D89799: [clang][driver] Rename DriverOption as NoXarchOption (NFC)

2020-10-20 Thread Reid Kleckner via Phabricator via cfe-commits
rnk added a comment.

This seems like pretty corner case functionality. Do we really need this 
diagnostic? @tra @yaxun


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89799

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


[PATCH] D89765: [LibTooling][Clang-cast] A Clang LibTool to convert C-style casts to C++ style casts and more.

2020-10-20 Thread Andrzej Warzynski via Phabricator via cfe-commits
awarzynski added a comment.

Hi @oneraynyday ! This looks very interesting - thanks for uploading! I've only 
quickly skimmed through. Two high level points:

- Have you considered sending an RFC to cfe-dev regarding this tool?  I think 
that it would be a great way of attracting peoples attention. More importantly, 
should we add another tool to clang-tools-extra?
- Tthis is a rather large patch - could you split it into separate chunks? 
Otherwise it's quite tricky to review.

Thanks,
-Andrzej


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89765

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


[PATCH] D88553: [clangd] Start using SyntaxTrees for folding ranges feature

2020-10-20 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 299449.
kbobyrev added a comment.

Resolve comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88553

Files:
  clang-tools-extra/clangd/SemanticSelection.cpp
  clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp
  clang/include/clang/Tooling/Syntax/Tree.h
  clang/lib/Tooling/Syntax/Tree.cpp

Index: clang/lib/Tooling/Syntax/Tree.cpp
===
--- clang/lib/Tooling/Syntax/Tree.cpp
+++ clang/lib/Tooling/Syntax/Tree.cpp
@@ -300,6 +300,14 @@
   return nullptr;
 }
 
+const syntax::Node *syntax::Tree::findChild(NodeRole R) const {
+  for (const auto *C = FirstChild; C; C = C->getNextSibling()) {
+if (C->getRole() == R)
+  return C;
+  }
+  return nullptr;
+}
+
 bool syntax::List::classof(const syntax::Node *N) {
   switch (N->getKind()) {
   case syntax::NodeKind::NestedNameSpecifier:
Index: clang/include/clang/Tooling/Syntax/Tree.h
===
--- clang/include/clang/Tooling/Syntax/Tree.h
+++ clang/include/clang/Tooling/Syntax/Tree.h
@@ -169,9 +169,9 @@
 return const_cast(this)->findLastLeaf();
   }
 
-protected:
   /// Find the first node with a corresponding role.
   Node *findChild(NodeRole R);
+  const Node *findChild(NodeRole R) const;
 
 private:
   /// Prepend \p Child to the list of children and and sets the parent pointer.
Index: clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp
@@ -203,26 +203,59 @@
 TEST(FoldingRanges, All) {
   const char *Tests[] = {
   R"cpp(
-[[int global_variable]];
+void func() {[[
+  int Variable = 100;
 
-[[void func() {
-  int v = 100;
-}]]
+  if (Variable > 5) {[[
+Variable += 42;
+  ]]} else if (Variable++)
+++Variable;
+  else {[[
+Variable--;
+  ]]}
+
+  // Do not generate FoldingRange for empty CompoundStmts.
+  for (;;) {}
+
+  // If there are newlines between {}, we should generate one.
+  for (;;) {[[
+
+  ]]}
+]]}
   )cpp",
   R"cpp(
-[[class Foo {
+#define FOO int foo() {}
+
+// Do not generate folding range for braces within macro expansion.
+FOO
+
+// Do not generate folding range within macro arguments.
+#define FUNCTOR(functor) functor
+void func() {[[
+  FUNCTOR([](){});
+]]}
+
+// Do not generate folding range with a brace coming from macro.
+#define LBRACE {
+void bar() LBRACE
+  int X = 42;
+}
+  )cpp",
+  R"cpp(
+class Foo {
 public:
-  [[Foo() {
+  Foo() {[[
 int X = 1;
-  }]]
+  ]]}
 
 private:
-  [[int getBar() {
+  int getBar() {[[
 return 42;
-  }]]
+  ]]}
 
-  [[void getFooBar() { }]]
-}]];
+  // Braces are located at the same line: no folding range here.
+  void getFooBar() { }
+};
   )cpp",
   };
   for (const char *Test : Tests) {
Index: clang-tools-extra/clangd/SemanticSelection.cpp
===
--- clang-tools-extra/clangd/SemanticSelection.cpp
+++ clang-tools-extra/clangd/SemanticSelection.cpp
@@ -5,6 +5,7 @@
 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
 //
 //===--===//
+
 #include "SemanticSelection.h"
 #include "FindSymbols.h"
 #include "ParsedAST.h"
@@ -13,8 +14,16 @@
 #include "SourceCode.h"
 #include "clang/AST/DeclBase.h"
 #include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/SourceManager.h"
+#include "clang/Basic/TokenKinds.h"
+#include "clang/Tooling/Syntax/BuildTree.h"
+#include "clang/Tooling/Syntax/Nodes.h"
+#include "clang/Tooling/Syntax/Tree.h"
 #include "llvm/ADT/ArrayRef.h"
+#include "llvm/Support/Casting.h"
 #include "llvm/Support/Error.h"
+#include 
+#include 
 
 namespace clang {
 namespace clangd {
@@ -28,17 +37,59 @@
   }
 }
 
-// Recursively collects FoldingRange from a symbol and its children.
-void collectFoldingRanges(DocumentSymbol Symbol,
-  std::vector ) {
+llvm::Optional toFoldingRange(SourceRange SR,
+const SourceManager ) {
+  // Don't produce folding ranges when SourceRange either of bounds is coming
+  // from macros.
+  if (SR.getBegin().isMacroID() || SR.getEnd().isMacroID())
+return llvm::None;
   FoldingRange Range;
-  Range.startLine = Symbol.range.start.line;
-  

[PATCH] D89799: [clang][driver] Rename DriverOption as NoXarchOption (NFC)

2020-10-20 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

LGTM. I think a number of options can probably drop the flag, but that can be 
left as a future clean-up for macOS -Xarch (can someone add a reviewer for 
macOS?) and CUDA -Xarch* folks.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89799

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


[PATCH] D67030: ContentCache: Simplify by always owning the MemoryBuffer

2020-10-20 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith added a comment.

ping

In D67030#2331280 , @dexonsmith wrote:

> Rebased on top of https://reviews.llvm.org/D89431 (the tests haven't finished 
> yet; I'll update if necessary, but this is pretty straightforward).

(FTR, the tests passed as expected.)


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

https://reviews.llvm.org/D67030

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


[PATCH] D72553: [clang-tidy] Add performance-prefer-preincrement check

2020-10-20 Thread Nathan James via Phabricator via cfe-commits
njames93 updated this revision to Diff 299443.
njames93 added a comment.

Rebased and fix issues relating to rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D72553

Files:
  clang-tools-extra/clang-tidy/llvm/CMakeLists.txt
  clang-tools-extra/clang-tidy/llvm/LLVMTidyModule.cpp
  clang-tools-extra/clang-tidy/performance/CMakeLists.txt
  clang-tools-extra/clang-tidy/performance/PerformanceTidyModule.cpp
  clang-tools-extra/clang-tidy/performance/PreferPreIncrementCheck.cpp
  clang-tools-extra/clang-tidy/performance/PreferPreIncrementCheck.h
  clang-tools-extra/docs/ReleaseNotes.rst
  clang-tools-extra/docs/clang-tidy/checks/list.rst
  clang-tools-extra/docs/clang-tidy/checks/llvm-prefer-pre-increment.rst
  clang-tools-extra/docs/clang-tidy/checks/performance-prefer-pre-increment.rst
  
clang-tools-extra/test/clang-tidy/checkers/Inputs/performance-prefer-pre-increment/iterator.h
  
clang-tools-extra/test/clang-tidy/checkers/performance-prefer-pre-increment-disable-cpp-opcalls.cpp
  clang-tools-extra/test/clang-tidy/checkers/performance-prefer-pre-increment.c
  
clang-tools-extra/test/clang-tidy/checkers/performance-prefer-pre-increment.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/performance-prefer-pre-increment.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/performance-prefer-pre-increment.cpp
@@ -0,0 +1,63 @@
+// RUN: %check_clang_tidy %s performance-prefer-pre-increment %t -- -- \
+// RUN: -I%S/Inputs/performance-prefer-pre-increment
+
+#include "iterator.h"
+
+class IntIterator : public Iterator {
+  using Iterator::Iterator;
+};
+
+void foo() {
+  int Array[32];
+  Iterator It([0]);
+  It++; // fooNormal
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: Use pre-increment instead of post-increment
+  // CHECK-FIXES: {{^}}  ++It; // fooNormal
+  It--; // fooNormal
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: Use pre-decrement instead of post-decrement
+  // CHECK-FIXES: {{^}}  --It; // fooNormal
+  (*It)++; // fooNormal
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: Use pre-increment instead of post-increment
+  // CHECK-FIXES: {{^}}  ++(*It); // fooNormal
+  (*It)--; // fooNormal
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: Use pre-decrement instead of post-decrement
+  // CHECK-FIXES: {{^}}  --(*It); // fooNormal
+  *It++; // fooNormal
+  *It--; // fooNormal
+
+  PostfixIterator PfIt([0]);
+  PfIt++;// fooPostfix
+  PfIt--;// fooPostfix
+  (*PfIt)++; // fooPostfix
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: Use pre-increment instead of post-increment
+  // CHECK-FIXES: {{^}}  ++(*PfIt); // fooPostfix
+  (*PfIt)--; // fooPostfix
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: Use pre-decrement instead of post-decrement
+  // CHECK-FIXES: {{^}}  --(*PfIt); // fooPostfix
+  *PfIt++; // fooPostfix
+  *PfIt--; // fooPostfix
+
+  IntIterator IntIt([0]);
+  IntIt++;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: Use pre-increment instead of post-increment
+  // CHECK-FIXES: {{^}}  ++IntIt;
+  IntIt--;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: Use pre-decrement instead of post-decrement
+  // CHECK-FIXES: {{^}}  --IntIt;
+  (*IntIt)++;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: Use pre-increment instead of post-increment
+  // CHECK-FIXES: {{^}}  ++(*IntIt);
+  (*IntIt)--;
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: Use pre-decrement instead of post-decrement
+  // CHECK-FIXES: {{^}}  --(*IntIt);
+  *IntIt++;
+  *IntIt--;
+}
+
+template 
+void tempDependent() {
+  typename T::iterator it;
+  it++; //depType
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: Use pre-increment instead of post-increment
+  // CHECK-FIXES-NOT: {{^}}  ++it; //depType
+}
Index: clang-tools-extra/test/clang-tidy/checkers/performance-prefer-pre-increment.c
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/performance-prefer-pre-increment.c
@@ -0,0 +1,128 @@
+// RUN: %check_clang_tidy %s performance-prefer-pre-increment %t
+
+#define INC(X) X++
+#define DEC(X) X--
+
+void foo(int A) {
+  for (int I = 0; I < 10; I++) {
+// CHECK-MESSAGES: [[@LINE-1]]:27: warning: Use pre-increment instead of post-increment
+// CHECK-FIXES: {{^}}  for (int I = 0; I < 10; ++I) {
+  }
+  for (int I = 0; I < 10; ++I) {
+// CHECK-MESSAGES-NOT: [[@LINE-1]]:{{\d*}}: warning: Use pre-increment instead of post-increment
+  }
+  for (int I = 0; I < 10; A = I++) {
+// CHECK-MESSAGES-NOT: [[@LINE-1]]:{{\d*}}: warning: Use pre-increment instead of post-increment
+  }
+
+  for (int I = 10; I < 0; I--) {
+// CHECK-MESSAGES: [[@LINE-1]]:27: warning: Use pre-decrement instead of post-decrement
+// CHECK-FIXES: {{^}}  for (int I = 10; I < 0; --I) {
+  }
+  for (int I = 10; I < 0; --I) {
+// CHECK-MESSAGES-NOT: [[@LINE-1]]:{{\d*}}: warning: Use pre-decrement instead of 

[PATCH] D88553: [clangd] Start using SyntaxTrees for folding ranges feature

2020-10-20 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: clang-tools-extra/clangd/SemanticSelection.cpp:52-55
+const syntax::Token *FirstToken = Tree->findFirstLeaf()->getToken(),
+*LastToken = Tree->findLastLeaf()->getToken();
+assert(FirstToken->kind() == tok::TokenKind::l_brace);
+assert(LastToken->kind() == tok::TokenKind::r_brace);

kbobyrev wrote:
> sammccall wrote:
> > eduucaldas wrote:
> > > Take a look at `clang/include/clang/Tooling/Syntax/Nodes.h`, syntax 
> > > constructs usually have nice classes with accessors.
> > > 
> > > For instance `CompoundStatement` has the accessors `getLbrace` and 
> > > `getRbrace` that seem to be exactly what you want.
> > > 
> > > However these might not give exactly the first leaf and last leaf in the 
> > > case of syntactically incorrect code.
> > I think we should treat all bracket-like things generically. Today this is 
> > just CompoundStmt, but we want to handle init lists, function calls, parens 
> > around for-loop conditions, template parameter and arg lists etc in the 
> > same way.
> > 
> > This sort of use is why the `OpenParen`/`CloseParen` NodeRoles are generic 
> > - we can have one set of logic to handle all of these. (No opinion on 
> > whether that should live here or in the syntax trees library, but putting 
> > it here for now seems fine).
> > 
> > So in the end I think checking the class name and then grabbing the braces 
> > by role (not kind) is the right thing here.
> > We definitely want to avoid asserting that the code looks the way we expect 
> > though.
> > So in the end I think checking the class name and then grabbing the braces 
> > by role (not kind) is the right thing here.
> > We definitely want to avoid asserting that the code looks the way we expect 
> > though.
> 
> Can you elaborate a bit on how this would work? Is your proposal to iterate 
> through `CompoundStatement` first-level children and grab the `OpenParen` + 
> `CloseParen` roles?
Exactly. And bail out if both don't exist.

And this can be done on Tree, so it's trivial to add support for function calls 
etc (but feel free to keep the scope small)



Comment at: clang/include/clang/Tooling/Syntax/Nodes.h:771
   }
-  Leaf *getLbrace();
+  Leaf *getLbrace() const;
   /// FIXME: use custom iterator instead of 'vector'.

This doesn't look right: now a const method grants mutable access to the child. 
I think we need both overloads :-(

(Fortunately this is to be tablegen'd one day...)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88553

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


[PATCH] D78760: Check a class doesn't have a dependent type before iterating over its base classes

2020-10-20 Thread Akira Hatanaka via Phabricator via cfe-commits
ahatanak added a comment.

ping


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D78760

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


[PATCH] D88553: [clangd] Start using SyntaxTrees for folding ranges feature

2020-10-20 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev added inline comments.



Comment at: clang-tools-extra/clangd/SemanticSelection.cpp:52-55
+const syntax::Token *FirstToken = Tree->findFirstLeaf()->getToken(),
+*LastToken = Tree->findLastLeaf()->getToken();
+assert(FirstToken->kind() == tok::TokenKind::l_brace);
+assert(LastToken->kind() == tok::TokenKind::r_brace);

sammccall wrote:
> eduucaldas wrote:
> > Take a look at `clang/include/clang/Tooling/Syntax/Nodes.h`, syntax 
> > constructs usually have nice classes with accessors.
> > 
> > For instance `CompoundStatement` has the accessors `getLbrace` and 
> > `getRbrace` that seem to be exactly what you want.
> > 
> > However these might not give exactly the first leaf and last leaf in the 
> > case of syntactically incorrect code.
> I think we should treat all bracket-like things generically. Today this is 
> just CompoundStmt, but we want to handle init lists, function calls, parens 
> around for-loop conditions, template parameter and arg lists etc in the same 
> way.
> 
> This sort of use is why the `OpenParen`/`CloseParen` NodeRoles are generic - 
> we can have one set of logic to handle all of these. (No opinion on whether 
> that should live here or in the syntax trees library, but putting it here for 
> now seems fine).
> 
> So in the end I think checking the class name and then grabbing the braces by 
> role (not kind) is the right thing here.
> We definitely want to avoid asserting that the code looks the way we expect 
> though.
> So in the end I think checking the class name and then grabbing the braces by 
> role (not kind) is the right thing here.
> We definitely want to avoid asserting that the code looks the way we expect 
> though.

Can you elaborate a bit on how this would work? Is your proposal to iterate 
through `CompoundStatement` first-level children and grab the `OpenParen` + 
`CloseParen` roles?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88553

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


[PATCH] D88553: [clangd] Start using SyntaxTrees for folding ranges feature

2020-10-20 Thread Kirill Bobyrev via Phabricator via cfe-commits
kbobyrev updated this revision to Diff 299438.
kbobyrev marked 9 inline comments as done.
kbobyrev added a comment.

Resolve review comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D88553

Files:
  clang-tools-extra/clangd/SemanticSelection.cpp
  clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp
  clang/include/clang/Tooling/Syntax/Nodes.h
  clang/include/clang/Tooling/Syntax/Tree.h
  clang/lib/Tooling/Syntax/Nodes.cpp
  clang/lib/Tooling/Syntax/Tree.cpp

Index: clang/lib/Tooling/Syntax/Tree.cpp
===
--- clang/lib/Tooling/Syntax/Tree.cpp
+++ clang/lib/Tooling/Syntax/Tree.cpp
@@ -292,7 +292,7 @@
   return Last;
 }
 
-syntax::Node *syntax::Tree::findChild(NodeRole R) {
+syntax::Node *syntax::Tree::findChild(NodeRole R) const {
   for (auto *C = FirstChild; C; C = C->getNextSibling()) {
 if (C->getRole() == R)
   return C;
Index: clang/lib/Tooling/Syntax/Nodes.cpp
===
--- clang/lib/Tooling/Syntax/Nodes.cpp
+++ clang/lib/Tooling/Syntax/Nodes.cpp
@@ -522,7 +522,7 @@
   findChild(syntax::NodeRole::Expression));
 }
 
-syntax::Leaf *syntax::CompoundStatement::getLbrace() {
+syntax::Leaf *syntax::CompoundStatement::getLbrace() const {
   return cast_or_null(findChild(syntax::NodeRole::OpenParen));
 }
 
@@ -535,7 +535,7 @@
   return Children;
 }
 
-syntax::Leaf *syntax::CompoundStatement::getRbrace() {
+syntax::Leaf *syntax::CompoundStatement::getRbrace() const {
   return cast_or_null(findChild(syntax::NodeRole::CloseParen));
 }
 
Index: clang/include/clang/Tooling/Syntax/Tree.h
===
--- clang/include/clang/Tooling/Syntax/Tree.h
+++ clang/include/clang/Tooling/Syntax/Tree.h
@@ -171,7 +171,7 @@
 
 protected:
   /// Find the first node with a corresponding role.
-  Node *findChild(NodeRole R);
+  Node *findChild(NodeRole R) const;
 
 private:
   /// Prepend \p Child to the list of children and and sets the parent pointer.
Index: clang/include/clang/Tooling/Syntax/Nodes.h
===
--- clang/include/clang/Tooling/Syntax/Nodes.h
+++ clang/include/clang/Tooling/Syntax/Nodes.h
@@ -768,10 +768,10 @@
   static bool classof(const Node *N) {
 return N->getKind() == NodeKind::CompoundStatement;
   }
-  Leaf *getLbrace();
+  Leaf *getLbrace() const;
   /// FIXME: use custom iterator instead of 'vector'.
   std::vector getStatements();
-  Leaf *getRbrace();
+  Leaf *getRbrace() const;
 };
 
 /// A declaration that can appear at the top-level. Note that this does *not*
Index: clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticSelectionTests.cpp
@@ -203,26 +203,59 @@
 TEST(FoldingRanges, All) {
   const char *Tests[] = {
   R"cpp(
-[[int global_variable]];
+void func() {[[
+  int Variable = 100;
 
-[[void func() {
-  int v = 100;
-}]]
+  if (Variable > 5) {[[
+Variable += 42;
+  ]]} else if (Variable++)
+++Variable;
+  else {[[
+Variable--;
+  ]]}
+
+  // Do not generate FoldingRange for empty CompoundStmts.
+  for (;;) {}
+
+  // If there are newlines between {}, we should generate one.
+  for (;;) {[[
+
+  ]]}
+]]}
   )cpp",
   R"cpp(
-[[class Foo {
+#define FOO int foo() {}
+
+// Do not generate folding range for braces within macro expansion.
+FOO
+
+// Do not generate folding range within macro arguments.
+#define FUNCTOR(functor) functor
+void func() {[[
+  FUNCTOR([](){});
+]]}
+
+// Do not generate folding range with a brace coming from macro.
+#define LBRACE {
+void bar() LBRACE
+  int X = 42;
+}
+  )cpp",
+  R"cpp(
+class Foo {
 public:
-  [[Foo() {
+  Foo() {[[
 int X = 1;
-  }]]
+  ]]}
 
 private:
-  [[int getBar() {
+  int getBar() {[[
 return 42;
-  }]]
+  ]]}
 
-  [[void getFooBar() { }]]
-}]];
+  // Braces are located at the same line: no folding range here.
+  void getFooBar() { }
+};
   )cpp",
   };
   for (const char *Test : Tests) {
Index: clang-tools-extra/clangd/SemanticSelection.cpp
===
--- clang-tools-extra/clangd/SemanticSelection.cpp
+++ clang-tools-extra/clangd/SemanticSelection.cpp
@@ -5,6 +5,7 @@
 // SPDX-License-Identifier: Apache-2.0 WITH 

[PATCH] D83448: [CodeGen] Emit destructor calls to destruct non-trivial C struct temporaries created by conditional and assignment operators

2020-10-20 Thread Akira Hatanaka via Phabricator via cfe-commits
ahatanak added a comment.

ping


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83448

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


[PATCH] D89490: Introduce __attribute__((darwin_abi))

2020-10-20 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/lib/CodeGen/CGCall.cpp:238
+  if (D->hasAttr())
+return IsDarwin ? CC_C : CC_AArch64Darwin;
+

mstorsjo wrote:
> aaron.ballman wrote:
> > Can you help me understand this change a bit better? If the declaration 
> > uses the Darwin ABI and the platform is Darwin, you want to use the cdecl 
> > convention?
> This (here and in the other similar places) matches the existing logic for 
> the `ms_abi` attribute; if you're on a platform where the attribute selects 
> what already is the default (what `CC_C` implies on this platform), we just 
> use that instead of the more explicit calling convention.
A, thank you for the clarification, that makes sense now.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89490

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


[PATCH] D89814: [TableGen] Change !getop and !setop to !getdagop and !setdagop

2020-10-20 Thread Paul C. Anagnostopoulos via Phabricator via cfe-commits
Paul-C-Anagnostopoulos created this revision.
Paul-C-Anagnostopoulos added reviewers: lattner, nhaehnle, rengolin, asl.
Herald added subscribers: llvm-commits, cfe-commits, dexonsmith, dmgreen, 
hiraditya, kristof.beyls.
Herald added projects: clang, LLVM.
Paul-C-Anagnostopoulos requested review of this revision.

In order to make the bang operators related to DAGs consistent, I'm adding 
'dag' to the names that don't already include it. This will help with overall 
consistency when the new DAG operators are added over the next few weeks.

I updated the test, along with uses of the two operators in 
clang/Basic/arm_mve.td and Target/ARM/ARMInstrMVE.td


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D89814

Files:
  clang/include/clang/Basic/arm_mve.td
  llvm/docs/TableGen/ProgRef.rst
  llvm/include/llvm/TableGen/Record.h
  llvm/lib/TableGen/Record.cpp
  llvm/lib/TableGen/TGLexer.cpp
  llvm/lib/TableGen/TGLexer.h
  llvm/lib/TableGen/TGParser.cpp
  llvm/lib/Target/ARM/ARMInstrMVE.td
  llvm/test/TableGen/getsetop.td

Index: llvm/test/TableGen/getsetop.td
===
--- llvm/test/TableGen/getsetop.td
+++ llvm/test/TableGen/getsetop.td
@@ -3,6 +3,9 @@
 // RUN: not llvm-tblgen -DERROR2 %s 2>&1 | FileCheck --check-prefix=ERROR2 %s
 // RUN: not llvm-tblgen -DERROR3 %s 2>&1 | FileCheck --check-prefix=ERROR3 %s
 
+// !setop and !getop are deprecated in favor of !setdagop and !getdagop.
+// Two tests retain the old names just to be sure they are still supported.
+
 class Base;
 class OtherBase;
 
@@ -18,28 +21,28 @@
   dag replaceWithBar = !setop(orig, bar);
 
   // CHECK: dag replaceWithBaz = (qux 1, 2:$a, ?:$b);
-  dag replaceWithBaz = !setop(orig, qux);
+  dag replaceWithBaz = !setdagop(orig, qux);
 
   // CHECK: Base getopWithCast = foo;
   Base getopWithCast = !getop(orig);
 
   // CHECK: dag getopToSetop = (foo "hello", ?:$world);
-  dag getopToSetop = !setop(another, !getop(orig));
+  dag getopToSetop = !setdagop(another, !getdagop(orig));
 
   // CHECK: dag getopToBangDag = (foo 1:$a, 2:$b, 3:$c);
-  dag getopToBangDag = !dag(!getop(orig), [1, 2, 3], ["a", "b", "c"]);
+  dag getopToBangDag = !dag(!getdagop(orig), [1, 2, 3], ["a", "b", "c"]);
 
   // CHECK: dag getopToDagInit = (foo "it worked");
-  dag getopToDagInit = (!getop(orig) "it worked");
+  dag getopToDagInit = (!getdagop(orig) "it worked");
 
 #ifdef ERROR1
-  // !getop(...) has a static type of 'any record at all, with no
+  // !getdagop(...) has a static type of 'any record at all, with no
   // required superclasses'. That's too general to use in an
   // assignment whose LHS demands an instance of Base, so we expect a
   // static (parse-time) type-checking error.
 
-  // ERROR1: error: Field 'noCast' of type 'Base' is incompatible with value '!getop(orig)' of type '{}'
-  Base noCast = !getop(orig);
+  // ERROR1: error: Field 'noCast' of type 'Base' is incompatible with value '!getdagop(orig)' of type '{}'
+  Base noCast = !getdagop(orig);
 #endif
 
 #ifdef ERROR2
@@ -47,15 +50,15 @@
   // evaluation time that the operator of 'another' is a record that
   // isn't an instance of the specified base class.
 
-  // ERROR2: error: Expected type 'Base', got 'OtherBase' in: !getop((qux "hello", ?:$world))
-  Base badCast = !getop(another);
+  // ERROR2: error: Expected type 'Base', got 'OtherBase' in: !getdagop((qux "hello", ?:$world))
+  Base badCast = !getdagop(another);
 #endif
 
 #ifdef ERROR3
-  // Obviously, you shouldn't be able to give any type to !getop that
+  // Obviously, you shouldn't be able to give any type to !getdagop that
   // isn't a class type.
 
-  // ERROR3: error: type for !getop must be a record type
-  int ridiculousCast = !getop(orig);
+  // ERROR3: error: type for !getdagop must be a record type
+  int ridiculousCast = !getdagop(orig);
 #endif
 }
Index: llvm/lib/Target/ARM/ARMInstrMVE.td
===
--- llvm/lib/Target/ARM/ARMInstrMVE.td
+++ llvm/lib/Target/ARM/ARMInstrMVE.td
@@ -3033,7 +3033,7 @@
   defvar outparams = (inst (OutVTI.Vec MQPR:$QdSrc), (InVTI.Vec MQPR:$Qm),
(imm:$imm));
 
-  def : Pat<(OutVTI.Vec !setop(inparams, int_arm_mve_vshrn)),
+  def : Pat<(OutVTI.Vec !setdagop(inparams, int_arm_mve_vshrn)),
 (OutVTI.Vec outparams)>;
   def : Pat<(OutVTI.Vec !con(inparams, (int_arm_mve_vshrn_predicated
(InVTI.Pred VCCR:$pred,
@@ -3235,7 +3235,7 @@
   defvar unpred_int = !cast("int_arm_mve_" # name);
   defvar pred_int = !cast("int_arm_mve_" # name # "_predicated");
 
-  def : Pat<(VTI.Vec !setop(inparams, unpred_int)),
+  def : Pat<(VTI.Vec !setdagop(inparams, unpred_int)),
 (VTI.Vec outparams)>;
   def : Pat<(VTI.Vec !con(inparams, (pred_int (VTI.Pred VCCR:$pred,
 (VTI.Vec !con(outparams, (? ARMVCCThen, VCCR:$pred)))>;
Index: llvm/lib/TableGen/TGParser.cpp

[PATCH] D87528: Enable '#pragma STDC FENV_ACCESS' in frontend cf. D69272 - Work in Progress

2020-10-20 Thread Melanie Blower via Phabricator via cfe-commits
mibintc updated this revision to Diff 299426.
mibintc added a comment.

I made the change requested by @rsmith to HandleIntToFloatCast, avoiding the 
check if Info.InConstantContext, then I corrected 2 tests so that -verify 
matches.

  clang/test/CXX/expr/expr.const/p2-0x.cpp
  clang/test/Parser/pragma-fenv_access.c

(I had 30 lit tests failing in my sandbox but I fixed the logic, so please 
ignore that remark from my previous revision)
check-clang is running clean


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87528

Files:
  clang/docs/UsersManual.rst
  clang/include/clang/AST/Decl.h
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/DiagnosticASTKinds.td
  clang/include/clang/Basic/DiagnosticParseKinds.td
  clang/include/clang/Basic/LangOptions.h
  clang/include/clang/Sema/ScopeInfo.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/ExprConstant.cpp
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/CodeGen/CodeGenModule.h
  clang/lib/Parse/ParsePragma.cpp
  clang/lib/Parse/ParseStmt.cpp
  clang/lib/Sema/ScopeInfo.cpp
  clang/lib/Sema/SemaAttr.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaStmt.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/lib/Serialization/ASTReaderDecl.cpp
  clang/lib/Serialization/ASTWriterDecl.cpp
  clang/test/CXX/expr/expr.const/p2-0x.cpp
  clang/test/CodeGen/fp-floatcontrol-pragma.cpp
  clang/test/CodeGen/pragma-fenv_access.c
  clang/test/Parser/fp-floatcontrol-syntax.cpp
  clang/test/Parser/pragma-fenv_access.c
  clang/test/Preprocessor/pragma_unknown.c

Index: clang/test/Preprocessor/pragma_unknown.c
===
--- clang/test/Preprocessor/pragma_unknown.c
+++ clang/test/Preprocessor/pragma_unknown.c
@@ -16,15 +16,6 @@
 // CHECK: {{^}}#pragma STDC FP_CONTRACT DEFAULT{{$}}
 // CHECK: {{^}}#pragma STDC FP_CONTRACT IN_BETWEEN{{$}}
 
-#pragma STDC FENV_ACCESS ON  // expected-warning {{pragma STDC FENV_ACCESS ON is not supported, ignoring pragma}}
-#pragma STDC FENV_ACCESS OFF
-#pragma STDC FENV_ACCESS DEFAULT
-#pragma STDC FENV_ACCESS IN_BETWEEN   // expected-warning {{expected 'ON' or 'OFF' or 'DEFAULT' in pragma}}
-// CHECK: {{^}}#pragma STDC FENV_ACCESS ON{{$}}
-// CHECK: {{^}}#pragma STDC FENV_ACCESS OFF{{$}}
-// CHECK: {{^}}#pragma STDC FENV_ACCESS DEFAULT{{$}}
-// CHECK: {{^}}#pragma STDC FENV_ACCESS IN_BETWEEN{{$}}
-
 #pragma STDC CX_LIMITED_RANGE ON
 #pragma STDC CX_LIMITED_RANGE OFF
 #pragma STDC CX_LIMITED_RANGE DEFAULT 
Index: clang/test/Parser/pragma-fenv_access.c
===
--- /dev/null
+++ clang/test/Parser/pragma-fenv_access.c
@@ -0,0 +1,46 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+// RUN: %clang_cc1 -ffp-exception-behavior=strict -DSTRICT -fsyntax-only -verify %s
+// RUN: %clang_cc1 -x c++ -DCPP -DSTRICT -ffp-exception-behavior=strict -fsyntax-only -verify %s
+#ifdef CPP
+#define CONST constexpr
+#else
+#define CONST const
+#endif
+
+#pragma STDC FENV_ACCESS IN_BETWEEN   // expected-warning {{expected 'ON' or 'OFF' or 'DEFAULT' in pragma}}
+
+#pragma STDC FENV_ACCESS OFF
+
+float func_04(int x, float y) {
+  if (x)
+return y + 2;
+  #pragma STDC FENV_ACCESS ON // expected-error{{'#pragma STDC FENV_ACCESS' can only appear at file scope or at the start of a compound statement}}
+  return x + y;
+}
+
+#pragma STDC FENV_ACCESS ON
+int main() {
+  CONST float one = 1.0F ;
+  CONST float three = 3.0F ;
+  CONST float four = 4.0F ;
+  CONST float frac_ok = one/four;
+#if defined(CPP) & defined(STRICT)
+//not-expected-error@+3 {{constexpr variable 'frac' must be initialized by a constant expression}}
+//not-expected-note@+2 {{compile time floating point arithmetic suppressed in strict evaluation modes}}
+#endif
+  CONST float frac = one/three; // rounding
+  CONST double d = one;
+  CONST int not_too_big = 255;
+  CONST float fnot_too_big = not_too_big;
+  CONST int too_big = 0x7ff0;
+#if defined(CPP) & defined(STRICT)
+//not-expected-error@+6 {{constexpr variable 'fbig' must be initialized by a constant expression}}
+//not-expected-note@+5 {{compile time floating point arithmetic suppressed in strict evaluation modes}}
+#endif
+#if defined(CPP)
+//expected-warning@+2{{implicit conversion}}
+#endif
+  CONST float fbig = too_big; // inexact
+  if (one <= four)  return 0;
+  return -1;
+}
Index: clang/test/Parser/fp-floatcontrol-syntax.cpp
===
--- clang/test/Parser/fp-floatcontrol-syntax.cpp
+++ clang/test/Parser/fp-floatcontrol-syntax.cpp
@@ -26,19 +26,13 @@
 double a = 0.0;
 double b = 1.0;
 
-//FIXME At some point this warning will be removed, until then
-//  document the warning
-#ifdef FAST
-// expected-warning@+1{{pragma STDC FENV_ACCESS ON is not supported, ignoring pragma}}

[PATCH] D89573: [Driver] Incorporate -mfloat-abi in the computed triple on ARM

2020-10-20 Thread John Brawn via Phabricator via cfe-commits
john.brawn updated this revision to Diff 299420.
john.brawn edited the summary of this revision.
john.brawn added a comment.

Adjusted to give an error when the specified float abi is incompatible with the 
default. Was a bit trickier than I expected as it required extracting out the 
logic to determine the default into a separate function (we could instead emit 
the error in arm::getARMFloatABI but then it would be emitted several times as 
the function is called from several places).


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

https://reviews.llvm.org/D89573

Files:
  clang/lib/Driver/ToolChain.cpp
  clang/lib/Driver/ToolChains/Arch/ARM.cpp
  clang/lib/Driver/ToolChains/Arch/ARM.h
  clang/test/Driver/arm-float-abi-lto.c
  clang/test/Driver/arm-float-abi.c
  clang/test/Driver/arm-triple.c
  clang/test/Driver/windows-thumbv7em.cpp

Index: clang/test/Driver/windows-thumbv7em.cpp
===
--- clang/test/Driver/windows-thumbv7em.cpp
+++ clang/test/Driver/windows-thumbv7em.cpp
@@ -1,8 +1,8 @@
 // RUN: %clang -target thumb-none-windows-eabi-coff -mcpu=cortex-m7 -### -c %s 2>&1 \
 // RUN: | FileCheck %s --check-prefix CHECK-V7
-// CHECK-V7-NOT: error: the target architecture 'thumbv7em' is not supported by the target 'thumbv7em-none-windows-eabi'
+// CHECK-V7-NOT: error: the target architecture 'thumbv7em' is not supported by the target 'thumbv7em-none-windows-eabihf'
 
 // RUN: %clang -target thumb-none-windows-eabi-coff -mcpu=cortex-m1 -### -c %s 2>&1 \
 // RUN: | FileCheck %s --check-prefix CHECK-V6
-// CHECK-V6: error: the target architecture 'thumbv6m' is not supported by the target 'thumbv6m-none-windows-eabi'
+// CHECK-V6: error: the target architecture 'thumbv6m' is not supported by the target 'thumbv6m-none-windows-eabihf'
 
Index: clang/test/Driver/arm-triple.c
===
--- /dev/null
+++ clang/test/Driver/arm-triple.c
@@ -0,0 +1,48 @@
+// RUN: %clang -print-effective-triple \
+// RUN:   --target=arm-none-eabi \
+// RUN:   | FileCheck %s --check-prefix=CHECK-DEFAULT
+// RUN: %clang -print-effective-triple \
+// RUN:   --target=armeb-none-eabi -mlittle-endian \
+// RUN:   | FileCheck %s --check-prefix=CHECK-DEFAULT
+// RUN: %clang -print-effective-triple \
+// RUN:   --target=arm-none-eabihf -march=armv4t -mfloat-abi=softfp \
+// RUN:   | FileCheck %s --check-prefix=CHECK-DEFAULT
+// CHECK-DEFAULT: armv4t-none-unknown-eabi
+
+// RUN: %clang -print-effective-triple \
+// RUN:   --target=armeb-none-eabi \
+// RUN:   | FileCheck %s --check-prefix=CHECK-EB
+// RUN: %clang -print-effective-triple \
+// RUN:   --target=arm-none-eabi -mbig-endian \
+// RUN:   | FileCheck %s --check-prefix=CHECK-EB
+// CHECK-EB: armebv4t-none-unknown-eabi
+
+// RUN: %clang -print-effective-triple \
+// RUN:   --target=arm-none-eabihf -march=armv4t \
+// RUN:   | FileCheck %s --check-prefix=CHECK-HF
+// RUN: %clang -print-effective-triple \
+// RUN:   --target=arm-none-eabi -mfloat-abi=hard \
+// RUN:   | FileCheck %s --check-prefix=CHECK-HF
+// CHECK-HF: armv4t-none-unknown-eabihf
+
+// RUN: %clang -print-effective-triple \
+// RUN:   --target=armeb-none-eabihf -march=armv4t \
+// RUN:   | FileCheck %s --check-prefix=CHECK-EB-HF
+// RUN: %clang -print-effective-triple \
+// RUN:   --target=armeb-none-eabi -mfloat-abi=hard \
+// RUN:   | FileCheck %s --check-prefix=CHECK-EB-HF
+// RUN: %clang -print-effective-triple -march=armv4t \
+// RUN:   --target=arm-none-eabihf -mbig-endian \
+// RUN:   | FileCheck %s --check-prefix=CHECK-EB-HF
+// RUN: %clang -print-effective-triple \
+// RUN:   --target=arm-none-eabi -mbig-endian -mfloat-abi=hard \
+// RUN:   | FileCheck %s --check-prefix=CHECK-EB-HF
+// CHECK-EB-HF: armebv4t-none-unknown-eabihf
+
+// RUN: %clang -print-effective-triple \
+// RUN:   --target=arm-none-eabi -march=armv8m.main -mbig-endian -mfloat-abi=hard \
+// RUN:   | FileCheck %s --check-prefix=CHECK-V8M-EB-HF
+// RUN: %clang -print-effective-triple \
+// RUN:   --target=arm-none-eabi -mcpu=cortex-m33 -mbig-endian -mfloat-abi=hard \
+// RUN:   | FileCheck %s --check-prefix=CHECK-V8M-EB-HF
+// CHECK-V8M-EB-HF: thumbebv8m.main-none-unknown-eabihf
Index: clang/test/Driver/arm-float-abi.c
===
--- clang/test/Driver/arm-float-abi.c
+++ clang/test/Driver/arm-float-abi.c
@@ -2,7 +2,7 @@
 // RUN: %clang %s -target armv7-apple-ios -mfloat-abi=softfp -### 2>&1 | FileCheck -check-prefix=NOERROR %s
 // RUN: %clang %s -arch armv7 -target thumbv7-apple-darwin-eabi -mfloat-abi=hard -### 2>&1 | FileCheck -check-prefix=NOERROR %s
 
-// ARMV7-ERROR: unsupported option '-mfloat-abi=hard' for target 'thumbv7'
+// ARMV7-ERROR: unsupported option '-mfloat-abi=hard' for target 'thumbv7-apple-ios'
 // NOERROR-NOT: unsupported option
 
 // RUN: %clang -target armv7-linux-androideabi21 %s -### -c 2>&1 \
@@ -14,3 +14,25 @@
 // RUN:   | FileCheck 

[PATCH] D89651: [clang-tidy] Add bugprone-suspicious-memory-comparison check

2020-10-20 Thread Gabor Bencze via Phabricator via cfe-commits
gbencze added a comment.

In D89651#2338266 , @njames93 wrote:

> Should point out there is already a check for cert-oop57-cpp, added in D72488 
> . Do these play nice with each other or 
> should they perhaps be merged or share code?

I would certainly expect some duplicate warnings with there two checks, but as 
far as I can tell that check does not currently warn on using `memcmp` with 
non-standard-layout types. 
I personally would leave the exp42 and flp37 parts of this check as separate, 
because those are useful in C as well. But maybe it'd be better to move the 
warning for non-standard-layout types from here to the existing one.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89651

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


[PATCH] D85474: Add -fbinutils-version= to gate ELF features on the specified binutils version

2020-10-20 Thread Saleem Abdulrasool via Phabricator via cfe-commits
compnerd added a comment.

Is there a reason to not use the existing `-mlinker-version=` option and 
expanding that beyond just Darwin targets?  I feel like having the same option 
would be much nicer.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D85474

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


[PATCH] D85697: [clang-tidy] Add cppcoreguidelines-prefer-scoped-enums

2020-10-20 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D85697#2340258 , @njames93 wrote:

> In D85697#2339055 , @aaron.ballman 
> wrote:
>
>> I tend to be very skeptical of the value of checks that basically throw out 
>> entire usable chunks of the base language because the check is effectively 
>> impossible to apply to an existing code base. Have you run the check over 
>> large C++ code bases to see just how often the diagnostic triggers and 
>> whether there are ways we might want to reduce false-positives that the C++ 
>> Core Guidelines haven't considered as part of their enforcement strategy?
>
> I disagree with this mentality, This is following what the core guideline 
> states perfectly. If a codebase doesn't want to adhere to those guidelines, 
> they don't need to run this check. If you think there are shortcomings in the 
> guidelines, raise an issue on their github.

As with other C++ core guideline checks, the usual approach is for the patch 
authors to go back to the C++ Core Guideline folks with these issues to find 
out how they should be addressed. This has produced better C++ Core Guidelines 
and better checkers in the past and is the way I think we should continue to 
proceed. That said, I agree with you that we will eventually go with whatever 
the guideline authors want -- but this is us doing our due diligence since the 
authors put very little thought into enforcement of the rules in general, and 
is appropriate (for any guidelines, not just the C++ core guidelines). Note, 
this is in keeping with the guidelines themselves which state that they're not 
meant to subset the language and are intended to allow for gradual adoption of 
rules 
(https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#innot-non-aims).

In D85697#2340381 , 
@janosbenjaminantal wrote:

> In D85697#2339055 , @aaron.ballman 
> wrote:
>
>> Btw, one fear I have with this check is that the automated fixits are 
>> somewhat risky -- unscoped vs scoped enumerations has ABI implications and 
>> changing from one to the other may break the ABI.
>
> I am not familiar with these specific ABI implications, if you could help me 
> with some keywords/references/link to start to investigate, I am happy to 
> deep dive into it. I am also willing to discard the automated fixes if it 
> makes this review better. What do you think?

I did some digging and I'm less certain I'm worried about this now. I was 
thinking that the mangling was different for these two cases, but it's the same 
mangling for `func()` either way: https://godbolt.org/z/xhcd7E The automated 
fixits still worry me in the places where they may take working code and change 
it to not be working (like narrowing conversions with the enumerator values, 
etc), but if those are addressed, then I think the fix-its are a benefit rather 
than a risk.




Comment at: 
clang-tools-extra/clang-tidy/cppcoreguidelines/PreferScopedEnumsCheck.cpp:22
+const LangOptions ) const {
+  return LangOpts.CPlusPlus11;
+}

janosbenjaminantal wrote:
> njames93 wrote:
> > aaron.ballman wrote:
> > > FWIW, Clang accepts scoped enumerations as a conforming language 
> > > extension in older language modes. Should this check be enabled for any 
> > > C++ mode?
> > If you go down that route, you lose portability as the transformed code 
> > will only compile on versions of clang, Could be option controlled I guess, 
> > WDYT?
> I think by default the check shouldn't do that (source codes that uses 
> multiple compilers?), but it might worth an option to be able to turn it on 
> on "clang-only" code bases.
The impression I have from the guidelines is that they're intended for C++11 
and later code bases as a way to improve the coding practices. They don't 
really seem to imply there's a requirement that code remains portable, but that 
sure seems like a reasonable goal to me. I think I'm fine leaving this disabled 
unless you're in C++11 mode, but we may want to see if there's a policy 
decision here for the core guideline checks (I have no idea how consistent 
we're being with considering older standards for these particular checks).



Comment at: 
clang-tools-extra/clang-tidy/cppcoreguidelines/PreferScopedEnumsCheck.cpp:28
+
+  Finder->addMatcher(UnscopedEnumDecl().bind("enumDecl"), this);
+

njames93 wrote:
> aaron.ballman wrote:
> > This should be checking whether the enumeration comes from a system header 
> > or not -- we should definitely not warn about enumerations the user cannot 
> > change.
> > This should be checking whether the enumeration comes from a system header 
> > or not -- we should definitely not warn about enumerations the user cannot 
> > change.
> 
> Won't clang-tidy handle this by suppressing system header diagnostics, I 
> thought 

[PATCH] D89469: FileManager: Test FileManager::getFileRef

2020-10-20 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
dexonsmith added a comment.
Herald added a subscriber: ormris.

In D89469#2342117 , @arphaman wrote:

> Thanks. Could you expand the comment in the test that this test path 
> specifically exercises the behavior produced by the RedirectingFileSystem?

Yup, done in 729d7d23282e9b00eaa7a5f35a4224929d73d3a4 
.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89469

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


[PATCH] D89469: FileManager: Test FileManager::getFileRef

2020-10-20 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG729d7d23282e: FileManager: Test FileManager::getFileRef 
(authored by dexonsmith).
Herald added a project: clang.

Changed prior to commit:
  https://reviews.llvm.org/D89469?vs=298379=299416#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89469

Files:
  clang/unittests/Basic/FileManagerTest.cpp

Index: clang/unittests/Basic/FileManagerTest.cpp
===
--- clang/unittests/Basic/FileManagerTest.cpp
+++ clang/unittests/Basic/FileManagerTest.cpp
@@ -28,17 +28,28 @@
   // not in this map is considered to not exist in the file system.
   llvm::StringMap StatCalls;
 
-  void InjectFileOrDirectory(const char *Path, ino_t INode, bool IsFile) {
+  void InjectFileOrDirectory(const char *Path, ino_t INode, bool IsFile,
+ const char *StatPath) {
 #ifndef _WIN32
 SmallString<128> NormalizedPath(Path);
 llvm::sys::path::native(NormalizedPath);
 Path = NormalizedPath.c_str();
+
+SmallString<128> NormalizedStatPath;
+if (StatPath) {
+  NormalizedStatPath = StatPath;
+  llvm::sys::path::native(NormalizedStatPath);
+  StatPath = NormalizedStatPath.c_str();
+}
 #endif
 
+if (!StatPath)
+  StatPath = Path;
+
 auto fileType = IsFile ?
   llvm::sys::fs::file_type::regular_file :
   llvm::sys::fs::file_type::directory_file;
-llvm::vfs::Status Status(Path, llvm::sys::fs::UniqueID(1, INode),
+llvm::vfs::Status Status(StatPath, llvm::sys::fs::UniqueID(1, INode),
  /*MTime*/{}, /*User*/0, /*Group*/0,
  /*Size*/0, fileType,
  llvm::sys::fs::perms::all_all);
@@ -47,13 +58,14 @@
 
 public:
   // Inject a file with the given inode value to the fake file system.
-  void InjectFile(const char *Path, ino_t INode) {
-InjectFileOrDirectory(Path, INode, /*IsFile=*/true);
+  void InjectFile(const char *Path, ino_t INode,
+  const char *StatPath = nullptr) {
+InjectFileOrDirectory(Path, INode, /*IsFile=*/true, StatPath);
   }
 
   // Inject a directory with the given inode value to the fake file system.
   void InjectDirectory(const char *Path, ino_t INode) {
-InjectFileOrDirectory(Path, INode, /*IsFile=*/false);
+InjectFileOrDirectory(Path, INode, /*IsFile=*/false, nullptr);
   }
 
   // Implement FileSystemStatCache::getStat().
@@ -249,6 +261,59 @@
 
   EXPECT_EQ(f1 ? *f1 : nullptr,
 f2 ? *f2 : nullptr);
+
+  // Check that getFileRef also does the right thing.
+  auto r1 = manager.getFileRef("abc/foo.cpp");
+  auto r2 = manager.getFileRef("abc/bar.cpp");
+  ASSERT_FALSE(!r1);
+  ASSERT_FALSE(!r2);
+
+  EXPECT_EQ("abc/foo.cpp", r1->getName());
+  EXPECT_EQ("abc/bar.cpp", r2->getName());
+  EXPECT_EQ((f1 ? *f1 : nullptr), >getFileEntry());
+  EXPECT_EQ((f2 ? *f2 : nullptr), >getFileEntry());
+}
+
+TEST_F(FileManagerTest, getFileRefReturnsCorrectNameForDifferentStatPath) {
+  // Inject files with the same inode, but where some files have a stat that
+  // gives a different name. This is adding coverage for weird stat behaviour
+  // triggered by the RedirectingFileSystem that FileManager::getFileRef has
+  // special logic for.
+  auto StatCache = std::make_unique();
+  StatCache->InjectDirectory("dir", 40);
+  StatCache->InjectFile("dir/f1.cpp", 41);
+  StatCache->InjectFile("dir/f1-alias.cpp", 41, "dir/f1.cpp");
+  StatCache->InjectFile("dir/f2.cpp", 42);
+  StatCache->InjectFile("dir/f2-alias.cpp", 42, "dir/f2.cpp");
+  manager.setStatCache(std::move(StatCache));
+
+  // With F2, test accessing the non-redirected name first.
+  auto F1 = manager.getFileRef("dir/f1.cpp");
+  auto F1Alias = manager.getFileRef("dir/f1-alias.cpp");
+  auto F1Alias2 = manager.getFileRef("dir/f1-alias.cpp");
+  ASSERT_FALSE(!F1);
+  ASSERT_FALSE(!F1Alias);
+  ASSERT_FALSE(!F1Alias2);
+  EXPECT_EQ("dir/f1.cpp", F1->getName());
+  EXPECT_EQ("dir/f1.cpp", F1->getFileEntry().getName());
+  EXPECT_EQ("dir/f1.cpp", F1Alias->getName());
+  EXPECT_EQ("dir/f1.cpp", F1Alias2->getName());
+  EXPECT_EQ(>getFileEntry(), >getFileEntry());
+  EXPECT_EQ(>getFileEntry(), >getFileEntry());
+
+  // With F2, test accessing the redirected name first.
+  auto F2Alias = manager.getFileRef("dir/f2-alias.cpp");
+  auto F2 = manager.getFileRef("dir/f2.cpp");
+  auto F2Alias2 = manager.getFileRef("dir/f2-alias.cpp");
+  ASSERT_FALSE(!F2);
+  ASSERT_FALSE(!F2Alias);
+  ASSERT_FALSE(!F2Alias2);
+  EXPECT_EQ("dir/f2.cpp", F2->getName());
+  EXPECT_EQ("dir/f2.cpp", F2->getFileEntry().getName());
+  EXPECT_EQ("dir/f2.cpp", F2Alias->getName());
+  EXPECT_EQ("dir/f2.cpp", F2Alias2->getName());
+  EXPECT_EQ(>getFileEntry(), >getFileEntry());
+  EXPECT_EQ(>getFileEntry(), >getFileEntry());
 }
 
 // getFile() returns the same FileEntry for virtual 

[clang] 729d7d2 - FileManager: Test FileManager::getFileRef

2020-10-20 Thread Duncan P . N . Exon Smith via cfe-commits

Author: Duncan P. N. Exon Smith
Date: 2020-10-20T13:40:23-04:00
New Revision: 729d7d23282e9b00eaa7a5f35a4224929d73d3a4

URL: 
https://github.com/llvm/llvm-project/commit/729d7d23282e9b00eaa7a5f35a4224929d73d3a4
DIFF: 
https://github.com/llvm/llvm-project/commit/729d7d23282e9b00eaa7a5f35a4224929d73d3a4.diff

LOG: FileManager: Test FileManager::getFileRef

Add a test demonstrating `getFileRef`'s behaviour, which isn't obvious
from code inspection when it's handling a redirected file.

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

Added: 


Modified: 
clang/unittests/Basic/FileManagerTest.cpp

Removed: 




diff  --git a/clang/unittests/Basic/FileManagerTest.cpp 
b/clang/unittests/Basic/FileManagerTest.cpp
index 9195cc008855..dfb79b477be9 100644
--- a/clang/unittests/Basic/FileManagerTest.cpp
+++ b/clang/unittests/Basic/FileManagerTest.cpp
@@ -28,17 +28,28 @@ class FakeStatCache : public FileSystemStatCache {
   // not in this map is considered to not exist in the file system.
   llvm::StringMap StatCalls;
 
-  void InjectFileOrDirectory(const char *Path, ino_t INode, bool IsFile) {
+  void InjectFileOrDirectory(const char *Path, ino_t INode, bool IsFile,
+ const char *StatPath) {
 #ifndef _WIN32
 SmallString<128> NormalizedPath(Path);
 llvm::sys::path::native(NormalizedPath);
 Path = NormalizedPath.c_str();
+
+SmallString<128> NormalizedStatPath;
+if (StatPath) {
+  NormalizedStatPath = StatPath;
+  llvm::sys::path::native(NormalizedStatPath);
+  StatPath = NormalizedStatPath.c_str();
+}
 #endif
 
+if (!StatPath)
+  StatPath = Path;
+
 auto fileType = IsFile ?
   llvm::sys::fs::file_type::regular_file :
   llvm::sys::fs::file_type::directory_file;
-llvm::vfs::Status Status(Path, llvm::sys::fs::UniqueID(1, INode),
+llvm::vfs::Status Status(StatPath, llvm::sys::fs::UniqueID(1, INode),
  /*MTime*/{}, /*User*/0, /*Group*/0,
  /*Size*/0, fileType,
  llvm::sys::fs::perms::all_all);
@@ -47,13 +58,14 @@ class FakeStatCache : public FileSystemStatCache {
 
 public:
   // Inject a file with the given inode value to the fake file system.
-  void InjectFile(const char *Path, ino_t INode) {
-InjectFileOrDirectory(Path, INode, /*IsFile=*/true);
+  void InjectFile(const char *Path, ino_t INode,
+  const char *StatPath = nullptr) {
+InjectFileOrDirectory(Path, INode, /*IsFile=*/true, StatPath);
   }
 
   // Inject a directory with the given inode value to the fake file system.
   void InjectDirectory(const char *Path, ino_t INode) {
-InjectFileOrDirectory(Path, INode, /*IsFile=*/false);
+InjectFileOrDirectory(Path, INode, /*IsFile=*/false, nullptr);
   }
 
   // Implement FileSystemStatCache::getStat().
@@ -249,6 +261,59 @@ TEST_F(FileManagerTest, 
getFileReturnsSameFileEntryForAliasedRealFiles) {
 
   EXPECT_EQ(f1 ? *f1 : nullptr,
 f2 ? *f2 : nullptr);
+
+  // Check that getFileRef also does the right thing.
+  auto r1 = manager.getFileRef("abc/foo.cpp");
+  auto r2 = manager.getFileRef("abc/bar.cpp");
+  ASSERT_FALSE(!r1);
+  ASSERT_FALSE(!r2);
+
+  EXPECT_EQ("abc/foo.cpp", r1->getName());
+  EXPECT_EQ("abc/bar.cpp", r2->getName());
+  EXPECT_EQ((f1 ? *f1 : nullptr), >getFileEntry());
+  EXPECT_EQ((f2 ? *f2 : nullptr), >getFileEntry());
+}
+
+TEST_F(FileManagerTest, getFileRefReturnsCorrectNameForDifferentStatPath) {
+  // Inject files with the same inode, but where some files have a stat that
+  // gives a 
diff erent name. This is adding coverage for weird stat behaviour
+  // triggered by the RedirectingFileSystem that FileManager::getFileRef has
+  // special logic for.
+  auto StatCache = std::make_unique();
+  StatCache->InjectDirectory("dir", 40);
+  StatCache->InjectFile("dir/f1.cpp", 41);
+  StatCache->InjectFile("dir/f1-alias.cpp", 41, "dir/f1.cpp");
+  StatCache->InjectFile("dir/f2.cpp", 42);
+  StatCache->InjectFile("dir/f2-alias.cpp", 42, "dir/f2.cpp");
+  manager.setStatCache(std::move(StatCache));
+
+  // With F2, test accessing the non-redirected name first.
+  auto F1 = manager.getFileRef("dir/f1.cpp");
+  auto F1Alias = manager.getFileRef("dir/f1-alias.cpp");
+  auto F1Alias2 = manager.getFileRef("dir/f1-alias.cpp");
+  ASSERT_FALSE(!F1);
+  ASSERT_FALSE(!F1Alias);
+  ASSERT_FALSE(!F1Alias2);
+  EXPECT_EQ("dir/f1.cpp", F1->getName());
+  EXPECT_EQ("dir/f1.cpp", F1->getFileEntry().getName());
+  EXPECT_EQ("dir/f1.cpp", F1Alias->getName());
+  EXPECT_EQ("dir/f1.cpp", F1Alias2->getName());
+  EXPECT_EQ(>getFileEntry(), >getFileEntry());
+  EXPECT_EQ(>getFileEntry(), >getFileEntry());
+
+  // With F2, test accessing the redirected name first.
+  auto F2Alias = manager.getFileRef("dir/f2-alias.cpp");
+  auto F2 = manager.getFileRef("dir/f2.cpp");
+  auto F2Alias2 = 

[PATCH] D89429: clang/Basic: Replace SourceManager::getMemoryBufferForFile, NFC

2020-10-20 Thread Jonas Devlieghere via Phabricator via cfe-commits
JDevlieghere accepted this revision.
JDevlieghere added a comment.

Thanks for the explanation!


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

https://reviews.llvm.org/D89429

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


[PATCH] D89427: clang/Frontend: Use MemoryBufferRef in FrontendInputFile (and remove SourceManager::getBuffer)

2020-10-20 Thread Duncan P. N. Exon Smith via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG51d1d585e583: clang/Frontend: Use MemoryBufferRef in 
FrontendInputFile (and remove… (authored by dexonsmith).
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89427

Files:
  clang/include/clang/Basic/SourceManager.h
  clang/include/clang/Frontend/FrontendAction.h
  clang/include/clang/Frontend/FrontendOptions.h
  clang/lib/Basic/SourceManager.cpp
  clang/lib/Format/MacroExpander.cpp
  clang/lib/Frontend/ASTUnit.cpp
  clang/lib/Frontend/CompilerInstance.cpp
  clang/lib/Frontend/FrontendAction.cpp
  clang/lib/Frontend/FrontendActions.cpp
  clang/unittests/Format/TestLexer.h

Index: clang/unittests/Format/TestLexer.h
===
--- clang/unittests/Format/TestLexer.h
+++ clang/unittests/Format/TestLexer.h
@@ -62,8 +62,8 @@
   TokenList lex(llvm::StringRef Code) {
 Buffers.push_back(
 llvm::MemoryBuffer::getMemBufferCopy(Code, ""));
-clang::FileID FID = SourceMgr.get().createFileID(SourceManager::Unowned,
- Buffers.back().get());
+clang::FileID FID =
+SourceMgr.get().createFileID(Buffers.back()->getMemBufferRef());
 FormatTokenLexer Lex(SourceMgr.get(), FID, 0, Style, Encoding, Allocator,
  IdentTable);
 auto Result = Lex.lex();
Index: clang/lib/Frontend/FrontendActions.cpp
===
--- clang/lib/Frontend/FrontendActions.cpp
+++ clang/lib/Frontend/FrontendActions.cpp
@@ -261,7 +261,7 @@
 if (FIF.getKind().getFormat() != InputKind::Source || !FIF.isFile()) {
   CI.getDiagnostics().Report(diag::err_module_header_file_not_found)
   << (FIF.isFile() ? FIF.getFile()
-   : FIF.getBuffer()->getBufferIdentifier());
+   : FIF.getBuffer().getBufferIdentifier());
   return true;
 }
 
@@ -275,7 +275,8 @@
 
   // Set that buffer up as our "real" input.
   Inputs.clear();
-  Inputs.push_back(FrontendInputFile(Buffer.get(), Kind, /*IsSystem*/false));
+  Inputs.push_back(
+  FrontendInputFile(Buffer->getMemBufferRef(), Kind, /*IsSystem*/ false));
 
   return GenerateModuleAction::PrepareToExecuteAction(CI);
 }
Index: clang/lib/Frontend/FrontendAction.cpp
===
--- clang/lib/Frontend/FrontendAction.cpp
+++ clang/lib/Frontend/FrontendAction.cpp
@@ -624,7 +624,7 @@
   if (auto *File = OldSM.getFileEntryForID(ID))
 Input = FrontendInputFile(File->getName(), Kind);
   else
-Input = FrontendInputFile(OldSM.getBuffer(ID), Kind);
+Input = FrontendInputFile(OldSM.getBufferOrFake(ID), Kind);
 }
 setCurrentInput(Input, std::move(AST));
   }
Index: clang/lib/Frontend/CompilerInstance.cpp
===
--- clang/lib/Frontend/CompilerInstance.cpp
+++ clang/lib/Frontend/CompilerInstance.cpp
@@ -831,8 +831,7 @@
   : Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User;
 
   if (Input.isBuffer()) {
-SourceMgr.setMainFileID(SourceMgr.createFileID(SourceManager::Unowned,
-   Input.getBuffer(), Kind));
+SourceMgr.setMainFileID(SourceMgr.createFileID(Input.getBuffer(), Kind));
 assert(SourceMgr.getMainFileID().isValid() &&
"Couldn't establish MainFileID!");
 return true;
Index: clang/lib/Frontend/ASTUnit.cpp
===
--- clang/lib/Frontend/ASTUnit.cpp
+++ clang/lib/Frontend/ASTUnit.cpp
@@ -1468,7 +1468,7 @@
 if (Input.isFile())
   return Input.getFile();
 else
-  return Input.getBuffer()->getBufferIdentifier();
+  return Input.getBuffer().getBufferIdentifier();
   }
 
   if (SourceMgr) {
Index: clang/lib/Format/MacroExpander.cpp
===
--- clang/lib/Format/MacroExpander.cpp
+++ clang/lib/Format/MacroExpander.cpp
@@ -136,8 +136,7 @@
 void MacroExpander::parseDefinition(const std::string ) {
   Buffers.push_back(
   llvm::MemoryBuffer::getMemBufferCopy(Macro, ""));
-  clang::FileID FID =
-  SourceMgr.createFileID(SourceManager::Unowned, Buffers.back().get());
+  clang::FileID FID = SourceMgr.createFileID(Buffers.back()->getMemBufferRef());
   FormatTokenLexer Lex(SourceMgr, FID, 0, Style, encoding::Encoding_UTF8,
Allocator, IdentTable);
   const auto Tokens = Lex.lex();
Index: clang/lib/Basic/SourceManager.cpp
===
--- clang/lib/Basic/SourceManager.cpp
+++ clang/lib/Basic/SourceManager.cpp
@@ -443,14 +443,13 @@
 
 /// Create a new ContentCache for the specified memory buffer.
 

[PATCH] D89752: [CUDA] Improve clang's ability to detect recent CUDA versions.

2020-10-20 Thread Artem Belevich via Phabricator via cfe-commits
tra updated this revision to Diff 299410.
tra marked 2 inline comments as done.
tra added a comment.

addresses review comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89752

Files:
  clang/lib/Driver/ToolChains/Cuda.cpp
  clang/test/Driver/Inputs/CUDA_111/usr/local/cuda/bin/.keep
  clang/test/Driver/Inputs/CUDA_111/usr/local/cuda/include/.keep
  clang/test/Driver/Inputs/CUDA_111/usr/local/cuda/lib/.keep
  clang/test/Driver/Inputs/CUDA_111/usr/local/cuda/lib64/.keep
  
clang/test/Driver/Inputs/CUDA_111/usr/local/cuda/nvvm/libdevice/libdevice.10.bc
  clang/test/Driver/cuda-version-check.cu


Index: clang/test/Driver/cuda-version-check.cu
===
--- clang/test/Driver/cuda-version-check.cu
+++ clang/test/Driver/cuda-version-check.cu
@@ -10,6 +10,11 @@
 // RUN:FileCheck %s --check-prefix=OK
 // RUN: %clang --target=x86_64-linux -v -### --cuda-gpu-arch=sm_60 
--cuda-path=%S/Inputs/CUDA-unknown/usr/local/cuda 2>&1 %s | \
 // RUN:FileCheck %s --check-prefix=UNKNOWN_VERSION
+// CUDA versions after 11.0 (update 1) do not carry version.txt file. Make sure
+// we still detect them as a new version and handle them the same as we handle
+// other new CUDA versions.
+// RUN: %clang --target=x86_64-linux -v -### --cuda-gpu-arch=sm_60 
--cuda-path=%S/Inputs/CUDA_111/usr/local/cuda 2>&1 %s | \
+// RUN:FileCheck %s --check-prefix=UNKNOWN_VERSION
 // Make sure that we don't warn about CUDA version during C++ compilation.
 // RUN: %clang --target=x86_64-linux -v -### -x c++ --cuda-gpu-arch=sm_60 \
 // RUN:--cuda-path=%S/Inputs/CUDA-unknown/usr/local/cuda 2>&1 %s | \
@@ -65,5 +70,5 @@
 // ERR_SM61: error: GPU arch sm_61 {{.*}}
 // ERR_SM61-NOT: error: GPU arch sm_61
 
-// UNKNOWN_VERSION: Unknown CUDA version 999.999. Assuming the latest 
supported version
+// UNKNOWN_VERSION: Unknown CUDA version {{.*}}. Assuming the latest supported 
version
 // UNKNOWN_VERSION_CXX-NOT: Unknown CUDA version
Index: clang/lib/Driver/ToolChains/Cuda.cpp
===
--- clang/lib/Driver/ToolChains/Cuda.cpp
+++ clang/lib/Driver/ToolChains/Cuda.cpp
@@ -155,9 +155,14 @@
 llvm::ErrorOr> VersionFile =
 FS.getBufferForFile(InstallPath + "/version.txt");
 if (!VersionFile) {
-  // CUDA 7.0 doesn't have a version.txt, so guess that's our version if
-  // version.txt isn't present.
-  Version = CudaVersion::CUDA_70;
+  // CUDA 7.0 and CUDA 11.1+ do not have version.txt file.
+  // Use libdevice file to distinguish 7.0 from the new versions.
+  if (FS.exists(LibDevicePath + "/libdevice.10.bc")) {
+Version = CudaVersion::LATEST;
+DetectedVersionIsNotSupported = Version > 
CudaVersion::LATEST_SUPPORTED;
+  } else {
+Version = CudaVersion::CUDA_70;
+  }
 } else {
   ParseCudaVersionFile((*VersionFile)->getBuffer());
 }


Index: clang/test/Driver/cuda-version-check.cu
===
--- clang/test/Driver/cuda-version-check.cu
+++ clang/test/Driver/cuda-version-check.cu
@@ -10,6 +10,11 @@
 // RUN:FileCheck %s --check-prefix=OK
 // RUN: %clang --target=x86_64-linux -v -### --cuda-gpu-arch=sm_60 --cuda-path=%S/Inputs/CUDA-unknown/usr/local/cuda 2>&1 %s | \
 // RUN:FileCheck %s --check-prefix=UNKNOWN_VERSION
+// CUDA versions after 11.0 (update 1) do not carry version.txt file. Make sure
+// we still detect them as a new version and handle them the same as we handle
+// other new CUDA versions.
+// RUN: %clang --target=x86_64-linux -v -### --cuda-gpu-arch=sm_60 --cuda-path=%S/Inputs/CUDA_111/usr/local/cuda 2>&1 %s | \
+// RUN:FileCheck %s --check-prefix=UNKNOWN_VERSION
 // Make sure that we don't warn about CUDA version during C++ compilation.
 // RUN: %clang --target=x86_64-linux -v -### -x c++ --cuda-gpu-arch=sm_60 \
 // RUN:--cuda-path=%S/Inputs/CUDA-unknown/usr/local/cuda 2>&1 %s | \
@@ -65,5 +70,5 @@
 // ERR_SM61: error: GPU arch sm_61 {{.*}}
 // ERR_SM61-NOT: error: GPU arch sm_61
 
-// UNKNOWN_VERSION: Unknown CUDA version 999.999. Assuming the latest supported version
+// UNKNOWN_VERSION: Unknown CUDA version {{.*}}. Assuming the latest supported version
 // UNKNOWN_VERSION_CXX-NOT: Unknown CUDA version
Index: clang/lib/Driver/ToolChains/Cuda.cpp
===
--- clang/lib/Driver/ToolChains/Cuda.cpp
+++ clang/lib/Driver/ToolChains/Cuda.cpp
@@ -155,9 +155,14 @@
 llvm::ErrorOr> VersionFile =
 FS.getBufferForFile(InstallPath + "/version.txt");
 if (!VersionFile) {
-  // CUDA 7.0 doesn't have a version.txt, so guess that's our version if
-  // version.txt isn't present.
-  Version = CudaVersion::CUDA_70;
+  // CUDA 7.0 and CUDA 11.1+ do not have version.txt file.
+  // Use libdevice file to 

[PATCH] D89752: [CUDA] Improve clang's ability to detect recent CUDA versions.

2020-10-20 Thread Artem Belevich via Phabricator via cfe-commits
tra added inline comments.



Comment at: clang/lib/Driver/ToolChains/Cuda.cpp:161
+  if (FS.exists(LibDevicePath + "/libdevice.10.bc")) {
+Version = CudaVersion::LATEST;
+DetectedVersionIsNotSupported = Version > 
CudaVersion::LATEST_SUPPORTED;

emankov wrote:
> Do we have any other mechanism besides version.txt for determining an exact 
> CUDA version? Setting the latest version in case of absence of version.txt 
> doesn't suit all the needs: sometimes the exact version is taken into 
> account, for instance in [[ 
> https://github.com/ROCm-Developer-Tools/HIPIFY#clang | hipify-clang ]].
Not easily. 

We could try running one of SDK binaries with `--version`. This would be 
fragile as the tool version does not necessarily match the SDK's  and NVIDIA 
has already started versioning elements per-component. E.g. some shared 
libraries in 11.1 are already versioned as 10.2, 11.0, 11.1 and 11.2. There are 
also situations when we had to cherry-pick a tool from a different release in 
order to work around a critical bug. We don't want to change compiler's idea of 
CUDA version based on that.

We could parse CUDA headers and try finding CUDA_VERSION macro. That's 
feasible. It may be somewhat fragile if we just search for a text string 
'#define CUDA_VERSION ' -- nvidia may change it. On the other hand it's not 
that much worse than relying on version.txt.  It also does not carry complete 
version, only major.minor, so we will not be able to tell `11.0 `apart from 
`11.0 update 1`. Probably not a big deal. I don't think we've needed it so far.

We could do something like this:
* if version.txt is there -- use it
* otherwise if cuda.h is found, extract version from CUDA_VERSION macro
* if that failed, use libdevice bitcode format to detect CUDA-7.0
* fall back to "last supported version" otherwise



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89752

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


[clang] 51d1d58 - clang/Frontend: Use MemoryBufferRef in FrontendInputFile (and remove SourceManager::getBuffer)

2020-10-20 Thread Duncan P . N . Exon Smith via cfe-commits

Author: Duncan P. N. Exon Smith
Date: 2020-10-20T13:35:46-04:00
New Revision: 51d1d585e5838ea0f02f1271f7543c4e43639969

URL: 
https://github.com/llvm/llvm-project/commit/51d1d585e5838ea0f02f1271f7543c4e43639969
DIFF: 
https://github.com/llvm/llvm-project/commit/51d1d585e5838ea0f02f1271f7543c4e43639969.diff

LOG: clang/Frontend: Use MemoryBufferRef in FrontendInputFile (and remove 
SourceManager::getBuffer)

In order to drop the final callers to `SourceManager::getBuffer`, change
`FrontendInputFile` to use `Optional`. Also updated
the "unowned" version of `SourceManager::createFileID` to take a
`MemoryBufferRef` (it now calls `MemoryBuffer::getMemBuffer`, which
creates a `MemoryBuffer` that does not own the buffer data).

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

Added: 


Modified: 
clang/include/clang/Basic/SourceManager.h
clang/include/clang/Frontend/FrontendAction.h
clang/include/clang/Frontend/FrontendOptions.h
clang/lib/Basic/SourceManager.cpp
clang/lib/Format/MacroExpander.cpp
clang/lib/Frontend/ASTUnit.cpp
clang/lib/Frontend/CompilerInstance.cpp
clang/lib/Frontend/FrontendAction.cpp
clang/lib/Frontend/FrontendActions.cpp
clang/unittests/Format/TestLexer.h

Removed: 




diff  --git a/clang/include/clang/Basic/SourceManager.h 
b/clang/include/clang/Basic/SourceManager.h
index 2156a013e53b..e1b510bab07c 100644
--- a/clang/include/clang/Basic/SourceManager.h
+++ b/clang/include/clang/Basic/SourceManager.h
@@ -860,13 +860,11 @@ class SourceManager : public 
RefCountedBase {
   int LoadedID = 0, unsigned LoadedOffset = 0,
   SourceLocation IncludeLoc = SourceLocation());
 
-  enum UnownedTag { Unowned };
-
   /// Create a new FileID that represents the specified memory buffer.
   ///
   /// This does not take ownership of the MemoryBuffer. The memory buffer must
   /// outlive the SourceManager.
-  FileID createFileID(UnownedTag, const llvm::MemoryBuffer *Buffer,
+  FileID createFileID(const llvm::MemoryBufferRef ,
   SrcMgr::CharacteristicKind FileCharacter = 
SrcMgr::C_User,
   int LoadedID = 0, unsigned LoadedOffset = 0,
   SourceLocation IncludeLoc = SourceLocation());
@@ -991,36 +989,6 @@ class SourceManager : public RefCountedBase 
{
 return getFakeBufferForRecovery()->getMemBufferRef();
   }
 
-  /// Return the buffer for the specified FileID.
-  ///
-  /// If there is an error opening this buffer the first time, this
-  /// manufactures a temporary buffer and returns a non-empty error string.
-  ///
-  /// TODO: Update users of Invalid to call getBufferOrNone and change return
-  /// type to MemoryBufferRef.
-  const llvm::MemoryBuffer *getBuffer(FileID FID, SourceLocation Loc,
-  bool *Invalid = nullptr) const {
-bool MyInvalid = false;
-const SrcMgr::SLocEntry  = getSLocEntry(FID, );
-if (MyInvalid || !Entry.isFile()) {
-  if (Invalid)
-*Invalid = true;
-
-  return getFakeBufferForRecovery();
-}
-
-auto *B = Entry.getFile().getContentCache()->getBufferPointer(
-Diag, getFileManager(), Loc);
-if (Invalid)
-  *Invalid = !B;
-return B ? B : getFakeBufferForRecovery();
-  }
-
-  const llvm::MemoryBuffer *getBuffer(FileID FID,
-  bool *Invalid = nullptr) const {
-return getBuffer(FID, SourceLocation(), Invalid);
-  }
-
   /// Returns the FileEntry record for the provided FileID.
   const FileEntry *getFileEntryForID(FileID FID) const {
 bool MyInvalid = false;
@@ -1844,7 +1812,7 @@ class SourceManager : public 
RefCountedBase {
 
   /// Create a new ContentCache for the specified  memory buffer.
   const SrcMgr::ContentCache *
-  createMemBufferContentCache(const llvm::MemoryBuffer *Buf, bool DoNotFree);
+  createMemBufferContentCache(std::unique_ptr Buf);
 
   FileID getFileIDSlow(unsigned SLocOffset) const;
   FileID getFileIDLocal(unsigned SLocOffset) const;

diff  --git a/clang/include/clang/Frontend/FrontendAction.h 
b/clang/include/clang/Frontend/FrontendAction.h
index c9f9f080c141..319b3bc62cc4 100644
--- a/clang/include/clang/Frontend/FrontendAction.h
+++ b/clang/include/clang/Frontend/FrontendAction.h
@@ -145,7 +145,7 @@ class FrontendAction {
 assert(!CurrentInput.isEmpty() && "No current file!");
 return CurrentInput.isFile()
? CurrentInput.getFile()
-   : CurrentInput.getBuffer()->getBufferIdentifier();
+   : CurrentInput.getBuffer().getBufferIdentifier();
   }
 
   InputKind getCurrentFileKind() const {

diff  --git a/clang/include/clang/Frontend/FrontendOptions.h 
b/clang/include/clang/Frontend/FrontendOptions.h
index b2be33032c08..51dc3a0dc7f1 100644
--- a/clang/include/clang/Frontend/FrontendOptions.h
+++ b/clang/include/clang/Frontend/FrontendOptions.h
@@ 

[PATCH] D89743: Support Attr in DynTypedNode and ASTMatchers.

2020-10-20 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D89743#2341900 , @sammccall wrote:

> In D89743#2341779 , @aaron.ballman 
> wrote:
>
>> This is *awesome*, thank you so much for working on it!
>
> Thanks for the comments - haven't addressed them yet, but wanted to clarify 
> scope first.
>
>> One question I have is: as it stands, this is not a particularly useful 
>> matcher because it can only be used to say "yup, there's an attribute"
>
> Yes definitely, I should have mentioned this...
>
> My main goal here was to support it in DynTypedNode, as we have APIs 
> (clangd::SelectionTree) that can only handle nodes that fit there.
> But the common test pattern in ASTTypeTraitsTest used matchers, and I figured 
> a basic matcher wasn't hard to add.

Okay, that makes sense to me.

>> are you planning to extend this functionality so that you can do something 
>> like `attr(hasName("foo"))`, or specify the syntax the attribute uses, 
>> `isImplicit()`, etc?
>
> I hadn't planned to - it definitely makes sense though I don't have any 
> immediate use cases. I can do any of:
>
> - leave as-is, waiting for someone to add matchers to make it useful
> - scope down the patch to exclude the matcher (and write the 
> ASTTypeTraitsTest another way)
> - add some simple matcher like hasName (I guess in a followup patch) to make 
> it minimally useful, with space for more
>
> What do you think?

My preference is to add support for `hasName()` as that's going to be the most 
common need for matching attributes. If you also added support for matching 
which syntax is used, support attributes for `hasArgument()` (which I suppose 
could be interesting given that there are the parsed attribute arguments and 
the semantic attribute arguments, and they may differ), etc, I certainly 
wouldn't complain, but I think at least name matching support is required to 
make the matcher marginally useful. I'm totally fine if this happens in a 
follow-up patch (or patches). WDYT?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89743

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


[PATCH] D88659: [FE]Split SuitableAlign into two parts

2020-10-20 Thread Xiangling Liao via Phabricator via cfe-commits
Xiangling_L updated this revision to Diff 299404.
Xiangling_L added a comment.
Herald added a subscriber: dexonsmith.

Edit the definition of `SuitableAlign`;


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

https://reviews.llvm.org/D88659

Files:
  clang/include/clang/Basic/TargetInfo.h


Index: clang/include/clang/Basic/TargetInfo.h
===
--- clang/include/clang/Basic/TargetInfo.h
+++ clang/include/clang/Basic/TargetInfo.h
@@ -581,8 +581,9 @@
   /// Determine whether constrained floating point is supported on this target.
   virtual bool hasStrictFP() const { return HasStrictFP; }
 
-  /// Return the alignment that is suitable for storing any
-  /// object with a fundamental alignment requirement.
+  /// Return the alignment that is the largest alignment ever used for any
+  /// scalar/SIMD data type on the target machine you are compiling for
+  /// (including types with an extended alignment requirement).
   unsigned getSuitableAlign() const { return SuitableAlign; }
 
   /// Return the default alignment for __attribute__((aligned)) on


Index: clang/include/clang/Basic/TargetInfo.h
===
--- clang/include/clang/Basic/TargetInfo.h
+++ clang/include/clang/Basic/TargetInfo.h
@@ -581,8 +581,9 @@
   /// Determine whether constrained floating point is supported on this target.
   virtual bool hasStrictFP() const { return HasStrictFP; }
 
-  /// Return the alignment that is suitable for storing any
-  /// object with a fundamental alignment requirement.
+  /// Return the alignment that is the largest alignment ever used for any
+  /// scalar/SIMD data type on the target machine you are compiling for
+  /// (including types with an extended alignment requirement).
   unsigned getSuitableAlign() const { return SuitableAlign; }
 
   /// Return the default alignment for __attribute__((aligned)) on
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D87528: Enable '#pragma STDC FENV_ACCESS' in frontend cf. D69272 - Work in Progress

2020-10-20 Thread Melanie Blower via Phabricator via cfe-commits
mibintc marked 2 inline comments as done.
mibintc added a comment.

In D87528#2270541 , @rsmith wrote:

>> @rsmith asked "I don't see changes to the constant evaluator". The semantic 
>> rules for enabling this pragma require that strict or precise semantics be 
>> in effect., see SemaAttr.cpp And the floating point constant evaluation 
>> doesn't occur when strict or precise
>
> What do you mean "the floating point constant evaluation doesn't occur when 
> strict or precise"? I don't see any code to do that in `ExprConstant.cpp`, 
> neither in trunk nor in this patch. The constant evaluator certainly is still 
> invoked when we're in strict or precise mode. I would expect the evaluator 
> would need to check for FP strictness whenever it encounters a floating-point 
> operator (eg, here: 
> https://github.com/llvm/llvm-project/blob/master/clang/lib/AST/ExprConstant.cpp#L13340),
>  and treat such cases as non-constant.

1.0/3.0 is now static folded.  @rsmith Did you change your mind about this?  Is 
static folding what you want here?

> I'd like to see a C++ test for something like this:
>
>   float myAdd() {
>   #pragma STDC FENV_ACCESS ON
>   static double v = 1.0 / 3.0;
>   return v;
>   }
>
> If that generates a runtime guarded initialization for `v`, then I'd be a bit 
> more convinced we're getting this right.

Some inline comments, still owe you a list of test that fails.  check-clang 
runs clean with this patch




Comment at: clang/lib/AST/ExprConstant.cpp:2496-2498
+  if (llvm::APFloatBase::opOK != Result.convertFromAPInt(Value,
+   Value.isSigned(),
+   APFloat::rmNearestTiesToEven) &&

rsmith wrote:
> Following D89360, we should skip this check if `Info.InConstantContext`.
I tried making this change but I got about 30 lit fails, maybe my patch was 
incorrect. I'll rerun with the patch and post the list of fails. 



Comment at: clang/test/CodeGen/fp-floatcontrol-pragma.cpp:159
+  //CHECK: store float 3.0{{.*}}retval{{.*}}
+  static double v = 1.0 / 3.0;
+  //CHECK-FENV: llvm.experimental.constrained.fptrunc.f32.f64{{.*}}

@rsmith - the division is constant folded.  is that right? 



Comment at: clang/test/Parser/pragma-fenv_access.c:28
+#if defined(CPP) & defined(STRICT)
+//not-expected-error@+3 {{constexpr variable 'frac' must be initialized by a 
constant expression}}
+//not-expected-note@+2 {{compile time floating point arithmetic suppressed in 
strict evaluation modes}}

@rsmith no diagnostic, is this OK?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87528

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


[PATCH] D83088: Introduce CfgTraits abstraction

2020-10-20 Thread Lei Zhang via Phabricator via cfe-commits
antiagainst added inline comments.



Comment at: mlir/include/mlir/IR/Dominance.h:49
+template <>
+struct llvm::CfgTraitsFor {
+  using CfgTraits = mlir::CfgTraits;

rriddle wrote:
> This seems to have broken the GCC5 build:
> https://buildkite.com/mlir/mlir-core/builds/8739#7a957564-9850-487c-a814-c6818890bd14
> 
> ```
> /mlir/include/mlir/IR/Dominance.h:49:14: error: specialization of 
> 'template struct llvm::CfgTraitsFor' in different 
> namespace [-fpermissive]
>  struct llvm::CfgTraitsFor {
>   ^
> In file included from mlir/include/mlir/IR/Dominance.h:13:0,
>  from mlir/lib/IR/Verifier.cpp:30:
> llvm/include/llvm/Support/CfgTraits.h:294:44: error:   from definition of 
> 'template struct llvm::CfgTraitsFor' [-fpermissive]
>  template  struct CfgTraitsFor;
> ```
Pushed 
https://github.com/llvm/llvm-project/commit/f2a06875b604c00cbe96e54363f4f5d28935d610


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83088

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


[PATCH] D83088: Introduce CfgTraits abstraction

2020-10-20 Thread River Riddle via Phabricator via cfe-commits
rriddle added inline comments.



Comment at: mlir/include/mlir/IR/Dominance.h:49
+template <>
+struct llvm::CfgTraitsFor {
+  using CfgTraits = mlir::CfgTraits;

This seems to have broken the GCC5 build:
https://buildkite.com/mlir/mlir-core/builds/8739#7a957564-9850-487c-a814-c6818890bd14

```
/mlir/include/mlir/IR/Dominance.h:49:14: error: specialization of 
'template struct llvm::CfgTraitsFor' in different 
namespace [-fpermissive]
 struct llvm::CfgTraitsFor {
  ^
In file included from mlir/include/mlir/IR/Dominance.h:13:0,
 from mlir/lib/IR/Verifier.cpp:30:
llvm/include/llvm/Support/CfgTraits.h:294:44: error:   from definition of 
'template struct llvm::CfgTraitsFor' [-fpermissive]
 template  struct CfgTraitsFor;
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D83088

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


[PATCH] D87528: Enable '#pragma STDC FENV_ACCESS' in frontend cf. D69272 - Work in Progress

2020-10-20 Thread Melanie Blower via Phabricator via cfe-commits
mibintc updated this revision to Diff 299395.
mibintc added a comment.
Herald added a reviewer: aaron.ballman.
Herald added a subscriber: dexonsmith.

I added StrictFPAttr clang function attribute accroding to @rjmccall 's 
suggestion instead of using a boolean on the function decl, rebased, and 
responded to other code review comments. will add replies inline


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D87528

Files:
  clang/docs/UsersManual.rst
  clang/include/clang/AST/Decl.h
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/DiagnosticASTKinds.td
  clang/include/clang/Basic/DiagnosticParseKinds.td
  clang/include/clang/Basic/LangOptions.h
  clang/include/clang/Sema/ScopeInfo.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/ExprConstant.cpp
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/lib/CodeGen/CodeGenModule.h
  clang/lib/Parse/ParsePragma.cpp
  clang/lib/Parse/ParseStmt.cpp
  clang/lib/Sema/ScopeInfo.cpp
  clang/lib/Sema/SemaAttr.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaStmt.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/lib/Serialization/ASTReaderDecl.cpp
  clang/lib/Serialization/ASTWriterDecl.cpp
  clang/test/CXX/expr/expr.const/p2-0x.cpp
  clang/test/CodeGen/fp-floatcontrol-pragma.cpp
  clang/test/CodeGen/pragma-fenv_access.c
  clang/test/Parser/fp-floatcontrol-syntax.cpp
  clang/test/Parser/pragma-fenv_access.c
  clang/test/Preprocessor/pragma_unknown.c

Index: clang/test/Preprocessor/pragma_unknown.c
===
--- clang/test/Preprocessor/pragma_unknown.c
+++ clang/test/Preprocessor/pragma_unknown.c
@@ -16,15 +16,6 @@
 // CHECK: {{^}}#pragma STDC FP_CONTRACT DEFAULT{{$}}
 // CHECK: {{^}}#pragma STDC FP_CONTRACT IN_BETWEEN{{$}}
 
-#pragma STDC FENV_ACCESS ON  // expected-warning {{pragma STDC FENV_ACCESS ON is not supported, ignoring pragma}}
-#pragma STDC FENV_ACCESS OFF
-#pragma STDC FENV_ACCESS DEFAULT
-#pragma STDC FENV_ACCESS IN_BETWEEN   // expected-warning {{expected 'ON' or 'OFF' or 'DEFAULT' in pragma}}
-// CHECK: {{^}}#pragma STDC FENV_ACCESS ON{{$}}
-// CHECK: {{^}}#pragma STDC FENV_ACCESS OFF{{$}}
-// CHECK: {{^}}#pragma STDC FENV_ACCESS DEFAULT{{$}}
-// CHECK: {{^}}#pragma STDC FENV_ACCESS IN_BETWEEN{{$}}
-
 #pragma STDC CX_LIMITED_RANGE ON
 #pragma STDC CX_LIMITED_RANGE OFF
 #pragma STDC CX_LIMITED_RANGE DEFAULT 
Index: clang/test/Parser/pragma-fenv_access.c
===
--- /dev/null
+++ clang/test/Parser/pragma-fenv_access.c
@@ -0,0 +1,46 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+// RUN: %clang_cc1 -ffp-exception-behavior=strict -DSTRICT -fsyntax-only -verify %s
+// RUN: %clang_cc1 -x c++ -DCPP -DSTRICT -ffp-exception-behavior=strict -fsyntax-only -verify %s
+#ifdef CPP
+#define CONST constexpr
+#else
+#define CONST const
+#endif
+
+#pragma STDC FENV_ACCESS IN_BETWEEN   // expected-warning {{expected 'ON' or 'OFF' or 'DEFAULT' in pragma}}
+
+#pragma STDC FENV_ACCESS OFF
+
+float func_04(int x, float y) {
+  if (x)
+return y + 2;
+  #pragma STDC FENV_ACCESS ON // expected-error{{'#pragma STDC FENV_ACCESS' can only appear at file scope or at the start of a compound statement}}
+  return x + y;
+}
+
+#pragma STDC FENV_ACCESS ON
+int main() {
+  CONST float one = 1.0F ;
+  CONST float three = 3.0F ;
+  CONST float four = 4.0F ;
+  CONST float frac_ok = one/four;
+#if defined(CPP) & defined(STRICT)
+//not-expected-error@+3 {{constexpr variable 'frac' must be initialized by a constant expression}}
+//not-expected-note@+2 {{compile time floating point arithmetic suppressed in strict evaluation modes}}
+#endif
+  CONST float frac = one/three; // rounding
+  CONST double d = one;
+  CONST int not_too_big = 255;
+  CONST float fnot_too_big = not_too_big;
+  CONST int too_big = 0x7ff0;
+#if defined(CPP) & defined(STRICT)
+//expected-error@+6 {{constexpr variable 'fbig' must be initialized by a constant expression}}
+//expected-note@+5 {{compile time floating point arithmetic suppressed in strict evaluation modes}}
+#endif
+#if defined(CPP)
+//expected-warning@+2{{implicit conversion}}
+#endif
+  CONST float fbig = too_big; // inexact
+  if (one <= four)  return 0;
+  return -1;
+}
Index: clang/test/Parser/fp-floatcontrol-syntax.cpp
===
--- clang/test/Parser/fp-floatcontrol-syntax.cpp
+++ clang/test/Parser/fp-floatcontrol-syntax.cpp
@@ -26,19 +26,13 @@
 double a = 0.0;
 double b = 1.0;
 
-//FIXME At some point this warning will be removed, until then
-//  document the warning
-#ifdef FAST
-// expected-warning@+1{{pragma STDC FENV_ACCESS ON is not supported, ignoring pragma}}
-#pragma STDC FENV_ACCESS ON
-#else
-#pragma STDC FENV_ACCESS ON // expected-warning{{pragma STDC FENV_ACCESS ON is 

[PATCH] D89469: FileManager: Test FileManager::getFileRef

2020-10-20 Thread Alex Lorenz via Phabricator via cfe-commits
arphaman added a comment.

Thanks. Could you expand the comment in the test that this test path 
specifically exercises the behavior produced by the RedirectingFileSystem?


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

https://reviews.llvm.org/D89469

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


[PATCH] D89801: [SystemZ][z/OS] Set short-enums as the default for z/OS

2020-10-20 Thread Zbigniew Sarbinowski via Phabricator via cfe-commits
zibi added a comment.

LGTM, though not sure why comment is referencing -fshort-enums=0.
If '=0' is not significant perhaps delete it to remove confusion.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89801

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


[PATCH] D89801: [SystemZ][z/OS] Set short-enums as the default for z/OS

2020-10-20 Thread Sean via Phabricator via cfe-commits
SeanP added inline comments.



Comment at: clang/test/Driver/zos-driver-defaults.c:1
+// RUN: %clang -### --target=s390x-none-zos -fsyntax-only %s 2>&1 | FileCheck 
%s
+// REQUIRES: clang-driver

Can you add an additional test for -fno-short-enum to make sure that works too.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89801

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


[PATCH] D89372: [OpenCL] Remove unused extensions

2020-10-20 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia accepted this revision.
Anastasia added a comment.

LGTM! Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89372

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


[PATCH] D89372: [OpenCL] Remove unused extensions

2020-10-20 Thread Anastasia Stulova via Phabricator via cfe-commits
Anastasia added a comment.

In D89372#2341638 , @mantognini wrote:

> I don't want to stop the wider discussion, that being said I think I've 
> addressed the comment regarding the content of this PR. Let me know if the 
> latest version is fine or needs further addressing. Thanks.

Thank you for providing comprehensive information regarding the extensions 
being removed. Since there are no kernel language changes in those I still see 
no reason to keep them in clang!

However, regarding the discussion about the general extension mechanisms for 
the language changes, @jvesely would you be willing to describe your vision 
regarding extensions pragma on this issue 
https://github.com/KhronosGroup/OpenCL-Docs/issues/82? Or otherwise, would you 
be ok if I summarise it there? I think it would be useful to aggregate all the 
information before discussing future directions with Khronos.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D89372

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


[PATCH] D86671: [clang-tidy] Add new case type to check variables with Hungarian notation

2020-10-20 Thread Nathan James via Phabricator via cfe-commits
njames93 added a comment.

In D86671#2341838 , @dougpuob wrote:

> Hi @njames93,
>
> It's a smart idea, the rework for it is worth. There is a special case if 
> lowercase name with Hungarian prefix, it possibly makes variable ambiguous, 
> like the `Case1`. How about separating them and `aNy_CasE` with an 
> underscore, like `Case2` ?
>
>   // Case1
>   bool bRIGHT_LEVEL; // UPPER_CASE
>   bool bRightLevel;  // CamelCase
>   bool bRight_Level; // Camel_Snake_Case
>   bool baNy_CasE;// aNy_CasE
>   bool bright_level; // lower_case
>   bool brightLevel;  // camelBack
>   bool bright_Level; // camel_Snake_Back
>   .^^ <-- right? bright?
>   
>   // Case2
>   bool bRIGHT_LEVEL; // UPPER_CASE
>   bool bRightLevel;  // CamelCase
>   bool bRight_Level; // Camel_Snake_Case
>   bool b_aNy_CasE;   // aNy_CasE
>   bool b_right_level;// lower_case
>   bool b_rightLevel; // camelBack
>   bool b_right_Level;// camel_Snake_Back
>   .^^^ <-- add an underscore

That still has hidden surprises. Maybe instead of a bool, an enum is used for 
controlling hungarian prefix (Off|On|...).
Can't think of a good name for the third option but it would do the inserting 
of '_' (bright_level ->b_right_level) or capitalising the first word of the 
identifier (brightLevel -> bRightLevel).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D86671

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


[PATCH] D69903: [Basic] Introduce PODSourceLocation, NFCI

2020-10-20 Thread Mikhail Maltsev via Phabricator via cfe-commits
miyuki added a comment.

In D69903#2340020 , @dexonsmith wrote:

> An alternative would be to update the unions to an `AlignedCharArrayUnion` 
> and use `SourceLocation` directly. WDYT?

So, say, in `DeclarationNameLoc`, I would add `AlignedCharArrayUnion` as 
follows:

  union {
llvm::AlignedCharArrayUnion UninitStorage;
struct NT NamedType;
struct CXXOpName CXXOperatorName;
struct CXXLitOpName CXXLiteralOperatorName;
  };

And change the constructor of `DeclarationNameLoc` to default-construct 
`UninitStorage`, i.e.:

  DeclarationNameLoc() : UninitStorage() {
memset(UninitStorage.buffer, 0, sizeof(UninitStorage.buffer));
  }

After that, I can use `SourceLocation` in `DeclarationNameLoc` directly.

Do I understand your idea correctly?


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

https://reviews.llvm.org/D69903

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


  1   2   3   >