[clang] ba31cb4 - [CodeGen] Store element type in RValue

2021-12-17 Thread Nikita Popov via cfe-commits

Author: Nikita Popov
Date: 2021-12-17T09:05:59+01:00
New Revision: ba31cb4d388098e01df226090db95aaf8c06d271

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

LOG: [CodeGen] Store element type in RValue

For aggregates, we need to store the element type to be able to
reconstruct the aggregate Address. This increases the size of this
packed structure (as the second value is already used for alignment
in this case), but I did not observe any compile-time or memory
usage regression from this change.

Added: 


Modified: 
clang/lib/CodeGen/CGValue.h

Removed: 




diff  --git a/clang/lib/CodeGen/CGValue.h b/clang/lib/CodeGen/CGValue.h
index 916f423ef5b88..f01eece042f86 100644
--- a/clang/lib/CodeGen/CGValue.h
+++ b/clang/lib/CodeGen/CGValue.h
@@ -47,6 +47,8 @@ class RValue {
   llvm::PointerIntPair V1;
   // Stores second value and volatility.
   llvm::PointerIntPair V2;
+  // Stores element type for aggregate values.
+  llvm::Type *ElementType;
 
 public:
   bool isScalar() const { return V1.getInt() == Scalar; }
@@ -71,7 +73,8 @@ class RValue {
   Address getAggregateAddress() const {
 assert(isAggregate() && "Not an aggregate!");
 auto align = reinterpret_cast(V2.getPointer()) >> AggAlignShift;
-return Address(V1.getPointer(), CharUnits::fromQuantity(align));
+return Address(
+V1.getPointer(), ElementType, CharUnits::fromQuantity(align));
   }
   llvm::Value *getAggregatePointer() const {
 assert(isAggregate() && "Not an aggregate!");
@@ -108,6 +111,7 @@ class RValue {
 RValue ER;
 ER.V1.setPointer(addr.getPointer());
 ER.V1.setInt(Aggregate);
+ER.ElementType = addr.getElementType();
 
 auto align = static_cast(addr.getAlignment().getQuantity());
 ER.V2.setPointer(reinterpret_cast(align << AggAlignShift));



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


[PATCH] D102669: [analyzer][ctu] Fix wrong 'multiple definitions' errors caused by space characters in lookup names when parsing the ctu index file

2021-12-17 Thread Balázs Benics via Phabricator via cfe-commits
steakhal edited reviewers, added: a.sidorin, shafik, xazax.hun, teemperor; 
removed: hgabii.
steakhal added a comment.

We shouldn't skip mac targets. I CC ASTImporter folks, they probably have an M1 
.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D102669

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


[PATCH] D114317: [clang-tidy][WIP] Do not run perfect alias checks

2021-12-17 Thread Carlos Galvez via Phabricator via cfe-commits
carlosgalvezp added a comment.

> no, I don't think that's quite what we want." :-)

Sorry for not being specific enough :) What we want is to keep this (current 
user-facing behavior today):

  error: forgot to frobble the quux [bugprone-frobble-quux, cert-quux45-cpp]

As opposed to:

  error: forgot to frobble the quux [bugprone-frobble-quux]

(the users wants CERT enabled, and yet they don't see diagnostics coming from 
`cert` (even though they effectively are enabled via `bugprone`)).

I'll try to dig a bit deeper and see if I can figure this out.


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

https://reviews.llvm.org/D114317

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


[PATCH] D115879: [clang-format] extern with new line brace without indentation

2021-12-17 Thread Owen Pan via Phabricator via cfe-commits
owenpan added inline comments.



Comment at: clang/unittests/Format/FormatTest.cpp:3816
+  Style.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock;
+  Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+  Style.BraceWrapping.AfterExternBlock = true;

This line is unnecessary too.



Comment at: clang/unittests/Format/FormatTest.cpp:3826-3827
+  Style.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock;
+  Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+  Style.BraceWrapping.AfterExternBlock = true;
+  Style.IndentExternBlock = FormatStyle::IEBS_Indent;

I would remove these too.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115879

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


[PATCH] D114483: [SYCL] Add support for sycl_special_class attribute

2021-12-17 Thread Mariya Podchishchaeva via Phabricator via cfe-commits
Fznamznon added inline comments.



Comment at: clang/lib/Sema/SemaDecl.cpp:9118
+  NewFD->getKind() == Decl::Kind::CXXMethod &&
+  NewFD->getName() == "__init" && D.isFunctionDefinition()) {
+if (auto *def = Parent->getDefinition())

In our downstream we have not only `__init`, but `__init_esimd` as well there. 
I wonder how this case should be handled?



Comment at: clang/lib/Sema/SemaDecl.cpp:16675-16683
+  if (auto *RD = dyn_cast(Tag)) {
 FieldCollector->FinishClass();
+if (RD->hasAttr()) {
+  auto *def = RD->getDefinition();
+  if (def && !def->hasInitMethod())
+Diag(RD->getLocation(),
+ diag::err_sycl_special_type_missing_init_method);

Code style correction.



Comment at: clang/lib/Sema/SemaDeclAttr.cpp:7762
+  // The 'sycl_special_class' attribute applies only to records.
+  const auto *RD = cast(D);
+  assert(RD && "Record type is expected");

I wonder if this check is enforced by this line in Attr.td:
```
let Subjects = SubjectList<[CXXRecord]>;
```
I would assume that it is.




Comment at: clang/test/SemaSYCL/special-class-attribute.cpp:21
+
+class [[clang::sycl_special_class]] struct1 {
+  void __init(){};

Did you mean `struct` keyword here?



Comment at: clang/test/SemaSYCL/special-class-attribute.cpp:31
+};
+class special5 {};
+

Is this one needed?



Comment at: clang/test/SemaSYCL/special-class-attribute.cpp:43
+class [[clang::sycl_special_class]] class8 { // expected-error {{types with 
'sycl_special_class' attribute must have an '__init' method defined}}
+  void __init();
+};

Will detection of `__init` method work correctly if it is defined outside of 
the class?
Maybe we should also mention that it should be not be defined in a separate 
library.


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

https://reviews.llvm.org/D114483

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


[PATCH] D115923: [RISCV][Don't Commit] Refactor the RISCV ISA extension info and target features to support multiple extension version

2021-12-17 Thread Zixuan Wu via Phabricator via cfe-commits
zixuan-wu created this revision.
zixuan-wu added reviewers: asb, craig.topper, kito-cheng, luismarques, apazos, 
jrtc27, Jim, akuegel, jhenderson, MaskRay, sjarus.
Herald added subscribers: VincentWu, luke957, achieveartificialintelligence, 
vkmr, frasercrmck, evandro, sameer.abuasal, s.egerton, benna, psnobl, jocewei, 
PkmX, the_o, brucehoult, MartinMosbeck, rogfer01, edward-jones, zzheng, niosHD, 
sabuasal, simoncook, johnrusso, rbar, hiraditya.
zixuan-wu requested review of this revision.
Herald added projects: clang, LLVM.
Herald added subscribers: llvm-commits, cfe-commits.

Split from https://reviews.llvm.org/D115921 since testcase change is too large 
to review.

This is part of D115921 , and will not be 
committed.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D115923

Files:
  clang/include/clang/Basic/BuiltinsRISCV.def
  clang/lib/Basic/Targets/RISCV.cpp
  clang/lib/Driver/ToolChains/Arch/RISCV.cpp
  clang/utils/TableGen/RISCVVEmitter.cpp
  llvm/include/llvm/Support/RISCVISAInfo.h
  llvm/lib/Object/ELFObjectFile.cpp
  llvm/lib/Support/RISCVISAInfo.cpp
  llvm/lib/Target/RISCV/AsmParser/RISCVAsmParser.cpp
  llvm/lib/Target/RISCV/RISCV.td
  llvm/lib/Target/RISCV/RISCVSubtarget.h

Index: llvm/lib/Target/RISCV/RISCVSubtarget.h
===
--- llvm/lib/Target/RISCV/RISCVSubtarget.h
+++ llvm/lib/Target/RISCV/RISCVSubtarget.h
@@ -24,6 +24,7 @@
 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
 #include "llvm/CodeGen/TargetSubtargetInfo.h"
 #include "llvm/IR/DataLayout.h"
+#include "llvm/Support/RISCVISAInfo.h"
 #include "llvm/Target/TargetMachine.h"
 
 #define GET_SUBTARGETINFO_HEADER
@@ -34,28 +35,28 @@
 
 class RISCVSubtarget : public RISCVGenSubtargetInfo {
   virtual void anchor();
-  bool HasStdExtM = false;
-  bool HasStdExtA = false;
-  bool HasStdExtF = false;
-  bool HasStdExtD = false;
-  bool HasStdExtC = false;
-  bool HasStdExtZba = false;
-  bool HasStdExtZbb = false;
-  bool HasStdExtZbc = false;
-  bool HasStdExtZbe = false;
-  bool HasStdExtZbf = false;
-  bool HasStdExtZbm = false;
-  bool HasStdExtZbp = false;
-  bool HasStdExtZbr = false;
-  bool HasStdExtZbs = false;
-  bool HasStdExtZbt = false;
-  bool HasStdExtV = false;
-  bool HasStdExtZvlsseg = false;
-  bool HasStdExtZvamo = false;
-  bool HasStdExtZfhmin = false;
-  bool HasStdExtZfh = false;
+  RISCVExtensionVersion StdExtM = {0, 0};
+  RISCVExtensionVersion StdExtA = {0, 0};
+  RISCVExtensionVersion StdExtF = {0, 0};
+  RISCVExtensionVersion StdExtD = {0, 0};
+  RISCVExtensionVersion StdExtC = {0, 0};
+  RISCVExtensionVersion StdExtZba = {0, 0};
+  RISCVExtensionVersion StdExtZbb = {0, 0};
+  RISCVExtensionVersion StdExtZbc = {0, 0};
+  RISCVExtensionVersion StdExtZbe = {0, 0};
+  RISCVExtensionVersion StdExtZbf = {0, 0};
+  RISCVExtensionVersion StdExtZbm = {0, 0};
+  RISCVExtensionVersion StdExtZbp = {0, 0};
+  RISCVExtensionVersion StdExtZbr = {0, 0};
+  RISCVExtensionVersion StdExtZbs = {0, 0};
+  RISCVExtensionVersion StdExtZbt = {0, 0};
+  RISCVExtensionVersion StdExtV = {0, 0};
+  RISCVExtensionVersion StdExtZvlsseg = {0, 0};
+  RISCVExtensionVersion StdExtZvamo = {0, 0};
+  RISCVExtensionVersion StdExtZfhmin = {0, 0};
+  RISCVExtensionVersion StdExtZfh = {0, 0};
+  RISCVExtensionVersion StdExtE = {0, 0};
   bool HasRV64 = false;
-  bool IsRV32E = false;
   bool EnableLinkerRelax = false;
   bool EnableRVCHintInstrs = true;
   bool EnableSaveRestore = false;
@@ -101,28 +102,34 @@
 return &TSInfo;
   }
   bool enableMachineScheduler() const override { return true; }
-  bool hasStdExtM() const { return HasStdExtM; }
-  bool hasStdExtA() const { return HasStdExtA; }
-  bool hasStdExtF() const { return HasStdExtF; }
-  bool hasStdExtD() const { return HasStdExtD; }
-  bool hasStdExtC() const { return HasStdExtC; }
-  bool hasStdExtZba() const { return HasStdExtZba; }
-  bool hasStdExtZbb() const { return HasStdExtZbb; }
-  bool hasStdExtZbc() const { return HasStdExtZbc; }
-  bool hasStdExtZbe() const { return HasStdExtZbe; }
-  bool hasStdExtZbf() const { return HasStdExtZbf; }
-  bool hasStdExtZbm() const { return HasStdExtZbm; }
-  bool hasStdExtZbp() const { return HasStdExtZbp; }
-  bool hasStdExtZbr() const { return HasStdExtZbr; }
-  bool hasStdExtZbs() const { return HasStdExtZbs; }
-  bool hasStdExtZbt() const { return HasStdExtZbt; }
-  bool hasStdExtV() const { return HasStdExtV; }
-  bool hasStdExtZvlsseg() const { return HasStdExtZvlsseg; }
-  bool hasStdExtZvamo() const { return HasStdExtZvamo; }
-  bool hasStdExtZfhmin() const { return HasStdExtZfhmin; }
-  bool hasStdExtZfh() const { return HasStdExtZfh; }
+  bool hasStdExtM() const { return StdExtM != RISCVExtensionVersion{0, 0}; }
+  bool hasStdExtA() const { return StdExtA != RISCVExtensionVersion{0, 0}; }
+  bool hasStdExtF() const { return StdExtF != RISCVExtensionVersion{0, 0}; }
+  bool hasStdExtD() const { return StdExtD != RISCVExtens

[PATCH] D102669: [analyzer][ctu] Fix wrong 'multiple definitions' errors caused by space characters in lookup names when parsing the ctu index file

2021-12-17 Thread Alexander Richardson via Phabricator via cfe-commits
arichardson added inline comments.



Comment at: clang/test/Analysis/ctu-lookup-name-with-space.cpp:13
+// RUN:   -verify %s
+
+void importee();

OikawaKirie wrote:
> Adding this line here.
Disabling the test on non- Linux is not a good idea IMO since it means we lose 
coverage on other platforms. My guess is that you just need to specify an 
explicit triple in the clang invocations.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D102669

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


[PATCH] D114639: Raise the minimum Visual Studio version to VS2019

2021-12-17 Thread Simon Pilgrim via Phabricator via cfe-commits
RKSimon added a comment.

@rnk I'm not certain but I think the only buildbot still using VS2017 is 
windows-gcebot2 ?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114639

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


[PATCH] D115503: [DebugInfo][Clang] record the access flag for class/struct/union types.

2021-12-17 Thread Esme Yi via Phabricator via cfe-commits
Esme added a comment.

In D115503#3195171 , @dblaikie wrote:

> Ah, cool - could you include % growth on those rows

Thanks, I edited the table in the previous comment.

> (hmm, .debug_line and .debug_str shouldn't be changing in size with this 
> change, right? If you use the same clang version to test the two cases (if 
> you're using a bootstrap with/without the patch applied, then the patch 
> changes itself would show up as changes here))

Hmm...it's a little strange. I got these data by:

1. pull a base llvm-project branch --> source codes
2. build the source --> clang1
3. build the codes after applying the patch  --> clang2
4. use clang1 to build the source (no patch) --> clang-before
5. use clang2 to build the source (no patch) --> clang-after
6. compare the size between clang-before and clang-after

I reproduced these steps on another base branch, and saw similar changes (i.e. 
.debug_line and .debug_str changed in size)...
But I think the change is so small as to be negligible?

> & if you could include this table in the commit message, that'd be great!
>
> (can you commit this yourself, or do you need someone to do that for you?)

I will include this table when committing, thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115503

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


[PATCH] D115503: [DebugInfo][Clang] record the access flag for class/struct/union types.

2021-12-17 Thread ChenZheng via Phabricator via cfe-commits
shchenz added a comment.

In D115503#3199459 , @Esme wrote:

> In D115503#3195171 , @dblaikie 
> wrote:
>
>> Ah, cool - could you include % growth on those rows
>
> Thanks, I edited the table in the previous comment.
>
>> (hmm, .debug_line and .debug_str shouldn't be changing in size with this 
>> change, right? If you use the same clang version to test the two cases (if 
>> you're using a bootstrap with/without the patch applied, then the patch 
>> changes itself would show up as changes here))
>
> Hmm...it's a little strange. I got these data by:
>
> 1. pull a base llvm-project branch --> source codes
> 2. build the source --> clang1
> 3. build the codes after applying the patch  --> clang2
> 4. use clang1 to build the source (no patch) --> clang-before
> 5. use clang2 to build the source (no patch) --> clang-after
> 6. compare the size between clang-before and clang-after
>
> I reproduced these steps on another base branch, and saw similar changes 
> (i.e. .debug_line and .debug_str changed in size)...
> But I think the change is so small as to be negligible?
>
>> & if you could include this table in the commit message, that'd be great!
>>
>> (can you commit this yourself, or do you need someone to do that for you?)
>
> I will include this table when committing, thanks!

`.debug_str` will be changed because of `DW_AT_producer`? We are using 
different compilers to compile the source.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115503

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


[PATCH] D115883: [analyzer][NFC] Change return value of StoreManager::attemptDownCast function from SVal to Optional

2021-12-17 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov added a comment.

@xazax.hun 
Many thanks for the review.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115883

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


[clang] da8bd97 - [analyzer][NFC] Change return value of StoreManager::attemptDownCast function from SVal to Optional

2021-12-17 Thread Denys Petrov via cfe-commits

Author: Denys Petrov
Date: 2021-12-17T13:03:47+02:00
New Revision: da8bd972a33ad642d6237b5b95b31a2a20f46a35

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

LOG: [analyzer][NFC] Change return value of StoreManager::attemptDownCast 
function from SVal to Optional

Summary: Refactor return value of `StoreManager::attemptDownCast` function by 
removing the last parameter `bool &Failed` and replace the return value `SVal` 
with `Optional`.  Make the function consistent with the family of 
`evalDerivedToBase` by renaming it to `evalBaseToDerived`. Aligned the code on 
the call side with these changes.

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

Added: 


Modified: 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h
clang/lib/StaticAnalyzer/Core/CallEvent.cpp
clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
clang/lib/StaticAnalyzer/Core/Store.cpp

Removed: 




diff  --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h
index d2461705d128..bdf9662d5d99 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/Store.h
@@ -172,9 +172,9 @@ class StoreManager {
   ///dynamic_cast.
   ///  - We don't know (base is a symbolic region and we don't have
   ///enough info to determine if the cast will succeed at run time).
-  /// The function returns an SVal representing the derived class; it's
-  /// valid only if Failed flag is set to false.
-  SVal attemptDownCast(SVal Base, QualType DerivedPtrType, bool &Failed);
+  /// The function returns an optional with SVal representing the derived class
+  /// in case of a successful cast and `None` otherwise.
+  Optional evalBaseToDerived(SVal Base, QualType DerivedPtrType);
 
   const ElementRegion *GetElementZeroRegion(const SubRegion *R, QualType T);
 

diff  --git a/clang/lib/StaticAnalyzer/Core/CallEvent.cpp 
b/clang/lib/StaticAnalyzer/Core/CallEvent.cpp
index 764dad3e7ab4..ae46709340d3 100644
--- a/clang/lib/StaticAnalyzer/Core/CallEvent.cpp
+++ b/clang/lib/StaticAnalyzer/Core/CallEvent.cpp
@@ -762,9 +762,9 @@ void CXXInstanceCall::getInitialStackFrameContents(
   QualType Ty = Ctx.getPointerType(Ctx.getRecordType(Class));
 
   // FIXME: CallEvent maybe shouldn't be directly accessing StoreManager.
-  bool Failed;
-  ThisVal = StateMgr.getStoreManager().attemptDownCast(ThisVal, Ty, 
Failed);
-  if (Failed) {
+  Optional V =
+  StateMgr.getStoreManager().evalBaseToDerived(ThisVal, Ty);
+  if (!V.hasValue()) {
 // We might have suffered some sort of placement new earlier, so
 // we're constructing in a completely unexpected storage.
 // Fall back to a generic pointer cast for this-value.
@@ -772,7 +772,8 @@ void CXXInstanceCall::getInitialStackFrameContents(
 const CXXRecordDecl *StaticClass = StaticMD->getParent();
 QualType StaticTy = Ctx.getPointerType(Ctx.getRecordType(StaticClass));
 ThisVal = SVB.evalCast(ThisVal, Ty, StaticTy);
-  }
+  } else
+ThisVal = *V;
 }
 
 if (!ThisVal.isUnknown())

diff  --git a/clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp 
b/clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
index 69d67cf9b465..637e4edfd778 100644
--- a/clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
+++ b/clang/lib/StaticAnalyzer/Core/ExprEngineC.cpp
@@ -439,14 +439,15 @@ void ExprEngine::VisitCast(const CastExpr *CastE, const 
Expr *Ex,
 if (CastE->isGLValue())
   resultType = getContext().getPointerType(resultType);
 
-bool Failed = false;
-
-// Check if the value being cast evaluates to 0.
-if (val.isZeroConstant())
-  Failed = true;
-// Else, evaluate the cast.
-else
-  val = getStoreManager().attemptDownCast(val, T, Failed);
+bool Failed = true;
+
+// Check if the value being cast does not evaluates to 0.
+if (!val.isZeroConstant())
+  if (Optional V =
+  StateMgr.getStoreManager().evalBaseToDerived(val, T)) {
+val = *V;
+Failed = false;
+  }
 
 if (Failed) {
   if (T->isReferenceType()) {
@@ -478,14 +479,13 @@ void ExprEngine::VisitCast(const CastExpr *CastE, const 
Expr *Ex,
 if (CastE->isGLValue())
   resultType = getContext().getPointerType(resultType);
 
-bool Failed = false;
-
 if (!val.isConstant()) {
-  val = getStoreManager().attemptDownCast(val, T, Failed);
+  Optional V = getStoreManager().evalBaseToDerived(val, T);
+  val = V ? *V : UnknownVal();
 }
 
 // Failed to cast or the result is unknown, fall ba

[clang] 9bf9173 - [CodeGen] Avoid more pointer element type accesses

2021-12-17 Thread Nikita Popov via cfe-commits

Author: Nikita Popov
Date: 2021-12-17T12:11:50+01:00
New Revision: 9bf917394eba3ba4df77cc17690c6d04f4e9d57f

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

LOG: [CodeGen] Avoid more pointer element type accesses

Added: 


Modified: 
clang/lib/CodeGen/CGCall.cpp
clang/lib/CodeGen/CGExprAgg.cpp
clang/lib/CodeGen/CodeGenFunction.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index 28fc75ba466e7..be20f7cc41e86 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -1261,8 +1261,7 @@ static llvm::Value *CreateCoercedLoad(Address Src, 
llvm::Type *Ty,
 //
 // FIXME: Assert that we aren't truncating non-padding bits when have 
access
 // to that information.
-Src = CGF.Builder.CreateBitCast(Src,
-Ty->getPointerTo(Src.getAddressSpace()));
+Src = CGF.Builder.CreateElementBitCast(Src, Ty);
 return CGF.Builder.CreateLoad(Src);
   }
 

diff  --git a/clang/lib/CodeGen/CGExprAgg.cpp b/clang/lib/CodeGen/CGExprAgg.cpp
index 980d6095b3a52..3b996b89a1d7d 100644
--- a/clang/lib/CodeGen/CGExprAgg.cpp
+++ b/clang/lib/CodeGen/CGExprAgg.cpp
@@ -493,7 +493,7 @@ void AggExprEmitter::EmitArrayInit(Address DestPtr, 
llvm::ArrayType *AType,
   CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
   CharUnits elementAlign =
 DestPtr.getAlignment().alignmentOfArrayElement(elementSize);
-  llvm::Type *llvmElementType = begin->getType()->getPointerElementType();
+  llvm::Type *llvmElementType = CGF.ConvertTypeForMem(elementType);
 
   // Consider initializing the array by copying from a global. For this to be
   // more efficient than per-element initialization, the size of the elements
@@ -566,8 +566,8 @@ void AggExprEmitter::EmitArrayInit(Address DestPtr, 
llvm::ArrayType *AType,
   if (endOfInit.isValid()) Builder.CreateStore(element, endOfInit);
 }
 
-LValue elementLV =
-  CGF.MakeAddrLValue(Address(element, elementAlign), elementType);
+LValue elementLV = CGF.MakeAddrLValue(
+Address(element, llvmElementType, elementAlign), elementType);
 EmitInitializationToLValue(E->getInit(i), elementLV);
   }
 

diff  --git a/clang/lib/CodeGen/CodeGenFunction.cpp 
b/clang/lib/CodeGen/CodeGenFunction.cpp
index f14e4c33e91a5..91deeb657d623 100644
--- a/clang/lib/CodeGen/CodeGenFunction.cpp
+++ b/clang/lib/CodeGen/CodeGenFunction.cpp
@@ -1070,7 +1070,8 @@ void CodeGenFunction::StartFunction(GlobalDecl GD, 
QualType RetTy,
 auto AI = CurFn->arg_begin();
 if (CurFnInfo->getReturnInfo().isSRetAfterThis())
   ++AI;
-ReturnValue = Address(&*AI, CurFnInfo->getReturnInfo().getIndirectAlign());
+ReturnValue = Address(&*AI, ConvertTypeForMem(RetTy),
+  CurFnInfo->getReturnInfo().getIndirectAlign());
 if (!CurFnInfo->getReturnInfo().getIndirectByVal()) {
   ReturnValuePointer =
   CreateDefaultAlignTempAlloca(Int8PtrTy, "result.ptr");



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


[PATCH] D115903: [clang-format] Extra spaces surrounding arrow in templated member call in variable decl

2021-12-17 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius accepted this revision.
curdeius added a comment.
This revision is now accepted and ready to land.

LGTM.




Comment at: clang/lib/Format/TokenAnnotator.cpp:1682
Current.NestingLevel == 0 &&
-   !Current.Previous->is(tok::kw_operator)) {
+   !Current.Previous->isOneOf(tok::kw_operator, tok::identifier)) {
   // not auto operator->() -> xxx;

MyDeveloperDay wrote:
> curdeius wrote:
> > Won't it break lambdas with an identifier (e.g. macro) before the arrow? 
> > E.g.:
> > ```
> > auto lmbd = [] NOEXCEPT -> int {
> >   return 0;
> > };
> > ```
> it doesn't seem so, maybe one of the other rules is catching that
> 
> auto lmbd = [] NOEXCEPT -> int { return 0; };
> 
Ok, but I'd like to see it as a test case if we don't have something similar 
already.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115903

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


[PATCH] D115879: [clang-format] extern with new line brace without indentation

2021-12-17 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius added inline comments.



Comment at: clang/unittests/Format/FormatTest.cpp:3819
+  Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
+  verifyFormat("extern \"C\"\n{ /*13*/\n}", Style);
+  verifyFormat("extern \"C\"\n{\n"

owenpan wrote:
> curdeius wrote:
> > I'd prefer that you split strings after `\n`. I find it easier to read that 
> > way.
> > The same below.
> It's everywhere in this function. We should fix them either now or in a 
> separate patch.
Ok, let's do it in another patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115879

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


[PATCH] D115879: [clang-format] extern with new line brace without indentation

2021-12-17 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay updated this revision to Diff 395088.
MyDeveloperDay added a comment.

As always you are both correct

- tidy up the unit tests to follow our pattern
- reduce unnecessary style setting
- try and tidy up the indent selection a little


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

https://reviews.llvm.org/D115879

Files:
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/unittests/Format/FormatTest.cpp

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -3781,14 +3781,18 @@
   Style.IndentWidth = 2;
 
   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
-  verifyFormat("extern \"C\" { /*9*/\n}", Style);
+  verifyFormat("extern \"C\" { /*9*/\n"
+   "}",
+   Style);
   verifyFormat("extern \"C\" {\n"
"  int foo10();\n"
"}",
Style);
 
   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
-  verifyFormat("extern \"C\" { /*11*/\n}", Style);
+  verifyFormat("extern \"C\" { /*11*/\n"
+   "}",
+   Style);
   verifyFormat("extern \"C\" {\n"
"int foo12();\n"
"}",
@@ -3797,20 +3801,48 @@
   Style.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock;
   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
   Style.BraceWrapping.AfterExternBlock = true;
-  verifyFormat("extern \"C\"\n{ /*13*/\n}", Style);
+  Style.IndentExternBlock = FormatStyle::IEBS_Indent;
+  verifyFormat("extern \"C\"\n"
+   "{ /*13*/\n"
+   "}",
+   Style);
   verifyFormat("extern \"C\"\n{\n"
"  int foo14();\n"
"}",
Style);
 
-  Style.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock;
-  Style.BreakBeforeBraces = FormatStyle::BS_Custom;
   Style.BraceWrapping.AfterExternBlock = false;
-  verifyFormat("extern \"C\" { /*15*/\n}", Style);
+  Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
+  verifyFormat("extern \"C\" { /*15*/\n"
+   "}",
+   Style);
   verifyFormat("extern \"C\" {\n"
"int foo16();\n"
"}",
Style);
+
+  Style.BraceWrapping.AfterExternBlock = true;
+  Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
+  verifyFormat("extern \"C\"\n"
+   "{ /*13*/\n"
+   "}",
+   Style);
+  verifyFormat("extern \"C\"\n"
+   "{\n"
+   "int foo14();\n"
+   "}",
+   Style);
+
+  Style.IndentExternBlock = FormatStyle::IEBS_Indent;
+  verifyFormat("extern \"C\"\n"
+   "{ /*13*/\n"
+   "}",
+   Style);
+  verifyFormat("extern \"C\"\n"
+   "{\n"
+   "  int foo14();\n"
+   "}",
+   Style);
 }
 
 TEST_F(FormatTest, FormatsInlineASM) {
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -1282,17 +1282,18 @@
 if (FormatTok->Tok.is(tok::string_literal)) {
   nextToken();
   if (FormatTok->Tok.is(tok::l_brace)) {
-if (!Style.IndentExternBlock) {
-  if (Style.BraceWrapping.AfterExternBlock) {
-addUnwrappedLine();
-  }
-  unsigned AddLevels = Style.BraceWrapping.AfterExternBlock ? 1u : 0u;
-  parseBlock(/*MustBeDeclaration=*/true, AddLevels);
-} else {
-  unsigned AddLevels =
-  Style.IndentExternBlock == FormatStyle::IEBS_Indent ? 1u : 0u;
-  parseBlock(/*MustBeDeclaration=*/true, AddLevels);
+if (Style.BraceWrapping.AfterExternBlock) {
+  addUnwrappedLine();
 }
+// Either we indent or for backwards compatibility we follow the
+// AfterExternBlock style.
+unsigned AddLevels =
+((Style.IndentExternBlock == FormatStyle::IEBS_Indent) ||
+ (Style.BraceWrapping.AfterExternBlock &&
+  Style.IndentExternBlock == FormatStyle::IEBS_AfterExternBlock))
+? 1u
+: 0u;
+parseBlock(/*MustBeDeclaration=*/true, AddLevels);
 addUnwrappedLine();
 return;
   }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D115879: [clang-format] extern with new line brace without indentation

2021-12-17 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay marked 7 inline comments as done.
MyDeveloperDay added inline comments.



Comment at: clang/lib/Format/UnwrappedLineParser.cpp:1282-1300
 if (FormatTok->Tok.is(tok::string_literal)) {
   nextToken();
   if (FormatTok->Tok.is(tok::l_brace)) {
+if (Style.BraceWrapping.AfterExternBlock) {
+  addUnwrappedLine();
+}
 if (!Style.IndentExternBlock) {

owenpan wrote:
> This `case` is kind of messy and some cleanup may be in order. A related 
> question: why do we make `IEBS_AfterExternBlock` depend on 
> `BraceWrapping.AfterExternBlock`? Can't we only have true/false for 
> `IndentExternBlock` and let the user set it independent of 
> `BraceWrapping.AfterExternBlock`?
This a a backwards compatibility thing, (its needed for the google style by the 
looks of things)


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

https://reviews.llvm.org/D115879

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


[PATCH] D115883: [analyzer][NFC] Change return value of StoreManager::attemptDownCast function from SVal to Optional

2021-12-17 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov closed this revision.
ASDenysPetrov added a comment.

Closed with rGda8bd972a33ad642d6237b5b95b31a2a20f46a35 



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115883

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


[PATCH] D114718: [analyzer] Implement a new checker for Strict Aliasing Rule.

2021-12-17 Thread Denys Petrov via Phabricator via cfe-commits
ASDenysPetrov added a comment.

@steakhal Thanks! I appreciate your comprehensive comment! I'll take everything 
you suggested into account.




Comment at: 
clang/test/Analysis/Checkers/StrictAliasingChecker/strict-aliasing.cpp:2
+// RUN: %clang_cc1 -std=c++20 -analyze -analyzer-config eagerly-assume=false 
-analyzer-checker=debug.ExprInspection,alpha.core.StrictAliasing -verify %s
+// NOTE: -relaxed-aliasing flag disables StrictAliasing checker.
+

steakhal wrote:
> I think `fno-strict-aliasing` should achieve this, by which the driver should 
> transform that flag into the `-relaxed-aliasing` flag consumed by the backend.
Yes, but here in the RUN line you should use a backend flag `-relaxed-aliasing` 
instead of `-fno-strict-aliasing`. `-fno-strict-aliasing` won't work here. I've 
tried.
P.S. Note that the checker works relying on the presentence of 
`-relaxed-aliasing`, so here the absense of `-relaxed-aliasing` is en 
equivalent of `-fstrict-aliasing`.


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

https://reviews.llvm.org/D114718

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


[PATCH] D115149: [analyzer][solver] Fix assertion on (NonLoc, Op, Loc) expressions

2021-12-17 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

In D115149#3195377 , @ASDenysPetrov 
wrote:

> @martong
> Thanks for clarification.
>
>> TLDR, it is recommended to use the arcanist.
>
> I'm not able to use arcanist. It doesn't work on Windows (at least I've tryed 
> several ways to set up it).
>
> BTW. I found a revision from which the 
> test(//symbol-simplification-nonloc-loc.cpp//) file starts to assert. It's 
> your one D113754 . You can checkout a 
> revision before and test the file. I think we should investigate it deeper to 
> understand the real cause.

Yes, as of D113754 , we handle `IntSymExprs` 
in the SValBuilder, and the half of the test cases added by Balazs are such 
(`nonloc_OP_loc`). These are the cases that triggers the assertion.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115149

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


[PATCH] D115903: [clang-format] Extra spaces surrounding arrow in templated member call in variable decl

2021-12-17 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added inline comments.



Comment at: clang/lib/Format/TokenAnnotator.cpp:1682
Current.NestingLevel == 0 &&
-   !Current.Previous->is(tok::kw_operator)) {
+   !Current.Previous->isOneOf(tok::kw_operator, tok::identifier)) {
   // not auto operator->() -> xxx;

curdeius wrote:
> MyDeveloperDay wrote:
> > curdeius wrote:
> > > Won't it break lambdas with an identifier (e.g. macro) before the arrow? 
> > > E.g.:
> > > ```
> > > auto lmbd = [] NOEXCEPT -> int {
> > >   return 0;
> > > };
> > > ```
> > it doesn't seem so, maybe one of the other rules is catching that
> > 
> > auto lmbd = [] NOEXCEPT -> int { return 0; };
> > 
> Ok, but I'd like to see it as a test case if we don't have something similar 
> already.
let me add that for completeness before I commit


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115903

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


[PATCH] D115931: [analyzer] Enable move semantics for CallDescriptionMap

2021-12-17 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 created this revision.
gamesh411 added reviewers: steakhal, martong.
Herald added subscribers: manas, ASDenysPetrov, dkrupp, donat.nagy, Szelethus, 
mikhail.ramalho, a.sidorin, rnkovacs, szepet, baloghadamsoftware, xazax.hun.
Herald added a reviewer: Szelethus.
gamesh411 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

CallDescriptionMap is supposed to be immutable and opaque about the
stored CallDescriptions, but moving a CallDescriptionMap does not
violate these principles.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D115931

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
  clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp


Index: clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp
===
--- clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp
+++ clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp
@@ -19,6 +19,10 @@
 namespace ento {
 namespace {
 
+static_assert(std::is_move_constructible>() &&
+  std::is_move_assignable>(),
+  "CallDescriptionMap should support move semantics");
+
 // A wrapper around CallDescriptionMap that allows verifying that
 // all functions have been found. This is needed because CallDescriptionMap
 // isn't supposed to support iteration.
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
@@ -141,6 +141,9 @@
   CallDescriptionMap(const CallDescriptionMap &) = delete;
   CallDescriptionMap &operator=(const CallDescription &) = delete;
 
+  CallDescriptionMap(CallDescriptionMap &&) = default;
+  CallDescriptionMap &operator=(CallDescriptionMap &&) = default;
+
   LLVM_NODISCARD const T *lookup(const CallEvent &Call) const {
 // Slow path: linear lookup.
 // TODO: Implement some sort of fast path.


Index: clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp
===
--- clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp
+++ clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp
@@ -19,6 +19,10 @@
 namespace ento {
 namespace {
 
+static_assert(std::is_move_constructible>() &&
+  std::is_move_assignable>(),
+  "CallDescriptionMap should support move semantics");
+
 // A wrapper around CallDescriptionMap that allows verifying that
 // all functions have been found. This is needed because CallDescriptionMap
 // isn't supposed to support iteration.
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
@@ -141,6 +141,9 @@
   CallDescriptionMap(const CallDescriptionMap &) = delete;
   CallDescriptionMap &operator=(const CallDescription &) = delete;
 
+  CallDescriptionMap(CallDescriptionMap &&) = default;
+  CallDescriptionMap &operator=(CallDescriptionMap &&) = default;
+
   LLVM_NODISCARD const T *lookup(const CallEvent &Call) const {
 // Slow path: linear lookup.
 // TODO: Implement some sort of fast path.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D115932: [Analyzer] Create and handle SymbolCast for pointer to integral conversion

2021-12-17 Thread Gabor Marton via Phabricator via cfe-commits
martong created this revision.
martong added reviewers: steakhal, NoQ, ASDenysPetrov.
Herald added subscribers: manas, gamesh411, dkrupp, donat.nagy, Szelethus, 
mikhail.ramalho, a.sidorin, rnkovacs, szepet, baloghadamsoftware, xazax.hun.
Herald added a reviewer: Szelethus.
martong requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Currently, pointer to integral type casts are not modeled properly in
the symbol tree.
Below

  void foo(int *p) {
12 - (long)p;
  }

the resulting symbol for the BinOP is an IntSymExpr. LHS is `12` and the RHS is
`&SymRegion{reg_$0}`.

Even though, the `SVal` that is created for `(long)p` is correctly an
`LocAsInteger`, we loose this information when we build up the symbol tree for
`12 - (long)p`. To preserve the cast, we have to create a new node in
the symbol tree that represents it: the `SymbolCast`. This
is what this patch does.

This reverts D115149 , except the test cases.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D115932

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValVisitor.h
  clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
  clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp


Index: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
@@ -1204,7 +1204,23 @@
   return SVB.makeSymbolVal(S);
 }
 
-// TODO: Support SymbolCast.
+SVal VisitSymbolCast(const SymbolCast *Cast) {
+  SVal Castee = Visit(Cast->getOperand());
+  const auto &Context = SVB.getContext();
+  QualType CastTy = Cast->getType();
+
+  // Cast a pointer to an integral type.
+  if (Castee.getAs() && !Loc::isLocType(CastTy)) {
+const unsigned BitWidth = Context.getIntWidth(CastTy);
+if (Castee.getAsSymbol())
+  return SVB.makeLocAsInteger(Castee.castAs(), BitWidth);
+if (auto X = Castee.getAs())
+  return SVB.makeIntVal(X->getValue());
+// FIXME other cases?
+  }
+
+  return Base::VisitSymbolCast(Cast);
+}
 
 SVal VisitSymIntExpr(const SymIntExpr *S) {
   auto I = Cached.find(S);
Index: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SValBuilder.cpp
@@ -412,6 +412,15 @@
   SymbolRef symLHS = LHS.getAsSymbol();
   SymbolRef symRHS = RHS.getAsSymbol();
 
+  // FIXME This should be done in getAsSymbol. But then getAsSymbol should be
+  // the member function of SValBuilder (?)
+  if (symRHS)
+if (auto RLocAsInt = RHS.getAs()) {
+  auto FromTy = symRHS->getType();
+  auto ToTy = RLocAsInt->getType(this->Context);
+  symRHS = this->getSymbolManager().getCastSymbol(symRHS, FromTy, ToTy);
+}
+
   // TODO: When the Max Complexity is reached, we should conjure a symbol
   // instead of generating an Unknown value and propagate the taint info to it.
   const unsigned MaxComp = AnOpts.MaxSymbolComplexity;
@@ -459,23 +468,14 @@
 return evalBinOpLN(state, op, *LV, rhs.castAs(), type);
   }
 
-  if (const Optional RV = rhs.getAs()) {
-const auto IsCommutative = [](BinaryOperatorKind Op) {
-  return Op == BO_Mul || Op == BO_Add || Op == BO_And || Op == BO_Xor ||
- Op == BO_Or;
-};
+  if (Optional RV = rhs.getAs()) {
+// Support pointer arithmetic where the addend is on the left
+// and the pointer on the right.
 
-if (IsCommutative(op)) {
-  // Swap operands.
-  return evalBinOpLN(state, op, *RV, lhs.castAs(), type);
-}
+assert(op == BO_Add);
 
-// If the right operand is a concrete int location then we have nothing
-// better but to treat it as a simple nonloc.
-if (auto RV = rhs.getAs()) {
-  const nonloc::ConcreteInt RhsAsLoc = makeIntVal(RV->getValue());
-  return evalBinOpNN(state, op, lhs.castAs(), RhsAsLoc, type);
-}
+// Commute the operands.
+return evalBinOpLN(state, op, *RV, lhs.castAs(), type);
   }
 
   return evalBinOpNN(state, op, lhs.castAs(), rhs.castAs(),
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValVisitor.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValVisitor.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/SValVisitor.h
@@ -141,6 +141,7 @@
   using SValVisitor::Visit;
   using SymExprVisitor::Visit;
   using MemRegionVisitor::Visit;
+  using Base = FullSValVisitor;
 };
 
 } // end namespace ento


Index: clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
===
--- clang/lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp
+++ clang/lib/StaticAnalyzer/Core/SimpleSValBu

[PATCH] D115149: [analyzer][solver] Fix assertion on (NonLoc, Op, Loc) expressions

2021-12-17 Thread Gabor Marton via Phabricator via cfe-commits
martong added a comment.

In D115149#3181580 , @NoQ wrote:

> Like, that's the whole reason why `nonloc::LocAsInteger` exists: so that we 
> could cast a pointer to an integer and actually have a way to represent the 
> resulting value as `NonLoc`.
> I'm confident that there's a way to get it right, simply because the program 
> under analysis is type-correct. If it's the simplifier, let's fix the 
> simplifier. If the original value is not verbose enough, let's fix the 
> original value. But I really think we should keep this assertion working 
> 24/7. I'm sure when you find the root cause it'll all make sense to you.

OK. Actually, we do create an SVal for the pointer-to-integer cast that is 
indeed an `LocAsInteger`. However, we loose this information when we build up 
the symbol tree in `SValBuilder::makeSymExprValNN`. I think, the only way to 
preserve this information is to create a `SymbolCast` node in the symbol tree. 
So, later the SValBuilder can build-up the correct SVal that represents the 
cast properly even when the symbol is constrained. I have created a new child 
patch that reverts this patch and which creates the SymbolCast.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115149

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


[PATCH] D115932: [Analyzer] Create and handle SymbolCast for pointer to integral conversion

2021-12-17 Thread Gabor Marton via Phabricator via cfe-commits
martong added inline comments.



Comment at: clang/lib/StaticAnalyzer/Core/SValBuilder.cpp:417
+  // the member function of SValBuilder (?)
+  if (symRHS)
+if (auto RLocAsInt = RHS.getAs()) {

We should handle LHS as well.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115932

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


[clang] 4170ea9 - [clang][deps] NFC: Fix whitespace formatting

2021-12-17 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2021-12-17T14:00:20+01:00
New Revision: 4170ea9445cc407ec1bf8cfa5bc5ce2d5295fa36

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

LOG: [clang][deps] NFC: Fix whitespace formatting

Added: 


Modified: 
clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp

Removed: 




diff  --git 
a/clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp 
b/clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
index 540f807bf8a60..eb99fb11fba37 100644
--- a/clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
+++ b/clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
@@ -115,15 +115,14 @@ static bool shouldMinimizeBasedOnExtension(StringRef 
Filename) {
   if (Ext.empty())
 return true; // C++ standard library
   return llvm::StringSwitch(Ext)
-.CasesLower(".c", ".cc", ".cpp", ".c++", ".cxx", true)
-.CasesLower(".h", ".hh", ".hpp", ".h++", ".hxx", true)
-.CasesLower(".m", ".mm", true)
-.CasesLower(".i", ".ii", ".mi", ".mmi", true)
-.CasesLower(".def", ".inc", true)
-.Default(false);
+  .CasesLower(".c", ".cc", ".cpp", ".c++", ".cxx", true)
+  .CasesLower(".h", ".hh", ".hpp", ".h++", ".hxx", true)
+  .CasesLower(".m", ".mm", true)
+  .CasesLower(".i", ".ii", ".mi", ".mmi", true)
+  .CasesLower(".def", ".inc", true)
+  .Default(false);
 }
 
-
 static bool shouldCacheStatFailures(StringRef Filename) {
   StringRef Ext = llvm::sys::path::extension(Filename);
   if (Ext.empty())



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


[clang] 195a529 - [clang][deps] NFC: Rename member variable

2021-12-17 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2021-12-17T14:00:20+01:00
New Revision: 195a5294c28e982607cc11bc63c3be1c0e3c312b

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

LOG: [clang][deps] NFC: Rename member variable

Added: 


Modified: 

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

Removed: 




diff  --git 
a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h 
b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
index 3981ccfd98c06..855ab0626b3dd 100644
--- 
a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
+++ 
b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
@@ -242,7 +242,7 @@ class DependencyScanningWorkerFilesystem : public 
llvm::vfs::ProxyFileSystem {
   DependencyScanningFilesystemSharedCache &SharedCache;
   /// The local cache is used by the worker thread to cache file system queries
   /// locally instead of querying the global cache every time.
-  DependencyScanningFilesystemLocalCache Cache;
+  DependencyScanningFilesystemLocalCache LocalCache;
   /// The optional mapping structure which records information about the
   /// excluded conditional directive skip mappings that are used by the
   /// currently active preprocessor.

diff  --git 
a/clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp 
b/clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
index eb99fb11fba37..664c118473b94 100644
--- a/clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
+++ b/clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
@@ -161,7 +161,7 @@ 
DependencyScanningWorkerFilesystem::getOrCreateFileSystemEntry(
 StringRef Filename) {
   bool ShouldBeMinimized = shouldMinimize(Filename);
 
-  const auto *Entry = Cache.getCachedEntry(Filename);
+  const auto *Entry = LocalCache.getCachedEntry(Filename);
   if (Entry && !Entry->needsUpdate(ShouldBeMinimized))
 return EntryRef(ShouldBeMinimized, Entry);
 



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


[clang] af7a421 - [clang][deps] NFC: Remove explicit call to implicit constructor

2021-12-17 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2021-12-17T14:00:20+01:00
New Revision: af7a421ef4aaf3d098ba78c1dda8ac35d31136cd

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

LOG: [clang][deps] NFC: Remove explicit call to implicit constructor

Added: 


Modified: 
clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp

Removed: 




diff  --git 
a/clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp 
b/clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
index 664c118473b9..199ab2bfe882 100644
--- a/clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
+++ b/clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
@@ -241,8 +241,8 @@ class MinimizedVFSFile final : public llvm::vfs::File {
 llvm::ErrorOr> MinimizedVFSFile::create(
 EntryRef Entry, ExcludedPreprocessorDirectiveSkipMapping *PPSkipMappings) {
   if (Entry.isDirectory())
-return llvm::ErrorOr>(
-std::make_error_code(std::errc::is_a_directory));
+return std::make_error_code(std::errc::is_a_directory);
+
   llvm::ErrorOr Contents = Entry.getContents();
   if (!Contents)
 return Contents.getError();



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


[clang] bcdf7f5 - [clang][deps] NFC: Take and store entry as reference

2021-12-17 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2021-12-17T14:00:20+01:00
New Revision: bcdf7f5e9104cb87d06969d74f4feb0cc7aba08f

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

LOG: [clang][deps] NFC: Take and store entry as reference

Added: 


Modified: 

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

Removed: 




diff  --git 
a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h 
b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
index 855ab0626b3d..7d0b8f2138f9 100644
--- 
a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
+++ 
b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
@@ -177,31 +177,31 @@ class EntryRef {
   bool Minimized;
 
   /// The underlying cached entry.
-  const CachedFileSystemEntry *Entry;
+  const CachedFileSystemEntry &Entry;
 
 public:
-  EntryRef(bool Minimized, const CachedFileSystemEntry *Entry)
+  EntryRef(bool Minimized, const CachedFileSystemEntry &Entry)
   : Minimized(Minimized), Entry(Entry) {}
 
   llvm::ErrorOr getStatus() const {
-auto MaybeStat = Entry->getStatus();
+auto MaybeStat = Entry.getStatus();
 if (!MaybeStat || MaybeStat->isDirectory())
   return MaybeStat;
 return llvm::vfs::Status::copyWithNewSize(*MaybeStat,
   getContents()->size());
   }
 
-  bool isDirectory() const { return Entry->isDirectory(); }
+  bool isDirectory() const { return Entry.isDirectory(); }
 
-  StringRef getName() const { return Entry->getName(); }
+  StringRef getName() const { return Entry.getName(); }
 
   llvm::ErrorOr getContents() const {
-return Minimized ? Entry->getMinimizedContents()
- : Entry->getOriginalContents();
+return Minimized ? Entry.getMinimizedContents()
+ : Entry.getOriginalContents();
   }
 
   const PreprocessorSkippedRangeMapping *getPPSkippedRangeMapping() const {
-return Minimized ? &Entry->getPPSkippedRangeMapping() : nullptr;
+return Minimized ? &Entry.getPPSkippedRangeMapping() : nullptr;
   }
 };
 

diff  --git 
a/clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp 
b/clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
index 199ab2bfe882..8ea59cb0d9a4 100644
--- a/clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
+++ b/clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
@@ -163,7 +163,7 @@ 
DependencyScanningWorkerFilesystem::getOrCreateFileSystemEntry(
 
   const auto *Entry = LocalCache.getCachedEntry(Filename);
   if (Entry && !Entry->needsUpdate(ShouldBeMinimized))
-return EntryRef(ShouldBeMinimized, Entry);
+return EntryRef(ShouldBeMinimized, *Entry);
 
   // FIXME: Handle PCM/PCH files.
   // FIXME: Handle module map files.
@@ -193,7 +193,7 @@ 
DependencyScanningWorkerFilesystem::getOrCreateFileSystemEntry(
 
   // Store the result in the local cache.
   Entry = &SharedCacheEntry.Value;
-  return EntryRef(ShouldBeMinimized, Entry);
+  return EntryRef(ShouldBeMinimized, *Entry);
 }
 
 llvm::ErrorOr



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


[clang] 3f3b5c3 - [clang][deps] NFC: Unify ErrorOr patterns

2021-12-17 Thread Jan Svoboda via cfe-commits

Author: Jan Svoboda
Date: 2021-12-17T14:00:20+01:00
New Revision: 3f3b5c3ec0da8f4982a8645fdb403de582295f0b

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

LOG: [clang][deps] NFC: Unify ErrorOr patterns

This patch canonicalized some code into repetitive ErrorOr pattern. This will 
make refactoring easier if we ever come up with a way to simplify this.

Added: 


Modified: 
clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp

Removed: 




diff  --git 
a/clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp 
b/clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
index 8ea59cb0d9a4..acceec690c11 100644
--- a/clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
+++ b/clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
@@ -19,21 +19,22 @@ using namespace dependencies;
 llvm::ErrorOr
 CachedFileSystemEntry::initFile(StringRef Filename, llvm::vfs::FileSystem &FS) 
{
   // Load the file and its content from the file system.
-  llvm::ErrorOr> MaybeFile =
-  FS.openFileForRead(Filename);
+  auto MaybeFile = FS.openFileForRead(Filename);
   if (!MaybeFile)
 return MaybeFile.getError();
+  auto File = std::move(*MaybeFile);
 
-  llvm::ErrorOr Stat = (*MaybeFile)->status();
-  if (!Stat)
-return Stat.getError();
+  auto MaybeStat = File->status();
+  if (!MaybeStat)
+return MaybeStat.getError();
+  auto Stat = std::move(*MaybeStat);
 
-  llvm::ErrorOr> MaybeBuffer =
-  (*MaybeFile)->getBuffer(Stat->getName());
+  auto MaybeBuffer = File->getBuffer(Stat.getName());
   if (!MaybeBuffer)
 return MaybeBuffer.getError();
+  auto Buffer = std::move(*MaybeBuffer);
 
-  OriginalContents = std::move(*MaybeBuffer);
+  OriginalContents = std::move(Buffer);
   return Stat;
 }
 



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


[PATCH] D115934: [analyzer] Add range constructor to CallDescriptionMap

2021-12-17 Thread Endre Fülöp via Phabricator via cfe-commits
gamesh411 created this revision.
gamesh411 added reviewers: steakhal, martong.
Herald added subscribers: manas, ASDenysPetrov, dkrupp, donat.nagy, Szelethus, 
mikhail.ramalho, a.sidorin, rnkovacs, szepet, baloghadamsoftware, xazax.hun.
Herald added a reviewer: Szelethus.
gamesh411 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

CallDescriptionMap benefits from a range constructor when the
CallDescription and mapped type pairs cannot be constructed at once, but
are built incrementally.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D115934

Files:
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
  clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp


Index: clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp
===
--- clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp
+++ clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp
@@ -19,6 +19,14 @@
 namespace ento {
 namespace {
 
+using ArgsContainer = std::vector>;
+
+static_assert(
+std::is_constructible,
+  decltype(std::declval().begin()),
+  decltype(std::declval().end())>(),
+"should be range constructible");
+
 // A wrapper around CallDescriptionMap that allows verifying that
 // all functions have been found. This is needed because CallDescriptionMap
 // isn't supposed to support iteration.
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
@@ -134,6 +134,9 @@
   std::initializer_list> &&List)
   : LinearMap(List) {}
 
+  template 
+  CallDescriptionMap(InputIt First, InputIt Last) : LinearMap(First, Last) {}
+
   ~CallDescriptionMap() = default;
 
   // These maps are usually stored once per checker, so let's make sure


Index: clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp
===
--- clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp
+++ clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp
@@ -19,6 +19,14 @@
 namespace ento {
 namespace {
 
+using ArgsContainer = std::vector>;
+
+static_assert(
+std::is_constructible,
+  decltype(std::declval().begin()),
+  decltype(std::declval().end())>(),
+"should be range constructible");
+
 // A wrapper around CallDescriptionMap that allows verifying that
 // all functions have been found. This is needed because CallDescriptionMap
 // isn't supposed to support iteration.
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
===
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h
@@ -134,6 +134,9 @@
   std::initializer_list> &&List)
   : LinearMap(List) {}
 
+  template 
+  CallDescriptionMap(InputIt First, InputIt Last) : LinearMap(First, Last) {}
+
   ~CallDescriptionMap() = default;
 
   // These maps are usually stored once per checker, so let's make sure
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D115935: [clang][deps] NFC: Simplify handling of cached FS errors

2021-12-17 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 created this revision.
jansvoboda11 added reviewers: Bigcheese, dexonsmith, arphaman.
jansvoboda11 requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

The return types of some `CachedFileSystemEntry` member function are needlessly 
complex.

This patch attempts to simplify the code by unwrapping cached entries that 
represent errors early, and then asserting `!isError()`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D115935

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

Index: clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
===
--- clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
+++ clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
@@ -164,7 +164,7 @@
 
   const auto *Entry = LocalCache.getCachedEntry(Filename);
   if (Entry && !Entry->needsUpdate(ShouldBeMinimized))
-return EntryRef(ShouldBeMinimized, *Entry);
+return EntryRef(ShouldBeMinimized, *Entry).unwrapError();
 
   // FIXME: Handle PCM/PCH files.
   // FIXME: Handle module map files.
@@ -194,7 +194,7 @@
 
   // Store the result in the local cache.
   Entry = &SharedCacheEntry.Value;
-  return EntryRef(ShouldBeMinimized, *Entry);
+  return EntryRef(ShouldBeMinimized, *Entry).unwrapError();
 }
 
 llvm::ErrorOr
@@ -241,16 +241,15 @@
 
 llvm::ErrorOr> MinimizedVFSFile::create(
 EntryRef Entry, ExcludedPreprocessorDirectiveSkipMapping *PPSkipMappings) {
+  assert(!Entry.isError() && "error");
+
   if (Entry.isDirectory())
 return std::make_error_code(std::errc::is_a_directory);
 
-  llvm::ErrorOr Contents = Entry.getContents();
-  if (!Contents)
-return Contents.getError();
   auto Result = std::make_unique(
-  llvm::MemoryBuffer::getMemBuffer(*Contents, Entry.getName(),
+  llvm::MemoryBuffer::getMemBuffer(Entry.getContents(), Entry.getName(),
/*RequiresNullTerminator=*/false),
-  *Entry.getStatus());
+  Entry.getStatus());
 
   const auto *EntrySkipMappings = Entry.getPPSkippedRangeMapping();
   if (EntrySkipMappings && !EntrySkipMappings->empty() && PPSkipMappings)
Index: clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
===
--- clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
+++ clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
@@ -57,25 +57,26 @@
 return !MaybeStat || MaybeStat->isStatusKnown();
   }
 
+  /// \returns True if the entry is a filesystem error.
+  bool isError() const { return !MaybeStat; }
+
   /// \returns True if the current entry points to a directory.
-  bool isDirectory() const { return MaybeStat && MaybeStat->isDirectory(); }
+  bool isDirectory() const { return !isError() && MaybeStat->isDirectory(); }
 
-  /// \returns The error or the file's original contents.
-  llvm::ErrorOr getOriginalContents() const {
-if (!MaybeStat)
-  return MaybeStat.getError();
-assert(!MaybeStat->isDirectory() && "not a file");
+  /// \returns Original contents of the file.
+  StringRef getOriginalContents() const {
 assert(isInitialized() && "not initialized");
+assert(!isError() && "error");
+assert(!MaybeStat->isDirectory() && "not a file");
 assert(OriginalContents && "not read");
 return OriginalContents->getBuffer();
   }
 
-  /// \returns The error or the file's minimized contents.
-  llvm::ErrorOr getMinimizedContents() const {
-if (!MaybeStat)
-  return MaybeStat.getError();
-assert(!MaybeStat->isDirectory() && "not a file");
+  /// \returns Minimized contents of the file.
+  StringRef getMinimizedContents() const {
 assert(isInitialized() && "not initialized");
+assert(!isError() && "error");
+assert(!isDirectory() && "not a file");
 llvm::MemoryBuffer *Buffer = MinimizedContentsAccess.load();
 assert(Buffer && "not minimized");
 return Buffer->getBuffer();
@@ -94,15 +95,23 @@
 return ShouldBeMinimized && !MinimizedContentsAccess.load();
   }
 
-  /// \returns The error or the status of the entry.
-  llvm::ErrorOr getStatus() const {
+  /// \returns The error.
+  std::error_code getError() const {
+assert(isInitialized() && "not initialized");
+return MaybeStat.getError();
+  }
+
+  /// \returns The entry status.
+  llvm::vfs::Status getStatus() const {
 assert(isInitialized() && "not initialized");
-return MaybeStat;
+assert(!isError() && "error");
+return *MaybeStat;
   }
 
   /// \returns the name of the file.
   StringRef getName() const {
 assert(isInitialized() && "not initialized");
+assert(!isError() && "error");
 return MaybeStat->getName();
   }
 
@@ -183,19 +192,25 @@
  

[PATCH] D115935: [clang][deps] NFC: Simplify handling of cached FS errors

2021-12-17 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 395101.
jansvoboda11 added a comment.

Add more assertions.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115935

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

Index: clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
===
--- clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
+++ clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
@@ -164,7 +164,7 @@
 
   const auto *Entry = LocalCache.getCachedEntry(Filename);
   if (Entry && !Entry->needsUpdate(ShouldBeMinimized))
-return EntryRef(ShouldBeMinimized, *Entry);
+return EntryRef(ShouldBeMinimized, *Entry).unwrapError();
 
   // FIXME: Handle PCM/PCH files.
   // FIXME: Handle module map files.
@@ -194,7 +194,7 @@
 
   // Store the result in the local cache.
   Entry = &SharedCacheEntry.Value;
-  return EntryRef(ShouldBeMinimized, *Entry);
+  return EntryRef(ShouldBeMinimized, *Entry).unwrapError();
 }
 
 llvm::ErrorOr
@@ -241,16 +241,15 @@
 
 llvm::ErrorOr> MinimizedVFSFile::create(
 EntryRef Entry, ExcludedPreprocessorDirectiveSkipMapping *PPSkipMappings) {
+  assert(!Entry.isError() && "error");
+
   if (Entry.isDirectory())
 return std::make_error_code(std::errc::is_a_directory);
 
-  llvm::ErrorOr Contents = Entry.getContents();
-  if (!Contents)
-return Contents.getError();
   auto Result = std::make_unique(
-  llvm::MemoryBuffer::getMemBuffer(*Contents, Entry.getName(),
+  llvm::MemoryBuffer::getMemBuffer(Entry.getContents(), Entry.getName(),
/*RequiresNullTerminator=*/false),
-  *Entry.getStatus());
+  Entry.getStatus());
 
   const auto *EntrySkipMappings = Entry.getPPSkippedRangeMapping();
   if (EntrySkipMappings && !EntrySkipMappings->empty() && PPSkipMappings)
Index: clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
===
--- clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
+++ clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
@@ -57,25 +57,26 @@
 return !MaybeStat || MaybeStat->isStatusKnown();
   }
 
+  /// \returns True if the entry is a filesystem error.
+  bool isError() const { return !MaybeStat; }
+
   /// \returns True if the current entry points to a directory.
-  bool isDirectory() const { return MaybeStat && MaybeStat->isDirectory(); }
+  bool isDirectory() const { return !isError() && MaybeStat->isDirectory(); }
 
-  /// \returns The error or the file's original contents.
-  llvm::ErrorOr getOriginalContents() const {
-if (!MaybeStat)
-  return MaybeStat.getError();
-assert(!MaybeStat->isDirectory() && "not a file");
+  /// \returns Original contents of the file.
+  StringRef getOriginalContents() const {
 assert(isInitialized() && "not initialized");
+assert(!isError() && "error");
+assert(!MaybeStat->isDirectory() && "not a file");
 assert(OriginalContents && "not read");
 return OriginalContents->getBuffer();
   }
 
-  /// \returns The error or the file's minimized contents.
-  llvm::ErrorOr getMinimizedContents() const {
-if (!MaybeStat)
-  return MaybeStat.getError();
-assert(!MaybeStat->isDirectory() && "not a file");
+  /// \returns Minimized contents of the file.
+  StringRef getMinimizedContents() const {
 assert(isInitialized() && "not initialized");
+assert(!isError() && "error");
+assert(!isDirectory() && "not a file");
 llvm::MemoryBuffer *Buffer = MinimizedContentsAccess.load();
 assert(Buffer && "not minimized");
 return Buffer->getBuffer();
@@ -94,21 +95,31 @@
 return ShouldBeMinimized && !MinimizedContentsAccess.load();
   }
 
-  /// \returns The error or the status of the entry.
-  llvm::ErrorOr getStatus() const {
+  /// \returns The error.
+  std::error_code getError() const {
+assert(isInitialized() && "not initialized");
+return MaybeStat.getError();
+  }
+
+  /// \returns The entry status.
+  llvm::vfs::Status getStatus() const {
 assert(isInitialized() && "not initialized");
-return MaybeStat;
+assert(!isError() && "error");
+return *MaybeStat;
   }
 
   /// \returns the name of the file.
   StringRef getName() const {
 assert(isInitialized() && "not initialized");
+assert(!isError() && "error");
 return MaybeStat->getName();
   }
 
   /// Return the mapping between location -> distance that is used to speed up
   /// the block skipping in the preprocessor.
   const PreprocessorSkippedRangeMapping &getPPSkippedRangeMapping() const {
+assert(!isError() && "error");
+assert(!isDirectory() && "not a file");
 return 

[PATCH] D114966: [clang][deps] Split stat and file content caches

2021-12-17 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 395102.
jansvoboda11 added a comment.

Implement new version that ensures the stat and contents of a file are always 
in sync.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114966

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

Index: clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
===
--- clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
+++ clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
@@ -16,10 +16,10 @@
 using namespace tooling;
 using namespace dependencies;
 
-llvm::ErrorOr
-CachedFileSystemEntry::initFile(StringRef Filename, llvm::vfs::FileSystem &FS) {
+llvm::ErrorOr
+DependencyScanningWorkerFilesystem::readFile(StringRef Filename) {
   // Load the file and its content from the file system.
-  auto MaybeFile = FS.openFileForRead(Filename);
+  auto MaybeFile = getUnderlyingFS().openFileForRead(Filename);
   if (!MaybeFile)
 return MaybeFile.getError();
   auto File = std::move(*MaybeFile);
@@ -34,24 +34,43 @@
 return MaybeBuffer.getError();
   auto Buffer = std::move(*MaybeBuffer);
 
-  OriginalContents = std::move(Buffer);
-  return Stat;
+  // If the file size changed between read and stat, pretend it didn't.
+  if (Stat.getSize() != Buffer->getBufferSize())
+Stat = llvm::vfs::Status::copyWithNewSize(Stat, Buffer->getBufferSize());
+
+  return TentativeEntry(std::move(Stat), std::move(Buffer));
 }
 
-void CachedFileSystemEntry::minimizeFile() {
-  assert(OriginalContents && "minimizing missing contents");
+EntryRef DependencyScanningWorkerFilesystem::minimizeIfNecessary(
+const CachedFileSystemEntry &Entry) {
+  if (Entry.isError() || Entry.isDirectory() ||
+  !shouldMinimize(Entry.getName()))
+return EntryRef(false, Entry);
+
+  CachedFileContents *Contents = Entry.getContents();
+  assert(Contents && "contents not allocated");
+
+  // Double-checked locking.
+  if (Contents->MinimizedAccess.load())
+return EntryRef(true, Entry);
+
+  std::lock_guard GuardLock(Contents->ValueLock);
+
+  // Double-checked locking.
+  if (Contents->MinimizedAccess.load())
+return EntryRef(true, Entry);
 
   llvm::SmallString<1024> MinimizedFileContents;
   // Minimize the file down to directives that might affect the dependencies.
   SmallVector Tokens;
-  if (minimizeSourceToDependencyDirectives(OriginalContents->getBuffer(),
+  if (minimizeSourceToDependencyDirectives(Contents->Original->getBuffer(),
MinimizedFileContents, Tokens)) {
 // FIXME: Propagate the diagnostic if desired by the client.
 // Use the original file if the minimization failed.
-MinimizedContentsStorage =
-llvm::MemoryBuffer::getMemBuffer(*OriginalContents);
-MinimizedContentsAccess.store(MinimizedContentsStorage.get());
-return;
+Contents->MinimizedStorage =
+llvm::MemoryBuffer::getMemBuffer(*Contents->Original);
+Contents->MinimizedAccess.store(Contents->MinimizedStorage.get());
+return EntryRef(true, Entry);
   }
 
   // The contents produced by the minimizer must be null terminated.
@@ -74,16 +93,17 @@
 }
 Mapping[Range.Offset] = Range.Length;
   }
-  PPSkippedRangeMapping = std::move(Mapping);
+  Contents->PPSkippedRangeMapping = std::move(Mapping);
 
-  MinimizedContentsStorage = std::make_unique(
+  Contents->MinimizedStorage = std::make_unique(
   std::move(MinimizedFileContents));
-  // The algorithm in `getOrCreateFileSystemEntry` uses the presence of
-  // minimized contents to decide whether an entry is up-to-date or not.
-  // If it is up-to-date, the skipped range mappings must be already computed.
-  // This is why we need to store the minimized contents **after** storing the
-  // skipped range mappings. Failing to do so would lead to a data race.
-  MinimizedContentsAccess.store(MinimizedContentsStorage.get());
+  // This function performed double-checked locking using `MinimizedAccess`.
+  // Assigning it must be the last thing this function does. If we were to
+  // assign it before `PPSkippedRangeMapping`, other threads may skip the
+  // critical section (`MinimizedAccess != nullptr`) and access the mappings
+  // that are about to be initialized, leading to a data race.
+  Contents->MinimizedAccess.store(Contents->MinimizedStorage.get());
+  return EntryRef(true, Entry);
 }
 
 DependencyScanningFilesystemSharedCache::
@@ -98,12 +118,69 @@
   CacheShards = std::make_unique(NumShards);
 }
 
-DependencyScanningFilesystemSharedCache::SharedFileSystemEntry &
-DependencyScanningFilesystemSharedCache::get(StringRef Key) {
-  CacheShard &Shard = CacheShards[llvm::hash_value(Key) % NumShards];
-  std::lock_guard LockGuard(Shard.Ca

[PATCH] D114966: [clang][deps] Split stat and file content caches

2021-12-17 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 395103.
jansvoboda11 added a comment.

Re-run CI.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114966

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

Index: clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
===
--- clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
+++ clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
@@ -16,10 +16,10 @@
 using namespace tooling;
 using namespace dependencies;
 
-llvm::ErrorOr
-CachedFileSystemEntry::initFile(StringRef Filename, llvm::vfs::FileSystem &FS) {
+llvm::ErrorOr
+DependencyScanningWorkerFilesystem::readFile(StringRef Filename) {
   // Load the file and its content from the file system.
-  auto MaybeFile = FS.openFileForRead(Filename);
+  auto MaybeFile = getUnderlyingFS().openFileForRead(Filename);
   if (!MaybeFile)
 return MaybeFile.getError();
   auto File = std::move(*MaybeFile);
@@ -34,24 +34,43 @@
 return MaybeBuffer.getError();
   auto Buffer = std::move(*MaybeBuffer);
 
-  OriginalContents = std::move(Buffer);
-  return Stat;
+  // If the file size changed between read and stat, pretend it didn't.
+  if (Stat.getSize() != Buffer->getBufferSize())
+Stat = llvm::vfs::Status::copyWithNewSize(Stat, Buffer->getBufferSize());
+
+  return TentativeEntry(std::move(Stat), std::move(Buffer));
 }
 
-void CachedFileSystemEntry::minimizeFile() {
-  assert(OriginalContents && "minimizing missing contents");
+EntryRef DependencyScanningWorkerFilesystem::minimizeIfNecessary(
+const CachedFileSystemEntry &Entry) {
+  if (Entry.isError() || Entry.isDirectory() ||
+  !shouldMinimize(Entry.getName()))
+return EntryRef(false, Entry);
+
+  CachedFileContents *Contents = Entry.getContents();
+  assert(Contents && "contents not allocated");
+
+  // Double-checked locking.
+  if (Contents->MinimizedAccess.load())
+return EntryRef(true, Entry);
+
+  std::lock_guard GuardLock(Contents->ValueLock);
+
+  // Double-checked locking.
+  if (Contents->MinimizedAccess.load())
+return EntryRef(true, Entry);
 
   llvm::SmallString<1024> MinimizedFileContents;
   // Minimize the file down to directives that might affect the dependencies.
   SmallVector Tokens;
-  if (minimizeSourceToDependencyDirectives(OriginalContents->getBuffer(),
+  if (minimizeSourceToDependencyDirectives(Contents->Original->getBuffer(),
MinimizedFileContents, Tokens)) {
 // FIXME: Propagate the diagnostic if desired by the client.
 // Use the original file if the minimization failed.
-MinimizedContentsStorage =
-llvm::MemoryBuffer::getMemBuffer(*OriginalContents);
-MinimizedContentsAccess.store(MinimizedContentsStorage.get());
-return;
+Contents->MinimizedStorage =
+llvm::MemoryBuffer::getMemBuffer(*Contents->Original);
+Contents->MinimizedAccess.store(Contents->MinimizedStorage.get());
+return EntryRef(true, Entry);
   }
 
   // The contents produced by the minimizer must be null terminated.
@@ -74,16 +93,17 @@
 }
 Mapping[Range.Offset] = Range.Length;
   }
-  PPSkippedRangeMapping = std::move(Mapping);
+  Contents->PPSkippedRangeMapping = std::move(Mapping);
 
-  MinimizedContentsStorage = std::make_unique(
+  Contents->MinimizedStorage = std::make_unique(
   std::move(MinimizedFileContents));
-  // The algorithm in `getOrCreateFileSystemEntry` uses the presence of
-  // minimized contents to decide whether an entry is up-to-date or not.
-  // If it is up-to-date, the skipped range mappings must be already computed.
-  // This is why we need to store the minimized contents **after** storing the
-  // skipped range mappings. Failing to do so would lead to a data race.
-  MinimizedContentsAccess.store(MinimizedContentsStorage.get());
+  // This function performed double-checked locking using `MinimizedAccess`.
+  // Assigning it must be the last thing this function does. If we were to
+  // assign it before `PPSkippedRangeMapping`, other threads may skip the
+  // critical section (`MinimizedAccess != nullptr`) and access the mappings
+  // that are about to be initialized, leading to a data race.
+  Contents->MinimizedAccess.store(Contents->MinimizedStorage.get());
+  return EntryRef(true, Entry);
 }
 
 DependencyScanningFilesystemSharedCache::
@@ -98,12 +118,69 @@
   CacheShards = std::make_unique(NumShards);
 }
 
-DependencyScanningFilesystemSharedCache::SharedFileSystemEntry &
-DependencyScanningFilesystemSharedCache::get(StringRef Key) {
-  CacheShard &Shard = CacheShards[llvm::hash_value(Key) % NumShards];
-  std::lock_guard LockGuard(Shard.CacheLock);
-  auto It = Shard.Cache.try_emplace(Key);
-  return It.first->getV

[PATCH] D114971: [clang][deps] Handle symlinks in minimizing FS

2021-12-17 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 updated this revision to Diff 395104.
jansvoboda11 added a comment.

Rebase on top of new version of D114966 .


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114971

Files:
  clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
  clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
  clang/test/ClangScanDeps/modules-symlink.c

Index: clang/test/ClangScanDeps/modules-symlink.c
===
--- /dev/null
+++ clang/test/ClangScanDeps/modules-symlink.c
@@ -0,0 +1,54 @@
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+
+//--- cdb_pch.json
+[
+  {
+"directory": "DIR",
+"command": "clang -x c-header DIR/pch.h -fmodules -gmodules -fimplicit-module-maps -fmodules-cache-path=DIR/cache -o DIR/pch.h.gch",
+"file": "DIR/pch.h"
+  }
+]
+
+//--- cdb_tu.json
+[
+  {
+"directory": "DIR",
+"command": "clang -c DIR/tu.c -fmodules -gmodules -fimplicit-module-maps -fmodules-cache-path=DIR/cache -include DIR/pch.h -o DIR/tu.o",
+"file": "DIR/tu.c"
+  }
+]
+
+//--- module.modulemap
+module mod { header "symlink.h" }
+
+//--- pch.h
+#include "symlink.h"
+
+//--- original.h
+// Comment that will be stripped by the minimizer.
+#define MACRO 1
+
+//--- tu.c
+#include "original.h"
+static int foo = MACRO; // Macro usage that will trigger
+// input file consistency checks.
+
+// RUN: ln -s %t/original.h %t/symlink.h
+
+// RUN: sed -e "s|DIR|%/t|g" %t/cdb_pch.json > %t/cdb.json
+// RUN: clang-scan-deps -compilation-database %t/cdb.json -format experimental-full \
+// RUN:   -generate-modules-path-args -module-files-dir %t/build > %t/result_pch.json
+//
+// RUN: %python %S/../../utils/module-deps-to-rsp.py %t/result_pch.json \
+// RUN:   --module-name=mod > %t/mod.cc1.rsp
+// RUN: %python %S/../../utils/module-deps-to-rsp.py %t/result_pch.json \
+// RUN:   --tu-index=0 > %t/pch.rsp
+//
+// RUN: %clang @%t/mod.cc1.rsp
+// RUN: %clang -x c-header %t/pch.h -fmodules -gmodules -fimplicit-module-maps \
+// RUN:   -fmodules-cache-path=%t/cache -o %t/pch.h.gch -I %t @%t/pch.rsp
+
+// RUN: sed -e "s|DIR|%/t|g" %t/cdb_tu.json > %t/cdb.json
+// RUN: clang-scan-deps -compilation-database %t/cdb.json -format experimental-full \
+// RUN:   -generate-modules-path-args -module-files-dir %t/build > %t/result_tu.json
Index: clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
===
--- clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
+++ clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp
@@ -43,8 +43,7 @@
 
 EntryRef DependencyScanningWorkerFilesystem::minimizeIfNecessary(
 const CachedFileSystemEntry &Entry) {
-  if (Entry.isError() || Entry.isDirectory() ||
-  !shouldMinimize(Entry.getName()))
+  if (Entry.isError() || Entry.isDirectory() || !shouldMinimize(Entry))
 return EntryRef(false, Entry);
 
   CachedFileContents *Contents = Entry.getContents();
@@ -210,19 +209,15 @@
 }
 
 void DependencyScanningWorkerFilesystem::disableMinimization(
-StringRef RawFilename) {
-  llvm::SmallString<256> Filename;
-  llvm::sys::path::native(RawFilename, Filename);
-  NotToBeMinimized.insert(Filename);
+StringRef Filename) {
+  if (llvm::ErrorOr Result = getOrCreateFileSystemEntry(Filename))
+NotToBeMinimized.insert(Result->getStatus().getUniqueID());
 }
 
-bool DependencyScanningWorkerFilesystem::shouldMinimize(StringRef RawFilename) {
-  if (!shouldMinimizeBasedOnExtension(RawFilename))
-return false;
-
-  llvm::SmallString<256> Filename;
-  llvm::sys::path::native(RawFilename, Filename);
-  return !NotToBeMinimized.contains(Filename);
+bool DependencyScanningWorkerFilesystem::shouldMinimize(
+const CachedFileSystemEntry &Entry) {
+  return shouldMinimizeBasedOnExtension(Entry.getName()) &&
+ !NotToBeMinimized.contains(Entry.getUniqueID());
 }
 
 const CachedFileSystemEntry &
Index: clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
===
--- clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
+++ clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
@@ -11,8 +11,8 @@
 
 #include "clang/Basic/LLVM.h"
 #include "clang/Lex/PreprocessorExcludedConditionalDirectiveSkipMapping.h"
+#include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/StringMap.h"
-#include "llvm/ADT/StringSet.h"
 #include "llvm/Support/Allocator.h"
 #include "llvm/Support/ErrorOr.h"
 #include "llvm/Support/VirtualFileSystem.h"
@@ -305,7 +305,7 @@
 
 private:
   /// Check whether the file should be minimized.
-  bool shouldMinimize(StringRef Filename);
+  bool shouldMinimize(const CachedFileSystemEntry &Entry);
 
   /// Returns entry for the 

[PATCH] D113837: Sema: Let InitListExpr have dependent type instead of 'void'

2021-12-17 Thread Aaron Puchert via Phabricator via cfe-commits
aaronpuchert added a comment.

Ping.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D113837

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


[PATCH] D115936: [Clang] Add isInNamespace() to check if a Decl in a specific namespace

2021-12-17 Thread Jun Zhang via Phabricator via cfe-commits
junaire created this revision.
junaire added reviewers: rtrieu, ddunbar, CornedBee, gribozavr.
junaire requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Currently we can only check whether a Decl in namespace `std` or not.
However, it will very useful if we can have a API to check if a Decl in
a specific namespace. With this, we can implement clang-tidy checks to
replace some old third-party library component to std, like boost::shared_ptr.

Signed-off-by: Jun Zhang 


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D115936

Files:
  clang/include/clang/AST/DeclBase.h
  clang/lib/AST/DeclBase.cpp


Index: clang/lib/AST/DeclBase.cpp
===
--- clang/lib/AST/DeclBase.cpp
+++ clang/lib/AST/DeclBase.cpp
@@ -392,8 +392,12 @@
 }
 
 bool Decl::isInStdNamespace() const {
+   return isInNamespace("std");
+}
+
+bool Decl::isInNamespace(llvm::StringRef Namespace) const {
   const DeclContext *DC = getDeclContext();
-  return DC && DC->isStdNamespace();
+  return DC && DC->isNamespace(Namespace);
 }
 
 TranslationUnitDecl *Decl::getTranslationUnitDecl() {
@@ -1124,6 +1128,10 @@
 }
 
 bool DeclContext::isStdNamespace() const {
+   return isNamespace("std");
+}
+
+bool DeclContext::isNamespace(llvm::StringRef Namespace) const {
   if (!isNamespace())
 return false;
 
@@ -1136,7 +1144,7 @@
 return false;
 
   const IdentifierInfo *II = ND->getIdentifier();
-  return II && II->isStr("std");
+  return II && II->isStr(Namespace);
 }
 
 bool DeclContext::isDependentContext() const {
Index: clang/include/clang/AST/DeclBase.h
===
--- clang/include/clang/AST/DeclBase.h
+++ clang/include/clang/AST/DeclBase.h
@@ -463,6 +463,7 @@
   bool isInAnonymousNamespace() const;
 
   bool isInStdNamespace() const;
+  bool isInNamespace(llvm::StringRef Namespace) const;
 
   ASTContext &getASTContext() const LLVM_READONLY;
 
@@ -1945,6 +1946,8 @@
 
   bool isStdNamespace() const;
 
+  bool isNamespace(llvm::StringRef Namespace) const;
+
   bool isInlineNamespace() const;
 
   /// Determines whether this context is dependent on a


Index: clang/lib/AST/DeclBase.cpp
===
--- clang/lib/AST/DeclBase.cpp
+++ clang/lib/AST/DeclBase.cpp
@@ -392,8 +392,12 @@
 }
 
 bool Decl::isInStdNamespace() const {
+	return isInNamespace("std");
+}
+
+bool Decl::isInNamespace(llvm::StringRef Namespace) const {
   const DeclContext *DC = getDeclContext();
-  return DC && DC->isStdNamespace();
+  return DC && DC->isNamespace(Namespace);
 }
 
 TranslationUnitDecl *Decl::getTranslationUnitDecl() {
@@ -1124,6 +1128,10 @@
 }
 
 bool DeclContext::isStdNamespace() const {
+	return isNamespace("std");
+}
+
+bool DeclContext::isNamespace(llvm::StringRef Namespace) const {
   if (!isNamespace())
 return false;
 
@@ -1136,7 +1144,7 @@
 return false;
 
   const IdentifierInfo *II = ND->getIdentifier();
-  return II && II->isStr("std");
+  return II && II->isStr(Namespace);
 }
 
 bool DeclContext::isDependentContext() const {
Index: clang/include/clang/AST/DeclBase.h
===
--- clang/include/clang/AST/DeclBase.h
+++ clang/include/clang/AST/DeclBase.h
@@ -463,6 +463,7 @@
   bool isInAnonymousNamespace() const;
 
   bool isInStdNamespace() const;
+  bool isInNamespace(llvm::StringRef Namespace) const;
 
   ASTContext &getASTContext() const LLVM_READONLY;
 
@@ -1945,6 +1946,8 @@
 
   bool isStdNamespace() const;
 
+  bool isNamespace(llvm::StringRef Namespace) const;
+
   bool isInlineNamespace() const;
 
   /// Determines whether this context is dependent on a
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] a94f68a - Implement some constexpr vector unary operators, fix boolean-ops

2021-12-17 Thread Erich Keane via cfe-commits

Author: Erich Keane
Date: 2021-12-17T06:08:36-08:00
New Revision: a94f68a2bd31db9712582b973e78746cee9a4e50

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

LOG: Implement some constexpr vector unary operators, fix boolean-ops

As requested in the review, this implements unary +,-,~, and ! for
vector types.

All of our boolean operations on vector types should be using something
like vcmpeqd, which results in a mask of '-1' for the 'truth' type. We are
currently instead using '1', which results in some incorrect
calculations when used later (note that it does NOT result in a boolean
vector, as that is not really a thing).

This patch corrects that 1 to be a -1, and updates the affected tests.

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

Added: 


Modified: 
clang/lib/AST/ExprConstant.cpp
clang/lib/Sema/SemaExpr.cpp
clang/test/SemaCXX/constexpr-vectors.cpp

Removed: 




diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index bb59e72ed51b6..9fcba4e25cef6 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -2931,6 +2931,11 @@ handleCompareOpForVectorHelper(const APTy &LHSValue, 
BinaryOperatorKind Opcode,
 break;
   }
 
+  // The boolean operations on these vector types use an instruction that
+  // results in a mask of '-1' for the 'truth' value.  Ensure that we negate 1
+  // to -1 to make sure that we produce the correct value.
+  Result.negate();
+
   return true;
 }
 
@@ -10179,7 +10184,8 @@ namespace {
 bool VisitInitListExpr(const InitListExpr *E);
 bool VisitUnaryImag(const UnaryOperator *E);
 bool VisitBinaryOperator(const BinaryOperator *E);
-// FIXME: Missing: unary -, unary ~, conditional operator (for GNU
+bool VisitUnaryOperator(const UnaryOperator *E);
+// FIXME: Missing: conditional operator (for GNU
 // conditional select), shufflevector, ExtVectorElementExpr
   };
 } // end anonymous namespace
@@ -10364,6 +10370,83 @@ bool VectorExprEvaluator::VisitBinaryOperator(const 
BinaryOperator *E) {
   return Success(LHSValue, E);
 }
 
+static llvm::Optional handleVectorUnaryOperator(ASTContext &Ctx,
+ QualType ResultTy,
+ UnaryOperatorKind Op,
+ APValue Elt) {
+  switch (Op) {
+  case UO_Plus:
+// Nothing to do here.
+return Elt;
+  case UO_Minus:
+if (Elt.getKind() == APValue::Int) {
+  Elt.getInt().negate();
+} else {
+  assert(Elt.getKind() == APValue::Float &&
+ "Vector can only be int or float type");
+  Elt.getFloat().changeSign();
+}
+return Elt;
+  case UO_Not:
+// This is only valid for integral types anyway, so we don't have to handle
+// float here.
+assert(Elt.getKind() == APValue::Int &&
+   "Vector operator ~ can only be int");
+Elt.getInt().flipAllBits();
+return Elt;
+  case UO_LNot: {
+if (Elt.getKind() == APValue::Int) {
+  Elt.getInt() = !Elt.getInt();
+  // operator ! on vectors returns -1 for 'truth', so negate it.
+  Elt.getInt().negate();
+  return Elt;
+}
+assert(Elt.getKind() == APValue::Float &&
+   "Vector can only be int or float type");
+// Float types result in an int of the same size, but -1 for true, or 0 for
+// false.
+APSInt EltResult{Ctx.getIntWidth(ResultTy),
+ ResultTy->isUnsignedIntegerType()};
+if (Elt.getFloat().isZero())
+  EltResult.setAllBits();
+else
+  EltResult.clearAllBits();
+
+return APValue{EltResult};
+  }
+  default:
+// FIXME: Implement the rest of the unary operators.
+return llvm::None;
+  }
+}
+
+bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
+  Expr *SubExpr = E->getSubExpr();
+  const auto *VD = SubExpr->getType()->castAs();
+  // This result element type 
diff ers in the case of negating a floating point
+  // vector, since the result type is the a vector of the equivilant sized
+  // integer.
+  const QualType ResultEltTy = VD->getElementType();
+  UnaryOperatorKind Op = E->getOpcode();
+
+  APValue SubExprValue;
+  if (!Evaluate(SubExprValue, Info, SubExpr))
+return false;
+
+  assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
+ "Vector length doesn't match type?");
+
+  SmallVector ResultElements;
+  for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
+llvm::Optional Elt = handleVectorUnaryOperator(
+Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
+if (!Elt)
+  return false;
+ResultElements.push_back(*Elt);
+  }
+  return Success(APValue(Resul

[PATCH] D115670: Implement some constexpr vector unary operators, fix boolean-ops

2021-12-17 Thread Erich Keane 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 rGa94f68a2bd31: Implement some constexpr vector unary 
operators, fix boolean-ops (authored by erichkeane).
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115670

Files:
  clang/lib/AST/ExprConstant.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/test/SemaCXX/constexpr-vectors.cpp

Index: clang/test/SemaCXX/constexpr-vectors.cpp
===
--- clang/test/SemaCXX/constexpr-vectors.cpp
+++ clang/test/SemaCXX/constexpr-vectors.cpp
@@ -11,12 +11,15 @@
 using FourLongLongsVecSize __attribute__((vector_size(32))) = long long;
 using FourFloatsVecSize __attribute__((vector_size(16))) = float;
 using FourDoublesVecSize __attribute__((vector_size(32))) = double;
+using FourI128VecSize __attribute__((vector_size(64))) = __int128;
 
 using FourCharsExtVec __attribute__((ext_vector_type(4))) = char;
 using FourIntsExtVec __attribute__((ext_vector_type(4))) = int;
 using FourLongLongsExtVec __attribute__((ext_vector_type(4))) = long long;
 using FourFloatsExtVec __attribute__((ext_vector_type(4))) = float;
 using FourDoublesExtVec __attribute__((ext_vector_type(4))) = double;
+using FourI128ExtVec __attribute__((ext_vector_type(4))) = __int128;
+
 
 // Next a series of tests to make sure these operations are usable in
 // constexpr functions. Template instantiations don't emit Winvalid-constexpr,
@@ -204,35 +207,35 @@
 
   constexpr auto w = FourCharsVecSize{1, 2, 3, 4} <
  FourCharsVecSize{4, 3, 2, 1};
-  // CHECK: store <4 x i8> 
+  // CHECK: store <4 x i8> 
   constexpr auto x = FourCharsVecSize{1, 2, 3, 4} >
  FourCharsVecSize{4, 3, 2, 1};
-  // CHECK: store <4 x i8> 
+  // CHECK: store <4 x i8> 
   constexpr auto y = FourCharsVecSize{1, 2, 3, 4} <=
  FourCharsVecSize{4, 3, 3, 1};
-  // CHECK: store <4 x i8> 
+  // CHECK: store <4 x i8> 
   constexpr auto z = FourCharsVecSize{1, 2, 3, 4} >=
  FourCharsVecSize{4, 3, 3, 1};
-  // CHECK: store <4 x i8> 
+  // CHECK: store <4 x i8> 
   constexpr auto A = FourCharsVecSize{1, 2, 3, 4} ==
  FourCharsVecSize{4, 3, 3, 1};
-  // CHECK: store <4 x i8> 
+  // CHECK: store <4 x i8> 
   constexpr auto B = FourCharsVecSize{1, 2, 3, 4} !=
  FourCharsVecSize{4, 3, 3, 1};
-  // CHECK: store <4 x i8> 
+  // CHECK: store <4 x i8> 
 
   constexpr auto C = FourCharsVecSize{1, 2, 3, 4} < 3;
-  // CHECK: store <4 x i8> 
+  // CHECK: store <4 x i8> 
   constexpr auto D = FourCharsVecSize{1, 2, 3, 4} > 3;
-  // CHECK: store <4 x i8> 
+  // CHECK: store <4 x i8> 
   constexpr auto E = FourCharsVecSize{1, 2, 3, 4} <= 3;
-  // CHECK: store <4 x i8> 
+  // CHECK: store <4 x i8> 
   constexpr auto F = FourCharsVecSize{1, 2, 3, 4} >= 3;
-  // CHECK: store <4 x i8> 
+  // CHECK: store <4 x i8> 
   constexpr auto G = FourCharsVecSize{1, 2, 3, 4} == 3;
-  // CHECK: store <4 x i8> 
+  // CHECK: store <4 x i8> 
   constexpr auto H = FourCharsVecSize{1, 2, 3, 4} != 3;
-  // CHECK: store <4 x i8> 
+  // CHECK: store <4 x i8> 
 
   constexpr auto I = FourCharsVecSize{1, 2, 3, 4} &
  FourCharsVecSize{4, 3, 2, 1};
@@ -277,10 +280,12 @@
   constexpr auto Y = CmpSub(a, b);
   // CHECK: store <4 x i8> 
 
-  constexpr auto Z = CmpLSH(a, H);
+  constexpr auto InvH = -H;
+  // CHECK: store <4 x i8> 
+  constexpr auto Z = CmpLSH(a, InvH);
   // CHECK: store <4 x i8> 
 
-  constexpr auto aa = CmpRSH(a, H);
+  constexpr auto aa = CmpRSH(a, InvH);
   // CHECK: store <4 x i8> 
 
   constexpr auto ab = CmpBinAnd(a, b);
@@ -291,6 +296,12 @@
 
   constexpr auto ad = CmpBinOr(a, b);
   // CHECK: store <4 x i8> 
+
+  constexpr auto ae = ~FourCharsVecSize{1, 2, 10, 20};
+  // CHECK: store <4 x i8> 
+
+  constexpr auto af = !FourCharsVecSize{0, 1, 8, -1};
+  // CHECK: store <4 x i8> 
 }
 
 void CharExtVecUsage() {
@@ -348,35 +359,35 @@
 
   constexpr auto w = FourCharsExtVec{1, 2, 3, 4} <
  FourCharsExtVec{4, 3, 2, 1};
-  // CHECK: store <4 x i8> 
+  // CHECK: store <4 x i8> 
   constexpr auto x = FourCharsExtVec{1, 2, 3, 4} >
  FourCharsExtVec{4, 3, 2, 1};
-  // CHECK: store <4 x i8> 
+  // CHECK: store <4 x i8> 
   constexpr auto y = FourCharsExtVec{1, 2, 3, 4} <=
  FourCharsExtVec{4, 3, 3, 1};
-  // CHECK: store <4 x i8> 
+  // CHECK: store <4 x i8> 
   constexpr auto z = FourCharsExtVec{1, 2, 3, 4} >=
  FourCharsExtVec{4, 3, 3, 1};
-  // CHECK: store <4 x i8> 
+  // CHECK: store <4 x i8> 
   constexpr auto A = FourCharsExtVec{1, 2, 3, 4} ==
  FourCharsExtVec{4, 3, 3, 1};
-  // CHECK: store <4 x i8> 
+  // CHECK: store <4 x i8> 
   constexpr auto B = FourCharsExtVec{1, 2, 3, 4

[PATCH] D115938: [clang-format] Formatter does not handle c++11 string literal prefix with stringize #

2021-12-17 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay created this revision.
MyDeveloperDay added reviewers: HazardyKnusperkeks, curdeius, owenpan.
MyDeveloperDay added projects: clang, clang-format.
MyDeveloperDay requested review of this revision.

https://github.com/llvm/llvm-project/issues/27740

Ensure

#define _u(str) u#str
#define _u(str) u8#str
#define _u(str) U#str

behave the same as

#define _u(str) L#str

when formatted

ensure clang-format follows the conventions for `L` `u` `U` `u8`

https://docs.microsoft.com/en-us/cpp/cpp/string-and-character-literals-cpp?redirectedfrom=MSDN&view=msvc-170

Fixes 27740


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D115938

Files:
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTest.cpp


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -4342,6 +4342,9 @@
 
 TEST_F(FormatTest, HashInMacroDefinition) {
   EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle()));
+  EXPECT_EQ("#define A(c) u#c", format("#define A(c) u#c", getLLVMStyle()));
+  EXPECT_EQ("#define A(c) U#c", format("#define A(c) U#c", getLLVMStyle()));
+  EXPECT_EQ("#define A(c) u8#c", format("#define A(c) u8#c", getLLVMStyle()));
   verifyFormat("#define A \\\n  b #c;", getLLVMStyleWithColumns(11));
   verifyFormat("#define A  \\\n"
"  {\\\n"
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -3225,7 +3225,10 @@
 return false;
   if (Left.is(tok::period) || Right.is(tok::period))
 return false;
-  if (Right.is(tok::hash) && Left.is(tok::identifier) && Left.TokenText == "L")
+  // u#str
+  if (Right.is(tok::hash) && Left.is(tok::identifier) &&
+  (Left.TokenText == "L" || Left.TokenText == "u" ||
+   Left.TokenText == "U" || Left.TokenText == "u8"))
 return false;
   if (Left.is(TT_TemplateCloser) && Left.MatchingParen &&
   Left.MatchingParen->Previous &&


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -4342,6 +4342,9 @@
 
 TEST_F(FormatTest, HashInMacroDefinition) {
   EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle()));
+  EXPECT_EQ("#define A(c) u#c", format("#define A(c) u#c", getLLVMStyle()));
+  EXPECT_EQ("#define A(c) U#c", format("#define A(c) U#c", getLLVMStyle()));
+  EXPECT_EQ("#define A(c) u8#c", format("#define A(c) u8#c", getLLVMStyle()));
   verifyFormat("#define A \\\n  b #c;", getLLVMStyleWithColumns(11));
   verifyFormat("#define A  \\\n"
"  {\\\n"
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -3225,7 +3225,10 @@
 return false;
   if (Left.is(tok::period) || Right.is(tok::period))
 return false;
-  if (Right.is(tok::hash) && Left.is(tok::identifier) && Left.TokenText == "L")
+  // u#str
+  if (Right.is(tok::hash) && Left.is(tok::identifier) &&
+  (Left.TokenText == "L" || Left.TokenText == "u" ||
+   Left.TokenText == "U" || Left.TokenText == "u8"))
 return false;
   if (Left.is(TT_TemplateCloser) && Left.MatchingParen &&
   Left.MatchingParen->Previous &&
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D115879: [clang-format] extern with new line brace without indentation

2021-12-17 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius accepted this revision.
curdeius added a comment.
This revision is now accepted and ready to land.

LGTM!




Comment at: clang/lib/Format/UnwrappedLineParser.cpp:1285-1287
+if (Style.BraceWrapping.AfterExternBlock) {
+  addUnwrappedLine();
 }

Nit.


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

https://reviews.llvm.org/D115879

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


[PATCH] D115938: [clang-format] Formatter does not handle c++11 string literal prefix with stringize #

2021-12-17 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius added a comment.

When at it, should we also take care of `LR"(string)"`, `uR...`, `u8R` and 
`UR`? Cf. https://en.cppreference.com/w/cpp/language/string_literal
From MS doc:

  // Raw string literals containing unescaped \ and "
  auto R0 =   R"("Hello \ world")"; // const char*
  auto R1 = u8R"("Hello \ world")"; // const char* before C++20, encoded as 
UTF-8,
// const char8_t* in C++20
  auto R2 =  LR"("Hello \ world")"; // const wchar_t*
  auto R3 =  uR"("Hello \ world")"; // const char16_t*, encoded as UTF-16
  auto R4 =  UR"("Hello \ world")"; // const char32_t*, encoded as UTF-32


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115938

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


[PATCH] D115938: [clang-format] Formatter does not handle c++11 string literal prefix with stringize #

2021-12-17 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

In D115938#3199832 , @curdeius wrote:

> When at it, should we also take care of `LR"(string)"`, `R`, `uR`, `u8R` and 
> `UR`? Cf. https://en.cppreference.com/w/cpp/language/string_literal
> From MS doc:
>
>   // Raw string literals containing unescaped \ and "
>   auto R0 =   R"("Hello \ world")"; // const char*
>   auto R1 = u8R"("Hello \ world")"; // const char* before C++20, encoded as 
> UTF-8,
> // const char8_t* in C++20
>   auto R2 =  LR"("Hello \ world")"; // const wchar_t*
>   auto R3 =  uR"("Hello \ world")"; // const char16_t*, encoded as UTF-16
>   auto R4 =  UR"("Hello \ world")"; // const char32_t*, encoded as UTF-32

I did think about that but I was thinking about how would the calling side work?

  #define MyRawString(str) R#str
  
  
  void foo()
  {
const char *s = MyRawString("(" Hello \ world ")")
  }

I think trying to pass the raw string into the macro confuses it no? this was 
why I left them out for now. Unless someone can give me an example of how it 
might work.

  Microsoft (R) C/C++ Optimizing Compiler Version 19.29.30137 for x64
  Copyright (C) Microsoft Corporation.  All rights reserved.
  
  test12.cpp
  test12.cpp(5): error C3513: '\': unsupported raw string literal delimiter 
character
  test12.cpp(7): error C3516: unexpected end-of-file found while processing the 
raw string literal; delimiter sequence '")' was not matched
  test12.cpp(5): note: start of raw string literal
  test12.cpp(7): fatal error C1903: unable to recover from previous error(s); 
stopping compilation




Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115938

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


[PATCH] D115934: [analyzer] Add range constructor to CallDescriptionMap

2021-12-17 Thread Balázs Benics via Phabricator via cfe-commits
steakhal accepted this revision.
steakhal added a comment.
This revision is now accepted and ready to land.

LGTM




Comment at: clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp:24-28
+static_assert(
+std::is_constructible,
+  decltype(std::declval().begin()),
+  decltype(std::declval().end())>(),
+"should be range constructible");

I'm not even sure we need this assertion though.



Comment at: clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp:38
 public:
   ResultMap(std::initializer_list> Data)
   : Found(0),

Maybe the `ResultMap` should also follow this and declare the ctor overload.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115934

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


[PATCH] D115938: [clang-format] Formatter does not handle c++11 string literal prefix with stringize #

2021-12-17 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius added a comment.

You shouldn't have added the outer quotes as `#str` adds them.
This works:

  // clang-format off
  #define MyRawString(str) R#str
  
  void foo()
  {
  const auto * s1 = MyRawString((" Hello \ world "));
  const auto * s2 = MyRawString(abc(" Hello \ world ")abc);
  }


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115938

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


[PATCH] D115931: [analyzer] Enable move semantics for CallDescriptionMap

2021-12-17 Thread Balázs Benics via Phabricator via cfe-commits
steakhal accepted this revision.
steakhal added a comment.
This revision is now accepted and ready to land.

LGTM




Comment at: clang/unittests/StaticAnalyzer/CallDescriptionTest.cpp:22
 
+static_assert(std::is_move_constructible>() &&
+  std::is_move_assignable>(),

Now I get why you assert this. This is actually an NFC change, which introduces 
a new overload/function. It cannot change existing behavior, so we don't need 
to test this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115931

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


[PATCH] D115932: [Analyzer] Create and handle SymbolCast for pointer to integral conversion

2021-12-17 Thread Balázs Benics via Phabricator via cfe-commits
steakhal added a comment.

Many thanks for digging into this @martong. I really enjoyed it!
I also believe that this is the fix for the underlying issue.

I also think the `getAsSymbol()` should be somewhere where we can create new 
symbols.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115932

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


[PATCH] D115738: [clang-format] Fix formatting of the code that follows C# Lambda Expressions

2021-12-17 Thread Peter Stys via Phabricator via cfe-commits
peterstys added a comment.

This is my first PR into this repo. I'd like to learn more about the process of 
submitting patches, specifically about:

- Do I need to get LGTM from all the reviewers before I can submit it?
- There are some build failures on the CI, but look unrelated, do I force 
submit passed them?

Could someone help me with these questions or point me to the relevant 
documentation. Thanks.


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

https://reviews.llvm.org/D115738

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


[clang] 9e45146 - [CodeGen] Fix element type for sret argument

2021-12-17 Thread Nikita Popov via cfe-commits

Author: Nikita Popov
Date: 2021-12-17T16:13:28+01:00
New Revision: 9e451467217be1325e95eca60bad7924d23e4fe4

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

LOG: [CodeGen] Fix element type for sret argument

Fix a mistake in 9bf917394eba3ba4df77cc17690c6d04f4e9d57f: sret
arguments use ConvertType, not ConvertTypeForMem, see the handling
in CodeGenTypes::GetFunctionType().

This fixes fp-matrix-pragma.c on s390x.

Added: 


Modified: 
clang/lib/CodeGen/CodeGenFunction.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CodeGenFunction.cpp 
b/clang/lib/CodeGen/CodeGenFunction.cpp
index 91deeb657d623..4c488bcd552ff 100644
--- a/clang/lib/CodeGen/CodeGenFunction.cpp
+++ b/clang/lib/CodeGen/CodeGenFunction.cpp
@@ -1070,7 +1070,7 @@ void CodeGenFunction::StartFunction(GlobalDecl GD, 
QualType RetTy,
 auto AI = CurFn->arg_begin();
 if (CurFnInfo->getReturnInfo().isSRetAfterThis())
   ++AI;
-ReturnValue = Address(&*AI, ConvertTypeForMem(RetTy),
+ReturnValue = Address(&*AI, ConvertType(RetTy),
   CurFnInfo->getReturnInfo().getIndirectAlign());
 if (!CurFnInfo->getReturnInfo().getIndirectByVal()) {
   ReturnValuePointer =



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


[PATCH] D115936: [Clang] Add isInNamespace() to check if a Decl in a specific namespace

2021-12-17 Thread Jun Zhang via Phabricator via cfe-commits
junaire updated this revision to Diff 395125.
junaire added a comment.

Format patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115936

Files:
  clang/include/clang/AST/DeclBase.h
  clang/lib/AST/DeclBase.cpp


Index: clang/lib/AST/DeclBase.cpp
===
--- clang/lib/AST/DeclBase.cpp
+++ clang/lib/AST/DeclBase.cpp
@@ -391,9 +391,11 @@
   return false;
 }
 
-bool Decl::isInStdNamespace() const {
+bool Decl::isInStdNamespace() const { return isInNamespace("std"); }
+
+bool Decl::isInNamespace(llvm::StringRef Namespace) const {
   const DeclContext *DC = getDeclContext();
-  return DC && DC->isStdNamespace();
+  return DC && DC->isNamespace(Namespace);
 }
 
 TranslationUnitDecl *Decl::getTranslationUnitDecl() {
@@ -1123,7 +1125,9 @@
  cast(this)->isInline();
 }
 
-bool DeclContext::isStdNamespace() const {
+bool DeclContext::isStdNamespace() const { return isNamespace("std"); }
+
+bool DeclContext::isNamespace(llvm::StringRef Namespace) const {
   if (!isNamespace())
 return false;
 
@@ -1136,7 +1140,7 @@
 return false;
 
   const IdentifierInfo *II = ND->getIdentifier();
-  return II && II->isStr("std");
+  return II && II->isStr(Namespace);
 }
 
 bool DeclContext::isDependentContext() const {
Index: clang/include/clang/AST/DeclBase.h
===
--- clang/include/clang/AST/DeclBase.h
+++ clang/include/clang/AST/DeclBase.h
@@ -463,6 +463,7 @@
   bool isInAnonymousNamespace() const;
 
   bool isInStdNamespace() const;
+  bool isInNamespace(llvm::StringRef Namespace) const;
 
   ASTContext &getASTContext() const LLVM_READONLY;
 
@@ -1945,6 +1946,8 @@
 
   bool isStdNamespace() const;
 
+  bool isNamespace(llvm::StringRef Namespace) const;
+
   bool isInlineNamespace() const;
 
   /// Determines whether this context is dependent on a


Index: clang/lib/AST/DeclBase.cpp
===
--- clang/lib/AST/DeclBase.cpp
+++ clang/lib/AST/DeclBase.cpp
@@ -391,9 +391,11 @@
   return false;
 }
 
-bool Decl::isInStdNamespace() const {
+bool Decl::isInStdNamespace() const { return isInNamespace("std"); }
+
+bool Decl::isInNamespace(llvm::StringRef Namespace) const {
   const DeclContext *DC = getDeclContext();
-  return DC && DC->isStdNamespace();
+  return DC && DC->isNamespace(Namespace);
 }
 
 TranslationUnitDecl *Decl::getTranslationUnitDecl() {
@@ -1123,7 +1125,9 @@
  cast(this)->isInline();
 }
 
-bool DeclContext::isStdNamespace() const {
+bool DeclContext::isStdNamespace() const { return isNamespace("std"); }
+
+bool DeclContext::isNamespace(llvm::StringRef Namespace) const {
   if (!isNamespace())
 return false;
 
@@ -1136,7 +1140,7 @@
 return false;
 
   const IdentifierInfo *II = ND->getIdentifier();
-  return II && II->isStr("std");
+  return II && II->isStr(Namespace);
 }
 
 bool DeclContext::isDependentContext() const {
Index: clang/include/clang/AST/DeclBase.h
===
--- clang/include/clang/AST/DeclBase.h
+++ clang/include/clang/AST/DeclBase.h
@@ -463,6 +463,7 @@
   bool isInAnonymousNamespace() const;
 
   bool isInStdNamespace() const;
+  bool isInNamespace(llvm::StringRef Namespace) const;
 
   ASTContext &getASTContext() const LLVM_READONLY;
 
@@ -1945,6 +1946,8 @@
 
   bool isStdNamespace() const;
 
+  bool isNamespace(llvm::StringRef Namespace) const;
+
   bool isInlineNamespace() const;
 
   /// Determines whether this context is dependent on a
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D115738: [clang-format] Fix formatting of the code that follows C# Lambda Expressions

2021-12-17 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

In D115738#3199879 , @peterstys wrote:

> This is my first PR into this repo. I'd like to learn more about the process 
> of submitting patches, specifically about:
>
> - Do I need to get LGTM from all the reviewers before I can submit it?



  No, one is likely enough, but employ some level of respect for others if they 
are commenting (they may not explicitly say LGTM but may accept) 

> - There are some build failures on the CI, but look unrelated, do I force 
> submit passed them?



  They CI doesn't block commit. just check to ensure its not you, (there is 
some odd Go issue ATM which I've seen reported elsewhere)

> Could someone help me with these questions or point me to the relevant 
> documentation. Thanks.

https://llvm.org/docs/Contributing.html
https://llvm.org/docs/Phabricator.html


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

https://reviews.llvm.org/D115738

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


[PATCH] D115790: [Coroutines] Set presplit attribute in Clang

2021-12-17 Thread Eugene Zhulenev via Phabricator via cfe-commits
ezhulenev added a subscriber: mehdi_amini.
ezhulenev added a comment.

There are two places where in MLIR you can put an attribute to coroutine 
functions:

1. 
https://github.com/llvm/llvm-project/blob/main/mlir/lib/Dialect/Async/Transforms/AsyncToAsyncRuntime.cpp#L126

This is the point when coroutine functions are created, and you can attach 
attribute to the `func` argument

2. 
https://github.com/llvm/llvm-project/blob/main/mlir/lib/Conversion/AsyncToLLVM/AsyncToLLVM.cpp#L325

Another options is to attach attribute to the `op->getParentOfType` 
when async runtime operations lowered to `coro.id` intrinsic.

/cc @mehdi_amini to chime in what option is better. I'm not sure though what 
type of MLIR attribute will be translated to LLVM `"coroutine.presplit"="0"`, 
`UnitAttr`? Or it must be `IntegerAttr`.

I'm on vacation with limjted access to computer until the end of the year, I 
can take a look at it myself ~late Dec or early Jan.


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

https://reviews.llvm.org/D115790

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


[PATCH] D115441: [X86][MS] Add 80bit long double support for Windows

2021-12-17 Thread Phoebe Wang via Phabricator via cfe-commits
pengfei updated this revision to Diff 395128.
pengfei added a comment.

Split the LLVM datalayout to a different patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115441

Files:
  clang/lib/Basic/TargetInfo.cpp
  clang/lib/Basic/Targets/X86.h
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/test/CodeGen/X86/long-double-config-size.c
  clang/test/CodeGen/target-data.c
  llvm/lib/Target/X86/X86TargetMachine.cpp
  llvm/test/CodeGen/X86/long-double-abi-align.ll
  llvm/test/CodeGen/X86/scalar-fp-to-i32.ll
  llvm/test/CodeGen/X86/scalar-fp-to-i64.ll

Index: llvm/test/CodeGen/X86/scalar-fp-to-i64.ll
===
--- llvm/test/CodeGen/X86/scalar-fp-to-i64.ll
+++ llvm/test/CodeGen/X86/scalar-fp-to-i64.ll
@@ -909,8 +909,8 @@
 ; X86-AVX512-WIN:   # %bb.0:
 ; X86-AVX512-WIN-NEXT:pushl %ebp
 ; X86-AVX512-WIN-NEXT:movl %esp, %ebp
-; X86-AVX512-WIN-NEXT:andl $-8, %esp
-; X86-AVX512-WIN-NEXT:subl $8, %esp
+; X86-AVX512-WIN-NEXT:andl $-16, %esp
+; X86-AVX512-WIN-NEXT:subl $16, %esp
 ; X86-AVX512-WIN-NEXT:fldt 8(%ebp)
 ; X86-AVX512-WIN-NEXT:flds __real@5f00
 ; X86-AVX512-WIN-NEXT:xorl %edx, %edx
@@ -985,8 +985,8 @@
 ; X86-SSE3-WIN:   # %bb.0:
 ; X86-SSE3-WIN-NEXT:pushl %ebp
 ; X86-SSE3-WIN-NEXT:movl %esp, %ebp
-; X86-SSE3-WIN-NEXT:andl $-8, %esp
-; X86-SSE3-WIN-NEXT:subl $8, %esp
+; X86-SSE3-WIN-NEXT:andl $-16, %esp
+; X86-SSE3-WIN-NEXT:subl $16, %esp
 ; X86-SSE3-WIN-NEXT:fldt 8(%ebp)
 ; X86-SSE3-WIN-NEXT:flds __real@5f00
 ; X86-SSE3-WIN-NEXT:xorl %edx, %edx
@@ -1061,8 +1061,8 @@
 ; X86-SSE2-WIN:   # %bb.0:
 ; X86-SSE2-WIN-NEXT:pushl %ebp
 ; X86-SSE2-WIN-NEXT:movl %esp, %ebp
-; X86-SSE2-WIN-NEXT:andl $-8, %esp
-; X86-SSE2-WIN-NEXT:subl $16, %esp
+; X86-SSE2-WIN-NEXT:andl $-16, %esp
+; X86-SSE2-WIN-NEXT:subl $32, %esp
 ; X86-SSE2-WIN-NEXT:fldt 8(%ebp)
 ; X86-SSE2-WIN-NEXT:flds __real@5f00
 ; X86-SSE2-WIN-NEXT:xorl %edx, %edx
@@ -1161,8 +1161,8 @@
 ; X87-WIN:   # %bb.0:
 ; X87-WIN-NEXT:pushl %ebp
 ; X87-WIN-NEXT:movl %esp, %ebp
-; X87-WIN-NEXT:andl $-8, %esp
-; X87-WIN-NEXT:subl $16, %esp
+; X87-WIN-NEXT:andl $-16, %esp
+; X87-WIN-NEXT:subl $32, %esp
 ; X87-WIN-NEXT:fldt 8(%ebp)
 ; X87-WIN-NEXT:flds __real@5f00
 ; X87-WIN-NEXT:fucom %st(1)
@@ -1235,8 +1235,8 @@
 ; X86-AVX512-WIN:   # %bb.0:
 ; X86-AVX512-WIN-NEXT:pushl %ebp
 ; X86-AVX512-WIN-NEXT:movl %esp, %ebp
-; X86-AVX512-WIN-NEXT:andl $-8, %esp
-; X86-AVX512-WIN-NEXT:subl $8, %esp
+; X86-AVX512-WIN-NEXT:andl $-16, %esp
+; X86-AVX512-WIN-NEXT:subl $16, %esp
 ; X86-AVX512-WIN-NEXT:fldt 8(%ebp)
 ; X86-AVX512-WIN-NEXT:fisttpll (%esp)
 ; X86-AVX512-WIN-NEXT:movl (%esp), %eax
@@ -1275,8 +1275,8 @@
 ; X86-SSE3-WIN:   # %bb.0:
 ; X86-SSE3-WIN-NEXT:pushl %ebp
 ; X86-SSE3-WIN-NEXT:movl %esp, %ebp
-; X86-SSE3-WIN-NEXT:andl $-8, %esp
-; X86-SSE3-WIN-NEXT:subl $8, %esp
+; X86-SSE3-WIN-NEXT:andl $-16, %esp
+; X86-SSE3-WIN-NEXT:subl $16, %esp
 ; X86-SSE3-WIN-NEXT:fldt 8(%ebp)
 ; X86-SSE3-WIN-NEXT:fisttpll (%esp)
 ; X86-SSE3-WIN-NEXT:movl (%esp), %eax
@@ -1315,8 +1315,8 @@
 ; X86-SSE2-WIN:   # %bb.0:
 ; X86-SSE2-WIN-NEXT:pushl %ebp
 ; X86-SSE2-WIN-NEXT:movl %esp, %ebp
-; X86-SSE2-WIN-NEXT:andl $-8, %esp
-; X86-SSE2-WIN-NEXT:subl $16, %esp
+; X86-SSE2-WIN-NEXT:andl $-16, %esp
+; X86-SSE2-WIN-NEXT:subl $32, %esp
 ; X86-SSE2-WIN-NEXT:fldt 8(%ebp)
 ; X86-SSE2-WIN-NEXT:fnstcw {{[0-9]+}}(%esp)
 ; X86-SSE2-WIN-NEXT:movzwl {{[0-9]+}}(%esp), %eax
@@ -1379,8 +1379,8 @@
 ; X87-WIN:   # %bb.0:
 ; X87-WIN-NEXT:pushl %ebp
 ; X87-WIN-NEXT:movl %esp, %ebp
-; X87-WIN-NEXT:andl $-8, %esp
-; X87-WIN-NEXT:subl $16, %esp
+; X87-WIN-NEXT:andl $-16, %esp
+; X87-WIN-NEXT:subl $32, %esp
 ; X87-WIN-NEXT:fldt 8(%ebp)
 ; X87-WIN-NEXT:fnstcw {{[0-9]+}}(%esp)
 ; X87-WIN-NEXT:movzwl {{[0-9]+}}(%esp), %eax
Index: llvm/test/CodeGen/X86/scalar-fp-to-i32.ll
===
--- llvm/test/CodeGen/X86/scalar-fp-to-i32.ll
+++ llvm/test/CodeGen/X86/scalar-fp-to-i32.ll
@@ -344,8 +344,8 @@
 ; X86-AVX512-WIN:   # %bb.0:
 ; X86-AVX512-WIN-NEXT:pushl %ebp
 ; X86-AVX512-WIN-NEXT:movl %esp, %ebp
-; X86-AVX512-WIN-NEXT:andl $-8, %esp
-; X86-AVX512-WIN-NEXT:subl $8, %esp
+; X86-AVX512-WIN-NEXT:andl $-16, %esp
+; X86-AVX512-WIN-NEXT:subl $16, %esp
 ; X86-AVX512-WIN-NEXT:fldt 8(%ebp)
 ; X86-AVX512-WIN-NEXT:fisttpll (%esp)
 ; X86-AVX512-WIN-NEXT:movl (%esp), %eax
@@ -382,8 +382,8 @@
 ; X86-SSE3-WIN:   # %bb.0:
 ; X86-SSE3-WIN-NEXT:pushl %ebp
 ; X86-SSE3-WIN-NEXT:movl %esp, %ebp
-; X86-SSE3-WIN-NEXT:andl $-8, %esp
-; X86-SSE3-WIN-NEXT:subl $8, %esp
+; X

[PATCH] D115441: [X86][MS] Add 80bit long double support for Windows

2021-12-17 Thread Phoebe Wang via Phabricator via cfe-commits
pengfei updated this revision to Diff 395129.
pengfei added a comment.

Split the LLVM datalayout to a different patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115441

Files:
  clang/lib/Basic/TargetInfo.cpp
  clang/lib/Frontend/CompilerInvocation.cpp
  clang/test/CodeGen/X86/long-double-config-size.c


Index: clang/test/CodeGen/X86/long-double-config-size.c
===
--- /dev/null
+++ clang/test/CodeGen/X86/long-double-config-size.c
@@ -0,0 +1,22 @@
+// RUN: %clang_cc1 -triple x86_64-windows-msvc %s -emit-llvm -mlong-double-64 
-o - | FileCheck %s --check-prefix=SIZE64
+// RUN: %clang_cc1 -triple i386-windows-msvc %s -emit-llvm -mlong-double-80 -o 
- | FileCheck %s --check-prefix=SIZE80
+// RUN: %clang_cc1 -triple x86_64-windows-msvc %s -emit-llvm -mlong-double-80 
-o - | FileCheck %s --check-prefix=SIZE80
+// RUN: %clang_cc1 -triple x86_64-windows-msvc %s -emit-llvm -mlong-double-128 
-o - | FileCheck %s --check-prefix=SIZE128
+// RUN: %clang_cc1 -triple x86_64-windows-msvc %s -emit-llvm -o - | FileCheck 
%s --check-prefix=SIZE64
+
+long double global;
+// SIZE64: @global = dso_local global double 0
+// SIZE80: @global = dso_local global x86_fp80 0xK{{0+}}, align 16
+// SIZE128: @global = dso_local global fp128 0
+
+long double func(long double param) {
+  // SIZE64: define dso_local double @func(double %param)
+  // SIZE80: define dso_local x86_fp80 @func(x86_fp80 %param)
+  // SIZE128: define dso_local fp128  @func(fp128 %param)
+  long double local = param;
+  // SIZE64: alloca double
+  // SIZE80: alloca x86_fp80, align 16
+  // SIZE128: alloca fp128
+  local = param;
+  return local + param;
+}
Index: clang/lib/Frontend/CompilerInvocation.cpp
===
--- clang/lib/Frontend/CompilerInvocation.cpp
+++ clang/lib/Frontend/CompilerInvocation.cpp
@@ -3454,6 +3454,8 @@
 GenerateArg(Args, OPT_mlong_double_128, SA);
   else if (Opts.LongDoubleSize == 64)
 GenerateArg(Args, OPT_mlong_double_64, SA);
+  else if (Opts.LongDoubleSize == 80)
+GenerateArg(Args, OPT_mlong_double_80, SA);
 
   // Not generating '-mrtd', it's just an alias for '-fdefault-calling-conv='.
 
@@ -3837,9 +3839,16 @@
   Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding;
   if (!Opts.NoBuiltin)
 getAllNoBuiltinFuncValues(Args, Opts.NoBuiltinFuncs);
-  Opts.LongDoubleSize = Args.hasArg(OPT_mlong_double_128)
-? 128
-: Args.hasArg(OPT_mlong_double_64) ? 64 : 0;
+  if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
+if (A->getOption().matches(options::OPT_mlong_double_64))
+  Opts.LongDoubleSize = 64;
+else if (A->getOption().matches(options::OPT_mlong_double_80))
+  Opts.LongDoubleSize = 80;
+else if (A->getOption().matches(options::OPT_mlong_double_128))
+  Opts.LongDoubleSize = 128;
+else
+  Opts.LongDoubleSize = 0;
+  }
   if (Opts.FastRelaxedMath)
 Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
   llvm::sort(Opts.ModuleFeatures);
Index: clang/lib/Basic/TargetInfo.cpp
===
--- clang/lib/Basic/TargetInfo.cpp
+++ clang/lib/Basic/TargetInfo.cpp
@@ -446,6 +446,20 @@
 } else if (Opts.LongDoubleSize == 128) {
   LongDoubleWidth = LongDoubleAlign = 128;
   LongDoubleFormat = &llvm::APFloat::IEEEquad();
+} else if (Opts.LongDoubleSize == 80) {
+  LongDoubleFormat = &llvm::APFloat::x87DoubleExtended();
+  if (getTriple().isWindowsMSVCEnvironment()) {
+LongDoubleWidth = 128;
+LongDoubleAlign = 128;
+  } else { // Linux
+if (getTriple().getArch() == llvm::Triple::x86) {
+  LongDoubleWidth = 96;
+  LongDoubleAlign = 32;
+} else {
+  LongDoubleWidth = 128;
+  LongDoubleAlign = 128;
+}
+  }
 }
   }
 


Index: clang/test/CodeGen/X86/long-double-config-size.c
===
--- /dev/null
+++ clang/test/CodeGen/X86/long-double-config-size.c
@@ -0,0 +1,22 @@
+// RUN: %clang_cc1 -triple x86_64-windows-msvc %s -emit-llvm -mlong-double-64 -o - | FileCheck %s --check-prefix=SIZE64
+// RUN: %clang_cc1 -triple i386-windows-msvc %s -emit-llvm -mlong-double-80 -o - | FileCheck %s --check-prefix=SIZE80
+// RUN: %clang_cc1 -triple x86_64-windows-msvc %s -emit-llvm -mlong-double-80 -o - | FileCheck %s --check-prefix=SIZE80
+// RUN: %clang_cc1 -triple x86_64-windows-msvc %s -emit-llvm -mlong-double-128 -o - | FileCheck %s --check-prefix=SIZE128
+// RUN: %clang_cc1 -triple x86_64-windows-msvc %s -emit-llvm -o - | FileCheck %s --check-prefix=SIZE64
+
+long double global;
+// SIZE64: @global = dso_local global double 0
+// SIZE80: @global = dso_local global x86_fp80 0xK{{0+}}, align 16
+// SIZE128: @glob

[PATCH] D115942: [X86][MS] Change the alignment of f80 to 16 bytes on Windows 32bits to match with ICC

2021-12-17 Thread Phoebe Wang via Phabricator via cfe-commits
pengfei created this revision.
pengfei added reviewers: rnk, andrew.w.kaylor, erichkeane, craig.topper.
Herald added a subscriber: hiraditya.
pengfei requested review of this revision.
Herald added projects: clang, LLVM.
Herald added subscribers: llvm-commits, cfe-commits.

MSVC currently doesn't support 80 bits long double. ICC supports it when
the option `/Qlong-double` is specified. Changing the alignment of f80
to 16 bytes so that we can be compatible with ICC's option.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D115942

Files:
  clang/lib/Basic/Targets/X86.h
  clang/test/CodeGen/target-data.c
  llvm/lib/Target/X86/X86TargetMachine.cpp
  llvm/test/CodeGen/X86/long-double-abi-align.ll
  llvm/test/CodeGen/X86/scalar-fp-to-i32.ll
  llvm/test/CodeGen/X86/scalar-fp-to-i64.ll

Index: llvm/test/CodeGen/X86/scalar-fp-to-i64.ll
===
--- llvm/test/CodeGen/X86/scalar-fp-to-i64.ll
+++ llvm/test/CodeGen/X86/scalar-fp-to-i64.ll
@@ -909,8 +909,8 @@
 ; X86-AVX512-WIN:   # %bb.0:
 ; X86-AVX512-WIN-NEXT:pushl %ebp
 ; X86-AVX512-WIN-NEXT:movl %esp, %ebp
-; X86-AVX512-WIN-NEXT:andl $-8, %esp
-; X86-AVX512-WIN-NEXT:subl $8, %esp
+; X86-AVX512-WIN-NEXT:andl $-16, %esp
+; X86-AVX512-WIN-NEXT:subl $16, %esp
 ; X86-AVX512-WIN-NEXT:fldt 8(%ebp)
 ; X86-AVX512-WIN-NEXT:flds __real@5f00
 ; X86-AVX512-WIN-NEXT:xorl %edx, %edx
@@ -985,8 +985,8 @@
 ; X86-SSE3-WIN:   # %bb.0:
 ; X86-SSE3-WIN-NEXT:pushl %ebp
 ; X86-SSE3-WIN-NEXT:movl %esp, %ebp
-; X86-SSE3-WIN-NEXT:andl $-8, %esp
-; X86-SSE3-WIN-NEXT:subl $8, %esp
+; X86-SSE3-WIN-NEXT:andl $-16, %esp
+; X86-SSE3-WIN-NEXT:subl $16, %esp
 ; X86-SSE3-WIN-NEXT:fldt 8(%ebp)
 ; X86-SSE3-WIN-NEXT:flds __real@5f00
 ; X86-SSE3-WIN-NEXT:xorl %edx, %edx
@@ -1061,8 +1061,8 @@
 ; X86-SSE2-WIN:   # %bb.0:
 ; X86-SSE2-WIN-NEXT:pushl %ebp
 ; X86-SSE2-WIN-NEXT:movl %esp, %ebp
-; X86-SSE2-WIN-NEXT:andl $-8, %esp
-; X86-SSE2-WIN-NEXT:subl $16, %esp
+; X86-SSE2-WIN-NEXT:andl $-16, %esp
+; X86-SSE2-WIN-NEXT:subl $32, %esp
 ; X86-SSE2-WIN-NEXT:fldt 8(%ebp)
 ; X86-SSE2-WIN-NEXT:flds __real@5f00
 ; X86-SSE2-WIN-NEXT:xorl %edx, %edx
@@ -1161,8 +1161,8 @@
 ; X87-WIN:   # %bb.0:
 ; X87-WIN-NEXT:pushl %ebp
 ; X87-WIN-NEXT:movl %esp, %ebp
-; X87-WIN-NEXT:andl $-8, %esp
-; X87-WIN-NEXT:subl $16, %esp
+; X87-WIN-NEXT:andl $-16, %esp
+; X87-WIN-NEXT:subl $32, %esp
 ; X87-WIN-NEXT:fldt 8(%ebp)
 ; X87-WIN-NEXT:flds __real@5f00
 ; X87-WIN-NEXT:fucom %st(1)
@@ -1235,8 +1235,8 @@
 ; X86-AVX512-WIN:   # %bb.0:
 ; X86-AVX512-WIN-NEXT:pushl %ebp
 ; X86-AVX512-WIN-NEXT:movl %esp, %ebp
-; X86-AVX512-WIN-NEXT:andl $-8, %esp
-; X86-AVX512-WIN-NEXT:subl $8, %esp
+; X86-AVX512-WIN-NEXT:andl $-16, %esp
+; X86-AVX512-WIN-NEXT:subl $16, %esp
 ; X86-AVX512-WIN-NEXT:fldt 8(%ebp)
 ; X86-AVX512-WIN-NEXT:fisttpll (%esp)
 ; X86-AVX512-WIN-NEXT:movl (%esp), %eax
@@ -1275,8 +1275,8 @@
 ; X86-SSE3-WIN:   # %bb.0:
 ; X86-SSE3-WIN-NEXT:pushl %ebp
 ; X86-SSE3-WIN-NEXT:movl %esp, %ebp
-; X86-SSE3-WIN-NEXT:andl $-8, %esp
-; X86-SSE3-WIN-NEXT:subl $8, %esp
+; X86-SSE3-WIN-NEXT:andl $-16, %esp
+; X86-SSE3-WIN-NEXT:subl $16, %esp
 ; X86-SSE3-WIN-NEXT:fldt 8(%ebp)
 ; X86-SSE3-WIN-NEXT:fisttpll (%esp)
 ; X86-SSE3-WIN-NEXT:movl (%esp), %eax
@@ -1315,8 +1315,8 @@
 ; X86-SSE2-WIN:   # %bb.0:
 ; X86-SSE2-WIN-NEXT:pushl %ebp
 ; X86-SSE2-WIN-NEXT:movl %esp, %ebp
-; X86-SSE2-WIN-NEXT:andl $-8, %esp
-; X86-SSE2-WIN-NEXT:subl $16, %esp
+; X86-SSE2-WIN-NEXT:andl $-16, %esp
+; X86-SSE2-WIN-NEXT:subl $32, %esp
 ; X86-SSE2-WIN-NEXT:fldt 8(%ebp)
 ; X86-SSE2-WIN-NEXT:fnstcw {{[0-9]+}}(%esp)
 ; X86-SSE2-WIN-NEXT:movzwl {{[0-9]+}}(%esp), %eax
@@ -1379,8 +1379,8 @@
 ; X87-WIN:   # %bb.0:
 ; X87-WIN-NEXT:pushl %ebp
 ; X87-WIN-NEXT:movl %esp, %ebp
-; X87-WIN-NEXT:andl $-8, %esp
-; X87-WIN-NEXT:subl $16, %esp
+; X87-WIN-NEXT:andl $-16, %esp
+; X87-WIN-NEXT:subl $32, %esp
 ; X87-WIN-NEXT:fldt 8(%ebp)
 ; X87-WIN-NEXT:fnstcw {{[0-9]+}}(%esp)
 ; X87-WIN-NEXT:movzwl {{[0-9]+}}(%esp), %eax
Index: llvm/test/CodeGen/X86/scalar-fp-to-i32.ll
===
--- llvm/test/CodeGen/X86/scalar-fp-to-i32.ll
+++ llvm/test/CodeGen/X86/scalar-fp-to-i32.ll
@@ -344,8 +344,8 @@
 ; X86-AVX512-WIN:   # %bb.0:
 ; X86-AVX512-WIN-NEXT:pushl %ebp
 ; X86-AVX512-WIN-NEXT:movl %esp, %ebp
-; X86-AVX512-WIN-NEXT:andl $-8, %esp
-; X86-AVX512-WIN-NEXT:subl $8, %esp
+; X86-AVX512-WIN-NEXT:andl $-16, %esp
+; X86-AVX512-WIN-NEXT:subl $16, %esp
 ; X86-AVX512-WIN-NEXT:fldt 8(%ebp)
 ; X86-AVX512-WIN-NEXT:fisttpll (%esp)
 ; X86-AVX512-WIN-NEXT:movl (%esp), %eax
@@ -382,8 +382,8 @@
 ; X86-SSE3-WIN:   # %bb

[PATCH] D115942: [X86][MS] Change the alignment of f80 to 16 bytes on Windows 32bits to match with ICC

2021-12-17 Thread Phoebe Wang via Phabricator via cfe-commits
pengfei added a comment.

This is split from D115441 . Add a targeted 
LLVM test. Thanks @rnk for the advise.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115942

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


[PATCH] D115738: [clang-format] Fix formatting of the code that follows C# Lambda Expressions

2021-12-17 Thread Peter Stys via Phabricator via cfe-commits
peterstys added a comment.

In D115738#3199896 , @MyDeveloperDay 
wrote:

> In D115738#3199879 , @peterstys 
> wrote:
>
>> This is my first PR into this repo. I'd like to learn more about the process 
>> of submitting patches, specifically about:
>>
>> - Do I need to get LGTM from all the reviewers before I can submit it?
>
>
>
>   No, one is likely enough, but employ some level of respect for others if 
> they are commenting (they may not explicitly say LGTM but may accept) 
>
>> - There are some build failures on the CI, but look unrelated, do I force 
>> submit passed them?
>
>
>
>   They CI doesn't block commit. just check to ensure its not you, (there is 
> some odd Go issue ATM which I've seen reported elsewhere)
>
>> Could someone help me with these questions or point me to the relevant 
>> documentation. Thanks.
>
> https://llvm.org/docs/Contributing.html
> https://llvm.org/docs/Phabricator.html

Great. Thank you. Very helpful.

Regarding failing CI: it seems that the LLVM_ALL_PROJECTS in CMakeLists.txt 
miss "bolt" setting (line 67): set(LLVM_ALL_PROJECTS 
"clang;clang-tools-extra;compiler-rt;cross-project-tests;libc;libclc;libcxx;libcxxabi;libunwind;lld;lldb;mlir;openmp;polly;pstl")

Regarding committing the change: I won't have commit rights. Could someone do 
it for me?


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

https://reviews.llvm.org/D115738

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


[PATCH] D110622: [HIPSPV][3/4] Enable SPIR-V emission for HIP

2021-12-17 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added a comment.

In D110622#3199233 , @linjamaki wrote:

> Assuming that this patch is ready to land. @tra or @yaxunl, could you please 
> commit this patch to the LLVM for us? Thanks.

I can help commit this patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D110622

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


[PATCH] D115738: [clang-format] Fix formatting of the code that follows C# Lambda Expressions

2021-12-17 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay added a comment.

Thank you for the patch We'll need your name and email address for that, but 
yes we'll be happy to commit it for you.

If you think you'd like to play some more, then you can apply for commit 
access. (not sure of the process for that now, but its probably in the 
documentation somewhere)


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

https://reviews.llvm.org/D115738

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


[PATCH] D115938: [clang-format] Formatter does not handle c++11 string literal prefix with stringize #

2021-12-17 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay updated this revision to Diff 395135.
MyDeveloperDay added a comment.

Add the raw string literal cases


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

https://reviews.llvm.org/D115938

Files:
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTest.cpp


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -4342,6 +4342,13 @@
 
 TEST_F(FormatTest, HashInMacroDefinition) {
   EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle()));
+  EXPECT_EQ("#define A(c) u#c", format("#define A(c) u#c", getLLVMStyle()));
+  EXPECT_EQ("#define A(c) U#c", format("#define A(c) U#c", getLLVMStyle()));
+  EXPECT_EQ("#define A(c) u8#c", format("#define A(c) u8#c", getLLVMStyle()));
+  EXPECT_EQ("#define A(c) LR#c", format("#define A(c) LR#c", getLLVMStyle()));
+  EXPECT_EQ("#define A(c) uR#c", format("#define A(c) uR#c", getLLVMStyle()));
+  EXPECT_EQ("#define A(c) UR#c", format("#define A(c) UR#c", getLLVMStyle()));
+  EXPECT_EQ("#define A(c) u8R#c", format("#define A(c) u8R#c", 
getLLVMStyle()));
   verifyFormat("#define A \\\n  b #c;", getLLVMStyleWithColumns(11));
   verifyFormat("#define A  \\\n"
"  {\\\n"
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -3225,7 +3225,13 @@
 return false;
   if (Left.is(tok::period) || Right.is(tok::period))
 return false;
-  if (Right.is(tok::hash) && Left.is(tok::identifier) && Left.TokenText == "L")
+  // u#str, U#str, L#str, u8#str
+  // uR#str, UR#str, LR#str, u8R#str
+  if (Right.is(tok::hash) && Left.is(tok::identifier) &&
+  (Left.TokenText == "L" || Left.TokenText == "u" ||
+   Left.TokenText == "U" || Left.TokenText == "u8" ||
+   Left.TokenText == "LR" || Left.TokenText == "uR" ||
+   Left.TokenText == "UR" || Left.TokenText == "u8R"))
 return false;
   if (Left.is(TT_TemplateCloser) && Left.MatchingParen &&
   Left.MatchingParen->Previous &&


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -4342,6 +4342,13 @@
 
 TEST_F(FormatTest, HashInMacroDefinition) {
   EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle()));
+  EXPECT_EQ("#define A(c) u#c", format("#define A(c) u#c", getLLVMStyle()));
+  EXPECT_EQ("#define A(c) U#c", format("#define A(c) U#c", getLLVMStyle()));
+  EXPECT_EQ("#define A(c) u8#c", format("#define A(c) u8#c", getLLVMStyle()));
+  EXPECT_EQ("#define A(c) LR#c", format("#define A(c) LR#c", getLLVMStyle()));
+  EXPECT_EQ("#define A(c) uR#c", format("#define A(c) uR#c", getLLVMStyle()));
+  EXPECT_EQ("#define A(c) UR#c", format("#define A(c) UR#c", getLLVMStyle()));
+  EXPECT_EQ("#define A(c) u8R#c", format("#define A(c) u8R#c", getLLVMStyle()));
   verifyFormat("#define A \\\n  b #c;", getLLVMStyleWithColumns(11));
   verifyFormat("#define A  \\\n"
"  {\\\n"
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -3225,7 +3225,13 @@
 return false;
   if (Left.is(tok::period) || Right.is(tok::period))
 return false;
-  if (Right.is(tok::hash) && Left.is(tok::identifier) && Left.TokenText == "L")
+  // u#str, U#str, L#str, u8#str
+  // uR#str, UR#str, LR#str, u8R#str
+  if (Right.is(tok::hash) && Left.is(tok::identifier) &&
+  (Left.TokenText == "L" || Left.TokenText == "u" ||
+   Left.TokenText == "U" || Left.TokenText == "u8" ||
+   Left.TokenText == "LR" || Left.TokenText == "uR" ||
+   Left.TokenText == "UR" || Left.TokenText == "u8R"))
 return false;
   if (Left.is(TT_TemplateCloser) && Left.MatchingParen &&
   Left.MatchingParen->Previous &&
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D114966: [clang][deps] Split stat and file content caches

2021-12-17 Thread Jan Svoboda via Phabricator via cfe-commits
jansvoboda11 added inline comments.



Comment at: 
clang/lib/Tooling/DependencyScanning/DependencyScanningFilesystem.cpp:275
+  const auto &Entry1 = getOrEmplaceSharedEntryForUID(std::move(TEntry));
+  const auto &Entry2 = getOrInsertSharedEntryForFilename(Filename, Entry1);
+  return insertLocalEntryForFilename(Filename, Entry2);

I'm not sure these should be separate. We could end up in situation where the 
Filename map contains different entry than the UID map for the same directory 
entry. I'm tempted to merge these functions into one and perform the updates in 
a single critical section...


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114966

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


[clang] 9fd4f80 - [ConstantFolding] Unify handling of load from uniform value

2021-12-17 Thread Nikita Popov via cfe-commits

Author: Nikita Popov
Date: 2021-12-17T17:05:06+01:00
New Revision: 9fd4f80e33a4ae4567483819646650f5735286e2

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

LOG: [ConstantFolding] Unify handling of load from uniform value

There are a number of places that specially handle loads from a
uniform value where all the bits are the same (zero, one, undef,
poison), because we a) don't care about the load offset in that
case and b) it bypasses casts that might not be legal generally
but do work with uniform values.

We had multiple implementations of this, with a different set of
supported values each time, as well as incomplete type checks in
some cases. In particular, this fixes the assertion reported in
https://reviews.llvm.org/D114889#3198921, as well as a similar
assertion that could be triggered via constant folding.

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

Added: 
llvm/test/Transforms/GlobalOpt/x86_mmx_load.ll

Modified: 
clang/test/CodeGen/aapcs-align.cpp
llvm/include/llvm/Analysis/ConstantFolding.h
llvm/lib/Analysis/ConstantFolding.cpp
llvm/lib/Transforms/IPO/GlobalOpt.cpp
llvm/test/Transforms/InstSimplify/ConstProp/loads.ll

Removed: 




diff  --git a/clang/test/CodeGen/aapcs-align.cpp 
b/clang/test/CodeGen/aapcs-align.cpp
index 8950908183efc..8543081caf233 100644
--- a/clang/test/CodeGen/aapcs-align.cpp
+++ b/clang/test/CodeGen/aapcs-align.cpp
@@ -134,8 +134,8 @@ void g6() {
   f6m(1, 2, 3, 4, 5, s);
 }
 // CHECK: define{{.*}} void @g6
-// CHECK: call void @f6(i32 1, [4 x i32] [i32 6, i32 7, i32 0, i32 0])
-// CHECK: call void @f6m(i32 1, i32 2, i32 3, i32 4, i32 5, [4 x i32] [i32 6, 
i32 7, i32 0, i32 0])
+// CHECK: call void @f6(i32 1, [4 x i32] [i32 6, i32 7, i32 0, i32 undef])
+// CHECK: call void @f6m(i32 1, i32 2, i32 3, i32 4, i32 5, [4 x i32] [i32 6, 
i32 7, i32 0, i32 undef])
 // CHECK: declare void @f6(i32, [4 x i32])
 // CHECK: declare void @f6m(i32, i32, i32, i32, i32, [4 x i32])
 }

diff  --git a/llvm/include/llvm/Analysis/ConstantFolding.h 
b/llvm/include/llvm/Analysis/ConstantFolding.h
index 45fb879f0c1f1..3b3a1785d7baa 100644
--- a/llvm/include/llvm/Analysis/ConstantFolding.h
+++ b/llvm/include/llvm/Analysis/ConstantFolding.h
@@ -148,6 +148,12 @@ Constant *ConstantFoldLoadFromConstPtr(Constant *C, Type 
*Ty, APInt Offset,
 Constant *ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty,
const DataLayout &DL);
 
+/// If C is a uniform value where all bits are the same (either all zero, all
+/// ones, all undef or all poison), return the corresponding uniform value in
+/// the new type. If the value is not uniform or the result cannot be
+/// represented, return null.
+Constant *ConstantFoldLoadFromUniformValue(Constant *C, Type *Ty);
+
 /// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
 /// getelementptr constantexpr, return the constant value being addressed by 
the
 /// constant expression, or null if something is funny and we can't decide.

diff  --git a/llvm/lib/Analysis/ConstantFolding.cpp 
b/llvm/lib/Analysis/ConstantFolding.cpp
index fcf4be4a538bc..3fc24d82f8681 100644
--- a/llvm/lib/Analysis/ConstantFolding.cpp
+++ b/llvm/lib/Analysis/ConstantFolding.cpp
@@ -106,11 +106,8 @@ Constant *FoldBitCast(Constant *C, Type *DestTy, const 
DataLayout &DL) {
  "Invalid constantexpr bitcast!");
 
   // Catch the obvious splat cases.
-  if (C->isNullValue() && !DestTy->isX86_MMXTy() && !DestTy->isX86_AMXTy())
-return Constant::getNullValue(DestTy);
-  if (C->isAllOnesValue() && !DestTy->isX86_MMXTy() && !DestTy->isX86_AMXTy() 
&&
-  !DestTy->isPtrOrPtrVectorTy()) // Don't get ones for ptr types!
-return Constant::getAllOnesValue(DestTy);
+  if (Constant *Res = ConstantFoldLoadFromUniformValue(C, DestTy))
+return Res;
 
   if (auto *VTy = dyn_cast(C->getType())) {
 // Handle a vector->scalar integer/fp cast.
@@ -362,16 +359,8 @@ Constant *llvm::ConstantFoldLoadThroughBitcast(Constant 
*C, Type *DestTy,
 
 // Catch the obvious splat cases (since all-zeros can coerce non-integral
 // pointers legally).
-if (C->isNullValue() && !DestTy->isX86_MMXTy() && !DestTy->isX86_AMXTy())
-  return Constant::getNullValue(DestTy);
-if (C->isAllOnesValue() &&
-(DestTy->isIntegerTy() || DestTy->isFloatingPointTy() ||
- DestTy->isVectorTy()) &&
-!DestTy->isX86_AMXTy() && !DestTy->isX86_MMXTy() &&
-!DestTy->isPtrOrPtrVectorTy())
-  // Get ones when the input is trivial, but
-  // only for supported types inside getAllOnesValue.
-  return Constant::getAllOnesValue(DestTy);
+if (Constant *Res = ConstantFoldLoadFromUniformValue(C, DestTy))
+  return Res;
 
 // If the type sizes are the same and a c

[PATCH] D115924: [ConstantFolding] Unify handling of load from uniform value

2021-12-17 Thread Nikita Popov via Phabricator via cfe-commits
This revision was not accepted when it landed; it landed in state "Needs 
Review".
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG9fd4f80e33a4: [ConstantFolding] Unify handling of load from 
uniform value (authored by nikic).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D115924?vs=395126&id=395136#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115924

Files:
  clang/test/CodeGen/aapcs-align.cpp
  llvm/include/llvm/Analysis/ConstantFolding.h
  llvm/lib/Analysis/ConstantFolding.cpp
  llvm/lib/Transforms/IPO/GlobalOpt.cpp
  llvm/test/Transforms/GlobalOpt/x86_mmx_load.ll
  llvm/test/Transforms/InstSimplify/ConstProp/loads.ll

Index: llvm/test/Transforms/InstSimplify/ConstProp/loads.ll
===
--- llvm/test/Transforms/InstSimplify/ConstProp/loads.ll
+++ llvm/test/Transforms/InstSimplify/ConstProp/loads.ll
@@ -280,3 +280,16 @@
   %v = load { i64, i64 }, { i64, i64 }* @g3
   ret { i64, i64 } %v
 }
+
+@m64 = internal constant [2 x i64] zeroinitializer
+@idx = external global i32
+
+; This should not try to create an x86_mmx null value.
+define x86_mmx @load_mmx() {
+; CHECK-LABEL: @load_mmx(
+; CHECK-NEXT:[[TEMP:%.*]] = load x86_mmx, x86_mmx* bitcast (i64* getelementptr ([2 x i64], [2 x i64]* @m64, i64 0, i64 ptrtoint (i32* @idx to i64)) to x86_mmx*), align 8
+; CHECK-NEXT:ret x86_mmx [[TEMP]]
+;
+  %temp = load x86_mmx, x86_mmx* bitcast (i64* getelementptr ([2 x i64], [2 x i64]* @m64, i64 0, i64 ptrtoint (i32* @idx to i64)) to x86_mmx*)
+  ret x86_mmx %temp
+}
Index: llvm/test/Transforms/GlobalOpt/x86_mmx_load.ll
===
--- /dev/null
+++ llvm/test/Transforms/GlobalOpt/x86_mmx_load.ll
@@ -0,0 +1,12 @@
+; NOTE: Assertions have been autogenerated by utils/update_test_checks.py
+; RUN: opt -S -globalopt < %s | FileCheck %s
+
+@m64 = internal global <1 x i64> zeroinitializer
+
+define i32 @load_mmx() {
+; CHECK-LABEL: @load_mmx(
+; CHECK-NEXT:ret i32 0
+;
+  %temp = load x86_mmx, x86_mmx* bitcast (<1 x i64>* @m64 to x86_mmx*)
+  ret i32 0
+}
Index: llvm/lib/Transforms/IPO/GlobalOpt.cpp
===
--- llvm/lib/Transforms/IPO/GlobalOpt.cpp
+++ llvm/lib/Transforms/IPO/GlobalOpt.cpp
@@ -305,8 +305,9 @@
 else if (auto *LI = dyn_cast(U)) {
   // A load from zeroinitializer is always zeroinitializer, regardless of
   // any applied offset.
-  if (Init->isNullValue()) {
-LI->replaceAllUsesWith(Constant::getNullValue(LI->getType()));
+  if (Constant *Res =
+  ConstantFoldLoadFromUniformValue(Init, LI->getType())) {
+LI->replaceAllUsesWith(Res);
 EraseFromParent(LI);
 continue;
   }
Index: llvm/lib/Analysis/ConstantFolding.cpp
===
--- llvm/lib/Analysis/ConstantFolding.cpp
+++ llvm/lib/Analysis/ConstantFolding.cpp
@@ -106,11 +106,8 @@
  "Invalid constantexpr bitcast!");
 
   // Catch the obvious splat cases.
-  if (C->isNullValue() && !DestTy->isX86_MMXTy() && !DestTy->isX86_AMXTy())
-return Constant::getNullValue(DestTy);
-  if (C->isAllOnesValue() && !DestTy->isX86_MMXTy() && !DestTy->isX86_AMXTy() &&
-  !DestTy->isPtrOrPtrVectorTy()) // Don't get ones for ptr types!
-return Constant::getAllOnesValue(DestTy);
+  if (Constant *Res = ConstantFoldLoadFromUniformValue(C, DestTy))
+return Res;
 
   if (auto *VTy = dyn_cast(C->getType())) {
 // Handle a vector->scalar integer/fp cast.
@@ -362,16 +359,8 @@
 
 // Catch the obvious splat cases (since all-zeros can coerce non-integral
 // pointers legally).
-if (C->isNullValue() && !DestTy->isX86_MMXTy() && !DestTy->isX86_AMXTy())
-  return Constant::getNullValue(DestTy);
-if (C->isAllOnesValue() &&
-(DestTy->isIntegerTy() || DestTy->isFloatingPointTy() ||
- DestTy->isVectorTy()) &&
-!DestTy->isX86_AMXTy() && !DestTy->isX86_MMXTy() &&
-!DestTy->isPtrOrPtrVectorTy())
-  // Get ones when the input is trivial, but
-  // only for supported types inside getAllOnesValue.
-  return Constant::getAllOnesValue(DestTy);
+if (Constant *Res = ConstantFoldLoadFromUniformValue(C, DestTy))
+  return Res;
 
 // If the type sizes are the same and a cast is legal, just directly
 // cast the constant.
@@ -704,16 +693,13 @@
Offset, DL))
 return Result;
 
-  // If this load comes from anywhere in a constant global, and if the global
-  // is all undef or zero, we know what it loads.
-  if (auto *GV = dyn_cast(getUnderlyingObject(C))) {
-if (GV->isConstan

[PATCH] D115938: [clang-format] Formatter does not handle c++11 string literal prefix with stringize #

2021-12-17 Thread Marek Kurdej via Phabricator via cfe-commits
curdeius accepted this revision.
curdeius added a comment.
This revision is now accepted and ready to land.

LGTM.


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

https://reviews.llvm.org/D115938

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


[PATCH] D115738: [clang-format] Fix formatting of the code that follows C# Lambda Expressions

2021-12-17 Thread Peter Stys via Phabricator via cfe-commits
peterstys added a comment.

In D115738#3199988 , @MyDeveloperDay 
wrote:

> Thank you for the patch We'll need your name and email address for that, but 
> yes we'll be happy to commit it for you.
>
> If you think you'd like to play some more, then you can apply for commit 
> access. (not sure of the process for that now, but its probably in the 
> documentation somewhere)

Peter Stys
peters...@google.com

Thank you!


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

https://reviews.llvm.org/D115738

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


[clang] 33cbaab - [funcattrs] Consistently treat calling a function pointer as a non-capturing read

2021-12-17 Thread Philip Reames via cfe-commits

Author: Philip Reames
Date: 2021-12-17T09:02:03-08:00
New Revision: 33cbaab1416b234d5a08b41e3110d64a00b0651c

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

LOG: [funcattrs] Consistently treat calling a function pointer as a 
non-capturing read

We were being wildly inconsistent about what memory access was implied by an 
indirect function call. Depending on the call site attributes, you could get 
anything from a read, to unknown, to none at all. (The last was a miscompile.)

We were also always traversing the uses of a readonly indirect call. This is 
entirely unneeded as the indirect call does not capture. The callee might 
capture itself internally, but that has no implications for this caller. (See 
the nice explanation in the CaptureTracking comments if that case is confusing.)

Note that elsewhere in the same file, we were correctly computing the nocapture 
attribute for indirect calls. The changed case only resulted in conservatism 
when computing memory attributes if say the return value was written to.

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

Added: 


Modified: 
clang/test/CodeGen/arm-cmse-attr.c
llvm/lib/Transforms/IPO/FunctionAttrs.cpp
llvm/test/Transforms/FunctionAttrs/nocapture.ll
llvm/test/Transforms/FunctionAttrs/writeonly.ll

Removed: 




diff  --git a/clang/test/CodeGen/arm-cmse-attr.c 
b/clang/test/CodeGen/arm-cmse-attr.c
index 5cfadfd3828a1..ae0b606a0bb21 100644
--- a/clang/test/CodeGen/arm-cmse-attr.c
+++ b/clang/test/CodeGen/arm-cmse-attr.c
@@ -29,9 +29,9 @@ void f4() __attribute__((cmse_nonsecure_entry))
 {
 }
 
-// CHECK: define{{.*}} void @f1(void ()* nocapture %fptr) {{[^#]*}}#0 {
+// CHECK: define{{.*}} void @f1(void ()* nocapture readonly %fptr) {{[^#]*}}#0 
{
 // CHECK: call void %fptr() #2
-// CHECK: define{{.*}} void @f2(void ()* nocapture %fptr) {{[^#]*}}#0 {
+// CHECK: define{{.*}} void @f2(void ()* nocapture readonly %fptr) {{[^#]*}}#0 
{
 // CHECK: call void %fptr() #2
 // CHECK: define{{.*}} void @f3() {{[^#]*}}#1 {
 // CHECK: define{{.*}} void @f4() {{[^#]*}}#1 {

diff  --git a/llvm/lib/Transforms/IPO/FunctionAttrs.cpp 
b/llvm/lib/Transforms/IPO/FunctionAttrs.cpp
index 2cee9c0b4766a..8c8aea465c490 100644
--- a/llvm/lib/Transforms/IPO/FunctionAttrs.cpp
+++ b/llvm/lib/Transforms/IPO/FunctionAttrs.cpp
@@ -702,6 +702,11 @@ determinePointerAccessAttrs(Argument *A,
   };
 
   CallBase &CB = cast(*I);
+  if (CB.isCallee(U)) {
+IsRead = true;
+Captures = false; // See comment in CaptureTracking for context
+continue;
+  }
   if (CB.doesNotAccessMemory()) {
 AddUsersToWorklistIfCapturing();
 continue;

diff  --git a/llvm/test/Transforms/FunctionAttrs/nocapture.ll 
b/llvm/test/Transforms/FunctionAttrs/nocapture.ll
index 3c699de9df6c9..ab84a0cece52e 100644
--- a/llvm/test/Transforms/FunctionAttrs/nocapture.ll
+++ b/llvm/test/Transforms/FunctionAttrs/nocapture.ll
@@ -128,7 +128,7 @@ define void @nc2(i32* %p, i32* %q) {
 }
 
 
-; FNATTR: define void @nc3(void ()* nocapture %p)
+; FNATTR: define void @nc3(void ()* nocapture readonly %p)
 define void @nc3(void ()* %p) {
call void %p()
ret void
@@ -141,7 +141,7 @@ define void @nc4(i8* %p) {
ret void
 }
 
-; FNATTR: define void @nc5(void (i8*)* nocapture %f, i8* nocapture %p)
+; FNATTR: define void @nc5(void (i8*)* nocapture readonly %f, i8* nocapture %p)
 define void @nc5(void (i8*)* %f, i8* %p) {
call void %f(i8* %p) readonly nounwind
call void %f(i8* nocapture %p)
@@ -319,21 +319,21 @@ define i1 @captureDereferenceableOrNullICmp(i32* 
dereferenceable_or_null(4) %x)
 
 declare void @capture(i8*)
 
-; FNATTR: define void @nocapture_fptr(i8* (i8*)* nocapture %f, i8* %p)
+; FNATTR: define void @nocapture_fptr(i8* (i8*)* nocapture readonly %f, i8* %p)
 define void @nocapture_fptr(i8* (i8*)* %f, i8* %p) {
   %res = call i8* %f(i8* %p)
   call void @capture(i8* %res)
   ret void
 }
 
-; FNATTR: define void @recurse_fptr(i8* (i8*)* nocapture %f, i8* %p)
+; FNATTR: define void @recurse_fptr(i8* (i8*)* nocapture readonly %f, i8* %p)
 define void @recurse_fptr(i8* (i8*)* %f, i8* %p) {
   %res = call i8* %f(i8* %p)
   store i8 0, i8* %res
   ret void
 }
 
-; FNATTR: define void @readnone_indirec(void (i8*)* nocapture readnone %f, i8* 
readnone %p)
+; FNATTR: define void @readnone_indirec(void (i8*)* nocapture readonly %f, i8* 
readnone %p)
 define void @readnone_indirec(void (i8*)* %f, i8* %p) {
   call void %f(i8* %p) readnone
   ret void

diff  --git a/llvm/test/Transforms/FunctionAttrs/writeonly.ll 
b/llvm/test/Transforms/FunctionAttrs/writeonly.ll
index fb39b301b..54d00d355f7af 100644
--- a/llvm/test/Transforms/FunctionAttrs/writeonly.ll
+++ b/llvm/test/Transforms/FunctionAttrs/

[PATCH] D115916: [funcattrs] Consistently treat calling a function pointer as a non-capturing read

2021-12-17 Thread Philip Reames 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 rG33cbaab1416b: [funcattrs] Consistently treat calling a 
function pointer as a non-capturing… (authored by reames).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D115916?vs=395035&id=395148#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115916

Files:
  clang/test/CodeGen/arm-cmse-attr.c
  llvm/lib/Transforms/IPO/FunctionAttrs.cpp
  llvm/test/Transforms/FunctionAttrs/nocapture.ll
  llvm/test/Transforms/FunctionAttrs/writeonly.ll

Index: llvm/test/Transforms/FunctionAttrs/writeonly.ll
===
--- llvm/test/Transforms/FunctionAttrs/writeonly.ll
+++ llvm/test/Transforms/FunctionAttrs/writeonly.ll
@@ -92,19 +92,19 @@
   ret void
 }
 
-; CHECK: define void @fptr_test1(i8* %p, void (i8*)* nocapture %f)
+; CHECK: define void @fptr_test1(i8* %p, void (i8*)* nocapture readonly %f)
 define void @fptr_test1(i8* %p, void (i8*)* %f) {
   call void %f(i8* %p)
   ret void
 }
 
-; CHECK: define void @fptr_test2(i8* %p, void (i8*)* nocapture %f)
+; CHECK: define void @fptr_test2(i8* %p, void (i8*)* nocapture readonly %f)
 define void @fptr_test2(i8* %p, void (i8*)* %f) {
   call void %f(i8* writeonly %p)
   ret void
 }
 
-; CHECK: define void @fptr_test3(i8* %p, void (i8*)* nocapture %f)
+; CHECK: define void @fptr_test3(i8* %p, void (i8*)* nocapture readonly %f)
 define void @fptr_test3(i8* %p, void (i8*)* %f) {
   call void %f(i8* %p) writeonly
   ret void
Index: llvm/test/Transforms/FunctionAttrs/nocapture.ll
===
--- llvm/test/Transforms/FunctionAttrs/nocapture.ll
+++ llvm/test/Transforms/FunctionAttrs/nocapture.ll
@@ -128,7 +128,7 @@
 }
 
 
-; FNATTR: define void @nc3(void ()* nocapture %p)
+; FNATTR: define void @nc3(void ()* nocapture readonly %p)
 define void @nc3(void ()* %p) {
 	call void %p()
 	ret void
@@ -141,7 +141,7 @@
 	ret void
 }
 
-; FNATTR: define void @nc5(void (i8*)* nocapture %f, i8* nocapture %p)
+; FNATTR: define void @nc5(void (i8*)* nocapture readonly %f, i8* nocapture %p)
 define void @nc5(void (i8*)* %f, i8* %p) {
 	call void %f(i8* %p) readonly nounwind
 	call void %f(i8* nocapture %p)
@@ -319,21 +319,21 @@
 
 declare void @capture(i8*)
 
-; FNATTR: define void @nocapture_fptr(i8* (i8*)* nocapture %f, i8* %p)
+; FNATTR: define void @nocapture_fptr(i8* (i8*)* nocapture readonly %f, i8* %p)
 define void @nocapture_fptr(i8* (i8*)* %f, i8* %p) {
   %res = call i8* %f(i8* %p)
   call void @capture(i8* %res)
   ret void
 }
 
-; FNATTR: define void @recurse_fptr(i8* (i8*)* nocapture %f, i8* %p)
+; FNATTR: define void @recurse_fptr(i8* (i8*)* nocapture readonly %f, i8* %p)
 define void @recurse_fptr(i8* (i8*)* %f, i8* %p) {
   %res = call i8* %f(i8* %p)
   store i8 0, i8* %res
   ret void
 }
 
-; FNATTR: define void @readnone_indirec(void (i8*)* nocapture readnone %f, i8* readnone %p)
+; FNATTR: define void @readnone_indirec(void (i8*)* nocapture readonly %f, i8* readnone %p)
 define void @readnone_indirec(void (i8*)* %f, i8* %p) {
   call void %f(i8* %p) readnone
   ret void
Index: llvm/lib/Transforms/IPO/FunctionAttrs.cpp
===
--- llvm/lib/Transforms/IPO/FunctionAttrs.cpp
+++ llvm/lib/Transforms/IPO/FunctionAttrs.cpp
@@ -702,6 +702,11 @@
   };
 
   CallBase &CB = cast(*I);
+  if (CB.isCallee(U)) {
+IsRead = true;
+Captures = false; // See comment in CaptureTracking for context
+continue;
+  }
   if (CB.doesNotAccessMemory()) {
 AddUsersToWorklistIfCapturing();
 continue;
Index: clang/test/CodeGen/arm-cmse-attr.c
===
--- clang/test/CodeGen/arm-cmse-attr.c
+++ clang/test/CodeGen/arm-cmse-attr.c
@@ -29,9 +29,9 @@
 {
 }
 
-// CHECK: define{{.*}} void @f1(void ()* nocapture %fptr) {{[^#]*}}#0 {
+// CHECK: define{{.*}} void @f1(void ()* nocapture readonly %fptr) {{[^#]*}}#0 {
 // CHECK: call void %fptr() #2
-// CHECK: define{{.*}} void @f2(void ()* nocapture %fptr) {{[^#]*}}#0 {
+// CHECK: define{{.*}} void @f2(void ()* nocapture readonly %fptr) {{[^#]*}}#0 {
 // CHECK: call void %fptr() #2
 // CHECK: define{{.*}} void @f3() {{[^#]*}}#1 {
 // CHECK: define{{.*}} void @f4() {{[^#]*}}#1 {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D114622: [clang-tidy][analyzer] Fix false-positive in IdenticalExprChecker and misc-redundant-expression

2021-12-17 Thread Balázs Benics via Phabricator via cfe-commits
steakhal updated this revision to Diff 395150.
steakhal added a comment.

Sorry for the late update, but here we are:

Now, I properly handle all kinds of `NestedNameSpecifiers`.
Basically, I verify if the decls are matching, then I use the nested name 
specifiers for finding mismatches. I look through namespace aliases and I use 
the canonical types.


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

https://reviews.llvm.org/D114622

Files:
  clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp
  clang-tools-extra/clang-tidy/misc/RedundantExpressionCheck.cpp
  clang-tools-extra/test/clang-tidy/checkers/misc-redundant-expression.cpp
  clang/lib/StaticAnalyzer/Checkers/IdenticalExprChecker.cpp
  clang/test/Analysis/identical-expressions.cpp

Index: clang/test/Analysis/identical-expressions.cpp
===
--- clang/test/Analysis/identical-expressions.cpp
+++ clang/test/Analysis/identical-expressions.cpp
@@ -1562,3 +1562,62 @@
   ;
   }
 }
+
+template  struct boolean_value {
+  static constexpr bool value = V;
+};
+template  struct my_trait : boolean_value {};
+
+bool respect_nested_name_specifiers(bool sink) {
+  sink |= my_trait::value || my_trait::value; // no-warning
+
+  sink |= my_trait::value || my_trait::value;
+  // expected-warning@-1 {{identical expressions on both sides of logical operator}}
+
+  using my_char = char;
+  sink |= my_trait::value || my_trait::value;
+  // expected-warning@-1 {{identical expressions on both sides of logical operator}}
+
+  sink |= my_trait::value || ::my_trait::value;
+  // expected-warning@-1 {{identical expressions on both sides of logical operator}}
+
+  using my_trait_alias = my_trait;
+  sink |= my_trait::value || my_trait_alias::value;
+  // expected-warning@-1 {{identical expressions on both sides of logical operator}}
+
+  return sink;
+}
+
+static void static_function() {}
+namespace my {
+int fn(int = 1);
+}
+void respect_namespaces(bool coin) {
+  namespace other = my;
+  namespace other2 = other;
+  using namespace other;
+
+  coin ? my::fn(1) : my::fn(2);// no-warning
+  coin ? my::fn(1) : other::fn(2); // no-warning
+
+  // expected-warning@+5 {{identical expressions on both sides of ':' in conditional expression}}
+  // expected-warning@+5 {{identical expressions on both sides of ':' in conditional expression}}
+  // expected-warning@+5 {{identical expressions on both sides of ':' in conditional expression}}
+  // expected-warning@+5 {{identical expressions on both sides of ':' in conditional expression}}
+  // expected-warning@+5 {{identical expressions on both sides of ':' in conditional expression}}
+  coin ? my::fn(1) : my::fn(1);
+  coin ? my::fn(1) : other::fn(1);
+  coin ? my::fn(1) : fn(1);
+  coin ? my::fn(1) : other2::fn(1);
+  coin ? fn(1) : other2::fn(1);
+
+  coin ? my::fn(1) : fn(); // FIXME: We should have a warning for this: the default parameter is also 1.
+
+  my::fn(1) & my::fn(1);// no-warning
+  my::fn(1) & other::fn(1); // no-warning
+
+  // expected-warning@+2 {{identical expressions on both sides of ':' in conditional expression}}
+  // expected-warning@+2 {{identical expressions on both sides of ':' in conditional expression}}
+  coin ? ::static_function() : ::static_function();
+  coin ? ::static_function() : static_function();
+}
Index: clang/lib/StaticAnalyzer/Checkers/IdenticalExprChecker.cpp
===
--- clang/lib/StaticAnalyzer/Checkers/IdenticalExprChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/IdenticalExprChecker.cpp
@@ -295,6 +295,81 @@
   return true;
 }
 
+static const NamespaceDecl *lookingThroughAliases(const NamedDecl *D) {
+  while (const auto *Alias = dyn_cast(D))
+D = Alias->getAliasedNamespace();
+  return cast_or_null(D);
+}
+
+static bool areEquivalentNameSpecifier(const NestedNameSpecifier *Left,
+   const NestedNameSpecifier *Right) {
+  const auto TryCompareAsNamespaces =
+  [](const NestedNameSpecifier *Left,
+ const NestedNameSpecifier *Right) -> Optional {
+const NamespaceDecl *LeftAsNS = Left->getAsNamespace();
+const NamespaceDecl *RightAsNS = Right->getAsNamespace();
+if (const auto *LeftAlias = Left->getAsNamespaceAlias())
+  LeftAsNS = lookingThroughAliases(LeftAlias);
+if (const auto *RightAlias = Left->getAsNamespaceAlias())
+  RightAsNS = lookingThroughAliases(RightAlias);
+
+if (!LeftAsNS || !RightAsNS)
+  return None;
+return LeftAsNS == RightAsNS;
+  };
+
+  const auto TryCompareAsTypes =
+  [](const NestedNameSpecifier *Left,
+ const NestedNameSpecifier *Right) -> Optional {
+const Type *LeftAsTy = Left->getAsType();
+const Type *RightAsTy = Right->getAsType();
+
+if (!LeftAsTy || !RightAsTy)
+  return None;
+
+LeftAsTy = LeftAsTy->getCanonicalTypeUnqualified().getTypePtr();
+RightAsTy = RightAsTy->get

[PATCH] D115879: [clang-format] extern with new line brace without indentation

2021-12-17 Thread Owen Pan via Phabricator via cfe-commits
owenpan accepted this revision.
owenpan added inline comments.



Comment at: clang/lib/Format/UnwrappedLineParser.cpp:1291-1293
+((Style.IndentExternBlock == FormatStyle::IEBS_Indent) ||
+ (Style.BraceWrapping.AfterExternBlock &&
+  Style.IndentExternBlock == FormatStyle::IEBS_AfterExternBlock))

Nit: the outer parens are unnecessary?



Comment at: clang/unittests/Format/FormatTest.cpp:3804
   Style.BraceWrapping.AfterExternBlock = true;
-  verifyFormat("extern \"C\"\n{ /*13*/\n}", Style);
+  Style.IndentExternBlock = FormatStyle::IEBS_Indent;
+  verifyFormat("extern \"C\"\n"

I would remove either line 3801 or 3804.



Comment at: clang/unittests/Format/FormatTest.cpp:3825
+  Style.BraceWrapping.AfterExternBlock = true;
+  Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
+  verifyFormat("extern \"C\"\n"

Nit: you can remove this line.


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

https://reviews.llvm.org/D115879

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


[PATCH] D115902: [OPENMP]Look through member function call base during implicit DSA analysis.

2021-12-17 Thread Mike Rice via Phabricator via cfe-commits
mikerice accepted this revision.
mikerice 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/D115902/new/

https://reviews.llvm.org/D115902

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


[PATCH] D115888: [Attributor][Fix] Add alignment return attribute to HeapToStack

2021-12-17 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert added inline comments.



Comment at: clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp:1411
+CGM.getLLVMContext(), llvm::Attribute::Alignment,
+CGM.getContext().getTypeAlignInChars(VarTy).getQuantity()));
 

This doesn't work. If the type alignment is > 8 the stack won't fulfill it 
unless you modify 
```
  /// Add worst-case padding so that future allocations are properly aligned.
  constexpr const uint32_t Alignment = 8;
```
in `openmp/libomptarget/DeviceRTL/src/State.cpp`.
The fact that the state has a fixed alignment right now makes it impossible to 
allocate higher aligned types anyway.

Proposal:
Add an argument to _alloc_shared that is the alignment as computed above, 
effecitively making it _alloc_shared_aligned. Modify the stack to actually 
align the base pointer rather than extend the allocation based on the alignment 
passed in. Then any type alignment can be handled, including user aligned types.



Comment at: clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp:1475
+  CGM.getModule(), OMPRTL___kmpc_free_shared),
+  {AddrSizePair.first, AddrSizePair.second});
 }

Not needed. Will cause a warning, no?



Comment at: llvm/lib/Transforms/IPO/AttributorAttributes.cpp:5940
+  } else if (MaybeAlign RetAlign = AI.CB->getRetAlign()) {
+Alignment = max(Alignment, RetAlign);
   }

This is sensible but needs a test. You can even do it without the else for all 
allocations. With the proposed changes above alloc_shared would also fall into 
the aligned_alloc case.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115888

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


[clang] d976fb0 - [OpenMP][NFC] update status for 5.1 'fail' atomic extension

2021-12-17 Thread via cfe-commits

Author: Deepak Eachempati
Date: 2021-12-17T11:46:37-06:00
New Revision: d976fb0204283b5aabf40d805e59ce6d1502d1d9

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

LOG: [OpenMP][NFC] update status for 5.1 'fail' atomic extension

Update status for the atomic 'fail' clause to "worked on".

Reviewed By: cchen

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

Added: 


Modified: 
clang/docs/OpenMPSupport.rst

Removed: 




diff  --git a/clang/docs/OpenMPSupport.rst b/clang/docs/OpenMPSupport.rst
index 8b530b9febef6..e5c4de102c258 100644
--- a/clang/docs/OpenMPSupport.rst
+++ b/clang/docs/OpenMPSupport.rst
@@ -266,7 +266,7 @@ want to help with the implementation.
 
+==+==+==+===+
 | atomic extension | 'compare' clause on atomic construct  
   | :good:`worked on`| 
  |
 
+--+--+--+---+
-| atomic extension | 'fail' clause on atomic construct 
   | :none:`unclaimed`| 
  |
+| atomic extension | 'fail' clause on atomic construct 
   | :part:`worked on`| 
  |
 
+--+--+--+---+
 | base language| C++ attribute specifier syntax
   | :good:`done` | D105648 
  |
 
+--+--+--+---+



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


[PATCH] D115901: [OpenMP][NFC] update status for 5.1 'fail' atomic extension

2021-12-17 Thread 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 rGd976fb020428: [OpenMP][NFC] update status for 5.1 
'fail' atomic extension (authored by dreachem, committed by Chi-Chun, 
Chen ).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115901

Files:
  clang/docs/OpenMPSupport.rst


Index: clang/docs/OpenMPSupport.rst
===
--- clang/docs/OpenMPSupport.rst
+++ clang/docs/OpenMPSupport.rst
@@ -266,7 +266,7 @@
 
+==+==+==+===+
 | atomic extension | 'compare' clause on atomic construct  
   | :good:`worked on`| 
  |
 
+--+--+--+---+
-| atomic extension | 'fail' clause on atomic construct 
   | :none:`unclaimed`| 
  |
+| atomic extension | 'fail' clause on atomic construct 
   | :part:`worked on`| 
  |
 
+--+--+--+---+
 | base language| C++ attribute specifier syntax
   | :good:`done` | D105648 
  |
 
+--+--+--+---+


Index: clang/docs/OpenMPSupport.rst
===
--- clang/docs/OpenMPSupport.rst
+++ clang/docs/OpenMPSupport.rst
@@ -266,7 +266,7 @@
 +==+==+==+===+
 | atomic extension | 'compare' clause on atomic construct | :good:`worked on`|   |
 +--+--+--+---+
-| atomic extension | 'fail' clause on atomic construct| :none:`unclaimed`|   |
+| atomic extension | 'fail' clause on atomic construct| :part:`worked on`|   |
 +--+--+--+---+
 | base language| C++ attribute specifier syntax   | :good:`done` | D105648   |
 +--+--+--+---+
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D115709: [RISCV] Remove Zvamo Extention

2021-12-17 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added a comment.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115709

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


[clang] 6674854 - [OPENMP]Look through member function call base during implicit DSA analysis.

2021-12-17 Thread Alexey Bataev via cfe-commits

Author: Alexey Bataev
Date: 2021-12-17T10:18:51-08:00
New Revision: 667485413fd32cf470d7cd6260b50e486fedaf5e

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

LOG: [OPENMP]Look through member function call base during implicit DSA 
analysis.

Need to look through the base of the member function calls at the DSA
analysis stage to correctly capture implicit class instances.

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

Added: 
clang/test/OpenMP/task_member_call_codegen.cpp

Modified: 
clang/lib/Sema/SemaOpenMP.cpp
clang/test/OpenMP/taskloop_codegen.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaOpenMP.cpp b/clang/lib/Sema/SemaOpenMP.cpp
index eb18afdccb326..c873e2661d44b 100644
--- a/clang/lib/Sema/SemaOpenMP.cpp
+++ b/clang/lib/Sema/SemaOpenMP.cpp
@@ -3837,6 +3837,9 @@ class DSAAttrChecker final : public 
StmtVisitor {
 Visit(C);
   }
 }
+if (Expr *Callee = S->getCallee())
+  if (auto *CE = dyn_cast(Callee->IgnoreParenImpCasts()))
+Visit(CE->getBase());
   }
   void VisitStmt(Stmt *S) {
 for (Stmt *C : S->children()) {

diff  --git a/clang/test/OpenMP/task_member_call_codegen.cpp 
b/clang/test/OpenMP/task_member_call_codegen.cpp
new file mode 100644
index 0..886d84020bfc4
--- /dev/null
+++ b/clang/test/OpenMP/task_member_call_codegen.cpp
@@ -0,0 +1,319 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --function-signature --include-generated-funcs --replace-value-regex 
"__omp_offloading_[0-9a-z]+_[0-9a-z]+" "reduction_size[.].+[.]" 
"pl_cond[.].+[.|,]" --prefix-filecheck-ir-name _
+// RUN: %clang_cc1 -verify -triple x86_64-apple-darwin10 -fopenmp -x c++ 
-emit-llvm %s -o - | FileCheck %s --check-prefix=CHECK1
+// RUN: %clang_cc1 -fopenmp -x c++ -triple x86_64-apple-darwin10 -emit-pch -o 
%t %s
+// RUN: %clang_cc1 -fopenmp -x c++ -triple x86_64-apple-darwin10 -include-pch 
%t -verify %s -emit-llvm -o - | FileCheck %s --check-prefix=CHECK2
+// RUN: %clang_cc1 -verify -triple x86_64-apple-darwin10 -fopenmp 
-fopenmp-enable-irbuilder -x c++ -emit-llvm %s -o - | FileCheck %s 
--check-prefix=CHECK3
+// RUN: %clang_cc1 -fopenmp -fopenmp-enable-irbuilder -x c++ -triple 
x86_64-apple-darwin10 -emit-pch -o %t %s
+// RUN: %clang_cc1 -fopenmp -fopenmp-enable-irbuilder -x c++ -triple 
x86_64-apple-darwin10 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s 
--check-prefix=CHECK4
+
+// RUN: %clang_cc1 -verify -triple x86_64-apple-darwin10 -fopenmp-simd -x c++ 
-emit-llvm %s -o - | FileCheck %s --implicit-check-not="{{__kmpc|__tgt}}"
+// RUN: %clang_cc1 -fopenmp-simd -x c++ -triple x86_64-apple-darwin10 
-emit-pch -o %t %s
+// RUN: %clang_cc1 -fopenmp-simd -x c++ -triple x86_64-apple-darwin10 
-include-pch %t -verify %s -emit-llvm -o - | FileCheck %s 
--implicit-check-not="{{__kmpc|__tgt}}"
+// expected-no-diagnostics
+
+#ifndef HEADER
+#define HEADER
+
+class a {
+public:
+  void b();
+};
+void c() {
+  a d;
+#pragma omp task
+  d.b();
+}
+#endif
+// CHECK1-LABEL: define {{[^@]+}}@_Z1cv
+// CHECK1-SAME: () #[[ATTR0:[0-9]+]] {
+// CHECK1-NEXT:  entry:
+// CHECK1-NEXT:[[D:%.*]] = alloca [[CLASS_A:%.*]], align 1
+// CHECK1-NEXT:[[AGG_CAPTURED:%.*]] = alloca [[STRUCT_ANON:%.*]], align 1
+// CHECK1-NEXT:[[TMP0:%.*]] = call i32 
@__kmpc_global_thread_num(%struct.ident_t* @[[GLOB1:[0-9]+]])
+// CHECK1-NEXT:[[TMP1:%.*]] = call i8* 
@__kmpc_omp_task_alloc(%struct.ident_t* @[[GLOB1]], i32 [[TMP0]], i32 1, i64 
48, i64 1, i32 (i32, i8*)* bitcast (i32 (i32, 
%struct.kmp_task_t_with_privates*)* @.omp_task_entry. to i32 (i32, i8*)*))
+// CHECK1-NEXT:[[TMP2:%.*]] = bitcast i8* [[TMP1]] to 
%struct.kmp_task_t_with_privates*
+// CHECK1-NEXT:[[TMP3:%.*]] = getelementptr inbounds 
[[STRUCT_KMP_TASK_T_WITH_PRIVATES:%.*]], %struct.kmp_task_t_with_privates* 
[[TMP2]], i32 0, i32 0
+// CHECK1-NEXT:[[TMP4:%.*]] = getelementptr inbounds 
[[STRUCT_KMP_TASK_T_WITH_PRIVATES]], %struct.kmp_task_t_with_privates* 
[[TMP2]], i32 0, i32 1
+// CHECK1-NEXT:[[TMP5:%.*]] = getelementptr inbounds 
[[STRUCT__KMP_PRIVATES_T:%.*]], %struct..kmp_privates.t* [[TMP4]], i32 0, i32 0
+// CHECK1-NEXT:[[TMP6:%.*]] = call i32 @__kmpc_omp_task(%struct.ident_t* 
@[[GLOB1]], i32 [[TMP0]], i8* [[TMP1]])
+// CHECK1-NEXT:ret void
+//
+//
+// CHECK1-LABEL: define {{[^@]+}}@.omp_task_privates_map.
+// CHECK1-SAME: (%struct..kmp_privates.t* noalias [[TMP0:%.*]], %class.a** 
noalias [[TMP1:%.*]]) #[[ATTR2:[0-9]+]] {
+// CHECK1-NEXT:  entry:
+// CHECK1-NEXT:[[DOTADDR:%.*]] = alloca %struct..kmp_privates.t*, align 8
+// CHECK1-NEXT:[[DOTADDR1:%.*]] = alloca %class.a**, align 8
+// CHECK1-NEXT:store %struct..kmp_privates.t* [[TMP0]], 
%struct..kmp_privates.t** [[DOTADDR]], align 8
+//

[PATCH] D115902: [OPENMP]Look through member function call base during implicit DSA analysis.

2021-12-17 Thread Alexey Bataev 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 rG667485413fd3: [OPENMP]Look through member function call base 
during implicit DSA analysis. (authored by ABataev).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115902

Files:
  clang/lib/Sema/SemaOpenMP.cpp
  clang/test/OpenMP/task_member_call_codegen.cpp
  clang/test/OpenMP/taskloop_codegen.cpp

Index: clang/test/OpenMP/taskloop_codegen.cpp
===
--- clang/test/OpenMP/taskloop_codegen.cpp
+++ clang/test/OpenMP/taskloop_codegen.cpp
@@ -238,8 +238,8 @@
 // CHECK-LABEL: taskloop_with_class
 void taskloop_with_class() {
   St s1;
-  // CHECK: [[TD:%.+]] = call i8* @__kmpc_omp_task_alloc(%struct.ident_t* @{{.+}}, i32 [[GTID:%.+]], i32 1, i64 80, i64 8, i32 (i32, i8*)* bitcast (i32 (i32, [[TD_TYPE:%.+]]*)* @{{.+}} to i32 (i32, i8*)*))
-  // CHECK: call void @__kmpc_taskloop(%struct.ident_t* @{{.+}}, i32 [[GTID]], i8* [[TD]], i32 1, i64* %{{.+}}, i64* %{{.+}}, i64 %{{.+}}, i32 1, i32 0, i64 0, i8* null)
+  // CHECK: [[TD:%.+]] = call i8* @__kmpc_omp_task_alloc(%struct.ident_t* @{{.+}}, i32 [[GTID:%.+]], i32 1, i64 88, i64 8, i32 (i32, i8*)* bitcast (i32 (i32, [[TD_TYPE:%.+]]*)* @{{.+}} to i32 (i32, i8*)*))
+  // CHECK: call void @__kmpc_taskloop(%struct.ident_t* @{{.+}}, i32 [[GTID]], i8* [[TD]], i32 1, i64* %{{.+}}, i64* %{{.+}}, i64 %{{.+}}, i32 1, i32 0, i64 0, i8* bitcast (void ([[TD_TYPE]]*, [[TD_TYPE]]*, i32)* @{{.+}} to i8*))
 #pragma omp taskloop
   for (St s = St(); s < s1; s += 1) {
   }
Index: clang/test/OpenMP/task_member_call_codegen.cpp
===
--- /dev/null
+++ clang/test/OpenMP/task_member_call_codegen.cpp
@@ -0,0 +1,319 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --function-signature --include-generated-funcs --replace-value-regex "__omp_offloading_[0-9a-z]+_[0-9a-z]+" "reduction_size[.].+[.]" "pl_cond[.].+[.|,]" --prefix-filecheck-ir-name _
+// RUN: %clang_cc1 -verify -triple x86_64-apple-darwin10 -fopenmp -x c++ -emit-llvm %s -o - | FileCheck %s --check-prefix=CHECK1
+// RUN: %clang_cc1 -fopenmp -x c++ -triple x86_64-apple-darwin10 -emit-pch -o %t %s
+// RUN: %clang_cc1 -fopenmp -x c++ -triple x86_64-apple-darwin10 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefix=CHECK2
+// RUN: %clang_cc1 -verify -triple x86_64-apple-darwin10 -fopenmp -fopenmp-enable-irbuilder -x c++ -emit-llvm %s -o - | FileCheck %s --check-prefix=CHECK3
+// RUN: %clang_cc1 -fopenmp -fopenmp-enable-irbuilder -x c++ -triple x86_64-apple-darwin10 -emit-pch -o %t %s
+// RUN: %clang_cc1 -fopenmp -fopenmp-enable-irbuilder -x c++ -triple x86_64-apple-darwin10 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefix=CHECK4
+
+// RUN: %clang_cc1 -verify -triple x86_64-apple-darwin10 -fopenmp-simd -x c++ -emit-llvm %s -o - | FileCheck %s --implicit-check-not="{{__kmpc|__tgt}}"
+// RUN: %clang_cc1 -fopenmp-simd -x c++ -triple x86_64-apple-darwin10 -emit-pch -o %t %s
+// RUN: %clang_cc1 -fopenmp-simd -x c++ -triple x86_64-apple-darwin10 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --implicit-check-not="{{__kmpc|__tgt}}"
+// expected-no-diagnostics
+
+#ifndef HEADER
+#define HEADER
+
+class a {
+public:
+  void b();
+};
+void c() {
+  a d;
+#pragma omp task
+  d.b();
+}
+#endif
+// CHECK1-LABEL: define {{[^@]+}}@_Z1cv
+// CHECK1-SAME: () #[[ATTR0:[0-9]+]] {
+// CHECK1-NEXT:  entry:
+// CHECK1-NEXT:[[D:%.*]] = alloca [[CLASS_A:%.*]], align 1
+// CHECK1-NEXT:[[AGG_CAPTURED:%.*]] = alloca [[STRUCT_ANON:%.*]], align 1
+// CHECK1-NEXT:[[TMP0:%.*]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @[[GLOB1:[0-9]+]])
+// CHECK1-NEXT:[[TMP1:%.*]] = call i8* @__kmpc_omp_task_alloc(%struct.ident_t* @[[GLOB1]], i32 [[TMP0]], i32 1, i64 48, i64 1, i32 (i32, i8*)* bitcast (i32 (i32, %struct.kmp_task_t_with_privates*)* @.omp_task_entry. to i32 (i32, i8*)*))
+// CHECK1-NEXT:[[TMP2:%.*]] = bitcast i8* [[TMP1]] to %struct.kmp_task_t_with_privates*
+// CHECK1-NEXT:[[TMP3:%.*]] = getelementptr inbounds [[STRUCT_KMP_TASK_T_WITH_PRIVATES:%.*]], %struct.kmp_task_t_with_privates* [[TMP2]], i32 0, i32 0
+// CHECK1-NEXT:[[TMP4:%.*]] = getelementptr inbounds [[STRUCT_KMP_TASK_T_WITH_PRIVATES]], %struct.kmp_task_t_with_privates* [[TMP2]], i32 0, i32 1
+// CHECK1-NEXT:[[TMP5:%.*]] = getelementptr inbounds [[STRUCT__KMP_PRIVATES_T:%.*]], %struct..kmp_privates.t* [[TMP4]], i32 0, i32 0
+// CHECK1-NEXT:[[TMP6:%.*]] = call i32 @__kmpc_omp_task(%struct.ident_t* @[[GLOB1]], i32 [[TMP0]], i8* [[TMP1]])
+// CHECK1-NEXT:ret void
+//
+//
+// CHECK1-LABEL: define {{[^@]+}}@.omp_task_privates_map.
+// CHECK1-SAME: (%struct..kmp_privates.t* noalias [[TMP0:%.*]], %class.a** noalias [

[clang] 62ead36 - [clang-format] Formatter does not handle c++11 string literal prefix with stringize #

2021-12-17 Thread via cfe-commits

Author: mydeveloperday
Date: 2021-12-17T18:29:32Z
New Revision: 62ead3654795bfb09bf7296ef5db8deea0f758cb

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

LOG: [clang-format] Formatter does not handle c++11 string literal prefix with 
stringize #

https://github.com/llvm/llvm-project/issues/27740

Ensure
```
```
behave the same as
```
```

when formatted, ensure clang-format follows the conventions for `L` `u` `U` `u8`

https://docs.microsoft.com/en-us/cpp/cpp/string-and-character-literals-cpp?redirectedfrom=MSDN&view=msvc-170

Fixes #27740

Reviewed By: curdeius, owenpan

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

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 9dfe1d3e18f4b..6fc3a4d5d18ae 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3242,7 +3242,13 @@ bool TokenAnnotator::spaceRequiredBetween(const 
AnnotatedLine &Line,
 return false;
   if (Left.is(tok::period) || Right.is(tok::period))
 return false;
-  if (Right.is(tok::hash) && Left.is(tok::identifier) && Left.TokenText == "L")
+  // u#str, U#str, L#str, u8#str
+  // uR#str, UR#str, LR#str, u8R#str
+  if (Right.is(tok::hash) && Left.is(tok::identifier) &&
+  (Left.TokenText == "L" || Left.TokenText == "u" ||
+   Left.TokenText == "U" || Left.TokenText == "u8" ||
+   Left.TokenText == "LR" || Left.TokenText == "uR" ||
+   Left.TokenText == "UR" || Left.TokenText == "u8R"))
 return false;
   if (Left.is(TT_TemplateCloser) && Left.MatchingParen &&
   Left.MatchingParen->Previous &&

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 2eb10609646a6..2b9a72e374144 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -4396,6 +4396,13 @@ TEST_F(FormatTest, MacroDefinitionInsideStatement) {
 
 TEST_F(FormatTest, HashInMacroDefinition) {
   EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle()));
+  EXPECT_EQ("#define A(c) u#c", format("#define A(c) u#c", getLLVMStyle()));
+  EXPECT_EQ("#define A(c) U#c", format("#define A(c) U#c", getLLVMStyle()));
+  EXPECT_EQ("#define A(c) u8#c", format("#define A(c) u8#c", getLLVMStyle()));
+  EXPECT_EQ("#define A(c) LR#c", format("#define A(c) LR#c", getLLVMStyle()));
+  EXPECT_EQ("#define A(c) uR#c", format("#define A(c) uR#c", getLLVMStyle()));
+  EXPECT_EQ("#define A(c) UR#c", format("#define A(c) UR#c", getLLVMStyle()));
+  EXPECT_EQ("#define A(c) u8R#c", format("#define A(c) u8R#c", 
getLLVMStyle()));
   verifyFormat("#define A \\\n  b #c;", getLLVMStyleWithColumns(11));
   verifyFormat("#define A  \\\n"
"  {\\\n"



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


[PATCH] D115938: [clang-format] Formatter does not handle c++11 string literal prefix with stringize #

2021-12-17 Thread MyDeveloperDay 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 rG62ead3654795: [clang-format] Formatter does not handle c++11 
string literal prefix with… (authored by MyDeveloperDay).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115938

Files:
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTest.cpp


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -4396,6 +4396,13 @@
 
 TEST_F(FormatTest, HashInMacroDefinition) {
   EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle()));
+  EXPECT_EQ("#define A(c) u#c", format("#define A(c) u#c", getLLVMStyle()));
+  EXPECT_EQ("#define A(c) U#c", format("#define A(c) U#c", getLLVMStyle()));
+  EXPECT_EQ("#define A(c) u8#c", format("#define A(c) u8#c", getLLVMStyle()));
+  EXPECT_EQ("#define A(c) LR#c", format("#define A(c) LR#c", getLLVMStyle()));
+  EXPECT_EQ("#define A(c) uR#c", format("#define A(c) uR#c", getLLVMStyle()));
+  EXPECT_EQ("#define A(c) UR#c", format("#define A(c) UR#c", getLLVMStyle()));
+  EXPECT_EQ("#define A(c) u8R#c", format("#define A(c) u8R#c", 
getLLVMStyle()));
   verifyFormat("#define A \\\n  b #c;", getLLVMStyleWithColumns(11));
   verifyFormat("#define A  \\\n"
"  {\\\n"
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -3242,7 +3242,13 @@
 return false;
   if (Left.is(tok::period) || Right.is(tok::period))
 return false;
-  if (Right.is(tok::hash) && Left.is(tok::identifier) && Left.TokenText == "L")
+  // u#str, U#str, L#str, u8#str
+  // uR#str, UR#str, LR#str, u8R#str
+  if (Right.is(tok::hash) && Left.is(tok::identifier) &&
+  (Left.TokenText == "L" || Left.TokenText == "u" ||
+   Left.TokenText == "U" || Left.TokenText == "u8" ||
+   Left.TokenText == "LR" || Left.TokenText == "uR" ||
+   Left.TokenText == "UR" || Left.TokenText == "u8R"))
 return false;
   if (Left.is(TT_TemplateCloser) && Left.MatchingParen &&
   Left.MatchingParen->Previous &&


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -4396,6 +4396,13 @@
 
 TEST_F(FormatTest, HashInMacroDefinition) {
   EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle()));
+  EXPECT_EQ("#define A(c) u#c", format("#define A(c) u#c", getLLVMStyle()));
+  EXPECT_EQ("#define A(c) U#c", format("#define A(c) U#c", getLLVMStyle()));
+  EXPECT_EQ("#define A(c) u8#c", format("#define A(c) u8#c", getLLVMStyle()));
+  EXPECT_EQ("#define A(c) LR#c", format("#define A(c) LR#c", getLLVMStyle()));
+  EXPECT_EQ("#define A(c) uR#c", format("#define A(c) uR#c", getLLVMStyle()));
+  EXPECT_EQ("#define A(c) UR#c", format("#define A(c) UR#c", getLLVMStyle()));
+  EXPECT_EQ("#define A(c) u8R#c", format("#define A(c) u8R#c", getLLVMStyle()));
   verifyFormat("#define A \\\n  b #c;", getLLVMStyleWithColumns(11));
   verifyFormat("#define A  \\\n"
"  {\\\n"
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -3242,7 +3242,13 @@
 return false;
   if (Left.is(tok::period) || Right.is(tok::period))
 return false;
-  if (Right.is(tok::hash) && Left.is(tok::identifier) && Left.TokenText == "L")
+  // u#str, U#str, L#str, u8#str
+  // uR#str, UR#str, LR#str, u8R#str
+  if (Right.is(tok::hash) && Left.is(tok::identifier) &&
+  (Left.TokenText == "L" || Left.TokenText == "u" ||
+   Left.TokenText == "U" || Left.TokenText == "u8" ||
+   Left.TokenText == "LR" || Left.TokenText == "uR" ||
+   Left.TokenText == "UR" || Left.TokenText == "u8R"))
 return false;
   if (Left.is(TT_TemplateCloser) && Left.MatchingParen &&
   Left.MatchingParen->Previous &&
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D115903: [clang-format] Extra spaces surrounding arrow in templated member call in variable decl

2021-12-17 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay updated this revision to Diff 395165.
MyDeveloperDay added a comment.

Add additional test to show lambda's should be ok


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

https://reviews.llvm.org/D115903

Files:
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTest.cpp


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -6780,6 +6780,9 @@
 
   // Not trailing return types.
   verifyFormat("void f() { auto a = b->c(); }");
+  verifyFormat("auto a = p->foo();");
+  verifyFormat("int a = p->foo();");
+  verifyFormat("auto lmbd = [] NOEXCEPT -> int { return 0; };");
 }
 
 TEST_F(FormatTest, DeductionGuides) {
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -1679,7 +1679,7 @@
   Current.setType(TT_LambdaArrow);
 } else if (Current.is(tok::arrow) && AutoFound && Line.MustBeDeclaration &&
Current.NestingLevel == 0 &&
-   !Current.Previous->is(tok::kw_operator)) {
+   !Current.Previous->isOneOf(tok::kw_operator, tok::identifier)) {
   // not auto operator->() -> xxx;
   Current.setType(TT_TrailingReturnArrow);
 } else if (Current.is(tok::arrow) && Current.Previous &&


Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -6780,6 +6780,9 @@
 
   // Not trailing return types.
   verifyFormat("void f() { auto a = b->c(); }");
+  verifyFormat("auto a = p->foo();");
+  verifyFormat("int a = p->foo();");
+  verifyFormat("auto lmbd = [] NOEXCEPT -> int { return 0; };");
 }
 
 TEST_F(FormatTest, DeductionGuides) {
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -1679,7 +1679,7 @@
   Current.setType(TT_LambdaArrow);
 } else if (Current.is(tok::arrow) && AutoFound && Line.MustBeDeclaration &&
Current.NestingLevel == 0 &&
-   !Current.Previous->is(tok::kw_operator)) {
+   !Current.Previous->isOneOf(tok::kw_operator, tok::identifier)) {
   // not auto operator->() -> xxx;
   Current.setType(TT_TrailingReturnArrow);
 } else if (Current.is(tok::arrow) && Current.Previous &&
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D115879: [clang-format] extern with new line brace without indentation

2021-12-17 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay updated this revision to Diff 395166.
MyDeveloperDay marked 4 inline comments as done.
MyDeveloperDay added a comment.

Address nits and review comments (remove unnecessary lines)


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

https://reviews.llvm.org/D115879

Files:
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/unittests/Format/FormatTest.cpp

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -3835,36 +3835,66 @@
   Style.IndentWidth = 2;
 
   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
-  verifyFormat("extern \"C\" { /*9*/\n}", Style);
+  verifyFormat("extern \"C\" { /*9*/\n"
+   "}",
+   Style);
   verifyFormat("extern \"C\" {\n"
"  int foo10();\n"
"}",
Style);
 
   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
-  verifyFormat("extern \"C\" { /*11*/\n}", Style);
+  verifyFormat("extern \"C\" { /*11*/\n"
+   "}",
+   Style);
   verifyFormat("extern \"C\" {\n"
"int foo12();\n"
"}",
Style);
 
-  Style.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock;
   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
   Style.BraceWrapping.AfterExternBlock = true;
-  verifyFormat("extern \"C\"\n{ /*13*/\n}", Style);
+  Style.IndentExternBlock = FormatStyle::IEBS_Indent;
+  verifyFormat("extern \"C\"\n"
+   "{ /*13*/\n"
+   "}",
+   Style);
   verifyFormat("extern \"C\"\n{\n"
"  int foo14();\n"
"}",
Style);
 
-  Style.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock;
-  Style.BreakBeforeBraces = FormatStyle::BS_Custom;
   Style.BraceWrapping.AfterExternBlock = false;
-  verifyFormat("extern \"C\" { /*15*/\n}", Style);
+  Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
+  verifyFormat("extern \"C\" { /*15*/\n"
+   "}",
+   Style);
   verifyFormat("extern \"C\" {\n"
"int foo16();\n"
"}",
Style);
+
+  Style.BraceWrapping.AfterExternBlock = true;
+  verifyFormat("extern \"C\"\n"
+   "{ /*13*/\n"
+   "}",
+   Style);
+  verifyFormat("extern \"C\"\n"
+   "{\n"
+   "int foo14();\n"
+   "}",
+   Style);
+
+  Style.IndentExternBlock = FormatStyle::IEBS_Indent;
+  verifyFormat("extern \"C\"\n"
+   "{ /*13*/\n"
+   "}",
+   Style);
+  verifyFormat("extern \"C\"\n"
+   "{\n"
+   "  int foo14();\n"
+   "}",
+   Style);
 }
 
 TEST_F(FormatTest, FormatsInlineASM) {
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -1279,17 +1279,18 @@
 if (FormatTok->Tok.is(tok::string_literal)) {
   nextToken();
   if (FormatTok->Tok.is(tok::l_brace)) {
-if (!Style.IndentExternBlock) {
-  if (Style.BraceWrapping.AfterExternBlock) {
-addUnwrappedLine();
-  }
-  unsigned AddLevels = Style.BraceWrapping.AfterExternBlock ? 1u : 0u;
-  parseBlock(/*MustBeDeclaration=*/true, AddLevels);
-} else {
-  unsigned AddLevels =
-  Style.IndentExternBlock == FormatStyle::IEBS_Indent ? 1u : 0u;
-  parseBlock(/*MustBeDeclaration=*/true, AddLevels);
-}
+if (Style.BraceWrapping.AfterExternBlock)
+  addUnwrappedLine();
+// Either we indent or for backwards compatibility we follow the
+// AfterExternBlock style.
+unsigned AddLevels =
+(Style.IndentExternBlock == FormatStyle::IEBS_Indent) ||
+(Style.BraceWrapping.AfterExternBlock &&
+ Style.IndentExternBlock ==
+ FormatStyle::IEBS_AfterExternBlock)
+? 1u
+: 0u;
+parseBlock(/*MustBeDeclaration=*/true, AddLevels);
 addUnwrappedLine();
 return;
   }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 163c13f - [clang-format] Fix formatting of the code that follows C# Lambda Expressions

2021-12-17 Thread Owen Pan via cfe-commits

Author: Peter Stys
Date: 2021-12-17T10:42:15-08:00
New Revision: 163c13fed9f68c31a14b3d2409b994909f0600bb

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

LOG: [clang-format] Fix formatting of the code that follows C# Lambda 
Expressions

The alignment fix introduced by https://reviews.llvm.org/D104388 caused a 
regression whereby formatting of code that follows the lambda block is 
incorrect i.e. separate expressions are put on the same line.

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

Added: 


Modified: 
clang/lib/Format/UnwrappedLineParser.cpp
clang/lib/Format/UnwrappedLineParser.h
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 78405f23e4003..0b1771ba7c9c9 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -1941,6 +1941,22 @@ bool UnwrappedLineParser::tryToParseBracedList() {
   return true;
 }
 
+bool UnwrappedLineParser::tryToParseCSharpLambda() {
+  // Fat arrows (=>) have tok::TokenKind tok::equal but TokenType
+  // TT_FatArrow. They always start an expression or a child block if
+  // followed by a curly brace.
+  nextToken();
+  if (FormatTok->isNot(tok::l_brace))
+return false;
+  // C# may break after => if the next character is a newline.
+  if (Style.BraceWrapping.AfterFunction) {
+// calling `addUnwrappedLine()` here causes odd parsing errors.
+FormatTok->MustBreakBefore = true;
+  }
+  parseChildBlock();
+  return true;
+}
+
 bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons,
   bool IsEnum,
   tok::TokenKind ClosingBraceKind) {
@@ -1949,23 +1965,9 @@ bool UnwrappedLineParser::parseBracedList(bool 
ContinueOnSemicolons,
   // FIXME: Once we have an expression parser in the UnwrappedLineParser,
   // replace this by using parseAssignmentExpression() inside.
   do {
-if (Style.isCSharp()) {
-  // Fat arrows (=>) have tok::TokenKind tok::equal but TokenType
-  // TT_FatArrow. They always start an expression or a child block if
-  // followed by a curly brace.
-  if (FormatTok->is(TT_FatArrow)) {
-nextToken();
-if (FormatTok->is(tok::l_brace)) {
-  // C# may break after => if the next character is a newline.
-  if (Style.isCSharp() && Style.BraceWrapping.AfterFunction == true) {
-// calling `addUnwrappedLine()` here causes odd parsing errors.
-FormatTok->MustBreakBefore = true;
-  }
-  parseChildBlock();
-  continue;
-}
-  }
-}
+if (Style.isCSharp() && FormatTok->is(TT_FatArrow))
+  if (tryToParseCSharpLambda())
+continue;
 if (Style.Language == FormatStyle::LK_JavaScript) {
   if (FormatTok->is(Keywords.kw_function) ||
   FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function)) {
@@ -2092,7 +2094,7 @@ void UnwrappedLineParser::parseParens() {
   break;
 case tok::equal:
   if (Style.isCSharp() && FormatTok->is(TT_FatArrow))
-parseStructuralElement();
+tryToParseCSharpLambda();
   else
 nextToken();
   break;

diff  --git a/clang/lib/Format/UnwrappedLineParser.h 
b/clang/lib/Format/UnwrappedLineParser.h
index b4c0826545971..3c07fbf2e8d36 100644
--- a/clang/lib/Format/UnwrappedLineParser.h
+++ b/clang/lib/Format/UnwrappedLineParser.h
@@ -138,6 +138,7 @@ class UnwrappedLineParser {
   // 
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/where-generic-type-constraint
   void parseCSharpGenericTypeConstraint();
   bool tryToParseLambda();
+  bool tryToParseCSharpLambda();
   bool tryToParseLambdaIntroducer();
   bool tryToParsePropertyAccessor();
   void tryToParseJSFunction();

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index 78547e07d2150..2cfec61d8f94b 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -759,6 +759,128 @@ class MyClass
GoogleStyle);
 }
 
+TEST_F(FormatTestCSharp, CSharpLambdasDontBreakFollowingCodeAlignment) {
+  FormatStyle GoogleStyle = getGoogleStyle(FormatStyle::LK_CSharp);
+  FormatStyle MicrosoftStyle = getMicrosoftStyle(FormatStyle::LK_CSharp);
+
+  verifyFormat(R"(//
+public class Sample
+{
+public void Test()
+{
+while (true)
+{
+preBindEnumerators.RemoveAll(enumerator => !enumerator.MoveNext());
+CodeThatFollowsLambda();
+IsWellAligned();
+}
+}
+})",
+   MicrosoftStyle);
+
+  verifyFormat(R"(//
+public

[PATCH] D115738: [clang-format] Fix formatting of the code that follows C# Lambda Expressions

2021-12-17 Thread Owen Pan 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 rG163c13fed9f6: [clang-format] Fix formatting of the code that 
follows C# Lambda Expressions (authored by peterstys, committed by owenpan).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115738

Files:
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/lib/Format/UnwrappedLineParser.h
  clang/unittests/Format/FormatTestCSharp.cpp

Index: clang/unittests/Format/FormatTestCSharp.cpp
===
--- clang/unittests/Format/FormatTestCSharp.cpp
+++ clang/unittests/Format/FormatTestCSharp.cpp
@@ -759,6 +759,128 @@
GoogleStyle);
 }
 
+TEST_F(FormatTestCSharp, CSharpLambdasDontBreakFollowingCodeAlignment) {
+  FormatStyle GoogleStyle = getGoogleStyle(FormatStyle::LK_CSharp);
+  FormatStyle MicrosoftStyle = getMicrosoftStyle(FormatStyle::LK_CSharp);
+
+  verifyFormat(R"(//
+public class Sample
+{
+public void Test()
+{
+while (true)
+{
+preBindEnumerators.RemoveAll(enumerator => !enumerator.MoveNext());
+CodeThatFollowsLambda();
+IsWellAligned();
+}
+}
+})",
+   MicrosoftStyle);
+
+  verifyFormat(R"(//
+public class Sample {
+  public void Test() {
+while (true) {
+  preBindEnumerators.RemoveAll(enumerator => !enumerator.MoveNext());
+  CodeThatFollowsLambda();
+  IsWellAligned();
+}
+  }
+})",
+   GoogleStyle);
+}
+
+TEST_F(FormatTestCSharp, CSharpLambdasComplexLambdasDontBreakAlignment) {
+  FormatStyle GoogleStyle = getGoogleStyle(FormatStyle::LK_CSharp);
+  FormatStyle MicrosoftStyle = getMicrosoftStyle(FormatStyle::LK_CSharp);
+
+  verifyFormat(R"(//
+public class Test
+{
+private static void ComplexLambda(BuildReport protoReport)
+{
+allSelectedScenes =
+veryVeryLongCollectionNameThatPutsTheLineLenghtAboveTheThresholds.Where(scene => scene.enabled)
+.Select(scene => scene.path)
+.ToArray();
+if (allSelectedScenes.Count == 0)
+{
+return;
+}
+Functions();
+AreWell();
+Aligned();
+AfterLambdaBlock();
+}
+})",
+   MicrosoftStyle);
+
+  verifyFormat(R"(//
+public class Test {
+  private static void ComplexLambda(BuildReport protoReport) {
+allSelectedScenes = veryVeryLongCollectionNameThatPutsTheLineLenghtAboveTheThresholds
+.Where(scene => scene.enabled)
+.Select(scene => scene.path)
+.ToArray();
+if (allSelectedScenes.Count == 0) {
+  return;
+}
+Functions();
+AreWell();
+Aligned();
+AfterLambdaBlock();
+  }
+})",
+   GoogleStyle);
+}
+
+TEST_F(FormatTestCSharp, CSharpLambdasMulipleLambdasDontBreakAlignment) {
+  FormatStyle GoogleStyle = getGoogleStyle(FormatStyle::LK_CSharp);
+  FormatStyle MicrosoftStyle = getMicrosoftStyle(FormatStyle::LK_CSharp);
+
+  verifyFormat(R"(//
+public class Test
+{
+private static void MultipleLambdas(BuildReport protoReport)
+{
+allSelectedScenes =
+veryVeryLongCollectionNameThatPutsTheLineLenghtAboveTheThresholds.Where(scene => scene.enabled)
+.Select(scene => scene.path)
+.ToArray();
+preBindEnumerators.RemoveAll(enumerator => !enumerator.MoveNext());
+if (allSelectedScenes.Count == 0)
+{
+return;
+}
+Functions();
+AreWell();
+Aligned();
+AfterLambdaBlock();
+}
+})",
+   MicrosoftStyle);
+
+  verifyFormat(R"(//
+public class Test {
+  private static void MultipleLambdas(BuildReport protoReport) {
+allSelectedScenes = veryVeryLongCollectionNameThatPutsTheLineLenghtAboveTheThresholds
+.Where(scene => scene.enabled)
+.Select(scene => scene.path)
+.ToArray();
+preBindEnumerators.RemoveAll(enumerator => !enumerator.MoveNext());
+if (allSelectedScenes.Count == 0) {
+  return;
+}
+Functions();
+AreWell();
+Aligned();
+AfterLambdaBlock();
+  }
+})",
+   GoogleStyle);
+}
+
 TEST_F(FormatTestCSharp, CSharpObjectInitializers) {
   FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
 
Index: clang/lib/Format/UnwrappedLineParser.h
===
--- clang/lib/Format/UnwrappedLineParser.h
+++ clang/lib/Format/UnwrappedLineParser.h
@@ -138,6 +138,7 @@
   // https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/where-generic-type-constraint
   void parseCSharpGenericTypeConstraint();
   bool tryToParseLambda();
+  bool tryToParseCSharpLambda();
   bool t

[PATCH] D115888: [Attributor][Fix] Add alignment return attribute to HeapToStack

2021-12-17 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 added a comment.

I will split this into two revisions, one handling the return alignment 
attribute in the Attributor, and one adding alignment information to the 
`__kmpc_alloc_shared` OpenMP runtime call, turning it into an aligned 
allocation.




Comment at: clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp:1411
+CGM.getLLVMContext(), llvm::Attribute::Alignment,
+CGM.getContext().getTypeAlignInChars(VarTy).getQuantity()));
 

jdoerfert wrote:
> This doesn't work. If the type alignment is > 8 the stack won't fulfill it 
> unless you modify 
> ```
>   /// Add worst-case padding so that future allocations are properly aligned.
>   constexpr const uint32_t Alignment = 8;
> ```
> in `openmp/libomptarget/DeviceRTL/src/State.cpp`.
> The fact that the state has a fixed alignment right now makes it impossible 
> to allocate higher aligned types anyway.
> 
> Proposal:
> Add an argument to _alloc_shared that is the alignment as computed above, 
> effecitively making it _alloc_shared_aligned. Modify the stack to actually 
> align the base pointer rather than extend the allocation based on the 
> alignment passed in. Then any type alignment can be handled, including user 
> aligned types.
That was an original though, I was hoping to avoid the extra work, but I think 
this is definitely the only way to solve this reasonably, it might also allow 
us to use the stack more efficiently. We'll still want this alignment 
information, but we'll need to inform the runtime of the expected alignment.



Comment at: clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp:1475
+  CGM.getModule(), OMPRTL___kmpc_free_shared),
+  {AddrSizePair.first, AddrSizePair.second});
 }

jdoerfert wrote:
> Not needed. Will cause a warning, no?
Forgot about this, not intended to be included.



Comment at: llvm/lib/Transforms/IPO/AttributorAttributes.cpp:5940
+  } else if (MaybeAlign RetAlign = AI.CB->getRetAlign()) {
+Alignment = max(Alignment, RetAlign);
   }

jdoerfert wrote:
> This is sensible but needs a test. You can even do it without the else for 
> all allocations. With the proposed changes above alloc_shared would also fall 
> into the aligned_alloc case.
Yes, we want this regardless because all `malloc` like calls now seem to have 
alignment attributes, which makes sure we respect the alignment of the original 
malloc call. I can probably split this into another patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115888

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


[PATCH] D115879: [clang-format] extern with new line brace without indentation

2021-12-17 Thread Owen Pan via Phabricator via cfe-commits
owenpan accepted this revision.
owenpan added a comment.

LGTM!


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

https://reviews.llvm.org/D115879

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


[PATCH] D104830: AST: Create __va_list in the std namespace even in C.

2021-12-17 Thread Jessica Clarke via Phabricator via cfe-commits
jrtc27 added a comment.

Ping?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D104830

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


[PATCH] D114483: [SYCL] Add support for sycl_special_class attribute

2021-12-17 Thread Zahira Ammarguellat via Phabricator via cfe-commits
zahiraam updated this revision to Diff 395176.
zahiraam marked 5 inline comments as done.

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

https://reviews.llvm.org/D114483

Files:
  clang/include/clang/AST/CXXRecordDeclDefinitionBits.def
  clang/include/clang/AST/DeclCXX.h
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/AST/DeclCXX.cpp
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/Misc/pragma-attribute-supported-attributes-list.test
  clang/test/SemaSYCL/special-class-attribute-on-non-sycl.cpp
  clang/test/SemaSYCL/special-class-attribute.cpp

Index: clang/test/SemaSYCL/special-class-attribute.cpp
===
--- /dev/null
+++ clang/test/SemaSYCL/special-class-attribute.cpp
@@ -0,0 +1,74 @@
+// RUN: %clang_cc1 -std=c++11 -fsyntax-only -fsycl-is-device -verify %s
+
+// No diagnostics
+class [[clang::sycl_special_class]] class1 {
+  void __init(){};
+};
+class __attribute__((sycl_special_class)) class2 {
+  void __init(){};
+};
+
+class class3;
+class [[clang::sycl_special_class]] class3 {
+  void __init(){};
+};
+
+class class4;
+class __attribute__((sycl_special_class)) class4 {
+  void __init(){};
+};
+
+struct [[clang::sycl_special_class]] struct1 {
+  void __init(){};
+};
+struct __attribute__((sycl_special_class)) struct2 {
+  void __init(){};
+};
+
+class __attribute__((sycl_special_class)) class5;
+class class5 {
+  void __init(){};
+};
+
+// Must have __init method defined
+class __attribute__((sycl_special_class)) class6 { // expected-error {{types with 'sycl_special_class' attribute must have an '__init' method defined}}
+  class6() {}
+};
+class [[clang::sycl_special_class]] class7 { // expected-error {{types with 'sycl_special_class' attribute must have an '__init' method defined}}
+  void __init();
+};
+
+struct __attribute__((sycl_special_class)) struct3;
+struct struct3 {}; // expected-error {{types with 'sycl_special_class' attribute must have an '__init' method defined}}
+
+// Only classes
+[[clang::sycl_special_class]] int var1 = 0;   // expected-warning {{'sycl_special_class' attribute only applies to classes}}
+__attribute__((sycl_special_class)) int var2 = 0; // expected-warning {{'sycl_special_class' attribute only applies to classes}}
+
+[[clang::sycl_special_class]] void foo1();   // expected-warning {{'sycl_special_class' attribute only applies to classes}}
+__attribute__((sycl_special_class)) void foo2(); // expected-warning {{'sycl_special_class' attribute only applies to classes}}
+
+// Attribute takes no arguments
+class [[clang::sycl_special_class(1)]] class9{}; // expected-error {{'sycl_special_class' attribute takes no arguments}}
+class __attribute__((sycl_special_class(1))) class10 {}; // expected-error {{'sycl_special_class' attribute takes no arguments}}
+
+// __init method must be defined inside the CXXRecordDecl.
+class [[clang::sycl_special_class]] class11 { // expected-error {{types with 'sycl_special_class' attribute must have an '__init' method defined}}
+  void __init();
+};
+void class11::__init(){};
+
+class __attribute__((sycl_special_class)) class12 { // expected-error {{types with 'sycl_special_class' attribute must have an '__init' method defined}}
+  void __init();
+};
+void class12::__init(){};
+
+struct [[clang::sycl_special_class]] struct4 { // expected-error {{types with 'sycl_special_class' attribute must have an '__init' method defined}}
+  void __init();
+};
+void struct4::__init(){};
+
+struct __attribute__((sycl_special_class)) struct5 { // expected-error {{types with 'sycl_special_class' attribute must have an '__init' method defined}}
+  void __init();
+};
+void struct5::__init(){};
Index: clang/test/SemaSYCL/special-class-attribute-on-non-sycl.cpp
===
--- /dev/null
+++ clang/test/SemaSYCL/special-class-attribute-on-non-sycl.cpp
@@ -0,0 +1,12 @@
+// RUN: %clang_cc1 -std=c++11 -fsyntax-only -fsycl-is-device -verify %s
+// RUN: %clang_cc1 -std=c++11 -fsyntax-only -verify -x c++ %s
+
+#ifndef __SYCL_DEVICE_ONLY__
+// expected-warning@+5 {{'sycl_special_class' attribute ignored}}
+#else
+// expected-no-diagnostics
+#endif
+
+class __attribute__((sycl_special_class)) special_class {
+  void __init(){};
+};
Index: clang/test/Misc/pragma-attribute-supported-attributes-list.test
===
--- clang/test/Misc/pragma-attribute-supported-attributes-list.test
+++ clang/test/Misc/pragma-attribute-supported-attributes-list.test
@@ -155,6 +155,7 @@
 // CHECK-NEXT: ReturnTypestate (SubjectMatchRule_function, SubjectMatchRule_variable_is_parameter)
 // CHECK-NEXT: ReturnsNonNull (SubjectMatchRule_objc_method, SubjectMatchRule_function)
 // CHECK-NEXT: ReturnsTwice (SubjectMatchRule_function)
+// CHECK-NEXT: SYCLSpecialClass (SubjectMat

[PATCH] D114483: [SYCL] Add support for sycl_special_class attribute

2021-12-17 Thread Zahira Ammarguellat via Phabricator via cfe-commits
zahiraam added inline comments.



Comment at: clang/lib/Sema/SemaDecl.cpp:9118
+  NewFD->getKind() == Decl::Kind::CXXMethod &&
+  NewFD->getName() == "__init" && D.isFunctionDefinition()) {
+if (auto *def = Parent->getDefinition())

Fznamznon wrote:
> In our downstream we have not only `__init`, but `__init_esimd` as well 
> there. I wonder how this case should be handled?
I think the presence of method `__init_esimd` implies the presence of  ` 
__init` method so we could eventually check first for the presence of 
`__init_esimd` and if not present check for the presence of `__init`?



Comment at: clang/test/SemaSYCL/special-class-attribute.cpp:43
+class [[clang::sycl_special_class]] class8 { // expected-error {{types with 
'sycl_special_class' attribute must have an '__init' method defined}}
+  void __init();
+};

Fznamznon wrote:
> Will detection of `__init` method work correctly if it is defined outside of 
> the class?
> Maybe we should also mention that it should be not be defined in a separate 
> library.
Both __init and __finalize must be defined inside the class/struct.


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

https://reviews.llvm.org/D114483

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


[PATCH] D115888: [Attributor][Fix] Add alignment return attribute to HeapToStack

2021-12-17 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 395182.
jhuber6 added a comment.

Removing OpenMP code, only adding support for return alignments. Fixing OpenMP
will occur in a following patch.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115888

Files:
  llvm/lib/Transforms/IPO/AttributorAttributes.cpp
  llvm/test/Transforms/Attributor/heap_to_stack.ll


Index: llvm/test/Transforms/Attributor/heap_to_stack.ll
===
--- llvm/test/Transforms/Attributor/heap_to_stack.ll
+++ llvm/test/Transforms/Attributor/heap_to_stack.ll
@@ -34,7 +34,7 @@
 ; ISOPM-LABEL: define {{[^@]+}}@h2s_value_simplify_interaction
 ; ISOPM-SAME: (i1 [[C:%.*]], i8* nocapture nofree readnone [[A:%.*]]) {
 ; ISOPM-NEXT:  entry:
-; ISOPM-NEXT:[[M:%.*]] = tail call noalias i8* @malloc(i64 noundef 
4)
+; ISOPM-NEXT:[[M:%.*]] = tail call noalias align 16 i8* 
@malloc(i64 noundef 4)
 ; ISOPM-NEXT:br i1 [[C]], label [[T:%.*]], label [[F:%.*]]
 ; ISOPM:   t:
 ; ISOPM-NEXT:br i1 false, label [[DEAD:%.*]], label [[F2:%.*]]
@@ -43,41 +43,41 @@
 ; ISOPM:   f2:
 ; ISOPM-NEXT:[[C1:%.*]] = bitcast i8* [[M]] to i32*
 ; ISOPM-NEXT:[[C2:%.*]] = bitcast i32* [[C1]] to i8*
-; ISOPM-NEXT:[[L:%.*]] = load i8, i8* [[C2]], align 1
+; ISOPM-NEXT:[[L:%.*]] = load i8, i8* [[C2]], align 16
 ; ISOPM-NEXT:call void @usei8(i8 [[L]])
-; ISOPM-NEXT:call void @no_sync_func(i8* nocapture nofree noundef 
[[C2]]) #[[ATTR5:[0-9]+]]
+; ISOPM-NEXT:call void @no_sync_func(i8* nocapture nofree noundef 
align 16 [[C2]]) #[[ATTR5:[0-9]+]]
 ; ISOPM-NEXT:br label [[J]]
 ; ISOPM:   dead:
 ; ISOPM-NEXT:unreachable
 ; ISOPM:   j:
 ; ISOPM-NEXT:[[PHI:%.*]] = phi i8* [ [[M]], [[F]] ], [ null, 
[[F2]] ]
-; ISOPM-NEXT:tail call void @no_sync_func(i8* nocapture nofree 
noundef [[PHI]]) #[[ATTR5]]
+; ISOPM-NEXT:tail call void @no_sync_func(i8* nocapture nofree 
noundef align 16 [[PHI]]) #[[ATTR5]]
 ; ISOPM-NEXT:ret void
 ;
 ; ISNPM-LABEL: define {{[^@]+}}@h2s_value_simplify_interaction
 ; ISNPM-SAME: (i1 [[C:%.*]], i8* nocapture nofree readnone [[A:%.*]]) {
 ; ISNPM-NEXT:  entry:
-; ISNPM-NEXT:[[TMP0:%.*]] = alloca i8, i64 4, align 1
+; ISNPM-NEXT:[[TMP0:%.*]] = alloca i8, i64 4, align 16
 ; ISNPM-NEXT:br i1 [[C]], label [[T:%.*]], label [[F:%.*]]
 ; ISNPM:   t:
 ; ISNPM-NEXT:br i1 false, label [[DEAD:%.*]], label [[F2:%.*]]
 ; ISNPM:   f:
 ; ISNPM-NEXT:br label [[J:%.*]]
 ; ISNPM:   f2:
-; ISNPM-NEXT:[[L:%.*]] = load i8, i8* [[TMP0]], align 1
+; ISNPM-NEXT:[[L:%.*]] = load i8, i8* [[TMP0]], align 16
 ; ISNPM-NEXT:call void @usei8(i8 [[L]])
-; ISNPM-NEXT:call void @no_sync_func(i8* nocapture nofree noundef 
[[TMP0]]) #[[ATTR6:[0-9]+]]
+; ISNPM-NEXT:call void @no_sync_func(i8* nocapture nofree noundef 
align 16 [[TMP0]]) #[[ATTR6:[0-9]+]]
 ; ISNPM-NEXT:br label [[J]]
 ; ISNPM:   dead:
 ; ISNPM-NEXT:unreachable
 ; ISNPM:   j:
 ; ISNPM-NEXT:[[PHI:%.*]] = phi i8* [ [[TMP0]], [[F]] ], [ null, 
[[F2]] ]
-; ISNPM-NEXT:tail call void @no_sync_func(i8* nocapture nofree 
noundef [[PHI]]) #[[ATTR6]]
+; ISNPM-NEXT:tail call void @no_sync_func(i8* nocapture nofree 
noundef align 16 [[PHI]]) #[[ATTR6]]
 ; ISNPM-NEXT:ret void
 ;
 entry:
   %add = add i64 2, 2
-  %m = tail call noalias i8* @malloc(i64 %add)
+  %m = tail call align 16 noalias i8* @malloc(i64 %add)
   br i1 %c, label %t, label %f
 t:
   br i1 false, label %dead, label %f2
Index: llvm/lib/Transforms/IPO/AttributorAttributes.cpp
===
--- llvm/lib/Transforms/IPO/AttributorAttributes.cpp
+++ llvm/lib/Transforms/IPO/AttributorAttributes.cpp
@@ -5936,6 +5936,8 @@
"Expected an alignment during manifest!");
 Alignment =
 max(Alignment, MaybeAlign(AlignmentAPI.getValue().getZExtValue()));
+  } else if (MaybeAlign RetAlign = AI.CB->getRetAlign()) {
+Alignment = max(Alignment, RetAlign);
   }
 
   unsigned AS = cast(AI.CB->getType())->getAddressSpace();


Index: llvm/test/Transforms/Attributor/heap_to_stack.ll
===
--- llvm/test/Transforms/Attributor/heap_to_stack.ll
+++ llvm/test/Transforms/Attributor/heap_to_stack.ll
@@ -34,7 +34,7 @@
 ; ISOPM-LABEL: define {{[^@]+}}@h2s_value_simplify_interaction
 ; ISOPM-SAME: (i1 [[C:%.*]], i8* nocapture nofree readnone [[A:%.*]]) {
 ; IS

[PATCH] D115959: [clangd] Fix undefined behavior when generating error message at rename with an invalid name

2021-12-17 Thread Aleksandr Platonov via Phabricator via cfe-commits
ArcsinX created this revision.
ArcsinX added reviewers: sammccall, kadircet, hokein.
Herald added subscribers: usaxena95, arphaman.
ArcsinX requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

`Message()` lambda uses `Reason.Details` as an input parameter for 
`llvm::formatv()`, but `Reason` in `Message()` is a local object.
Return value of `llvm::formatv()` contains references to its input arguments, 
thus `Message()` returns an object which contains a reference to `Details` 
field of the local object `Reason`.
This patch fixes this behavior by passing `Reason` as a reference to 
`Message()` to ensure that return value of `Message()` contains references to 
alive object and also prevents copying of `InvalidName` structure at passing it 
to `makeError()`.

Provided test passes on Linux+GCC with or without this patch, but fails on 
Windows+VisualStudio without this patch.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D115959

Files:
  clang-tools-extra/clangd/refactor/Rename.cpp
  clang-tools-extra/clangd/unittests/RenameTests.cpp


Index: clang-tools-extra/clangd/unittests/RenameTests.cpp
===
--- clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -1060,6 +1060,11 @@
   )cpp",
"conflict", !HeaderFile, "Conflict"},
 
+  {R"cpp(
+int V^ar;
+  )cpp",
+   "\"const\" is a keyword", !HeaderFile, "const"},
+
   {R"cpp(// Trying to rename into the same name, SameName == SameName.
 void func() {
   int S^ameName;
Index: clang-tools-extra/clangd/refactor/Rename.cpp
===
--- clang-tools-extra/clangd/refactor/Rename.cpp
+++ clang-tools-extra/clangd/refactor/Rename.cpp
@@ -455,7 +455,7 @@
 }
 
 llvm::Error makeError(InvalidName Reason) {
-  auto Message = [](InvalidName Reason) {
+  auto Message = [](const InvalidName &Reason) {
 switch (Reason.K) {
 case InvalidName::Keywords:
   return llvm::formatv("the chosen name \"{0}\" is a keyword",
@@ -733,7 +733,7 @@
 return makeError(ReasonToReject::SameName);
   auto Invalid = checkName(RenameDecl, RInputs.NewName);
   if (Invalid)
-return makeError(*Invalid);
+return makeError(std::move(*Invalid));
 
   auto Reject = renameable(RenameDecl, RInputs.MainFilePath, RInputs.Index);
   if (Reject)


Index: clang-tools-extra/clangd/unittests/RenameTests.cpp
===
--- clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -1060,6 +1060,11 @@
   )cpp",
"conflict", !HeaderFile, "Conflict"},
 
+  {R"cpp(
+int V^ar;
+  )cpp",
+   "\"const\" is a keyword", !HeaderFile, "const"},
+
   {R"cpp(// Trying to rename into the same name, SameName == SameName.
 void func() {
   int S^ameName;
Index: clang-tools-extra/clangd/refactor/Rename.cpp
===
--- clang-tools-extra/clangd/refactor/Rename.cpp
+++ clang-tools-extra/clangd/refactor/Rename.cpp
@@ -455,7 +455,7 @@
 }
 
 llvm::Error makeError(InvalidName Reason) {
-  auto Message = [](InvalidName Reason) {
+  auto Message = [](const InvalidName &Reason) {
 switch (Reason.K) {
 case InvalidName::Keywords:
   return llvm::formatv("the chosen name \"{0}\" is a keyword",
@@ -733,7 +733,7 @@
 return makeError(ReasonToReject::SameName);
   auto Invalid = checkName(RenameDecl, RInputs.NewName);
   if (Invalid)
-return makeError(*Invalid);
+return makeError(std::move(*Invalid));
 
   auto Reject = renameable(RenameDecl, RInputs.MainFilePath, RInputs.Index);
   if (Reject)
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D115888: [Attributor][Fix] Add alignment return attribute to HeapToStack

2021-12-17 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 395187.
jhuber6 added a comment.

Removing else if, we should be able to check for all allocations.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115888

Files:
  llvm/lib/Transforms/IPO/AttributorAttributes.cpp
  llvm/test/Transforms/Attributor/heap_to_stack.ll


Index: llvm/test/Transforms/Attributor/heap_to_stack.ll
===
--- llvm/test/Transforms/Attributor/heap_to_stack.ll
+++ llvm/test/Transforms/Attributor/heap_to_stack.ll
@@ -34,7 +34,7 @@
 ; ISOPM-LABEL: define {{[^@]+}}@h2s_value_simplify_interaction
 ; ISOPM-SAME: (i1 [[C:%.*]], i8* nocapture nofree readnone [[A:%.*]]) {
 ; ISOPM-NEXT:  entry:
-; ISOPM-NEXT:[[M:%.*]] = tail call noalias i8* @malloc(i64 noundef 
4)
+; ISOPM-NEXT:[[M:%.*]] = tail call noalias align 16 i8* 
@malloc(i64 noundef 4)
 ; ISOPM-NEXT:br i1 [[C]], label [[T:%.*]], label [[F:%.*]]
 ; ISOPM:   t:
 ; ISOPM-NEXT:br i1 false, label [[DEAD:%.*]], label [[F2:%.*]]
@@ -43,41 +43,41 @@
 ; ISOPM:   f2:
 ; ISOPM-NEXT:[[C1:%.*]] = bitcast i8* [[M]] to i32*
 ; ISOPM-NEXT:[[C2:%.*]] = bitcast i32* [[C1]] to i8*
-; ISOPM-NEXT:[[L:%.*]] = load i8, i8* [[C2]], align 1
+; ISOPM-NEXT:[[L:%.*]] = load i8, i8* [[C2]], align 16
 ; ISOPM-NEXT:call void @usei8(i8 [[L]])
-; ISOPM-NEXT:call void @no_sync_func(i8* nocapture nofree noundef 
[[C2]]) #[[ATTR5:[0-9]+]]
+; ISOPM-NEXT:call void @no_sync_func(i8* nocapture nofree noundef 
align 16 [[C2]]) #[[ATTR5:[0-9]+]]
 ; ISOPM-NEXT:br label [[J]]
 ; ISOPM:   dead:
 ; ISOPM-NEXT:unreachable
 ; ISOPM:   j:
 ; ISOPM-NEXT:[[PHI:%.*]] = phi i8* [ [[M]], [[F]] ], [ null, 
[[F2]] ]
-; ISOPM-NEXT:tail call void @no_sync_func(i8* nocapture nofree 
noundef [[PHI]]) #[[ATTR5]]
+; ISOPM-NEXT:tail call void @no_sync_func(i8* nocapture nofree 
noundef align 16 [[PHI]]) #[[ATTR5]]
 ; ISOPM-NEXT:ret void
 ;
 ; ISNPM-LABEL: define {{[^@]+}}@h2s_value_simplify_interaction
 ; ISNPM-SAME: (i1 [[C:%.*]], i8* nocapture nofree readnone [[A:%.*]]) {
 ; ISNPM-NEXT:  entry:
-; ISNPM-NEXT:[[TMP0:%.*]] = alloca i8, i64 4, align 1
+; ISNPM-NEXT:[[TMP0:%.*]] = alloca i8, i64 4, align 16
 ; ISNPM-NEXT:br i1 [[C]], label [[T:%.*]], label [[F:%.*]]
 ; ISNPM:   t:
 ; ISNPM-NEXT:br i1 false, label [[DEAD:%.*]], label [[F2:%.*]]
 ; ISNPM:   f:
 ; ISNPM-NEXT:br label [[J:%.*]]
 ; ISNPM:   f2:
-; ISNPM-NEXT:[[L:%.*]] = load i8, i8* [[TMP0]], align 1
+; ISNPM-NEXT:[[L:%.*]] = load i8, i8* [[TMP0]], align 16
 ; ISNPM-NEXT:call void @usei8(i8 [[L]])
-; ISNPM-NEXT:call void @no_sync_func(i8* nocapture nofree noundef 
[[TMP0]]) #[[ATTR6:[0-9]+]]
+; ISNPM-NEXT:call void @no_sync_func(i8* nocapture nofree noundef 
align 16 [[TMP0]]) #[[ATTR6:[0-9]+]]
 ; ISNPM-NEXT:br label [[J]]
 ; ISNPM:   dead:
 ; ISNPM-NEXT:unreachable
 ; ISNPM:   j:
 ; ISNPM-NEXT:[[PHI:%.*]] = phi i8* [ [[TMP0]], [[F]] ], [ null, 
[[F2]] ]
-; ISNPM-NEXT:tail call void @no_sync_func(i8* nocapture nofree 
noundef [[PHI]]) #[[ATTR6]]
+; ISNPM-NEXT:tail call void @no_sync_func(i8* nocapture nofree 
noundef align 16 [[PHI]]) #[[ATTR6]]
 ; ISNPM-NEXT:ret void
 ;
 entry:
   %add = add i64 2, 2
-  %m = tail call noalias i8* @malloc(i64 %add)
+  %m = tail call align 16 noalias i8* @malloc(i64 %add)
   br i1 %c, label %t, label %f
 t:
   br i1 false, label %dead, label %f2
Index: llvm/lib/Transforms/IPO/AttributorAttributes.cpp
===
--- llvm/lib/Transforms/IPO/AttributorAttributes.cpp
+++ llvm/lib/Transforms/IPO/AttributorAttributes.cpp
@@ -5929,6 +5929,8 @@
   }
 
   Align Alignment(1);
+  if (MaybeAlign RetAlign = AI.CB->getRetAlign())
+Alignment = max(Alignment, RetAlign);
   if (AI.Kind == AllocationInfo::AllocationKind::ALIGNED_ALLOC) {
 Optional AlignmentAPI =
 getAPInt(A, *this, *AI.CB->getArgOperand(0));


Index: llvm/test/Transforms/Attributor/heap_to_stack.ll
===
--- llvm/test/Transforms/Attributor/heap_to_stack.ll
+++ llvm/test/Transforms/Attributor/heap_to_stack.ll
@@ -34,7 +34,7 @@
 ; ISOPM-LABEL: define {{[^@]+}}@h2s_value_simplify_interaction
 ; ISOPM-SAME: (i1 [[C:%.*]], i8* nocapture nofree readnone [[A:%.*]]) {
 ; ISOPM-NEXT:  entry:
-; ISOPM-NEXT:[[M:%.*]] = tail call noalias i8* @malloc(

[PATCH] D115888: [Attributor][Fix] Add alignment return attribute to HeapToStack

2021-12-17 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert accepted this revision.
jdoerfert added a comment.

LG, don't forget to update the commit message.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115888

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


[PATCH] D114995: clang-tidy: improve the 'modernize-use-default-member-init'

2021-12-17 Thread Oleg Smolsky via Phabricator via cfe-commits
oleg.smolsky updated this revision to Diff 395190.
oleg.smolsky added a comment.

Added a "two constructors" test case along with the support for that.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114995

Files:
  clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
  
clang-tools-extra/test/clang-tidy/checkers/modernize-use-default-member-init.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/modernize-use-default-member-init.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/modernize-use-default-member-init.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/modernize-use-default-member-init.cpp
@@ -45,6 +45,42 @@
   // CHECK-FIXES: int j{1};
 };
 
+struct PositiveNotDefaultInt {
+  PositiveNotDefaultInt(int) : i(7) {}
+  // CHECK-FIXES: PositiveNotDefaultInt(int)  {}
+  int i;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use default member initializer for 'i'
+  // CHECK-FIXES: int i{7};
+};
+
+// We cannot reconcile these initializers.
+struct TwoConstructors {
+TwoConstructors(int) : i(7) {}
+TwoConstructors(int, int) : i(8) {}
+int i;
+};
+
+struct PositiveNotDefaultOOLInt {
+  PositiveNotDefaultOOLInt(int);
+  int i;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use default member initializer for 'i'
+  // CHECK-FIXES: int i{7};
+};
+
+PositiveNotDefaultOOLInt::PositiveNotDefaultOOLInt(int) : i(7) {}
+// CHECK-FIXES: PositiveNotDefaultOOLInt::PositiveNotDefaultOOLInt(int)  {}
+
+struct PositiveNotDefaultOOLInt2 {
+  PositiveNotDefaultOOLInt2(int, int);
+  int i;
+  // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use default member initializer for 'i'
+  // CHECK-FIXES: int i{7};
+  int j;
+};
+
+PositiveNotDefaultOOLInt2::PositiveNotDefaultOOLInt2(int, int arg) : i(7), j(arg) {}
+// CHECK-FIXES: PositiveNotDefaultOOLInt2::PositiveNotDefaultOOLInt2(int, int arg) :  j(arg) {}
+
 struct PositiveUnaryMinusInt {
   PositiveUnaryMinusInt() : j(-1) {}
   // CHECK-FIXES: PositiveUnaryMinusInt()  {}
@@ -234,12 +270,6 @@
   int i : 5;
 };
 
-struct NegativeNotDefaultInt
-{
-  NegativeNotDefaultInt(int) : i(7) {}
-  int i;
-};
-
 struct NegativeDefaultArg
 {
   NegativeDefaultArg(int i = 4) : i(i) {}
Index: clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
===
--- clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
+++ clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp
@@ -1,3 +1,4 @@
+
 //===--- UseDefaultMemberInitCheck.cpp - clang-tidy===//
 //
 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
@@ -212,17 +213,14 @@
 InitBase);
 
   Finder->addMatcher(
-  cxxConstructorDecl(
-  isDefaultConstructor(),
-  forEachConstructorInitializer(
-  cxxCtorInitializer(
-  forField(unless(anyOf(getLangOpts().CPlusPlus20
-? unless(anything())
-: isBitField(),
-hasInClassInitializer(anything()),
-hasParent(recordDecl(isUnion()),
-  withInitializer(Init))
-  .bind("default"))),
+  cxxConstructorDecl(forEachConstructorInitializer(
+  cxxCtorInitializer(
+  forField(unless(anyOf(
+  getLangOpts().CPlusPlus20 ? unless(anything()) : isBitField(),
+  hasInClassInitializer(anything()),
+  hasParent(recordDecl(isUnion()),
+  withInitializer(Init))
+  .bind("default"))),
   this);
 
   Finder->addMatcher(
@@ -248,6 +246,13 @@
 const MatchFinder::MatchResult &Result, const CXXCtorInitializer *Init) {
   const FieldDecl *Field = Init->getAnyMember();
 
+  // Check whether we have multiple hand-written constructors and bomb out, as
+  // it is hard to reconcile their sets of member initializers.
+  auto ClassDecl = dyn_cast(Field->getParent());
+  if (std::count_if(ClassDecl->ctors().begin(), ClassDecl->ctors().end(),
+[](const auto Ctor) { return !Ctor->isCopyOrMoveConstructor(); }) > 1)
+return;
+
   SourceLocation StartLoc = Field->getBeginLoc();
   if (StartLoc.isMacroID() && IgnoreMacros)
 return;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D114995: clang-tidy: improve the 'modernize-use-default-member-init'

2021-12-17 Thread Oleg Smolsky via Phabricator via cfe-commits
oleg.smolsky added a comment.

In D114995#3198033 , @aaron.ballman 
wrote:

> In D114995#3183240 , 
> @malcolm.parsons wrote:
>
>> In D114995#3180475 , 
>> @aaron.ballman wrote:
>>
>>> was there a reason we didn't cover that case originally or was it an 
>>> oversight/left for future work?
>>
>> It was left for future work - by only considering the initializer list of 
>> the default constructor, clang-tidy did not have to work out what to do when 
>> the constructors don't agree on what value the member init should have.
>
> Thank you for verifying! @oleg.smolsky -- this would be a very useful test 
> case to add, btw.

Yep, done.

PLAL


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D114995

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


[PATCH] D115967: [clang-format][NFC] Handle wrapping after => in mustBreakBefore()

2021-12-17 Thread Owen Pan via Phabricator via cfe-commits
owenpan created this revision.
owenpan added reviewers: MyDeveloperDay, curdeius, HazardyKnusperkeks, 
peterstys.
owenpan added a project: clang-format.
owenpan requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Move the handling of brace wrapping after => from unwrapped line parser to 
token annotator and clean up the parser.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D115967

Files:
  clang/lib/Format/TokenAnnotator.cpp
  clang/lib/Format/UnwrappedLineParser.cpp


Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -1638,19 +1638,8 @@
   break;
 }
 case tok::equal:
-  // Fat arrows (=>) have tok::TokenKind tok::equal but TokenType
-  // TT_FatArrow. They always start an expression or a child block if
-  // followed by a curly brace.
   if (FormatTok->is(TT_FatArrow)) {
-nextToken();
-if (FormatTok->is(tok::l_brace)) {
-  // C# may break after => if the next character is a newline.
-  if (Style.isCSharp() && Style.BraceWrapping.AfterFunction == true) {
-// calling `addUnwrappedLine()` here causes odd parsing errors.
-FormatTok->MustBreakBefore = true;
-  }
-  parseChildBlock();
-}
+tryToParseCSharpLambda();
 break;
   }
 
@@ -1726,7 +1715,7 @@
   // Try to parse the property accessor:
   // 
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties
   Tokens->setPosition(StoredPosition);
-  if (!IsTrivialPropertyAccessor && Style.BraceWrapping.AfterFunction == true)
+  if (!IsTrivialPropertyAccessor && Style.BraceWrapping.AfterFunction)
 addUnwrappedLine();
   nextToken();
   do {
@@ -1942,17 +1931,13 @@
 }
 
 bool UnwrappedLineParser::tryToParseCSharpLambda() {
-  // Fat arrows (=>) have tok::TokenKind tok::equal but TokenType
-  // TT_FatArrow. They always start an expression or a child block if
-  // followed by a curly brace.
+  assert(FormatTok->is(TT_FatArrow));
+  // Fat arrows (=>) have tok::TokenKind tok::equal but TokenType TT_FatArrow.
+  // They always start an expression or a child block if followed by a curly
+  // brace.
   nextToken();
   if (FormatTok->isNot(tok::l_brace))
 return false;
-  // C# may break after => if the next character is a newline.
-  if (Style.BraceWrapping.AfterFunction) {
-// calling `addUnwrappedLine()` here causes odd parsing errors.
-FormatTok->MustBreakBefore = true;
-  }
   parseChildBlock();
   return true;
 }
@@ -1965,24 +1950,17 @@
   // FIXME: Once we have an expression parser in the UnwrappedLineParser,
   // replace this by using parseAssignmentExpression() inside.
   do {
-if (Style.isCSharp() && FormatTok->is(TT_FatArrow))
-  if (tryToParseCSharpLambda())
-continue;
+if (Style.isCSharp() && FormatTok->is(TT_FatArrow) &&
+tryToParseCSharpLambda())
+  continue;
 if (Style.Language == FormatStyle::LK_JavaScript) {
   if (FormatTok->is(Keywords.kw_function) ||
   FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function)) {
 tryToParseJSFunction();
 continue;
   }
-  if (FormatTok->is(TT_FatArrow)) {
-nextToken();
-// Fat arrows can be followed by simple expressions or by child blocks
-// in curly braces.
-if (FormatTok->is(tok::l_brace)) {
-  parseChildBlock();
-  continue;
-}
-  }
+  if (FormatTok->is(TT_FatArrow) && tryToParseCSharpLambda())
+continue;
   if (FormatTok->is(tok::l_brace)) {
 // Could be a method inside of a braced list `{a() { return 1; }}`.
 if (tryToParseBracedList())
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -3717,6 +3717,9 @@
 return true;
 
   if (Style.isCSharp()) {
+if (Left.is(TT_FatArrow) && Right.is(tok::l_brace) &&
+Style.BraceWrapping.AfterFunction)
+  return true;
 if (Right.is(TT_CSharpNamedArgumentColon) ||
 Left.is(TT_CSharpNamedArgumentColon))
   return false;


Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -1638,19 +1638,8 @@
   break;
 }
 case tok::equal:
-  // Fat arrows (=>) have tok::TokenKind tok::equal but TokenType
-  // TT_FatArrow. They always start an expression or a child block if
-  // followed by a curly brace.
   if (FormatTok->is(TT_FatArrow)) {
-nextToken();
-if (FormatTok->is(tok::l_brace)) {
-  // C# may break after => if the next

[PATCH] D115967: [clang-format][NFC] Handle wrapping after => in mustBreakBefore()

2021-12-17 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added inline comments.



Comment at: clang/lib/Format/UnwrappedLineParser.cpp:1641
 case tok::equal:
-  // Fat arrows (=>) have tok::TokenKind tok::equal but TokenType
-  // TT_FatArrow. They always start an expression or a child block if
-  // followed by a curly brace.
   if (FormatTok->is(TT_FatArrow)) {
+tryToParseCSharpLambda();

Should we add the isCSharp check?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115967

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


[PATCH] D114622: [clang-tidy][analyzer] Fix false-positive in IdenticalExprChecker and misc-redundant-expression

2021-12-17 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added a comment.

These checks are almost 2000 lines of code each and it looks like all they do 
is figure out if two statements are the same and we have a very flexible 
reusable solution for this sort of stuff - `CloneDetector`, but none of them 
use it. Your patch demonstrates that they all have the same bugs that need to 
be fixed in each of them separately, so reusability seems really valuable. If I 
was to work on these checks, the first thing I'd try would be to throw out 
their machines and plug in a reusable solution.


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

https://reviews.llvm.org/D114622

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


[PATCH] D115561: [Clang][OpenMP] Add the support for atomic compare in parser

2021-12-17 Thread Shilei Tian via Phabricator via cfe-commits
tianshilei1992 updated this revision to Diff 395207.
tianshilei1992 added a comment.
Herald added a project: Flang.

update one test case and flang fix


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115561

Files:
  clang/include/clang/AST/OpenMPClause.h
  clang/include/clang/AST/RecursiveASTVisitor.h
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/OpenMPClause.cpp
  clang/lib/AST/StmtProfile.cpp
  clang/lib/Basic/OpenMPKinds.cpp
  clang/lib/CodeGen/CGStmtOpenMP.cpp
  clang/lib/Parse/ParseOpenMP.cpp
  clang/lib/Sema/SemaOpenMP.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/OpenMP/atomic_ast_print.cpp
  clang/test/OpenMP/atomic_messages.cpp
  clang/tools/libclang/CIndex.cpp
  flang/lib/Semantics/check-omp-structure.cpp
  llvm/include/llvm/Frontend/OpenMP/OMP.td

Index: llvm/include/llvm/Frontend/OpenMP/OMP.td
===
--- llvm/include/llvm/Frontend/OpenMP/OMP.td
+++ llvm/include/llvm/Frontend/OpenMP/OMP.td
@@ -180,6 +180,7 @@
 def OMPC_Write : Clause<"write"> { let clangClass = "OMPWriteClause"; }
 def OMPC_Update : Clause<"update"> { let clangClass = "OMPUpdateClause"; }
 def OMPC_Capture : Clause<"capture"> { let clangClass = "OMPCaptureClause"; }
+def OMPC_Compare : Clause<"compare"> { let clangClass = "OMPCompareClause"; }
 def OMPC_SeqCst : Clause<"seq_cst"> { let clangClass = "OMPSeqCstClause"; }
 def OMPC_AcqRel : Clause<"acq_rel"> { let clangClass = "OMPAcqRelClause"; }
 def OMPC_Acquire : Clause<"acquire"> { let clangClass = "OMPAcquireClause"; }
@@ -536,6 +537,7 @@
 VersionedClause,
 VersionedClause,
 VersionedClause,
+VersionedClause
   ];
   let allowedOnceClauses = [
 VersionedClause,
Index: flang/lib/Semantics/check-omp-structure.cpp
===
--- flang/lib/Semantics/check-omp-structure.cpp
+++ flang/lib/Semantics/check-omp-structure.cpp
@@ -1482,6 +1482,7 @@
 CHECK_SIMPLE_CLAUSE(MemoryOrder, OMPC_memory_order)
 CHECK_SIMPLE_CLAUSE(Bind, OMPC_bind)
 CHECK_SIMPLE_CLAUSE(Align, OMPC_align)
+CHECK_SIMPLE_CLAUSE(Compare, OMPC_compare)
 
 CHECK_REQ_SCALAR_INT_CLAUSE(Grainsize, OMPC_grainsize)
 CHECK_REQ_SCALAR_INT_CLAUSE(NumTasks, OMPC_num_tasks)
Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -2273,6 +2273,8 @@
 
 void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
 
+void OMPClauseEnqueue::VisitOMPCompareClause(const OMPCompareClause *) {}
+
 void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
 
 void OMPClauseEnqueue::VisitOMPAcqRelClause(const OMPAcqRelClause *) {}
Index: clang/test/OpenMP/atomic_messages.cpp
===
--- clang/test/OpenMP/atomic_messages.cpp
+++ clang/test/OpenMP/atomic_messages.cpp
@@ -896,19 +896,19 @@
 template 
 T mixed() {
   T a, b = T();
-// expected-error@+2 2 {{directive '#pragma omp atomic' cannot contain more than one 'read', 'write', 'update' or 'capture' clause}}
+// expected-error@+2 2 {{directive '#pragma omp atomic' cannot contain more than one 'read', 'write', 'update', 'capture', or 'compare' clause}}
 // expected-note@+1 2 {{'read' clause used here}}
 #pragma omp atomic read write
   a = b;
-// expected-error@+2 2 {{directive '#pragma omp atomic' cannot contain more than one 'read', 'write', 'update' or 'capture' clause}}
+// expected-error@+2 2 {{directive '#pragma omp atomic' cannot contain more than one 'read', 'write', 'update', 'capture', or 'compare' clause}}
 // expected-note@+1 2 {{'write' clause used here}}
 #pragma omp atomic write read
   a = b;
-// expected-error@+2 2 {{directive '#pragma omp atomic' cannot contain more than one 'read', 'write', 'update' or 'capture' clause}}
+// expected-error@+2 2 {{directive '#pragma omp atomic' cannot contain more than one 'read', 'write', 'update', 'capture', or 'compare' clause}}
 // expected-note@+1 2 {{'update' clause used here}}
 #pragma omp atomic update read
   a += b;
-// expected-error@+2 2 {{directive '#pragma omp atomic' cannot contain more than one 'read', 'write', 'update' or 'capture' clause}}
+// expected-error@+2 2 {{directive '#pragma omp atomic' cannot contain more than one 'read', 'write', 'update', 'capture', or 'compare' clause}}
 // expected-note@+1 2 {{'capture' clause used here}}
 #pragma omp atomic capture read
   a = ++b;
@@ -917,19 +917,19 @@
 
 int mixed() {
   int a, b = 0;
-// expected-error@+2 {{directive '#pragma omp atomic' cannot contain more than one 'read', 'write', 'update' or 'capture' clause}}
+// expected-error@+2 {{directive '#pragma omp atomic' cannot contain more than one 'read', 'wr

[PATCH] D115561: [Clang][OpenMP] Add the support for atomic compare in parser

2021-12-17 Thread Shilei Tian via Phabricator via cfe-commits
tianshilei1992 updated this revision to Diff 395208.
tianshilei1992 added a comment.

remove unexpected change


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115561

Files:
  clang/include/clang/AST/OpenMPClause.h
  clang/include/clang/AST/RecursiveASTVisitor.h
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/OpenMPClause.cpp
  clang/lib/AST/StmtProfile.cpp
  clang/lib/Basic/OpenMPKinds.cpp
  clang/lib/CodeGen/CGStmtOpenMP.cpp
  clang/lib/Parse/ParseOpenMP.cpp
  clang/lib/Sema/SemaOpenMP.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/OpenMP/atomic_messages.cpp
  clang/tools/libclang/CIndex.cpp
  flang/lib/Semantics/check-omp-structure.cpp
  llvm/include/llvm/Frontend/OpenMP/OMP.td

Index: llvm/include/llvm/Frontend/OpenMP/OMP.td
===
--- llvm/include/llvm/Frontend/OpenMP/OMP.td
+++ llvm/include/llvm/Frontend/OpenMP/OMP.td
@@ -180,6 +180,7 @@
 def OMPC_Write : Clause<"write"> { let clangClass = "OMPWriteClause"; }
 def OMPC_Update : Clause<"update"> { let clangClass = "OMPUpdateClause"; }
 def OMPC_Capture : Clause<"capture"> { let clangClass = "OMPCaptureClause"; }
+def OMPC_Compare : Clause<"compare"> { let clangClass = "OMPCompareClause"; }
 def OMPC_SeqCst : Clause<"seq_cst"> { let clangClass = "OMPSeqCstClause"; }
 def OMPC_AcqRel : Clause<"acq_rel"> { let clangClass = "OMPAcqRelClause"; }
 def OMPC_Acquire : Clause<"acquire"> { let clangClass = "OMPAcquireClause"; }
@@ -536,6 +537,7 @@
 VersionedClause,
 VersionedClause,
 VersionedClause,
+VersionedClause
   ];
   let allowedOnceClauses = [
 VersionedClause,
Index: flang/lib/Semantics/check-omp-structure.cpp
===
--- flang/lib/Semantics/check-omp-structure.cpp
+++ flang/lib/Semantics/check-omp-structure.cpp
@@ -1482,6 +1482,7 @@
 CHECK_SIMPLE_CLAUSE(MemoryOrder, OMPC_memory_order)
 CHECK_SIMPLE_CLAUSE(Bind, OMPC_bind)
 CHECK_SIMPLE_CLAUSE(Align, OMPC_align)
+CHECK_SIMPLE_CLAUSE(Compare, OMPC_compare)
 
 CHECK_REQ_SCALAR_INT_CLAUSE(Grainsize, OMPC_grainsize)
 CHECK_REQ_SCALAR_INT_CLAUSE(NumTasks, OMPC_num_tasks)
Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -2273,6 +2273,8 @@
 
 void OMPClauseEnqueue::VisitOMPCaptureClause(const OMPCaptureClause *) {}
 
+void OMPClauseEnqueue::VisitOMPCompareClause(const OMPCompareClause *) {}
+
 void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
 
 void OMPClauseEnqueue::VisitOMPAcqRelClause(const OMPAcqRelClause *) {}
Index: clang/test/OpenMP/atomic_messages.cpp
===
--- clang/test/OpenMP/atomic_messages.cpp
+++ clang/test/OpenMP/atomic_messages.cpp
@@ -896,19 +896,19 @@
 template 
 T mixed() {
   T a, b = T();
-// expected-error@+2 2 {{directive '#pragma omp atomic' cannot contain more than one 'read', 'write', 'update' or 'capture' clause}}
+// expected-error@+2 2 {{directive '#pragma omp atomic' cannot contain more than one 'read', 'write', 'update', 'capture', or 'compare' clause}}
 // expected-note@+1 2 {{'read' clause used here}}
 #pragma omp atomic read write
   a = b;
-// expected-error@+2 2 {{directive '#pragma omp atomic' cannot contain more than one 'read', 'write', 'update' or 'capture' clause}}
+// expected-error@+2 2 {{directive '#pragma omp atomic' cannot contain more than one 'read', 'write', 'update', 'capture', or 'compare' clause}}
 // expected-note@+1 2 {{'write' clause used here}}
 #pragma omp atomic write read
   a = b;
-// expected-error@+2 2 {{directive '#pragma omp atomic' cannot contain more than one 'read', 'write', 'update' or 'capture' clause}}
+// expected-error@+2 2 {{directive '#pragma omp atomic' cannot contain more than one 'read', 'write', 'update', 'capture', or 'compare' clause}}
 // expected-note@+1 2 {{'update' clause used here}}
 #pragma omp atomic update read
   a += b;
-// expected-error@+2 2 {{directive '#pragma omp atomic' cannot contain more than one 'read', 'write', 'update' or 'capture' clause}}
+// expected-error@+2 2 {{directive '#pragma omp atomic' cannot contain more than one 'read', 'write', 'update', 'capture', or 'compare' clause}}
 // expected-note@+1 2 {{'capture' clause used here}}
 #pragma omp atomic capture read
   a = ++b;
@@ -917,19 +917,19 @@
 
 int mixed() {
   int a, b = 0;
-// expected-error@+2 {{directive '#pragma omp atomic' cannot contain more than one 'read', 'write', 'update' or 'capture' clause}}
+// expected-error@+2 {{directive '#pragma omp atomic' cannot contain more than one 'read', 'write', 'update', 'capture', or 'compare' clause}}
 // expected-note@+1 {{'read' cla

[PATCH] D115932: [Analyzer] Create and handle SymbolCast for pointer to integral conversion

2021-12-17 Thread Artem Dergachev via Phabricator via cfe-commits
NoQ added a comment.

Oh nice, it's great to see these things moving.

I have a couple observations for your specific approach:

(1) Sounds like you're introducing a symbol `(long p)` that represents the 
exact same value as (and is used interchangeably with) `&SymRegion{$p} (as 
long)`. Ambiguity is generally bad because it means a lot of duplication and 
missed cornercases.

(2) I think you can run into the same problem with a non-symbolic region which 
you can't unwrap the same way because there's no symbol to cast:

  void foo() {
int p;
12 - (long)&p;
  }

Maybe we should stick to your approach as strictly superior and eliminate 
`LocAsInteger` entirely? In this case the example (2) will work through 
introducing a new custom symbol `SymbolRegionAddress` which would look like 
`$addr`. Then add a hard canonicalization rule `SymRegion{$addr} = R` 
(symregions around address symbols are ill-formed). Ideally we'd also have to 
unwrap offsets, i.e. `$addr{Element{x, char, $i}} = $addr + $i`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D115932

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


  1   2   >