[clang] 74e4f77 - [Lex] Simplify and cleanup the updateConsecutiveMacroArgTokens implementation.

2022-10-07 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2022-10-07T09:16:08+02:00
New Revision: 74e4f778cf16cbf7163b5c6de6027a43f5e9169f

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

LOG: [Lex] Simplify and cleanup the updateConsecutiveMacroArgTokens 
implementation.

The code falls back to the pre-2011 partition-file-id solution (see for
[details](https://reviews.llvm.org/D20401#3823476)).

This patch simplifies/rewrites the code based on the partition-based-on-file-id
idea. The new implementation is optimized by reducing the number of
calling getFileID (~40% drop).

Despite the huge drop of getFileID, this is a marignal improvment on
speed (becase the number of calling non-cached getFileID is roughly
the same). It removes the evaluation-order performance gap between 
gcc-built-clang
and clang-built-clang.

SemaExpr.cpp:
- before: 315063 SLocEntries, FileID scans: 388230 linear, 1393437 binary. 
458893 cache hits, 672299 getFileID calls
- after:  313494 SLocEntries, FileID scans: 397525 linear, 1451890 binary, 
176714 cache hits, 397144 getFileID calls

FindTarget.cpp:
- before: 279984 SLocEntries, FileID scans: 361926 linear, 1275930 binary, 
436072 cache hits, 632150 getFileID calls
- after:  278426 SLocEntries, FileID scans: 371279 linear, 1333963 binary, 
153705 cache hits, 356814 getFileID calls

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

Added: 


Modified: 
clang/lib/Lex/TokenLexer.cpp

Removed: 




diff  --git a/clang/lib/Lex/TokenLexer.cpp b/clang/lib/Lex/TokenLexer.cpp
index efda6d0046fa1..ecbc764a61ac2 100644
--- a/clang/lib/Lex/TokenLexer.cpp
+++ b/clang/lib/Lex/TokenLexer.cpp
@@ -25,6 +25,7 @@
 #include "clang/Lex/Token.h"
 #include "clang/Lex/VariadicMacroSupport.h"
 #include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/iterator_range.h"
@@ -987,62 +988,57 @@ static void updateConsecutiveMacroArgTokens(SourceManager 
&SM,
 SourceLocation InstLoc,
 Token *&begin_tokens,
 Token * end_tokens) {
-  assert(begin_tokens < end_tokens);
-
-  SourceLocation FirstLoc = begin_tokens->getLocation();
-  SourceLocation CurLoc = FirstLoc;
-
-  // Compare the source location offset of tokens and group together tokens 
that
-  // are close, even if their locations point to 
diff erent FileIDs. e.g.
-  //
-  //  |bar|  foo | cake   |  (3 tokens from 3 consecutive FileIDs)
-  //  ^^
-  //  |bar   foo   cake| (one SLocEntry chunk for all tokens)
-  //
-  // we can perform this "merge" since the token's spelling location depends
-  // on the relative offset.
-
-  Token *NextTok = begin_tokens + 1;
-  for (; NextTok < end_tokens; ++NextTok) {
-SourceLocation NextLoc = NextTok->getLocation();
-if (CurLoc.isFileID() != NextLoc.isFileID())
-  break; // Token from 
diff erent kind of FileID.
-
-SourceLocation::IntTy RelOffs;
-if (!SM.isInSameSLocAddrSpace(CurLoc, NextLoc, &RelOffs))
-  break; // Token from 
diff erent local/loaded location.
-// Check that token is not before the previous token or more than 50
-// "characters" away.
-if (RelOffs < 0 || RelOffs > 50)
-  break;
-
-if (CurLoc.isMacroID() && !SM.isWrittenInSameFile(CurLoc, NextLoc))
-  break; // Token from a 
diff erent macro.
-
-CurLoc = NextLoc;
+  assert(begin_tokens + 1 < end_tokens);
+  SourceLocation BeginLoc = begin_tokens->getLocation();
+  llvm::MutableArrayRef All(begin_tokens, end_tokens);
+  llvm::MutableArrayRef Partition;
+
+  // Partition the tokens by their FileID.
+  // This is a hot function, and calling getFileID can be expensive, the
+  // implementation is optimized by reducing the number of getFileID.
+  if (BeginLoc.isFileID()) {
+// Consecutive tokens not written in macros must be from the same file.
+// (Neither #include nor eof can occur inside a macro argument.)
+Partition = All.take_while([&](const Token &T) {
+  return T.getLocation().isFileID();
+});
+  } else {
+// Call getFileID once to calculate the bounds, and use the cheaper
+// sourcelocation-against-bounds comparison.
+FileID BeginFID = SM.getFileID(BeginLoc);
+SourceLocation Limit =
+SM.getComposedLoc(BeginFID, SM.getFileIDSize(BeginFID));
+Partition = All.take_while([&](const Token &T) {
+  return T.getLocation() >= BeginLoc && T.getLocation() < Limit;
+});
   }
+  assert(!Partition.empty());
 
   // For the consecutive tokens, find the length of the SLocEntry to contain
   // all of them.
-  Token &LastConsecutiveTok = *(NextTok-1);
-  SourceLocation::IntTy LastRelOffs = 0;
-  SM.isIn

[PATCH] D134942: [Lex] Simplify and cleanup the updateConsecutiveMacroArgTokens implementation.

2022-10-07 Thread Haojian Wu via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
hokein marked an inline comment as done.
Closed by commit rG74e4f778cf16: [Lex] Simplify and cleanup the 
updateConsecutiveMacroArgTokens implementation. (authored by hokein).

Changed prior to commit:
  https://reviews.llvm.org/D134942?vs=465321&id=465983#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134942

Files:
  clang/lib/Lex/TokenLexer.cpp

Index: clang/lib/Lex/TokenLexer.cpp
===
--- clang/lib/Lex/TokenLexer.cpp
+++ clang/lib/Lex/TokenLexer.cpp
@@ -25,6 +25,7 @@
 #include "clang/Lex/Token.h"
 #include "clang/Lex/VariadicMacroSupport.h"
 #include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/iterator_range.h"
@@ -987,62 +988,57 @@
 SourceLocation InstLoc,
 Token *&begin_tokens,
 Token * end_tokens) {
-  assert(begin_tokens < end_tokens);
-
-  SourceLocation FirstLoc = begin_tokens->getLocation();
-  SourceLocation CurLoc = FirstLoc;
-
-  // Compare the source location offset of tokens and group together tokens that
-  // are close, even if their locations point to different FileIDs. e.g.
-  //
-  //  |bar|  foo | cake   |  (3 tokens from 3 consecutive FileIDs)
-  //  ^^
-  //  |bar   foo   cake| (one SLocEntry chunk for all tokens)
-  //
-  // we can perform this "merge" since the token's spelling location depends
-  // on the relative offset.
-
-  Token *NextTok = begin_tokens + 1;
-  for (; NextTok < end_tokens; ++NextTok) {
-SourceLocation NextLoc = NextTok->getLocation();
-if (CurLoc.isFileID() != NextLoc.isFileID())
-  break; // Token from different kind of FileID.
-
-SourceLocation::IntTy RelOffs;
-if (!SM.isInSameSLocAddrSpace(CurLoc, NextLoc, &RelOffs))
-  break; // Token from different local/loaded location.
-// Check that token is not before the previous token or more than 50
-// "characters" away.
-if (RelOffs < 0 || RelOffs > 50)
-  break;
-
-if (CurLoc.isMacroID() && !SM.isWrittenInSameFile(CurLoc, NextLoc))
-  break; // Token from a different macro.
-
-CurLoc = NextLoc;
+  assert(begin_tokens + 1 < end_tokens);
+  SourceLocation BeginLoc = begin_tokens->getLocation();
+  llvm::MutableArrayRef All(begin_tokens, end_tokens);
+  llvm::MutableArrayRef Partition;
+
+  // Partition the tokens by their FileID.
+  // This is a hot function, and calling getFileID can be expensive, the
+  // implementation is optimized by reducing the number of getFileID.
+  if (BeginLoc.isFileID()) {
+// Consecutive tokens not written in macros must be from the same file.
+// (Neither #include nor eof can occur inside a macro argument.)
+Partition = All.take_while([&](const Token &T) {
+  return T.getLocation().isFileID();
+});
+  } else {
+// Call getFileID once to calculate the bounds, and use the cheaper
+// sourcelocation-against-bounds comparison.
+FileID BeginFID = SM.getFileID(BeginLoc);
+SourceLocation Limit =
+SM.getComposedLoc(BeginFID, SM.getFileIDSize(BeginFID));
+Partition = All.take_while([&](const Token &T) {
+  return T.getLocation() >= BeginLoc && T.getLocation() < Limit;
+});
   }
+  assert(!Partition.empty());
 
   // For the consecutive tokens, find the length of the SLocEntry to contain
   // all of them.
-  Token &LastConsecutiveTok = *(NextTok-1);
-  SourceLocation::IntTy LastRelOffs = 0;
-  SM.isInSameSLocAddrSpace(FirstLoc, LastConsecutiveTok.getLocation(),
-   &LastRelOffs);
   SourceLocation::UIntTy FullLength =
-  LastRelOffs + LastConsecutiveTok.getLength();
-
+  Partition.back().getEndLoc().getRawEncoding() -
+  Partition.front().getLocation().getRawEncoding();
   // Create a macro expansion SLocEntry that will "contain" all of the tokens.
   SourceLocation Expansion =
-  SM.createMacroArgExpansionLoc(FirstLoc, InstLoc,FullLength);
-
+  SM.createMacroArgExpansionLoc(BeginLoc, InstLoc, FullLength);
+
+#ifdef EXPENSIVE_CHECKS
+  assert(llvm::all_of(Partition.drop_front(),
+  [&SM, ID = SM.getFileID(Partition.front().getLocation())](
+  const Token &T) {
+return ID == SM.getFileID(T.getLocation());
+  }) &&
+ "Must have the same FIleID!");
+#endif
   // Change the location of the tokens from the spelling location to the new
   // expanded location.
-  for (; begin_tokens < NextTok; ++begin_tokens) {
-Token &Tok = *begin_tokens;
-SourceLocation::IntTy RelOffs = 0;
-SM.isInSameSLocAddrSpace(Firs

[PATCH] D135132: [SourceManager] Improve getFileIDLocal.

2022-10-07 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 465988.
hokein marked an inline comment as done.
hokein added a comment.

update


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135132

Files:
  clang/lib/Basic/SourceManager.cpp


Index: clang/lib/Basic/SourceManager.cpp
===
--- clang/lib/Basic/SourceManager.cpp
+++ clang/lib/Basic/SourceManager.cpp
@@ -793,24 +793,28 @@
 
   // See if this is near the file point - worst case we start scanning from the
   // most newly created FileID.
-  const SrcMgr::SLocEntry *I;
 
-  if (LastFileIDLookup.ID < 0 ||
-  LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
-// Neither loc prunes our search.
-I = LocalSLocEntryTable.end();
-  } else {
-// Perhaps it is near the file point.
-I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID;
+  // LessIndex - This is the lower bound of the range that we're searching.
+  // We know that the offset corresponding to the FileID is is less than
+  // SLocOffset.
+  unsigned LessIndex = 0;
+  // upper bound of the search range.
+  unsigned GreaterIndex = LocalSLocEntryTable.size();
+  if (LastFileIDLookup.ID >= 0) {
+// Use the LastFileIDLookup to prune the search space.
+if (LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset)
+  LessIndex = LastFileIDLookup.ID;
+else
+  GreaterIndex = LastFileIDLookup.ID;
   }
 
-  // Find the FileID that contains this.  "I" is an iterator that points to a
-  // FileID whose offset is known to be larger than SLocOffset.
+  // Find the FileID that contains this.
   unsigned NumProbes = 0;
   while (true) {
---I;
-if (I->getOffset() <= SLocOffset) {
-  FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin()));
+--GreaterIndex;
+assert(GreaterIndex < LocalSLocEntryTable.size());
+if (LocalSLocEntryTable[GreaterIndex].getOffset() <= SLocOffset) {
+  FileID Res = FileID::get(int(GreaterIndex));
   // Remember it.  We have good locality across FileID lookups.
   LastFileIDLookup = Res;
   NumLinearScans += NumProbes+1;
@@ -820,13 +824,6 @@
   break;
   }
 
-  // Convert "I" back into an index.  We know that it is an entry whose index 
is
-  // larger than the offset we are looking for.
-  unsigned GreaterIndex = I - LocalSLocEntryTable.begin();
-  // LessIndex - This is the lower bound of the range that we're searching.
-  // We know that the offset corresponding to the FileID is is less than
-  // SLocOffset.
-  unsigned LessIndex = 0;
   NumProbes = 0;
   while (true) {
 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;


Index: clang/lib/Basic/SourceManager.cpp
===
--- clang/lib/Basic/SourceManager.cpp
+++ clang/lib/Basic/SourceManager.cpp
@@ -793,24 +793,28 @@
 
   // See if this is near the file point - worst case we start scanning from the
   // most newly created FileID.
-  const SrcMgr::SLocEntry *I;
 
-  if (LastFileIDLookup.ID < 0 ||
-  LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
-// Neither loc prunes our search.
-I = LocalSLocEntryTable.end();
-  } else {
-// Perhaps it is near the file point.
-I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID;
+  // LessIndex - This is the lower bound of the range that we're searching.
+  // We know that the offset corresponding to the FileID is is less than
+  // SLocOffset.
+  unsigned LessIndex = 0;
+  // upper bound of the search range.
+  unsigned GreaterIndex = LocalSLocEntryTable.size();
+  if (LastFileIDLookup.ID >= 0) {
+// Use the LastFileIDLookup to prune the search space.
+if (LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset)
+  LessIndex = LastFileIDLookup.ID;
+else
+  GreaterIndex = LastFileIDLookup.ID;
   }
 
-  // Find the FileID that contains this.  "I" is an iterator that points to a
-  // FileID whose offset is known to be larger than SLocOffset.
+  // Find the FileID that contains this.
   unsigned NumProbes = 0;
   while (true) {
---I;
-if (I->getOffset() <= SLocOffset) {
-  FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin()));
+--GreaterIndex;
+assert(GreaterIndex < LocalSLocEntryTable.size());
+if (LocalSLocEntryTable[GreaterIndex].getOffset() <= SLocOffset) {
+  FileID Res = FileID::get(int(GreaterIndex));
   // Remember it.  We have good locality across FileID lookups.
   LastFileIDLookup = Res;
   NumLinearScans += NumProbes+1;
@@ -820,13 +824,6 @@
   break;
   }
 
-  // Convert "I" back into an index.  We know that it is an entry whose index is
-  // larger than the offset we are looking for.
-  unsigned GreaterIndex = I - LocalSLocEntryTable.begin();
-  // LessIndex - This is the lower bound of the range that we're searching.
-  // We know that the offset corres

[PATCH] D135132: [SourceManager] Improve getFileIDLocal.

2022-10-07 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: clang/lib/Basic/SourceManager.cpp:797
-  LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
-// Neither loc prunes our search.
-I = LocalSLocEntryTable.end();

nickdesaulniers wrote:
> nickdesaulniers wrote:
> > Consider renaming this `LesserIndex` which matches with `GreaterIndex` 
> > better.
> So this comment was wrong?
This comment was true before the patch. I have updated it to match the current 
code.



Comment at: clang/lib/Basic/SourceManager.cpp:797
+  // SLocOffset.
+  unsigned LessIndex = 0;
+  // upper bound of the search range.

hokein wrote:
> nickdesaulniers wrote:
> > nickdesaulniers wrote:
> > > Consider renaming this `LesserIndex` which matches with `GreaterIndex` 
> > > better.
> > So this comment was wrong?
> This comment was true before the patch. I have updated it to match the 
> current code.
I'm not sure, it doesn't seem to be much better (I'm leaning towards keeping it 
as-is).



Comment at: clang/lib/Basic/SourceManager.cpp:807
   }
 
   // Find the FileID that contains this.  "I" is an iterator that points to a

sammccall wrote:
> Just checking: we decrement GreaterIndex without a bounds check in the loop 
> and then dereference it in the loop.
> 
> I guess this is safe because:
> - in the case where it's equal to size(), it's nonzero due to a dummy entry 
> at 0 (and unchanged in this patch)
> - in the case where the cache is used, it's also nonzero (guarded)
> 
> Maybe this is worth an assertion?
yes, exactly. added an assertion.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135132

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


[clang] a6a0d9e - [SourceManager] Improve getFileIDLocal.

2022-10-07 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2022-10-07T09:37:04+02:00
New Revision: a6a0d9ecd5d744316e699fa78a053376bb659dd1

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

LOG: [SourceManager] Improve getFileIDLocal.

Prune the search space -- If we know offset(LastFileIDLookup) < SearchOffset, we
can prune the initial binary-search range from [0, end) to [LastFileIDlookup, 
end).

It reduces the binary search scan by ~30%.

SemaExpr.cpp:   1393437 -> 1035426
FindTarget.cpp: 1275930 -> 920087

Linux kernel:
getFileIDLocal: 2.45% -> 2.15%

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

Added: 


Modified: 
clang/lib/Basic/SourceManager.cpp

Removed: 




diff  --git a/clang/lib/Basic/SourceManager.cpp 
b/clang/lib/Basic/SourceManager.cpp
index 32234b5cc73ee..f82df598ffc3f 100644
--- a/clang/lib/Basic/SourceManager.cpp
+++ b/clang/lib/Basic/SourceManager.cpp
@@ -793,24 +793,28 @@ FileID 
SourceManager::getFileIDLocal(SourceLocation::UIntTy SLocOffset) const {
 
   // See if this is near the file point - worst case we start scanning from the
   // most newly created FileID.
-  const SrcMgr::SLocEntry *I;
 
-  if (LastFileIDLookup.ID < 0 ||
-  LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
-// Neither loc prunes our search.
-I = LocalSLocEntryTable.end();
-  } else {
-// Perhaps it is near the file point.
-I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID;
+  // LessIndex - This is the lower bound of the range that we're searching.
+  // We know that the offset corresponding to the FileID is is less than
+  // SLocOffset.
+  unsigned LessIndex = 0;
+  // upper bound of the search range.
+  unsigned GreaterIndex = LocalSLocEntryTable.size();
+  if (LastFileIDLookup.ID >= 0) {
+// Use the LastFileIDLookup to prune the search space.
+if (LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset)
+  LessIndex = LastFileIDLookup.ID;
+else
+  GreaterIndex = LastFileIDLookup.ID;
   }
 
-  // Find the FileID that contains this.  "I" is an iterator that points to a
-  // FileID whose offset is known to be larger than SLocOffset.
+  // Find the FileID that contains this.
   unsigned NumProbes = 0;
   while (true) {
---I;
-if (I->getOffset() <= SLocOffset) {
-  FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin()));
+--GreaterIndex;
+assert(GreaterIndex < LocalSLocEntryTable.size());
+if (LocalSLocEntryTable[GreaterIndex].getOffset() <= SLocOffset) {
+  FileID Res = FileID::get(int(GreaterIndex));
   // Remember it.  We have good locality across FileID lookups.
   LastFileIDLookup = Res;
   NumLinearScans += NumProbes+1;
@@ -820,13 +824,6 @@ FileID 
SourceManager::getFileIDLocal(SourceLocation::UIntTy SLocOffset) const {
   break;
   }
 
-  // Convert "I" back into an index.  We know that it is an entry whose index 
is
-  // larger than the offset we are looking for.
-  unsigned GreaterIndex = I - LocalSLocEntryTable.begin();
-  // LessIndex - This is the lower bound of the range that we're searching.
-  // We know that the offset corresponding to the FileID is is less than
-  // SLocOffset.
-  unsigned LessIndex = 0;
   NumProbes = 0;
   while (true) {
 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;



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


[PATCH] D135132: [SourceManager] Improve getFileIDLocal.

2022-10-07 Thread Haojian Wu 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 rGa6a0d9ecd5d7: [SourceManager] Improve getFileIDLocal. 
(authored by hokein).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135132

Files:
  clang/lib/Basic/SourceManager.cpp


Index: clang/lib/Basic/SourceManager.cpp
===
--- clang/lib/Basic/SourceManager.cpp
+++ clang/lib/Basic/SourceManager.cpp
@@ -793,24 +793,28 @@
 
   // See if this is near the file point - worst case we start scanning from the
   // most newly created FileID.
-  const SrcMgr::SLocEntry *I;
 
-  if (LastFileIDLookup.ID < 0 ||
-  LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
-// Neither loc prunes our search.
-I = LocalSLocEntryTable.end();
-  } else {
-// Perhaps it is near the file point.
-I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID;
+  // LessIndex - This is the lower bound of the range that we're searching.
+  // We know that the offset corresponding to the FileID is is less than
+  // SLocOffset.
+  unsigned LessIndex = 0;
+  // upper bound of the search range.
+  unsigned GreaterIndex = LocalSLocEntryTable.size();
+  if (LastFileIDLookup.ID >= 0) {
+// Use the LastFileIDLookup to prune the search space.
+if (LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset)
+  LessIndex = LastFileIDLookup.ID;
+else
+  GreaterIndex = LastFileIDLookup.ID;
   }
 
-  // Find the FileID that contains this.  "I" is an iterator that points to a
-  // FileID whose offset is known to be larger than SLocOffset.
+  // Find the FileID that contains this.
   unsigned NumProbes = 0;
   while (true) {
---I;
-if (I->getOffset() <= SLocOffset) {
-  FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin()));
+--GreaterIndex;
+assert(GreaterIndex < LocalSLocEntryTable.size());
+if (LocalSLocEntryTable[GreaterIndex].getOffset() <= SLocOffset) {
+  FileID Res = FileID::get(int(GreaterIndex));
   // Remember it.  We have good locality across FileID lookups.
   LastFileIDLookup = Res;
   NumLinearScans += NumProbes+1;
@@ -820,13 +824,6 @@
   break;
   }
 
-  // Convert "I" back into an index.  We know that it is an entry whose index 
is
-  // larger than the offset we are looking for.
-  unsigned GreaterIndex = I - LocalSLocEntryTable.begin();
-  // LessIndex - This is the lower bound of the range that we're searching.
-  // We know that the offset corresponding to the FileID is is less than
-  // SLocOffset.
-  unsigned LessIndex = 0;
   NumProbes = 0;
   while (true) {
 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;


Index: clang/lib/Basic/SourceManager.cpp
===
--- clang/lib/Basic/SourceManager.cpp
+++ clang/lib/Basic/SourceManager.cpp
@@ -793,24 +793,28 @@
 
   // See if this is near the file point - worst case we start scanning from the
   // most newly created FileID.
-  const SrcMgr::SLocEntry *I;
 
-  if (LastFileIDLookup.ID < 0 ||
-  LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) {
-// Neither loc prunes our search.
-I = LocalSLocEntryTable.end();
-  } else {
-// Perhaps it is near the file point.
-I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID;
+  // LessIndex - This is the lower bound of the range that we're searching.
+  // We know that the offset corresponding to the FileID is is less than
+  // SLocOffset.
+  unsigned LessIndex = 0;
+  // upper bound of the search range.
+  unsigned GreaterIndex = LocalSLocEntryTable.size();
+  if (LastFileIDLookup.ID >= 0) {
+// Use the LastFileIDLookup to prune the search space.
+if (LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset)
+  LessIndex = LastFileIDLookup.ID;
+else
+  GreaterIndex = LastFileIDLookup.ID;
   }
 
-  // Find the FileID that contains this.  "I" is an iterator that points to a
-  // FileID whose offset is known to be larger than SLocOffset.
+  // Find the FileID that contains this.
   unsigned NumProbes = 0;
   while (true) {
---I;
-if (I->getOffset() <= SLocOffset) {
-  FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin()));
+--GreaterIndex;
+assert(GreaterIndex < LocalSLocEntryTable.size());
+if (LocalSLocEntryTable[GreaterIndex].getOffset() <= SLocOffset) {
+  FileID Res = FileID::get(int(GreaterIndex));
   // Remember it.  We have good locality across FileID lookups.
   LastFileIDLookup = Res;
   NumLinearScans += NumProbes+1;
@@ -820,13 +824,6 @@
   break;
   }
 
-  // Convert "I" back into an index.  We know that it is an entry whose index is
-  // larger than the offset we are looking for.
-  unsigned GreaterIndex = I - LocalSLocEntryTable.begin();
-  // 

[PATCH] D135429: [HLSL] [DirectX backend] Move generateGlobalCtorDtorCalls into DirectX backend.

2022-10-07 Thread Xiang Li via Phabricator via cfe-commits
python3kgae created this revision.
python3kgae added reviewers: efriedma, pow2clk, beanz, bogner.
Herald added subscribers: Anastasia, hiraditya.
Herald added a project: All.
python3kgae requested review of this revision.
Herald added projects: clang, LLVM.
Herald added subscribers: llvm-commits, cfe-commits.

Move generateGlobalCtorDtorCalls out of clang CodeGen.
A new transform pass GlobalCtorDtorCalls is created to do the job.
GlobalCtorDtorCalls is registed in 
registerPipelineEarlySimplificationEPCallback.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D135429

Files:
  clang/lib/CodeGen/CGHLSLRuntime.cpp
  clang/lib/CodeGen/CGHLSLRuntime.h
  clang/test/CodeGenHLSL/GlobalConstructorFunction.hlsl
  clang/test/CodeGenHLSL/GlobalConstructorLib.hlsl
  clang/test/CodeGenHLSL/GlobalConstructors.hlsl
  clang/test/CodeGenHLSL/GlobalDestructors.hlsl
  llvm/lib/Target/DirectX/CMakeLists.txt
  llvm/lib/Target/DirectX/DirectXTargetMachine.cpp
  llvm/lib/Target/DirectX/GlobalCtorDtorCalls.cpp
  llvm/lib/Target/DirectX/GlobalCtorDtorCalls.h
  llvm/test/CodeGen/DirectX/global_constructor_cs.ll
  llvm/test/CodeGen/DirectX/global_constructor_function.ll
  llvm/test/CodeGen/DirectX/global_constructor_lib.ll
  llvm/test/CodeGen/DirectX/global_destructor_cs.ll
  llvm/test/CodeGen/DirectX/global_destructor_lib.ll

Index: llvm/test/CodeGen/DirectX/global_destructor_lib.ll
===
--- /dev/null
+++ llvm/test/CodeGen/DirectX/global_destructor_lib.ll
@@ -0,0 +1,186 @@
+; RUN: opt -S -passes="global-ctor-dtor-calls" < %s | FileCheck %s
+
+target datalayout = "e-m:e-p:32:32-i1:32-i8:8-i16:16-i32:32-i64:64-f16:16-f32:32-f64:64-n8:16:32:64"
+target triple = "dxil-unknown-shadermodel6.3-library"
+
+; Make sure global variable for ctors/dtors exist.
+; CHECK:@llvm.global_ctors
+; CHECK:@llvm.global_dtors
+
+;CHECK:  define void @main()
+;CHECK-NEXT: entry:
+;CHECK-NEXT:   call void @_GLOBAL__sub_I_GlobalDestructors.hlsl()
+;CHECK-NEXT:   %0 = call i32 @llvm.dx.flattened.thread.id.in.group()
+;CHECK-NEXT:   call void @"?main@@YAXI@Z"(i32 %0)
+;CHECK-NEXT:   call void @_GLOBAL__D_a()
+;CHECK-NEXT:   ret void
+
+; This is really just a sanity check I needed for myself to verify that
+; function scope static variables also get destroyed properly.
+
+;CHECK: define internal void @_GLOBAL__D_a()
+;CHECK-NEXT: entry:
+;CHECK-NEXT:   call void @"??1Tail@@QAA@XZ"(ptr @"?T@?1??Wag@@YAXXZ@4UTail@@A")
+;CHECK-NEXT:   call void @"??1Pupper@@QAA@XZ"(ptr @"?GlobalPup@@3UPupper@@A")
+;CHECK-NEXT:   ret void
+
+%struct.Pupper = type { i8 }
+%struct.Tail = type { i8 }
+
+$"??1Pupper@@QAA@XZ" = comdat any
+
+$"??1Tail@@QAA@XZ" = comdat any
+
+@"?GlobalPup@@3UPupper@@A" = global %struct.Pupper zeroinitializer, align 1
+@"?T@?1??Wag@@YAXXZ@4UTail@@A" = internal global %struct.Tail zeroinitializer, align 1
+@"?$TSS0@?1??Wag@@YAXXZ@4HA" = internal global i32 0, align 4
+@_Init_thread_epoch = external thread_local global i32, align 4
+@"?Count@Pupper@@2HA" = global i32 0, align 4
+@"?Count@?1??add@Tail@@QAAXH@Z@4HA" = linkonce_odr global i32 0, align 4
+@llvm.global_ctors = appending global [1 x { i32, ptr, ptr }] [{ i32, ptr, ptr } { i32 65535, ptr @_GLOBAL__sub_I_GlobalDestructors.hlsl, ptr null }]
+@llvm.global_dtors = appending global [1 x { i32, ptr, ptr }] [{ i32, ptr, ptr } { i32 65535, ptr @_GLOBAL__D_a, ptr null }]
+
+; Function Attrs: nounwind
+define internal void @"??__EGlobalPup@@YAXXZ"() #0 {
+entry:
+  %call = call noundef ptr @"??0Pupper@@QAA@XZ"(ptr noundef nonnull align 1 dereferenceable(1) @"?GlobalPup@@3UPupper@@A")
+  ret void
+}
+
+; Function Attrs: nounwind
+define linkonce_odr noundef ptr @"??0Pupper@@QAA@XZ"(ptr noundef nonnull returned align 1 dereferenceable(1) %this) unnamed_addr #0 align 2 {
+entry:
+  %this.addr = alloca ptr, align 4
+  store ptr %this, ptr %this.addr, align 4
+  %this1 = load ptr, ptr %this.addr, align 4
+  %0 = load i32, ptr @"?Count@Pupper@@2HA", align 4
+  %add = add nsw i32 %0, 1
+  store i32 %add, ptr @"?Count@Pupper@@2HA", align 4
+  ret ptr %this1
+}
+
+; Function Attrs: nounwind
+define linkonce_odr void @"??1Pupper@@QAA@XZ"(ptr noundef nonnull align 1 dereferenceable(1) %this) unnamed_addr #0 comdat align 2 {
+entry:
+  %this.addr = alloca ptr, align 4
+  store ptr %this, ptr %this.addr, align 4
+  %this1 = load ptr, ptr %this.addr, align 4
+  %0 = load i32, ptr @"?Count@Pupper@@2HA", align 4
+  %sub = sub nsw i32 %0, 1
+  store i32 %sub, ptr @"?Count@Pupper@@2HA", align 4
+  ret void
+}
+
+; Function Attrs: nounwind
+define void @"?Wag@@YAXXZ"() #0 {
+entry:
+  %0 = load atomic i32, ptr @"?$TSS0@?1??Wag@@YAXXZ@4HA" unordered, align 4
+  %1 = load i32, ptr @_Init_thread_epoch, align 4
+  %2 = icmp sgt i32 %0, %1
+  br i1 %2, label %init.attempt, label %init.end
+
+init.attempt: ; preds = %entry
+  call void @_Init_thread_header(ptr @"?$TSS0@?1??Wag@@YAXXZ@4HA") #1
+  %3 = load atomi

[PATCH] D129443: [clang-format] Add option for aligning requires clause body

2022-10-07 Thread Emilia Dreamer via Phabricator via cfe-commits
rymiel added a comment.

It wasn't an accidental regression, though, it was a conscious formatting 
decision (maybe ask @HazardyKnusperkeks for more). Similar to how lambdas can 
be formatted aligned to the introducer, i think this option does make sense.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129443

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


[PATCH] D135169: [LLDB] Fix printing a static bool struct member when using "image lookup -t"

2022-10-07 Thread David Spickett via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG02c1c939486f: [LLDB] Fix printing a static bool struct 
member when using "image lookup -t" (authored by DavidSpickett).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135169

Files:
  lldb/include/lldb/Symbol/CompilerType.h
  lldb/include/lldb/Symbol/TypeSystem.h
  lldb/source/Plugins/SymbolFile/DWARF/DWARFASTParserClang.cpp
  lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
  lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
  lldb/source/Symbol/CompilerType.cpp
  
lldb/test/API/lang/cpp/const_static_integral_member/TestConstStaticIntegralMember.py
  lldb/test/API/lang/cpp/const_static_integral_member/main.cpp

Index: lldb/test/API/lang/cpp/const_static_integral_member/main.cpp
===
--- lldb/test/API/lang/cpp/const_static_integral_member/main.cpp
+++ lldb/test/API/lang/cpp/const_static_integral_member/main.cpp
@@ -79,8 +79,13 @@
   ScopedEnum::scoped_enum_case1;
 };
 
+struct StaticBoolStruct {
+  static const bool value = false;
+};
+
 int main() {
   A a;
+  StaticBoolStruct sbs;
 
   auto char_max = A::char_max;
   auto uchar_max = A::uchar_max;
Index: lldb/test/API/lang/cpp/const_static_integral_member/TestConstStaticIntegralMember.py
===
--- lldb/test/API/lang/cpp/const_static_integral_member/TestConstStaticIntegralMember.py
+++ lldb/test/API/lang/cpp/const_static_integral_member/TestConstStaticIntegralMember.py
@@ -32,6 +32,11 @@
 # Test a bool member.
 self.expect_expr("A::bool_val", result_value="true")
 
+# Test a bool member when printing the struct it is a member of.
+# TODO: replace this with printing struct A, once doing so doesn't crash lldb.
+self.expect("image lookup -t StaticBoolStruct",
+substrs=["static const bool value = false;"])
+
 # Test that minimum and maximum values for each data type are right.
 self.expect_expr("A::char_max == char_max", result_value="true")
 self.expect_expr("A::uchar_max == uchar_max", result_value="true")
Index: lldb/source/Symbol/CompilerType.cpp
===
--- lldb/source/Symbol/CompilerType.cpp
+++ lldb/source/Symbol/CompilerType.cpp
@@ -154,6 +154,12 @@
   return IsIntegerType(is_signed) || IsEnumerationType(is_signed);
 }
 
+bool CompilerType::IsBooleanType() const {
+  if (IsValid())
+return m_type_system->IsBooleanType(m_type);
+  return false;
+}
+
 bool CompilerType::IsPointerType(CompilerType *pointee_type) const {
   if (IsValid()) {
 return m_type_system->IsPointerType(m_type, pointee_type);
Index: lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
===
--- lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
+++ lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h
@@ -592,6 +592,8 @@
   bool IsEnumerationType(lldb::opaque_compiler_type_t type,
  bool &is_signed) override;
 
+  bool IsBooleanType(lldb::opaque_compiler_type_t type) override;
+
   bool IsScopedEnumerationType(lldb::opaque_compiler_type_t type) override;
 
   static bool IsObjCClassType(const CompilerType &type);
@@ -860,6 +862,8 @@
   static void SetIntegerInitializerForVariable(clang::VarDecl *var,
const llvm::APInt &init_value);
 
+  static void SetBoolInitializerForVariable(clang::VarDecl *var, bool value);
+
   /// Initializes a variable with a floating point value.
   /// \param var The variable to initialize. Must not already have an
   ///initializer and must have a floating point type.
Index: lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
===
--- lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
+++ lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp
@@ -3224,6 +3224,20 @@
   return false;
 }
 
+bool TypeSystemClang::IsBooleanType(lldb::opaque_compiler_type_t type) {
+  if (!type)
+return false;
+
+  clang::QualType qual_type(GetCanonicalQualType(type));
+  const clang::BuiltinType *builtin_type =
+  llvm::dyn_cast(qual_type->getCanonicalTypeInternal());
+
+  if (!builtin_type)
+return false;
+
+  return builtin_type->isBooleanType();
+}
+
 bool TypeSystemClang::IsEnumerationType(lldb::opaque_compiler_type_t type,
 bool &is_signed) {
   if (type) {
@@ -7574,6 +7588,18 @@
   return var_decl;
 }
 
+void TypeSystemClang::SetBoolInitializerForVariable(VarDecl *var, bool value) {
+  assert(!var->hasInit() && "variable already initialized");
+
+  QualType qt = var->getType();
+  assert(qt->isSpecificBuiltinType(BuiltinType::Bool

[PATCH] D134902: [clang] Implement -fstrict-flex-arrays=3

2022-10-07 Thread Bill Wendling via Phabricator via cfe-commits
void marked an inline comment as done.
void added inline comments.



Comment at: clang/test/CodeGen/bounds-checking-fam.c:2
 // REQUIRES: x86-registered-target
-// RUN: %clang_cc1 -emit-llvm -triple x86_64 -fstrict-flex-arrays=0 
-fsanitize=array-bounds%s -o - | FileCheck %s 
--check-prefixes=CHECK,CHECK-STRICT-0
-// RUN: %clang_cc1 -emit-llvm -triple x86_64 -fstrict-flex-arrays=0 
-fsanitize=array-bounds -x c++ %s -o - | FileCheck %s 
--check-prefixes=CHECK,CHECK-STRICT-0,CXX,CXX-STRICT-0
-// RUN: %clang_cc1 -emit-llvm -triple x86_64 -fstrict-flex-arrays=1 
-fsanitize=array-bounds%s -o - | FileCheck %s 
--check-prefixes=CHECK,CHECK-STRICT-1
-// RUN: %clang_cc1 -emit-llvm -triple x86_64 -fstrict-flex-arrays=1 
-fsanitize=array-bounds -x c++ %s -o - | FileCheck %s 
--check-prefixes=CHECK,CHECK-STRICT-1,CXX
-// RUN: %clang_cc1 -emit-llvm -triple x86_64 -fstrict-flex-arrays=2 
-fsanitize=array-bounds%s -o - | FileCheck %s 
--check-prefixes=CHECK,CHECK-STRICT-2
-// RUN: %clang_cc1 -emit-llvm -triple x86_64 -fstrict-flex-arrays=2 
-fsanitize=array-bounds -x c++ %s -o - | FileCheck %s 
--check-prefixes=CHECK,CHECK-STRICT-2,CXX
+// RUN: %clang_cc1 -O2 -emit-llvm -triple x86_64 -fstrict-flex-arrays=0 
-fsanitize=array-bounds%s -o - | FileCheck %s 
--check-prefixes=CHECK,CHECK-STRICT-0
+// RUN: %clang_cc1 -O2 -emit-llvm -triple x86_64 -fstrict-flex-arrays=0 
-fsanitize=array-bounds -x c++ %s -o - | FileCheck %s 
--check-prefixes=CHECK,CHECK-STRICT-0,CXX,CXX-STRICT-0

serge-sans-paille wrote:
> Why adding -02 here?
Mostly because that's how Linux compiles its files. It also mirrors the test 
below. I'm not super married to it if you'd rather I omit it.



Comment at: clang/test/CodeGen/object-size-flex-array.c:45
+  // CHECK-STRICT-2: ret i32 -1
+  // CHECK-STRICT-3: ret i32 0
   return OBJECT_SIZE_BUILTIN(f->c, 1);

serge-sans-paille wrote:
> kees wrote:
> > serge-sans-paille wrote:
> > > This one worries me a bit, as an array of size 0 is invalid C, unless you 
> > > consider the extension of it being a FAM. Shouldn't we emit a warning or 
> > > something here? @kees what meaning would you give to that construct under 
> > > `-fstrict-flex-arrays=3` ?
> > ```
> > type identifier[0]
> > ```
> > when not a fake FAM is the same as:
> > 
> > ```
> > struct { } identifier
> > ```
> > 
> > It's addressable with no size.
> > 
> > FWIW, this is how GCC is treating it, and opted for no warning. The warning 
> > gains nothing and is likely an irritant: if someone is requesting =3, they 
> > want this behavior. If they didn't, they'd just use `-Wzero-length-array`. 
> > In particular, the Linux kernel is in the position of needing to have 
> > zero-length arrays (legacy userspace API) alongside real FAMs, even if we 
> > don't reference the zero-length members. So we cannot use 
> > '-Wzero-length-array', but we want to make sure no zero-length arrays will 
> > ever be used as fake FAMs, as a code quality/style enforcement. This is 
> > especially true of FORTIFY_SOURCE, where `__bos()` needs to report 0 
> > instead of -1 for such a destination buffer size, so that we immediately 
> > trip compile-time (or at worst, run-time) warnings, to keep any kernel 
> > internals from using the deprecated members as a fake FAM.
> > 
> > Take this case:
> > 
> > ```
> > struct broken {
> > int foo;
> > int fake_fam[0];
> > struct something oops;
> > };
> > ```
> > 
> > There have been bugs where the above struct was created because "oops" got 
> > added after "fake_fam" by someone not realizing. Under FORTIFY_SOURCE, 
> > doing:
> > 
> > ```
> > memcpy(p->fake_fam, src, len);
> > ```
> > 
> > raises no warning when `__bos(p->fake_fam, 1)` returns -1 and will happily 
> > stomp on "oops". If `__bos()` returns 0, we can compile-time (or run-time) 
> > block the memcpy. (And this holds for -fsanitize=bounds as well: if it is 
> > considered to be unknown size, it won't trip on access, but if it's 
> > 0-sized, it'll trip.) 
> > 
> > So, we can't keep zero-length arrays out of the kernel, but we want to be 
> > able to enforce that if they DO show up, they will trip warnings quickly.
> > 
> Thanks for clarifying the situation, esp. the kernel background. This looks 
> like a quite specific scenario, but it's fine with me.
I'll add @kees's comment to the commit message.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134902

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


[PATCH] D135170: [LLDB] Fix crash when printing a struct with a static signed char member

2022-10-07 Thread David Spickett 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 rG5a9e21305803: [LLDB] Fix crash when printing a struct with a 
static signed char member (authored by DavidSpickett).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135170

Files:
  clang/lib/AST/StmtPrinter.cpp
  
lldb/test/API/lang/cpp/const_static_integral_member/TestConstStaticIntegralMember.py
  lldb/test/API/lang/cpp/const_static_integral_member/main.cpp


Index: lldb/test/API/lang/cpp/const_static_integral_member/main.cpp
===
--- lldb/test/API/lang/cpp/const_static_integral_member/main.cpp
+++ lldb/test/API/lang/cpp/const_static_integral_member/main.cpp
@@ -79,13 +79,8 @@
   ScopedEnum::scoped_enum_case1;
 };
 
-struct StaticBoolStruct {
-  static const bool value = false;
-};
-
 int main() {
   A a;
-  StaticBoolStruct sbs;
 
   auto char_max = A::char_max;
   auto uchar_max = A::uchar_max;
Index: 
lldb/test/API/lang/cpp/const_static_integral_member/TestConstStaticIntegralMember.py
===
--- 
lldb/test/API/lang/cpp/const_static_integral_member/TestConstStaticIntegralMember.py
+++ 
lldb/test/API/lang/cpp/const_static_integral_member/TestConstStaticIntegralMember.py
@@ -32,11 +32,6 @@
 # Test a bool member.
 self.expect_expr("A::bool_val", result_value="true")
 
-# Test a bool member when printing the struct it is a member of.
-# TODO: replace this with printing struct A, once doing so doesn't 
crash lldb.
-self.expect("image lookup -t StaticBoolStruct",
-substrs=["static const bool value = false;"])
-
 # Test that minimum and maximum values for each data type are right.
 self.expect_expr("A::char_max == char_max", result_value="true")
 self.expect_expr("A::uchar_max == uchar_max", result_value="true")
@@ -88,6 +83,10 @@
 self.expect_expr("const int *i = &A::int_val_with_address; *i",
  result_value="2")
 
+# Printing the whole type takes a slightly different code path. Check 
that
+# it does not crash.
+self.expect("image lookup -t A")
+
 # dsymutil strips the debug info for classes that only have const static
 # data members without a definition namespace scope.
 @expectedFailureAll(debug_info=["dsym"])
Index: clang/lib/AST/StmtPrinter.cpp
===
--- clang/lib/AST/StmtPrinter.cpp
+++ clang/lib/AST/StmtPrinter.cpp
@@ -1280,6 +1280,7 @@
   case BuiltinType::Char_S:
   case BuiltinType::Char_U:OS << "i8"; break;
   case BuiltinType::UChar: OS << "Ui8"; break;
+  case BuiltinType::SChar: OS << "i8"; break;
   case BuiltinType::Short: OS << "i16"; break;
   case BuiltinType::UShort:OS << "Ui16"; break;
   case BuiltinType::Int:   break; // no suffix.


Index: lldb/test/API/lang/cpp/const_static_integral_member/main.cpp
===
--- lldb/test/API/lang/cpp/const_static_integral_member/main.cpp
+++ lldb/test/API/lang/cpp/const_static_integral_member/main.cpp
@@ -79,13 +79,8 @@
   ScopedEnum::scoped_enum_case1;
 };
 
-struct StaticBoolStruct {
-  static const bool value = false;
-};
-
 int main() {
   A a;
-  StaticBoolStruct sbs;
 
   auto char_max = A::char_max;
   auto uchar_max = A::uchar_max;
Index: lldb/test/API/lang/cpp/const_static_integral_member/TestConstStaticIntegralMember.py
===
--- lldb/test/API/lang/cpp/const_static_integral_member/TestConstStaticIntegralMember.py
+++ lldb/test/API/lang/cpp/const_static_integral_member/TestConstStaticIntegralMember.py
@@ -32,11 +32,6 @@
 # Test a bool member.
 self.expect_expr("A::bool_val", result_value="true")
 
-# Test a bool member when printing the struct it is a member of.
-# TODO: replace this with printing struct A, once doing so doesn't crash lldb.
-self.expect("image lookup -t StaticBoolStruct",
-substrs=["static const bool value = false;"])
-
 # Test that minimum and maximum values for each data type are right.
 self.expect_expr("A::char_max == char_max", result_value="true")
 self.expect_expr("A::uchar_max == uchar_max", result_value="true")
@@ -88,6 +83,10 @@
 self.expect_expr("const int *i = &A::int_val_with_address; *i",
  result_value="2")
 
+# Printing the whole type takes a slightly different code path. Check that
+# it does not crash.
+self.expect("image lookup -t A")
+
 # dsymutil strips the debug info for classes that only have const static
 # data members without a definition na

[clang] 5a9e213 - [LLDB] Fix crash when printing a struct with a static signed char member

2022-10-07 Thread David Spickett via cfe-commits

Author: David Spickett
Date: 2022-10-07T09:11:15Z
New Revision: 5a9e21305803336dc359f72014849845b1a7e173

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

LOG: [LLDB] Fix crash when printing a struct with a static signed char member

As with static bool for whatever reason printing them on their own
worked fine but wasn't handled when you printed the whole type.

I don't see a good way to test this from clang's side so our existing
tests will have to do.

We can now print all of the struct "A", so there's no need for a separate
one for static bool testing. I've not checked the output, just that it
succeeds. This saves us having to handle different min/max between systems.

Depends on D135169

Reviewed By: aeubanks, shafik

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

Added: 


Modified: 
clang/lib/AST/StmtPrinter.cpp

lldb/test/API/lang/cpp/const_static_integral_member/TestConstStaticIntegralMember.py
lldb/test/API/lang/cpp/const_static_integral_member/main.cpp

Removed: 




diff  --git a/clang/lib/AST/StmtPrinter.cpp b/clang/lib/AST/StmtPrinter.cpp
index 03b71a7ec9416..fabffbd323648 100644
--- a/clang/lib/AST/StmtPrinter.cpp
+++ b/clang/lib/AST/StmtPrinter.cpp
@@ -1280,6 +1280,7 @@ void StmtPrinter::VisitIntegerLiteral(IntegerLiteral 
*Node) {
   case BuiltinType::Char_S:
   case BuiltinType::Char_U:OS << "i8"; break;
   case BuiltinType::UChar: OS << "Ui8"; break;
+  case BuiltinType::SChar: OS << "i8"; break;
   case BuiltinType::Short: OS << "i16"; break;
   case BuiltinType::UShort:OS << "Ui16"; break;
   case BuiltinType::Int:   break; // no suffix.

diff  --git 
a/lldb/test/API/lang/cpp/const_static_integral_member/TestConstStaticIntegralMember.py
 
b/lldb/test/API/lang/cpp/const_static_integral_member/TestConstStaticIntegralMember.py
index 0482007d48147..5252247191383 100644
--- 
a/lldb/test/API/lang/cpp/const_static_integral_member/TestConstStaticIntegralMember.py
+++ 
b/lldb/test/API/lang/cpp/const_static_integral_member/TestConstStaticIntegralMember.py
@@ -32,11 +32,6 @@ def test(self):
 # Test a bool member.
 self.expect_expr("A::bool_val", result_value="true")
 
-# Test a bool member when printing the struct it is a member of.
-# TODO: replace this with printing struct A, once doing so doesn't 
crash lldb.
-self.expect("image lookup -t StaticBoolStruct",
-substrs=["static const bool value = false;"])
-
 # Test that minimum and maximum values for each data type are right.
 self.expect_expr("A::char_max == char_max", result_value="true")
 self.expect_expr("A::uchar_max == uchar_max", result_value="true")
@@ -88,6 +83,10 @@ def test(self):
 self.expect_expr("const int *i = &A::int_val_with_address; *i",
  result_value="2")
 
+# Printing the whole type takes a slightly 
diff erent code path. Check that
+# it does not crash.
+self.expect("image lookup -t A")
+
 # dsymutil strips the debug info for classes that only have const static
 # data members without a definition namespace scope.
 @expectedFailureAll(debug_info=["dsym"])

diff  --git a/lldb/test/API/lang/cpp/const_static_integral_member/main.cpp 
b/lldb/test/API/lang/cpp/const_static_integral_member/main.cpp
index d078076b99dc8..977e12295760a 100644
--- a/lldb/test/API/lang/cpp/const_static_integral_member/main.cpp
+++ b/lldb/test/API/lang/cpp/const_static_integral_member/main.cpp
@@ -79,13 +79,8 @@ struct ClassWithEnumAlias {
   ScopedEnum::scoped_enum_case1;
 };
 
-struct StaticBoolStruct {
-  static const bool value = false;
-};
-
 int main() {
   A a;
-  StaticBoolStruct sbs;
 
   auto char_max = A::char_max;
   auto uchar_max = A::uchar_max;



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


[PATCH] D134902: [clang] Implement -fstrict-flex-arrays=3

2022-10-07 Thread Bill Wendling via Phabricator via cfe-commits
void updated this revision to Diff 466011.
void added a comment.
Herald added subscribers: steakhal, martong.
Herald added a reviewer: NoQ.

Update comments to reflect reality.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134902

Files:
  clang/include/clang/Basic/LangOptions.h
  clang/include/clang/Driver/Options.td
  clang/lib/AST/ExprConstant.cpp
  clang/lib/StaticAnalyzer/Core/MemRegion.cpp
  clang/test/CodeGen/bounds-checking-fam.c
  clang/test/CodeGen/object-size-flex-array.c
  clang/test/Sema/array-bounds-ptr-arith.c
  clang/test/SemaCXX/array-bounds-strict-flex-arrays.cpp

Index: clang/test/SemaCXX/array-bounds-strict-flex-arrays.cpp
===
--- clang/test/SemaCXX/array-bounds-strict-flex-arrays.cpp
+++ clang/test/SemaCXX/array-bounds-strict-flex-arrays.cpp
@@ -1,5 +1,6 @@
 // RUN: %clang_cc1 -verify=relaxed -fstrict-flex-arrays=1 %s
 // RUN: %clang_cc1 -verify=relaxed,strict -fstrict-flex-arrays=2 %s
+// RUN: %clang_cc1 -verify=relaxed,strict -fstrict-flex-arrays=3 %s
 
 // We cannot know for sure the size of a flexible array.
 struct t {
@@ -10,7 +11,7 @@
   s2->a[2] = 0; // no-warning
 }
 
-// Under -fstrict-flex-arrays={1,2} `a` is not a flexible array
+// Under -fstrict-flex-arrays={1,2,3} `a` is not a flexible array
 struct t0 {
   int f;
   int a[10]; // relaxed-note {{array 'a' declared here}}
@@ -29,7 +30,7 @@
   s2->a[2] = 0; // strict-warning {{array index 2 is past the end of the array (which contains 1 element)}}
 }
 
-// Under -fstrict-flex-arrays={1,2} `a` is a flexible array.
+// Under -fstrict-flex-arrays={1,2} `a` is a flexible array, but not under -fstrict-flex-arrays=3.
 struct t2 {
   int f;
   int a[0];
Index: clang/test/Sema/array-bounds-ptr-arith.c
===
--- clang/test/Sema/array-bounds-ptr-arith.c
+++ clang/test/Sema/array-bounds-ptr-arith.c
@@ -1,6 +1,7 @@
 // RUN: %clang_cc1 -verify=expected -Warray-bounds-pointer-arithmetic %s
 // RUN: %clang_cc1 -verify=expected -Warray-bounds-pointer-arithmetic %s -fstrict-flex-arrays=0
 // RUN: %clang_cc1 -verify=expected,strict -Warray-bounds-pointer-arithmetic %s -fstrict-flex-arrays=2
+// RUN: %clang_cc1 -verify=expected,strict -Warray-bounds-pointer-arithmetic %s -fstrict-flex-arrays=3
 
 // Test case from PR10615
 struct ext2_super_block{
Index: clang/test/CodeGen/object-size-flex-array.c
===
--- clang/test/CodeGen/object-size-flex-array.c
+++ clang/test/CodeGen/object-size-flex-array.c
@@ -1,6 +1,8 @@
-// RUN: %clang -fstrict-flex-arrays=2 -target x86_64-apple-darwin -S -emit-llvm %s -o - 2>&1 | FileCheck --check-prefixes=CHECK,CHECK-STRICT-2 %s
-// RUN: %clang -fstrict-flex-arrays=1 -target x86_64-apple-darwin -S -emit-llvm %s -o - 2>&1 | FileCheck --check-prefixes=CHECK,CHECK-STRICT-1 %s
-// RUN: %clang -fstrict-flex-arrays=0 -target x86_64-apple-darwin -S -emit-llvm %s -o - 2>&1 | FileCheck --check-prefixes=CHECK,CHECK-STRICT-0 %s
+// RUN: %clang-target x86_64 -O2 -S -emit-llvm %s -o - 2>&1 | FileCheck --check-prefixes=CHECK,CHECK-NO-STRICT %s
+// RUN: %clang -fstrict-flex-arrays=0 -target x86_64 -O2 -S -emit-llvm %s -o - 2>&1 | FileCheck --check-prefixes=CHECK,CHECK-STRICT-0 %s
+// RUN: %clang -fstrict-flex-arrays=1 -target x86_64 -O2 -S -emit-llvm %s -o - 2>&1 | FileCheck --check-prefixes=CHECK,CHECK-STRICT-1 %s
+// RUN: %clang -fstrict-flex-arrays=2 -target x86_64 -O2 -S -emit-llvm %s -o - 2>&1 | FileCheck --check-prefixes=CHECK,CHECK-STRICT-2 %s
+// RUN: %clang -fstrict-flex-arrays=3 -target x86_64 -O2 -S -emit-llvm %s -o - 2>&1 | FileCheck --check-prefixes=CHECK,CHECK-STRICT-3 %s
 
 #define OBJECT_SIZE_BUILTIN __builtin_object_size
 
@@ -26,36 +28,86 @@
 
 // CHECK-LABEL: @bar(
 unsigned bar(foo_t *f) {
-  // CHECK-STRICT-0: ret i32 %
-  // CHECK-STRICT-1: ret i32 %
-  // CHECK-STRICT-2: ret i32 %
+  // CHECK-NO-STRICT: ret i32 -1
+  // CHECK-STRICT-0: ret i32 -1
+  // CHECK-STRICT-1: ret i32 -1
+  // CHECK-STRICT-2: ret i32 -1
+  // CHECK-STRICT-3: ret i32 -1
   return OBJECT_SIZE_BUILTIN(f->c, 1);
 }
 
 // CHECK-LABEL: @bar0(
 unsigned bar0(foo0_t *f) {
-  // CHECK-STRICT-0: ret i32 %
-  // CHECK-STRICT-1: ret i32 %
-  // CHECK-STRICT-2: ret i32 %
+  // CHECK-NO-STRICT: ret i32 -1
+  // CHECK-STRICT-0: ret i32 -1
+  // CHECK-STRICT-1: ret i32 -1
+  // CHECK-STRICT-2: ret i32 -1
+  // CHECK-STRICT-3: ret i32 0
   return OBJECT_SIZE_BUILTIN(f->c, 1);
 }
 
 // CHECK-LABEL: @bar1(
 unsigned bar1(foo1_t *f) {
-  // CHECK-STRICT-0: ret i32 %
-  // CHECK-STRICT-1: ret i32 %
+  // CHECK-NO-STRICT: ret i32 -1
+  // CHECK-STRICT-0: ret i32 -1
+  // CHECK-STRICT-1: ret i32 -1
   // CHECK-STRICT-2: ret i32 8
+  // CHECK-STRICT-3: ret i32 8
   return OBJECT_SIZE_BUILTIN(f->c, 1);
 }
 
 // CHECK-LABEL: @bar2(
 unsigned bar2(foo2_t *f) {
- 

[PATCH] D135257: [clangd][Tweak] Make sure enclosing function doesnt have invalid children

2022-10-07 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added a comment.

I wasn't claiming that there are legitimate reasons for having null children, I 
completely agree with your verdict on this one. The only one I can think of is 
cases like this, i.e. you don't want to perform some analysis if function body 
has invalid code in it. but i think that should rather be indicated in the 
container of children, rather than being inferred by traversing the children.

I am just saying that going out and fixing all the statement types that can 
contain sub-statements is a much bigger effort.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135257

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


[PATCH] D135257: [clangd][Tweak] Make sure enclosing function doesnt have invalid children

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

To be clear: landing this change seems fine, I was not trying to block it, 
sorry if it seemed that way. I'm just trying to understand whether it would 
also make sense to  change the defaults.
I believe we are on the same page here, it's just a matter of booking someone's 
time to do this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135257

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


[PATCH] D129443: [clang-format] Add option for aligning requires clause body

2022-10-07 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added a comment.

In D129443#3841248 , @owenpan wrote:

> Is this option really required? Can we just fix the regression as reported in 
> https://github.com/llvm/llvm-project/issues/56283? It seems that we haven't 
> followed the policy 
> 
>  lately when adding new options.

If it's a regression or not is a matter of perspective. Before my patch there 
were no real handling of concepts and they just looked like that. I had changed 
that (on purpose) if I remember correctly to bring in closer to lambdas.
We can //fix// that regression, and I will adopt this change for my company to 
keep the requires expressions where they are. :)

Also asking for a style guide concerning concepts and requires is a bit hard I 
think, I think in none of the styles we implement it is mentioned, it at least 
wasn't when I added the handling.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129443

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


[PATCH] D135422: Fix clang-format misattributing preprocessor directives to macros

2022-10-07 Thread Björn Schäpers via Phabricator via cfe-commits
HazardyKnusperkeks added a comment.

Please add a regression test.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135422

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


[PATCH] D135433: [clang][Interp] Implement while and do-while loops

2022-10-07 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder created this revision.
tbaeder added reviewers: aaron.ballman, erichkeane, shafik, tahonermann.
Herald added a project: All.
tbaeder requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

I was wondering whether it is somehow possible to get a loop into a expression 
so I can use it directly in a `static_assert()` (and it would be interpreted 
directly rather than compiled to bytecode).


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D135433

Files:
  clang/lib/AST/Interp/ByteCodeStmtGen.cpp
  clang/lib/AST/Interp/ByteCodeStmtGen.h
  clang/test/AST/Interp/loops.cpp

Index: clang/test/AST/Interp/loops.cpp
===
--- /dev/null
+++ clang/test/AST/Interp/loops.cpp
@@ -0,0 +1,47 @@
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -std=c++14 -verify %s
+// RUN: %clang_cc1 -std=c++14 -verify=ref %s
+
+// expected-no-diagnostics
+// ref-no-diagnostics
+
+namespace WhileLoop {
+  constexpr int f() {
+int i = 0;
+while(false) {
+  i = i + 1;
+}
+return i;
+  }
+  static_assert(f() == 0, "");
+
+
+  constexpr int f2() {
+int i = 0;
+while(i != 5) {
+  i = i + 1;
+}
+return i;
+  }
+  static_assert(f2() == 5, "");
+};
+
+namespace DoWhileLoop {
+
+  constexpr int f() {
+int i = 0;
+do {
+  i = i + 1;
+} while(false);
+return i;
+  }
+  static_assert(f() == 1, "");
+
+  constexpr int f2() {
+int i = 0;
+do {
+  i = i + 1;
+} while(i != 5);
+return i;
+  }
+  static_assert(f2() == 5, "");
+};
Index: clang/lib/AST/Interp/ByteCodeStmtGen.h
===
--- clang/lib/AST/Interp/ByteCodeStmtGen.h
+++ clang/lib/AST/Interp/ByteCodeStmtGen.h
@@ -58,6 +58,8 @@
   bool visitDeclStmt(const DeclStmt *DS);
   bool visitReturnStmt(const ReturnStmt *RS);
   bool visitIfStmt(const IfStmt *IS);
+  bool visitWhileStmt(const WhileStmt *S);
+  bool visitDoStmt(const DoStmt *S);
 
   /// Compiles a variable declaration.
   bool visitVarDecl(const VarDecl *VD);
Index: clang/lib/AST/Interp/ByteCodeStmtGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeStmtGen.cpp
+++ clang/lib/AST/Interp/ByteCodeStmtGen.cpp
@@ -167,6 +167,10 @@
 return visitReturnStmt(cast(S));
   case Stmt::IfStmtClass:
 return visitIfStmt(cast(S));
+  case Stmt::WhileStmtClass:
+return visitWhileStmt(cast(S));
+  case Stmt::DoStmtClass:
+return visitDoStmt(cast(S));
   case Stmt::NullStmtClass:
 return true;
   default: {
@@ -276,6 +280,47 @@
   return true;
 }
 
+template 
+bool ByteCodeStmtGen::visitWhileStmt(const WhileStmt *S) {
+  const Expr *Cond = S->getCond();
+  const Stmt *Body = S->getBody();
+
+  LabelTy CondLabel = this->getLabel(); // Label before the condition.
+  LabelTy EndLabel = this->getLabel();  // Label after the loop
+
+  this->emitLabel(CondLabel);
+  if (!this->visitBool(Cond))
+return false;
+  if (!this->jumpFalse(EndLabel))
+return false;
+
+  if (!this->visitStmt(Body))
+return false;
+  if (!this->jump(CondLabel))
+return false;
+
+  this->emitLabel(EndLabel);
+
+  return true;
+}
+
+template 
+bool ByteCodeStmtGen::visitDoStmt(const DoStmt *S) {
+  const Expr *Cond = S->getCond();
+  const Stmt *Body = S->getBody();
+
+  LabelTy StartLabel = this->getLabel();
+
+  this->emitLabel(StartLabel);
+  if (!this->visitStmt(Body))
+return false;
+  if (!this->visitBool(Cond))
+return false;
+  if (!this->jumpTrue(StartLabel))
+return false;
+  return true;
+}
+
 template 
 bool ByteCodeStmtGen::visitVarDecl(const VarDecl *VD) {
   if (!VD->hasLocalStorage()) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] e09aa0d - [clangd][Tweak] Make sure enclosing function doesnt have invalid children

2022-10-07 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2022-10-07T12:00:22+02:00
New Revision: e09aa0d192e0ae240c55aaf8205e8320d49f9bdb

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

LOG: [clangd][Tweak] Make sure enclosing function doesnt have invalid children

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

Added: 


Modified: 
clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp 
b/clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
index 66fe4fdbfa2d3..4231de8cc45d6 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
@@ -248,6 +248,13 @@ const FunctionDecl *findEnclosingFunction(const Node 
*CommonAnc) {
   // FIXME: Support extraction from templated functions.
   if (Func->isTemplated())
 return nullptr;
+  for (const auto *S : Func->getBody()->children()) {
+// During apply phase, we perform semantic analysis (e.g. figure out
+// what variables requires hoisting). We cannot perform those when the
+// body has invalid statements, so fail up front.
+if (!S)
+  return nullptr;
+  }
   return Func;
 }
   }



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


[PATCH] D135257: [clangd][Tweak] Make sure enclosing function doesnt have invalid children

2022-10-07 Thread Kadir Cetinkaya via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGe09aa0d192e0: [clangd][Tweak] Make sure enclosing function 
doesnt have invalid children (authored by kadircet).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135257

Files:
  clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp


Index: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
===
--- clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
+++ clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
@@ -248,6 +248,13 @@
   // FIXME: Support extraction from templated functions.
   if (Func->isTemplated())
 return nullptr;
+  for (const auto *S : Func->getBody()->children()) {
+// During apply phase, we perform semantic analysis (e.g. figure out
+// what variables requires hoisting). We cannot perform those when the
+// body has invalid statements, so fail up front.
+if (!S)
+  return nullptr;
+  }
   return Func;
 }
   }


Index: clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
===
--- clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
+++ clang-tools-extra/clangd/refactor/tweaks/ExtractFunction.cpp
@@ -248,6 +248,13 @@
   // FIXME: Support extraction from templated functions.
   if (Func->isTemplated())
 return nullptr;
+  for (const auto *S : Func->getBody()->children()) {
+// During apply phase, we perform semantic analysis (e.g. figure out
+// what variables requires hoisting). We cannot perform those when the
+// body has invalid statements, so fail up front.
+if (!S)
+  return nullptr;
+  }
   return Func;
 }
   }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D135433: [clang][Interp] Implement while and do-while loops

2022-10-07 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 466022.
tbaeder added a comment.

Add `break` and `continue` support as well.


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

https://reviews.llvm.org/D135433

Files:
  clang/lib/AST/Interp/ByteCodeStmtGen.cpp
  clang/lib/AST/Interp/ByteCodeStmtGen.h
  clang/test/AST/Interp/loops.cpp

Index: clang/test/AST/Interp/loops.cpp
===
--- /dev/null
+++ clang/test/AST/Interp/loops.cpp
@@ -0,0 +1,94 @@
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -std=c++14 -verify %s
+// RUN: %clang_cc1 -std=c++14 -verify=ref %s
+
+// expected-no-diagnostics
+// ref-no-diagnostics
+
+namespace WhileLoop {
+  constexpr int f() {
+int i = 0;
+while(false) {
+  i = i + 1;
+}
+return i;
+  }
+  static_assert(f() == 0, "");
+
+
+  constexpr int f2() {
+int i = 0;
+while(i != 5) {
+  i = i + 1;
+}
+return i;
+  }
+  static_assert(f2() == 5, "");
+
+  constexpr int f3() {
+int i = 0;
+while(true) {
+  i = i + 1;
+
+  if (i == 5)
+break;
+}
+return i;
+  }
+  static_assert(f3() == 5, "");
+
+  constexpr int f4() {
+int i = 0;
+while(i != 5) {
+
+  i = i + 1;
+  continue;
+  i = i - 1;
+}
+return i;
+  }
+  static_assert(f4() == 5, "");
+};
+
+namespace DoWhileLoop {
+
+  constexpr int f() {
+int i = 0;
+do {
+  i = i + 1;
+} while(false);
+return i;
+  }
+  static_assert(f() == 1, "");
+
+  constexpr int f2() {
+int i = 0;
+do {
+  i = i + 1;
+} while(i != 5);
+return i;
+  }
+  static_assert(f2() == 5, "");
+
+
+  constexpr int f3() {
+int i = 0;
+do {
+  i = i + 1;
+  if (i == 5)
+break;
+} while(true);
+return i;
+  }
+  static_assert(f3() == 5, "");
+
+  constexpr int f4() {
+int i = 0;
+do {
+  i = i + 1;
+  continue;
+  i = i - 1;
+} while(i != 5);
+return i;
+  }
+  static_assert(f4() == 5, "");
+};
Index: clang/lib/AST/Interp/ByteCodeStmtGen.h
===
--- clang/lib/AST/Interp/ByteCodeStmtGen.h
+++ clang/lib/AST/Interp/ByteCodeStmtGen.h
@@ -58,6 +58,10 @@
   bool visitDeclStmt(const DeclStmt *DS);
   bool visitReturnStmt(const ReturnStmt *RS);
   bool visitIfStmt(const IfStmt *IS);
+  bool visitWhileStmt(const WhileStmt *S);
+  bool visitDoStmt(const DoStmt *S);
+  bool visitBreakStmt(const BreakStmt *S);
+  bool visitContinueStmt(const ContinueStmt *S);
 
   /// Compiles a variable declaration.
   bool visitVarDecl(const VarDecl *VD);
Index: clang/lib/AST/Interp/ByteCodeStmtGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeStmtGen.cpp
+++ clang/lib/AST/Interp/ByteCodeStmtGen.cpp
@@ -167,6 +167,14 @@
 return visitReturnStmt(cast(S));
   case Stmt::IfStmtClass:
 return visitIfStmt(cast(S));
+  case Stmt::WhileStmtClass:
+return visitWhileStmt(cast(S));
+  case Stmt::DoStmtClass:
+return visitDoStmt(cast(S));
+  case Stmt::BreakStmtClass:
+return visitBreakStmt(cast(S));
+  case Stmt::ContinueStmtClass:
+return visitContinueStmt(cast(S));
   case Stmt::NullStmtClass:
 return true;
   default: {
@@ -276,6 +284,69 @@
   return true;
 }
 
+template 
+bool ByteCodeStmtGen::visitWhileStmt(const WhileStmt *S) {
+  const Expr *Cond = S->getCond();
+  const Stmt *Body = S->getBody();
+
+  LabelTy CondLabel = this->getLabel(); // Label before the condition.
+  LabelTy EndLabel = this->getLabel();  // Label after the loop
+  LoopScope LS(this, EndLabel, CondLabel);
+
+  this->emitLabel(CondLabel);
+  if (!this->visitBool(Cond))
+return false;
+  if (!this->jumpFalse(EndLabel))
+return false;
+
+  if (!this->visitStmt(Body))
+return false;
+  if (!this->jump(CondLabel))
+return false;
+
+  this->emitLabel(EndLabel);
+
+  return true;
+}
+
+template 
+bool ByteCodeStmtGen::visitDoStmt(const DoStmt *S) {
+  const Expr *Cond = S->getCond();
+  const Stmt *Body = S->getBody();
+
+  LabelTy StartLabel = this->getLabel();
+  LabelTy EndLabel = this->getLabel();
+  LabelTy CondLabel = this->getLabel();
+  LoopScope LS(this, EndLabel, CondLabel);
+
+  this->emitLabel(StartLabel);
+  if (!this->visitStmt(Body))
+return false;
+  this->emitLabel(CondLabel);
+  if (!this->visitBool(Cond))
+return false;
+  if (!this->jumpTrue(StartLabel))
+return false;
+  this->emitLabel(EndLabel);
+  return true;
+}
+
+template 
+bool ByteCodeStmtGen::visitBreakStmt(const BreakStmt *S) {
+  if (!BreakLabel)
+return false;
+
+  return this->jump(*BreakLabel);
+}
+
+template 
+bool ByteCodeStmtGen::visitContinueStmt(const ContinueStmt *S) {
+  if (!ContinueLabel)
+return false;
+
+  return this->jump(*ContinueLabel);
+}
+
 template 
 bool ByteCodeStmtGen::visitVarDecl(const VarDecl *VD) {
   if (!VD->hasLocalStorage()) {
_

[PATCH] D135154: Keep inherited dllimport/export attrs for explicit specialization of template class member functions

2022-10-07 Thread Hans Wennborg via Phabricator via cfe-commits
hans added a comment.

Looking at the Chromium code some more, the case of trying to delete a 
specialization of a dllexport class template member seems suspect.

Since the error also matches MSVC I think we should keep that behavior, but 
I'll add a release note about it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135154

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


[PATCH] D135154: Keep inherited dllimport/export attrs for explicit specialization of template class member functions

2022-10-07 Thread Hans Wennborg via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGc9b771b9fc2f: Keep inherited dllimport/export attrs for 
explicit specialization of class… (authored by hans).

Changed prior to commit:
  https://reviews.llvm.org/D135154?vs=464984&id=466023#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135154

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaTemplate.cpp
  clang/test/CodeGenCXX/dllexport-members.cpp
  clang/test/CodeGenCXX/dllimport-members.cpp
  clang/test/SemaCXX/dllexport.cpp
  clang/test/SemaCXX/dllimport.cpp

Index: clang/test/SemaCXX/dllimport.cpp
===
--- clang/test/SemaCXX/dllimport.cpp
+++ clang/test/SemaCXX/dllimport.cpp
@@ -1138,6 +1138,9 @@
 // Import individual members of a class template.
 template
 struct ImportClassTmplMembers {
+#ifndef GNU
+// expected-note@+2{{attribute is here}}
+#endif
   __declspec(dllimport)void normalDecl();
 #ifdef GNU
 // expected-note@+2{{previous attribute is here}}
@@ -1300,6 +1303,34 @@
 template __declspec(dllimport) constexpr int CTMR::ConstexprField;
 
 
+// MSVC imports explicit specialization of imported class template member
+// function, and errors on such definitions. MinGW does not treat them as
+// dllimport.
+template  struct ClassTmpl {
+#if !defined(GNU)
+// expected-note@+2{{attribute is here}}
+#endif
+  void __declspec(dllimport) importedNormal();
+#if !defined(GNU)
+// expected-note@+2{{attribute is here}}
+#endif
+  static void __declspec(dllimport) importedStatic();
+};
+#if !defined(GNU)
+// expected-error@+2{{cannot define non-inline dllimport template specialization}}
+#endif
+template<> void ClassTmpl::importedNormal() {}
+#if !defined(GNU)
+// expected-error@+2{{cannot define non-inline dllimport template specialization}}
+#endif
+template<> void ClassTmpl::importedStatic() {}
+
+#if !defined(GNU)
+// expected-error@+3{{cannot define non-inline dllimport template specialization}}
+// expected-error@+2{{attribute 'dllimport' cannot be applied to a deleted function}}
+#endif
+template <> void ImportClassTmplMembers::normalDecl() = delete;
+
 
 //===--===//
 // Class template member templates
Index: clang/test/SemaCXX/dllexport.cpp
===
--- clang/test/SemaCXX/dllexport.cpp
+++ clang/test/SemaCXX/dllexport.cpp
@@ -1,11 +1,11 @@
-// RUN: %clang_cc1 -triple i686-win32 -fsyntax-only -fms-extensions -verify -std=c++11 -Wunsupported-dll-base-class-template -DMS %s
-// RUN: %clang_cc1 -triple x86_64-win32   -fsyntax-only -fms-extensions -verify -std=c++1y -Wunsupported-dll-base-class-template -DMS %s
-// RUN: %clang_cc1 -triple i686-mingw32   -fsyntax-only -fms-extensions -verify -std=c++1y -Wunsupported-dll-base-class-template %s
-// RUN: %clang_cc1 -triple x86_64-mingw32 -fsyntax-only -fms-extensions -verify -std=c++11 -Wunsupported-dll-base-class-template %s
-// RUN: %clang_cc1 -triple i686-windows-itanium   -fsyntax-only -fms-extensions -verify -std=c++11 -Wunsupported-dll-base-class-template -DWI %s
-// RUN: %clang_cc1 -triple x86_64-windows-itanium -fsyntax-only -fms-extensions -verify -std=c++1y -Wunsupported-dll-base-class-template -DWI %s
-// RUN: %clang_cc1 -triple x86_64-scei-ps4-fsyntax-only -fdeclspec  -verify -std=c++11 -Wunsupported-dll-base-class-template -DWI %s
-// RUN: %clang_cc1 -triple x86_64-sie-ps5 -fsyntax-only -fdeclspec  -verify -std=c++1y -Wunsupported-dll-base-class-template -DWI %s
+// RUN: %clang_cc1 -triple i686-win32 -fsyntax-only -fms-extensions -verify -std=c++11 -Wunsupported-dll-base-class-template -DMS  %s
+// RUN: %clang_cc1 -triple x86_64-win32   -fsyntax-only -fms-extensions -verify -std=c++1y -Wunsupported-dll-base-class-template -DMS  %s
+// RUN: %clang_cc1 -triple i686-mingw32   -fsyntax-only -fms-extensions -verify -std=c++1y -Wunsupported-dll-base-class-template -DGNU %s
+// RUN: %clang_cc1 -triple x86_64-mingw32 -fsyntax-only -fms-extensions -verify -std=c++11 -Wunsupported-dll-base-class-template -DGNU %s
+// RUN: %clang_cc1 -triple i686-windows-itanium   -fsyntax-only -fms-extensions -verify -std=c++11 -Wunsupported-dll-base-class-template -DWI  %s
+// RUN: %clang_cc1 -triple x86_64-windows-itanium -fsyntax-only -fms-extensions -verify -std=c++1y -Wunsupported-dll-base-class-template -DWI  %s
+// RUN: %clang_cc1 -triple x86_64-scei-ps4-fsyntax-only -fdeclspec  -verify -std=c++11 -Wunsupported-dll-base-class-template -DWI  %s
+// RUN: %clang_cc1 -triple x86_64-sie-ps5 -fsyntax-only -fdeclspec  -verify -std=c++1y -Wunsupported-dll-base-class-template -DWI  

[clang] c9b771b - Keep inherited dllimport/export attrs for explicit specialization of class template member functions

2022-10-07 Thread Hans Wennborg via cfe-commits

Author: Hans Wennborg
Date: 2022-10-07T12:24:19+02:00
New Revision: c9b771b9fc2f17cccd9ccbf8f1d52e2642679b8a

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

LOG: Keep inherited dllimport/export attrs for explicit specialization of class 
template member functions

Previously we were stripping these normally inherited attributes during
explicit specialization. However for class template member functions
(but not function templates), MSVC keeps the attribute.

This makes Clang match that behavior, and fixes GitHub issue #54717

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

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/SemaDecl.cpp
clang/lib/Sema/SemaTemplate.cpp
clang/test/CodeGenCXX/dllexport-members.cpp
clang/test/CodeGenCXX/dllimport-members.cpp
clang/test/SemaCXX/dllexport.cpp
clang/test/SemaCXX/dllimport.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index b9a5e0507e35e..7dc779ccc2e24 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -86,6 +86,36 @@ code bases.
   typedef char int8_a16 __attribute__((aligned(16)));
   int8_a16 array[4]; // Now diagnosed as the element size not being a multiple 
of the array alignment.
 
+- When compiling for Windows in MSVC compatibility mode (for example by using
+  clang-cl), the compiler will now propagate dllimport/export declspecs in
+  explicit specializations of class template member functions (`Issue 54717
+  `_):
+
+  .. code-block:: c++
+
+template  struct __declspec(dllexport) S {
+  void f();
+};
+template<> void S::f() {}  // clang-cl will now dllexport this.
+
+  This matches what MSVC does, so it improves compatibility, but it can also
+  cause errors for code which clang-cl would previously accept, for example:
+
+  .. code-block:: c++
+
+template  struct __declspec(dllexport) S {
+  void f();
+};
+template<> void S::f() = delete;  // Error: cannot delete dllexport 
function.
+
+  .. code-block:: c++
+
+template  struct __declspec(dllimport) S {
+  void f();
+};
+template<> void S::f() {};  // Error: cannot define dllimport 
function.
+
+  These errors also match MSVC's behavior.
 
 What's New in Clang |release|?
 ==

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 0c7b64c7a94b4..8a721d45e78f0 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -3469,6 +3469,8 @@ def warn_attribute_dll_redeclaration : Warning<
   InGroup>;
 def err_attribute_dllimport_function_definition : Error<
   "dllimport cannot be applied to non-inline function definition">;
+def err_attribute_dllimport_function_specialization_definition : Error<
+  "cannot define non-inline dllimport template specialization">;
 def err_attribute_dll_deleted : Error<
   "attribute %q0 cannot be applied to a deleted function">;
 def err_attribute_dllimport_data_definition : Error<

diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 60b8d1c3c59c7..760cf7fd805cc 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -7041,13 +7041,24 @@ static void checkDLLAttributeRedeclaration(Sema &S, 
NamedDecl *OldDecl,
   (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
   !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
 if (IsMicrosoftABI && IsDefinition) {
-  S.Diag(NewDecl->getLocation(),
- diag::warn_redeclaration_without_import_attribute)
-  << NewDecl;
-  S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
-  NewDecl->dropAttr();
-  NewDecl->addAttr(
-  DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
+  if (IsSpecialization) {
+S.Diag(
+NewDecl->getLocation(),
+diag::err_attribute_dllimport_function_specialization_definition);
+S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
+NewDecl->dropAttr();
+  } else {
+S.Diag(NewDecl->getLocation(),
+   diag::warn_redeclaration_without_import_attribute)
+<< NewDecl;
+S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
+NewDecl->dropAttr();
+NewDecl->addAttr(DLLExportAttr::CreateImplicit(
+S.Context, NewImportAttr->getRange()));
+  }
+} else if (IsMicrosoftABI && IsSpecialization) {
+  assert(!IsDefinition);
+  // MSVC allows this. Keep the inherited attribute.
 } e

[PATCH] D134859: [clang][Interp] Implement basic support for floating point values

2022-10-07 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 466027.

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

https://reviews.llvm.org/D134859

Files:
  clang/lib/AST/CMakeLists.txt
  clang/lib/AST/Interp/Boolean.h
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/lib/AST/Interp/ByteCodeExprGen.h
  clang/lib/AST/Interp/Context.cpp
  clang/lib/AST/Interp/Descriptor.cpp
  clang/lib/AST/Interp/Floating.cpp
  clang/lib/AST/Interp/Floating.h
  clang/lib/AST/Interp/Integral.h
  clang/lib/AST/Interp/Interp.cpp
  clang/lib/AST/Interp/Interp.h
  clang/lib/AST/Interp/InterpStack.h
  clang/lib/AST/Interp/Opcodes.td
  clang/lib/AST/Interp/PrimType.h
  clang/lib/AST/Interp/Primitives.h
  clang/test/AST/Interp/literals.cpp

Index: clang/test/AST/Interp/literals.cpp
===
--- clang/test/AST/Interp/literals.cpp
+++ clang/test/AST/Interp/literals.cpp
@@ -270,3 +270,31 @@
   static_assert((1337 & -1) == 1337, "");
   static_assert((0 & gimme(12)) == 0, "");
 };
+
+namespace floats {
+  constexpr int i = 2;
+  constexpr float f = 1.0f;
+  static_assert(f == 1.0f, "");
+
+  constexpr float f2 = 1u * f;
+  static_assert(f2 == 1.0f, "");
+
+  static_assert(1.0f + 3u == 4, "");
+  static_assert(4.0f / 1.0f == 4, "");
+  static_assert(10.0f * false == 0, "");
+
+  constexpr float floats[] = {1.0f, 2.0f, 3.0f, 4.0f};
+
+  constexpr float m = 5.0f / 0.0f; // ref-error {{must be initialized by a constant expression}} \
+   // ref-note {{division by zero}} \
+   // expected-error {{must be initialized by a constant expression}} \
+   // expected-note {{division by zero}}
+
+  static_assert(~2.0f == 3, ""); // ref-error {{invalid argument type 'float' to unary expression}} \
+ // expected-error {{invalid argument type 'float' to unary expression}}
+
+  /// Initialized by a double.
+  constexpr float df = 0.0;
+  /// The other way around.
+  constexpr double fd = 0.0f;
+};
Index: clang/lib/AST/Interp/Primitives.h
===
--- /dev/null
+++ clang/lib/AST/Interp/Primitives.h
@@ -0,0 +1,36 @@
+//===-- Primitives.h - Types for the constexpr VM ---*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// Utilities and helper functions for all primitive types:
+//  - Integral
+//  - Floating
+//  - Boolean
+//
+//===--===//
+
+#ifndef LLVM_CLANG_AST_INTERP_PRIMITIVES_H
+#define LLVM_CLANG_AST_INTERP_PRIMITIVES_H
+
+#include "clang/AST/ComparisonCategories.h"
+
+namespace clang {
+namespace interp {
+
+/// Helper to compare two comparable types.
+template  ComparisonCategoryResult Compare(const T &X, const T &Y) {
+  if (X < Y)
+return ComparisonCategoryResult::Less;
+  if (X > Y)
+return ComparisonCategoryResult::Greater;
+  return ComparisonCategoryResult::Equal;
+}
+
+} // namespace interp
+} // namespace clang
+
+#endif
Index: clang/lib/AST/Interp/PrimType.h
===
--- clang/lib/AST/Interp/PrimType.h
+++ clang/lib/AST/Interp/PrimType.h
@@ -13,11 +13,12 @@
 #ifndef LLVM_CLANG_AST_INTERP_TYPE_H
 #define LLVM_CLANG_AST_INTERP_TYPE_H
 
+#include "Boolean.h"
+#include "Floating.h"
+#include "Integral.h"
 #include 
 #include 
 #include 
-#include "Boolean.h"
-#include "Integral.h"
 
 namespace clang {
 namespace interp {
@@ -35,6 +36,7 @@
   PT_Sint64,
   PT_Uint64,
   PT_Bool,
+  PT_Float,
   PT_Ptr,
 };
 
@@ -48,6 +50,7 @@
 template <> struct PrimConv { using T = Integral<32, false>; };
 template <> struct PrimConv { using T = Integral<64, true>; };
 template <> struct PrimConv { using T = Integral<64, false>; };
+template <> struct PrimConv { using T = Floating; };
 template <> struct PrimConv { using T = Boolean; };
 template <> struct PrimConv { using T = Pointer; };
 
@@ -70,6 +73,7 @@
   case PT_Uint32:
   case PT_Sint64:
   case PT_Uint64:
+  case PT_Float:
 return true;
   default:
 return false;
@@ -94,6 +98,7 @@
   TYPE_SWITCH_CASE(PT_Uint32, B)   \
   TYPE_SWITCH_CASE(PT_Sint64, B)   \
   TYPE_SWITCH_CASE(PT_Uint64, B)   \
+  TYPE_SWITCH_CASE(PT_Float, B)\
   TYPE_SWITCH_CASE(PT_Bool, B) \
   TYPE_SWITCH_CASE(PT_Ptr, B)  \
 }  \

[PATCH] D134859: [clang][Interp] Implement basic support for floating point values

2022-10-07 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 466031.

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

https://reviews.llvm.org/D134859

Files:
  clang/lib/AST/CMakeLists.txt
  clang/lib/AST/Interp/Boolean.h
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/lib/AST/Interp/ByteCodeExprGen.h
  clang/lib/AST/Interp/Context.cpp
  clang/lib/AST/Interp/Descriptor.cpp
  clang/lib/AST/Interp/Floating.cpp
  clang/lib/AST/Interp/Floating.h
  clang/lib/AST/Interp/Integral.h
  clang/lib/AST/Interp/Interp.cpp
  clang/lib/AST/Interp/Interp.h
  clang/lib/AST/Interp/InterpStack.h
  clang/lib/AST/Interp/Opcodes.td
  clang/lib/AST/Interp/PrimType.h
  clang/lib/AST/Interp/Primitives.h
  clang/test/AST/Interp/literals.cpp

Index: clang/test/AST/Interp/literals.cpp
===
--- clang/test/AST/Interp/literals.cpp
+++ clang/test/AST/Interp/literals.cpp
@@ -270,3 +270,33 @@
   static_assert((1337 & -1) == 1337, "");
   static_assert((0 & gimme(12)) == 0, "");
 };
+
+namespace floats {
+  constexpr int i = 2;
+  constexpr float f = 1.0f;
+  static_assert(f == 1.0f, "");
+
+  constexpr float f2 = 1u * f;
+  static_assert(f2 == 1.0f, "");
+
+  static_assert(1.0f + 3u == 4, "");
+  static_assert(4.0f / 1.0f == 4, "");
+  static_assert(10.0f * false == 0, "");
+
+  constexpr float floats[] = {1.0f, 2.0f, 3.0f, 4.0f};
+
+  constexpr float m = 5.0f / 0.0f; // ref-error {{must be initialized by a constant expression}} \
+   // ref-note {{division by zero}} \
+   // expected-error {{must be initialized by a constant expression}} \
+   // expected-note {{division by zero}}
+
+  static_assert(~2.0f == 3, ""); // ref-error {{invalid argument type 'float' to unary expression}} \
+ // expected-error {{invalid argument type 'float' to unary expression}}
+
+  /// Initialized by a double.
+  constexpr float df = 0.0;
+  /// The other way around.
+  constexpr double fd = 0.0f;
+
+  static_assert(0.0f == -0.0f, "");
+};
Index: clang/lib/AST/Interp/Primitives.h
===
--- /dev/null
+++ clang/lib/AST/Interp/Primitives.h
@@ -0,0 +1,36 @@
+//===-- Primitives.h - Types for the constexpr VM ---*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// Utilities and helper functions for all primitive types:
+//  - Integral
+//  - Floating
+//  - Boolean
+//
+//===--===//
+
+#ifndef LLVM_CLANG_AST_INTERP_PRIMITIVES_H
+#define LLVM_CLANG_AST_INTERP_PRIMITIVES_H
+
+#include "clang/AST/ComparisonCategories.h"
+
+namespace clang {
+namespace interp {
+
+/// Helper to compare two comparable types.
+template  ComparisonCategoryResult Compare(const T &X, const T &Y) {
+  if (X < Y)
+return ComparisonCategoryResult::Less;
+  if (X > Y)
+return ComparisonCategoryResult::Greater;
+  return ComparisonCategoryResult::Equal;
+}
+
+} // namespace interp
+} // namespace clang
+
+#endif
Index: clang/lib/AST/Interp/PrimType.h
===
--- clang/lib/AST/Interp/PrimType.h
+++ clang/lib/AST/Interp/PrimType.h
@@ -13,11 +13,12 @@
 #ifndef LLVM_CLANG_AST_INTERP_TYPE_H
 #define LLVM_CLANG_AST_INTERP_TYPE_H
 
+#include "Boolean.h"
+#include "Floating.h"
+#include "Integral.h"
 #include 
 #include 
 #include 
-#include "Boolean.h"
-#include "Integral.h"
 
 namespace clang {
 namespace interp {
@@ -35,6 +36,7 @@
   PT_Sint64,
   PT_Uint64,
   PT_Bool,
+  PT_Float,
   PT_Ptr,
 };
 
@@ -48,6 +50,7 @@
 template <> struct PrimConv { using T = Integral<32, false>; };
 template <> struct PrimConv { using T = Integral<64, true>; };
 template <> struct PrimConv { using T = Integral<64, false>; };
+template <> struct PrimConv { using T = Floating; };
 template <> struct PrimConv { using T = Boolean; };
 template <> struct PrimConv { using T = Pointer; };
 
@@ -70,6 +73,7 @@
   case PT_Uint32:
   case PT_Sint64:
   case PT_Uint64:
+  case PT_Float:
 return true;
   default:
 return false;
@@ -94,6 +98,7 @@
   TYPE_SWITCH_CASE(PT_Uint32, B)   \
   TYPE_SWITCH_CASE(PT_Sint64, B)   \
   TYPE_SWITCH_CASE(PT_Uint64, B)   \
+  TYPE_SWITCH_CASE(PT_Float, B)\
   TYPE_SWITCH_CASE(PT_Bool, B) \
   TYPE_SWITCH_CASE(PT_Ptr, B)  \
 } 

[PATCH] D135439: Keep configuration file search directories in ExpansionContext. NFC

2022-10-07 Thread Serge Pavlov via Phabricator via cfe-commits
sepavloff created this revision.
sepavloff added reviewers: MaskRay, mgorny.
Herald added subscribers: StephenFan, hiraditya.
Herald added a project: All.
sepavloff requested review of this revision.
Herald added projects: clang, LLVM.
Herald added a subscriber: llvm-commits.

Class ExpansionContext encapsulates options for search and expansion of
response files, including configuration files. With this change the
directories which are searched for configuration files are also stored
in ExpansionContext.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D135439

Files:
  clang/include/clang/Driver/Driver.h
  clang/lib/Driver/Driver.cpp
  llvm/include/llvm/Support/CommandLine.h
  llvm/lib/Support/CommandLine.cpp

Index: llvm/lib/Support/CommandLine.cpp
===
--- llvm/lib/Support/CommandLine.cpp
+++ llvm/lib/Support/CommandLine.cpp
@@ -1350,6 +1350,43 @@
 ExpansionContext::ExpansionContext(BumpPtrAllocator &A, TokenizerCallback T)
 : Saver(A), Tokenizer(T), FS(vfs::getRealFileSystem().get()) {}
 
+bool ExpansionContext::findConfigFile(StringRef FileName,
+  std::string &FilePath) {
+  SmallString<128> CfgFilePath;
+  const auto FileExists = [this](SmallString<128> Path) -> bool {
+auto Status = FS->status(Path);
+return Status &&
+   Status->getType() == llvm::sys::fs::file_type::regular_file;
+  };
+
+  // If file name contains directory separator, treat it as a path to
+  // configuration file.
+  if (llvm::sys::path::has_parent_path(FileName)) {
+CfgFilePath = FileName;
+if (llvm::sys::path::is_relative(FileName) && FS->makeAbsolute(CfgFilePath))
+  return false;
+if (!FileExists(CfgFilePath))
+  return false;
+FilePath = CfgFilePath.str();
+return true;
+  }
+
+  // Look for the file in search directories.
+  for (const StringRef &Dir : SearchDirs) {
+if (Dir.empty())
+  continue;
+CfgFilePath.assign(Dir);
+llvm::sys::path::append(CfgFilePath, FileName);
+llvm::sys::path::native(CfgFilePath);
+if (FileExists(CfgFilePath)) {
+  FilePath = CfgFilePath.str();
+  return true;
+}
+  }
+
+  return false;
+}
+
 bool ExpansionContext::readConfigFile(StringRef CfgFile,
   SmallVectorImpl &Argv) {
   SmallString<128> AbsPath;
Index: llvm/include/llvm/Support/CommandLine.h
===
--- llvm/include/llvm/Support/CommandLine.h
+++ llvm/include/llvm/Support/CommandLine.h
@@ -2081,6 +2081,9 @@
   /// current directory is used instead.
   StringRef CurrentDir;
 
+  /// Directories used for search of config files.
+  ArrayRef SearchDirs;
+
   /// True if names of nested response files must be resolved relative to
   /// including file.
   bool RelativeNames = false;
@@ -2113,11 +2116,27 @@
 return *this;
   }
 
+  ExpansionContext &setSearchDirs(ArrayRef X) {
+SearchDirs = X;
+return *this;
+  }
+
   ExpansionContext &setVFS(vfs::FileSystem *X) {
 FS = X;
 return *this;
   }
 
+  /// Looks for the specified configuration file.
+  ///
+  /// \param[in]  FileName Name of the file to search for.
+  /// \param[out] FilePath File absolute path, if it was found.
+  /// \return True if file was found.
+  ///
+  /// If the specified file name contains a directory separator, it is searched
+  /// for by its absolute path. Otherwise looks for file sequentially in
+  /// directories specified by SearchDirs field.
+  bool findConfigFile(StringRef FileName, std::string &FilePath);
+
   /// Reads command line options from the given configuration file.
   ///
   /// \param [in] CfgFile Path to configuration file.
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -909,35 +909,6 @@
   //
 }
 
-/// Looks the given directories for the specified file.
-///
-/// \param[out] FilePath File path, if the file was found.
-/// \param[in]  Dirs Directories used for the search.
-/// \param[in]  FileName Name of the file to search for.
-/// \return True if file was found.
-///
-/// Looks for file specified by FileName sequentially in directories specified
-/// by Dirs.
-///
-static bool searchForFile(SmallVectorImpl &FilePath,
-  ArrayRef Dirs, StringRef FileName,
-  llvm::vfs::FileSystem &FS) {
-  SmallString<128> WPath;
-  for (const StringRef &Dir : Dirs) {
-if (Dir.empty())
-  continue;
-WPath.clear();
-llvm::sys::path::append(WPath, Dir, FileName);
-llvm::sys::path::native(WPath);
-auto Status = FS.status(WPath);
-if (Status && Status->getType() == llvm::sys::fs::file_type::regular_file) {
-  FilePath = std::move(WPath);
-  return true;
-}
-  }
-  return false;
-}
-
 static void appendOneArg(InputArgList &Args, const Arg *Opt,
   

[PATCH] D135440: [SourceManager] Speedup getFileIDLocal with a separate Offset Table.

2022-10-07 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added reviewers: sammccall, nickdesaulniers.
Herald added a subscriber: kadircet.
Herald added a project: All.
hokein requested review of this revision.
Herald added a subscriber: ilya-biryukov.
Herald added a project: clang.

This patch introduces a separate Offset array in SourceManager, it is redundant
and merely used for searching. This "AOS vs. SOA" optimization give us a large
memory locality win, see the data below.

This is a low-hanging fruit optimization (without significantly changing the
SlocEntry and its underlying storge in SourceManager). The sad bit is thatit
increases SourceManager memory usage, however it is a small fraction (< 10%) of
clang AST memory usage, which I think it is mostly negligible.

getFileIDLoaded is excluded in this patch, it is trickier due to the lazy load 
of
SLocEntry, unclear we will gain as much speedup as the local one.

Speedup:

  Linux kernel: getFileIDLocal overhead is reduced to 1.66% (~30% saving)

Memory usage in bytes (AST built in clangd):

  SemaExpr.cpp:  149529494 -> 149502874
  FindTarget.cpp  83177157 ->  83177569


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D135440

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


Index: clang/lib/Basic/SourceManager.cpp
===
--- clang/lib/Basic/SourceManager.cpp
+++ clang/lib/Basic/SourceManager.cpp
@@ -336,6 +336,7 @@
 void SourceManager::clearIDTables() {
   MainFileID = FileID();
   LocalSLocEntryTable.clear();
+  LocalLocOffsetTable.clear();
   LoadedSLocEntryTable.clear();
   SLocEntryLoaded.clear();
   LastLineNoFileIDQuery = FileID();
@@ -618,6 +619,7 @@
   LocalSLocEntryTable.push_back(
   SLocEntry::get(NextLocalOffset,
  FileInfo::get(IncludePos, File, FileCharacter, 
Filename)));
+  LocalLocOffsetTable.push_back(NextLocalOffset);
   // We do a +1 here because we want a SourceLocation that means "the end of 
the
   // file", e.g. for the "no newline at the end of the file" diagnostic.
   NextLocalOffset += FileSize + 1;
@@ -669,6 +671,7 @@
 return SourceLocation::getMacroLoc(LoadedOffset);
   }
   LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info));
+  LocalLocOffsetTable.push_back(NextLocalOffset);
   assert(NextLocalOffset + Length + 1 > NextLocalOffset &&
  NextLocalOffset + Length + 1 <= CurrentLoadedOffset &&
  "Ran out of source locations!");
@@ -799,10 +802,10 @@
   // SLocOffset.
   unsigned LessIndex = 0;
   // upper bound of the search range.
-  unsigned GreaterIndex = LocalSLocEntryTable.size();
+  unsigned GreaterIndex = LocalLocOffsetTable.size();
   if (LastFileIDLookup.ID >= 0) {
 // Use the LastFileIDLookup to prune the search space.
-if (LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset)
+if (LocalLocOffsetTable[LastFileIDLookup.ID] < SLocOffset)
   LessIndex = LastFileIDLookup.ID;
 else
   GreaterIndex = LastFileIDLookup.ID;
@@ -812,8 +815,8 @@
   unsigned NumProbes = 0;
   while (true) {
 --GreaterIndex;
-assert(GreaterIndex < LocalSLocEntryTable.size());
-if (LocalSLocEntryTable[GreaterIndex].getOffset() <= SLocOffset) {
+assert(GreaterIndex < LocalLocOffsetTable.size());
+if (LocalLocOffsetTable[GreaterIndex] <= SLocOffset) {
   FileID Res = FileID::get(int(GreaterIndex));
   // Remember it.  We have good locality across FileID lookups.
   LastFileIDLookup = Res;
@@ -827,8 +830,7 @@
   NumProbes = 0;
   while (true) {
 unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex;
-SourceLocation::UIntTy MidOffset =
-getLocalSLocEntry(MiddleIndex).getOffset();
+SourceLocation::UIntTy MidOffset = LocalLocOffsetTable[MiddleIndex];
 
 ++NumProbes;
 
@@ -840,8 +842,8 @@
 }
 
 // If the middle index contains the value, succeed and return.
-if (MiddleIndex + 1 == LocalSLocEntryTable.size() ||
-SLocOffset < getLocalSLocEntry(MiddleIndex + 1).getOffset()) {
+if (MiddleIndex + 1 == LocalLocOffsetTable.size() ||
+SLocOffset < LocalLocOffsetTable[MiddleIndex + 1]) {
   FileID Res = FileID::get(MiddleIndex);
 
   // Remember it.  We have good locality across FileID lookups.
@@ -2254,6 +2256,7 @@
 size_t SourceManager::getDataStructureSizes() const {
   size_t size = llvm::capacity_in_bytes(MemBufferInfos)
 + llvm::capacity_in_bytes(LocalSLocEntryTable)
++ llvm::capacity_in_bytes(LocalLocOffsetTable)
 + llvm::capacity_in_bytes(LoadedSLocEntryTable)
 + llvm::capacity_in_bytes(SLocEntryLoaded)
 + llvm::capacity_in_bytes(FileInfos);
Index: clang/include/clang/Basic/SourceManager.h
===
--- clang/include/clang/Basic/SourceManager.h
+++ clang/include/clang/Basic/SourceManager.h
@@ -692,6 +692,9 @@
   /// Positive FileIDs are indexes into this table. Entry 0 indicates an 

[PATCH] D135367: [clang-tidy] Dump effective diagnostics level in YAML output

2022-10-07 Thread Dmitry Polukhin via Phabricator via cfe-commits
DmitryPolukhin updated this revision to Diff 466037.
DmitryPolukhin added a comment.

Rebase


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135367

Files:
  clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
  clang-tools-extra/test/clang-tidy/infrastructure/export-diagnostics.cpp


Index: clang-tools-extra/test/clang-tidy/infrastructure/export-diagnostics.cpp
===
--- clang-tools-extra/test/clang-tidy/infrastructure/export-diagnostics.cpp
+++ clang-tools-extra/test/clang-tidy/infrastructure/export-diagnostics.cpp
@@ -1,5 +1,5 @@
 // RUN: grep -Ev "// *[A-Z-]+:" %s > %t-input.cpp
-// RUN: not clang-tidy %t-input.cpp 
-checks='-*,google-explicit-constructor,clang-diagnostic-missing-prototypes,clang-diagnostic-zero-length-array'
 -export-fixes=%t.yaml -- -Wmissing-prototypes -Wzero-length-array > %t.msg 2>&1
+// RUN: not clang-tidy %t-input.cpp 
-checks='-*,google-explicit-constructor,clang-diagnostic-missing-prototypes,clang-diagnostic-zero-length-array'
 --warnings-as-errors='clang-diagnostic-missing-prototypes' 
-export-fixes=%t.yaml -- -Wmissing-prototypes -Wzero-length-array > %t.msg 2>&1
 // RUN: FileCheck -input-file=%t.msg -check-prefix=CHECK-MESSAGES %s 
-implicit-check-not='{{warning|error|note}}:'
 // RUN: FileCheck -input-file=%t.yaml -check-prefix=CHECK-YAML %s
 #define X(n) void n ## n() {}
@@ -12,7 +12,7 @@
   member;
 };
 
-// CHECK-MESSAGES: -input.cpp:2:1: warning: no previous prototype for function 
'ff' [clang-diagnostic-missing-prototypes]
+// CHECK-MESSAGES: -input.cpp:2:1: error: no previous prototype for function 
'ff' [clang-diagnostic-missing-prototypes,-warnings-as-errors]
 // CHECK-MESSAGES: -input.cpp:1:19: note: expanded from macro 'X'
 // CHECK-MESSAGES: {{^}}note: expanded from here{{$}}
 // CHECK-MESSAGES: -input.cpp:2:1: note: declare 'static' if the function is 
not intended to be used outside of this translation unit
@@ -52,7 +52,7 @@
 // CHECK-YAML-NEXT: FilePath:'{{.*}}-input.cpp'
 // CHECK-YAML-NEXT: FileOffset:  13
 // CHECK-YAML-NEXT: Replacements:[]
-// CHECK-YAML-NEXT: Level:   Warning
+// CHECK-YAML-NEXT: Level:   Error
 // CHECK-YAML-NEXT: BuildDirectory:  '{{.*}}'
 // CHECK-YAML-NEXT:   - DiagnosticName:  clang-diagnostic-error
 // CHECK-YAML-NEXT: DiagnosticMessage:
Index: clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
===
--- clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
+++ clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
@@ -403,6 +403,8 @@
 
 bool IsWarningAsError = DiagLevel == DiagnosticsEngine::Warning &&
 Context.treatAsError(CheckName);
+if (IsWarningAsError)
+  Level = ClangTidyError::Error;
 Errors.emplace_back(CheckName, Level, Context.getCurrentBuildDirectory(),
 IsWarningAsError);
   }


Index: clang-tools-extra/test/clang-tidy/infrastructure/export-diagnostics.cpp
===
--- clang-tools-extra/test/clang-tidy/infrastructure/export-diagnostics.cpp
+++ clang-tools-extra/test/clang-tidy/infrastructure/export-diagnostics.cpp
@@ -1,5 +1,5 @@
 // RUN: grep -Ev "// *[A-Z-]+:" %s > %t-input.cpp
-// RUN: not clang-tidy %t-input.cpp -checks='-*,google-explicit-constructor,clang-diagnostic-missing-prototypes,clang-diagnostic-zero-length-array' -export-fixes=%t.yaml -- -Wmissing-prototypes -Wzero-length-array > %t.msg 2>&1
+// RUN: not clang-tidy %t-input.cpp -checks='-*,google-explicit-constructor,clang-diagnostic-missing-prototypes,clang-diagnostic-zero-length-array' --warnings-as-errors='clang-diagnostic-missing-prototypes' -export-fixes=%t.yaml -- -Wmissing-prototypes -Wzero-length-array > %t.msg 2>&1
 // RUN: FileCheck -input-file=%t.msg -check-prefix=CHECK-MESSAGES %s -implicit-check-not='{{warning|error|note}}:'
 // RUN: FileCheck -input-file=%t.yaml -check-prefix=CHECK-YAML %s
 #define X(n) void n ## n() {}
@@ -12,7 +12,7 @@
   member;
 };
 
-// CHECK-MESSAGES: -input.cpp:2:1: warning: no previous prototype for function 'ff' [clang-diagnostic-missing-prototypes]
+// CHECK-MESSAGES: -input.cpp:2:1: error: no previous prototype for function 'ff' [clang-diagnostic-missing-prototypes,-warnings-as-errors]
 // CHECK-MESSAGES: -input.cpp:1:19: note: expanded from macro 'X'
 // CHECK-MESSAGES: {{^}}note: expanded from here{{$}}
 // CHECK-MESSAGES: -input.cpp:2:1: note: declare 'static' if the function is not intended to be used outside of this translation unit
@@ -52,7 +52,7 @@
 // CHECK-YAML-NEXT: FilePath:'{{.*}}-input.cpp'
 // CHECK-YAML-NEXT: FileOffset:  13
 // CHECK-YAML-NEXT: Replacements:[]
-// CHECK-YAML-NEXT: Level:   Warning
+// CHECK-YAML-N

[PATCH] D135361: [clang][Interp] Implement bitwise Or operations

2022-10-07 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135361

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


[PATCH] D135392: Use PoisonValue in vector BIs [NFC]

2022-10-07 Thread Nuno Lopes via Phabricator via cfe-commits
nlopes accepted this revision.
nlopes 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/D135392/new/

https://reviews.llvm.org/D135392

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


[PATCH] D129755: Thread safety analysis: Support copy-elided production of scoped capabilities through arbitrary calls

2022-10-07 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/lib/Analysis/ThreadSafety.cpp:1789
+  auto inserted = ConstructedObjects.insert({Exp, Placeholder.first});
+  assert(inserted.second && "Are we visiting the same expression again?");
+  if (isa(Exp))

aaronpuchert wrote:
> chapuni wrote:
> > 'inserted' is used only here.
> Correct, is that an issue? Perhaps `-Wunused-variable` in Release builds?
> 
> Otherwise I believe it's correct—we don't need the iterator and we should 
> generally not insert expressions twice, hence the assertion.
Yeah, that's the trouble -- this breaks release builds using -Werror. You 
should add `[[maybe_unused]]` to the declaration (as an NFC commit).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129755

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


[clang] 14e2592 - [clang][CodeGen] Use poison instead of undef as placeholder in ARM builtins [NFC]

2022-10-07 Thread Nuno Lopes via cfe-commits

Author: Manuel Brito
Date: 2022-10-07T12:50:59+01:00
New Revision: 14e2592ff6112d1869ba1533d058822200162bf1

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

LOG: [clang][CodeGen] Use poison instead of undef as placeholder in ARM 
builtins [NFC]

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

Added: 


Modified: 
clang/lib/CodeGen/CGBuiltin.cpp
clang/test/CodeGen/PowerPC/builtins-ppc-int128.c
clang/test/CodeGen/aarch64-bf16-ldst-intrinsics.c
clang/test/CodeGen/aarch64-neon-intrinsics.c
clang/test/CodeGen/aarch64-neon-ldst-one.c
clang/test/CodeGen/aarch64-neon-scalar-x-indexed-elem.c
clang/test/CodeGen/aarch64-sve-intrinsics/acle_sve_dupq-bfloat.c
clang/test/CodeGen/aarch64-sve-intrinsics/acle_sve_dupq.c
clang/test/CodeGen/arm-mve-intrinsics/vld24.c
clang/test/CodeGen/arm_neon_intrinsics.c

Removed: 




diff  --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 786ed8c5935f9..81fa7b27541c5 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -6861,7 +6861,7 @@ Value *CodeGenFunction::EmitCommonNeonBuiltinExpr(
   }
   case NEON::BI__builtin_neon_vld1_dup_v:
   case NEON::BI__builtin_neon_vld1q_dup_v: {
-Value *V = UndefValue::get(Ty);
+Value *V = PoisonValue::get(Ty);
 PtrOp0 = Builder.CreateElementBitCast(PtrOp0, VTy->getElementType());
 LoadInst *Ld = Builder.CreateLoad(PtrOp0);
 llvm::Constant *CI = ConstantInt::get(SizeTy, 0);
@@ -8303,7 +8303,7 @@ Value *CodeGenFunction::EmitARMMVEBuiltinExpr(unsigned 
BuiltinID,
 
 Function *F = CGM.getIntrinsic(IRIntr, makeArrayRef(Tys));
 Value *LoadResult = Builder.CreateCall(F, Ops);
-Value *MvecOut = UndefValue::get(MvecLType);
+Value *MvecOut = PoisonValue::get(MvecLType);
 for (unsigned i = 0; i < NumVectors; ++i) {
   Value *Vec = Builder.CreateExtractValue(LoadResult, i);
   MvecOut = Builder.CreateInsertValue(MvecOut, Vec, {0, i});
@@ -8518,7 +8518,7 @@ static Value *EmitAArch64TblBuiltinExpr(CodeGenFunction 
&CGF, unsigned BuiltinID
 Value *CodeGenFunction::vectorWrapScalar16(Value *Op) {
   auto *VTy = llvm::FixedVectorType::get(Int16Ty, 4);
   Op = Builder.CreateBitCast(Op, Int16Ty);
-  Value *V = UndefValue::get(VTy);
+  Value *V = PoisonValue::get(VTy);
   llvm::Constant *CI = ConstantInt::get(SizeTy, 0);
   Op = Builder.CreateInsertElement(V, Op, CI);
   return Op;
@@ -11692,7 +11692,7 @@ Value *CodeGenFunction::EmitAArch64BuiltinExpr(unsigned 
BuiltinID,
   }
   case NEON::BI__builtin_neon_vld1_dup_v:
   case NEON::BI__builtin_neon_vld1q_dup_v: {
-Value *V = UndefValue::get(Ty);
+Value *V = PoisonValue::get(Ty);
 Ty = llvm::PointerType::getUnqual(VTy->getElementType());
 Ops[0] = Builder.CreateBitCast(Ops[0], Ty);
 Ops[0] = Builder.CreateAlignedLoad(VTy->getElementType(), Ops[0],
@@ -12090,7 +12090,7 @@ BuildVector(ArrayRef Ops) {
   }
 
   // Otherwise, insertelement the values to build the vector.
-  Value *Result = llvm::UndefValue::get(
+  Value *Result = llvm::PoisonValue::get(
   llvm::FixedVectorType::get(Ops[0]->getType(), Ops.size()));
 
   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
@@ -16143,10 +16143,10 @@ Value *CodeGenFunction::EmitPPCBuiltinExpr(unsigned 
BuiltinID,
 Value *Op0 = EmitScalarExpr(E->getArg(0));
 Value *Op1 = EmitScalarExpr(E->getArg(1));
 bool isLittleEndian = getTarget().isLittleEndian();
-Value *UndefValue =
-llvm::UndefValue::get(llvm::FixedVectorType::get(Op0->getType(), 2));
+Value *PoisonValue =
+llvm::PoisonValue::get(llvm::FixedVectorType::get(Op0->getType(), 2));
 Value *Res = Builder.CreateInsertElement(
-UndefValue, Op0, (uint64_t)(isLittleEndian ? 1 : 0));
+PoisonValue, Op0, (uint64_t)(isLittleEndian ? 1 : 0));
 Res = Builder.CreateInsertElement(Res, Op1,
   (uint64_t)(isLittleEndian ? 0 : 1));
 return Builder.CreateBitCast(Res, ConvertType(E->getType()));

diff  --git a/clang/test/CodeGen/PowerPC/builtins-ppc-int128.c 
b/clang/test/CodeGen/PowerPC/builtins-ppc-int128.c
index 52d705589a893..2b8221c725e66 100644
--- a/clang/test/CodeGen/PowerPC/builtins-ppc-int128.c
+++ b/clang/test/CodeGen/PowerPC/builtins-ppc-int128.c
@@ -15,11 +15,11 @@ void testVectorInt128Pack(){
 // CHECK-LABEL: testVectorInt128Pack
 // CHECK-LABEL-LE: testVectorInt128Pack
   res_vslll = __builtin_pack_vector_int128(aull[0], aull[1]);
-// CHECK: %[[V1:[0-9]+]] = insertelement <2 x i64> undef, i64 %{{[0-9]+}}, i64 0
+// CHECK: %[[V1:[0-9]+]] = insertelement <2 x i64> poison, i64 %{{[0-9]+}}, 
i64 0
 // CHECK-NEXT: %[[V2:[0-9]+]] = insertelement <2 x i64> %[[V1]], i64 
%{{[0-9]+}}, i64 1
 // CHECK-NEXT:  bitcast <2 x i64> %[[V2]] to

[PATCH] D135392: Use PoisonValue in vector BIs [NFC]

2022-10-07 Thread Nuno Lopes via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG14e2592ff611: [clang][CodeGen] Use poison instead of undef 
as placeholder in ARM builtins… (authored by ManuelJBrito, committed by nlopes).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135392

Files:
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/test/CodeGen/PowerPC/builtins-ppc-int128.c
  clang/test/CodeGen/aarch64-bf16-ldst-intrinsics.c
  clang/test/CodeGen/aarch64-neon-intrinsics.c
  clang/test/CodeGen/aarch64-neon-ldst-one.c
  clang/test/CodeGen/aarch64-neon-scalar-x-indexed-elem.c
  clang/test/CodeGen/aarch64-sve-intrinsics/acle_sve_dupq-bfloat.c
  clang/test/CodeGen/aarch64-sve-intrinsics/acle_sve_dupq.c
  clang/test/CodeGen/arm-mve-intrinsics/vld24.c
  clang/test/CodeGen/arm_neon_intrinsics.c

Index: clang/test/CodeGen/arm_neon_intrinsics.c
===
--- clang/test/CodeGen/arm_neon_intrinsics.c
+++ clang/test/CodeGen/arm_neon_intrinsics.c
@@ -4077,7 +4077,7 @@
 
 // CHECK-LABEL: @test_vld1q_dup_u8(
 // CHECK:   [[TMP0:%.*]] = load i8, i8* %a, align 1
-// CHECK:   [[TMP1:%.*]] = insertelement <16 x i8> undef, i8 [[TMP0]], i32 0
+// CHECK:   [[TMP1:%.*]] = insertelement <16 x i8> poison, i8 [[TMP0]], i32 0
 // CHECK:   [[LANE:%.*]] = shufflevector <16 x i8> [[TMP1]], <16 x i8> [[TMP1]], <16 x i32> zeroinitializer
 // CHECK:   ret <16 x i8> [[LANE]]
 uint8x16_t test_vld1q_dup_u8(uint8_t const * a) {
@@ -4088,7 +4088,7 @@
 // CHECK:   [[TMP0:%.*]] = bitcast i16* %a to i8*
 // CHECK:   [[TMP1:%.*]] = bitcast i8* [[TMP0]] to i16*
 // CHECK:   [[TMP2:%.*]] = load i16, i16* [[TMP1]], align 2
-// CHECK:   [[TMP3:%.*]] = insertelement <8 x i16> undef, i16 [[TMP2]], i32 0
+// CHECK:   [[TMP3:%.*]] = insertelement <8 x i16> poison, i16 [[TMP2]], i32 0
 // CHECK:   [[LANE:%.*]] = shufflevector <8 x i16> [[TMP3]], <8 x i16> [[TMP3]], <8 x i32> zeroinitializer
 // CHECK:   ret <8 x i16> [[LANE]]
 uint16x8_t test_vld1q_dup_u16(uint16_t const * a) {
@@ -4099,7 +4099,7 @@
 // CHECK:   [[TMP0:%.*]] = bitcast i32* %a to i8*
 // CHECK:   [[TMP1:%.*]] = bitcast i8* [[TMP0]] to i32*
 // CHECK:   [[TMP2:%.*]] = load i32, i32* [[TMP1]], align 4
-// CHECK:   [[TMP3:%.*]] = insertelement <4 x i32> undef, i32 [[TMP2]], i32 0
+// CHECK:   [[TMP3:%.*]] = insertelement <4 x i32> poison, i32 [[TMP2]], i32 0
 // CHECK:   [[LANE:%.*]] = shufflevector <4 x i32> [[TMP3]], <4 x i32> [[TMP3]], <4 x i32> zeroinitializer
 // CHECK:   ret <4 x i32> [[LANE]]
 uint32x4_t test_vld1q_dup_u32(uint32_t const * a) {
@@ -4110,7 +4110,7 @@
 // CHECK:   [[TMP0:%.*]] = bitcast i64* %a to i8*
 // CHECK:   [[TMP1:%.*]] = bitcast i8* [[TMP0]] to i64*
 // CHECK:   [[TMP2:%.*]] = load i64, i64* [[TMP1]], align 4
-// CHECK:   [[TMP3:%.*]] = insertelement <2 x i64> undef, i64 [[TMP2]], i32 0
+// CHECK:   [[TMP3:%.*]] = insertelement <2 x i64> poison, i64 [[TMP2]], i32 0
 // CHECK:   [[LANE:%.*]] = shufflevector <2 x i64> [[TMP3]], <2 x i64> [[TMP3]], <2 x i32> zeroinitializer
 // CHECK:   ret <2 x i64> [[LANE]]
 uint64x2_t test_vld1q_dup_u64(uint64_t const * a) {
@@ -4119,7 +4119,7 @@
 
 // CHECK-LABEL: @test_vld1q_dup_s8(
 // CHECK:   [[TMP0:%.*]] = load i8, i8* %a, align 1
-// CHECK:   [[TMP1:%.*]] = insertelement <16 x i8> undef, i8 [[TMP0]], i32 0
+// CHECK:   [[TMP1:%.*]] = insertelement <16 x i8> poison, i8 [[TMP0]], i32 0
 // CHECK:   [[LANE:%.*]] = shufflevector <16 x i8> [[TMP1]], <16 x i8> [[TMP1]], <16 x i32> zeroinitializer
 // CHECK:   ret <16 x i8> [[LANE]]
 int8x16_t test_vld1q_dup_s8(int8_t const * a) {
@@ -4130,7 +4130,7 @@
 // CHECK:   [[TMP0:%.*]] = bitcast i16* %a to i8*
 // CHECK:   [[TMP1:%.*]] = bitcast i8* [[TMP0]] to i16*
 // CHECK:   [[TMP2:%.*]] = load i16, i16* [[TMP1]], align 2
-// CHECK:   [[TMP3:%.*]] = insertelement <8 x i16> undef, i16 [[TMP2]], i32 0
+// CHECK:   [[TMP3:%.*]] = insertelement <8 x i16> poison, i16 [[TMP2]], i32 0
 // CHECK:   [[LANE:%.*]] = shufflevector <8 x i16> [[TMP3]], <8 x i16> [[TMP3]], <8 x i32> zeroinitializer
 // CHECK:   ret <8 x i16> [[LANE]]
 int16x8_t test_vld1q_dup_s16(int16_t const * a) {
@@ -4141,7 +4141,7 @@
 // CHECK:   [[TMP0:%.*]] = bitcast i32* %a to i8*
 // CHECK:   [[TMP1:%.*]] = bitcast i8* [[TMP0]] to i32*
 // CHECK:   [[TMP2:%.*]] = load i32, i32* [[TMP1]], align 4
-// CHECK:   [[TMP3:%.*]] = insertelement <4 x i32> undef, i32 [[TMP2]], i32 0
+// CHECK:   [[TMP3:%.*]] = insertelement <4 x i32> poison, i32 [[TMP2]], i32 0
 // CHECK:   [[LANE:%.*]] = shufflevector <4 x i32> [[TMP3]], <4 x i32> [[TMP3]], <4 x i32> zeroinitializer
 // CHECK:   ret <4 x i32> [[LANE]]
 int32x4_t test_vld1q_dup_s32(int32_t const * a) {
@@ -4152,7 +4152,7 @@
 // CHECK:   [[TMP0:%.*]] = bitcast i64* %a to i8*
 // CHECK:   [[TMP1:%.*]] = bitcast i8* [[TMP0]] to i64*
 // CHECK:   [[TMP2:%.*]] = load i64, i64* [[TMP1]], align 4
-// CHECK:   [[TMP3:%.*]] = insertelement <2 x i64>

[clang] 4627cef - [OpenMP][OMPIRBuilder] Migrate emitOffloadingArraysArgument from clang

2022-10-07 Thread Jan Sjodin via cfe-commits

Author: Jan Sjodin
Date: 2022-10-07T07:03:03-05:00
New Revision: 4627cef1134f99f3802a5ebfe26188d2c66da22f

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

LOG: [OpenMP][OMPIRBuilder] Migrate emitOffloadingArraysArgument from clang

This patch moves the emitOffloadingArraysArgument function and
supporting data structures to OpenMPIRBuilder. This will later be used
in flang as well. The TargetDataInfo class was split up into generic
information and clang-specific data, which remain in clang. Further
migration will be done in in the future.

Reviewed By: jdoerfert

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

Added: 


Modified: 
clang/lib/CodeGen/CGOpenMPRuntime.cpp
clang/lib/CodeGen/CGOpenMPRuntime.h
llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index 5bf0e0815111e..0260b4cdc1572 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -9442,7 +9442,7 @@ static void emitNonContiguousDescriptor(
 DimsAddr, CGM.Int8PtrTy, CGM.Int8Ty);
 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
-Info.PointersArray, 0, I);
+Info.RTArgs.PointersArray, 0, I);
 Address PAddr(P, CGM.VoidPtrTy, CGF.getPointerAlign());
 CGF.Builder.CreateStore(DAddr.getPointer(), PAddr);
 ++L;
@@ -9520,13 +9520,13 @@ static void emitOffloadingArrays(
 Ctx.VoidPtrTy, PointerNumAP, nullptr, ArrayType::Normal,
 /*IndexTypeQuals=*/0);
 
-Info.BasePointersArray =
+Info.RTArgs.BasePointersArray =
 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
-Info.PointersArray =
+Info.RTArgs.PointersArray =
 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
 Address MappersArray =
 CGF.CreateMemTemp(PointerArrayType, ".offload_mappers");
-Info.MappersArray = MappersArray.getPointer();
+Info.RTArgs.MappersArray = MappersArray.getPointer();
 
 // If we don't have any VLA types or other types that require runtime
 // evaluation, we can use a constant array for the map sizes, otherwise we
@@ -9555,7 +9555,7 @@ static void emitOffloadingArrays(
   QualType SizeArrayType = Ctx.getConstantArrayType(
   Int64Ty, PointerNumAP, nullptr, ArrayType::Normal,
   /*IndexTypeQuals=*/0);
-  Info.SizesArray =
+  Info.RTArgs.SizesArray =
   CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
 } else {
   auto *SizesArrayInit = llvm::ConstantArray::get(
@@ -9579,9 +9579,9 @@ static void emitOffloadingArrays(
 CGM.getNaturalTypeAlignment(Ctx.getIntTypeForBitwidth(
 /*DestWidth=*/64, /*Signed=*/false))),
 CGF.getTypeSize(SizeArrayType));
-Info.SizesArray = Buffer.getPointer();
+Info.RTArgs.SizesArray = Buffer.getPointer();
   } else {
-Info.SizesArray = SizesArrayGbl;
+Info.RTArgs.SizesArray = SizesArrayGbl;
   }
 }
 
@@ -9593,12 +9593,12 @@ static void emitOffloadingArrays(
 CGM.getOpenMPRuntime().getName({"offload_maptypes"});
 auto *MapTypesArrayGbl =
 OMPBuilder.createOffloadMaptypes(Mapping, MaptypesName);
-Info.MapTypesArray = MapTypesArrayGbl;
+Info.RTArgs.MapTypesArray = MapTypesArrayGbl;
 
 // The information types are only built if there is debug information
 // requested.
 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo) {
-  Info.MapNamesArray = llvm::Constant::getNullValue(
+  Info.RTArgs.MapNamesArray = llvm::Constant::getNullValue(
   llvm::Type::getInt8Ty(CGF.Builder.getContext())->getPointerTo());
 } else {
   auto fillInfoMap = [&](MappableExprsHandler::MappingExprInfo &MapExpr) {
@@ -9610,7 +9610,7 @@ static void emitOffloadingArrays(
   CGM.getOpenMPRuntime().getName({"offload_mapnames"});
   auto *MapNamesArrayGbl =
   OMPBuilder.createOffloadMapnames(InfoMap, MapnamesName);
-  Info.MapNamesArray = MapNamesArrayGbl;
+  Info.RTArgs.MapNamesArray = MapNamesArrayGbl;
 }
 
 // If there's a present map type modifier, it must not be applied to the 
end
@@ -9626,7 +9626,7 @@ static void emitOffloadingArrays(
   if (EndMapTypesDiffer) {
 MapTypesArrayGbl =
 OMPBuilder.createOffloadMaptypes(Mapping, MaptypesName);
-Info.MapTypesArrayEnd = MapTypesArrayGbl;
+Info.RTArgs.MapTypesArrayEnd = MapTypesArrayGbl;
   }
 }
 
@@ -9634,7 +9634

[PATCH] D134662: [OpenMPIRBuilder] Migrate emitOffloadingArraysArgument from clang

2022-10-07 Thread Jan Sjödin via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG4627cef1134f: [OpenMP][OMPIRBuilder] Migrate 
emitOffloadingArraysArgument from clang (authored by jsjodin).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134662

Files:
  clang/lib/CodeGen/CGOpenMPRuntime.cpp
  clang/lib/CodeGen/CGOpenMPRuntime.h
  llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
  llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
  llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp

Index: llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp
===
--- llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp
+++ llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp
@@ -5312,4 +5312,55 @@
   verifyDFSOrder(F, RefOrder);
 }
 
+TEST_F(OpenMPIRBuilderTest, EmitOffloadingArraysArguments) {
+  OpenMPIRBuilder OMPBuilder(*M);
+  OMPBuilder.initialize();
+
+  IRBuilder<> Builder(BB);
+
+  OpenMPIRBuilder::TargetDataRTArgs RTArgs;
+  OpenMPIRBuilder::TargetDataInfo Info(true, false);
+
+  auto VoidPtrTy = Type::getInt8PtrTy(Builder.getContext());
+  auto VoidPtrPtrTy = VoidPtrTy->getPointerTo(0);
+  auto Int64Ty = Type::getInt64Ty(Builder.getContext());
+  auto Int64PtrTy = Type::getInt64PtrTy(Builder.getContext());
+  auto Array4VoidPtrTy = ArrayType::get(VoidPtrTy, 4);
+  auto Array4Int64PtrTy = ArrayType::get(Int64Ty, 4);
+
+  Info.RTArgs.BasePointersArray =
+  ConstantPointerNull::get(Array4VoidPtrTy->getPointerTo(0));
+  Info.RTArgs.PointersArray =
+  ConstantPointerNull::get(Array4VoidPtrTy->getPointerTo());
+  Info.RTArgs.SizesArray =
+  ConstantPointerNull::get(Array4Int64PtrTy->getPointerTo());
+  Info.RTArgs.MapTypesArray =
+  ConstantPointerNull::get(Array4Int64PtrTy->getPointerTo());
+  Info.RTArgs.MapNamesArray =
+  ConstantPointerNull::get(Array4VoidPtrTy->getPointerTo());
+  Info.RTArgs.MappersArray =
+  ConstantPointerNull::get(Array4VoidPtrTy->getPointerTo());
+  Info.NumberOfPtrs = 4;
+
+  OMPBuilder.emitOffloadingArraysArgument(Builder, RTArgs, Info, false, false);
+
+  EXPECT_NE(RTArgs.BasePointersArray, nullptr);
+  EXPECT_NE(RTArgs.PointersArray, nullptr);
+  EXPECT_NE(RTArgs.SizesArray, nullptr);
+  EXPECT_NE(RTArgs.MapTypesArray, nullptr);
+  EXPECT_NE(RTArgs.MappersArray, nullptr);
+  EXPECT_NE(RTArgs.MapNamesArray, nullptr);
+  EXPECT_EQ(RTArgs.MapTypesArrayEnd, nullptr);
+
+  EXPECT_EQ(RTArgs.BasePointersArray->getType(), VoidPtrPtrTy);
+  RTArgs.BasePointersArray->getType()->dump();
+  VoidPtrTy->dump();
+  EXPECT_EQ(RTArgs.PointersArray->getType(), VoidPtrPtrTy);
+  EXPECT_EQ(RTArgs.SizesArray->getType(), Int64PtrTy);
+  RTArgs.SizesArray->getType()->dump();
+  Int64PtrTy->dump();
+  EXPECT_EQ(RTArgs.MapTypesArray->getType(), Int64PtrTy);
+  EXPECT_EQ(RTArgs.MappersArray->getType(), VoidPtrPtrTy);
+  EXPECT_EQ(RTArgs.MapNamesArray->getType(), VoidPtrPtrTy);
+}
 } // namespace
Index: llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
===
--- llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
+++ llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
@@ -3990,6 +3990,64 @@
   ArgSizesGEP, MaptypesArg, MapnamesArg, NullPtr});
 }
 
+void OpenMPIRBuilder::emitOffloadingArraysArgument(IRBuilderBase &Builder,
+   TargetDataRTArgs &RTArgs,
+   TargetDataInfo &Info,
+   bool EmitDebug,
+   bool ForEndCall) {
+  assert((!ForEndCall || Info.separateBeginEndCalls()) &&
+ "expected region end call to runtime only when end call is separate");
+  auto VoidPtrTy = Type::getInt8PtrTy(M.getContext());
+  auto VoidPtrPtrTy = VoidPtrTy->getPointerTo(0);
+  auto Int64Ty = Type::getInt64Ty(M.getContext());
+  auto Int64PtrTy = Type::getInt64PtrTy(M.getContext());
+
+  if (!Info.NumberOfPtrs) {
+RTArgs.BasePointersArray = ConstantPointerNull::get(VoidPtrPtrTy);
+RTArgs.PointersArray = ConstantPointerNull::get(VoidPtrPtrTy);
+RTArgs.SizesArray = ConstantPointerNull::get(Int64PtrTy);
+RTArgs.MapTypesArray = ConstantPointerNull::get(Int64PtrTy);
+RTArgs.MapNamesArray = ConstantPointerNull::get(VoidPtrPtrTy);
+RTArgs.MappersArray = ConstantPointerNull::get(VoidPtrPtrTy);
+return;
+  }
+
+  RTArgs.BasePointersArray = Builder.CreateConstInBoundsGEP2_32(
+  ArrayType::get(VoidPtrTy, Info.NumberOfPtrs),
+  Info.RTArgs.BasePointersArray,
+  /*Idx0=*/0, /*Idx1=*/0);
+  RTArgs.PointersArray = Builder.CreateConstInBoundsGEP2_32(
+  ArrayType::get(VoidPtrTy, Info.NumberOfPtrs), Info.RTArgs.PointersArray,
+  /*Idx0=*/0,
+  /*Idx1=*/0);
+  RTArgs.SizesArray = Builder.CreateConstInBoundsGEP2_32(
+  Array

[PATCH] D135397: [clang][dataflow] Add support for a Top value in boolean formulas.

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

Thanks for the thorough reviews! Agreed on all points, and will address.




Comment at: 
clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h:157
+  TopValue &createTop() {
+return takeOwnership(std::make_unique());
+  }

xazax.hun wrote:
> gribozavr2 wrote:
> > Should we be creating a new top every time, or should it be a singleton 
> > like true and false?
> > 
> > It seems like we explicitly don't care about its identity (or else it would 
> > be isomorphic to AtomicBool).
> Good point, a singleton Top might actually simplify some parts of the code.
Good question. That was my initial implementation, but it ran into the problem 
that the solver (in `buildBooleanFormula`) maps each unique (by pointer) 
subexpression into a fresh SAT variable in . If we use a singleton Top, we need 
to modify that algorithm appropriately. I'm open to suggestions, though, 
because of the advantages of a singleton Top.

If we assume that a given `Top` is never actually shared in a boolean formula 
(unlike other subexpressions, which may be shared), then we can use a singleton 
and special case it in `buildBooleanFormula`. I think that's a good assumption, 
but am not sure. Thoughts?



Comment at: clang/include/clang/Analysis/FlowSensitive/Value.h:102
+  static bool classof(const Value *Val) { return Val->getKind() == Kind::Top; }
+};
+

gribozavr2 wrote:
> Since TopValue is a BoolValue, can we form say a ConjunctionValue where LHS 
> or RHS is Top?
> 
> What if we create such a conjunction twice? It seems like such conjunctions 
> would incorrectly compare equal, even though each Top will be replaced with a 
> unique fresh variable.
> 
> Would it make sense to change our factory functions for boolean formulas to 
> eagerly open Top?
> 
> Then we wouldn't need a recursive walk in unpackValue().
They would only compare equal if we're using a singleton Top. In fact, that's 
not quite right because we have no deep equality on formulas. But, the caching 
mechanism would generate the same formula, so the point holds. In that case, we 
would need to eagerly open the Top, because we would lose any way to 
distinguish them.  But, with different Top instances, this wouldn't be 
necessary. Overall, it seems like "open top as soon as possible without killing 
convergence" is probably our best heuristic, so this seems like a win. But, I'm 
pretty sure there are places where it will prevent convergence (on its own -- 
`widen` will still handle it fine I believe).

Avoiding the recursive walk would be nice. 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135397

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


[clang] d779356 - [SourceManager] Fix the incorrect counting stats in getFileIDLoaded.

2022-10-07 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2022-10-07T14:24:31+02:00
New Revision: d779356043a895280d0880551ef33d663fe36c7e

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

LOG: [SourceManager] Fix the incorrect counting stats in getFileIDLoaded.

We were double-counting the number of binary search FileID scans.

Added: 


Modified: 
clang/lib/Basic/SourceManager.cpp

Removed: 




diff  --git a/clang/lib/Basic/SourceManager.cpp 
b/clang/lib/Basic/SourceManager.cpp
index f82df598ffc3..7229561394e3 100644
--- a/clang/lib/Basic/SourceManager.cpp
+++ b/clang/lib/Basic/SourceManager.cpp
@@ -906,8 +906,6 @@ FileID 
SourceManager::getFileIDLoaded(SourceLocation::UIntTy SLocOffset) const {
 if (Invalid)
   return FileID(); // invalid entry.
 
-++NumProbes;
-
 if (E.getOffset() > SLocOffset) {
   if (GreaterIndex == MiddleIndex) {
 assert(0 && "binary search missed the entry");



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


[clang] a4afa2b - Revert "Thread safety analysis: Support copy-elided production of scoped capabilities through arbitrary calls"

2022-10-07 Thread Hans Wennborg via cfe-commits

Author: Hans Wennborg
Date: 2022-10-07T14:30:36+02:00
New Revision: a4afa2bde6f4db215ddd3267a8d11c04367812e5

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

LOG: Revert "Thread safety analysis: Support copy-elided production of scoped 
capabilities through arbitrary calls"

This caused false positives, see comment on the code review.

> When support for copy elision was initially added in e97654b2f2807, it
> was taking attributes from a constructor call, although that constructor
> call is actually not involved. It seems more natural to use attributes
> on the function returning the scoped capability, which is where it's
> actually coming from. This would also support a number of interesting
> use cases, like producing different scope kinds without the need for tag
> types, or producing scopes from a private mutex.
>
> Changing the behavior was surprisingly difficult: we were not handling
> CXXConstructorExpr calls like regular calls but instead handled them
> through the DeclStmt they're contained in. This was based on the
> assumption that constructors are basically only called in variable
> declarations (not true because of temporaries), and that variable
> declarations necessitate constructors (not true with C++17 anymore).
>
> Untangling this required separating construction from assigning a
> variable name. When a call produces an object, we use a placeholder
> til::LiteralPtr for `this`, and we collect the call expression and
> placeholder in a map. Later when going through a DeclStmt, we look up
> the call expression and set the placeholder to the new VarDecl.
>
> The change has a couple of nice side effects:
> * We don't miss constructor calls not contained in DeclStmts anymore,
>   allowing patterns like
> MutexLock{&mu}, requiresMutex();
>   The scoped lock temporary will be destructed at the end of the full
>   statement, so it protects the following call without the need for a
>   scope, but with the ability to unlock in case of an exception.
> * We support lifetime extension of temporaries. While unusual, one can
>   now write
> const MutexLock &scope = MutexLock(&mu);
>   and have it behave as expected.
> * Destructors used to be handled in a weird way: since there is no
>   expression in the AST for implicit destructor calls, we instead
>   provided a made-up DeclRefExpr to the variable being destructed, and
>   passed that instead of a CallExpr. Then later in translateAttrExpr
>   there was special code that knew that destructor expressions worked a
>   bit different.
> * We were producing dummy DeclRefExprs in a number of places, this has
>   been eliminated. We now use til::SExprs instead.
>
> Technically this could break existing code, but the current handling
> seems unexpected enough to justify this change.
>
> Reviewed By: aaron.ballman
>
> Differential Revision: https://reviews.llvm.org/D129755

This reverts commit 0041a69495f828f6732803cfb0f1e3fddd7fbf2a and the follow-up
warning fix in 83d93d3c11ac9727bf3d4c5c956de44233cc7f87.

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/docs/ThreadSafetyAnalysis.rst
clang/include/clang/Analysis/Analyses/ThreadSafetyCommon.h
clang/include/clang/Analysis/Analyses/ThreadSafetyTIL.h
clang/include/clang/Analysis/Analyses/ThreadSafetyTraverse.h
clang/lib/Analysis/ThreadSafety.cpp
clang/lib/Analysis/ThreadSafetyCommon.cpp
clang/test/SemaCXX/warn-thread-safety-analysis.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 7dc779ccc2e24..65febfaa24c38 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -265,11 +265,6 @@ Improvements to Clang's diagnostics
   function definition without a prototype which is preceded by a static
   declaration of the function with a prototype. Fixes
   `Issue 58181 `_.
-- Copy-elided initialization of lock scopes is now handled 
diff erently in
-  ``-Wthread-safety-analysis``: annotations on the move constructor are no
-  longer taken into account, in favor of annotations on the function returning
-  the lock scope by value. This could result in new warnings if code depended
-  on the previous undocumented behavior.
 
 Non-comprehensive list of changes in this release
 -

diff  --git a/clang/docs/ThreadSafetyAnalysis.rst 
b/clang/docs/ThreadSafetyAnalysis.rst
index dcde0c706c704..23f460b248e11 100644
--- a/clang/docs/ThreadSafetyAnalysis.rst
+++ b/clang/docs/ThreadSafetyAnalysis.rst
@@ -408,8 +408,7 @@ and destructor refer to the capability via 
diff erent names; see the
 Scoped capabilities are treated as capabilities that are implicitly acquired
 on construction and released on de

[PATCH] D129755: Thread safety analysis: Support copy-elided production of scoped capabilities through arbitrary calls

2022-10-07 Thread Hans Wennborg via Phabricator via cfe-commits
hans added a comment.

We're hitting a false positive in grpc after this:

  > ../../third_party/grpc/src/src/core/lib/gprpp/ref_counted_ptr.h:335:31: 
error: calling function 'TlsSessionKeyLoggerCache' requires holding mutex 
'g_tls_session_key_log_cache_mu' exclusively [-Werror,-Wthread-safety-analysis]
  >   return RefCountedPtr(new T(std::forward(args)...));
  >   ^
  > 
../../third_party/grpc/src/src/core/tsi/ssl/key_logging/ssl_key_logging.cc:121:26:
 note: in instantiation of function template specialization 
'grpc_core::MakeRefCounted' requested here
  >  cache = grpc_core::MakeRefCounted();
  > ^
  
  
  The code looks like this:
  
  grpc_core::RefCountedPtr TlsSessionKeyLoggerCache::Get(
  std::string tls_session_key_log_file_path) {
gpr_once_init(&g_cache_mutex_init, do_cache_mutex_init);
GPR_DEBUG_ASSERT(g_tls_session_key_log_cache_mu != nullptr);
if (tls_session_key_log_file_path.empty()) {
  return nullptr;
}
{
  grpc_core::MutexLock lock(g_tls_session_key_log_cache_mu);
<-- holding the mutex
  grpc_core::RefCountedPtr cache;
  if (g_cache_instance == nullptr) {
// This will automatically set g_cache_instance.
cache = grpc_core::MakeRefCounted();  
<-- line 121
  
  
  
  lock is holding a MutexLock (I assume that's an exclusive thing) on 
g_tls_session_key_log_cache_mu.

See https://bugs.chromium.org/p/chromium/issues/detail?id=1372394#c4 for how to 
reproduce.

I've reverted this in 
https://github.com/llvm/llvm-project/commit/a4afa2bde6f4db215ddd3267a8d11c04367812e5
 in the meantime.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129755

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


[PATCH] D135362: [clang] Make variables of undeduced types to have dependent alignment

2022-10-07 Thread Aleksandr Platonov via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG5a42c90b778c: [clang] Make variables of undeduced types to 
have dependent alignment (authored by ArcsinX).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135362

Files:
  clang/lib/AST/Decl.cpp
  clang/test/Sema/tls_alignment.cpp


Index: clang/test/Sema/tls_alignment.cpp
===
--- clang/test/Sema/tls_alignment.cpp
+++ clang/test/Sema/tls_alignment.cpp
@@ -1,6 +1,6 @@
 // TLS variable cannot be aligned to more than 32 bytes on PS4.
 
-// RUN: %clang_cc1 -triple x86_64-scei-ps4 -fsyntax-only -verify %s
+// RUN: %clang_cc1 -triple x86_64-scei-ps4 -std=c++17 -fsyntax-only -verify %s
 
 
 // A non-aligned type.
@@ -18,6 +18,12 @@
 int some_aligned_data[12] __attribute__(( aligned(64) )); // 48 bytes of 
stuff, aligned to 64.
 };
 
+// A templated type
+template 
+struct templated_struct {};
+// expected-note@-1{{candidate template ignored: couldn't infer template 
argument ''}}
+// expected-note@-2{{candidate function template not viable: requires 1 
argument, but 0 were provided}}
+
 // A typedef of the aligned struct.
 typedef aligned_struct another_aligned_struct;
 
@@ -42,6 +48,9 @@
 // Variable aligned because of typedef, second case.
 __thread yet_another_aligned_structbar5; // expected-error{{alignment 
(64) of thread-local variable}}
 
+// No crash for undeduced type.
+__thread templated_struct  bar6; // expected-error{{no viable 
constructor or deduction guide for deduction of template arguments of 
'templated_struct'}}
+
 int baz ()
 {
 return foo.some_data[0] + bar.some_data[1] + bar2.some_data[2] +
Index: clang/lib/AST/Decl.cpp
===
--- clang/lib/AST/Decl.cpp
+++ clang/lib/AST/Decl.cpp
@@ -2581,7 +2581,7 @@
 
 bool VarDecl::hasDependentAlignment() const {
   QualType T = getType();
-  return T->isDependentType() || T->isUndeducedAutoType() ||
+  return T->isDependentType() || T->isUndeducedType() ||
  llvm::any_of(specific_attrs(), [](const AlignedAttr *AA) 
{
return AA->isAlignmentDependent();
  });


Index: clang/test/Sema/tls_alignment.cpp
===
--- clang/test/Sema/tls_alignment.cpp
+++ clang/test/Sema/tls_alignment.cpp
@@ -1,6 +1,6 @@
 // TLS variable cannot be aligned to more than 32 bytes on PS4.
 
-// RUN: %clang_cc1 -triple x86_64-scei-ps4 -fsyntax-only -verify %s
+// RUN: %clang_cc1 -triple x86_64-scei-ps4 -std=c++17 -fsyntax-only -verify %s
 
 
 // A non-aligned type.
@@ -18,6 +18,12 @@
 int some_aligned_data[12] __attribute__(( aligned(64) )); // 48 bytes of stuff, aligned to 64.
 };
 
+// A templated type
+template 
+struct templated_struct {};
+// expected-note@-1{{candidate template ignored: couldn't infer template argument ''}}
+// expected-note@-2{{candidate function template not viable: requires 1 argument, but 0 were provided}}
+
 // A typedef of the aligned struct.
 typedef aligned_struct another_aligned_struct;
 
@@ -42,6 +48,9 @@
 // Variable aligned because of typedef, second case.
 __thread yet_another_aligned_structbar5; // expected-error{{alignment (64) of thread-local variable}}
 
+// No crash for undeduced type.
+__thread templated_struct  bar6; // expected-error{{no viable constructor or deduction guide for deduction of template arguments of 'templated_struct'}}
+
 int baz ()
 {
 return foo.some_data[0] + bar.some_data[1] + bar2.some_data[2] +
Index: clang/lib/AST/Decl.cpp
===
--- clang/lib/AST/Decl.cpp
+++ clang/lib/AST/Decl.cpp
@@ -2581,7 +2581,7 @@
 
 bool VarDecl::hasDependentAlignment() const {
   QualType T = getType();
-  return T->isDependentType() || T->isUndeducedAutoType() ||
+  return T->isDependentType() || T->isUndeducedType() ||
  llvm::any_of(specific_attrs(), [](const AlignedAttr *AA) {
return AA->isAlignmentDependent();
  });
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 5a42c90 - [clang] Make variables of undeduced types to have dependent alignment

2022-10-07 Thread Aleksandr Platonov via cfe-commits

Author: Aleksandr Platonov
Date: 2022-10-07T20:40:03+08:00
New Revision: 5a42c90b778c65238a54f0f1d8c8d6b35e2f6007

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

LOG: [clang] Make variables of undeduced types to have dependent alignment

Without this patch `VarDecl::hasDependent()` checks only undeduced auto types, 
so can give false negatives result for other undeduced types.
This lead to crashes in sequence `!VarDecl::hasDepentent()` => `getDeclAlign()`.

It seems this problem appeared since D105380

Reviewed By: mizvekov

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

Added: 


Modified: 
clang/lib/AST/Decl.cpp
clang/test/Sema/tls_alignment.cpp

Removed: 




diff  --git a/clang/lib/AST/Decl.cpp b/clang/lib/AST/Decl.cpp
index 49ad2230e7ca0..b326933b1d7d1 100644
--- a/clang/lib/AST/Decl.cpp
+++ b/clang/lib/AST/Decl.cpp
@@ -2581,7 +2581,7 @@ bool VarDecl::isNonEscapingByref() const {
 
 bool VarDecl::hasDependentAlignment() const {
   QualType T = getType();
-  return T->isDependentType() || T->isUndeducedAutoType() ||
+  return T->isDependentType() || T->isUndeducedType() ||
  llvm::any_of(specific_attrs(), [](const AlignedAttr *AA) 
{
return AA->isAlignmentDependent();
  });

diff  --git a/clang/test/Sema/tls_alignment.cpp 
b/clang/test/Sema/tls_alignment.cpp
index 5a7bb2c463f37..18db565055d0e 100644
--- a/clang/test/Sema/tls_alignment.cpp
+++ b/clang/test/Sema/tls_alignment.cpp
@@ -1,6 +1,6 @@
 // TLS variable cannot be aligned to more than 32 bytes on PS4.
 
-// RUN: %clang_cc1 -triple x86_64-scei-ps4 -fsyntax-only -verify %s
+// RUN: %clang_cc1 -triple x86_64-scei-ps4 -std=c++17 -fsyntax-only -verify %s
 
 
 // A non-aligned type.
@@ -18,6 +18,12 @@ struct  struct_with_aligned_field {
 int some_aligned_data[12] __attribute__(( aligned(64) )); // 48 bytes of 
stuff, aligned to 64.
 };
 
+// A templated type
+template 
+struct templated_struct {};
+// expected-note@-1{{candidate template ignored: couldn't infer template 
argument ''}}
+// expected-note@-2{{candidate function template not viable: requires 1 
argument, but 0 were provided}}
+
 // A typedef of the aligned struct.
 typedef aligned_struct another_aligned_struct;
 
@@ -42,6 +48,9 @@ __thread another_aligned_structbar4; // 
expected-error{{alignment (6
 // Variable aligned because of typedef, second case.
 __thread yet_another_aligned_structbar5; // expected-error{{alignment 
(64) of thread-local variable}}
 
+// No crash for undeduced type.
+__thread templated_struct  bar6; // expected-error{{no viable 
constructor or deduction guide for deduction of template arguments of 
'templated_struct'}}
+
 int baz ()
 {
 return foo.some_data[0] + bar.some_data[1] + bar2.some_data[2] +



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


[PATCH] D129755: Thread safety analysis: Support copy-elided production of scoped capabilities through arbitrary calls

2022-10-07 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

In D129755#3842729 , @hans wrote:

> We're hitting a false positive in grpc after this:
>
>   > ../../third_party/grpc/src/src/core/lib/gprpp/ref_counted_ptr.h:335:31: 
> error: calling function 'TlsSessionKeyLoggerCache' requires holding mutex 
> 'g_tls_session_key_log_cache_mu' exclusively 
> [-Werror,-Wthread-safety-analysis]
>   >   return RefCountedPtr(new T(std::forward(args)...));
>   >   ^
>   > 
> ../../third_party/grpc/src/src/core/tsi/ssl/key_logging/ssl_key_logging.cc:121:26:
>  note: in instantiation of function template specialization 
> 'grpc_core::MakeRefCounted' requested here
>   >  cache = grpc_core::MakeRefCounted();
>   > ^
>   
>   
>   The code looks like this:
>   
>   grpc_core::RefCountedPtr TlsSessionKeyLoggerCache::Get(
>   std::string tls_session_key_log_file_path) {
> gpr_once_init(&g_cache_mutex_init, do_cache_mutex_init);
> GPR_DEBUG_ASSERT(g_tls_session_key_log_cache_mu != nullptr);
> if (tls_session_key_log_file_path.empty()) {
>   return nullptr;
> }
> {
>   grpc_core::MutexLock lock(g_tls_session_key_log_cache_mu);
> <-- holding the mutex
>   grpc_core::RefCountedPtr cache;
>   if (g_cache_instance == nullptr) {
> // This will automatically set g_cache_instance.
> cache = grpc_core::MakeRefCounted();  
> <-- line 121
>   
>   
>   
>   lock is holding a MutexLock (I assume that's an exclusive thing) on 
> g_tls_session_key_log_cache_mu.
>
> See https://bugs.chromium.org/p/chromium/issues/detail?id=1372394#c4 for how 
> to reproduce.
>
> I've reverted this in 
> https://github.com/llvm/llvm-project/commit/a4afa2bde6f4db215ddd3267a8d11c04367812e5
>  in the meantime.

I'm not opposed to a revert here, but reverting on (plausible) assumptions of 
this being a false positive without discussion or a reproducer beyond "compile 
chromium" comes across as a somewhat aggressive revert. Especially given that 
we knew this had the potential to break code and we were okay with that code 
being broken (as stated in the commit message). No community bots went red from 
this change and it's possible this could have been fixed forward/explained as a 
desired break with less churn to the codebase. Nothing to be done for it now 
(and it wasn't wrong per se), just something to keep in mind for future reverts 
-- a bit of discussion before a revert like this would be appropriate.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129755

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


[PATCH] D134813: Properly print unnamed TagDecl objects in diagnostics

2022-10-07 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman updated this revision to Diff 466052.
aaron.ballman added a comment.
Herald added a subscriber: kadircet.
Herald added a project: clang-tools-extra.

Updated to fix the clangd unit test breakage.


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

https://reviews.llvm.org/D134813

Files:
  clang-tools-extra/clangd/unittests/FindTargetTests.cpp
  clang/include/clang/AST/Decl.h
  clang/include/clang/AST/DeclCXX.h
  clang/include/clang/AST/DeclTemplate.h
  clang/lib/AST/ASTDiagnostic.cpp
  clang/lib/AST/Decl.cpp
  clang/lib/AST/DeclCXX.cpp
  clang/lib/AST/DeclPrinter.cpp
  clang/lib/AST/DeclTemplate.cpp
  clang/lib/AST/NestedNameSpecifier.cpp
  clang/lib/AST/TemplateName.cpp
  clang/lib/CodeGen/CodeGenTypes.cpp
  clang/lib/Sema/SemaTemplateInstantiate.cpp
  clang/test/AST/ast-dump-record-definition-data-json.cpp
  clang/test/ExtractAPI/enum.c
  clang/test/Index/annotate-comments-typedef.m
  clang/test/Index/c-index-api-loadTU-test.m
  clang/test/Index/c-index-getCursor-test.m
  clang/test/Index/print-type.c
  clang/test/Index/print-type.cpp
  clang/test/Index/targeted-annotation.c
  clang/test/Index/targeted-cursor.c
  clang/test/Index/usrs.m
  clang/test/Sema/address-packed.c
  clang/test/Sema/attr-flag-enum.c
  clang/test/SemaCXX/attr-unused.cpp
  clang/test/SemaCXX/lambda-expressions.cpp
  clang/test/SemaCXX/ms-interface.cpp
  clang/test/SemaObjCXX/arc-0x.mm
  clang/test/Templight/templight-empty-entries-fix.cpp
  llvm/utils/lit/lit/TestRunner.py

Index: llvm/utils/lit/lit/TestRunner.py
===
--- llvm/utils/lit/lit/TestRunner.py
+++ llvm/utils/lit/lit/TestRunner.py
@@ -1174,6 +1174,7 @@
 ('%/p', sourcedir.replace('\\', '/')),
 ('%/t', tmpBase.replace('\\', '/') + '.tmp'),
 ('%/T', tmpDir.replace('\\', '/')),
+('%/et',tmpName.replace('\\', '')),
 ])
 
 # "%{/[STpst]:regex_replacement}" should be normalized like "%/[STpst]" but we're
Index: clang/test/Templight/templight-empty-entries-fix.cpp
===
--- clang/test/Templight/templight-empty-entries-fix.cpp
+++ clang/test/Templight/templight-empty-entries-fix.cpp
@@ -5,13 +5,13 @@
 }
 
 // CHECK-LABEL: {{^---$}}
-// CHECK: {{^name:[ ]+'lambda at .*templight-empty-entries-fix.cpp:4:3'$}}
+// CHECK: {{^name:[ ]+'\(lambda at .*templight-empty-entries-fix.cpp:4:3\)'$}}
 // CHECK: {{^kind:[ ]+Memoization$}}
 // CHECK: {{^event:[ ]+Begin$}}
 // CHECK: {{^orig:[ ]+'.*templight-empty-entries-fix.cpp:4:3'$}}
 // CHECK: {{^poi:[ ]+'.*templight-empty-entries-fix.cpp:4:3'$}}
 // CHECK-LABEL: {{^---$}}
-// CHECK: {{^name:[ ]+'lambda at .*templight-empty-entries-fix.cpp:4:3'$}}
+// CHECK: {{^name:[ ]+'\(lambda at .*templight-empty-entries-fix.cpp:4:3\)'$}}
 // CHECK: {{^kind:[ ]+Memoization$}}
 // CHECK: {{^event:[ ]+End$}}
 // CHECK: {{^orig:[ ]+'.*templight-empty-entries-fix.cpp:4:3'$}}
@@ -225,37 +225,37 @@
 }
 
 // CHECK-LABEL: {{^---$}}
-// CHECK: {{^name:[ ]+unnamed struct$}}
+// CHECK: {{^name:[ ]+'\(unnamed struct at .*templight-empty-entries-fix.cpp:223:3\)'$}}
 // CHECK: {{^kind:[ ]+Memoization$}}
 // CHECK: {{^event:[ ]+Begin$}}
 // CHECK: {{^orig:[ ]+'.*templight-empty-entries-fix.cpp:223:3'$}}
 // CHECK: {{^poi:[ ]+'.*templight-empty-entries-fix.cpp:224:5'$}}
 // CHECK-LABEL: {{^---$}}
-// CHECK: {{^name:[ ]+unnamed struct$}}
+// CHECK: {{^name:[ ]+'\(unnamed struct at .*templight-empty-entries-fix.cpp:223:3\)'$}}
 // CHECK: {{^kind:[ ]+Memoization$}}
 // CHECK: {{^event:[ ]+End$}}
 // CHECK: {{^orig:[ ]+'.*templight-empty-entries-fix.cpp:223:3'$}}
 // CHECK: {{^poi:[ ]+'.*templight-empty-entries-fix.cpp:224:5'$}}
 // CHECK-LABEL: {{^---$}}
-// CHECK: {{^name:[ ]+unnamed struct$}}
+// CHECK: {{^name:[ ]+'\(unnamed struct at .*templight-empty-entries-fix.cpp:223:3\)'$}}
 // CHECK: {{^kind:[ ]+Memoization$}}
 // CHECK: {{^event:[ ]+Begin$}}
 // CHECK: {{^orig:[ ]+'.*templight-empty-entries-fix.cpp:223:3'$}}
 // CHECK: {{^poi:[ ]+'.*templight-empty-entries-fix.cpp:224:5'$}}
 // CHECK-LABEL: {{^---$}}
-// CHECK: {{^name:[ ]+unnamed struct$}}
+// CHECK: {{^name:[ ]+'\(unnamed struct at .*templight-empty-entries-fix.cpp:223:3\)'$}}
 // CHECK: {{^kind:[ ]+Memoization$}}
 // CHECK: {{^event:[ ]+End$}}
 // CHECK: {{^orig:[ ]+'.*templight-empty-entries-fix.cpp:223:3'$}}
 // CHECK: {{^poi:[ ]+'.*templight-empty-entries-fix.cpp:224:5'$}}
 // CHECK-LABEL: {{^---$}}
-// CHECK: {{^name:[ ]+unnamed struct$}}
+// CHECK: {{^name:[ ]+'\(unnamed struct at .*templight-empty-entries-fix.cpp:223:3\)'$}}
 // CHECK: {{^kind:[ ]+Memoization$}}
 // CHECK: {{^event:[ ]+Begin$}}
 // CHECK: {{^orig:[ ]+'.*templight-empty-entries-fix.cpp:223:3'$}}
 // CHECK: {{^poi:[ ]+'.*templight-empty-entries-fix.cpp:223:3'$}}
 // CHECK-LABEL: {{^---$}}
-// CHECK: {{^name:[ ]+unnamed struct$}}
+// CHECK: {{^name:[ ]+'\(unnamed struct at .*templight-empty-entries-fix.cpp:223:3

[PATCH] D129755: Thread safety analysis: Support copy-elided production of scoped capabilities through arbitrary calls

2022-10-07 Thread Hans Wennborg via Phabricator via cfe-commits
hans added a comment.

We also hit a different case: 
https://bugs.chromium.org/p/chromium/issues/detail?id=1372394#c6


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129755

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


[clang] 853df5e - [Concepts] Fix friend duplicate detection when referencing containing Record

2022-10-07 Thread Erich Keane via cfe-commits

Author: Erich Keane
Date: 2022-10-07T06:14:11-07:00
New Revision: 853df5e1d63684cbf3bf3da63d3e467003262282

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

LOG: [Concepts] Fix friend duplicate detection when referencing containing 
Record

As another regression from the Deferred Concepts Instantiation patch, we
weren't properly detecting that a friend referenced its containing
Record when it referred to it without its template parameters.  This
patch makes sure that we do.

Added: 


Modified: 
clang/include/clang/Sema/Sema.h
clang/lib/Sema/SemaConcept.cpp
clang/lib/Sema/SemaTemplate.cpp
clang/test/SemaTemplate/concepts-friends.cpp

Removed: 




diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 37fcfd2940d7..a6acdf6b4952 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -3686,8 +3686,10 @@ class Sema final {
   // template, or just the current friend function. A 'lower' TemplateDepth in
   // the AST refers to a 'containing' template. As the constraint is
   // uninstantiated, this is relative to the 'top' of the TU.
-  bool ConstraintExpressionDependsOnEnclosingTemplate(unsigned TemplateDepth,
-  const Expr *Constraint);
+  bool
+  ConstraintExpressionDependsOnEnclosingTemplate(const FunctionDecl *Friend,
+ unsigned TemplateDepth,
+ const Expr *Constraint);
 
   // Calculates whether the friend function depends on an enclosing template 
for
   // the purposes of [temp.friend] p9.

diff  --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index d8dadb38758b..f3301a67d227 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -657,7 +657,7 @@ bool Sema::FriendConstraintsDependOnEnclosingTemplate(const 
FunctionDecl *FD) {
 
   unsigned OldTemplateDepth = CalculateTemplateDepthForConstraints(*this, FD);
   for (const Expr *Constraint : ACs)
-if (ConstraintExpressionDependsOnEnclosingTemplate(OldTemplateDepth,
+if (ConstraintExpressionDependsOnEnclosingTemplate(FD, OldTemplateDepth,
Constraint))
   return true;
 

diff  --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index e07ad3a72b4b..9fa821ea6bde 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -1691,14 +1691,28 @@ namespace {
 class ConstraintRefersToContainingTemplateChecker
 : public TreeTransform {
   bool Result = false;
+  const FunctionDecl *Friend = nullptr;
   unsigned TemplateDepth = 0;
 
+  // Check a record-decl that we've seen to see if it is a lexical parent of 
the
+  // Friend, likely because it was referred to without its template arguments.
+  void CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
+CheckingRD = CheckingRD->getMostRecentDecl();
+
+for (const DeclContext *DC = Friend->getLexicalDeclContext();
+ DC && !DC->isFileContext(); DC = DC->getParent())
+  if (const auto *RD = dyn_cast(DC))
+if (CheckingRD == RD->getMostRecentDecl())
+  Result = true;
+  }
+
 public:
   using inherited = TreeTransform;
 
   ConstraintRefersToContainingTemplateChecker(Sema &SemaRef,
+  const FunctionDecl *Friend,
   unsigned TemplateDepth)
-  : inherited(SemaRef), TemplateDepth(TemplateDepth) {}
+  : inherited(SemaRef), Friend(Friend), TemplateDepth(TemplateDepth) {}
   bool getResult() const { return Result; }
 
   // This should be the only template parm type that we have to deal with.
@@ -1728,6 +1742,8 @@ class ConstraintRefersToContainingTemplateChecker
   TransformType(VD->getType());
 else if (auto *TD = dyn_cast(D))
   TransformTemplateParameterList(TD->getTemplateParameters());
+else if (auto *RD = dyn_cast(D))
+  CheckIfContainingRecord(RD);
 else if (isa(D)) {
   // No direct types to visit here I believe.
 } else
@@ -1738,8 +1754,11 @@ class ConstraintRefersToContainingTemplateChecker
 } // namespace
 
 bool Sema::ConstraintExpressionDependsOnEnclosingTemplate(
-unsigned TemplateDepth, const Expr *Constraint) {
-  ConstraintRefersToContainingTemplateChecker Checker(*this, TemplateDepth);
+const FunctionDecl *Friend, unsigned TemplateDepth,
+const Expr *Constraint) {
+  assert(Friend->getFriendObjectKind() && "Only works on a friend");
+  ConstraintRefersToContainingTemplateChecker Checker(*this, Friend,
+  TemplateDepth);
   Checker.TransformExpr(const_cast(Constraint)

[PATCH] D134128: Resubmit an implemention for constrained template template parameters [P0857R0 Part B]

2022-10-07 Thread Liming Liu via Phabricator via cfe-commits
lime updated this revision to Diff 466056.
lime added a comment.

> The changes in Sema.h and the changes of CalculateTemplateDepthForConstraints

I think it might be fine now. The above changes are related to 
`NormalizationCache`. This cache used to take `NamedDecl` as its key. However, 
as constrains need to be adjusted to different depths, and `p3-2a.cpp` can 
reproduce the case. Thus, `NameDecl` is not enough, and a heavier key is used. 
But the needs to adjust the depth seem unique to template-template parameter, 
so I'm not sure whether there is a better solution. And 
`IsAtLeastAsConstrained` takes `ArrayRef` as its argument, which leads to new 
spaces for potentially adjusted constrains. I think `MutableArryRef` could be 
used here.

BTW, this comment includes an update that involves `git clang-format`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134128

Files:
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/ParseTemplate.cpp
  clang/lib/Sema/SemaConcept.cpp
  clang/test/CXX/temp/temp.arg/temp.arg.template/p3-2a.cpp
  clang/test/SemaTemplate/concepts.cpp
  clang/www/cxx_status.html

Index: clang/www/cxx_status.html
===
--- clang/www/cxx_status.html
+++ clang/www/cxx_status.html
@@ -912,11 +912,7 @@
 

 https://wg21.link/p0857r0";>P0857R0
-
-  Partial
-Constraining template template parameters is not yet supported.
-  
-
+Clang 16
   

 https://wg21.link/p1084r2";>P1084R2
Index: clang/test/SemaTemplate/concepts.cpp
===
--- clang/test/SemaTemplate/concepts.cpp
+++ clang/test/SemaTemplate/concepts.cpp
@@ -59,11 +59,10 @@
 x.operator()(); // expected-error {{no matching member function}}
   }
 
-  // FIXME: This is valid under P0857R0.
   template concept C = true;
-  template requires C typename U> struct X {}; // expected-error {{requires 'class'}} expected-error 0+{{}}
+  template requires C typename U> struct X {};
   template requires C struct Y {};
-  X xy; // expected-error {{no template named 'X'}}
+  X xy;
 }
 
 namespace PR50306 {
Index: clang/test/CXX/temp/temp.arg/temp.arg.template/p3-2a.cpp
===
--- clang/test/CXX/temp/temp.arg/temp.arg.template/p3-2a.cpp
+++ clang/test/CXX/temp/temp.arg/temp.arg.template/p3-2a.cpp
@@ -1,22 +1,27 @@
 // RUN:  %clang_cc1 -std=c++2a -frelaxed-template-template-args -verify %s
 
-template concept C = T::f();
-// expected-note@-1{{similar constraint}}
+template concept C = T::f(); // #C
 template concept D = C && T::g();
-template concept F = T::f();
-// expected-note@-1{{similar constraint expressions not considered equivalent}}
-template class P> struct S1 { }; // expected-note 2{{'P' declared here}}
+template concept F = T::f(); // #F
+template class P> struct S1 { }; // #S1
 
 template struct X { };
-
-template struct Y { }; // expected-note{{'Y' declared here}}
+template struct Y { }; // #Y
 template struct Z { };
-template struct W { }; // expected-note{{'W' declared here}}
+template struct W { }; // #W
 
 S1 s11;
-S1 s12; // expected-error{{template template argument 'Y' is more constrained than template template parameter 'P'}}
+S1 s12;
+// expected-error@-1 {{template template argument 'Y' is more constrained than template template parameter 'P'}}
+// expected-note@#S1 {{'P' declared here}}
+// expected-note@#Y {{'Y' declared here}}
 S1 s13;
-S1 s14; // expected-error{{template template argument 'W' is more constrained than template template parameter 'P'}}
+S1 s14;
+// expected-error@-1 {{template template argument 'W' is more constrained than template template parameter 'P'}}
+// expected-note@#S1 {{'P' declared here}}
+// expected-note@#W {{'W' declared here}}
+// expected-note@#F 1-2{{similar constraint expressions not considered equivalent}}
+// expected-note@#C 1-2{{similar constraint}}
 
 template class P> struct S2 { };
 
@@ -32,3 +37,25 @@
 
 using s31 = S3;
 using s32 = S3;
+
+template requires C class P> struct S4 { }; // #S4
+
+S4 s41;
+S4 s42;
+// expected-error@-1 {{template template argument 'Y' is more constrained than template template parameter 'P'}}
+// expected-note@#S4 {{'P' declared here}}
+// expected-note@#Y {{'Y' declared here}}
+S4 s43;
+S4 s44;
+// expected-error@-1 {{template template argument 'W' is more constrained than template template parameter 'P'}}
+// expected-note@#S4 {{'P' declared here}}
+// expected-note@#W {{'W' declared here}}
+
+template requires C typename U> struct S5 {
+  template static U V;
+};
+
+struct Nothing {};
+
+// FIXME: Wait the standard to clarify the intent.
+template<> template<> Z S5::V;
Index: clang/lib/Sema/SemaConcept.cpp
===
--- clang/lib/Sema/SemaCo

[PATCH] D135384: Enable the use of the -pg flag

2022-10-07 Thread Chris Bowler via Phabricator via cfe-commits
cebowleratibm added inline comments.



Comment at: clang/test/CodeGen/mcount-aix.c:2
+// RUN: %clang_cc1 -pg -no-opaque-pointers -triple powerpc-ibm-aix7.2.0.0 -S 
-emit-llvm %s -o - | FileCheck %s
+// RUN: %clang_cc1 -pg -no-opaque-pointers -triple powerpc64-ibm-aix7.2.0.0 -S 
-emit-llvm %s -o - | FileCheck %s -check-prefix=CHECK64
+

Is it necessary to specify -no-opaque-pointers for this test?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135384

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


[PATCH] D135370: Narrow inline namespace filtration for unqualified friend declarations

2022-10-07 Thread Troy Johnson via Phabricator via cfe-commits
troyj updated this revision to Diff 466072.
troyj added a comment.

Added more diff context as requested.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135370

Files:
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp


Index: clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
===
--- clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -2273,9 +2273,11 @@
 // Filter out previous declarations that don't match the scope. The only
 // effect this has is to remove declarations found in inline namespaces
 // for friend declarations with unqualified names.
-SemaRef.FilterLookupForScope(Previous, DC, /*Scope*/ nullptr,
- /*ConsiderLinkage*/ true,
- QualifierLoc.hasQualifier());
+if (isFriend && !QualifierLoc && !FunctionTemplate) {
+  SemaRef.FilterLookupForScope(Previous, DC, /*Scope=*/ nullptr,
+   /*ConsiderLinkage=*/ true,
+   QualifierLoc.hasQualifier());
+}
   }
 
   // Per [temp.inst], default arguments in function declarations at local scope


Index: clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
===
--- clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -2273,9 +2273,11 @@
 // Filter out previous declarations that don't match the scope. The only
 // effect this has is to remove declarations found in inline namespaces
 // for friend declarations with unqualified names.
-SemaRef.FilterLookupForScope(Previous, DC, /*Scope*/ nullptr,
- /*ConsiderLinkage*/ true,
- QualifierLoc.hasQualifier());
+if (isFriend && !QualifierLoc && !FunctionTemplate) {
+  SemaRef.FilterLookupForScope(Previous, DC, /*Scope=*/ nullptr,
+   /*ConsiderLinkage=*/ true,
+   QualifierLoc.hasQualifier());
+}
   }
 
   // Per [temp.inst], default arguments in function declarations at local scope
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] bb46022 - [CMake] Small fix to HLSL header install paths

2022-10-07 Thread Chris Bieneman via cfe-commits

Author: Chris Bieneman
Date: 2022-10-07T09:45:11-05:00
New Revision: bb46022abe78497d3d5a8c6a6cf8599f7ec0d2ec

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

LOG: [CMake] Small fix to HLSL header install paths

HLSL headers were being installed in two locations, one correct and one
incorrect, and they were always being installed (even when
CLANG_ENABLE_HLSL=Off). This corrects both issues by ensuring that the
HLSL headers aren't added to the universal header list.

Added: 


Modified: 
clang/lib/Headers/CMakeLists.txt

Removed: 




diff  --git a/clang/lib/Headers/CMakeLists.txt 
b/clang/lib/Headers/CMakeLists.txt
index 0e78238436c94..bd2161d597a8f 100644
--- a/clang/lib/Headers/CMakeLists.txt
+++ b/clang/lib/Headers/CMakeLists.txt
@@ -225,7 +225,6 @@ set(files
   ${cuda_files}
   ${hexagon_files}
   ${hip_files}
-  ${hlsl_files}
   ${mips_msa_files}
   ${opencl_files}
   ${ppc_files}
@@ -302,7 +301,7 @@ endfunction(clang_generate_header)
 
 
 # Copy header files from the source directory to the build directory
-foreach( f ${files} ${cuda_wrapper_files} ${ppc_wrapper_files} 
${openmp_wrapper_files})
+foreach( f ${files} ${cuda_wrapper_files} ${ppc_wrapper_files} 
${openmp_wrapper_files} ${hlsl_files})
   copy_header_to_output_dir(${CMAKE_CURRENT_SOURCE_DIR} ${f})
 endforeach( f )
 



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


[PATCH] D135269: [AMDGPU] Disable bool range metadata to workaround backend issue

2022-10-07 Thread Yaxun Liu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG107ee2613063: [AMDGPU] Disable bool range metadata to 
workaround backend issue (authored by yaxunl).
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135269

Files:
  clang/lib/CodeGen/CGExpr.cpp
  clang/test/CodeGenCUDA/bool-range.cu


Index: clang/test/CodeGenCUDA/bool-range.cu
===
--- /dev/null
+++ clang/test/CodeGenCUDA/bool-range.cu
@@ -0,0 +1,23 @@
+// RUN: %clang_cc1 -emit-llvm %s -O3 -o - -fcuda-is-device \
+// RUN:   -triple nvptx64-unknown-unknown | FileCheck %s -check-prefixes=NV
+// RUN: %clang_cc1 -emit-llvm %s -O3 -o - -fcuda-is-device \
+// RUN:   -triple amdgcn-amd-amdhsa | FileCheck %s -check-prefixes=AMD
+
+#include "Inputs/cuda.h"
+
+// NV:  %[[LD:[0-9]+]] = load i8, ptr %x,{{.*}} !range ![[MD:[0-9]+]]
+// NV:  store i8 %[[LD]], ptr %y
+// NV: ![[MD]] = !{i8 0, i8 2}
+
+// Make sure bool loaded from memory is truncated and
+// range metadata is not emitted.
+// TODO: Re-enable range metadata after issue
+// https://github.com/llvm/llvm-project/issues/58176 is fixed.
+
+// AMD:  %[[LD:[0-9]+]] = load i8, ptr addrspace(1) %x.global
+// AMD-NOT: !range
+// AMD:  %[[AND:[0-9]+]] = and i8 %[[LD]], 1
+// AMD:  store i8 %[[AND]], ptr addrspace(1) %y.global
+__global__ void test1(bool *x, bool *y) {
+  *y = *x != false;
+}
Index: clang/lib/CodeGen/CGExpr.cpp
===
--- clang/lib/CodeGen/CGExpr.cpp
+++ clang/lib/CodeGen/CGExpr.cpp
@@ -1748,7 +1748,10 @@
   if (EmitScalarRangeCheck(Load, Ty, Loc)) {
 // In order to prevent the optimizer from throwing away the check, don't
 // attach range metadata to the load.
-  } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
+// TODO: Enable range metadata for AMDGCN after issue
+// https://github.com/llvm/llvm-project/issues/58176 is fixed.
+  } else if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
+ !CGM.getTriple().isAMDGCN())
 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
   Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
 


Index: clang/test/CodeGenCUDA/bool-range.cu
===
--- /dev/null
+++ clang/test/CodeGenCUDA/bool-range.cu
@@ -0,0 +1,23 @@
+// RUN: %clang_cc1 -emit-llvm %s -O3 -o - -fcuda-is-device \
+// RUN:   -triple nvptx64-unknown-unknown | FileCheck %s -check-prefixes=NV
+// RUN: %clang_cc1 -emit-llvm %s -O3 -o - -fcuda-is-device \
+// RUN:   -triple amdgcn-amd-amdhsa | FileCheck %s -check-prefixes=AMD
+
+#include "Inputs/cuda.h"
+
+// NV:  %[[LD:[0-9]+]] = load i8, ptr %x,{{.*}} !range ![[MD:[0-9]+]]
+// NV:  store i8 %[[LD]], ptr %y
+// NV: ![[MD]] = !{i8 0, i8 2}
+
+// Make sure bool loaded from memory is truncated and
+// range metadata is not emitted.
+// TODO: Re-enable range metadata after issue
+// https://github.com/llvm/llvm-project/issues/58176 is fixed.
+
+// AMD:  %[[LD:[0-9]+]] = load i8, ptr addrspace(1) %x.global
+// AMD-NOT: !range
+// AMD:  %[[AND:[0-9]+]] = and i8 %[[LD]], 1
+// AMD:  store i8 %[[AND]], ptr addrspace(1) %y.global
+__global__ void test1(bool *x, bool *y) {
+  *y = *x != false;
+}
Index: clang/lib/CodeGen/CGExpr.cpp
===
--- clang/lib/CodeGen/CGExpr.cpp
+++ clang/lib/CodeGen/CGExpr.cpp
@@ -1748,7 +1748,10 @@
   if (EmitScalarRangeCheck(Load, Ty, Loc)) {
 // In order to prevent the optimizer from throwing away the check, don't
 // attach range metadata to the load.
-  } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
+// TODO: Enable range metadata for AMDGCN after issue
+// https://github.com/llvm/llvm-project/issues/58176 is fixed.
+  } else if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
+ !CGM.getTriple().isAMDGCN())
 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
   Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 107ee26 - [AMDGPU] Disable bool range metadata to workaround backend issue

2022-10-07 Thread Yaxun Liu via cfe-commits

Author: Yaxun (Sam) Liu
Date: 2022-10-07T10:46:04-04:00
New Revision: 107ee2613063183cb643cef97f0fad403508c9f0

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

LOG: [AMDGPU] Disable bool range metadata to workaround backend issue

Currently there is a middle-end or backend issue
https://github.com/llvm/llvm-project/issues/58176
which causes values loaded from bool pointer incorrect when
bool range metadata is emitted. Temporarily
disable bool range metadata until the backend issue
is fixed.

Reviewed by: Artem Belevich

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

Fixes: SWDEV-344137

Added: 
clang/test/CodeGenCUDA/bool-range.cu

Modified: 
clang/lib/CodeGen/CGExpr.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index b58d5c29a1f9e..af753767f0328 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -1748,7 +1748,10 @@ llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address 
Addr, bool Volatile,
   if (EmitScalarRangeCheck(Load, Ty, Loc)) {
 // In order to prevent the optimizer from throwing away the check, don't
 // attach range metadata to the load.
-  } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
+// TODO: Enable range metadata for AMDGCN after issue
+// https://github.com/llvm/llvm-project/issues/58176 is fixed.
+  } else if (CGM.getCodeGenOpts().OptimizationLevel > 0 &&
+ !CGM.getTriple().isAMDGCN())
 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
   Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
 

diff  --git a/clang/test/CodeGenCUDA/bool-range.cu 
b/clang/test/CodeGenCUDA/bool-range.cu
new file mode 100644
index 0..5dc68612e7191
--- /dev/null
+++ b/clang/test/CodeGenCUDA/bool-range.cu
@@ -0,0 +1,23 @@
+// RUN: %clang_cc1 -emit-llvm %s -O3 -o - -fcuda-is-device \
+// RUN:   -triple nvptx64-unknown-unknown | FileCheck %s -check-prefixes=NV
+// RUN: %clang_cc1 -emit-llvm %s -O3 -o - -fcuda-is-device \
+// RUN:   -triple amdgcn-amd-amdhsa | FileCheck %s -check-prefixes=AMD
+
+#include "Inputs/cuda.h"
+
+// NV:  %[[LD:[0-9]+]] = load i8, ptr %x,{{.*}} !range ![[MD:[0-9]+]]
+// NV:  store i8 %[[LD]], ptr %y
+// NV: ![[MD]] = !{i8 0, i8 2}
+
+// Make sure bool loaded from memory is truncated and
+// range metadata is not emitted.
+// TODO: Re-enable range metadata after issue
+// https://github.com/llvm/llvm-project/issues/58176 is fixed.
+
+// AMD:  %[[LD:[0-9]+]] = load i8, ptr addrspace(1) %x.global
+// AMD-NOT: !range
+// AMD:  %[[AND:[0-9]+]] = and i8 %[[LD]], 1
+// AMD:  store i8 %[[AND]], ptr addrspace(1) %y.global
+__global__ void test1(bool *x, bool *y) {
+  *y = *x != false;
+}



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


[clang] 3b652fc - [analyzer] Fix static code analysis concerns

2022-10-07 Thread via cfe-commits

Author: Soumi Manna
Date: 2022-10-07T16:58:37+02:00
New Revision: 3b652fc6d6447aae91c9e8c35815eed19245757d

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

LOG: [analyzer] Fix static code analysis concerns

ProcessMemberDtor(), ProcessDeleteDtor(), and ProcessAutomaticObjDtor():
Fix static analyzer warnings with suspicious dereference of pointer
'Pred' in function call before NULL checks - NFCI

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

Added: 


Modified: 
clang/lib/StaticAnalyzer/Core/ExprEngine.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp 
b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
index b1514a5473f5e..f6b6de73796e2 100644
--- a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -1378,10 +1378,10 @@ void ExprEngine::ProcessAutomaticObjDtor(const 
CFGAutomaticObjDtor Dtor,
   "Prepare for object destruction");
   PreImplicitCall PP(DtorDecl, varDecl->getLocation(), LCtx, &PT);
   Pred = Bldr.generateNode(PP, state, Pred);
-  Bldr.takeNodes(Pred);
 
   if (!Pred)
 return;
+  Bldr.takeNodes(Pred);
 
   VisitCXXDestructor(varType, Region, Dtor.getTriggerStmt(),
  /*IsBase=*/false, Pred, Dst, CallOpts);
@@ -1452,10 +1452,10 @@ void ExprEngine::ProcessDeleteDtor(const CFGDeleteDtor 
Dtor,
   "Prepare for object destruction");
   PreImplicitCall PP(getDtorDecl(DTy), DE->getBeginLoc(), LCtx, &PT);
   Pred = Bldr.generateNode(PP, State, Pred);
-  Bldr.takeNodes(Pred);
 
   if (!Pred)
 return;
+  Bldr.takeNodes(Pred);
 
   VisitCXXDestructor(DTy, ArgR, DE, /*IsBase=*/false, Pred, Dst, CallOpts);
 }
@@ -1528,10 +1528,10 @@ void ExprEngine::ProcessMemberDtor(const CFGMemberDtor 
D,
   "Prepare for object destruction");
   PreImplicitCall PP(DtorDecl, Member->getLocation(), LCtx, &PT);
   Pred = Bldr.generateNode(PP, State, Pred);
-  Bldr.takeNodes(Pred);
 
   if (!Pred)
 return;
+  Bldr.takeNodes(Pred);
 
   VisitCXXDestructor(T, FieldVal.getAsRegion(), CurDtor->getBody(),
  /*IsBase=*/false, Pred, Dst, CallOpts);



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


[PATCH] D135290: [analyzer] Fix static code analysis concerns

2022-10-07 Thread Domján Dániel 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 rG3b652fc6d644: [analyzer] Fix static code analysis concerns 
(authored by Manna, committed by isuckatcs).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135290

Files:
  clang/lib/StaticAnalyzer/Core/ExprEngine.cpp


Index: clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
===
--- clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -1378,10 +1378,10 @@
   "Prepare for object destruction");
   PreImplicitCall PP(DtorDecl, varDecl->getLocation(), LCtx, &PT);
   Pred = Bldr.generateNode(PP, state, Pred);
-  Bldr.takeNodes(Pred);
 
   if (!Pred)
 return;
+  Bldr.takeNodes(Pred);
 
   VisitCXXDestructor(varType, Region, Dtor.getTriggerStmt(),
  /*IsBase=*/false, Pred, Dst, CallOpts);
@@ -1452,10 +1452,10 @@
   "Prepare for object destruction");
   PreImplicitCall PP(getDtorDecl(DTy), DE->getBeginLoc(), LCtx, &PT);
   Pred = Bldr.generateNode(PP, State, Pred);
-  Bldr.takeNodes(Pred);
 
   if (!Pred)
 return;
+  Bldr.takeNodes(Pred);
 
   VisitCXXDestructor(DTy, ArgR, DE, /*IsBase=*/false, Pred, Dst, CallOpts);
 }
@@ -1528,10 +1528,10 @@
   "Prepare for object destruction");
   PreImplicitCall PP(DtorDecl, Member->getLocation(), LCtx, &PT);
   Pred = Bldr.generateNode(PP, State, Pred);
-  Bldr.takeNodes(Pred);
 
   if (!Pred)
 return;
+  Bldr.takeNodes(Pred);
 
   VisitCXXDestructor(T, FieldVal.getAsRegion(), CurDtor->getBody(),
  /*IsBase=*/false, Pred, Dst, CallOpts);


Index: clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
===
--- clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -1378,10 +1378,10 @@
   "Prepare for object destruction");
   PreImplicitCall PP(DtorDecl, varDecl->getLocation(), LCtx, &PT);
   Pred = Bldr.generateNode(PP, state, Pred);
-  Bldr.takeNodes(Pred);
 
   if (!Pred)
 return;
+  Bldr.takeNodes(Pred);
 
   VisitCXXDestructor(varType, Region, Dtor.getTriggerStmt(),
  /*IsBase=*/false, Pred, Dst, CallOpts);
@@ -1452,10 +1452,10 @@
   "Prepare for object destruction");
   PreImplicitCall PP(getDtorDecl(DTy), DE->getBeginLoc(), LCtx, &PT);
   Pred = Bldr.generateNode(PP, State, Pred);
-  Bldr.takeNodes(Pred);
 
   if (!Pred)
 return;
+  Bldr.takeNodes(Pred);
 
   VisitCXXDestructor(DTy, ArgR, DE, /*IsBase=*/false, Pred, Dst, CallOpts);
 }
@@ -1528,10 +1528,10 @@
   "Prepare for object destruction");
   PreImplicitCall PP(DtorDecl, Member->getLocation(), LCtx, &PT);
   Pred = Bldr.generateNode(PP, State, Pred);
-  Bldr.takeNodes(Pred);
 
   if (!Pred)
 return;
+  Bldr.takeNodes(Pred);
 
   VisitCXXDestructor(T, FieldVal.getAsRegion(), CurDtor->getBody(),
  /*IsBase=*/false, Pred, Dst, CallOpts);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D129689: [limits.h] USHRT_MAX fix for 16 bit architectures

2022-10-07 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

This seems to have fallen through the cracks -- @SebastianPerta are you 
planning to update the patch, or would you be okay if I commandeered it?


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

https://reviews.llvm.org/D129689

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


[PATCH] D135236: [Clang][OpenMP] Add one missing form of atomic compare capture

2022-10-07 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev accepted this revision.
ABataev added a comment.
This revision is now accepted and ready to land.

LG


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135236

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


[clang] eb26baf - Fix test bool-range.cu

2022-10-07 Thread Yaxun Liu via cfe-commits

Author: Yaxun (Sam) Liu
Date: 2022-10-07T11:17:28-04:00
New Revision: eb26baf4ade6c1e73eb14e8a89d5771e57bc61a3

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

LOG: Fix test bool-range.cu

Promoting kernel arg pointer to global addr space is only
available with registered amdgcn target.

Fix test so that it does not require registered amdgcn target.

Added: 


Modified: 
clang/test/CodeGenCUDA/bool-range.cu

Removed: 




diff  --git a/clang/test/CodeGenCUDA/bool-range.cu 
b/clang/test/CodeGenCUDA/bool-range.cu
index 5dc68612e7191..e33174a2ad670 100644
--- a/clang/test/CodeGenCUDA/bool-range.cu
+++ b/clang/test/CodeGenCUDA/bool-range.cu
@@ -14,10 +14,10 @@
 // TODO: Re-enable range metadata after issue
 // https://github.com/llvm/llvm-project/issues/58176 is fixed.
 
-// AMD:  %[[LD:[0-9]+]] = load i8, ptr addrspace(1) %x.global
+// AMD:  %[[LD:[0-9]+]] = load i8, ptr {{.*}}%x
 // AMD-NOT: !range
 // AMD:  %[[AND:[0-9]+]] = and i8 %[[LD]], 1
-// AMD:  store i8 %[[AND]], ptr addrspace(1) %y.global
+// AMD:  store i8 %[[AND]], ptr {{.*}}%y
 __global__ void test1(bool *x, bool *y) {
   *y = *x != false;
 }



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


[PATCH] D135367: [clang-tidy] Dump effective diagnostics level in YAML output

2022-10-07 Thread Nathan James via Phabricator via cfe-commits
njames93 accepted this revision.
njames93 added a comment.
This revision is now accepted and ready to land.

LGTM, just maybe include a test case where a warning from a clang-tidy check is 
promoted to an error as well.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135367

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


[PATCH] D135341: [clang] adds `__reference_constructs_from_temporary` and `__reference_converts_from_temporary`

2022-10-07 Thread Christopher Di Bella via Phabricator via cfe-commits
cjdb updated this revision to Diff 466088.
cjdb added a comment.

Gets `__reference_constructs_from_temporary` correct. Still WIP for the latter.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135341

Files:
  clang/docs/LanguageExtensions.rst
  clang/include/clang/Basic/TokenKinds.def
  clang/lib/Lex/PPMacroExpansion.cpp
  clang/lib/Parse/ParseDeclCXX.cpp
  clang/lib/Parse/ParseExpr.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/test/SemaCXX/type-traits.cpp
  clang/www/cxx_status.html

Index: clang/www/cxx_status.html
===
--- clang/www/cxx_status.html
+++ clang/www/cxx_status.html
@@ -1417,16 +1417,7 @@
 
   Type trait to determine if a reference binds to a temporary
   https://wg21.link/P2255R2";>P2255R2
-  
-Partial
-  Clang provides a __reference_binds_to_temporary type trait
-  builtin, with which the library facility can be partially implemented.
-  Both __reference_constructs_from_temporary and
-  __reference_converts_from_temporary builtins should be
-  provided, following the normal cross-vendor convention to implement
-  traits requiring compiler support directly.
-
-  
+  Clang 16
 
 
 
Index: clang/test/SemaCXX/type-traits.cpp
===
--- clang/test/SemaCXX/type-traits.cpp
+++ clang/test/SemaCXX/type-traits.cpp
@@ -4704,6 +4704,96 @@
   { int arr[T((__reference_binds_to_temporary(const int &, long)))]; }
 }
 
+void reference_constructs_from_temporary_checks() {
+  static_assert(!__reference_constructs_from_temporary(int &, int &), "");
+  static_assert(!__reference_constructs_from_temporary(int &, int &&), "");
+
+  static_assert(!__reference_constructs_from_temporary(int const &, int &), "");
+  static_assert(!__reference_constructs_from_temporary(int const &, int const &), "");
+  static_assert(!__reference_constructs_from_temporary(int const &, int &&), "");
+
+  static_assert(!__reference_constructs_from_temporary(int &, long &), ""); // doesn't construct
+
+  static_assert(__reference_constructs_from_temporary(int const &, long &), "");
+  static_assert(__reference_constructs_from_temporary(int const &, long &&), "");
+  static_assert(__reference_constructs_from_temporary(int &&, long &), "");
+
+  using LRef = ConvertsToRef;
+  using RRef = ConvertsToRef;
+  using CLRef = ConvertsToRef;
+  using LongRef = ConvertsToRef;
+  static_assert(__is_constructible(int &, LRef), "");
+  static_assert(!__reference_constructs_from_temporary(int &, LRef), "");
+
+  static_assert(__is_constructible(int &&, RRef), "");
+  static_assert(!__reference_constructs_from_temporary(int &&, RRef), "");
+
+  static_assert(__is_constructible(int const &, CLRef), "");
+  static_assert(!__reference_constructs_from_temporary(int &&, CLRef), "");
+
+  static_assert(__is_constructible(int const &, LongRef), "");
+  static_assert(__reference_constructs_from_temporary(int const &, LongRef), "");
+
+  // Test that it doesn't accept non-reference types as input.
+  static_assert(!__reference_constructs_from_temporary(int, long), "");
+
+  static_assert(__reference_constructs_from_temporary(const int &, long), "");
+
+  // Additional checks
+  static_assert(__reference_constructs_from_temporary(POD const&, Derives), "");
+  static_assert(__reference_constructs_from_temporary(int&&, int), "");
+  static_assert(__reference_constructs_from_temporary(const int&, int), "");
+  static_assert(!__reference_constructs_from_temporary(int&&, int&&), "");
+  static_assert(!__reference_constructs_from_temporary(const int&, int&&), "");
+  static_assert(__reference_constructs_from_temporary(int&&, long&&), "");
+  static_assert(__reference_constructs_from_temporary(int&&, long), "");
+}
+
+void reference_converts_from_temporary_checks() {
+  static_assert(!__reference_converts_from_temporary(int &, int &), "");
+  static_assert(!__reference_converts_from_temporary(int &, int &&), "");
+
+  static_assert(!__reference_converts_from_temporary(int const &, int &), "");
+  static_assert(!__reference_converts_from_temporary(int const &, int const &), "");
+  static_assert(!__reference_converts_from_temporary(int const &, int &&), "");
+
+  static_assert(!__reference_converts_from_temporary(int &, long &), ""); // doesn't construct
+
+  static_assert(__reference_converts_from_temporary(int const &, long &), "");
+  static_assert(__reference_converts_from_temporary(int const &, long &&), "");
+  static_assert(__reference_converts_from_temporary(int &&, long &), "");
+
+  using LRef = ConvertsToRef;
+  using RRef = ConvertsToRef;
+  using CLRef = ConvertsToRef;
+  using LongRef = ConvertsToRef;
+  static_assert(__is_convertible(LRef, int &), "");
+  static_assert(!__reference_converts_from_temporary(int &, LRef), "");
+
+  static_assert(__is_c

[PATCH] D135199: [OpenMP][C++] Allow #pragma omp simd in constexpr functions

2022-10-07 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/lib/AST/ExprConstant.cpp:8274-8279
 // Only if a local variable was declared in the function currently being
 // evaluated, do we expect to be able to find its value in the current
 // frame. (Otherwise it was likely declared in an enclosing context and
 // could either have a valid evaluatable value (for e.g. a constexpr
 // variable) or be ill-formed (and trigger an appropriate evaluation
 // diagnostic)).

jdoerfert wrote:
> aaron.ballman wrote:
> > This comment no longer matches the code. It also suggests that the way to 
> > address your issue is to capture the variable into the current frame -- did 
> > you explore that approach?
> The problem is that OpenMP introduces artificial capture statements. I am not 
> sure if/how those can be "merged" into the parent context and in general that 
> is not allowed (e.g., as we allow clauses on SIMD, like private). I feel the 
> comment needs updating and I'll try that. 
Is there a way to limit the change to only OpenMP captured variables so that 
we're not changing the semantics for all language modes?



Comment at: clang/lib/Sema/SemaDeclCXX.cpp:2175-2178
+SemaRef.Diag(
+S->getBeginLoc(),
+diag::err_constexpr_body_invalid_omp_simd_stmt_with_clauses)
+<< isa(Dcl) << Dcl->isConsteval();

jdoerfert wrote:
> aaron.ballman wrote:
> > C++20 now has constexpr destructors, but there are also other kinds of 
> > special member functions too. It seems like the constraint really is 
> > "constant evaluation of a function with SIMD clauses is invalid" and so we 
> > might want to go with a more generic diagnostic instead of trying to 
> > distinguish between kinds of functions.
> I copied this from below (see comment). I would assume the two have to stay 
> in sync. All the differentiation of constructor does it to specify where it 
> was found, no? So:
> SIMD with clauses is not supported, found in XYZ.
Yeah, they should stay in sync; I don't insist on a change to the diagnostic as 
part of this review unless you feel like it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135199

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


[PATCH] D135099: [C2x] Implement support for nullptr and nullptr_t

2022-10-07 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

Ping


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

https://reviews.llvm.org/D135099

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


[PATCH] D135099: [C2x] Implement support for nullptr and nullptr_t

2022-10-07 Thread Erich Keane via Phabricator via cfe-commits
erichkeane accepted this revision.
erichkeane added a comment.
This revision is now accepted and ready to land.

Happy with this, thanks!


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

https://reviews.llvm.org/D135099

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


[PATCH] D129755: Thread safety analysis: Support copy-elided production of scoped capabilities through arbitrary calls

2022-10-07 Thread Gulfem Savrun Yeniceri via Phabricator via cfe-commits
gulfem added a comment.

We also started seeing `-Wthread-safety-precise` error in our Fuchsia code. 
https://luci-milo.appspot.com/ui/p/fuchsia/builders/ci/clang_toolchain.ci.core.x64-release/b8800959115965408001/overview
I'm trying to verify with our team whether it is a false positive, but I just 
wanted to give you heads up!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129755

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


[PATCH] D129755: Thread safety analysis: Support copy-elided production of scoped capabilities through arbitrary calls

2022-10-07 Thread Aaron Puchert via Phabricator via cfe-commits
aaronpuchert added a comment.

In D129755#3842729 , @hans wrote:

> We're hitting a false positive in grpc after this:
>
>   > ../../third_party/grpc/src/src/core/lib/gprpp/ref_counted_ptr.h:335:31: 
> error: calling function 'TlsSessionKeyLoggerCache' requires holding mutex 
> 'g_tls_session_key_log_cache_mu' exclusively 
> [-Werror,-Wthread-safety-analysis]
>   >   return RefCountedPtr(new T(std::forward(args)...));
>   >   ^
>   > 
> ../../third_party/grpc/src/src/core/tsi/ssl/key_logging/ssl_key_logging.cc:121:26:
>  note: in instantiation of function template specialization 
> 'grpc_core::MakeRefCounted' requested here
>   >  cache = grpc_core::MakeRefCounted();
>   > ^
>   
>   
>   The code looks like this:
>   
>   grpc_core::RefCountedPtr TlsSessionKeyLoggerCache::Get(
>   std::string tls_session_key_log_file_path) {
> gpr_once_init(&g_cache_mutex_init, do_cache_mutex_init);
> GPR_DEBUG_ASSERT(g_tls_session_key_log_cache_mu != nullptr);
> if (tls_session_key_log_file_path.empty()) {
>   return nullptr;
> }
> {
>   grpc_core::MutexLock lock(g_tls_session_key_log_cache_mu);
> <-- holding the mutex
>   grpc_core::RefCountedPtr cache;
>   if (g_cache_instance == nullptr) {
> // This will automatically set g_cache_instance.
> cache = grpc_core::MakeRefCounted();  
> <-- line 121
>   
>   
>   
>   lock is holding a MutexLock (I assume that's an exclusive thing) on 
> g_tls_session_key_log_cache_mu.
>
> See https://bugs.chromium.org/p/chromium/issues/detail?id=1372394#c4 for how 
> to reproduce.
>
> I've reverted this in 
> https://github.com/llvm/llvm-project/commit/a4afa2bde6f4db215ddd3267a8d11c04367812e5
>  in the meantime.

This doesn't look like a false positive to me. The documentation states that no 
inlining  is 
being done, so unless `grpc_core::MakeRefCounted` (or a specialization) has a 
`require_capability` attribute, the lock doesn't count as locked in the 
function body. That has always been the case.

The only thing that changed is that we now also consider `CXXConstructExpr` 
outside of `DeclStmt`s, which is arguably an improvement.

In D129755#3842744 , @hans wrote:

> We also hit a different case: 
> https://bugs.chromium.org/p/chromium/issues/detail?id=1372394#c6

From the logs:

  
../../extensions/browser/api/content_settings/content_settings_store.cc(75,49): 
note: mutex acquired here
std::unique_ptr auto_lock(new base::AutoLock(lock_));
  ^

That seems to be precisely the example that the documentation says doesn't 
work. The constructor of `std::unique_ptr` has no thread safety annotations and 
so we have a constructor call without a matching destructor call. (The 
destructor is called indirectly from the destructor of `unique_ptr`. We see 
this now because of the constructor call that doesn't initialize a local 
variable.

The documentation also lists ways to make this work (such as having more 
powerful scope types).

I'll give you some time to reply before I reland, but I can't see a bug here. 
For the next time, as already pointed out, give the involved people some time 
to reply before you revert (unless it's a crash). We have to be able to 
continue working on the compiler without having Google revert changes all the 
time because we produce new warnings.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129755

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


[PATCH] D135461: [LLDB] Fix crash when printing a struct with a static wchar_t member

2022-10-07 Thread Arthur Eubanks via Phabricator via cfe-commits
aeubanks created this revision.
aeubanks added a reviewer: DavidSpickett.
Herald added a project: All.
aeubanks requested review of this revision.
Herald added projects: clang, LLDB.
Herald added subscribers: lldb-commits, cfe-commits.

Similar to D135170 .


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D135461

Files:
  clang/lib/AST/StmtPrinter.cpp
  lldb/test/API/lang/cpp/const_static_integral_member/main.cpp


Index: lldb/test/API/lang/cpp/const_static_integral_member/main.cpp
===
--- lldb/test/API/lang/cpp/const_static_integral_member/main.cpp
+++ lldb/test/API/lang/cpp/const_static_integral_member/main.cpp
@@ -35,6 +35,7 @@
   const static auto longlong_max = std::numeric_limits::max();
   const static auto ulonglong_max =
   std::numeric_limits::max();
+  const static auto wchar_max = std::numeric_limits::max();
 
   const static auto char_min = std::numeric_limits::min();
   const static auto uchar_min = std::numeric_limits::min();
@@ -45,6 +46,7 @@
   const static auto longlong_min = std::numeric_limits::min();
   const static auto ulonglong_min =
   std::numeric_limits::min();
+  const static auto wchar_min = std::numeric_limits::min();
 
   const static Enum enum_val = enum_case2;
   const static ScopedEnum scoped_enum_val = ScopedEnum::scoped_enum_case2;
Index: clang/lib/AST/StmtPrinter.cpp
===
--- clang/lib/AST/StmtPrinter.cpp
+++ clang/lib/AST/StmtPrinter.cpp
@@ -1293,6 +1293,9 @@
 break; // no suffix.
   case BuiltinType::UInt128:
 break; // no suffix.
+  case BuiltinType::WChar_S:
+  case BuiltinType::WChar_U:
+break; // no suffix.
   }
 }
 


Index: lldb/test/API/lang/cpp/const_static_integral_member/main.cpp
===
--- lldb/test/API/lang/cpp/const_static_integral_member/main.cpp
+++ lldb/test/API/lang/cpp/const_static_integral_member/main.cpp
@@ -35,6 +35,7 @@
   const static auto longlong_max = std::numeric_limits::max();
   const static auto ulonglong_max =
   std::numeric_limits::max();
+  const static auto wchar_max = std::numeric_limits::max();
 
   const static auto char_min = std::numeric_limits::min();
   const static auto uchar_min = std::numeric_limits::min();
@@ -45,6 +46,7 @@
   const static auto longlong_min = std::numeric_limits::min();
   const static auto ulonglong_min =
   std::numeric_limits::min();
+  const static auto wchar_min = std::numeric_limits::min();
 
   const static Enum enum_val = enum_case2;
   const static ScopedEnum scoped_enum_val = ScopedEnum::scoped_enum_case2;
Index: clang/lib/AST/StmtPrinter.cpp
===
--- clang/lib/AST/StmtPrinter.cpp
+++ clang/lib/AST/StmtPrinter.cpp
@@ -1293,6 +1293,9 @@
 break; // no suffix.
   case BuiltinType::UInt128:
 break; // no suffix.
+  case BuiltinType::WChar_S:
+  case BuiltinType::WChar_U:
+break; // no suffix.
   }
 }
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D129755: Thread safety analysis: Support copy-elided production of scoped capabilities through arbitrary calls

2022-10-07 Thread Aaron Puchert via Phabricator via cfe-commits
aaronpuchert added a comment.

In D129755#3843144 , @gulfem wrote:

> We also started seeing `-Wthread-safety-precise` error in our Fuchsia code. 
> https://luci-milo.appspot.com/ui/p/fuchsia/builders/ci/clang_toolchain.ci.core.x64-release/b8800959115965408001/overview
> I'm trying to verify with our team whether it is a false positive, but I just 
> wanted to give you heads up!

Both places have 


  Cursor cursor(DiscardableVmosLock::Get(), ...);
  AssertHeld(cursor.lock_ref());

At the end of the scope we get

  error: calling function '~VmoCursor' requires holding mutex 'lock_' 
exclusively [-Werror,-Wthread-safety-precise]
  note: found near match 'cursor.lock_'

Presumably `Cursor` is some kind of alias to `VmoCursor`, as we don't look at 
base destructors yet. Since the code is not easily searchable for me, can you 
look up the annotations on `DiscardableVmosLock::Get`, the constructor of 
`Cursor`/`VmoCursor` being used here, `Cursor::lock_ref`, and `AssertHeld`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129755

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


[PATCH] D135366: [clang][Interp] Implement String- and CharacterLiterals

2022-10-07 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/lib/AST/Interp/ByteCodeExprGen.cpp:446
+  if (Optional T = classify(LitType)) {
+APInt Val(getIntWidth(LitType), E->getValue());
+return this->emitConst(*T, 0, Val, E);

Should this be concerned about the sign of the promoted literal?



Comment at: clang/test/AST/Interp/arrays.cpp:135
+  static_assert(u32[1] == U'b', "");
+};
+

I think you need a more coverage for character literals. Some test cases that 
are interesting: multichar literals (`'abcd'`), character literals with UCNs 
(`'\u'`), character literals with numeric escapes (`'\xFF'`). I'm 
especially interested in seeing whether we handle integer promotions properly, 
especially when promoting to `unsigned int`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135366

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


[PATCH] D135466: [clang-format] Add support to remove unnecessary semicolons after function definition

2022-10-07 Thread MyDeveloperDay via Phabricator via cfe-commits
MyDeveloperDay created this revision.
MyDeveloperDay added reviewers: HazardyKnusperkeks, owenpan, curdeius, rymiel, 
Eugene.Zelenko.
MyDeveloperDay added projects: clang, clang-format.
Herald added a project: All.
MyDeveloperDay requested review of this revision.

Fixes: #58217

This change is to remove extraneous and unnecessary ';' from after a function 
declaration, its off by default and carries the same "code modification" 
warning as some of our other code manipulating changes.

  int max(int a, int b)
  {
  return a>b?a:b;
  };
  
  class Foo
  {
  int getSomething() const { return something; };
  };

At first, I thought this was a minor problem and not worth anything other than 
using `-Wextra-semi/-Wextra-semi-stmt` as pointed out in the issue comments. 
But clang-format is used by people who may not use the clang compiler, and not 
all compilers have this extra semi warning (AFAIK)

However, I ran this over the clang-codebase and realized (in clang and even the 
clang-format Tests!) how prevalent this is.

This is implemented very much on the same lines as @owenpan does for removing 
the `{}` with RemoveBracesLLVM, there is some repeated code that we could 
rationalize down if accepted. (I didn't want to be too invasive on that work)

This is definitely one of those changes that it would be nice for those of us 
that use "clang-format on save" could get without having to go through a 
compile phase in order to catch the warnings.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D135466

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Format/Format.h
  clang/lib/Format/Format.cpp
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/lib/Format/UnwrappedLineParser.h
  clang/unittests/Format/FormatTest.cpp

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -20281,6 +20281,7 @@
   CHECK_PARSE_BOOL(Cpp11BracedListStyle);
   CHECK_PARSE_BOOL(ReflowComments);
   CHECK_PARSE_BOOL(RemoveBracesLLVM);
+  CHECK_PARSE_BOOL(RemoveSemiColons);
   CHECK_PARSE_BOOL(SortUsingDeclarations);
   CHECK_PARSE_BOOL(SpacesInParentheses);
   CHECK_PARSE_BOOL(SpacesInSquareBrackets);
@@ -26740,6 +26741,22 @@
"inline bool var = is_integral_v && is_signed_v;");
 }
 
+TEST_F(FormatTest, RemoveSemiColons) {
+  FormatStyle Style = getLLVMStyle();
+  Style.InsertBraces = true;
+
+  verifyFormat("int max(int a, int b) { return a > b ? a : b; }",
+   "int max(int a, int b) { return a > b ? a : b; };", Style);
+
+  verifyFormat("class Foo {\n"
+   "  int getSomething() const { return something; }\n"
+   "};",
+   "class Foo {\n"
+   "  int getSomething() const { return something; };\n"
+   "};",
+   Style);
+}
+
 } // namespace
 } // namespace format
 } // namespace clang
Index: clang/lib/Format/UnwrappedLineParser.h
===
--- clang/lib/Format/UnwrappedLineParser.h
+++ clang/lib/Format/UnwrappedLineParser.h
@@ -111,7 +111,8 @@
   bool KeepBraces = true, IfStmtKind *IfKind = nullptr,
   bool UnindentWhitesmithsBraces = false,
   bool CanContainBracedList = true,
-  TokenType NextLBracesType = TT_Unknown);
+  TokenType NextLBracesType = TT_Unknown,
+  bool IsFunctionBlock = false);
   void parseChildBlock(bool CanContainBracedList = true,
TokenType NextLBracesType = TT_Unknown);
   void parsePPDirective();
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -839,7 +839,8 @@
 FormatToken *UnwrappedLineParser::parseBlock(
 bool MustBeDeclaration, unsigned AddLevels, bool MunchSemi, bool KeepBraces,
 IfStmtKind *IfKind, bool UnindentWhitesmithsBraces,
-bool CanContainBracedList, TokenType NextLBracesType) {
+bool CanContainBracedList, TokenType NextLBracesType,
+bool IsFunctionBlock) {
   auto HandleVerilogBlockLabel = [this]() {
 // ":" name
 if (Style.isVerilog() && FormatTok->is(tok::colon)) {
@@ -978,8 +979,17 @@
 parseStructuralElement();
   }
 
-  if (MunchSemi && FormatTok->is(tok::semi))
+  // When this is a function block and there is an unnecessary semicolon
+  // afterwards then mark it as optional (so the RemoveSemi pass can get rid of
+  // it later).
+  if (MunchSemi && FormatTok->is(tok::semi)) {
+if (IsFunctionBlock) {
+  FormatToken *Previous = Tokens->getPreviousToken();
+  if (Previous && Previous->is(tok::r_brace))
+FormatTok->Optional = true;
+}
 nextToken();

[PATCH] D133668: [HLSL] Use _BitInt(16) for int16_t to avoid promote to int.

2022-10-07 Thread Xiang Li via Phabricator via cfe-commits
python3kgae added a comment.

Hi, @rjmccall and @efriedma,
Could you take a look at this PR?
Or should I find someone else to review it?

Thanks
Xiang


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133668

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


[PATCH] D129755: Thread safety analysis: Support copy-elided production of scoped capabilities through arbitrary calls

2022-10-07 Thread Aaron Puchert via Phabricator via cfe-commits
aaronpuchert planned changes to this revision.
aaronpuchert added a comment.

In D129755#3843206 , @aaronpuchert 
wrote:

> Presumably `Cursor` is some kind of alias to `VmoCursor`, as we don't look at 
> base destructors yet. Since the code is not easily searchable for me, can you 
> look up the annotations on `DiscardableVmosLock::Get`, the constructor of 
> `Cursor`/`VmoCursor` being used here, `Cursor::lock_ref`, and `AssertHeld`?

Nevermind, I think I've found it 
:
 `lock_ref` has `TA_RET_CAP(lock_)`, so `cursor.lock_ref()` translates to 
`cursor.lock_`. So we have that lock. The destructor `~VmoCursor()` has 
`TA_REQ(lock_)` referring to the same lock. So that looks like a bug, I think 
we're missing the substitution somehow. Need to look into it.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129755

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


[PATCH] D129755: Thread safety analysis: Support copy-elided production of scoped capabilities through arbitrary calls

2022-10-07 Thread Gulfem Savrun Yeniceri via Phabricator via cfe-commits
gulfem added a comment.

In D129755#3843206 , @aaronpuchert 
wrote:

> In D129755#3843144 , @gulfem wrote:
>
>> We also started seeing `-Wthread-safety-precise` error in our Fuchsia code. 
>> https://luci-milo.appspot.com/ui/p/fuchsia/builders/ci/clang_toolchain.ci.core.x64-release/b8800959115965408001/overview
>> I'm trying to verify with our team whether it is a false positive, but I 
>> just wanted to give you heads up!
>
> Both places have 
> 
>
>   Cursor cursor(DiscardableVmosLock::Get(), ...);
>   AssertHeld(cursor.lock_ref());
>
> At the end of the scope we get
>
>   error: calling function '~VmoCursor' requires holding mutex 'lock_' 
> exclusively [-Werror,-Wthread-safety-precise]
>   note: found near match 'cursor.lock_'
>
> Presumably `Cursor` is some kind of alias to `VmoCursor`, as we don't look at 
> base destructors yet. Since the code is not easily searchable for me, can you 
> look up the annotations on `DiscardableVmosLock::Get`, the constructor of 
> `Cursor`/`VmoCursor` being used here, `Cursor::lock_ref`, and `AssertHeld`?

https://cs.opensource.google/fuchsia/fuchsia/+/main:zircon/kernel/vm/vm_cow_pages.cc
It looks like `Cursor` is an alias to `VmoCursor`.
https://cs.opensource.google/fuchsia/fuchsia/+/main:zircon/kernel/vm/include/vm/vm_cow_pages.h

> Edit: the second error seems to be same that @hans was posting. That's a true 
> positive sadly, we didn't emit a warning previously by accident.

Yes, that is the same error.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129755

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


[PATCH] D135091: Create storage for the `_cmd` argument to the helper function for generated getters/setters of `direct` Objective-C properties.

2022-10-07 Thread Michael Wyman via Phabricator via cfe-commits
mwyman added inline comments.



Comment at: clang/lib/CodeGen/CGObjC.cpp:1125
+llvm::Type *selType = CGF.ConvertType(CGF.getContext().getObjCSelType());
+return llvm::UndefValue::get(selType);
+  }

nlopes wrote:
> Please consider using PoisonValue here instead (if appropriate). We are 
> trying to get rid of undef.
> Thank you!
> A poison value is a result of an erroneous operation.

I could very well be misunderstanding, but based on this description from 
LangRef.html `PoisonValue` doesn't seem appropriate here; this is not 
"erroneous" behavior: it is just continuing the behavior prior to removing the 
`_cmd` implicit argument from the ABI, which was that the value was `undef` 
from the generated getter/setter's caller.

https://github.com/llvm/llvm-project/blob/49acab3f1408be9439a57833aa7b67678c9a05ba/clang/lib/CodeGen/CGObjCMac.cpp#L2142

Since this is (essentially) replicating that behavior, I'm not sure 
`PoisonValue` is what we want.



Comment at: clang/test/CodeGenObjC/direct-method.m:178
+// CHECK-NEXT: [[IVAR:%.*]] = load {{.*}} @"OBJC_IVAR_$_Root._objectProperty",
+// CHECK-NEXT: call i8* @objc_getProperty(i8* noundef [[SELF]], i8* noundef 
undef, i64 noundef [[IVAR]], {{.*}})
+

ahatanak wrote:
> `noundef` means the value isn't undefined, right? Is it safe to use it with 
> `undef`? We might want to fix this if it isn't.
It does feel questionable, however the pre-D131424 behavior was similar with 
the `undef` value coming from the caller and opaque to these generated 
getters/setters.

At least according to the OSS drop of `libobjc`, nothing in 
`objc_getProperty`/`objc_setProperty` actually references the `_cmd` argument 
so it seems safe-ish for now: 
https://github.com/apple-oss-distributions/objc4/blob/8701d5672d3fd3cd817aeb84db1077aafe1a1604/runtime/objc-accessors.mm#L48

FWIW, searching the code, I do see a handful of `noundef undef` in some other 
tests.


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

https://reviews.llvm.org/D135091

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


[PATCH] D135245: [clang][Tooling] Move STL recognizer to its own library

2022-10-07 Thread Kamau Bridgeman via Phabricator via cfe-commits
kamaub added a comment.

This change causes a linking failure during the `check-all` testing of 
'clang-tools-extra' on the clang-ppc64le-rhel #22596 
 and 
clang-ppc64le-linux-multistage #23864 
 build bots, please 
address this failure as soon as possible.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135245

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


[PATCH] D135199: [OpenMP][C++] Allow #pragma omp simd in constexpr functions

2022-10-07 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert added inline comments.



Comment at: clang/lib/AST/ExprConstant.cpp:8274-8279
 // Only if a local variable was declared in the function currently being
 // evaluated, do we expect to be able to find its value in the current
 // frame. (Otherwise it was likely declared in an enclosing context and
 // could either have a valid evaluatable value (for e.g. a constexpr
 // variable) or be ill-formed (and trigger an appropriate evaluation
 // diagnostic)).

aaron.ballman wrote:
> jdoerfert wrote:
> > aaron.ballman wrote:
> > > This comment no longer matches the code. It also suggests that the way to 
> > > address your issue is to capture the variable into the current frame -- 
> > > did you explore that approach?
> > The problem is that OpenMP introduces artificial capture statements. I am 
> > not sure if/how those can be "merged" into the parent context and in 
> > general that is not allowed (e.g., as we allow clauses on SIMD, like 
> > private). I feel the comment needs updating and I'll try that. 
> Is there a way to limit the change to only OpenMP captured variables so that 
> we're not changing the semantics for all language modes?
I could reasonably guard this to look for -fopenmp if we want to. The variables 
themselves are probably not easy to identify. I'll look at it again next week 
in the hope to make more sense of the intermediate frame and maybe avoid this 
to spill over to other models.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135199

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


[PATCH] D134330: [Docs] [HLSL] Add note about PCH support

2022-10-07 Thread Xiang Li via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG6a6f10fd23b2: [Docs] [HLSL] Add note about PCH support 
(authored by python3kgae).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134330

Files:
  clang/docs/HLSL/HLSLSupport.rst


Index: clang/docs/HLSL/HLSLSupport.rst
===
--- clang/docs/HLSL/HLSLSupport.rst
+++ clang/docs/HLSL/HLSLSupport.rst
@@ -89,6 +89,15 @@
 ``ExternalSemaSource`` to lazily complete data types, which is a **huge**
 performance win for HLSL.
 
+If precompiled headers are used when compiling HLSL, the ``ExternalSemaSource``
+will be a ``MultiplexExternalSemaSource`` which includes both the ``ASTReader``
+and ``HLSLExternalSemaSource``. For Built-in declarations that are already
+completed in the serialized AST, the ``HLSLExternalSemaSource`` will reuse the
+existing declarations and not introduce new declarations. If the built-in types
+are not completed in the serialized AST, the ``HLSLExternalSemaSource`` will
+create new declarations and connect the de-serialized decls as the previous
+declaration.
+
 CodeGen
 ---
 


Index: clang/docs/HLSL/HLSLSupport.rst
===
--- clang/docs/HLSL/HLSLSupport.rst
+++ clang/docs/HLSL/HLSLSupport.rst
@@ -89,6 +89,15 @@
 ``ExternalSemaSource`` to lazily complete data types, which is a **huge**
 performance win for HLSL.
 
+If precompiled headers are used when compiling HLSL, the ``ExternalSemaSource``
+will be a ``MultiplexExternalSemaSource`` which includes both the ``ASTReader``
+and ``HLSLExternalSemaSource``. For Built-in declarations that are already
+completed in the serialized AST, the ``HLSLExternalSemaSource`` will reuse the
+existing declarations and not introduce new declarations. If the built-in types
+are not completed in the serialized AST, the ``HLSLExternalSemaSource`` will
+create new declarations and connect the de-serialized decls as the previous
+declaration.
+
 CodeGen
 ---
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 6a6f10f - [Docs] [HLSL] Add note about PCH support

2022-10-07 Thread Xiang Li via cfe-commits

Author: Xiang Li
Date: 2022-10-07T10:49:21-07:00
New Revision: 6a6f10fd23b2730e2c01051541c5a83f5df9131b

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

LOG: [Docs] [HLSL] Add note about PCH support

PCH supported for HLSL is added when compile in -cc1 mode using -include-pch 
for test AST.
This change add some notes about the support of PCH for HLSL.

Reviewed By: beanz

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

Added: 


Modified: 
clang/docs/HLSL/HLSLSupport.rst

Removed: 




diff  --git a/clang/docs/HLSL/HLSLSupport.rst b/clang/docs/HLSL/HLSLSupport.rst
index a8c9c09b2e9f8..b091c17fd2a76 100644
--- a/clang/docs/HLSL/HLSLSupport.rst
+++ b/clang/docs/HLSL/HLSLSupport.rst
@@ -89,6 +89,15 @@ types and built-in templates. Clang is already designed to 
allow an attached
 ``ExternalSemaSource`` to lazily complete data types, which is a **huge**
 performance win for HLSL.
 
+If precompiled headers are used when compiling HLSL, the ``ExternalSemaSource``
+will be a ``MultiplexExternalSemaSource`` which includes both the ``ASTReader``
+and ``HLSLExternalSemaSource``. For Built-in declarations that are already
+completed in the serialized AST, the ``HLSLExternalSemaSource`` will reuse the
+existing declarations and not introduce new declarations. If the built-in types
+are not completed in the serialized AST, the ``HLSLExternalSemaSource`` will
+create new declarations and connect the de-serialized decls as the previous
+declaration.
+
 CodeGen
 ---
 



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


[PATCH] D133983: [HLSL] Add SV_DispatchThreadID

2022-10-07 Thread Chris Bieneman via Phabricator via cfe-commits
beanz added inline comments.



Comment at: clang/lib/CodeGen/CGHLSLRuntime.cpp:135
+llvm::Function *DxThreadID = CGM.getIntrinsic(Intrinsic::dx_thread_id);
+// dx_thread_id
+return buildVectorInput(B, DxThreadID, Ty);

nit: this comment doesn't add value



Comment at: clang/lib/CodeGen/CGHLSLRuntime.cpp:166
+  unsigned SRetOffset = 0;
+  for (auto &Param : Fn->args()) {
+if (Param.hasStructRetAttr()) {

Was dropping the `const` here intentional? Getting the parameter's type 
shouldn't modify it.



Comment at: clang/test/CodeGenHLSL/sret_output.hlsl:5
+
+// FIXME: add semantic to a
+// See https://github.com/llvm/llvm-project/issues/57874





Comment at: clang/test/CodeGenHLSL/sret_output.hlsl:18
+};
\ No newline at end of file


add newline to the end of the file


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133983

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


[PATCH] D135397: [clang][dataflow] Add support for a Top value in boolean formulas.

2022-10-07 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel updated this revision to Diff 466124.
ymandel marked an inline comment as done.
ymandel added a comment.

Address (most) comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135397

Files:
  clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h
  clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
  clang/include/clang/Analysis/FlowSensitive/Value.h
  clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
  clang/lib/Analysis/FlowSensitive/DebugSupport.cpp
  clang/lib/Analysis/FlowSensitive/Transfer.cpp
  clang/lib/Analysis/FlowSensitive/WatchedLiteralsSolver.cpp
  clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp

Index: clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
===
--- clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
+++ clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
@@ -17,6 +17,7 @@
 #include "clang/Analysis/FlowSensitive/DataflowAnalysisContext.h"
 #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
 #include "clang/Analysis/FlowSensitive/DataflowLattice.h"
+#include "clang/Analysis/FlowSensitive/DebugSupport.h"
 #include "clang/Analysis/FlowSensitive/NoopAnalysis.h"
 #include "clang/Analysis/FlowSensitive/Value.h"
 #include "clang/Analysis/FlowSensitive/WatchedLiteralsSolver.h"
@@ -166,7 +167,7 @@
 auto CS = Elt->getAs();
 if (!CS)
   return;
-auto S = CS->getStmt();
+const auto *S = CS->getStmt();
 if (auto *C = dyn_cast(S)) {
   if (auto *F = dyn_cast(C->getCalleeDecl())) {
 E.CalledFunctions.insert(F->getNameInfo().getAsString());
@@ -322,7 +323,7 @@
 auto CS = Elt->getAs();
 if (!CS)
   return;
-auto S = CS->getStmt();
+const auto *S = CS->getStmt();
 auto SpecialBoolRecordDecl = recordDecl(hasName("SpecialBool"));
 auto HasSpecialBoolType = hasType(SpecialBoolRecordDecl);
 
@@ -468,9 +469,8 @@
 class OptionalIntAnalysis
 : public DataflowAnalysis {
 public:
-  explicit OptionalIntAnalysis(ASTContext &Context, BoolValue &HasValueTop)
-  : DataflowAnalysis(Context),
-HasValueTop(HasValueTop) {}
+  explicit OptionalIntAnalysis(ASTContext &Context)
+  : DataflowAnalysis(Context) {}
 
   static NoopLattice initialElement() { return {}; }
 
@@ -478,22 +478,23 @@
 auto CS = Elt->getAs();
 if (!CS)
   return;
-auto S = CS->getStmt();
+const Stmt *S = CS->getStmt();
 auto OptionalIntRecordDecl = recordDecl(hasName("OptionalInt"));
 auto HasOptionalIntType = hasType(OptionalIntRecordDecl);
 
+SmallVector Matches = match(
+stmt(anyOf(cxxConstructExpr(HasOptionalIntType).bind("construct"),
+   cxxOperatorCallExpr(
+   callee(cxxMethodDecl(ofClass(OptionalIntRecordDecl
+   .bind("operator"))),
+*S, getASTContext());
 if (const auto *E = selectFirst(
-"call", match(cxxConstructExpr(HasOptionalIntType).bind("call"), *S,
-  getASTContext( {
+"construct", Matches)) {
   auto &ConstructorVal = *Env.createValue(E->getType());
   ConstructorVal.setProperty("has_value", Env.getBoolLiteralValue(false));
   Env.setValue(*Env.getStorageLocation(*E, SkipPast::None), ConstructorVal);
-} else if (const auto *E = selectFirst(
-   "call",
-   match(cxxOperatorCallExpr(callee(cxxMethodDecl(ofClass(
- OptionalIntRecordDecl
- .bind("call"),
- *S, getASTContext( {
+} else if (const auto *E =
+   selectFirst("operator", Matches)) {
   assert(E->getNumArgs() > 0);
   auto *Object = E->getArg(0);
   assert(Object != nullptr);
@@ -516,7 +517,11 @@
 Type->getAsCXXRecordDecl()->getQualifiedNameAsString() != "OptionalInt")
   return false;
 
-return Val1.getProperty("has_value") == Val2.getProperty("has_value");
+auto *Prop1  = Val1.getProperty("has_value");
+auto *Prop2 = Val2.getProperty("has_value");
+return Prop1 == Prop2 ||
+   (Prop1 != nullptr && Prop2 != nullptr && isa(Prop1) &&
+isa(Prop2));
   }
 
   bool merge(QualType Type, const Value &Val1, const Environment &Env1,
@@ -538,11 +543,9 @@
 if (HasValue1 == HasValue2)
   MergedVal.setProperty("has_value", *HasValue1);
 else
-  MergedVal.setProperty("has_value", HasValueTop);
+  MergedVal.setProperty("has_value", MergedEnv.makeTopBoolValue());
 return true;
   }
-
-  BoolValue &HasValueTop;
 };
 
 class WideningTest : public Test {
@@ -561,11 +564,8 @@
 checkDataflow(
 AnalysisInputs(
 Code, ast_matchers::hasName("target"),
-

[clang-tools-extra] bb4f0af - [clangd] Fix buildbots after d1f13c54f172875d9a14c46c09afb1f22d78cdf8

2022-10-07 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2022-10-07T20:10:32+02:00
New Revision: bb4f0af97dba600c50a0f727b25a760e8185c578

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

LOG: [clangd] Fix buildbots after d1f13c54f172875d9a14c46c09afb1f22d78cdf8

Added: 


Modified: 
clang-tools-extra/clangd/unittests/CMakeLists.txt

Removed: 




diff  --git a/clang-tools-extra/clangd/unittests/CMakeLists.txt 
b/clang-tools-extra/clangd/unittests/CMakeLists.txt
index 692d7f8038d95..af94cc5b270de 100644
--- a/clang-tools-extra/clangd/unittests/CMakeLists.txt
+++ b/clang-tools-extra/clangd/unittests/CMakeLists.txt
@@ -153,6 +153,7 @@ clang_target_link_libraries(ClangdTests
   clangTooling
   clangToolingCore
   clangToolingInclusions
+  clangToolingInclusionsStdlib
   clangToolingRefactoring
   clangToolingSyntax
   )



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


[PATCH] D135397: [clang][dataflow] Add support for a Top value in boolean formulas.

2022-10-07 Thread Yitzhak Mandelbaum via Phabricator via cfe-commits
ymandel marked 11 inline comments as done.
ymandel added inline comments.



Comment at: clang/lib/Analysis/FlowSensitive/WatchedLiteralsSolver.cpp:237-238
+  case Value::Kind::Top:
+// Nothing more to do. Each `Top` instance will be mapped to a fresh
+// variable and is thereafter anonymous.
+break;

gribozavr2 wrote:
> 
regarding the latter clause -- its freedom *does* affect satisfiability. e.g.` 
A || Top` is trivially satisfiable. I'm just going to drop the "and ...".



Comment at: 
clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp:527-528
+auto *Prop2 = Val2.getProperty("has_value");
+return Prop1 == Prop2 || (Prop1 != nullptr && Prop2 != nullptr &&
+  isTop(*Prop1) && isTop(*Prop2));
   }

xazax.hun wrote:
> I feel like this logic is repeated multiple times. I wonder if we should 
> define an `operator==` for `const BoolValue*`.
Agreed.  I want to wait until we settle on the representation and then we can 
consider this operator. But, if we end up with a singleton Top then I think we 
can hold off.



Comment at: 
clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp:1192
+ const Environment &Env1, const Value &Val2,
+ const Environment &Env2) final {
+// Changes to a sounds approximation, which allows us to test whether we 
can

xazax.hun wrote:
> Nit: I usually prefer marking whole classes final rather than individual 
> virtual methods, but feel free to leave as is.
Good point. I was following what's done elsewhere in the file -- I think we 
should update all or nothing. that said, if you mark the class final, then what 
do you do with each method? nothing or `override`?



Comment at: 
clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp:1302-1311
+void target(bool Cond) {
+  bool Foo = makeTop();
+  // Force a new block.
+  if (false) return;
+  (void)0;
+  /*[[p1]]*/
+

gribozavr2 wrote:
> Similarly in tests below.
> 
> `if (false)` theoretically could be handled in a special way in future and 
> could be folded away during CFG construction.
Sure. I went with a different name since it's playing a very specific role 
that's not related to the test in the way that `Cond` is.



Comment at: 
clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp:1454
+  });
+}
+

gribozavr2 wrote:
> Could you add a variant of this test?
> 
> ```
> void target(bool Cond) {
>   bool Foo = makeTop();
>   // Force a new block.
>   if (false) return;
>   (void)0;
>   /*[[p1]]*/
> 
>   bool Zab;
>   if (Cond) {
> Zab = Foo;
>   } else {
> Zab = Foo;
>   }
>   (void)0;
>   if (Zab == Foo) { return; }
>   /*[[p2]]*/
> }
> ```
> 
> Show the loss of precision by checking that the flow condition for p2 is 
> satisfiable.
Added, but there's no loss of precision and so the test demonstrates that. My 
initial instinct was that there would be loss, but the guard of `Cond` actually 
preserves the precision. The cost is complexity -- Zab is a fresh atomic and 
the flow condition encoded enough information to recover its equivalence to 
`Foo`. But, it is not _equal_ to `Foo`, which would be nice.

The case where we lose precision is a loop, where the incoming edge doesn't 
carry a condition.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135397

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


[PATCH] D135328: [CUDA] Refactored CUDA version housekeeping to use less boilerplate.

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

@yaxunl - Are you OK with the patch? PTAL.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135328

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


[PATCH] D135397: [clang][dataflow] Add support for a Top value in boolean formulas.

2022-10-07 Thread Dmitri Gribenko via Phabricator via cfe-commits
gribozavr2 accepted this revision.
gribozavr2 added inline comments.



Comment at: 
clang/include/clang/Analysis/FlowSensitive/DataflowAnalysisContext.h:157
+  TopValue &createTop() {
+return takeOwnership(std::make_unique());
+  }

ymandel wrote:
> xazax.hun wrote:
> > gribozavr2 wrote:
> > > Should we be creating a new top every time, or should it be a singleton 
> > > like true and false?
> > > 
> > > It seems like we explicitly don't care about its identity (or else it 
> > > would be isomorphic to AtomicBool).
> > Good point, a singleton Top might actually simplify some parts of the code.
> Good question. That was my initial implementation, but it ran into the 
> problem that the solver (in `buildBooleanFormula`) maps each unique (by 
> pointer) subexpression into a fresh SAT variable in . If we use a singleton 
> Top, we need to modify that algorithm appropriately. I'm open to suggestions, 
> though, because of the advantages of a singleton Top.
> 
> If we assume that a given `Top` is never actually shared in a boolean formula 
> (unlike other subexpressions, which may be shared), then we can use a 
> singleton and special case it in `buildBooleanFormula`. I think that's a good 
> assumption, but am not sure. Thoughts?
I see. Could you add some direct tests for the SAT solver with formulas that 
include Top to check the behavior we care about?



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135397

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


[PATCH] D135471: [CMake] Drop libLTO and switch to PIE for Fuchsia toolchain

2022-10-07 Thread Petr Hosek via Phabricator via cfe-commits
phosek created this revision.
phosek added a reviewer: abrachet.
Herald added a subscriber: inglorion.
Herald added a project: All.
phosek requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

All our users have migrated to ld64.lld so we no longer need libLTO.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D135471

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


Index: clang/cmake/caches/Fuchsia-stage2.cmake
===
--- clang/cmake/caches/Fuchsia-stage2.cmake
+++ clang/cmake/caches/Fuchsia-stage2.cmake
@@ -14,6 +14,7 @@
 set(LLVM_ENABLE_LLD ON CACHE BOOL "")
 set(LLVM_ENABLE_LTO ON CACHE BOOL "")
 set(LLVM_ENABLE_PER_TARGET_RUNTIME_DIR ON CACHE BOOL "")
+set(LLVM_ENABLE_PIC OFF CACHE BOOL "")
 set(LLVM_ENABLE_PLUGINS OFF CACHE BOOL "")
 set(LLVM_ENABLE_TERMINFO OFF CACHE BOOL "")
 set(LLVM_ENABLE_UNWIND_TABLES OFF CACHE BOOL "")
@@ -289,7 +290,6 @@
 set(LLVM_DISTRIBUTION_COMPONENTS
   clang
   lld
-  LTO
   clang-apply-replacements
   clang-doc
   clang-format


Index: clang/cmake/caches/Fuchsia-stage2.cmake
===
--- clang/cmake/caches/Fuchsia-stage2.cmake
+++ clang/cmake/caches/Fuchsia-stage2.cmake
@@ -14,6 +14,7 @@
 set(LLVM_ENABLE_LLD ON CACHE BOOL "")
 set(LLVM_ENABLE_LTO ON CACHE BOOL "")
 set(LLVM_ENABLE_PER_TARGET_RUNTIME_DIR ON CACHE BOOL "")
+set(LLVM_ENABLE_PIC OFF CACHE BOOL "")
 set(LLVM_ENABLE_PLUGINS OFF CACHE BOOL "")
 set(LLVM_ENABLE_TERMINFO OFF CACHE BOOL "")
 set(LLVM_ENABLE_UNWIND_TABLES OFF CACHE BOOL "")
@@ -289,7 +290,6 @@
 set(LLVM_DISTRIBUTION_COMPONENTS
   clang
   lld
-  LTO
   clang-apply-replacements
   clang-doc
   clang-format
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D135472: [ODRHash] Hash attributes on declarations.

2022-10-07 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai created this revision.
vsapsai added reviewers: rtrieu, aaron.ballman, ChuanqiXu, Bigcheese.
Herald added a subscriber: ributzka.
Herald added a project: All.
vsapsai requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Arguments not for all attributes are covered. More can be added later as
needed.

rdar://100482330


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D135472

Files:
  clang/include/clang/AST/ODRDiagsEmitter.h
  clang/include/clang/AST/ODRHash.h
  clang/include/clang/Basic/DiagnosticASTKinds.td
  clang/lib/AST/ODRDiagsEmitter.cpp
  clang/lib/AST/ODRHash.cpp
  clang/test/Modules/odr_hash.cpp

Index: clang/test/Modules/odr_hash.cpp
===
--- clang/test/Modules/odr_hash.cpp
+++ clang/test/Modules/odr_hash.cpp
@@ -3637,6 +3637,202 @@
 #endif
 }  // namespace DependentSizedExtVector
 
+namespace Attributes {
+#if defined(FIRST)
+struct __attribute__((packed)) PackingPresence {
+  char x;
+  long y;
+};
+#elif defined(SECOND)
+struct PackingPresence {
+  char x;
+  long y;
+};
+#else
+PackingPresence testPackingAttributePresence;
+// expected-error@first.h:* {{'Types::Attributes::PackingPresence' has different definitions in different modules; first difference is definition in module 'FirstModule' found attribute 'packed'}}
+// expected-note@first.h:* {{attribute specified here}}
+// expected-note@second.h:* {{but in 'SecondModule' found no attribute}}
+#endif
+
+#if defined(FIRST)
+struct AlignmentPresence {
+  char x;
+  alignas(8) char y;
+};
+struct DifferentAlignmentKeywords {
+  char x;
+  char __attribute__((aligned(8))) y;
+};
+struct DifferentAlignmentValues {
+  char x;
+  alignas(4) char y;
+};
+struct AlignmentWithTypedefType {
+  char x;
+  alignas(float) char y;
+};
+#elif defined(SECOND)
+struct AlignmentPresence {
+  char x;
+  char y;
+};
+struct DifferentAlignmentKeywords {
+  char x;
+  alignas(8) char y;
+};
+struct DifferentAlignmentValues {
+  char x;
+  alignas(8) char y;
+};
+typedef float MyFloat;
+struct AlignmentWithTypedefType {
+  char x;
+  alignas(MyFloat) char y;
+};
+#else
+AlignmentPresence testAlignmentAttributePresence;
+// expected-error@first.h:* {{'Types::Attributes::AlignmentPresence' has different definitions in different modules; first difference is definition in module 'FirstModule' found 'y' with attribute 'alignas'}}
+// expected-note@first.h:* {{attribute specified here}}
+// expected-note@second.h:* {{but in 'SecondModule' found 'y' with no attribute}}
+DifferentAlignmentKeywords testDifferentAlignmentKeywords; // expected no errors as different keywords have the same meaning
+DifferentAlignmentValues testDifferentAlignments;
+// expected-error@first.h:* {{'Types::Attributes::DifferentAlignmentValues' has different definitions in different modules; first difference is definition in module 'FirstModule' found 'y' with attribute ' alignas(4)'}}
+// expected-note@first.h:* {{attribute specified here}}
+// expected-note@second.h:* {{but in 'SecondModule' found 'y' with different attribute argument ' alignas(8)'}}
+// expected-note@second.h:* {{attribute specified here}}
+AlignmentWithTypedefType testAligningAsTheSameTypeButDifferentName;
+// expected-error@first.h:* {{'Types::Attributes::AlignmentWithTypedefType' has different definitions in different modules; first difference is definition in module 'FirstModule' found 'y' with attribute ' alignas(alignof(float))'}}
+// expected-note@first.h:* {{attribute specified here}}
+// expected-note@second.h:* {{but in 'SecondModule' found 'y' with different attribute argument ' alignas(alignof(MyFloat))'}}
+// expected-note@second.h:* {{attribute specified here}}
+#endif
+
+#if defined(FIRST)
+struct AttributeOnMethod {
+  int test(int x, int y);
+};
+struct AttributeOnStaticField {
+  __attribute__((unused)) static int x;
+};
+#elif defined(SECOND)
+struct AttributeOnMethod {
+  __attribute__((optnone)) int test(int x, int y);
+};
+struct AttributeOnStaticField {
+  static int x;
+};
+#else
+AttributeOnMethod testAttributeDifferenceOnMethods;
+// expected-error@first.h:* {{'Types::Attributes::AttributeOnMethod' has different definitions in different modules; first difference is definition in module 'FirstModule' found 'test' with no attribute}}
+// expected-note@second.h:* {{but in 'SecondModule' found 'test' with attribute 'optnone'}}
+// expected-note@second.h:* {{attribute specified here}}
+AttributeOnStaticField testAttributeDifferenceOnStaticFields;
+// expected-error@first.h:* {{'Types::Attributes::AttributeOnStaticField' has different definitions in different modules; first difference is definition in module 'FirstModule' found 'x' with attribute 'unused'}}
+// expected-note@first.h:* {{attribute specified here}}
+// expected-note@second.h:* {{but in 'SecondModule' found 'x' with no attribute}}
+#endif
+
+#if defined(FIRST)
+struct __attribute__((packed)) __attribute_

[PATCH] D135472: [ODRHash] Hash attributes on declarations.

2022-10-07 Thread Volodymyr Sapsai via Phabricator via cfe-commits
vsapsai added inline comments.



Comment at: clang/lib/AST/ODRHash.cpp:479-480
+
+  llvm::copy_if(D->attrs(), std::back_inserter(HashableAttrs),
+[](const Attr *A) { return !A->isImplicit(); });
+}

I'm not sure `isImplicit` is the best indicator of attributes to check, so 
suggestions in this area are welcome. I think we can start strict and relax 
some of the checks if needed.

If people have strong opinions that some attributes shouldn't be ignored, we 
can add them to the tests to avoid regressions. Personally, I believe that 
alignment and packed attributes should never be silently ignored.



Comment at: clang/test/Modules/odr_hash.cpp:3640
 
+namespace Attributes {
+#if defined(FIRST)

As we land hashing for C and Objective-C, we can move these tests to their own 
file. But for now I think it makes sense to keep everything in odr_hash.cpp. 
Though I don't have a strong preference.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135472

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


[PATCH] D135177: [clang] adds `__is_scoped_enum`, `__is_nullptr`, and `__is_referenceable`

2022-10-07 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/test/SemaCXX/type-traits.cpp:374
 
+void is_scoped_enum() {
+  static_assert(!__is_scoped_enum(Enum), "");

It'd probably not be a bad idea at some point to add test coverage for 
incomplete types.



Comment at: clang/test/SemaCXX/type-traits.cpp:822
+
+  { int a[F(__is_referenceable(void))]; }
+}

I think we should have test cases for the following:
```
struct incomplete;

__is_referenceable(struct incomplete); // Also interesting to make sure we 
handle elaborated type specifiers properly

typedef void function_type(int);
__is_referenceable(function_type); // Note, this is not a function *pointer* 
type

struct S {
  void func1() &;
  void func2() const;
};

// Both of these should be false, by my understanding of what "referenceable" 
means in the standard.
__is_referenceable(decltype(&S::func1));
__is_referenceable(decltype(&S::func2));
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135177

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


[PATCH] D135471: [CMake] Drop libLTO and switch to PIE for Fuchsia toolchain

2022-10-07 Thread Alex Brachet via Phabricator via cfe-commits
abrachet accepted this revision.
abrachet added a comment.
This revision is now accepted and ready to land.

Nice thats 71mb saved :)


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135471

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


[PATCH] D135177: [clang] adds `__is_scoped_enum`, `__is_nullptr`, and `__is_referenceable`

2022-10-07 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.

Assuming the additional test cases don't uncover any surprises, this LGTM as 
well (modulo nits already brought up).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135177

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


[PATCH] D133983: [HLSL] Add SV_DispatchThreadID

2022-10-07 Thread Xiang Li via Phabricator via cfe-commits
python3kgae updated this revision to Diff 466141.
python3kgae marked 5 inline comments as done.
python3kgae added a comment.

Fix test fail after rebase and code cleanup to match comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133983

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Basic/AttrDocs.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/CodeGen/CGHLSLRuntime.cpp
  clang/lib/CodeGen/CGHLSLRuntime.h
  clang/lib/Parse/ParseHLSL.cpp
  clang/lib/Sema/SemaDeclAttr.cpp
  clang/test/CodeGenHLSL/semantics/DispatchThreadID.hlsl
  clang/test/CodeGenHLSL/sret_output.hlsl
  clang/test/SemaHLSL/Semantics/entry_parameter.hlsl
  clang/test/SemaHLSL/Semantics/invalid_entry_parameter.hlsl
  clang/test/SemaHLSL/Semantics/valid_entry_parameter.hlsl

Index: clang/test/SemaHLSL/Semantics/valid_entry_parameter.hlsl
===
--- /dev/null
+++ clang/test/SemaHLSL/Semantics/valid_entry_parameter.hlsl
@@ -0,0 +1,26 @@
+// RUN: %clang_cc1 -triple dxil-pc-shadermodel6.0-compute -x hlsl  -finclude-default-header -ast-dump  -o - %s | FileCheck %s
+
+[numthreads(8,8,1)]
+void CSMain(uint ID : SV_DispatchThreadID) {
+// CHECK: FunctionDecl 0x{{[0-9a-fA-F]+}} <{{.*}}> line:[[@LINE-1]]:6 CSMain 'void (uint)'
+// CHECK-NEXT: ParmVarDecl 0x{{[0-9a-fA-F]+}} <{{.*}}> col:18 ID 'uint'
+// CHECK-NEXT: HLSLSV_DispatchThreadIDAttr
+}
+[numthreads(8,8,1)]
+void CSMain1(uint2 ID : SV_DispatchThreadID) {
+// CHECK: FunctionDecl 0x{{[0-9a-fA-F]+}} <{{.*}}> line:[[@LINE-1]]:6 CSMain1 'void (uint2)'
+// CHECK-NEXT: ParmVarDecl 0x{{[0-9a-fA-F]+}} <{{.*}}> col:20 ID 'uint2'
+// CHECK-NEXT: HLSLSV_DispatchThreadIDAttr
+}
+[numthreads(8,8,1)]
+void CSMain2(uint3 ID : SV_DispatchThreadID) {
+// CHECK: FunctionDecl 0x{{[0-9a-fA-F]+}} <{{.*}}> line:[[@LINE-1]]:6 CSMain2 'void (uint3)'
+// CHECK-NEXT: ParmVarDecl 0x{{[0-9a-fA-F]+}} <{{.*}}> col:20 ID 'uint3'
+// CHECK-NEXT: HLSLSV_DispatchThreadIDAttr
+}
+[numthreads(8,8,1)]
+void CSMain3(uint3 : SV_DispatchThreadID) {
+// CHECK: FunctionDecl 0x{{[0-9a-fA-F]+}} <{{.*}}> line:[[@LINE-1]]:6 CSMain3 'void (uint3)'
+// CHECK-NEXT: ParmVarDecl 0x{{[0-9a-fA-F]+}} <{{.*}}> col:20 'uint3'
+// CHECK-NEXT: HLSLSV_DispatchThreadIDAttr
+}
Index: clang/test/SemaHLSL/Semantics/invalid_entry_parameter.hlsl
===
--- /dev/null
+++ clang/test/SemaHLSL/Semantics/invalid_entry_parameter.hlsl
@@ -0,0 +1,30 @@
+// RUN: %clang_cc1 -triple dxil-pc-shadermodel6.3-library -finclude-default-header -x hlsl -ast-dump -verify -o - %s
+
+[numthreads(8,8,1)]
+// expected-error@+1 {{attribute 'SV_DispatchThreadID' only applies to a field or parameter of type 'uint/uint2/uint3'}}
+void CSMain(float ID : SV_DispatchThreadID) {
+
+}
+
+struct ST {
+  int a;
+  float b;
+};
+[numthreads(8,8,1)]
+// expected-error@+1 {{attribute 'SV_DispatchThreadID' only applies to a field or parameter of type 'uint/uint2/uint3'}}
+void CSMain2(ST ID : SV_DispatchThreadID) {
+
+}
+
+void foo() {
+// expected-warning@+1 {{'SV_DispatchThreadID' attribute only applies to parameters and non-static data members}}
+  uint V : SV_DispatchThreadID;
+
+}
+
+struct ST2 {
+// expected-error@+1 {{use of undeclared identifier 'SV_DispatchThreadID'}}
+static uint X : SV_DispatchThreadID;
+// expected-error@+1 {{use of undeclared identifier 'SV_DispatchThreadID'}}
+uint s : SV_DispatchThreadID;
+};
Index: clang/test/SemaHLSL/Semantics/entry_parameter.hlsl
===
--- clang/test/SemaHLSL/Semantics/entry_parameter.hlsl
+++ clang/test/SemaHLSL/Semantics/entry_parameter.hlsl
@@ -1,10 +1,13 @@
-// RUN: %clang_cc1 -triple dxil-pc-shadermodel6.0-compute -x hlsl -ast-dump -o - %s | FileCheck %s 
-// RUN: %clang_cc1 -triple dxil-pc-shadermodel6.0-mesh -x hlsl -ast-dump -verify -o - %s 
+// RUN: %clang_cc1 -triple dxil-pc-shadermodel6.0-compute -x hlsl  -finclude-default-header  -ast-dump -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple dxil-pc-shadermodel6.0-mesh -x hlsl -ast-dump  -finclude-default-header  -verify -o - %s
 
-[numthreads(8,8, 1)]
-// expected-error@+1 {{attribute 'SV_GroupIndex' is unsupported in Mesh shaders, requires Compute}}
-void CSMain(int GI : SV_GroupIndex) {
-// CHECK: FunctionDecl 0x{{[0-9a-fA-F]+}} <{{.*}}> line:[[@LINE-1]]:6 CSMain 'void (int)'
+[numthreads(8,8,1)]
+// expected-error@+2 {{attribute 'SV_GroupIndex' is unsupported in Mesh shaders, requires Compute}}
+// expected-error@+1 {{attribute 'SV_DispatchThreadID' is unsupported in Mesh shaders, requires Compute}}
+void CSMain(int GI : SV_GroupIndex, uint ID : SV_DispatchThreadID) {
+// CHECK: FunctionDecl 0x{{[0-9a-fA-F]+}} <{{.*}}> line:[[@LINE-1]]:6 CSMain 'void (int, uint)'
 // CHECK-NEXT: ParmVarDecl 0x{{[0-9a-fA-F]+}} <{{.*}}> col:17 GI 'int'
 // CHECK-NEXT: HLSLSV_GroupIndex

[PATCH] D135466: [clang-format] Add support to remove unnecessary semicolons after function definition

2022-10-07 Thread Jakub Klinkovský via Phabricator via cfe-commits
lahwaacz added inline comments.



Comment at: clang/docs/ClangFormatStyleOptions.rst:3769
+   care should be taken to review code changes made by this option.
+   NOTE:
+   Setting this to false will not add `;` where they were missing

Nit: the note should probably not be part of the warning.



Comment at: clang/docs/ClangFormatStyleOptions.rst:3779
+  return a>b?a:b;return a>b?a:b;
+}; };
+

There is an extra `;` in the `true` case ;-)



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135466

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


[PATCH] D134369: [Clang] Support constexpr builtin fmax

2022-10-07 Thread Joshua Cranmer via Phabricator via cfe-commits
jcranmer-intel added inline comments.



Comment at: clang/lib/AST/ExprConstant.cpp:14029-14030
+  case Builtin::BI__builtin_fmaxf16:
+  case Builtin::BI__builtin_fmaxf128: {
+APFloat RHS(0.);
+if (!EvaluateFloat(E->getArg(0), Result, Info) ||

I think you should add a comment saying `// TODO: Handle sNaN`, just so that we 
remember to revisit this later.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134369

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


[PATCH] D135476: [clang-tidy] Support concepts in `bugprone-forwarding-reference-overload`

2022-10-07 Thread Evgeny Shulgin via Phabricator via cfe-commits
Izaron created this revision.
Izaron added reviewers: hokein, aaron.ballman, LegalizeAdulthood, njames93.
Herald added subscribers: carlosgalvezp, xazax.hun.
Herald added a project: All.
Izaron requested review of this revision.
Herald added a project: clang-tools-extra.
Herald added a subscriber: cfe-commits.

Ignore constrained perfect forwarding constructors.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D135476

Files:
  clang-tools-extra/clang-tidy/bugprone/ForwardingReferenceOverloadCheck.cpp
  
clang-tools-extra/docs/clang-tidy/checks/bugprone/forwarding-reference-overload.rst
  
clang-tools-extra/test/clang-tidy/checkers/bugprone/forwarding-reference-overload.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/bugprone/forwarding-reference-overload.cpp
===
--- 
clang-tools-extra/test/clang-tidy/checkers/bugprone/forwarding-reference-overload.cpp
+++ 
clang-tools-extra/test/clang-tidy/checkers/bugprone/forwarding-reference-overload.cpp
@@ -1,4 +1,4 @@
-// RUN: %check_clang_tidy %s bugprone-forwarding-reference-overload %t
+// RUN: %check_clang_tidy -std=c++20 %s bugprone-forwarding-reference-overload 
%t
 
 namespace std {
 template  struct enable_if { typedef T type; };
@@ -251,3 +251,20 @@
   Test10(T &&Item, E e)
   : e(e){}
 };
+
+class Test11 {
+public:
+  // Guarded with requires expression.
+  template 
+  requires requires { just_true; }
+  Test11(T &&n);
+};
+
+template
+concept JustTrueConcept = requires { just_true; };
+
+class Test12 {
+public:
+  // Guarded with concept requirement.
+  template  Test12(T &&n);
+};
Index: 
clang-tools-extra/docs/clang-tidy/checks/bugprone/forwarding-reference-overload.rst
===
--- 
clang-tools-extra/docs/clang-tidy/checks/bugprone/forwarding-reference-overload.rst
+++ 
clang-tools-extra/docs/clang-tidy/checks/bugprone/forwarding-reference-overload.rst
@@ -34,6 +34,15 @@
 enable_if_t, A&&...>, int> = 0>
   explicit Person(A&&... a) {}
 
+  // C5: perfect forwarding ctor guarded with requires expression
+  template
+  requires requires { is_special; }
+  explicit Person(T&& n) {}
+
+  // C6: perfect forwarding ctor guarded with concept requirement
+  template
+  explicit Person(T&& n) {}
+
   // (possibly compiler generated) copy ctor
   Person(const Person& rhs);
 };
@@ -42,7 +51,7 @@
 constructors. We suppress warnings if the copy and the move constructors are 
both
 disabled (deleted or private), because there is nothing the perfect forwarding
 constructor could hide in this case. We also suppress warnings for constructors
-like C3 and C4 that are guarded with an ``enable_if``, assuming the programmer 
was
+like C3-C6 that are guarded with an ``enable_if`` or a concept, assuming the 
programmer was
 aware of the possible hiding.
 
 Background
Index: 
clang-tools-extra/clang-tidy/bugprone/ForwardingReferenceOverloadCheck.cpp
===
--- clang-tools-extra/clang-tidy/bugprone/ForwardingReferenceOverloadCheck.cpp
+++ clang-tools-extra/clang-tidy/bugprone/ForwardingReferenceOverloadCheck.cpp
@@ -58,6 +58,9 @@
   return Node.hasDefaultArgument() &&
  TypeMatcher.matches(Node.getDefaultArgument(), Finder, Builder);
 }
+AST_MATCHER(TemplateDecl, hasAssociatedConstraints) {
+  return Node.hasAssociatedConstraints();
+}
 } // namespace
 
 void ForwardingReferenceOverloadCheck::registerMatchers(MatchFinder *Finder) {
@@ -76,6 +79,9 @@
   // No warning: enable_if as constructor parameter.
   parmVarDecl(hasType(isEnableIf(),
   unless(hasParent(functionTemplateDecl(anyOf(
+  // No warning: has associated constraints (like requires
+  // expression).
+  hasAssociatedConstraints(),
   // No warning: enable_if as type parameter.
   has(templateTypeParmDecl(hasDefaultArgument(isEnableIf(,
   // No warning: enable_if as non-type template parameter.


Index: clang-tools-extra/test/clang-tidy/checkers/bugprone/forwarding-reference-overload.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/bugprone/forwarding-reference-overload.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone/forwarding-reference-overload.cpp
@@ -1,4 +1,4 @@
-// RUN: %check_clang_tidy %s bugprone-forwarding-reference-overload %t
+// RUN: %check_clang_tidy -std=c++20 %s bugprone-forwarding-reference-overload %t
 
 namespace std {
 template  struct enable_if { typedef T type; };
@@ -251,3 +251,20 @@
   Test10(T &&Item, E e)
   : e(e){}
 };
+
+class Test11 {
+public:
+  // Guarded with requires expression.
+  template 
+  requires requires { just_true; }
+  Test11(T &&n);
+};
+
+template
+concept JustTrueConcept = requires { just_true; };
+
+clas

[PATCH] D135476: [clang-tidy] Support concepts in `bugprone-forwarding-reference-overload`

2022-10-07 Thread Evgeny Shulgin via Phabricator via cfe-commits
Izaron updated this revision to Diff 466147.
Izaron added a comment.

Fixes https://github.com/llvm/llvm-project/issues/58230


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135476

Files:
  clang-tools-extra/clang-tidy/bugprone/ForwardingReferenceOverloadCheck.cpp
  
clang-tools-extra/docs/clang-tidy/checks/bugprone/forwarding-reference-overload.rst
  
clang-tools-extra/test/clang-tidy/checkers/bugprone/forwarding-reference-overload.cpp


Index: 
clang-tools-extra/test/clang-tidy/checkers/bugprone/forwarding-reference-overload.cpp
===
--- 
clang-tools-extra/test/clang-tidy/checkers/bugprone/forwarding-reference-overload.cpp
+++ 
clang-tools-extra/test/clang-tidy/checkers/bugprone/forwarding-reference-overload.cpp
@@ -1,4 +1,4 @@
-// RUN: %check_clang_tidy %s bugprone-forwarding-reference-overload %t
+// RUN: %check_clang_tidy -std=c++20 %s bugprone-forwarding-reference-overload 
%t
 
 namespace std {
 template  struct enable_if { typedef T type; };
@@ -251,3 +251,20 @@
   Test10(T &&Item, E e)
   : e(e){}
 };
+
+class Test11 {
+public:
+  // Guarded with requires expression.
+  template 
+  requires requires { just_true; }
+  Test11(T &&n);
+};
+
+template
+concept JustTrueConcept = requires { just_true; };
+
+class Test12 {
+public:
+  // Guarded with concept requirement.
+  template  Test12(T &&n);
+};
Index: 
clang-tools-extra/docs/clang-tidy/checks/bugprone/forwarding-reference-overload.rst
===
--- 
clang-tools-extra/docs/clang-tidy/checks/bugprone/forwarding-reference-overload.rst
+++ 
clang-tools-extra/docs/clang-tidy/checks/bugprone/forwarding-reference-overload.rst
@@ -34,6 +34,15 @@
 enable_if_t, A&&...>, int> = 0>
   explicit Person(A&&... a) {}
 
+  // C5: perfect forwarding ctor guarded with requires expression
+  template
+  requires requires { is_special; }
+  explicit Person(T&& n) {}
+
+  // C6: perfect forwarding ctor guarded with concept requirement
+  template
+  explicit Person(T&& n) {}
+
   // (possibly compiler generated) copy ctor
   Person(const Person& rhs);
 };
@@ -42,7 +51,7 @@
 constructors. We suppress warnings if the copy and the move constructors are 
both
 disabled (deleted or private), because there is nothing the perfect forwarding
 constructor could hide in this case. We also suppress warnings for constructors
-like C3 and C4 that are guarded with an ``enable_if``, assuming the programmer 
was
+like C3-C6 that are guarded with an ``enable_if`` or a concept, assuming the 
programmer was
 aware of the possible hiding.
 
 Background
Index: 
clang-tools-extra/clang-tidy/bugprone/ForwardingReferenceOverloadCheck.cpp
===
--- clang-tools-extra/clang-tidy/bugprone/ForwardingReferenceOverloadCheck.cpp
+++ clang-tools-extra/clang-tidy/bugprone/ForwardingReferenceOverloadCheck.cpp
@@ -58,6 +58,9 @@
   return Node.hasDefaultArgument() &&
  TypeMatcher.matches(Node.getDefaultArgument(), Finder, Builder);
 }
+AST_MATCHER(TemplateDecl, hasAssociatedConstraints) {
+  return Node.hasAssociatedConstraints();
+}
 } // namespace
 
 void ForwardingReferenceOverloadCheck::registerMatchers(MatchFinder *Finder) {
@@ -76,6 +79,9 @@
   // No warning: enable_if as constructor parameter.
   parmVarDecl(hasType(isEnableIf(),
   unless(hasParent(functionTemplateDecl(anyOf(
+  // No warning: has associated constraints (like requires
+  // expression).
+  hasAssociatedConstraints(),
   // No warning: enable_if as type parameter.
   has(templateTypeParmDecl(hasDefaultArgument(isEnableIf(,
   // No warning: enable_if as non-type template parameter.


Index: clang-tools-extra/test/clang-tidy/checkers/bugprone/forwarding-reference-overload.cpp
===
--- clang-tools-extra/test/clang-tidy/checkers/bugprone/forwarding-reference-overload.cpp
+++ clang-tools-extra/test/clang-tidy/checkers/bugprone/forwarding-reference-overload.cpp
@@ -1,4 +1,4 @@
-// RUN: %check_clang_tidy %s bugprone-forwarding-reference-overload %t
+// RUN: %check_clang_tidy -std=c++20 %s bugprone-forwarding-reference-overload %t
 
 namespace std {
 template  struct enable_if { typedef T type; };
@@ -251,3 +251,20 @@
   Test10(T &&Item, E e)
   : e(e){}
 };
+
+class Test11 {
+public:
+  // Guarded with requires expression.
+  template 
+  requires requires { just_true; }
+  Test11(T &&n);
+};
+
+template
+concept JustTrueConcept = requires { just_true; };
+
+class Test12 {
+public:
+  // Guarded with concept requirement.
+  template  Test12(T &&n);
+};
Index: clang-tools-extra/docs/clang-tidy/checks/bugprone/forwarding-reference-ov

[PATCH] D135476: [clang-tidy] Support concepts in `bugprone-forwarding-reference-overload`

2022-10-07 Thread Eugene Zelenko via Phabricator via cfe-commits
Eugene.Zelenko added inline comments.



Comment at: 
clang-tools-extra/docs/clang-tidy/checks/bugprone/forwarding-reference-overload.rst:54
 constructor could hide in this case. We also suppress warnings for constructors
-like C3 and C4 that are guarded with an ``enable_if``, assuming the programmer 
was
+like C3-C6 that are guarded with an ``enable_if`` or a concept, assuming the 
programmer was
 aware of the possible hiding.

Please follow 80 characters limit.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135476

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


[PATCH] D134813: Properly print unnamed TagDecl objects in diagnostics

2022-10-07 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman updated this revision to Diff 466145.
aaron.ballman added a comment.

Fixes the failing AST unit test in Clang found by precommit CI.


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

https://reviews.llvm.org/D134813

Files:
  clang-tools-extra/clangd/unittests/FindTargetTests.cpp
  clang/include/clang/AST/Decl.h
  clang/include/clang/AST/DeclCXX.h
  clang/include/clang/AST/DeclTemplate.h
  clang/lib/AST/ASTDiagnostic.cpp
  clang/lib/AST/Decl.cpp
  clang/lib/AST/DeclCXX.cpp
  clang/lib/AST/DeclPrinter.cpp
  clang/lib/AST/DeclTemplate.cpp
  clang/lib/AST/NestedNameSpecifier.cpp
  clang/lib/AST/TemplateName.cpp
  clang/lib/CodeGen/CodeGenTypes.cpp
  clang/lib/Sema/SemaTemplateInstantiate.cpp
  clang/test/AST/ast-dump-record-definition-data-json.cpp
  clang/test/ExtractAPI/enum.c
  clang/test/Index/annotate-comments-typedef.m
  clang/test/Index/c-index-api-loadTU-test.m
  clang/test/Index/c-index-getCursor-test.m
  clang/test/Index/print-type.c
  clang/test/Index/print-type.cpp
  clang/test/Index/targeted-annotation.c
  clang/test/Index/targeted-cursor.c
  clang/test/Index/usrs.m
  clang/test/Sema/address-packed.c
  clang/test/Sema/attr-flag-enum.c
  clang/test/SemaCXX/attr-unused.cpp
  clang/test/SemaCXX/lambda-expressions.cpp
  clang/test/SemaCXX/ms-interface.cpp
  clang/test/SemaObjCXX/arc-0x.mm
  clang/test/Templight/templight-empty-entries-fix.cpp
  clang/unittests/AST/ASTTraverserTest.cpp
  llvm/utils/lit/lit/TestRunner.py

Index: llvm/utils/lit/lit/TestRunner.py
===
--- llvm/utils/lit/lit/TestRunner.py
+++ llvm/utils/lit/lit/TestRunner.py
@@ -1174,6 +1174,7 @@
 ('%/p', sourcedir.replace('\\', '/')),
 ('%/t', tmpBase.replace('\\', '/') + '.tmp'),
 ('%/T', tmpDir.replace('\\', '/')),
+('%/et',tmpName.replace('\\', '')),
 ])
 
 # "%{/[STpst]:regex_replacement}" should be normalized like "%/[STpst]" but we're
Index: clang/unittests/AST/ASTTraverserTest.cpp
===
--- clang/unittests/AST/ASTTraverserTest.cpp
+++ clang/unittests/AST/ASTTraverserTest.cpp
@@ -1011,7 +1011,7 @@
 | |-FieldDecl ''
 | |-FieldDecl ''
 | |-FieldDecl ''
-| `-CXXDestructorDecl '~'
+| `-CXXDestructorDecl '~(lambda at input.cc:9:3)'
 |-ImplicitCastExpr
 | `-DeclRefExpr 'a'
 |-DeclRefExpr 'b'
Index: clang/test/Templight/templight-empty-entries-fix.cpp
===
--- clang/test/Templight/templight-empty-entries-fix.cpp
+++ clang/test/Templight/templight-empty-entries-fix.cpp
@@ -5,13 +5,13 @@
 }
 
 // CHECK-LABEL: {{^---$}}
-// CHECK: {{^name:[ ]+'lambda at .*templight-empty-entries-fix.cpp:4:3'$}}
+// CHECK: {{^name:[ ]+'\(lambda at .*templight-empty-entries-fix.cpp:4:3\)'$}}
 // CHECK: {{^kind:[ ]+Memoization$}}
 // CHECK: {{^event:[ ]+Begin$}}
 // CHECK: {{^orig:[ ]+'.*templight-empty-entries-fix.cpp:4:3'$}}
 // CHECK: {{^poi:[ ]+'.*templight-empty-entries-fix.cpp:4:3'$}}
 // CHECK-LABEL: {{^---$}}
-// CHECK: {{^name:[ ]+'lambda at .*templight-empty-entries-fix.cpp:4:3'$}}
+// CHECK: {{^name:[ ]+'\(lambda at .*templight-empty-entries-fix.cpp:4:3\)'$}}
 // CHECK: {{^kind:[ ]+Memoization$}}
 // CHECK: {{^event:[ ]+End$}}
 // CHECK: {{^orig:[ ]+'.*templight-empty-entries-fix.cpp:4:3'$}}
@@ -225,37 +225,37 @@
 }
 
 // CHECK-LABEL: {{^---$}}
-// CHECK: {{^name:[ ]+unnamed struct$}}
+// CHECK: {{^name:[ ]+'\(unnamed struct at .*templight-empty-entries-fix.cpp:223:3\)'$}}
 // CHECK: {{^kind:[ ]+Memoization$}}
 // CHECK: {{^event:[ ]+Begin$}}
 // CHECK: {{^orig:[ ]+'.*templight-empty-entries-fix.cpp:223:3'$}}
 // CHECK: {{^poi:[ ]+'.*templight-empty-entries-fix.cpp:224:5'$}}
 // CHECK-LABEL: {{^---$}}
-// CHECK: {{^name:[ ]+unnamed struct$}}
+// CHECK: {{^name:[ ]+'\(unnamed struct at .*templight-empty-entries-fix.cpp:223:3\)'$}}
 // CHECK: {{^kind:[ ]+Memoization$}}
 // CHECK: {{^event:[ ]+End$}}
 // CHECK: {{^orig:[ ]+'.*templight-empty-entries-fix.cpp:223:3'$}}
 // CHECK: {{^poi:[ ]+'.*templight-empty-entries-fix.cpp:224:5'$}}
 // CHECK-LABEL: {{^---$}}
-// CHECK: {{^name:[ ]+unnamed struct$}}
+// CHECK: {{^name:[ ]+'\(unnamed struct at .*templight-empty-entries-fix.cpp:223:3\)'$}}
 // CHECK: {{^kind:[ ]+Memoization$}}
 // CHECK: {{^event:[ ]+Begin$}}
 // CHECK: {{^orig:[ ]+'.*templight-empty-entries-fix.cpp:223:3'$}}
 // CHECK: {{^poi:[ ]+'.*templight-empty-entries-fix.cpp:224:5'$}}
 // CHECK-LABEL: {{^---$}}
-// CHECK: {{^name:[ ]+unnamed struct$}}
+// CHECK: {{^name:[ ]+'\(unnamed struct at .*templight-empty-entries-fix.cpp:223:3\)'$}}
 // CHECK: {{^kind:[ ]+Memoization$}}
 // CHECK: {{^event:[ ]+End$}}
 // CHECK: {{^orig:[ ]+'.*templight-empty-entries-fix.cpp:223:3'$}}
 // CHECK: {{^poi:[ ]+'.*templight-empty-entries-fix.cpp:224:5'$}}
 // CHECK-LABEL: {{^---$}}
-// CHECK: {{^name:[ ]+unnamed struct$}}
+// CHECK: {{^name:[ ]+'\(unnamed struct at .*

[PATCH] D134369: [Clang] Support constexpr builtin fmax

2022-10-07 Thread Evgeny Shulgin via Phabricator via cfe-commits
Izaron updated this revision to Diff 466151.
Izaron added a comment.

Add TODO comment about sNaN. Thanks to @jcranmer-intel!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134369

Files:
  clang/docs/LanguageExtensions.rst
  clang/lib/AST/ExprConstant.cpp
  clang/test/Sema/constant-builtins-fmax.cpp


Index: clang/test/Sema/constant-builtins-fmax.cpp
===
--- /dev/null
+++ clang/test/Sema/constant-builtins-fmax.cpp
@@ -0,0 +1,54 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+// expected-no-diagnostics
+
+constexpr double NaN = __builtin_nan("");
+constexpr double Inf = __builtin_inf();
+constexpr double NegInf = -__builtin_inf();
+
+#define FMAX_TEST_SIMPLE(T, FUNC)   \
+static_assert(T(6.7890) == FUNC(T(1.2345), T(6.7890))); \
+static_assert(T(6.7890) == FUNC(T(6.7890), T(1.2345)));
+
+#define FMAX_TEST_NAN(T, FUNC)  \
+static_assert(Inf == FUNC(NaN, Inf));   \
+static_assert(NegInf == FUNC(NegInf, NaN)); \
+static_assert(0.0 == FUNC(NaN, 0.0));   \
+static_assert(-0.0 == FUNC(-0.0, NaN)); \
+static_assert(T(-1.2345) == FUNC(NaN, T(-1.2345))); \
+static_assert(T(1.2345) == FUNC(T(1.2345), NaN));   \
+static_assert(__builtin_isnan(FUNC(NaN, NaN)));
+
+#define FMAX_TEST_INF(T, FUNC)  \
+static_assert(Inf == FUNC(NegInf, Inf));\
+static_assert(Inf == FUNC(Inf, 0.0));   \
+static_assert(Inf == FUNC(-0.0, Inf));  \
+static_assert(Inf == FUNC(Inf, T(1.2345))); \
+static_assert(Inf == FUNC(T(-1.2345), Inf));
+
+#define FMAX_TEST_NEG_INF(T, FUNC) \
+static_assert(Inf == FUNC(Inf, NegInf));   \
+static_assert(0.0 == FUNC(NegInf, 0.0));   \
+static_assert(-0.0 == FUNC(-0.0, NegInf)); \
+static_assert(T(-1.2345) == FUNC(NegInf, T(-1.2345))); \
+static_assert(T(1.2345) == FUNC(T(1.2345), NegInf));
+
+#define FMAX_TEST_BOTH_ZERO(T, FUNC)   \
+static_assert(__builtin_copysign(1.0, FUNC(0.0, 0.0)) == 1.0);  \
+static_assert(__builtin_copysign(1.0, FUNC(-0.0, 0.0)) == 1.0);  \
+static_assert(__builtin_copysign(1.0, FUNC(0.0, -0.0)) == 1.0);  \
+static_assert(__builtin_copysign(1.0, FUNC(-0.0, -0.0)) == -1.0);
+
+#define LIST_FMAX_TESTS(T, FUNC) \
+FMAX_TEST_SIMPLE(T, FUNC)\
+FMAX_TEST_NAN(T, FUNC)   \
+FMAX_TEST_INF(T, FUNC)   \
+FMAX_TEST_NEG_INF(T, FUNC)   \
+FMAX_TEST_BOTH_ZERO(T, FUNC)
+
+LIST_FMAX_TESTS(double, __builtin_fmax)
+LIST_FMAX_TESTS(float, __builtin_fmaxf)
+LIST_FMAX_TESTS((long double), __builtin_fmaxl)
+LIST_FMAX_TESTS(__fp16, __builtin_fmaxf16)
+#ifdef __FLOAT128__
+LIST_FMAX_TESTS(__float128, __builtin_fmaxf128)
+#endif
Index: clang/lib/AST/ExprConstant.cpp
===
--- clang/lib/AST/ExprConstant.cpp
+++ clang/lib/AST/ExprConstant.cpp
@@ -14021,6 +14021,24 @@
 Result.copySign(RHS);
 return true;
   }
+
+  case Builtin::BI__builtin_fmax:
+  case Builtin::BI__builtin_fmaxf:
+  case Builtin::BI__builtin_fmaxl:
+  case Builtin::BI__builtin_fmaxf16:
+  case Builtin::BI__builtin_fmaxf128: {
+// TODO: Handle sNaN.
+APFloat RHS(0.);
+if (!EvaluateFloat(E->getArg(0), Result, Info) ||
+!EvaluateFloat(E->getArg(1), RHS, Info))
+  return false;
+// When comparing zeroes, return +0.0 if one of the zeroes is positive.
+if (Result.isZero() && RHS.isZero() && Result.isNegative())
+  Result = RHS;
+else if (Result.isNaN() || RHS > Result)
+  Result = RHS;
+return true;
+  }
   }
 }
 
Index: clang/docs/LanguageExtensions.rst
===
--- clang/docs/LanguageExtensions.rst
+++ clang/docs/LanguageExtensions.rst
@@ -4660,6 +4660,7 @@
 * ``__builtin_ffs``
 * ``__builtin_ffsl``
 * ``__builtin_ffsll``
+* ``__builtin_fmax``
 * ``__builtin_fpclassify``
 * ``__builtin_inf``
 * ``__builtin_isinf``


Index: clang/test/Sema/constant-builtins-fmax.cpp
===
--- /dev/null
+++ clang/test/Sema/constant-builtins-fmax.cpp
@@ -0,0 +1,54 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+// expected-no-diagnostics
+
+constexpr double NaN = __builtin_nan("");
+constexpr double Inf = __builtin_inf();
+constexpr double NegInf = -__builtin_inf();
+
+#define FMAX_TEST_SIMPLE(T, FUNC)   \
+static_assert(T(6.7890) == FUNC(T(1.2345), T(6.7890))); \
+static_assert(T(6.7890) == FUNC(T(6.7890), T(1.2345)));
+
+#define FMAX_TEST_NAN(T, FUNC)  \
+static_assert(Inf == FUNC(NaN, Inf));   \
+static_assert(NegInf == FUNC(NegInf, NaN)); \
+static_assert(0.0 == FUNC(NaN, 0.0)); 

[PATCH] D135433: [clang][Interp] Implement while and do-while loops

2022-10-07 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/test/AST/Interp/loops.cpp:93
+  }
+  static_assert(f4() == 5, "");
+};

Can you also add some tests that use nested loops with multiple levels of 
`break` and `continue` use?

Also, I think it might be useful to show the jump statements causing code to be 
an invalid constant expression, as in: 
```
constexpr int foo() {
  int i;

  do {
break;
i = 12;
  } while (1);

  return i;
}

constexpr int f = foo();
```


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

https://reviews.llvm.org/D135433

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


[PATCH] D135370: Narrow inline namespace filtration for unqualified friend declarations

2022-10-07 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman added a comment.

LGTM! Should we also add a release note or do we think this isn't enough of a 
compile-time performance improvement to warrant that?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135370

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


[PATCH] D129755: Thread safety analysis: Support copy-elided production of scoped capabilities through arbitrary calls

2022-10-07 Thread Hans Wennborg via Phabricator via cfe-commits
hans added a comment.

In D129755#3843146 , @aaronpuchert 
wrote:

> In D129755#3842729 , @hans wrote:
>
>> We're hitting a false positive in grpc after this:
>>
>>   > ../../third_party/grpc/src/src/core/lib/gprpp/ref_counted_ptr.h:335:31: 
>> error: calling function 'TlsSessionKeyLoggerCache' requires holding mutex 
>> 'g_tls_session_key_log_cache_mu' exclusively 
>> [-Werror,-Wthread-safety-analysis]
>>   >   return RefCountedPtr(new T(std::forward(args)...));
>>   >   ^
>>   > 
>> ../../third_party/grpc/src/src/core/tsi/ssl/key_logging/ssl_key_logging.cc:121:26:
>>  note: in instantiation of function template specialization 
>> 'grpc_core::MakeRefCounted' requested here
>>   >  cache = grpc_core::MakeRefCounted();
>>   > ^
>>   
>>   
>>   The code looks like this:
>>   
>>   grpc_core::RefCountedPtr 
>> TlsSessionKeyLoggerCache::Get(
>>   std::string tls_session_key_log_file_path) {
>> gpr_once_init(&g_cache_mutex_init, do_cache_mutex_init);
>> GPR_DEBUG_ASSERT(g_tls_session_key_log_cache_mu != nullptr);
>> if (tls_session_key_log_file_path.empty()) {
>>   return nullptr;
>> }
>> {
>>   grpc_core::MutexLock lock(g_tls_session_key_log_cache_mu);
>> <-- holding the mutex
>>   grpc_core::RefCountedPtr cache;
>>   if (g_cache_instance == nullptr) {
>> // This will automatically set g_cache_instance.
>> cache = grpc_core::MakeRefCounted();  
>> <-- line 121
>>   
>>   
>>   
>>   lock is holding a MutexLock (I assume that's an exclusive thing) on 
>> g_tls_session_key_log_cache_mu.
>>
>> See https://bugs.chromium.org/p/chromium/issues/detail?id=1372394#c4 for how 
>> to reproduce.
>>
>> I've reverted this in 
>> https://github.com/llvm/llvm-project/commit/a4afa2bde6f4db215ddd3267a8d11c04367812e5
>>  in the meantime.
>
> This doesn't look like a false positive to me. The documentation states that 
> no inlining 
>  is being 
> done, so unless `grpc_core::MakeRefCounted` (or a specialization) has a 
> `require_capability` attribute, the lock doesn't count as locked in the 
> function body. That has always been the case.

Thanks for looking into this so quickly.

I'd still call it a false positive since the mutex is in fact being held. 
However I now understand that this is due to a pre-existing limitation in the 
analysis.

How would you suggest the developers work around this?

> In D129755#3842744 , @hans wrote:
>
>> We also hit a different case: 
>> https://bugs.chromium.org/p/chromium/issues/detail?id=1372394#c6
>
> From the logs:
>
>   
> ../../extensions/browser/api/content_settings/content_settings_store.cc(75,49):
>  note: mutex acquired here
> std::unique_ptr auto_lock(new base::AutoLock(lock_));
>   ^
>
> That seems to be precisely the example that the documentation says doesn't 
> work. The constructor of `std::unique_ptr` has no thread safety annotations 
> and so we have a constructor call without a matching destructor call. (The 
> destructor is called indirectly from the destructor of `unique_ptr`. We see 
> this now because of the constructor call that doesn't initialize a local 
> variable.
>
> The documentation also lists ways to make this work (such as having more 
> powerful scope types).

I see. I looked through the docs but it wasn't clear what you referred too. How 
would one change base::AutoLock in this case? Or do the developers need to 
avoid unique_ptr, or is there something else?

> I'll give you some time to reply before I reland, but I can't see a bug here. 
> For the next time, as already pointed out, give the involved people some time 
> to reply before you revert (unless it's a crash). We have to be able to 
> continue working on the compiler without having Google revert changes all the 
> time because we produce new warnings.

We've seen reports here of various breakages from two different projects in 
short time after your patch. The general policy is to revert to green, so I 
think that was the right call. Typically, new warnings are introduced behind 
new flags so that users can adopt them incrementally, though I realize that 
might be tricky in this instance. In any case, perhaps we should give other 
projects some time to assess the impact of this before relanding?

This also seems like the kind of disruptive change we'd want to announce on 
Discourse, as discussed in Aaron's recent RFC 
.
 Probably should be mentioned in the "Potentially Breaking Changes" section of 
the release notes too.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llv

[PATCH] D135328: [CUDA] Refactored CUDA version housekeeping to use less boilerplate.

2022-10-07 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl accepted this revision.
yaxunl added a comment.
This revision is now accepted and ready to land.

LGTM. Thanks.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135328

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


  1   2   >