[PATCH] D133413: [clang-tidy] Fix crashes on `if consteval` in readability checks

2022-10-05 Thread Emilia Dreamer via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG2d149d17f069: [clang-tidy] Fix crashes on `if consteval` in 
readability checks (authored by rymiel).

Changed prior to commit:
  https://reviews.llvm.org/D133413?vs=464176&id=465291#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133413

Files:
  clang-tools-extra/clang-tidy/readability/BracesAroundStatementsCheck.cpp
  clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
  clang-tools-extra/docs/ReleaseNotes.rst
  
clang-tools-extra/test/clang-tidy/checkers/readability/braces-around-statements-consteval-if.cpp
  
clang-tools-extra/test/clang-tidy/checkers/readability/simplify-bool-expr-cxx23.cpp

Index: clang-tools-extra/test/clang-tidy/checkers/readability/simplify-bool-expr-cxx23.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/readability/simplify-bool-expr-cxx23.cpp
@@ -0,0 +1,37 @@
+// RUN: clang-tidy %s -checks='-*,readability-simplify-boolean-expr' -- -std=c++2b | count 0
+template 
+constexpr int testIf() {
+  if consteval {
+if constexpr (Cond) {
+  return 0;
+} else {
+  return 1;
+}
+  } else {
+return 2;
+  }
+}
+
+constexpr bool testCompound() {
+  if consteval {
+return true;
+  }
+  return false;
+}
+
+constexpr bool testCase(int I) {
+  switch (I) {
+case 0: {
+  if consteval {
+return true;
+  }
+  return false;
+}
+default: {
+  if consteval {
+return false;
+  }
+  return true;
+}
+  }
+}
Index: clang-tools-extra/test/clang-tidy/checkers/readability/braces-around-statements-consteval-if.cpp
===
--- /dev/null
+++ clang-tools-extra/test/clang-tidy/checkers/readability/braces-around-statements-consteval-if.cpp
@@ -0,0 +1,31 @@
+// RUN: clang-tidy %s -checks='-*,readability-braces-around-statements' -- -std=c++2b | count 0
+
+constexpr void handle(bool) {}
+
+constexpr void shouldPass() {
+  if consteval {
+handle(true);
+  } else {
+handle(false);
+  }
+}
+
+constexpr void shouldPassNegated() {
+  if !consteval {
+handle(false);
+  } else {
+handle(true);
+  }
+}
+
+constexpr void shouldPassSimple() {
+  if consteval {
+handle(true);
+  }
+}
+
+void run() {
+shouldPass();
+shouldPassNegated();
+shouldPassSimple();
+}
Index: clang-tools-extra/docs/ReleaseNotes.rst
===
--- clang-tools-extra/docs/ReleaseNotes.rst
+++ clang-tools-extra/docs/ReleaseNotes.rst
@@ -159,6 +159,11 @@
   ` to not
   warn about `const` value parameters of declarations inside macros.
 
+- Fixed crashes in :doc:`readability-braces-around-statements
+  ` and
+  :doc:`readability-simplify-boolean-expr `
+  when using a C++23 ``if consteval`` statement.
+
 Removed checks
 ^^
 
Index: clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
@@ -354,8 +354,9 @@
   }
 
   bool VisitIfStmt(IfStmt *If) {
-// Skip any if's that have a condition var or an init statement.
-if (If->hasInitStorage() || If->hasVarStorage())
+// Skip any if's that have a condition var or an init statement, or are
+// "if consteval" statements.
+if (If->hasInitStorage() || If->hasVarStorage() || If->isConsteval())
   return true;
 /*
  * if (true) ThenStmt(); -> ThenStmt();
@@ -467,7 +468,8 @@
  * if (Cond) return false; return true; -> return !Cond;
  */
 auto *If = cast(*First);
-if (!If->hasInitStorage() && !If->hasVarStorage()) {
+if (!If->hasInitStorage() && !If->hasVarStorage() &&
+!If->isConsteval()) {
   ExprAndBool ThenReturnBool =
   checkSingleStatement(If->getThen(), parseReturnLiteralBool);
   if (ThenReturnBool &&
@@ -491,7 +493,7 @@
 : cast(*First)->getSubStmt();
 auto *SubIf = dyn_cast(SubStmt);
 if (SubIf && !SubIf->getElse() && !SubIf->hasInitStorage() &&
-!SubIf->hasVarStorage()) {
+!SubIf->hasVarStorage() && !SubIf->isConsteval()) {
   ExprAndBool ThenReturnBool =
   checkSingleStatement(SubIf->getThen(), parseReturnLiteralBool);
   if (ThenReturnBool &&
Index: clang-tools-extra/clang-tidy/readability/BracesAroundStatementsCheck.cpp
===
--- clang-tools-extra/clang-tidy/readability/BracesAroundStatementsCheck.cpp
+++ clang-tools-extra/clang-tidy/readability/BracesAroundStatementsCheck.cpp
@@ -131,6 +131,1

[clang-tools-extra] 2d149d1 - [clang-tidy] Fix crashes on `if consteval` in readability checks

2022-10-05 Thread Emilia Dreamer via cfe-commits

Author: Emilia Dreamer
Date: 2022-10-05T09:38:05+03:00
New Revision: 2d149d17f069e671e064a000cb038590f4fc5303

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

LOG: [clang-tidy] Fix crashes on `if consteval` in readability checks

The `readability-braces-around-statements` check tries to look at the
closing parens of the if condition to determine where to insert braces,
however, "consteval if" statements don't have a condition, and always
have braces regardless, so the skip can be checked.

The `readability-simplify-boolean-expr` check looks at the condition
of the if statement to determine what could be simplified, but as
"consteval if" statements do not have a condition that could be
simplified, they can also be skipped here.

There may still be more checks that try to look at the conditions of
`if`s that aren't included here

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

Reviewed By: njames93, aaron.ballman

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

Added: 

clang-tools-extra/test/clang-tidy/checkers/readability/braces-around-statements-consteval-if.cpp

clang-tools-extra/test/clang-tidy/checkers/readability/simplify-bool-expr-cxx23.cpp

Modified: 
clang-tools-extra/clang-tidy/readability/BracesAroundStatementsCheck.cpp
clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
clang-tools-extra/docs/ReleaseNotes.rst

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/readability/BracesAroundStatementsCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/BracesAroundStatementsCheck.cpp
index 07e962a07e843..d6f4d920b5e93 100644
--- a/clang-tools-extra/clang-tidy/readability/BracesAroundStatementsCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/BracesAroundStatementsCheck.cpp
@@ -131,6 +131,10 @@ void BracesAroundStatementsCheck::check(
   return;
 checkStmt(Result, S->getBody(), StartLoc);
   } else if (const auto *S = Result.Nodes.getNodeAs("if")) {
+// "if consteval" always has braces.
+if (S->isConsteval())
+  return;
+
 SourceLocation StartLoc = findRParenLoc(S, SM, Context);
 if (StartLoc.isInvalid())
   return;

diff  --git 
a/clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
index afb4a1044a79a..9369f73371223 100644
--- a/clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/SimplifyBooleanExprCheck.cpp
@@ -354,8 +354,9 @@ class SimplifyBooleanExprCheck::Visitor : public 
RecursiveASTVisitor {
   }
 
   bool VisitIfStmt(IfStmt *If) {
-// Skip any if's that have a condition var or an init statement.
-if (If->hasInitStorage() || If->hasVarStorage())
+// Skip any if's that have a condition var or an init statement, or are
+// "if consteval" statements.
+if (If->hasInitStorage() || If->hasVarStorage() || If->isConsteval())
   return true;
 /*
  * if (true) ThenStmt(); -> ThenStmt();
@@ -467,7 +468,8 @@ class SimplifyBooleanExprCheck::Visitor : public 
RecursiveASTVisitor {
  * if (Cond) return false; return true; -> return !Cond;
  */
 auto *If = cast(*First);
-if (!If->hasInitStorage() && !If->hasVarStorage()) {
+if (!If->hasInitStorage() && !If->hasVarStorage() &&
+!If->isConsteval()) {
   ExprAndBool ThenReturnBool =
   checkSingleStatement(If->getThen(), parseReturnLiteralBool);
   if (ThenReturnBool &&
@@ -491,7 +493,7 @@ class SimplifyBooleanExprCheck::Visitor : public 
RecursiveASTVisitor {
 : cast(*First)->getSubStmt();
 auto *SubIf = dyn_cast(SubStmt);
 if (SubIf && !SubIf->getElse() && !SubIf->hasInitStorage() &&
-!SubIf->hasVarStorage()) {
+!SubIf->hasVarStorage() && !SubIf->isConsteval()) {
   ExprAndBool ThenReturnBool =
   checkSingleStatement(SubIf->getThen(), parseReturnLiteralBool);
   if (ThenReturnBool &&

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 199f46ae14334..4082a2b0bce2c 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -159,6 +159,11 @@ Changes in existing checks
   ` to not
   warn about `const` value parameters of declarations inside macros.
 
+- Fixed crashes in :doc:`readability-braces-around-statements
+  ` and
+  :doc:`readability-simplify-boolean-expr 
`
+  when using a C++23 ``if consteval`` statement.
+
 Removed checks
 ^^
 

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/readability/braces-around-statements-consteval-if.cpp
 
b/clang-tools-extra/

[PATCH] D135132: [SourceManager] Improve getFileIDLocal.

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

Remove the I variable, use GreaterIndex instead.


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
@@ -790,24 +790,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.
   unsigned NumProbes = 0;
   while (true) {
---I;
-if (I->getOffset() <= SLocOffset) {
-  FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin()));
+--GreaterIndex;
+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;
@@ -817,13 +821,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
@@ -790,24 +790,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.
   unsigned NumProbes = 0;
   while (true) {
---I;
-if (I->getOffset() <= SLocOffset) {
-  FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin()));
+--GreaterIndex;
+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;
@@ -817,13 +821,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 = (Greate

[PATCH] D135132: [SourceManager] Improve getFileIDLocal.

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



Comment at: clang/lib/Basic/SourceManager.cpp:897
   // actually a lower index!
   unsigned GreaterIndex = I;
   unsigned LessIndex = LoadedSLocEntryTable.size();

sammccall wrote:
> is the same optimization available here?
> I think getFileIDLoaded() is important for module builds and when we use PCH.
> Though admittedly I don't think this is relevant to the lexer path we've been 
> looking at: those locations should always be local.
Yeah. That's my next step. I plan to send a separate patch for it.


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


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

2022-10-05 Thread David Spickett via Phabricator via cfe-commits
DavidSpickett added inline comments.



Comment at: clang/include/clang/AST/ExprCXX.h:733
 
+  static CXXBoolLiteralExpr *Create(const ASTContext &C, bool Val, QualType Ty,
+SourceLocation Loc) {

shafik wrote:
> I think this makes sense but if we are going to do this refactor then we 
> should clean up all the locations we are currently doing `new (Context) 
> CXXBoolLiteralExpr()` as well.
> 
> Maybe that should be the initial PR and then this change would be a follow-up.
Sounds good to me, I'll do that.



Comment at: 
lldb/test/API/lang/cpp/const_static_integral_member/TestConstStaticIntegralMember.py:36
+# 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",

And just to be clear, this is TODO is resolved in the patch stacked on this one.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135169

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


[PATCH] D134425: [NFC] Create a AllocLikeOpInterface and make memref::AllocOp, memref::AllocaOp and gpu::AllocOp implement it.

2022-10-05 Thread Uday Bondhugula via Phabricator via cfe-commits
bondhugula added a comment.

This is looking good to me. Please pull out changes unrelated to 
AllocLikeOpInterface into a separate revision (the ones just switching to 
`hasSingleEffect`).




Comment at: mlir/lib/Dialect/Affine/Transforms/LoopFusion.cpp:1967
   auto *op = memref.getDefiningOp();
-  if (isa_and_nonnull(op))
+  if (hasSingleEffect(op))
 op->erase();

This change isn't related to the `AllocLikeOpInterface`; this and other similar 
changes can go into another revision.



Comment at: mlir/lib/Dialect/Affine/Utils/Utils.cpp:1071
+if (!defOp || (!hasSingleEffect(defOp) &&
+   !isa(defOp)))
   // TODO: if the memref was returned by a 'call' operation, we

The change to include `GetGlobalOp` is unrelated to this PR (and not proper as 
well) - it should be dropped.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134425

___
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-05 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added inline comments.
This revision is now accepted and ready to land.



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

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?


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


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

2022-10-05 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet created this revision.
kadircet added a reviewer: sammccall.
Herald added a subscriber: arphaman.
Herald added a project: All.
kadircet requested review of this revision.
Herald added projects: clang, clang-tools-extra.
Herald added a subscriber: cfe-commits.

As pointed out in https://reviews.llvm.org/D119130#3829816, this
introduces a clang AST dependency to the clangToolingInclusions, which is used
by clang-format.

Since rest of the inclusion tooling doesn't depend on clang ast, moving this
into a separate library.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D135245

Files:
  clang-tools-extra/clangd/CMakeLists.txt
  clang/lib/Tooling/Inclusions/CMakeLists.txt
  clang/lib/Tooling/Inclusions/STL/CMakeLists.txt
  clang/lib/Tooling/Inclusions/STL/StandardLibrary.cpp
  clang/lib/Tooling/Inclusions/StandardLibrary.cpp
  clang/unittests/Tooling/CMakeLists.txt

Index: clang/unittests/Tooling/CMakeLists.txt
===
--- clang/unittests/Tooling/CMakeLists.txt
+++ clang/unittests/Tooling/CMakeLists.txt
@@ -81,6 +81,7 @@
   clangTooling
   clangToolingCore
   clangToolingInclusions
+  clangToolingInclusionsSTL
   clangToolingRefactoring
   clangTransformer
   )
Index: clang/lib/Tooling/Inclusions/StandardLibrary.cpp
===
--- /dev/null
+++ clang/lib/Tooling/Inclusions/StandardLibrary.cpp
@@ -1,165 +0,0 @@
-//===--- StandardLibrary.cpp *- C++ -*-===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===--===//
-
-#include "clang/Tooling/Inclusions/StandardLibrary.h"
-#include "llvm/ADT/Optional.h"
-#include "llvm/ADT/StringRef.h"
-#include "llvm/Support/Casting.h"
-
-namespace clang {
-namespace tooling {
-namespace stdlib {
-
-static llvm::StringRef *HeaderNames;
-static std::pair *SymbolNames;
-static unsigned *SymbolHeaderIDs;
-static llvm::DenseMap *HeaderIDs;
-// Maps symbol name -> Symbol::ID, within a namespace.
-using NSSymbolMap = llvm::DenseMap;
-static llvm::DenseMap *NamespaceSymbols;
-
-static int initialize() {
-  unsigned SymCount = 0;
-#define SYMBOL(Name, NS, Header) ++SymCount;
-#include "clang/Tooling/Inclusions/CSymbolMap.inc"
-#include "clang/Tooling/Inclusions/StdSymbolMap.inc"
-#undef SYMBOL
-  SymbolNames = new std::remove_reference_t[SymCount];
-  SymbolHeaderIDs =
-  new std::remove_reference_t[SymCount];
-  NamespaceSymbols = new std::remove_reference_t;
-  HeaderIDs = new std::remove_reference_t;
-
-  auto AddNS = [&](llvm::StringRef NS) -> NSSymbolMap & {
-auto R = NamespaceSymbols->try_emplace(NS, nullptr);
-if (R.second)
-  R.first->second = new NSSymbolMap();
-return *R.first->second;
-  };
-
-  auto AddHeader = [&](llvm::StringRef Header) -> unsigned {
-return HeaderIDs->try_emplace(Header, HeaderIDs->size()).first->second;
-  };
-
-  auto Add = [&, SymIndex(0)](llvm::StringRef Name, llvm::StringRef NS,
-  llvm::StringRef HeaderName) mutable {
-if (NS == "None")
-  NS = "";
-
-SymbolNames[SymIndex] = {NS, Name};
-SymbolHeaderIDs[SymIndex] = AddHeader(HeaderName);
-
-NSSymbolMap &NSSymbols = AddNS(NS);
-NSSymbols.try_emplace(Name, SymIndex);
-
-++SymIndex;
-  };
-#define SYMBOL(Name, NS, Header) Add(#Name, #NS, #Header);
-#include "clang/Tooling/Inclusions/CSymbolMap.inc"
-#include "clang/Tooling/Inclusions/StdSymbolMap.inc"
-#undef SYMBOL
-
-  HeaderNames = new llvm::StringRef[HeaderIDs->size()];
-  for (const auto &E : *HeaderIDs)
-HeaderNames[E.second] = E.first;
-
-  return 0;
-}
-
-static void ensureInitialized() {
-  static int Dummy = initialize();
-  (void)Dummy;
-}
-
-llvm::Optional Header::named(llvm::StringRef Name) {
-  ensureInitialized();
-  auto It = HeaderIDs->find(Name);
-  if (It == HeaderIDs->end())
-return llvm::None;
-  return Header(It->second);
-}
-llvm::StringRef Header::name() const { return HeaderNames[ID]; }
-llvm::StringRef Symbol::scope() const { return SymbolNames[ID].first; }
-llvm::StringRef Symbol::name() const { return SymbolNames[ID].second; }
-llvm::Optional Symbol::named(llvm::StringRef Scope,
- llvm::StringRef Name) {
-  ensureInitialized();
-  if (NSSymbolMap *NSSymbols = NamespaceSymbols->lookup(Scope)) {
-auto It = NSSymbols->find(Name);
-if (It != NSSymbols->end())
-  return Symbol(It->second);
-  }
-  return llvm::None;
-}
-Header Symbol::header() const { return Header(SymbolHeaderIDs[ID]); }
-llvm::SmallVector Symbol::headers() const {
-  return {header()}; // FIXME: multiple in case of ambiguity
-}
-
-Recognizer::Recognizer() { ensureInitialized(); }
-
-NSSymbolMap *Recognizer::namespaceSymb

[PATCH] D119130: [clangd] NFC: Move stdlib headers handling to Clang

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

sent out  https://reviews.llvm.org/D135245


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D119130

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


[clang] 36a2002 - [clang][Lex] Fix a crash on malformed string literals

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

Author: Kadir Cetinkaya
Date: 2022-10-05T09:55:50+02:00
New Revision: 36a200208facf58d454c9b7253c956c2f2a8b946

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

LOG: [clang][Lex] Fix a crash on malformed string literals

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

Added: 


Modified: 
clang/lib/Lex/LiteralSupport.cpp
clang/test/Lexer/char-escapes-delimited.c
clang/unittests/Lex/LexerTest.cpp

Removed: 




diff  --git a/clang/lib/Lex/LiteralSupport.cpp 
b/clang/lib/Lex/LiteralSupport.cpp
index 1a48a68c28b62..160240e49dd70 100644
--- a/clang/lib/Lex/LiteralSupport.cpp
+++ b/clang/lib/Lex/LiteralSupport.cpp
@@ -545,7 +545,6 @@ static bool ProcessNamedUCNEscape(const char *ThisTokBegin,
diag::err_delimited_escape_missing_brace)
   << StringRef(&ThisTokBuf[-1], 1);
 }
-ThisTokBuf++;
 return false;
   }
   ThisTokBuf++;

diff  --git a/clang/test/Lexer/char-escapes-delimited.c 
b/clang/test/Lexer/char-escapes-delimited.c
index 65e3dc740e3b4..43ade65a58309 100644
--- a/clang/test/Lexer/char-escapes-delimited.c
+++ b/clang/test/Lexer/char-escapes-delimited.c
@@ -94,7 +94,7 @@ void named(void) {
 
   unsigned h = U'\N{LOTUS}';  // ext-warning {{extension}} 
cxx2b-warning {{C++2b}}
   unsigned i = u'\N{GREEK CAPITAL LETTER DELTA}'; // ext-warning {{extension}} 
cxx2b-warning {{C++2b}}
-  char j = '\NN'; // expected-error {{expected 
'{' after '\N' escape sequence}}
+  char j = '\NN'; // expected-error {{expected 
'{' after '\N' escape sequence}} expected-warning {{multi-character character 
constant}}
   unsigned k = u'\N{LOTUS';   // expected-error 
{{incomplete universal character name}}
 }
 

diff  --git a/clang/unittests/Lex/LexerTest.cpp 
b/clang/unittests/Lex/LexerTest.cpp
index 0ad644ce71465..aefe5f1ab35a3 100644
--- a/clang/unittests/Lex/LexerTest.cpp
+++ b/clang/unittests/Lex/LexerTest.cpp
@@ -18,6 +18,7 @@
 #include "clang/Basic/TokenKinds.h"
 #include "clang/Lex/HeaderSearch.h"
 #include "clang/Lex/HeaderSearchOptions.h"
+#include "clang/Lex/LiteralSupport.h"
 #include "clang/Lex/MacroArgs.h"
 #include "clang/Lex/MacroInfo.h"
 #include "clang/Lex/ModuleLoader.h"
@@ -659,4 +660,11 @@ TEST_F(LexerTest, RawAndNormalLexSameForLineComments) {
   }
   EXPECT_TRUE(ToksView.empty());
 }
+
+TEST_F(LexerTest, BrokenStringLiteral) {
+  const llvm::StringLiteral Source = R"cpp("\N")cpp";
+  // Make sure this isn't crashing.
+  StringLiteralParser P(Lex(Source), *PP);
+  EXPECT_TRUE(P.hadError);
+}
 } // anonymous namespace



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


[PATCH] D135161: [clang][Lex] Fix a crash on malformed string literals

2022-10-05 Thread Kadir Cetinkaya 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 rG36a200208fac: [clang][Lex] Fix a crash on malformed string 
literals (authored by kadircet).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135161

Files:
  clang/lib/Lex/LiteralSupport.cpp
  clang/test/Lexer/char-escapes-delimited.c
  clang/unittests/Lex/LexerTest.cpp


Index: clang/unittests/Lex/LexerTest.cpp
===
--- clang/unittests/Lex/LexerTest.cpp
+++ clang/unittests/Lex/LexerTest.cpp
@@ -18,6 +18,7 @@
 #include "clang/Basic/TokenKinds.h"
 #include "clang/Lex/HeaderSearch.h"
 #include "clang/Lex/HeaderSearchOptions.h"
+#include "clang/Lex/LiteralSupport.h"
 #include "clang/Lex/MacroArgs.h"
 #include "clang/Lex/MacroInfo.h"
 #include "clang/Lex/ModuleLoader.h"
@@ -659,4 +660,11 @@
   }
   EXPECT_TRUE(ToksView.empty());
 }
+
+TEST_F(LexerTest, BrokenStringLiteral) {
+  const llvm::StringLiteral Source = R"cpp("\N")cpp";
+  // Make sure this isn't crashing.
+  StringLiteralParser P(Lex(Source), *PP);
+  EXPECT_TRUE(P.hadError);
+}
 } // anonymous namespace
Index: clang/test/Lexer/char-escapes-delimited.c
===
--- clang/test/Lexer/char-escapes-delimited.c
+++ clang/test/Lexer/char-escapes-delimited.c
@@ -94,7 +94,7 @@
 
   unsigned h = U'\N{LOTUS}';  // ext-warning {{extension}} 
cxx2b-warning {{C++2b}}
   unsigned i = u'\N{GREEK CAPITAL LETTER DELTA}'; // ext-warning {{extension}} 
cxx2b-warning {{C++2b}}
-  char j = '\NN'; // expected-error {{expected 
'{' after '\N' escape sequence}}
+  char j = '\NN'; // expected-error {{expected 
'{' after '\N' escape sequence}} expected-warning {{multi-character character 
constant}}
   unsigned k = u'\N{LOTUS';   // expected-error 
{{incomplete universal character name}}
 }
 
Index: clang/lib/Lex/LiteralSupport.cpp
===
--- clang/lib/Lex/LiteralSupport.cpp
+++ clang/lib/Lex/LiteralSupport.cpp
@@ -545,7 +545,6 @@
diag::err_delimited_escape_missing_brace)
   << StringRef(&ThisTokBuf[-1], 1);
 }
-ThisTokBuf++;
 return false;
   }
   ThisTokBuf++;


Index: clang/unittests/Lex/LexerTest.cpp
===
--- clang/unittests/Lex/LexerTest.cpp
+++ clang/unittests/Lex/LexerTest.cpp
@@ -18,6 +18,7 @@
 #include "clang/Basic/TokenKinds.h"
 #include "clang/Lex/HeaderSearch.h"
 #include "clang/Lex/HeaderSearchOptions.h"
+#include "clang/Lex/LiteralSupport.h"
 #include "clang/Lex/MacroArgs.h"
 #include "clang/Lex/MacroInfo.h"
 #include "clang/Lex/ModuleLoader.h"
@@ -659,4 +660,11 @@
   }
   EXPECT_TRUE(ToksView.empty());
 }
+
+TEST_F(LexerTest, BrokenStringLiteral) {
+  const llvm::StringLiteral Source = R"cpp("\N")cpp";
+  // Make sure this isn't crashing.
+  StringLiteralParser P(Lex(Source), *PP);
+  EXPECT_TRUE(P.hadError);
+}
 } // anonymous namespace
Index: clang/test/Lexer/char-escapes-delimited.c
===
--- clang/test/Lexer/char-escapes-delimited.c
+++ clang/test/Lexer/char-escapes-delimited.c
@@ -94,7 +94,7 @@
 
   unsigned h = U'\N{LOTUS}';  // ext-warning {{extension}} cxx2b-warning {{C++2b}}
   unsigned i = u'\N{GREEK CAPITAL LETTER DELTA}'; // ext-warning {{extension}} cxx2b-warning {{C++2b}}
-  char j = '\NN'; // expected-error {{expected '{' after '\N' escape sequence}}
+  char j = '\NN'; // expected-error {{expected '{' after '\N' escape sequence}} expected-warning {{multi-character character constant}}
   unsigned k = u'\N{LOTUS';   // expected-error {{incomplete universal character name}}
 }
 
Index: clang/lib/Lex/LiteralSupport.cpp
===
--- clang/lib/Lex/LiteralSupport.cpp
+++ clang/lib/Lex/LiteralSupport.cpp
@@ -545,7 +545,6 @@
diag::err_delimited_escape_missing_brace)
   << StringRef(&ThisTokBuf[-1], 1);
 }
-ThisTokBuf++;
 return false;
   }
   ThisTokBuf++;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D133289: [C2X] N3007 Type inference for object definitions

2022-10-05 Thread Guillot Tony via Phabricator via cfe-commits
to268 updated this revision to Diff 465312.
to268 added a comment.

Added a check to not diagnose a missing type specifier in C2x mode


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133289

Files:
  clang/include/clang/Basic/DiagnosticParseKinds.td
  clang/lib/Parse/ParseDecl.cpp
  clang/lib/Parse/ParseExpr.cpp
  clang/lib/Sema/DeclSpec.cpp
  clang/lib/Sema/SemaType.cpp
  clang/test/C/C2x/n3007.c
  clang/test/CodeGen/auto.c
  clang/test/Parser/c2x-auto.c
  clang/test/Sema/c2x-auto.c
  clang/www/c_status.html

Index: clang/www/c_status.html
===
--- clang/www/c_status.html
+++ clang/www/c_status.html
@@ -1184,7 +1184,7 @@
 
   Type inference for object declarations
   https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3007.htm";>N3007
-  No
+  Clang 16
 
 
   constexpr for object definitions
Index: clang/test/Sema/c2x-auto.c
===
--- /dev/null
+++ clang/test/Sema/c2x-auto.c
@@ -0,0 +1,52 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -std=c2x %s
+
+void test_basic_types(void) {
+  auto undefined; // expected-error {{declaration of variable 'undefined' with deduced type 'auto' requires an initializer}}
+  auto auto_int = 4;
+  auto auto_long = 4UL;
+}
+
+void test_sizeof_typeof(void) {
+  auto auto_size = sizeof(auto);  // expected-error {{expected expression}}
+  typeof(auto) tpof = 4;  // expected-error {{expected expression}}
+}
+
+void test_casts(void) {
+  auto int_cast = (int)(4 + 3);
+  auto double_cast = (double)(1 / 3);
+  auto long_cast = (long)(4UL + 3UL);
+  auto auto_cast = (auto)(4 + 3); // expected-error {{expected expression}}
+}
+
+void test_compound_literral(void) {
+  auto int_cl = (int){13};
+  auto double_cl = (double){2.5};
+
+  // FIXME: This should be accepted per C2x 6.5.2.5p4
+  auto auto_cl = (auto){13};  // expected-error {{'auto' is not allowed in a compound literal}}
+  auto array[] = { 1, 2, 3 }; // expected-error {{'array' declared as array of 'auto'}}
+}
+
+void test_qualifiers(int x, const int y) {
+  const auto a = x;
+  auto b = y;
+  static auto c = 1UL;
+  int* pa = &a; // expected-warning {{initializing 'int *' with an expression of type 'const int *' discards qualifiers}}
+  const int* pb = &b;
+  int* pc = &c; // expected-warning {{incompatible pointer types initializing 'int *' with an expression of type 'unsigned long *'}}
+}
+
+void test_scopes(void) {
+  {
+auto a = 7;
+auto b = 9;
+auto c = a + b;
+  }
+  {
+auto d = a * b;   // expected-error {{use of undeclared identifier 'a'}} \
+ expected-error {{use of undeclared identifier 'b'}}
+{
+  auto e = d + c; // expected-error {{use of undeclared identifier 'c'}}
+}
+  }
+}
Index: clang/test/Parser/c2x-auto.c
===
--- /dev/null
+++ clang/test/Parser/c2x-auto.c
@@ -0,0 +1,123 @@
+// RUN: %clang_cc1 -fsyntax-only -verify=expected,c2x -std=c2x %s
+// RUN: %clang_cc1 -fsyntax-only -verify=expected,c17 -std=c17 %s
+
+#define AUTO_MACRO(_NAME, ARG, ARG2, ARG3) \
+  auto _NAME = ARG + (ARG2 / ARG3);
+
+struct S {
+int a;
+auto b;   // c2x-error {{'auto' not allowed in struct member}} \
+ c17-error {{type name does not allow storage class to be specified}} \
+ c17-error {{type specifier missing, defaults to 'int'; ISO C99 and later do not support implicit int}}
+union {
+  char c;
+  auto smth;  // c2x-error {{'auto' not allowed in union member}} \
+ c17-error {{type name does not allow storage class to be specified}} \
+ c17-error {{type specifier missing, defaults to 'int'; ISO C99 and later do not support implicit int}}
+} u;
+};
+
+enum E : auto { // c2x-error {{'auto' not allowed here}} \
+   c17-error {{expected a type}} \
+   c17-error {{type name does not allow storage class to be specified}}
+  One,
+  Two,
+  Tree,
+};
+
+auto basic_usage(auto auto) {   // c2x-error {{'auto' not allowed in function prototype}} \
+   c2x-error {{'auto' not allowed in function return type}} \
+   c2x-error {{cannot combine with previous 'auto' declaration specifier}} \
+   c17-error {{invalid storage class specifier in function declarator}} \
+   c17-error {{illegal storage class on function}} \
+   c17-warning {{duplicate 'auto' declaration specifier}} \
+   c17-warning {{omitting the parameter name in a function definition is a C2x extension}} \
+   c17-error {{type specifier missing, defaults to 'in

[PATCH] D135247: [clang][analyzer] Add stream functions to StdLibraryFunctionsChecker.

2022-10-05 Thread Balázs Kéri via Phabricator via cfe-commits
balazske created this revision.
Herald added subscribers: steakhal, manas, ASDenysPetrov, martong, gamesh411, 
dkrupp, donat.nagy, Szelethus, mikhail.ramalho, a.sidorin, szepet, 
baloghadamsoftware, xazax.hun.
Herald added a reviewer: Szelethus.
Herald added a reviewer: NoQ.
Herald added a project: All.
balazske requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Some of the stream handling functions are modeled in StreamChecker.
These are now added to StdLibraryFunctionsChecker where additional
checks are performed on these functions. This includes setting of
'errno' related state. In this way the errno state is set for these
functions (almost) completely in StdLibraryFunctionsChecker.
The two checkers work together and 'apiModeling.StdCLibraryFunctions'
and its 'ModelPOSIX=true' option should be now a dependency of
checker 'alpha.unix.Stream'.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D135247

Files:
  clang/lib/StaticAnalyzer/Checkers/ErrnoChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/ErrnoModeling.cpp
  clang/lib/StaticAnalyzer/Checkers/ErrnoModeling.h
  clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
  clang/test/Analysis/Inputs/system-header-simulator.h
  clang/test/Analysis/stream-errno-note.c
  clang/test/Analysis/stream-errno.c
  clang/test/Analysis/stream-noopen.c

Index: clang/test/Analysis/stream-noopen.c
===
--- /dev/null
+++ clang/test/Analysis/stream-noopen.c
@@ -0,0 +1,97 @@
+// RUN: %clang_analyze_cc1 -verify %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=alpha.unix.Errno \
+// RUN:   -analyzer-checker=alpha.unix.Stream \
+// RUN:   -analyzer-checker=apiModeling.StdCLibraryFunctions \
+// RUN:   -analyzer-config apiModeling.StdCLibraryFunctions:ModelPOSIX=true \
+// RUN:   -analyzer-checker=debug.ExprInspection
+
+// enable only StdCLibraryFunctions checker
+// RUN: %clang_analyze_cc1 -verify %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=alpha.unix.Errno \
+// RUN:   -analyzer-checker=apiModeling.StdCLibraryFunctions \
+// RUN:   -analyzer-config apiModeling.StdCLibraryFunctions:ModelPOSIX=true \
+// RUN:   -analyzer-checker=debug.ExprInspection
+
+#include "Inputs/system-header-simulator.h"
+#include "Inputs/errno_var.h"
+
+void clang_analyzer_eval(int);
+
+const char *WBuf = "123456789";
+char RBuf[10];
+
+void test_freopen(FILE *F) {
+  F = freopen("xxx", "w", F);
+  if (F) {
+if (errno) {} // expected-warning{{undefined}}
+  } else {
+clang_analyzer_eval(errno != 0); // expected-warning {{TRUE}}
+  }
+}
+
+void test_fread(FILE *F) {
+  size_t Ret = fread(RBuf, 1, 10, F);
+  if (Ret == 10) {
+if (errno) {} // expected-warning{{undefined}}
+  } else {
+clang_analyzer_eval(errno != 0); // expected-warning {{TRUE}}
+  }
+  clang_analyzer_eval(feof(F)); // expected-warning {{UNKNOWN}}
+  clang_analyzer_eval(ferror(F)); // expected-warning {{UNKNOWN}}
+}
+
+void test_fwrite(FILE *F) {
+  size_t Ret = fwrite(WBuf, 1, 10, F);
+  if (Ret == 10) {
+if (errno) {} // expected-warning{{undefined}}
+  } else {
+clang_analyzer_eval(errno != 0); // expected-warning {{TRUE}}
+  }
+  clang_analyzer_eval(feof(F)); // expected-warning {{UNKNOWN}}
+  clang_analyzer_eval(ferror(F)); // expected-warning {{UNKNOWN}}
+}
+
+void test_fclose(FILE *F) {
+  int Ret = fclose(F);
+  if (Ret == 0) {
+if (errno) {} // expected-warning{{undefined}}
+  } else {
+clang_analyzer_eval(Ret == EOF); // expected-warning {{TRUE}}
+clang_analyzer_eval(errno != 0); // expected-warning {{TRUE}}
+  }
+  clang_analyzer_eval(feof(F)); // expected-warning {{UNKNOWN}}
+  clang_analyzer_eval(ferror(F)); // expected-warning {{UNKNOWN}}
+}
+
+void test_fseek(FILE *F) {
+  int Ret = fseek(F, SEEK_SET, 1);
+  if (Ret == 0) {
+if (errno) {} // expected-warning{{undefined}}
+  } else {
+clang_analyzer_eval(Ret == -1); // expected-warning {{TRUE}}
+clang_analyzer_eval(errno != 0); // expected-warning {{TRUE}}
+  }
+  clang_analyzer_eval(feof(F)); // expected-warning {{UNKNOWN}}
+  clang_analyzer_eval(ferror(F)); // expected-warning {{UNKNOWN}}
+}
+
+void freadwrite_zerosize(FILE *F) {
+  fwrite(WBuf, 1, 0, F);
+  clang_analyzer_eval(feof(F)); // expected-warning {{UNKNOWN}}
+  clang_analyzer_eval(ferror(F)); // expected-warning {{UNKNOWN}}
+  if (errno) {} // no-warning
+  fwrite(WBuf, 0, 1, F);
+  clang_analyzer_eval(feof(F)); // expected-warning {{UNKNOWN}}
+  clang_analyzer_eval(ferror(F)); // expected-warning {{UNKNOWN}}
+  if (errno) {} // no-warning
+  fread(RBuf, 1, 0, F);
+  clang_analyzer_eval(feof(F)); // expected-warning {{UNKNOWN}}
+  clang_analyzer_eval(ferror(F)); // expected-warning {{UNKNOWN}}
+  if (errno) {} // no-warning
+  fread(RBuf, 0, 1, F);
+  clang_analyzer_eval(feof(F)); // expected-warning {{UNKNOWN}}
+  clang_

[PATCH] D135247: [clang][analyzer] Add stream functions to StdLibraryFunctionsChecker.

2022-10-05 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added a reviewer: martong.
balazske added a comment.
Herald added a subscriber: rnkovacs.

This is another approach to D132017 . This 
eliminates redundant code from `StreamChecker` that can be done with 
`StdLibraryFunctionsChecker` too. Something to fix is to somehow mention the 
dependency of **apiModeling.StdCLibraryFunctions** and //ModelPOSIX=true// 
option. If `StreamChecker` is used without these dependencies the errno part of 
the modeling can be incorrect (errno is not changed by the `evalCall` in 
`StreamChecker`, it is expected to be updated in the other checker in 
`postCall`).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135247

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


[PATCH] D134425: [NFC] Create a AllocLikeOpInterface and make memref::AllocOp, memref::AllocaOp and gpu::AllocOp implement it.

2022-10-05 Thread Alex Zinenko via Phabricator via cfe-commits
ftynse requested changes to this revision.
ftynse added a comment.
This revision now requires changes to proceed.

I would expect a new top-level interface (in lib/Interfaces) to go through the 
RFC process.

I have concerns about the interface design. Specifically, it appears to be 
promoting details specific to operations from one dialect (`memref.alloc(a)`) 
such as the fact that the result of an allocation is a memref (it's not, we 
have allocations in LLVM and SPIR-V that produce different types), that it has 
alignment defined as integer, and that it has some symbol operands presumably 
related to memref's affine layouts. If this were to live in `lib/Interfaces`, 
it should make either cover wider range of allocation-like operations or make a 
clear case as to why this is not desired accompanied by a name change.




Comment at: mlir/include/mlir/Dialect/GPU/IR/GPUOps.td:937-954
+
+/// Returns the dynamic sizes for this alloc operation if specified.
+operand_range getDynamicSizes() { return dynamicSizes(); }
+
+/// Returns the symbol operands for this alloc operation if specified.
+operand_range getSymbolOperands() { return symbolOperands(); }
+

I suppose these are only necessary because the dialect doesn't emit accessor 
using the prefixed form? Make sure to rebase this commit because the GPU 
dialect must have been switched to the prefixed form - 
https://discourse.llvm.org/t/psa-raw-accessors-are-being-removed/65629.



Comment at: mlir/include/mlir/Dialect/MemRef/IR/MemRefOps.td:103-120
+
+/// Returns the dynamic sizes for this alloc operation if specified.
+operand_range getDynamicSizes() { return dynamicSizes(); }
+
+/// Returns the symbol operands for this alloc operation if specified.
+operand_range getSymbolOperands() { return symbolOperands(); }
+

Ditto.



Comment at: mlir/include/mlir/Interfaces/AllocLikeOpInterface.h:1
+//===- AllocLikeOpInterface.h - alloc like  operations interface-===//
+//

Please use the correct header line.



Comment at: mlir/include/mlir/Interfaces/AllocLikeOpInterface.td:1
+//===-- AllocLikeOpInterface.td -*- tablegen 
-*===//
+//

Please follow the (implicit) convention from other files for this line: the 
file name is left aligned, the file type is right aligned, and the entire line 
fits into 80 cols.



Comment at: mlir/include/mlir/Interfaces/AllocLikeOpInterface.td:9
+//
+// Defines the interface for copy-like operations.
+//

This looks wrong.



Comment at: mlir/include/mlir/Interfaces/AllocLikeOpInterface.td:20
+  let description = [{
+A alloc-like operation is one that allocates memory of a given type.
+  }];

Type is not mandatory for allocations, can be just bytes.



Comment at: mlir/include/mlir/Interfaces/AllocLikeOpInterface.td:26
+InterfaceMethod<
+  /*desc=*/"Returns the dynamic dimension sizes of the resultant memref.",
+  /*retTy=*/"::llvm::SmallVector<::mlir::Value>",

Memref is not a mandatory concept for allocating memory, I would rather not 
enshrine it in the top-level interface.



Comment at: mlir/include/mlir/Interfaces/AllocLikeOpInterface.td:27
+  /*desc=*/"Returns the dynamic dimension sizes of the resultant memref.",
+  /*retTy=*/"::llvm::SmallVector<::mlir::Value>",
+  /*methodName=*/"getDynamicSizes"

Does it have to be a vector (copy) of values? Can't it be an `OperandRange`, a 
`ValueRange` or something similar?



Comment at: mlir/lib/Interfaces/AllocLikeOpInterface.cpp:1
+//===- AllocLikeOpInterface.cpp - Alloc like operations interface in MLIR-===//
+//

Nit: 80 cols.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134425

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


[clang] feea7ef - Revert "[clang][Lex] Fix a crash on malformed string literals"

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

Author: Kadir Cetinkaya
Date: 2022-10-05T10:37:32+02:00
New Revision: feea7ef23cb1bef92d363cc613052f8f3a878fc2

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

LOG: Revert "[clang][Lex] Fix a crash on malformed string literals"

This reverts commit 36a200208facf58d454c9b7253c956c2f2a8b946.

Added: 


Modified: 
clang/lib/Lex/LiteralSupport.cpp
clang/test/Lexer/char-escapes-delimited.c
clang/unittests/Lex/LexerTest.cpp

Removed: 




diff  --git a/clang/lib/Lex/LiteralSupport.cpp 
b/clang/lib/Lex/LiteralSupport.cpp
index 160240e49dd70..1a48a68c28b62 100644
--- a/clang/lib/Lex/LiteralSupport.cpp
+++ b/clang/lib/Lex/LiteralSupport.cpp
@@ -545,6 +545,7 @@ static bool ProcessNamedUCNEscape(const char *ThisTokBegin,
diag::err_delimited_escape_missing_brace)
   << StringRef(&ThisTokBuf[-1], 1);
 }
+ThisTokBuf++;
 return false;
   }
   ThisTokBuf++;

diff  --git a/clang/test/Lexer/char-escapes-delimited.c 
b/clang/test/Lexer/char-escapes-delimited.c
index 43ade65a58309..65e3dc740e3b4 100644
--- a/clang/test/Lexer/char-escapes-delimited.c
+++ b/clang/test/Lexer/char-escapes-delimited.c
@@ -94,7 +94,7 @@ void named(void) {
 
   unsigned h = U'\N{LOTUS}';  // ext-warning {{extension}} 
cxx2b-warning {{C++2b}}
   unsigned i = u'\N{GREEK CAPITAL LETTER DELTA}'; // ext-warning {{extension}} 
cxx2b-warning {{C++2b}}
-  char j = '\NN'; // expected-error {{expected 
'{' after '\N' escape sequence}} expected-warning {{multi-character character 
constant}}
+  char j = '\NN'; // expected-error {{expected 
'{' after '\N' escape sequence}}
   unsigned k = u'\N{LOTUS';   // expected-error 
{{incomplete universal character name}}
 }
 

diff  --git a/clang/unittests/Lex/LexerTest.cpp 
b/clang/unittests/Lex/LexerTest.cpp
index aefe5f1ab35a3..0ad644ce71465 100644
--- a/clang/unittests/Lex/LexerTest.cpp
+++ b/clang/unittests/Lex/LexerTest.cpp
@@ -18,7 +18,6 @@
 #include "clang/Basic/TokenKinds.h"
 #include "clang/Lex/HeaderSearch.h"
 #include "clang/Lex/HeaderSearchOptions.h"
-#include "clang/Lex/LiteralSupport.h"
 #include "clang/Lex/MacroArgs.h"
 #include "clang/Lex/MacroInfo.h"
 #include "clang/Lex/ModuleLoader.h"
@@ -660,11 +659,4 @@ TEST_F(LexerTest, RawAndNormalLexSameForLineComments) {
   }
   EXPECT_TRUE(ToksView.empty());
 }
-
-TEST_F(LexerTest, BrokenStringLiteral) {
-  const llvm::StringLiteral Source = R"cpp("\N")cpp";
-  // Make sure this isn't crashing.
-  StringLiteralParser P(Lex(Source), *PP);
-  EXPECT_TRUE(P.hadError);
-}
 } // anonymous namespace



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


[PATCH] D135161: [clang][Lex] Fix a crash on malformed string literals

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

this is causing some crashes in buildbots, and i can't repro. reverting until i 
figure this out.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135161

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


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

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

address comments


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,55 @@
 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());
+  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!");
 
   // 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);
 
   // 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(FirstLoc, Tok.getLocation(), &RelOffs);
-Tok.setLocation(Expansion.getLocWithOffset(RelOffs));
+  for (Token& T : Partition) {
+SourceLocation::IntTy RelativeOffset = T.getLocation().getRawEncoding() -
+   BeginLoc.getRawEncoding();
+T.setLocation(Expansion.getLocWithOffset(RelativeOf

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

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



Comment at: clang/lib/Lex/TokenLexer.cpp:1019
+// sourcelocation-against-bounds comparison.
+FileID BeginFID = SM.getFileID(BeginLoc);
+SourceLocation Limit =

nickdesaulniers wrote:
> sammccall wrote:
> > this getFileID() call is unneccesary when `All.empty() || 
> > All.front().getLocation().isFileID()`.
> > 
> > Worth checking whether bailing out in that case is profitable?
> > 
> > You could do it right at the top:
> > ```
> > if (All.size() == 1 || All[0].getLocation().isFileID() != 
> > All[1].getLocation().isFileID())
> >   return All.take_front(1);
> > ```
> Good point; I'd say "avoid getFileID" at all costs, even to readability/style.
We have handled the 1-element special case in the caller, so All.size() > 1 in 
this function. Added an assertion. 

> All[0].getLocation().isFileID() != All[1].getLocation().isFileID()

I tried it when writing this patch, I don't find the result now, but IIRC 
performance difference is negligible. I'm happy to add this special case since 
it won't hurt the readability too much.



Comment at: clang/lib/Lex/TokenLexer.cpp:1038
+  for (Token& T : Partition) {
+SourceLocation::IntTy RelativeOffset = T.getLocation().getRawEncoding() -
+   BeginLoc.getRawEncoding();

sammccall wrote:
> hmm, actually maybe just before this line would be the best place to assert 
> that T and BeginLoc are in the same FileID, as it justifies the subtraction
I agree that this is the best place to put the check-file-id assertion.

Simply adding `assert(getFileID(BeginLoc) == getFileID(T.getLocation()))` can 
work, but it creates N-1 unnecessary getFileID calls on BeginLoc for assert 
build, it is better to avoid it. The only way I can think of is 

```
#ifndef NDEBUG
FileID BeginFID = SM.getFileID(BeginLoc);
assert(BeginFID == getFileID(T.getLocation()));
#endif
```



Comment at: clang/lib/Lex/TokenLexer.cpp:1008
+});
+assert(!Partition.empty() &&
+   llvm::all_of(Partition.drop_front(),

nickdesaulniers wrote:
> hokein wrote:
> > sammccall wrote:
> > > nickdesaulniers wrote:
> > > > Could you just check that all of the tokens in the partition have the 
> > > > same fileID as the first token?
> > > > 
> > > > ```
> > > > FileID FirstFID = SM.getFileID(Partition[0]->getLocation());
> > > > llvm::all_of(Partition, [&SM, &FirstID](const Token &T) { return 
> > > > SM.getFileID(T.getLocation() == FID; });
> > > > ```
> > > > or move the assertion into the take_while above so we iterate less?
> > > this assertion seems to belong outside the if() - it applies to both the 
> > > file/macro case?
> > > I'd suggest asserting nonempty first and then the rest as another 
> > > assertion.
> > > also missing an assertion that if there are any more tokens, the next 
> > > token has a different FileID
> > > 
> > > that said with these assertions we should probably check we're not 
> > > regressing debug performance too much!
> > The optimization for this case is that we don't call any `getFileID`, the 
> > getFileID is only needed in the assert sanity check, so moving the 
> > assertion to `take_while` doesn't really work.
> > 
> > I adjust the code to save some unnecessary `getFileID` call in assert.
> Right, I do all development and profiles with Release builds with assertions 
> enabled.  So avoiding getFileID in release+no_asserts builds is a win, but am 
> somewhat bummed to not get as much a win for my rel+assert builds.
> this assertion seems to belong outside the if() - it applies to both the 
> file/macro case?

yeah, it should apply the `else` case. Moved it outside -- it seems unnecessary 
to check the `else` case, since we actually do the partition based on the file 
id (that being said, it is somehow like `int s = 1+1; assert(s == 2);`),  but 
it might be good for code readability.

> I do all development and profiles with Release builds with assertions enabled

hmm, I think when doing profiles we probably should use a release build without 
assertions enabled to give a more correct result, since assertion will slow 
everything down.



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134942

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


[PATCH] D134529: [C++20][Clang] P2468R2 The Equality Operator You Are Looking For

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

Thanks! I have only various code style comments here, ptal. Overall LG.




Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:4705
+def note_ovl_ambiguous_eqeq_reversed_self_non_const : Note<
+  "mark operator== as const or add a matching operator!= to resolve the 
ambiguity">;
 def note_ovl_ambiguous_oper_binary_selected_candidate : Note<

NIT: for consistency with other diagnostics.



Comment at: clang/include/clang/Sema/Overload.h:1024
   /// candidates for operator Op.
-  bool shouldAddReversed(OverloadedOperatorKind Op);
+  bool mayAddReversed(OverloadedOperatorKind Op);
 

I am not sure the new name adds clarity.
It's unclear what the `true` return value means here. `should` clearly 
indicated returning true means the code has to proceed with adding the reversed 
operator. `may` means the code can choose to do so or not, I don't think that's 
quite right. `should` was really a better choice here.

That said, I don't think the rename itself is a bad idea, maybe there is a 
better name, but I couldn't come up with one.



Comment at: clang/lib/Sema/SemaOverload.cpp:904
+  for (unsigned I = 0; I < X->getNumParams(); ++I)
+if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
+Y->getParamDecl(I)->getType()))

Or, wow, I did not realize that template parameters types for different 
functions are considered equal. TIL something new, thanks :)



Comment at: clang/lib/Sema/SemaOverload.cpp:953
+  Sema::LookupNameKind::LookupOperatorName);
+  S.LookupName(NonMembers, S.getScopeForContext(const_cast(
+   EqFD->getEnclosingNamespaceContext(;

NIT: remove `const_cast`,  the non-const `FunctionDecl*` instead.
You'd need to do this for the corresponding parameter in `shouldAddReversed` 
too, but that seems very easy.



Comment at: clang/lib/Sema/SemaOverload.cpp:976
 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
-ASTContext &Ctx, const FunctionDecl *FD) {
-  if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator()))
+Sema &S, ArrayRef Args, const FunctionDecl *FD) {
+  auto Op = FD->getOverloadedOperator();

NIT: same suggestion as before. Just pass `Expr* FirstOperand` as the parameter 
instead of an array.



Comment at: 
clang/test/CXX/over/over.match/over.match.funcs/over.match.oper/p3-2a.cpp:129
+namespace P2468R2 {
+//=Problem cases prior to P2468R2 but now intentionally 
rejected=
+struct SymmetricNonConst {

NIT: same suggestion as before. use plain comments without `` padding for 
consistency with the rest of the file.



Comment at: 
clang/test/CXX/over/over.match/over.match.funcs/over.match.oper/p3-2a.cpp:207
+  ImplicitInt(int*);
+  bool operator==(const ImplicitInt&) const; // expected-note {{reversed}}
+  operator int*() const;

NIT: could we match against a larger piece of the message?
it's hard to read what the test is trying to check here.
In particular, I'm not sure if this intends to show the newly added note or 
simply point to operator that had its arguments reversed.



Comment at: 
clang/test/CXX/over/over.match/over.match.funcs/over.match.oper/p3-2a.cpp:231
+bool c1 = B() == C(); // OK, calls 2; reversed 2 is not a candidate because 
search for operator!= in C finds #3
+bool c2 = C() == B();  // expected-warning {{ISO C++20 considers use of 
overloaded operator '==' (with operand types 'C' and 'B') to be ambiguous 
despite there being a unique best viable function}}
+

NIT: could you add a comment explaining why this is ambiguous? This seems 
non-obvious.
It's because the search for `operator!=` happens inside `B` and never finds 
`3`, right?



Comment at: 
clang/test/CXX/over/over.match/over.match.funcs/over.match.oper/p3-2a.cpp:238
+}
+bool d1 = 0 == D();  // OK, calls reversed 4; 5 does not forbid 4 as a rewrite 
target
+} // namespace example

NIT: could you add a comment mentioning that "search" does not look inside 
inline namespaces?
This seems non-obvious.



Comment at: 
clang/test/CXX/over/over.match/over.match.funcs/over.match.oper/p3-2a.cpp:269
+};
+bool b = B() == B(); // ok. No rewrite due to const.
+

Also due to different parameter types (`T` vs `B`)?
So the description is incomplete or am I missing something?



Comment at: 
clang/test/CXX/over/over.match/over.match.funcs/over.match.oper/p3-2a.cpp:275
+bool operator!=(C, int);
+bool c = 0 == C(); // Ok. Use rewritten candidate.
+}

NIT: add `as the non-template operator != does not correspond to template 
operator ==`



Comment at: 
c

[clang] c21e571 - Fix clang baremetal test

2022-10-05 Thread Mikhail Goncharov via cfe-commits

Author: Mikhail Goncharov
Date: 2022-10-05T11:32:28+02:00
New Revision: c21e57156c25734df44bb4893b9fc31dfc7de56d

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

LOG: Fix clang baremetal test

def48cae45a5085b7759f2be71768e27718b901a accidentally dropped 
-no-canonical-prefixes

Added: 


Modified: 
clang/test/Driver/baremetal.cpp

Removed: 




diff  --git a/clang/test/Driver/baremetal.cpp b/clang/test/Driver/baremetal.cpp
index ac99089432477..aded919156095 100644
--- a/clang/test/Driver/baremetal.cpp
+++ b/clang/test/Driver/baremetal.cpp
@@ -97,7 +97,7 @@
 // RUN:   | FileCheck %s --check-prefix=CHECK-SYSROOT-INC
 // CHECK-SYSROOT-INC-NOT: "-internal-isystem" "include"
 
-// RUN: %clang %s -### --target=aarch64-none-elf 2>&1 \
+// RUN: %clang -no-canonical-prefixes %s -### --target=aarch64-none-elf 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-AARCH64-NO-HOST-INC %s
 // Verify that the bare metal driver does not include any host system paths:
 // CHECK-AARCH64-NO-HOST-INC: InstalledDir: [[INSTALLEDDIR:.+]]



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


[PATCH] D129156: Add -fpass-plugin option to Flang

2022-10-05 Thread Valentin Clement via Phabricator via cfe-commits
clementval added a comment.

I get a failure  since this commit. `Could not load library By.so` ... `cannot 
open shared object file: No such file or directory`. Maybe a missing dependency?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129156

___
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-05 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 465325.
hokein marked an inline comment as done.
hokein added a comment.

add an assertion.


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
@@ -790,24 +790,29 @@
 
   // 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.
   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;
@@ -817,13 +822,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
@@ -790,24 +790,29 @@
 
   // 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.
   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;
@@ -817,13 +822,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 LessI

[PATCH] D135254: [clang][Sema] Fix crash on invalid base destructor

2022-10-05 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet created this revision.
kadircet added a reviewer: hokein.
Herald added a project: All.
kadircet requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

LookupSpecialMember might fail, so changes the cast to cast_or_null.
Inside Sema, skip a particular base, similar to other cases, rather than
asserting on dtor showing up.

Other option would be to mark classes with invalid destructors as invalid, but
that seems like a lot more invasive and we do lose lots of diagnostics that
currently work on classes with broken members.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D135254

Files:
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaLookup.cpp
  clang/test/SemaCXX/destructor.cpp


Index: clang/test/SemaCXX/destructor.cpp
===
--- clang/test/SemaCXX/destructor.cpp
+++ clang/test/SemaCXX/destructor.cpp
@@ -550,4 +550,20 @@
   template void f(T *p) { p->~U(); } // expected-error 
{{ambiguous}}
 }
 
+namespace crash_on_invalid_base_dtor {
+struct Test {
+  virtual ~Test();
+};
+struct Baz : public Test { // expected-warning {{non-virtual destructor}}
+  Baz() {}
+  ~Baz() = defaul; // expected-error {{undeclared identifier 'defaul'}} \
+   // expected-error {{initializer on function}} \
+   // expected-note {{overridden virtual function is here}}
+};
+struct Foo : public Baz { // expected-error {{cannot override a non-deleted 
function}} \
+  // expected-note {{destructor of 'Foo' is implicitly 
deleted}}
+  Foo() {}
+};
+}
+
 #endif // BE_THE_HEADER
Index: clang/lib/Sema/SemaLookup.cpp
===
--- clang/lib/Sema/SemaLookup.cpp
+++ clang/lib/Sema/SemaLookup.cpp
@@ -40,6 +40,7 @@
 #include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/TinyPtrVector.h"
 #include "llvm/ADT/edit_distance.h"
+#include "llvm/Support/Casting.h"
 #include "llvm/Support/ErrorHandling.h"
 #include 
 #include 
@@ -3616,9 +3617,10 @@
 ///
 /// \returns The destructor for this class.
 CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
-  return cast(LookupSpecialMember(Class, CXXDestructor,
- false, false, false,
- false, 
false).getMethod());
+  return llvm::cast_or_null(
+  LookupSpecialMember(Class, CXXDestructor, false, false, false, false,
+  false)
+  .getMethod());
 }
 
 /// LookupLiteralOperator - Determine which literal operator should be used for
Index: clang/lib/Sema/SemaDeclCXX.cpp
===
--- clang/lib/Sema/SemaDeclCXX.cpp
+++ clang/lib/Sema/SemaDeclCXX.cpp
@@ -5696,7 +5696,9 @@
   continue;
 
 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
-assert(Dtor && "No dtor found for BaseClassDecl!");
+// Dtor might still be missing, e.g because it's invalid.
+if (!Dtor)
+  continue;
 
 // FIXME: caret should be on the start of the class name
 CheckDestructorAccess(Base.getBeginLoc(), Dtor,


Index: clang/test/SemaCXX/destructor.cpp
===
--- clang/test/SemaCXX/destructor.cpp
+++ clang/test/SemaCXX/destructor.cpp
@@ -550,4 +550,20 @@
   template void f(T *p) { p->~U(); } // expected-error {{ambiguous}}
 }
 
+namespace crash_on_invalid_base_dtor {
+struct Test {
+  virtual ~Test();
+};
+struct Baz : public Test { // expected-warning {{non-virtual destructor}}
+  Baz() {}
+  ~Baz() = defaul; // expected-error {{undeclared identifier 'defaul'}} \
+   // expected-error {{initializer on function}} \
+   // expected-note {{overridden virtual function is here}}
+};
+struct Foo : public Baz { // expected-error {{cannot override a non-deleted function}} \
+  // expected-note {{destructor of 'Foo' is implicitly deleted}}
+  Foo() {}
+};
+}
+
 #endif // BE_THE_HEADER
Index: clang/lib/Sema/SemaLookup.cpp
===
--- clang/lib/Sema/SemaLookup.cpp
+++ clang/lib/Sema/SemaLookup.cpp
@@ -40,6 +40,7 @@
 #include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/TinyPtrVector.h"
 #include "llvm/ADT/edit_distance.h"
+#include "llvm/Support/Casting.h"
 #include "llvm/Support/ErrorHandling.h"
 #include 
 #include 
@@ -3616,9 +3617,10 @@
 ///
 /// \returns The destructor for this class.
 CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
-  return cast(LookupSpecialMember(Class, CXXDestructor,
- false, false, false,
- false, false).getMethod());
+  return llvm::cast_or_null(
+  LookupSpecialMember(Class, CXXDestructor, false, false, false, false,
+   

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

2022-10-05 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/lib/Lex/TokenLexer.cpp:1038
+  for (Token& T : Partition) {
+SourceLocation::IntTy RelativeOffset = T.getLocation().getRawEncoding() -
+   BeginLoc.getRawEncoding();

hokein wrote:
> sammccall wrote:
> > hmm, actually maybe just before this line would be the best place to assert 
> > that T and BeginLoc are in the same FileID, as it justifies the subtraction
> I agree that this is the best place to put the check-file-id assertion.
> 
> Simply adding `assert(getFileID(BeginLoc) == getFileID(T.getLocation()))` can 
> work, but it creates N-1 unnecessary getFileID calls on BeginLoc for assert 
> build, it is better to avoid it. The only way I can think of is 
> 
> ```
> #ifndef NDEBUG
> FileID BeginFID = SM.getFileID(BeginLoc);
> assert(BeginFID == getFileID(T.getLocation()));
> #endif
> ```
I assume you mean with the #if once above, but the assert outside the #if and 
inside the loop?
That LGTM

There's also #ifdef EXPENSIVE_CHECKS, maybe not needed here though.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134942

___
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-05 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added inline comments.
This revision is now accepted and ready to land.



Comment at: clang-tools-extra/clangd/CMakeLists.txt:163
   clangToolingInclusions
+  clangToolingInclusionsSTL
   clangToolingSyntax

StandardLibrary or Stdlib?

STL isn't accurate or consistent with the names in the code.



Comment at: clang/lib/Tooling/Inclusions/STL/CMakeLists.txt:2
+add_clang_library(clangToolingInclusionsSTL
+  StandardLibrary.cpp
+

This means the implementation files and the header files have a different 
directory structure, which may be confusing to people trying to work out which 
library to link against based on the headers they included.

On the other hand, I think the cascading effect of dependencies => libraries => 
directory structure => header structure is pretty unfortunate leaking of llvm's 
sad cmake structure. Up to you




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] D133578: [OpenMP][OMPIRBuilder] Add generation of SIMD align assumptions to OMPIRBuilder

2022-10-05 Thread Dominik Adamski via Phabricator via cfe-commits
domada updated this revision to Diff 465332.
domada added a comment.

Patch rebased.


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

https://reviews.llvm.org/D133578

Files:
  clang/lib/CodeGen/CGStmtOpenMP.cpp
  llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
  llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
  llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp
  mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp

Index: mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
===
--- mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
+++ mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
@@ -996,8 +996,9 @@
   if (llvm::Optional safelenVar = loop.getSafelen())
 safelen = builder.getInt64(safelenVar.value());
 
+  llvm::DenseMap alignedVars;
   ompBuilder->applySimd(
-  loopInfo,
+  loopInfo, alignedVars,
   loop.getIfExpr() ? moduleTranslation.lookupValue(loop.getIfExpr())
: nullptr,
   llvm::omp::OrderKind::OMP_ORDER_unknown, simdlen, safelen);
Index: llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp
===
--- llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp
+++ llvm/unittests/Frontend/OpenMPIRBuilderTest.cpp
@@ -1767,11 +1767,12 @@
 
 TEST_F(OpenMPIRBuilderTest, ApplySimd) {
   OpenMPIRBuilder OMPBuilder(*M);
-
+  DenseMap AlignedVars;
   CanonicalLoopInfo *CLI = buildSingleLoopFunction(DL, OMPBuilder, 32);
 
   // Simd-ize the loop.
-  OMPBuilder.applySimd(CLI, /* IfCond */ nullptr, OrderKind::OMP_ORDER_unknown,
+  OMPBuilder.applySimd(CLI, AlignedVars, /* IfCond */ nullptr,
+   OrderKind::OMP_ORDER_unknown,
/* Simdlen */ nullptr,
/* Safelen */ nullptr);
 
@@ -1798,13 +1799,84 @@
   }));
 }
 
-TEST_F(OpenMPIRBuilderTest, ApplySimdlen) {
+TEST_F(OpenMPIRBuilderTest, ApplySimdCustomAligned) {
   OpenMPIRBuilder OMPBuilder(*M);
+  IRBuilder<> Builder(BB);
+  const int AlignmentValue = 32;
+  AllocaInst *Alloc1 =
+  Builder.CreateAlloca(Builder.getInt8PtrTy(), Builder.getInt64(1));
+  AllocaInst *Alloc2 = Builder.CreateAlloca(
+  ArrayType::get(Builder.getInt32Ty(), 10), Builder.getInt64(1));
+  DenseMap AlignedVars;
+  auto Int8Ty = Builder.getInt8Ty();
+  Instruction *MallocInstr = CallInst::CreateMalloc(
+  Alloc2, Builder.getInt64Ty(), Int8Ty, ConstantExpr::getSizeOf(Int8Ty),
+  Builder.getInt64(400), nullptr, "");
+  Builder.CreateStore(MallocInstr, Alloc1);
+
+  AlignedVars.insert({Alloc1, Builder.getInt64(AlignmentValue)});
+  AlignedVars.insert({Alloc2, Builder.getInt64(AlignmentValue)});
 
   CanonicalLoopInfo *CLI = buildSingleLoopFunction(DL, OMPBuilder, 32);
 
   // Simd-ize the loop.
-  OMPBuilder.applySimd(CLI, /* IfCond */ nullptr, OrderKind::OMP_ORDER_unknown,
+  OMPBuilder.applySimd(CLI, AlignedVars, /* IfCond */ nullptr,
+   OrderKind::OMP_ORDER_unknown,
+   /* Simdlen */ nullptr,
+   /* Safelen */ nullptr);
+
+  OMPBuilder.finalize();
+  EXPECT_FALSE(verifyModule(*M, &errs()));
+
+  PassBuilder PB;
+  FunctionAnalysisManager FAM;
+  PB.registerFunctionAnalyses(FAM);
+  LoopInfo &LI = FAM.getResult(*F);
+
+  const std::vector &TopLvl = LI.getTopLevelLoops();
+  EXPECT_EQ(TopLvl.size(), 1u);
+
+  Loop *L = TopLvl.front();
+  EXPECT_TRUE(findStringMetadataForLoop(L, "llvm.loop.parallel_accesses"));
+  EXPECT_TRUE(getBooleanLoopAttribute(L, "llvm.loop.vectorize.enable"));
+
+  // Check for llvm.access.group metadata attached to the printf
+  // function in the loop body.
+  BasicBlock *LoopBody = CLI->getBody();
+  EXPECT_TRUE(any_of(*LoopBody, [](Instruction &I) {
+return I.getMetadata("llvm.access.group") != nullptr;
+  }));
+
+  // Check if number of assumption instructions is equal to number of aligned
+  // variables
+  BasicBlock *LoopPreheader = CLI->getPreheader();
+  size_t NumAssummptionCallsInPreheader = count_if(
+  *LoopPreheader, [](Instruction &I) { return isa(I); });
+  EXPECT_EQ(NumAssummptionCallsInPreheader, AlignedVars.size());
+
+  // Check if variables are correctly aligned
+  for (auto &Instr : LoopPreheader->getInstList()) {
+if (isa(Instr)) {
+  auto AssumeInstruction = dyn_cast(&Instr);
+  if (AssumeInstruction->getNumTotalBundleOperands()) {
+auto Bundle = AssumeInstruction->getOperandBundleAt(0);
+if (Bundle.getTagName() == "align") {
+  EXPECT_TRUE(isa(Bundle.Inputs[1]));
+  auto ConstIntVal = dyn_cast(Bundle.Inputs[1]);
+  EXPECT_EQ(ConstIntVal->getSExtValue(), AlignmentValue);
+}
+  }
+}
+  }
+}
+TEST_F(OpenMPIRBuilderTest, ApplySimdlen) {
+  OpenMPIRBuilder OMPBuilder(*M);
+  DenseMap AlignedVars;
+  CanonicalLoopInfo *CLI = buildSingleLoopFunction(DL, OMPBuilder, 32);
+
+  // Simd-ize the loop.
+  OMPBuild

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

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

This did turn up a problem.

With this patch Clang treats the following (based on 
https://source.chromium.org/chromium/chromium/src/+/main:media/formats/hls/source_string.h;l=125)
 as invalid, and so does MSVC:

  template  struct __declspec(dllexport) Foo {
  static Foo create();
  };
  
  // Don't allow creating Foo's of ints.
  template <> Foo Foo::create() = delete; // MSVC: attempting to 
delete a __declspec(dllexport) function

The dllimport case errors similarly.

I'm tempted to make Clang keep allowing this. The intent of the code is 
perfectly clear -- the user is trying to delete the function, not export/import 
it -- and I can't think of any good way for the user to work around the error.

(Besides this issue, at least Chromium builds cleanly with this patch.)


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] D134859: [clang][Interp] Implement basic support for floating point values

2022-10-05 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder added inline comments.



Comment at: clang/lib/AST/Interp/Floating.h:27-29
+  template  struct Repr;
+  template <> struct Repr<32> { using Type = float; };
+  template <> struct Repr<64> { using Type = double; };

dblaikie wrote:
> jcranmer-intel wrote:
> > aaron.ballman wrote:
> > > tbaeder wrote:
> > > > aaron.ballman wrote:
> > > > > tbaeder wrote:
> > > > > > jcranmer-intel wrote:
> > > > > > > tbaeder wrote:
> > > > > > > > jcranmer-intel wrote:
> > > > > > > > > aaron.ballman wrote:
> > > > > > > > > > Er, how will this extend to `long double` where the number 
> > > > > > > > > > of bits is rather more difficult?
> > > > > > > > > Or `half` and `bfloat`, which are both 16-bit floating-point 
> > > > > > > > > types?
> > > > > > > > I have spent some time with this today and tried to simply 
> > > > > > > > always use `APFloat` instead of a primitive type. Unfortunately 
> > > > > > > > that doesn't work because what we put on the stack is not the 
> > > > > > > > `Floating` (or `Integral`), but the underlying primitive type. 
> > > > > > > > So even if we do the final math (in `::add`, etc) via 
> > > > > > > > `APFloat`, we need something we can serialize to `char[]` so we 
> > > > > > > > can put it on the stack. Do you think that would work?
> > > > > > > I don't know enough about the structure of the bytecode 
> > > > > > > interpreter here to say for sure, but this smells to me like 
> > > > > > > you're baking in an assumption that every primitive target type 
> > > > > > > has a corresponding primitive type on the host. This assumption 
> > > > > > > just doesn't hold when it comes to floating point (only two of 
> > > > > > > the seven types, `float` and `double`, are generally portable, 
> > > > > > > and even then, there be dragons in some corner cases).
> > > > > > > 
> > > > > > > If you do need to continue down this route, there are two 
> > > > > > > requirements that should be upheld:
> > > > > > > * The representation shouldn't assume that the underlying 
> > > > > > > primitive type exists on host (bfloat16 and float128 are better 
> > > > > > > test cases here).
> > > > > > > * Conversion to/from host primitive types shouldn't be easy to 
> > > > > > > accidentally do.
> > > > > > > 
> > > > > > > (Worth repeating again that bit size is insufficient to 
> > > > > > > distinguish floating point types: `bfloat` and `half` are both 
> > > > > > > 16-bit, PPC `long double` and IEEE 754 quad precision are both 
> > > > > > > 128-bit, and x86 `long double` is 80 bits stored as 96 bits on 
> > > > > > > 32-bit and 128 bits on 64-bit.)
> > > > > > Well, is there a way to convert an APFloat to a char[] that would 
> > > > > > work instead of going to float/double and storing that? The only 
> > > > > > thing I see in the docs is `convertToHexString()` (and the docs 
> > > > > > don't mention whether the conversion is lossy). If not, do you 
> > > > > > think adding such a conversion to `APFloat` and its various 
> > > > > > implementations is the better way forward?
> > > > > Let's avoid serializing the floats to strings so that we can parse 
> > > > > the string to turn it back into a float later; that's going to have 
> > > > > poor performance even if we do get all the corner cases correct 
> > > > > regarding things like rounding, etc.
> > > > > 
> > > > > `APFloat` does not have any sort of serialization functionality 
> > > > > beyond through strings representing the value. I think you'd have to 
> > > > > invent such an interface.
> > > > Do you know who I might talk to regrading such an interface, both the 
> > > > implementation as well as general feasibility?
> > > I think there may be at least two ways to do this: use an `APFloat` and 
> > > put the serialization interfaces there, or use an `APValue` and put the 
> > > serialization interfaces there.
> > > 
> > > Because `APFloat` is an ADT in LLVM, I think it should probably go up on 
> > > Discourse for broader discussion. @chandlerc is still listed as the code 
> > > owner for ADTs but he's not been active in quite some time. Instead, I 
> > > would recommend talking to @dblaikie (he's got a good eye for ADT work in 
> > > general) and @foad, @RKSimon, and @sepavloff as folks who have recently 
> > > been touching `APFloat`.
> > > 
> > > `APValue` is a Clang-specific class, and it already has some amount of 
> > > serialization support, it seems 
> > > (https://github.com/llvm/llvm-project/blob/main/clang/include/clang/AST/APValue.h#L54).
> > >  From a quick look, it seems we're already using `APValue` in a 
> > > reasonable number of places in the interpreter, so it might make sense to 
> > > use this object consistently to represent all values in the new 
> > > interpreter?
> > Going through `APInt` is already possible in `APFloat`, and that might have 
> > some methods to go to char arrays.
> Yeah - IR gets serialized APFloats somehow (maybe through some layers of 
> indirection) so

[PATCH] D135256: [clang] Add Create method for CXXBoolLiteralExpr

2022-10-05 Thread David Spickett via Phabricator via cfe-commits
DavidSpickett created this revision.
Herald added a subscriber: martong.
Herald added a reviewer: shafik.
Herald added a project: All.
DavidSpickett requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D135256

Files:
  clang/include/clang/AST/ExprCXX.h
  clang/lib/AST/ASTImporter.cpp
  clang/lib/Sema/SemaTemplate.cpp


Index: clang/lib/Sema/SemaTemplate.cpp
===
--- clang/lib/Sema/SemaTemplate.cpp
+++ clang/lib/Sema/SemaTemplate.cpp
@@ -7829,8 +7829,8 @@
 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
Kind, T, Loc);
   } else if (T->isBooleanType()) {
-E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
- T, Loc);
+E = CXXBoolLiteralExpr::Create(Context, Arg.getAsIntegral().getBoolValue(),
+   T, Loc);
   } else if (T->isNullPtrType()) {
 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
   } else {
Index: clang/lib/AST/ASTImporter.cpp
===
--- clang/lib/AST/ASTImporter.cpp
+++ clang/lib/AST/ASTImporter.cpp
@@ -7922,8 +7922,8 @@
   if (!ToLocationOrErr)
 return ToLocationOrErr.takeError();
 
-  return new (Importer.getToContext()) CXXBoolLiteralExpr(
-  E->getValue(), *ToTypeOrErr, *ToLocationOrErr);
+  return CXXBoolLiteralExpr::Create(Importer.getToContext(), E->getValue(),
+*ToTypeOrErr, *ToLocationOrErr);
 }
 
 ExpectedStmt ASTNodeImporter::VisitMemberExpr(MemberExpr *E) {
Index: clang/include/clang/AST/ExprCXX.h
===
--- clang/include/clang/AST/ExprCXX.h
+++ clang/include/clang/AST/ExprCXX.h
@@ -730,6 +730,11 @@
   explicit CXXBoolLiteralExpr(EmptyShell Empty)
   : Expr(CXXBoolLiteralExprClass, Empty) {}
 
+  static CXXBoolLiteralExpr *Create(const ASTContext &C, bool Val, QualType Ty,
+SourceLocation Loc) {
+return new (C) CXXBoolLiteralExpr(Val, Ty, Loc);
+  }
+
   bool getValue() const { return CXXBoolLiteralExprBits.Value; }
   void setValue(bool V) { CXXBoolLiteralExprBits.Value = V; }
 


Index: clang/lib/Sema/SemaTemplate.cpp
===
--- clang/lib/Sema/SemaTemplate.cpp
+++ clang/lib/Sema/SemaTemplate.cpp
@@ -7829,8 +7829,8 @@
 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
Kind, T, Loc);
   } else if (T->isBooleanType()) {
-E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
- T, Loc);
+E = CXXBoolLiteralExpr::Create(Context, Arg.getAsIntegral().getBoolValue(),
+   T, Loc);
   } else if (T->isNullPtrType()) {
 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
   } else {
Index: clang/lib/AST/ASTImporter.cpp
===
--- clang/lib/AST/ASTImporter.cpp
+++ clang/lib/AST/ASTImporter.cpp
@@ -7922,8 +7922,8 @@
   if (!ToLocationOrErr)
 return ToLocationOrErr.takeError();
 
-  return new (Importer.getToContext()) CXXBoolLiteralExpr(
-  E->getValue(), *ToTypeOrErr, *ToLocationOrErr);
+  return CXXBoolLiteralExpr::Create(Importer.getToContext(), E->getValue(),
+*ToTypeOrErr, *ToLocationOrErr);
 }
 
 ExpectedStmt ASTNodeImporter::VisitMemberExpr(MemberExpr *E) {
Index: clang/include/clang/AST/ExprCXX.h
===
--- clang/include/clang/AST/ExprCXX.h
+++ clang/include/clang/AST/ExprCXX.h
@@ -730,6 +730,11 @@
   explicit CXXBoolLiteralExpr(EmptyShell Empty)
   : Expr(CXXBoolLiteralExprClass, Empty) {}
 
+  static CXXBoolLiteralExpr *Create(const ASTContext &C, bool Val, QualType Ty,
+SourceLocation Loc) {
+return new (C) CXXBoolLiteralExpr(Val, Ty, Loc);
+  }
+
   bool getValue() const { return CXXBoolLiteralExprBits.Value; }
   void setValue(bool V) { CXXBoolLiteralExprBits.Value = V; }
 
___
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-05 Thread David Spickett via Phabricator via cfe-commits
DavidSpickett updated this revision to Diff 465341.
DavidSpickett added a comment.

Rebase, Create moved to parent change.


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) &&
+ "only boolean supported");
+
+  clang::ASTContext &ast = var->getASTContext

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

2022-10-05 Thread David Spickett via Phabricator via cfe-commits
DavidSpickett updated this revision to Diff 465342.
DavidSpickett added a comment.

Rebase


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 namespace scope.
 @expectedFailureAll(debug_info=["dsym"])
Index: clang/lib/AST/StmtPrinter.cpp
===
--- clan

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

2022-10-05 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet created this revision.
kadircet added a reviewer: hokein.
Herald added a subscriber: arphaman.
Herald added a project: All.
kadircet requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

Repository:
  rG LLVM Github Monorepo

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] D135257: [clangd][Tweak] Make sure enclosing function doesnt have invalid children

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

This is triggering crashes in our production setup, but I couldn't come up with 
a reduced test case.

crash is triggered in the loop:

  for (const auto *S : EnclosingFunction->getBody()->children()) {
if (SM.isBeforeInTranslationUnit(S->getSourceRange().getEnd(),
 ZoneRange.getEnd()))

in which `S` is `nullptr`.


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] D133578: [OpenMP][OMPIRBuilder] Add generation of SIMD align assumptions to OMPIRBuilder

2022-10-05 Thread Dominik Adamski via Phabricator via cfe-commits
domada added inline comments.



Comment at: llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp:2976
 
+  const int DefaultAlignment = 16;
+

jdoerfert wrote:
> domada wrote:
> > jdoerfert wrote:
> > > domada wrote:
> > > > jdoerfert wrote:
> > > > > This doesn't work. Use the data layout for any default values please.
> > > > I have used pointer ABI alignment as the default value. Is it ok?
> > > > Clang has separate method to calculate OpenMP default alignment defined 
> > > > in TargetInfo class ( [[ 
> > > > https://clang.llvm.org/doxygen/classclang_1_1TargetInfo.html#af0c75e3288adc13601732329c44db147
> > > >  |  link ]])
> > > > Unfortunately, there is no simple replacement of this function in 
> > > > OMPIRBuilder or in Flang driver. There are some requests to expose 
> > > > TargetInfo data in Clang-independent manner: [[ 
> > > > https://discourse.llvm.org/t/rfc-targetinfo-library/64342 | RFC1 ]], 
> > > > [[https://discourse.llvm.org/t/complex-to-libm-conversion-abi-issues/65131
> > > >  |RFC2]] , but this issue is not solved.
> > > Let's step back:
> > > 1) User tells us the alignment via `aligned(X:64)`. This should populate 
> > > the map in Clang, I would assume.
> > > 2) User tells us the alignment "implicitly" via `align(Y)`. Again, clang 
> > > should populate the map with the default/preferred alignment of the type. 
> > > You can use the function you linked, or use the data layout API to get 
> > > the preferred alignment.
> > > 3) User tells us nothing. We should pick the default or, don't annotate 
> > > anything. If we go with defaults, you need to look up the default for the 
> > > address space but I don't know why we would annotate anything not 
> > > provided by the user.
> > > 
> > > 
> > Ad 1) Agree
> > Ad 2) OK, I will add assertion to ensure that the map is correctly 
> > populated with the default/preferred alignment if the user specifies only: 
> > `align(Y)`.
> > 
> > I was thinking that OMPIRBuilder should pick the default value if the user 
> > specifies `align(Y)`. Thanks for clarification. 
> > 
> > Ad 3)  I assume that if the user tells us nothing we should not annotate 
> > anything. I will expect empty map and no generated annotations. Currently 
> > we do not generate any annotations if there is no align clause.
> > I was thinking that OMPIRBuilder should pick the default value if the user 
> > specifies align(Y). Thanks for clarification.
> 
> That works with me, but you need the actual type. So the Value is not 
> sufficient, you need `&X and double` to ask DataLayout for the preferred 
> type. For now you can use the clang functionality or pass the type and use DL.
> 
> > I assume that if the user tells us nothing we should not annotate anything. 
> 
> Agreed.
>> I was thinking that OMPIRBuilder should pick the default value if the user 
>> specifies align(Y). Thanks for clarification.
> That works with me, but you need the actual type. So the Value is not 
> sufficient, you need &X and double to ask DataLayout for the preferred type. 
> For now you can use the clang functionality or pass the type and use DL.

I rely on Clang functionality and I assume that the Clang always sets the 
size(default or specified by the user). That's why I added additional `assert` 
to applySimd function  to be sure that Clang always sets the alignment value.

Currently Clang does not use the actual type to calculate the default simd 
alignment: 
https://clang.llvm.org/doxygen/classclang_1_1TargetInfo.html#af0c75e3288adc13601732329c44db147
 . IMO it's better to rely on Clang and it's functionality which is widely 
tested.


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

https://reviews.llvm.org/D133578

___
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-05 Thread Ilya Biryukov via Phabricator via cfe-commits
ilya-biryukov added a comment.

Having `nullptr` inside `children()` seems really weird. Should we fix those 
instead to never produce `nullptr`? Or is this something that is expected (I 
can come up with a few contracts where this would make sense, but that all 
looks really akward).


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] D135258: [SourceManager] Improve getFileIDLoaded.

2022-10-05 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: sammccall.
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.

Similar to getFileIDLocal patch, but for the version for load module.

Test with clangd (building AST with preamble), FileID scans in binary
search is reduced:

SemaExpr.cpp: 142K -> 137K (-3%)
FindTarget.cpp: 368K -> 343K (-6%)


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D135258

Files:
  clang/lib/Basic/SourceManager.cpp


Index: clang/lib/Basic/SourceManager.cpp
===
--- clang/lib/Basic/SourceManager.cpp
+++ clang/lib/Basic/SourceManager.cpp
@@ -863,36 +863,37 @@
   }
 
   // Essentially the same as the local case, but the loaded array is sorted
-  // in the other direction.
+  // in the other direction (decreasing order).
+  // GreaterIndex is the one where the offset is greater, which is actually a
+  // lower index!
+  unsigned GreaterIndex = 0;
+  unsigned LessIndex = LoadedSLocEntryTable.size();
+  if (LastFileIDLookup.ID < 0) {
+// Prune the search space.
+int LastID = LastFileIDLookup.ID;
+if (getLoadedSLocEntryByID(LastID).getOffset() >= SLocOffset)
+  GreaterIndex = (-LastID - 2) + 1;
+else
+  LessIndex = -LastID - 2;
+  }
 
   // First do a linear scan from the last lookup position, if possible.
-  unsigned I;
-  int LastID = LastFileIDLookup.ID;
-  if (LastID >= 0 || getLoadedSLocEntryByID(LastID).getOffset() < SLocOffset)
-I = 0;
-  else
-I = (-LastID - 2) + 1;
-
   unsigned NumProbes;
   bool Invalid = false;
-  for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++I) {
+  for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++GreaterIndex) {
 // Make sure the entry is loaded!
-const SrcMgr::SLocEntry &E = getLoadedSLocEntry(I, &Invalid);
+const SrcMgr::SLocEntry &E = getLoadedSLocEntry(GreaterIndex, &Invalid);
 if (Invalid)
   return FileID(); // invalid entry.
 if (E.getOffset() <= SLocOffset) {
-  FileID Res = FileID::get(-int(I) - 2);
+  FileID Res = FileID::get(-int(GreaterIndex) - 2);
   LastFileIDLookup = Res;
   NumLinearScans += NumProbes + 1;
   return Res;
 }
   }
 
-  // Linear scan failed. Do the binary search. Note the reverse sorting of the
-  // table: GreaterIndex is the one where the offset is greater, which is
-  // actually a lower index!
-  unsigned GreaterIndex = I;
-  unsigned LessIndex = LoadedSLocEntryTable.size();
+  // Linear scan failed. Do the binary search.
   NumProbes = 0;
   while (true) {
 ++NumProbes;


Index: clang/lib/Basic/SourceManager.cpp
===
--- clang/lib/Basic/SourceManager.cpp
+++ clang/lib/Basic/SourceManager.cpp
@@ -863,36 +863,37 @@
   }
 
   // Essentially the same as the local case, but the loaded array is sorted
-  // in the other direction.
+  // in the other direction (decreasing order).
+  // GreaterIndex is the one where the offset is greater, which is actually a
+  // lower index!
+  unsigned GreaterIndex = 0;
+  unsigned LessIndex = LoadedSLocEntryTable.size();
+  if (LastFileIDLookup.ID < 0) {
+// Prune the search space.
+int LastID = LastFileIDLookup.ID;
+if (getLoadedSLocEntryByID(LastID).getOffset() >= SLocOffset)
+  GreaterIndex = (-LastID - 2) + 1;
+else
+  LessIndex = -LastID - 2;
+  }
 
   // First do a linear scan from the last lookup position, if possible.
-  unsigned I;
-  int LastID = LastFileIDLookup.ID;
-  if (LastID >= 0 || getLoadedSLocEntryByID(LastID).getOffset() < SLocOffset)
-I = 0;
-  else
-I = (-LastID - 2) + 1;
-
   unsigned NumProbes;
   bool Invalid = false;
-  for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++I) {
+  for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++GreaterIndex) {
 // Make sure the entry is loaded!
-const SrcMgr::SLocEntry &E = getLoadedSLocEntry(I, &Invalid);
+const SrcMgr::SLocEntry &E = getLoadedSLocEntry(GreaterIndex, &Invalid);
 if (Invalid)
   return FileID(); // invalid entry.
 if (E.getOffset() <= SLocOffset) {
-  FileID Res = FileID::get(-int(I) - 2);
+  FileID Res = FileID::get(-int(GreaterIndex) - 2);
   LastFileIDLookup = Res;
   NumLinearScans += NumProbes + 1;
   return Res;
 }
   }
 
-  // Linear scan failed. Do the binary search. Note the reverse sorting of the
-  // table: GreaterIndex is the one where the offset is greater, which is
-  // actually a lower index!
-  unsigned GreaterIndex = I;
-  unsigned LessIndex = LoadedSLocEntryTable.size();
+  // Linear scan failed. Do the binary search.
   NumProbes = 0;
   while (true) {
 ++NumProbes;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D135224: [Clang][OpenMP] Only check value if the expression is not instantiation dependent

2022-10-05 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/D135224/new/

https://reviews.llvm.org/D135224

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


[PATCH] D135155: [AMDGPU] Annotate the intrinsics to be default and nocallback

2022-10-05 Thread Johannes Doerfert via Phabricator via cfe-commits
jdoerfert updated this revision to Diff 465350.
jdoerfert added a comment.

Last changes


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135155

Files:
  clang/test/CodeGenOpenCL/builtins-amdgcn.cl
  llvm/include/llvm/IR/Intrinsics.td
  llvm/include/llvm/IR/IntrinsicsAMDGPU.td
  llvm/test/Bitcode/compatibility-3.6.ll
  llvm/test/Bitcode/compatibility-3.7.ll
  llvm/test/Bitcode/compatibility-3.8.ll
  llvm/test/Bitcode/compatibility-3.9.ll
  llvm/test/Bitcode/compatibility-4.0.ll
  llvm/test/Bitcode/compatibility-5.0.ll
  llvm/test/Bitcode/compatibility-6.0.ll
  llvm/test/Bitcode/compatibility.ll
  llvm/test/CodeGen/AMDGPU/annotate-kernel-features-hsa-call.ll
  llvm/test/CodeGen/AMDGPU/annotate-kernel-features-hsa.ll
  llvm/test/CodeGen/AMDGPU/annotate-kernel-features.ll
  llvm/test/CodeGen/AMDGPU/pal-simple-indirect-call.ll
  llvm/test/Transforms/Inline/AMDGPU/amdgpu-inline-alloca-argument.ll
  llvm/test/Transforms/OpenMP/barrier_removal.ll

Index: llvm/test/Transforms/OpenMP/barrier_removal.ll
===
--- llvm/test/Transforms/OpenMP/barrier_removal.ll
+++ llvm/test/Transforms/OpenMP/barrier_removal.ll
@@ -249,7 +249,8 @@
 ;.
 ; CHECK: attributes #[[ATTR0:[0-9]+]] = { "llvm.assume"="ompx_aligned_barrier" }
 ; CHECK: attributes #[[ATTR1:[0-9]+]] = { convergent nocallback nounwind }
-; CHECK: attributes #[[ATTR2:[0-9]+]] = { convergent nounwind willreturn }
+; CHECK: attributes #[[ATTR2:[0-9]+]] = { convergent nocallback nounwind willreturn }
+; CHECK: attributes #[[ATTR3:[0-9]+]] = { inaccessiblememonly nocallback nofree nosync nounwind willreturn }
 ;.
 ; CHECK: [[META0:![0-9]+]] = !{i32 7, !"openmp", i32 50}
 ; CHECK: [[META1:![0-9]+]] = !{i32 7, !"openmp-device", i32 50}
Index: llvm/test/Transforms/Inline/AMDGPU/amdgpu-inline-alloca-argument.ll
===
--- llvm/test/Transforms/Inline/AMDGPU/amdgpu-inline-alloca-argument.ll
+++ llvm/test/Transforms/Inline/AMDGPU/amdgpu-inline-alloca-argument.ll
@@ -45,8 +45,7 @@
 ; addrspacecasted' alloca.
 ; CHECK-LABEL: @test_inliner_flat_ptr(
 ; CHECK: call i32 @llvm.amdgcn.workitem.id.x()
-; CHECK-NOT: call
-; CHECK-NOT: call
+; CHECK-NOT: call [[.*]]@
 define amdgpu_kernel void @test_inliner_flat_ptr(float addrspace(1)* nocapture %a, i32 %n) {
 entry:
   %pvt_arr = alloca [64 x float], align 4, addrspace(5)
Index: llvm/test/CodeGen/AMDGPU/pal-simple-indirect-call.ll
===
--- llvm/test/CodeGen/AMDGPU/pal-simple-indirect-call.ll
+++ llvm/test/CodeGen/AMDGPU/pal-simple-indirect-call.ll
@@ -40,7 +40,6 @@
 ; GFX9-NEXT:s_mov_b64 s[2:3], s[10:11]
 ; GFX9-NEXT:s_swappc_b64 s[30:31], s[4:5]
 ; GFX9-NEXT:s_endpgm
-;
 ; GFX10-LABEL: test_simple_indirect_call:
 ; GFX10:   ; %bb.0:
 ; GFX10-NEXT:s_getpc_b64 s[8:9]
@@ -69,8 +68,8 @@
 
 attributes #0 = { nounwind readnone speculatable willreturn }
 ;.
-; AKF_GCN: attributes #[[ATTR0:[0-9]+]] = { nounwind readnone speculatable willreturn }
+; AKF_GCN: attributes #[[ATTR0:[0-9]+]] = { nocallback nofree nosync nounwind readnone speculatable willreturn }
 ;.
 ; ATTRIBUTOR_GCN: attributes #[[ATTR0]] = { "uniform-work-group-size"="false" }
-; ATTRIBUTOR_GCN: attributes #[[ATTR1:[0-9]+]] = { nounwind readnone speculatable willreturn }
+; ATTRIBUTOR_GCN: attributes #[[ATTR1:[0-9]+]] = { nocallback nofree nosync nounwind readnone speculatable willreturn }
 ;.
Index: llvm/test/CodeGen/AMDGPU/annotate-kernel-features.ll
===
--- llvm/test/CodeGen/AMDGPU/annotate-kernel-features.ll
+++ llvm/test/CodeGen/AMDGPU/annotate-kernel-features.ll
@@ -414,10 +414,10 @@
 ; NOHSA: attributes #[[ATTR8]] = { nounwind "amdgpu-work-item-id-y" "amdgpu-work-item-id-z" "uniform-work-group-size"="false" }
 ; NOHSA: attributes #[[ATTR9]] = { nounwind "amdgpu-work-group-id-y" "amdgpu-work-group-id-z" "amdgpu-work-item-id-y" "amdgpu-work-item-id-z" "uniform-work-group-size"="false" }
 ;.
-; AKF_CHECK: attributes #[[ATTR0:[0-9]+]] = { nounwind readnone speculatable willreturn }
+; AKF_CHECK: attributes #[[ATTR0:[0-9]+]] = { nocallback nofree nosync nounwind readnone speculatable willreturn }
 ; AKF_CHECK: attributes #[[ATTR1]] = { nounwind }
 ;.
-; ATTRIBUTOR_CHECK: attributes #[[ATTR0:[0-9]+]] = { nounwind readnone speculatable willreturn }
+; ATTRIBUTOR_CHECK: attributes #[[ATTR0:[0-9]+]] = { nocallback nofree nosync nounwind readnone speculatable willreturn }
 ; ATTRIBUTOR_CHECK: attributes #[[ATTR1]] = { nounwind "amdgpu-no-dispatch-id" "amdgpu-no-dispatch-ptr" "amdgpu-no-heap-ptr" "amdgpu-no-hostcall-ptr" "amdgpu-no-implicitarg-ptr" "amdgpu-no-lds-kernel-id" "amdgpu-no-multigrid-sync-arg" "amdgpu-no-queue-ptr" "amdgpu-no-workgroup-id-x" "amdgpu-no-workgroup-id-y" "amdgpu-no-workgroup-id-z" "amdgpu-no-workitem-id-x" "a

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

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

In D134813#3834938 , @sammccall wrote:

> In D134813#3834776 , @aaron.ballman 
> wrote:
>
>> Thank you for this! I applied D135191  
>> over the top of my changes here and ran the tests to get all the new 
>> failures with the changes, then I reverted those tests which failed back to 
>> their trunk form. When I re-ran the tests, I get the following failures:
>>
>>    TEST 'Clang :: Index/usrs.m' FAILED 
>> 
>>   ...
>>   $ "f:\source\llvm-project\llvm\out\build\x64-debug\bin\filecheck.exe" 
>> "-check-prefix=CHECK-source" "F:\source\llvm-project\clang\test\Index\usrs.m"
>>   # command stderr:
>>   F:\source\llvm-project\clang\test\Index\usrs.m:188:18: error: 
>> CHECK-source: expected string not found in input
>>   // CHECK-source: usrs.m:5:1: EnumDecl=:5:1 (Definition) Extent=[5:1 - 8:2]
>>^
>>   :386:63: note: scanning from here
>>   // CHECK: usrs.m:3:56: DeclRefExpr=y:3:40 Extent=[3:56 - 3:57]
>> ^
>>   :387:89: note: possible intended match here
>>   // CHECK: usrs.m:5:1: EnumDecl=enum (unnamed at 
>> F:\source\llvm-project\clang\test\Index\usrs.m:5:1):5:1 (Definition) 
>> Extent=[5:1 - 8:2]
>
> This isn't a change to USRs, it's a change to libclang's 
> `clang_getCursorSpelling`. I think it's safe to update (unlike the USRs 
> earlier in the file).
> Since this is a general-purpose API it makes sense that it would follow the 
> change in printName() defaults.
>
>>    TEST 'Clang :: ExtractAPI/enum.c' FAILED 
>> 
>>   # command output:
>>   *** 
>> F:\source\llvm-project\llvm\out\build\x64-Debug\tools\clang\test\ExtractAPI\Output\enum.c.tmp/reference.output.json
>>   --- 
>> F:\source\llvm-project\llvm\out\build\x64-Debug\tools\clang\test\ExtractAPI\Output\enum.c.tmp/output-normalized.json
>>   ***
>>   *** 655,667 
>> "navigator": [
>>   {
>> "kind": "identifier",
>>   ! "spelling": "(anonymous)"
>>   !   }
>>   ! ],
>>   ! "title": "(anonymous)"
>>   !   },
>>   !   "pathComponents": [
>>   ! "(anonymous)"
>>   ]
>> },
>> {
>>   --- 655,667 
>> "navigator": [
>>   {
>> "kind": "identifier",
>>   ! "spelling": "enum (unnamed at 
>> F:\\source\\llvm-project\\llvm\\out\\build\\x64-Debug\\tools\\clang\\test\\ExtractAPI\\Output\\enum.c.tmp/input.h:17:1)"
>>   !   }
>>   ! ],
>>   ! "title": "enum (unnamed at 
>> F:\\source\\llvm-project\\llvm\\out\\build\\x64-Debug\\tools\\clang\\test\\ExtractAPI\\Output\\enum.c.tmp/input.h:17:1)"
>>   !   },
>>   !   "pathComponents": [
>>   ! "enum (unnamed at 
>> F:\\source\\llvm-project\\llvm\\out\\build\\x64-Debug\\tools\\clang\\test\\ExtractAPI\\Output\\enum.c.tmp/input.h:17:1)"
>>   ]
>> },
>>   ...
>
> ExtractAPI seems to produce a data description of the AST for programmatic 
> consumption (apple swift interop?), this looks like a breaking change to me.
> It looks like they have at least one explicit check similar to USRs in 
> clang/lib/ExtractAPI/ExtractAPIConsumer.cpp:361, but I know very little about 
> how this tool is used out-of-tree by Apple: I'm not sure how much the exact 
> strings/lack of strings matters, may need owners of that tool involved here.
>
>>    TEST 'Clang :: Index/annotate-comments-typedef.m' 
>> FAILED 
>
> I can't see the actual output of the tool in that log, but I guess this is 
> related to clang/lib/Index/CommentToXML.cpp:908.
> I don't know if reporting exactly `` is important behavior that 
> should be preserved, or `(unnamed)` would be fine. I don't even know what 
> CommentToXML is: again I guess it's consumed by something related to XCode 
> out-of-tree.
>
>> and also the clangd unit tests failed:
>>
>>   [--] 1 test from FindExplicitReferencesTest
>>   [ RUN  ] FindExplicitReferencesTest.All
>>   ...
>>   With diff:
>>   @@ -1,3 +1,3 @@
>>   -0: targets = {}
>>   +0: targets = {(unnamed)}
>>1: targets = {x}, decl
>>2: targets = {fptr}, decl
>>   
>>   
>>void foo() {
>> $0^class {} $1^x;
>> int (*$2^fptr)(int $3^a, int) = nullptr;
>>}
>
> Yes, this is expected: the test identifies which target is referenced by 
> name, and we changed the name from "" to "(unnamed)".
> This patch can change the test data on 
> clang-tools-extra/clangd/unittests/FindTargetTests.cpp:1619 from `targets = 
> {}` to `targets={(unnamed)}`.

Thank you for the extra analysis! In terms of next steps, do you think I should 
roll your changes into this review and adjust the tests acco

[PATCH] D134456: [PGO] Consider parent context when weighing branches with likelyhood.

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

I'm not comfortable giving the final LG but the changes here look reasonable to 
me.




Comment at: clang/lib/CodeGen/CGStmt.cpp:829-831
+  CGM.getCodeGenOpts().OptimizationLevel) {
 LH = Stmt::getLikelihood(S.getThen(), S.getElse());
+  }

You can drop the braces here per the coding standard.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134456

___
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-05 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added reviewers: shafik, erichkeane, tbaeder.
aaron.ballman added a comment.

Adding a few more reviewers who have been poking around in constant expression 
evaluation lately.




Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:2722-2723
   InGroup, DefaultIgnore;
+def err_constexpr_body_invalid_omp_simd_stmt_with_clauses : Error<
+  "OpenMP simd statement with clauses not allowed in 
%select{constexpr|consteval}1 %select{function|constructor}0">;
 def ext_constexpr_type_definition : ExtWarn<

You should manually re-flow this to the usual 80-col limit.



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)).

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?



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();

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.


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] D134617: [HLSL] Support register binding attribute on global variable

2022-10-05 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman accepted this revision.
aaron.ballman 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/D134617/new/

https://reviews.llvm.org/D134617

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


[PATCH] D135254: [clang][Sema] Fix crash on invalid base destructor

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

looks good, Sema::LookupDefaultConstructor already does the similar thing as 
well.




Comment at: clang/lib/Sema/SemaDeclCXX.cpp:5699
 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
-assert(Dtor && "No dtor found for BaseClassDecl!");
+// Dtor might still be missing, e.g because it's invalid.
+if (!Dtor)

I think we should do similar change on L5699, L5736 as well.



Comment at: clang/lib/Sema/SemaLookup.cpp:3620
 CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
-  return cast(LookupSpecialMember(Class, CXXDestructor,
- false, false, false,
- false, 
false).getMethod());
+  return llvm::cast_or_null(
+  LookupSpecialMember(Class, CXXDestructor, false, false, false, false,

nit: the prefix `llvm::` can be eliminated.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135254

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


[PATCH] D133578: [OpenMP][OMPIRBuilder] Add generation of SIMD align assumptions to OMPIRBuilder

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



Comment at: clang/lib/CodeGen/CGStmtOpenMP.cpp:2640
   if (UseOMPIRBuilder) {
+llvm::DenseMap AlignedVars;
 // Emit the associated statement and get its loop representation.

Where is this map populated?



Comment at: llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h:621
+  /// \param LoopThe loop to simd-ize.
+  /// \param AlignedVars The map of the variables which need to aligned with.
+  /// \param IfCond  The value which corresponds to the if clause

> The map of the variables which need to aligned with.

This reads weird. Can you rephrase



Comment at: llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp:3033
+   "Value which needs to be aligned must represented by alloca "
+   "instruction");
+assert(AlignedItem.second &&

Why use Value as type and then assert it's an Alloca? Use a map with Alloca as 
key.



Comment at: llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp:3037
+Value *AlignPtrInstruction = nullptr;
+AllocaInst *AllocaInstruction = dyn_cast(AlignedItem.first);
+Builder.SetInsertPoint(CanonicalLoop->getPreheader()->getTerminator());

This won't be necessary once you change the type but as a hint, `cast` is the 
right choice after an `isa`.



Comment at: llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp:3049
+assert(AlignPtrInstruction &&
+   "Aligned variables must be either pointer or array type");
+

Is Alloca of an array tested? I would not have assumed two different paths 
here. GEP on the alloca makes an assumption about the alloca, load of the 
alloca makes an assumption about the allocated type. If anything, this 
distinction should be based on the "isArray" property, not the allocated type. 
I mean, `alloca i32, 4` and `alloca [4xi32]` are different beasts. I fear we 
apply the handling of the former to the latter but I didn't check.



Comment at: llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp:2976
 
+  const int DefaultAlignment = 16;
+

domada wrote:
> jdoerfert wrote:
> > domada wrote:
> > > jdoerfert wrote:
> > > > domada wrote:
> > > > > jdoerfert wrote:
> > > > > > This doesn't work. Use the data layout for any default values 
> > > > > > please.
> > > > > I have used pointer ABI alignment as the default value. Is it ok?
> > > > > Clang has separate method to calculate OpenMP default alignment 
> > > > > defined in TargetInfo class ( [[ 
> > > > > https://clang.llvm.org/doxygen/classclang_1_1TargetInfo.html#af0c75e3288adc13601732329c44db147
> > > > >  |  link ]])
> > > > > Unfortunately, there is no simple replacement of this function in 
> > > > > OMPIRBuilder or in Flang driver. There are some requests to expose 
> > > > > TargetInfo data in Clang-independent manner: [[ 
> > > > > https://discourse.llvm.org/t/rfc-targetinfo-library/64342 | RFC1 ]], 
> > > > > [[https://discourse.llvm.org/t/complex-to-libm-conversion-abi-issues/65131
> > > > >  |RFC2]] , but this issue is not solved.
> > > > Let's step back:
> > > > 1) User tells us the alignment via `aligned(X:64)`. This should 
> > > > populate the map in Clang, I would assume.
> > > > 2) User tells us the alignment "implicitly" via `align(Y)`. Again, 
> > > > clang should populate the map with the default/preferred alignment of 
> > > > the type. You can use the function you linked, or use the data layout 
> > > > API to get the preferred alignment.
> > > > 3) User tells us nothing. We should pick the default or, don't annotate 
> > > > anything. If we go with defaults, you need to look up the default for 
> > > > the address space but I don't know why we would annotate anything not 
> > > > provided by the user.
> > > > 
> > > > 
> > > Ad 1) Agree
> > > Ad 2) OK, I will add assertion to ensure that the map is correctly 
> > > populated with the default/preferred alignment if the user specifies 
> > > only: `align(Y)`.
> > > 
> > > I was thinking that OMPIRBuilder should pick the default value if the 
> > > user specifies `align(Y)`. Thanks for clarification. 
> > > 
> > > Ad 3)  I assume that if the user tells us nothing we should not annotate 
> > > anything. I will expect empty map and no generated annotations. Currently 
> > > we do not generate any annotations if there is no align clause.
> > > I was thinking that OMPIRBuilder should pick the default value if the 
> > > user specifies align(Y). Thanks for clarification.
> > 
> > That works with me, but you need the actual type. So the Value is not 
> > sufficient, you need `&X and double` to ask DataLayout for the preferred 
> > type. For now you can use the clang functionality or pass the type and use 
> > DL.
> > 
> > > I assume that if the user tells us nothing we should not annotate 
> > > anything. 
> > 
> > Agreed.
> >> I was thinking that OMPIRBuilder should pick the default value if the 

[PATCH] D127910: [Clang][AArch64] Add SME C intrinsics for load and store

2022-10-05 Thread David Sherwood via Phabricator via cfe-commits
david-arm added a comment.

Hi @sagarkulkarni19, thank you for working on the ACLE builtins for SME! I've 
had a look through and I have a few comments, mostly around how the code is 
structured. It would be good if you could try to separate SVE from SME in this 
implementation, in the same way that NEON and SVE are distinct. It's possible 
to do this whilst reusing much of the code in SveEmitter.cpp.




Comment at: clang/include/clang/Basic/arm_sve.td:210
+def IsSME : FlagType<0x8>;
+def IsSMELd1  : FlagType<0x10>;
+def IsSMESt1  : FlagType<0x20>;

We don't need these new flags 'IsSMELd1' and 'IsSMESt1'. Please can you reuse 
the existing `IsLoad` and `IsStore` flags?



Comment at: clang/include/clang/Basic/arm_sve.td:549
 
+def SVLD1_HOR_ZA8 : MInst<"svld1_hor_za8", "vimiPQ", "", [IsOverloadNone, 
IsSME, IsSMELd1], MemEltTyDefault, "aarch64_sme_ld1b_horiz">;
+def SVLD1_HOR_ZA16 : MInst<"svld1_hor_za16", "vimiPQ", "", [IsOverloadNone, 
IsSME, IsSMELd1], MemEltTyDefault, "aarch64_sme_ld1h_horiz">;

SME is really a distinct architecture and so I think it should live in it's own 
arm_sme.td file in the same way that we have arm_neon.td and arm_sve.td. It's 
possible to do this and still reuse the SveEmitter.cpp code. If you look at 
SveEmitter.cpp you'll see these functions:

  void EmitSveHeader(RecordKeeper &Records, raw_ostream &OS) {
SVEEmitter(Records).createHeader(OS);
  }

  void EmitSveBuiltins(RecordKeeper &Records, raw_ostream &OS) {
SVEEmitter(Records).createBuiltins(OS);
  }

  void EmitSveBuiltinCG(RecordKeeper &Records, raw_ostream &OS) {
SVEEmitter(Records).createCodeGenMap(OS);
  }

  void EmitSveRangeChecks(RecordKeeper &Records, raw_ostream &OS) {
SVEEmitter(Records).createRangeChecks(OS);
  }

It would be good to add similar ones for SME, i.e. `EmitSmeRangeChecks`, etc.



Comment at: clang/include/clang/Basic/arm_sve.td:209
 def IsTupleSet: FlagType<0x4>;
+def IsSME : FlagType<0x8>;
+def IsSMELoadStore: FlagType<0x10>;

sagarkulkarni19 wrote:
> sdesmalen wrote:
> > Is there value in having both `IsSME` and `IsSMELoadStore`?
> `IsSME` flag is checked in the SveEmitter.cpp : createSMEHeader(...) to 
> generate arm_sme.h with only the SME intrinsics, whereas `IsSMELoadStore` is 
> used to correctly CodeGen (CGBuiltins.cpp) load and store intrinsics. 
You don't need the `IsSME` flag either because in 
`CodeGenFunction::EmitAArch64BuiltinExpr` you can do exactly the same thing as 
SVE, i.e. something like

  if (BuiltinID >= AArch64::FirstSMEBuiltin &&
  BuiltinID <= AArch64::LastSMEBuiltin)
return EmitAArch64SMEBuiltinExpr(BuiltinID, E);



Comment at: clang/lib/CodeGen/CGBuiltin.cpp:9230
 return EmitSVEMaskedStore(E, Ops, Builtin->LLVMIntrinsic);
+  else if (TypeFlags.isSMELd1() || TypeFlags.isSMESt1())
+return EmitSMELd1St1(TypeFlags, Ops, Builtin->LLVMIntrinsic);

I would prefer this to be handled inside it's own `EmitAArch64SMEBuiltinExpr`, 
since it's a separate architecture.



Comment at: clang/utils/TableGen/SveEmitter.cpp:867
+if (this->Flags & Emitter.getEnumValueForFlag("IsSMELd1"))
+  this->SMEAttributes = "arm_streaming, arm_shared_za";
+else if (this->Flags & Emitter.getEnumValueForFlag("IsSMESt1"))

I would prefer this to be done more precisely via separate attribute flags, 
i.e. in the .td file decorate each ACLE builtin with something like `IsShared`, 
`IsStreaming`, `IsStreamingCompatible`, etc. otherwise you'll end up needing 
loads of flags for all different possible combinations. That way you can do:

  if (this->Flags & Emitter.getEnumValueForFlag("IsStreaming"))
this->SMEAttributes += "arm_streaming";

etc.



Comment at: clang/utils/TableGen/SveEmitter.cpp:1042
 
+  bool SMEFlag = Flags & getEnumValueForFlag("IsSME");
+  if (SMEFlag != IsSME)

If you move the builtins to their own file in arm_sme.td and emit the records 
using interfaces like EmitSmeBuiltins, etc. then you already know they are SME 
builtins and so don't need the flag.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D127910

___
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-05 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:
> 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. 



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();

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.



Comment at: clang/lib/Sema/SemaDeclCXX.cpp:2202
 << isa(Dcl) << Dcl->isConsteval();
   }
   return false;

^ here


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] D135254: [clang][Sema] Fix crash on invalid base destructor

2022-10-05 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet updated this revision to Diff 465365.
kadircet marked 2 inline comments as done.
kadircet added a comment.

-address comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135254

Files:
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaLookup.cpp
  clang/test/SemaCXX/destructor.cpp


Index: clang/test/SemaCXX/destructor.cpp
===
--- clang/test/SemaCXX/destructor.cpp
+++ clang/test/SemaCXX/destructor.cpp
@@ -550,4 +550,20 @@
   template void f(T *p) { p->~U(); } // expected-error 
{{ambiguous}}
 }
 
+namespace crash_on_invalid_base_dtor {
+struct Test {
+  virtual ~Test();
+};
+struct Baz : public Test { // expected-warning {{non-virtual destructor}}
+  Baz() {}
+  ~Baz() = defaul; // expected-error {{undeclared identifier 'defaul'}} \
+   // expected-error {{initializer on function}} \
+   // expected-note {{overridden virtual function is here}}
+};
+struct Foo : public Baz { // expected-error {{cannot override a non-deleted 
function}} \
+  // expected-note {{destructor of 'Foo' is implicitly 
deleted}}
+  Foo() {}
+};
+}
+
 #endif // BE_THE_HEADER
Index: clang/lib/Sema/SemaLookup.cpp
===
--- clang/lib/Sema/SemaLookup.cpp
+++ clang/lib/Sema/SemaLookup.cpp
@@ -40,6 +40,7 @@
 #include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/TinyPtrVector.h"
 #include "llvm/ADT/edit_distance.h"
+#include "llvm/Support/Casting.h"
 #include "llvm/Support/ErrorHandling.h"
 #include 
 #include 
@@ -3616,9 +3617,10 @@
 ///
 /// \returns The destructor for this class.
 CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
-  return cast(LookupSpecialMember(Class, CXXDestructor,
- false, false, false,
- false, 
false).getMethod());
+  return cast_or_null(
+  LookupSpecialMember(Class, CXXDestructor, false, false, false, false,
+  false)
+  .getMethod());
 }
 
 /// LookupLiteralOperator - Determine which literal operator should be used for
Index: clang/lib/Sema/SemaDeclCXX.cpp
===
--- clang/lib/Sema/SemaDeclCXX.cpp
+++ clang/lib/Sema/SemaDeclCXX.cpp
@@ -17,6 +17,7 @@
 #include "clang/AST/CXXInheritance.h"
 #include "clang/AST/CharUnits.h"
 #include "clang/AST/ComparisonCategories.h"
+#include "clang/AST/DeclCXX.h"
 #include "clang/AST/DeclTemplate.h"
 #include "clang/AST/EvaluatedExprVisitor.h"
 #include "clang/AST/ExprCXX.h"
@@ -5650,7 +5651,9 @@
   continue;
 
 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
-assert(Dtor && "No dtor found for FieldClassDecl!");
+// Dtor might still be missing, e.g because it's invalid.
+if (!Dtor)
+  continue;
 CheckDestructorAccess(Field->getLocation(), Dtor,
   PDiag(diag::err_access_dtor_field)
 << Field->getDeclName()
@@ -5696,7 +5699,9 @@
   continue;
 
 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
-assert(Dtor && "No dtor found for BaseClassDecl!");
+// Dtor might still be missing, e.g because it's invalid.
+if (!Dtor)
+  continue;
 
 // FIXME: caret should be on the start of the class name
 CheckDestructorAccess(Base.getBeginLoc(), Dtor,
@@ -5733,7 +5738,9 @@
   continue;
 
 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
-assert(Dtor && "No dtor found for BaseClassDecl!");
+// Dtor might still be missing, e.g because it's invalid.
+if (!Dtor)
+  continue;
 if (CheckDestructorAccess(
 ClassDecl->getLocation(), Dtor,
 PDiag(diag::err_access_dtor_vbase)


Index: clang/test/SemaCXX/destructor.cpp
===
--- clang/test/SemaCXX/destructor.cpp
+++ clang/test/SemaCXX/destructor.cpp
@@ -550,4 +550,20 @@
   template void f(T *p) { p->~U(); } // expected-error {{ambiguous}}
 }
 
+namespace crash_on_invalid_base_dtor {
+struct Test {
+  virtual ~Test();
+};
+struct Baz : public Test { // expected-warning {{non-virtual destructor}}
+  Baz() {}
+  ~Baz() = defaul; // expected-error {{undeclared identifier 'defaul'}} \
+   // expected-error {{initializer on function}} \
+   // expected-note {{overridden virtual function is here}}
+};
+struct Foo : public Baz { // expected-error {{cannot override a non-deleted function}} \
+  // expected-note {{destructor of 'Foo' is implicitly deleted}}
+  Foo() {}
+};
+}
+
 #endif // BE_THE_HEADER
Index: clang/lib/Sema/SemaLookup.cpp
===
--- clang/lib/Sema/SemaLookup.cpp
+++ clang/lib/Sema/SemaLooku

[PATCH] D135254: [clang][Sema] Fix crash on invalid base destructor

2022-10-05 Thread Kadir Cetinkaya 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 rGadab08ecf2bd: [clang][Sema] Fix crash on invalid base 
destructor (authored by kadircet).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135254

Files:
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaLookup.cpp
  clang/test/SemaCXX/destructor.cpp


Index: clang/test/SemaCXX/destructor.cpp
===
--- clang/test/SemaCXX/destructor.cpp
+++ clang/test/SemaCXX/destructor.cpp
@@ -550,4 +550,20 @@
   template void f(T *p) { p->~U(); } // expected-error 
{{ambiguous}}
 }
 
+namespace crash_on_invalid_base_dtor {
+struct Test {
+  virtual ~Test();
+};
+struct Baz : public Test { // expected-warning {{non-virtual destructor}}
+  Baz() {}
+  ~Baz() = defaul; // expected-error {{undeclared identifier 'defaul'}} \
+   // expected-error {{initializer on function}} \
+   // expected-note {{overridden virtual function is here}}
+};
+struct Foo : public Baz { // expected-error {{cannot override a non-deleted 
function}} \
+  // expected-note {{destructor of 'Foo' is implicitly 
deleted}}
+  Foo() {}
+};
+}
+
 #endif // BE_THE_HEADER
Index: clang/lib/Sema/SemaLookup.cpp
===
--- clang/lib/Sema/SemaLookup.cpp
+++ clang/lib/Sema/SemaLookup.cpp
@@ -40,6 +40,7 @@
 #include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/TinyPtrVector.h"
 #include "llvm/ADT/edit_distance.h"
+#include "llvm/Support/Casting.h"
 #include "llvm/Support/ErrorHandling.h"
 #include 
 #include 
@@ -3616,9 +3617,10 @@
 ///
 /// \returns The destructor for this class.
 CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
-  return cast(LookupSpecialMember(Class, CXXDestructor,
- false, false, false,
- false, 
false).getMethod());
+  return cast_or_null(
+  LookupSpecialMember(Class, CXXDestructor, false, false, false, false,
+  false)
+  .getMethod());
 }
 
 /// LookupLiteralOperator - Determine which literal operator should be used for
Index: clang/lib/Sema/SemaDeclCXX.cpp
===
--- clang/lib/Sema/SemaDeclCXX.cpp
+++ clang/lib/Sema/SemaDeclCXX.cpp
@@ -17,6 +17,7 @@
 #include "clang/AST/CXXInheritance.h"
 #include "clang/AST/CharUnits.h"
 #include "clang/AST/ComparisonCategories.h"
+#include "clang/AST/DeclCXX.h"
 #include "clang/AST/DeclTemplate.h"
 #include "clang/AST/EvaluatedExprVisitor.h"
 #include "clang/AST/ExprCXX.h"
@@ -5650,7 +5651,9 @@
   continue;
 
 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
-assert(Dtor && "No dtor found for FieldClassDecl!");
+// Dtor might still be missing, e.g because it's invalid.
+if (!Dtor)
+  continue;
 CheckDestructorAccess(Field->getLocation(), Dtor,
   PDiag(diag::err_access_dtor_field)
 << Field->getDeclName()
@@ -5696,7 +5699,9 @@
   continue;
 
 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
-assert(Dtor && "No dtor found for BaseClassDecl!");
+// Dtor might still be missing, e.g because it's invalid.
+if (!Dtor)
+  continue;
 
 // FIXME: caret should be on the start of the class name
 CheckDestructorAccess(Base.getBeginLoc(), Dtor,
@@ -5733,7 +5738,9 @@
   continue;
 
 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
-assert(Dtor && "No dtor found for BaseClassDecl!");
+// Dtor might still be missing, e.g because it's invalid.
+if (!Dtor)
+  continue;
 if (CheckDestructorAccess(
 ClassDecl->getLocation(), Dtor,
 PDiag(diag::err_access_dtor_vbase)


Index: clang/test/SemaCXX/destructor.cpp
===
--- clang/test/SemaCXX/destructor.cpp
+++ clang/test/SemaCXX/destructor.cpp
@@ -550,4 +550,20 @@
   template void f(T *p) { p->~U(); } // expected-error {{ambiguous}}
 }
 
+namespace crash_on_invalid_base_dtor {
+struct Test {
+  virtual ~Test();
+};
+struct Baz : public Test { // expected-warning {{non-virtual destructor}}
+  Baz() {}
+  ~Baz() = defaul; // expected-error {{undeclared identifier 'defaul'}} \
+   // expected-error {{initializer on function}} \
+   // expected-note {{overridden virtual function is here}}
+};
+struct Foo : public Baz { // expected-error {{cannot override a non-deleted function}} \
+  // expected-note {{destructor of 'Foo' is implicitly deleted}}
+  Foo() {}
+};
+}
+
 #endif // BE_THE_HEADER
Index: clang/lib/Sema/SemaLookup.cpp
===

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

2022-10-05 Thread Haojian Wu via Phabricator via cfe-commits
hokein added a comment.

In D135257#3836511 , @ilya-biryukov 
wrote:

> Having `nullptr` inside `children()` seems really weird. Should we fix those 
> instead to never produce `nullptr`? Or is this something that is expected (I 
> can come up with a few contracts where this would make sense, but that all 
> looks really akward).

I'm not too surprised to see this, given the code action is widely triggered 
(on broken code). It would be nice that clang never produce a nullptr, but 
we're not in a perfect world. And there are other places (e.g. 
)
 in the code base doing this nullptr check. So to me, this patch is an 
improvement making clangd more robust, it looks good from my side.


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] D129156: Add -fpass-plugin option to Flang

2022-10-05 Thread Tarun Prabhu via Phabricator via cfe-commits
tarunprabhu added a comment.

I think there is a typo somehow. It should be "Bye.so". Not sure how that 
happened. I'm looking into this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129156

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


[PATCH] D135191: [Index] USRGeneration doesn't depend on unnamed.printName() => ''. NFC

2022-10-05 Thread Sam McCall via Phabricator via cfe-commits
This revision was not accepted when it landed; it landed in state "Needs 
Review".
This revision was automatically updated to reflect the committed changes.
Closed by commit rG20c9ac292504: [Index] USRGeneration doesn't depend on 
unnamed.printName() => ''. NFC (authored by sammccall).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135191

Files:
  clang/lib/Index/USRGeneration.cpp


Index: clang/lib/Index/USRGeneration.cpp
===
--- clang/lib/Index/USRGeneration.cpp
+++ clang/lib/Index/USRGeneration.cpp
@@ -179,10 +179,11 @@
 
//===--===//
 
 bool USRGenerator::EmitDeclName(const NamedDecl *D) {
-  const unsigned startSize = Buf.size();
-  D->printName(Out);
-  const unsigned endSize = Buf.size();
-  return startSize == endSize;
+  DeclarationName N = D->getDeclName();
+  if (N.isEmpty())
+return true;
+  Out << N;
+  return false;
 }
 
 bool USRGenerator::ShouldGenerateLocation(const NamedDecl *D) {


Index: clang/lib/Index/USRGeneration.cpp
===
--- clang/lib/Index/USRGeneration.cpp
+++ clang/lib/Index/USRGeneration.cpp
@@ -179,10 +179,11 @@
 //===--===//
 
 bool USRGenerator::EmitDeclName(const NamedDecl *D) {
-  const unsigned startSize = Buf.size();
-  D->printName(Out);
-  const unsigned endSize = Buf.size();
-  return startSize == endSize;
+  DeclarationName N = D->getDeclName();
+  if (N.isEmpty())
+return true;
+  Out << N;
+  return false;
 }
 
 bool USRGenerator::ShouldGenerateLocation(const NamedDecl *D) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] adab08e - [clang][Sema] Fix crash on invalid base destructor

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

Author: Kadir Cetinkaya
Date: 2022-10-05T15:23:15+02:00
New Revision: adab08ecf2bdeb84dc7d2009d4c0c13617db9c58

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

LOG: [clang][Sema] Fix crash on invalid base destructor

LookupSpecialMember might fail, so changes the cast to cast_or_null.
Inside Sema, skip a particular base, similar to other cases, rather than
asserting on dtor showing up.

Other option would be to mark classes with invalid destructors as invalid, but
that seems like a lot more invasive and we do lose lots of diagnostics that
currently work on classes with broken members.

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

Added: 


Modified: 
clang/lib/Sema/SemaDeclCXX.cpp
clang/lib/Sema/SemaLookup.cpp
clang/test/SemaCXX/destructor.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 5cc5dc1c449a6..a490f1e59dd10 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -17,6 +17,7 @@
 #include "clang/AST/CXXInheritance.h"
 #include "clang/AST/CharUnits.h"
 #include "clang/AST/ComparisonCategories.h"
+#include "clang/AST/DeclCXX.h"
 #include "clang/AST/DeclTemplate.h"
 #include "clang/AST/EvaluatedExprVisitor.h"
 #include "clang/AST/ExprCXX.h"
@@ -5650,7 +5651,9 @@ 
Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
   continue;
 
 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
-assert(Dtor && "No dtor found for FieldClassDecl!");
+// Dtor might still be missing, e.g because it's invalid.
+if (!Dtor)
+  continue;
 CheckDestructorAccess(Field->getLocation(), Dtor,
   PDiag(diag::err_access_dtor_field)
 << Field->getDeclName()
@@ -5696,7 +5699,9 @@ 
Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
   continue;
 
 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
-assert(Dtor && "No dtor found for BaseClassDecl!");
+// Dtor might still be missing, e.g because it's invalid.
+if (!Dtor)
+  continue;
 
 // FIXME: caret should be on the start of the class name
 CheckDestructorAccess(Base.getBeginLoc(), Dtor,
@@ -5733,7 +5738,9 @@ void Sema::MarkVirtualBaseDestructorsReferenced(
   continue;
 
 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
-assert(Dtor && "No dtor found for BaseClassDecl!");
+// Dtor might still be missing, e.g because it's invalid.
+if (!Dtor)
+  continue;
 if (CheckDestructorAccess(
 ClassDecl->getLocation(), Dtor,
 PDiag(diag::err_access_dtor_vbase)

diff  --git a/clang/lib/Sema/SemaLookup.cpp b/clang/lib/Sema/SemaLookup.cpp
index 70d0ce0baae06..a144cb40b7abc 100644
--- a/clang/lib/Sema/SemaLookup.cpp
+++ b/clang/lib/Sema/SemaLookup.cpp
@@ -40,6 +40,7 @@
 #include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/TinyPtrVector.h"
 #include "llvm/ADT/edit_distance.h"
+#include "llvm/Support/Casting.h"
 #include "llvm/Support/ErrorHandling.h"
 #include 
 #include 
@@ -3616,9 +3617,10 @@ CXXMethodDecl 
*Sema::LookupMovingAssignment(CXXRecordDecl *Class,
 ///
 /// \returns The destructor for this class.
 CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
-  return cast(LookupSpecialMember(Class, CXXDestructor,
- false, false, false,
- false, 
false).getMethod());
+  return cast_or_null(
+  LookupSpecialMember(Class, CXXDestructor, false, false, false, false,
+  false)
+  .getMethod());
 }
 
 /// LookupLiteralOperator - Determine which literal operator should be used for

diff  --git a/clang/test/SemaCXX/destructor.cpp 
b/clang/test/SemaCXX/destructor.cpp
index 040d13ed99143..971cea621e865 100644
--- a/clang/test/SemaCXX/destructor.cpp
+++ b/clang/test/SemaCXX/destructor.cpp
@@ -550,4 +550,20 @@ namespace PR44978 {
   template void f(T *p) { p->~U(); } // expected-error 
{{ambiguous}}
 }
 
+namespace crash_on_invalid_base_dtor {
+struct Test {
+  virtual ~Test();
+};
+struct Baz : public Test { // expected-warning {{non-virtual destructor}}
+  Baz() {}
+  ~Baz() = defaul; // expected-error {{undeclared identifier 'defaul'}} \
+   // expected-error {{initializer on function}} \
+   // expected-note {{overridden virtual function is here}}
+};
+struct Foo : public Baz { // expected-error {{cannot override a non-deleted 
function}} \
+  // expected-note {{destructor of 'Foo' is implicitly 
deleted}}
+  Foo() {}
+};
+}
+
 #endif // BE_THE_HEADER



___
cfe-commits mailing list
cfe-commi

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

2022-10-05 Thread Sam McCall via Phabricator via cfe-commits
sammccall added a comment.

I just landed that change to USR generation as 
20c9ac29250493f5e0a3791dc1e5e9114ff0dc6e 
, so there 
should now be no USR changes (just some changes to debug representations that 
happen to be in some of the USR test files, which can be updated).

I'd guess we need some kind of change to CommentXML and ExtractAPI, but I don't 
know enough to be sure what it should be.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134813

___
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-05 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added subscribers: zixuw, dexonsmith, gribozavr.
aaron.ballman added a comment.

In D134813#3836826 , @sammccall wrote:

> I just landed that change to USR generation as 
> 20c9ac29250493f5e0a3791dc1e5e9114ff0dc6e 
> , so 
> there should now be no USR changes (just some changes to debug 
> representations that happen to be in some of the USR test files, which can be 
> updated).

Thank you!

> I'd guess we need some kind of change to CommentXML and ExtractAPI, but I 
> don't know enough to be sure what it should be.

Ping @dang @zixuw and @dexonsmith for questions about how to handle ExtractAPI 
changes, and @gribozavr for questions about CommentXML


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134813

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


[PATCH] D129156: Add -fpass-plugin option to Flang

2022-10-05 Thread Valentin Clement via Phabricator via cfe-commits
clementval added a comment.

In D129156#3836768 , @tarunprabhu 
wrote:

> I think there is a typo somehow. It should be "Bye.so". Not sure how that 
> happened. I'm looking into this.

I probably didn't copy the error correctly .. this is the correct libs that is 
not found `llvm-project/build/lib/Bye.so`


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129156

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


[PATCH] D134878: Update developer policy on potentially breaking changes

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

Pinging reviewers from projects other than libcxx (I'm hoping to get buy-in 
from someone on the LLVM side of things; lldb would be nice as well).


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

https://reviews.llvm.org/D134878

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


[PATCH] D135258: [SourceManager] Improve getFileIDLoaded.

2022-10-05 Thread Sam McCall via Phabricator via cfe-commits
sammccall accepted this revision.
sammccall added a comment.
This revision is now accepted and ready to land.

Nice!

Just a couple of comments where we could take the opportunity to clarify the 
existing code. Optional.




Comment at: clang/lib/Basic/SourceManager.cpp:874
+int LastID = LastFileIDLookup.ID;
+if (getLoadedSLocEntryByID(LastID).getOffset() >= SLocOffset)
+  GreaterIndex = (-LastID - 2) + 1;

This is confusing: if SLocEntry.getOffset() > SLocOffset then it means 
SLocOffset is *not* part the entry (entry can be pruned), but if they're equal 
it means it *is* part of the entry (entry should not be pruned).
Then we're pruning the entry regardless.

I think we're getting away with this because we never get here in the `==` case 
as we would have hit the cache.
But `>` seems clearer than `>=`, assuming my analysis is right.



Comment at: clang/lib/Basic/SourceManager.cpp:875
+if (getLoadedSLocEntryByID(LastID).getOffset() >= SLocOffset)
+  GreaterIndex = (-LastID - 2) + 1;
+else

I believe the `+1` here is in order to exclude `LastFileIDLookup.ID`, and again 
the justification is that we would otherwise have hit the cache.

I think a short comment `// Exclude LastID, else we would have hit the cache` 
would help here


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135258

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


[clang] 20c9ac2 - [Index] USRGeneration doesn't depend on unnamed.printName() => ''. NFC

2022-10-05 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2022-10-05T15:51:00+02:00
New Revision: 20c9ac29250493f5e0a3791dc1e5e9114ff0dc6e

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

LOG: [Index] USRGeneration doesn't depend on unnamed.printName() => ''. NFC

This prepares for printName() to print `(anonymous struct)` etc in D134813.

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

Added: 


Modified: 
clang/lib/Index/USRGeneration.cpp

Removed: 




diff  --git a/clang/lib/Index/USRGeneration.cpp 
b/clang/lib/Index/USRGeneration.cpp
index c1120058235c6..e804abe2de50f 100644
--- a/clang/lib/Index/USRGeneration.cpp
+++ b/clang/lib/Index/USRGeneration.cpp
@@ -179,10 +179,11 @@ class USRGenerator : public 
ConstDeclVisitor {
 
//===--===//
 
 bool USRGenerator::EmitDeclName(const NamedDecl *D) {
-  const unsigned startSize = Buf.size();
-  D->printName(Out);
-  const unsigned endSize = Buf.size();
-  return startSize == endSize;
+  DeclarationName N = D->getDeclName();
+  if (N.isEmpty())
+return true;
+  Out << N;
+  return false;
 }
 
 bool USRGenerator::ShouldGenerateLocation(const NamedDecl *D) {



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


[clang-tools-extra] 0a50eaf - [clangd] Stop isSpelledInSource from printing source locations.

2022-10-05 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2022-10-05T15:49:22+02:00
New Revision: 0a50eafd1d44fae786a673e44831dd130a21b057

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

LOG: [clangd] Stop isSpelledInSource from printing source locations.

It shows up on profiles, albeit only at 0.1% or so.

Added: 


Modified: 
clang-tools-extra/clangd/SourceCode.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/SourceCode.cpp 
b/clang-tools-extra/clangd/SourceCode.cpp
index 670289eb37a5e..5928541635e67 100644
--- a/clang-tools-extra/clangd/SourceCode.cpp
+++ b/clang-tools-extra/clangd/SourceCode.cpp
@@ -228,12 +228,16 @@ Position sourceLocToPosition(const SourceManager &SM, 
SourceLocation Loc) {
 }
 
 bool isSpelledInSource(SourceLocation Loc, const SourceManager &SM) {
-  if (Loc.isMacroID()) {
-std::string PrintLoc = SM.getSpellingLoc(Loc).printToString(SM);
-if (llvm::StringRef(PrintLoc).startswith(""))
-  return false;
-  }
+  if (Loc.isFileID())
+return true;
+  auto Spelling = SM.getDecomposedSpellingLoc(Loc);
+  StringRef SpellingFile = SM.getSLocEntry(Spelling.first).getFile().getName();
+  if (SpellingFile == "")
+return false;
+  if (SpellingFile == "")
+// __STDC__ etc are considered spelled, but BAR in arg -DFOO=BAR is not.
+return !SM.isWrittenInCommandLineFile(
+SM.getComposedLoc(Spelling.first, Spelling.second));
   return true;
 }
 



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


[PATCH] D134797: [X86][vectorcall] Make floating-type passed by value to match with MSVC

2022-10-05 Thread Phoebe Wang via Phabricator via cfe-commits
pengfei updated this revision to Diff 465391.
pengfei added a comment.

Address @rnk's comments. Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134797

Files:
  clang/lib/CodeGen/TargetInfo.cpp
  clang/test/CodeGen/vectorcall.c


Index: clang/test/CodeGen/vectorcall.c
===
--- clang/test/CodeGen/vectorcall.c
+++ clang/test/CodeGen/vectorcall.c
@@ -140,4 +140,33 @@
 // X86-SAME: <4 x float>* inreg noundef %0,
 // X86-SAME: i32 inreg noundef %edx,
 // X86-SAME: <4 x float>* noundef %1)
+
+// The passing format of floating-point types are different from vector when 
SSE registers exhausted.
+// They are passed indirectly by value rather than address.
+void __vectorcall vectorcall_indirect_fp(
+double xmm0, double xmm1, double xmm2, double xmm3, double xmm4,
+v4f32 xmm5, double stack) {
+}
+// X86: define dso_local x86_vectorcallcc void 
@"\01vectorcall_indirect_fp@@{{[0-9]+}}"
+// X86-SAME: (double inreg noundef %xmm0,
+// X86-SAME: double inreg noundef %xmm1,
+// X86-SAME: double inreg noundef %xmm2,
+// X86-SAME: double inreg noundef %xmm3,
+// X86-SAME: double inreg noundef %xmm4,
+// X86-SAME: <4 x float> inreg noundef %xmm5,
+// X86-SAME: double noundef %stack)
+
+// Make sure HFA is passed indirectly by address.
+void __vectorcall vectorcall_indirect_hfa(
+double xmm0, double xmm1, double xmm2, double xmm3, double xmm4,
+v4f32 xmm5, struct HFA2 hfa2) {
+}
+// X86: define dso_local x86_vectorcallcc void 
@"\01vectorcall_indirect_hfa@@{{[0-9]+}}"
+// X86-SAME: (double inreg noundef %xmm0,
+// X86-SAME: double inreg noundef %xmm1,
+// X86-SAME: double inreg noundef %xmm2,
+// X86-SAME: double inreg noundef %xmm3,
+// X86-SAME: double inreg noundef %xmm4,
+// X86-SAME: <4 x float> inreg noundef %xmm5,
+// X86-SAME: %struct.HFA2* inreg noundef %hfa2)
 #endif
Index: clang/lib/CodeGen/TargetInfo.cpp
===
--- clang/lib/CodeGen/TargetInfo.cpp
+++ clang/lib/CodeGen/TargetInfo.cpp
@@ -1837,25 +1837,35 @@
 }
   }
 
-  // Regcall uses the concept of a homogenous vector aggregate, similar
-  // to other targets.
-  const Type *Base = nullptr;
-  uint64_t NumElts = 0;
-  if ((IsRegCall || IsVectorCall) &&
-  isHomogeneousAggregate(Ty, Base, NumElts)) {
-if (State.FreeSSERegs >= NumElts) {
-  State.FreeSSERegs -= NumElts;
-
-  // Vectorcall passes HVAs directly and does not flatten them, but regcall
-  // does.
-  if (IsVectorCall)
-return getDirectX86Hva();
-
-  if (Ty->isBuiltinType() || Ty->isVectorType())
-return ABIArgInfo::getDirect();
-  return ABIArgInfo::getExpand();
+  if (IsRegCall || IsVectorCall) {
+// Regcall uses the concept of a homogenous vector aggregate, similar
+// to other targets.
+const Type *Base = nullptr;
+uint64_t NumElts = 0;
+bool IsInReg = false;
+if (isHomogeneousAggregate(Ty, Base, NumElts)) {
+  if (State.FreeSSERegs >= NumElts) {
+State.FreeSSERegs -= NumElts;
+IsInReg = true;
+  }
+  if (IsRegCall) {
+if (IsInReg) {
+  // Regcall passes HVAs directly and flattens them.
+  if (Ty->isBuiltinType() || Ty->isVectorType())
+return ABIArgInfo::getDirect();
+  return ABIArgInfo::getExpand();
+}
+  } else {
+// Vectorcall passes floating types directly no matter if they can be
+// passed in register or not.
+if (Ty->isFloatingType())
+  return ABIArgInfo::getDirect();
+// Vectorcall passes HVAs directly and does not flatten them.
+if (IsInReg)
+  return getDirectX86Hva();
+  }
+  return getIndirectResult(Ty, /*ByVal=*/false, State);
 }
-return getIndirectResult(Ty, /*ByVal=*/false, State);
   }
 
   if (isAggregateTypeForABI(Ty)) {


Index: clang/test/CodeGen/vectorcall.c
===
--- clang/test/CodeGen/vectorcall.c
+++ clang/test/CodeGen/vectorcall.c
@@ -140,4 +140,33 @@
 // X86-SAME: <4 x float>* inreg noundef %0,
 // X86-SAME: i32 inreg noundef %edx,
 // X86-SAME: <4 x float>* noundef %1)
+
+// The passing format of floating-point types are different from vector when SSE registers exhausted.
+// They are passed indirectly by value rather than address.
+void __vectorcall vectorcall_indirect_fp(
+double xmm0, double xmm1, double xmm2, double xmm3, double xmm4,
+v4f32 xmm5, double stack) {
+}
+// X86: define dso_local x86_vectorcallcc void @"\01vectorcall_indirect_fp@@{{[0-9]+}}"
+// X86-SAME: (double inreg noundef %xmm0,
+// X86-SAME: double inreg noundef %xmm1,
+// X86-SAME: double inreg noundef %xmm2,
+// X86-SAME: double inreg noundef %xmm3,
+// X86-SAME: double inreg noundef %xmm4,
+// X86-SAME: <4 x float> inreg noundef %xmm5,
+// X86-SAME: double noundef %stac

[PATCH] D134797: [X86][vectorcall] Make floating-type passed by value to match with MSVC

2022-10-05 Thread Phoebe Wang via Phabricator via cfe-commits
pengfei added inline comments.



Comment at: clang/lib/CodeGen/TargetInfo.cpp:1858-1859
 }
-return getIndirectResult(Ty, /*ByVal=*/false, State);
+bool ByVal = IsVectorCall && Ty->isFloatingType();
+return getIndirectResult(Ty, ByVal, State);
   }

rnk wrote:
> pengfei wrote:
> > rnk wrote:
> > > I would try to refactor this so that the vectorcall HFA that can't be 
> > > passed in SSE regs falls through to the following logic. I suspect that 
> > > it correctly handles each case that we care about:
> > > - double: direct
> > > - vector: indirect for alignment
> > > - aggregate: indirect for alignment, any HFA will presumably be aligned 
> > > to more than 32bits
> > > 
> > Not sure if I understand it correctly, the HFA is not a floating type, so 
> > it won't be affected. Add a test case for it.
> > MSVC passes it indirectly too. https://gcc.godbolt.org/z/3qf4dTYfv
> Thanks, I see what you mean. I thought the code for handling overaligned 
> aggregates would trigger, passing any HFA indirectly, but it does not for 
> plain FP HFAs. You can observe the difference by replacing `double` in HFA2 
> with `__int64`, and see that HFA2 is passed underaligned on the stack:
> https://gcc.godbolt.org/z/jqx4xcnjq
> 
> I still think this code would benefit from separating the regcall and 
> vectorcall cases, something like:
>   bool IsInReg = State.FreeSSERegs >= NumElts;
>   if (IsInReg)
> State.FreeSSERegs -= NumElts;
>   if (IsRegCall) {
> // handle regcall
> if (IsInReg)
>...
>   } else {
> // handle vectorcall
> if (IsInReg)
>   ...
>   }
> 
> They seem to have pretty different rules both when SSE regs are available and 
> when not.
I can see the reason is non plain FP HFAs are not `HomogeneousAggregate` 
(possible be passed by SSE) on X86.
Anyway, I got your point now. Refactor the code seems better, thanks!



Comment at: clang/test/CodeGen/vectorcall.c:157
+// X86-SAME: <4 x float> inreg noundef %xmm5,
+// X86-SAME: double* noundef byval(double) align 4 %0)
 #endif

rnk wrote:
> pengfei wrote:
> > rnk wrote:
> > > Why not pass the double directly? That should be ABI compatible:
> > > https://gcc.godbolt.org/z/W4rjn63b5
> > Sorry, I'm not sure what's your mean here. Do you mean I should use your 
> > example as the test case? Here the case mocked `vectorcall_indirect_vec`, 
> > which I think is intended to check if the type, `inreg` and `byval` etc. 
> > are generated correctly.
> I mean that these two LLVM prototypes are ABI compatible at the binary level 
> for i686, but the second is much easier to optimize:
>   double @byval(double* byval(double) %p) {
> %v = load double, double* %p
> ret double %v
>   }
>   double @direct(double %v) {
> ret double %v
>   }
> https://gcc.godbolt.org/z/MjEvdEKbT
> 
> Clang should generate the prototype.
I see your point now, sounds good to me, thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134797

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


[PATCH] D129156: Add -fpass-plugin option to Flang

2022-10-05 Thread Tarun Prabhu via Phabricator via cfe-commits
tarunprabhu added a comment.

In D129156#3836838 , @clementval 
wrote:

> I probably didn't copy the error correctly .. this is the correct libs that 
> is not found `llvm-project/build/lib/Bye.so`

I need some help with this.

The failing build is building flang out-of-tree. It looks like %llvmshlibdir/ 
does not get set correctly in this case. Bye.so is located in %llvmshlibdir 
which is within the LLVM build directory.

Do you know if there is a way to tell the test-suite about %llvmshlibdir?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D129156

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


[PATCH] D134529: [C++20][Clang] P2468R2 The Equality Operator You Are Looking For

2022-10-05 Thread Utkarsh Saxena via Phabricator via cfe-commits
usaxena95 updated this revision to Diff 465393.
usaxena95 marked 11 inline comments as done.
usaxena95 added a comment.

Addressed comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134529

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/Overload.h
  clang/lib/Sema/SemaDeclCXX.cpp
  clang/lib/Sema/SemaOverload.cpp
  clang/test/CXX/over/over.match/over.match.funcs/over.match.oper/p3-2a.cpp

Index: clang/test/CXX/over/over.match/over.match.funcs/over.match.oper/p3-2a.cpp
===
--- clang/test/CXX/over/over.match/over.match.funcs/over.match.oper/p3-2a.cpp
+++ clang/test/CXX/over/over.match/over.match.funcs/over.match.oper/p3-2a.cpp
@@ -125,46 +125,204 @@
   bool b2 = 0 == ADL::type();
 }
 
-// Various C++17 cases that are known to be broken by the C++20 rules.
-namespace problem_cases {
-  // We can have an ambiguity between an operator and its reversed form. This
-  // wasn't intended by the original "consistent comparison" proposal, and we
-  // allow it as extension, picking the non-reversed form.
-  struct A {
-bool operator==(const A&); // expected-note {{ambiguity is between a regular call to this operator and a call with the argument order reversed}}
-  };
-  bool cmp_non_const = A() == A(); // expected-warning {{ambiguous}}
+namespace P2468R2 {
+// Problem cases prior to P2468R2 but now intentionally rejected.
+struct SymmetricNonConst {
+  bool operator==(const SymmetricNonConst&); // expected-note {{ambiguity is between a regular call to this operator and a call with the argument order reversed}}
+  // expected-note@-1 {{mark 'operator==' as const or add a matching 'operator!=' to resolve the ambiguity}}
+};
+bool cmp_non_const = SymmetricNonConst() == SymmetricNonConst(); // expected-warning {{ambiguous}}
 
-  struct B {
-virtual bool operator==(const B&) const;
-  };
-  struct D : B {
-bool operator==(const B&) const override; // expected-note {{operator}}
-  };
-  bool cmp_base_derived = D() == D(); // expected-warning {{ambiguous}}
+struct SymmetricConst {
+  bool operator==(const SymmetricConst&) const;
+};
+bool cmp_const = SymmetricConst() == SymmetricConst();
 
-  template struct CRTPBase {
-bool operator==(const T&) const; // expected-note {{operator}} expected-note {{reversed}}
-bool operator!=(const T&) const; // expected-note {{non-reversed}}
-  };
-  struct CRTP : CRTPBase {};
-  bool cmp_crtp = CRTP() == CRTP(); // expected-warning-re {{ambiguous despite there being a unique best viable function{{$}}
-  bool cmp_crtp2 = CRTP() != CRTP(); // expected-warning {{ambiguous despite there being a unique best viable function with non-reversed arguments}}
-
-  // Given a choice between a rewritten and non-rewritten function with the
-  // same parameter types, where the rewritten function is reversed and each
-  // has a better conversion for one of the two arguments, prefer the
-  // non-rewritten one.
-  using UBool = signed char; // ICU uses this.
-  struct ICUBase {
-virtual UBool operator==(const ICUBase&) const;
-UBool operator!=(const ICUBase &arg) const { return !operator==(arg); }
-  };
-  struct ICUDerived : ICUBase {
-UBool operator==(const ICUBase&) const override; // expected-note {{declared here}} expected-note {{ambiguity is between}}
-  };
-  bool cmp_icu = ICUDerived() != ICUDerived(); // expected-warning {{ambiguous}} expected-warning {{'bool', not 'UBool'}}
+struct SymmetricNonConstWithoutConstRef {
+  bool operator==(SymmetricNonConstWithoutConstRef);
+};
+bool cmp_non_const_wo_ref = SymmetricNonConstWithoutConstRef() == SymmetricNonConstWithoutConstRef();
+
+struct B {
+  virtual bool operator==(const B&) const;
+};
+struct D : B {
+  bool operator==(const B&) const override; // expected-note {{operator}}
+};
+bool cmp_base_derived = D() == D(); // expected-warning {{ambiguous}}
+
+// Reversed "3" not used because we find "2".
+// Rewrite != from "3" but warn that "chosen rewritten candidate must return cv-bool".
+using UBool = signed char;
+struct ICUBase {
+  virtual UBool operator==(const ICUBase&) const; // 1.
+  UBool operator!=(const ICUBase &arg) const { return !operator==(arg); } // 2.
+};
+struct ICUDerived : ICUBase {
+  // 3.
+  UBool operator==(const ICUBase&) const override; // expected-note {{declared here}}
+};
+bool cmp_icu = ICUDerived() != ICUDerived(); // expected-warning {{ISO C++20 requires return type of selected 'operator==' function for rewritten '!=' comparison to be 'bool', not 'UBool' (aka 'signed char')}}
+// Accepted by P2468R2.
+// 1
+struct S {
+  bool operator==(const S&) { return true; }
+  bool operator!=(const S&) { return false; }
+};
+bool ts = S{} != S{};
+// 2
+template struct CRTPBase {
+  bool operator==(const T&) const;
+  bool operator!=(const T&) const;
+};
+struct CRTP : CRTPB

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

2022-10-05 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl created this revision.
yaxunl added reviewers: tra, ronl.
Herald added subscribers: kosarev, t-tye, tpr, dstuttard, kzhuravl.
Herald added a project: All.
yaxunl requested review of this revision.
Herald added a subscriber: wdng.

Currently there is some backend issue 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.


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"
+
+// Make sure bool loaded from memory is truncated and
+// range metadata is not emitted.
+
+// NV:  %[[LD:[0-9]+]] = load i8, ptr %x,{{.*}} !range ![[MD:[0-9]+]]
+// NV:  store i8 %[[LD]], ptr %y
+// NV: ![[MD]] = !{i8 0, i8 2}
+
+// TODO: Re-enable range metadata after backend issue 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
@@ -1789,7 +1789,9 @@
   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 backend issue 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"
+
+// Make sure bool loaded from memory is truncated and
+// range metadata is not emitted.
+
+// NV:  %[[LD:[0-9]+]] = load i8, ptr %x,{{.*}} !range ![[MD:[0-9]+]]
+// NV:  store i8 %[[LD]], ptr %y
+// NV: ![[MD]] = !{i8 0, i8 2}
+
+// TODO: Re-enable range metadata after backend issue 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
@@ -1789,7 +1789,9 @@
   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 backend issue 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


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

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

I provided a solution for the problem I mentioned above, although it may look 
ugly. Then, I will take a look at `friend` related stuffs.


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/SemaConcept.h
  clang/lib/Parse/ParseTemplate.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 {{similar constraint expressions not considered equivalent}}
+// expected-note@#C {{similar constraint}}
 
 template class P> struct S2 { };
 
@@ -32,3 +37,27 @@
 
 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}}
+// expected-note@#F {{similar constraint expressions not considered equivalent}}
+// expected-note@#C {{similar constraint}}
+
+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/Parse/ParseTemplate.cpp
===
--- clang/lib/Parse/ParseTemplate.cpp
+++ clang/lib/Parse/ParseTemplate.cpp
@@ -874,27 +874,39 @@
 /// template parameters.
 ///
 ///   type-parameter:[C++ temp.param]
-/// 'template' '<' template-parameter-list '>' type-parameter-key
-///  ...[opt] identifier[opt]
-/// 'template' '<' template-parameter-list '>' type-parameter-key
-///  identifier[opt] = id-expression
+/// template-head type-parameter-key ...[opt] identifier[opt]
+/// template-head type-parameter-key iden

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

2022-10-05 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl updated this revision to Diff 465403.
yaxunl added a comment.

fix comments in test


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,22 @@
+// 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 backend issue 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
@@ -1789,7 +1789,9 @@
   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 backend issue 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,22 @@
+// 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 backend issue 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
@@ -1789,7 +1789,9 @@
   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 backend issue 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


[PATCH] D134618: [Syntax] Fix macro-arg handling in TokenBuffer::spelledForExpanded

2022-10-05 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet accepted this revision.
kadircet added a comment.
This revision is now accepted and ready to land.

thanks, lgtm!




Comment at: clang/lib/Tooling/Syntax/Tokens.cpp:82
+  // When First and Last are part of the *same macro arg* of a macro written
+  // in the main file, we may return only that part of the arg, i.e. their
+  // spelling range.

`main file` here and in rest of the comments feels a little confusing. maybe 
rename `FID` to `MainFile` (which is still somewhat confusing) or call it 
`SpelledFID` and also change the mentions of `main file` in comments to 
`spelling file` (or similar). (assuming i am not misunderstanding something)



Comment at: clang/lib/Tooling/Syntax/Tokens.cpp:102
+// Careful, given:
+//   #define HIDE ID(ID(a))
+//   ID(ID(HIDE))

s/a/A/



Comment at: clang/lib/Tooling/Syntax/Tokens.cpp:137
+//  ID2(prev, target) // selecting 'target' succeeds
+//  #define LARGE ID(prev, target)
+//  LARGE // selecting 'target' fails

nit: s/ID/ID2



Comment at: clang/lib/Tooling/Syntax/Tokens.cpp:475
+  // Mapping. We must use the general (SourceManager-based) algorithm.
+  if (FirstMapping && LastMapping && FirstMapping == LastMapping &&
+  SourceMgr->isMacroArgExpansion(First->location()) &&

nit: drop the check for `LastMapping`



Comment at: clang/lib/Tooling/Syntax/Tokens.cpp:487
+First->location(), Last->location(), Prev, Next, FID, *SourceMgr);
+if (Range.isInvalid())
+  return llvm::None;

can we also have a test like:
```
#define ID(X) X
#define BAR ID(1)
BAR
```

to make sure we can select the object-like macro when the whole contents are 
matched (it's probably also worth mentioning in the public documentation)



Comment at: clang/unittests/Tooling/Syntax/TokensTest.cpp:760
+  EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("y")),
+  ValueIs(SameRange(findSpelled("( y").drop_front(;
+

"y" is only mentioned once in the main-file no need for matching something wider


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134618

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


[PATCH] D134852: [clang-format][NFC] Clean up class HeaderIncludes and Format.cpp

2022-10-05 Thread Konrad Wilhelm Kleine via Phabricator via cfe-commits
kwk accepted this revision.
kwk added inline comments.
This revision is now accepted and ready to land.



Comment at: clang/lib/Format/Format.cpp:2774
-
-const char CppIncludeRegexPattern[] =
-R"(^[\t\ ]*#[\t\ ]*(import|include)[^"<]*(["<][^">]*[">]))";

owenpan wrote:
> kwk wrote:
> > owenpan wrote:
> > > kwk wrote:
> > > > MyDeveloperDay wrote:
> > > > > Did I miss where this comes from now?
> > > > @MyDeveloperDay `clang/lib/Tooling/Inclusions/HeaderIncludes.cpp` still 
> > > > has this:
> > > > 
> > > > ```lang=c++
> > > > const char IncludeRegexPattern[] =
> > > > R"(^[\t\ ]*#[\t\ ]*(import|include)[^"<]*(["<][^">]*[">]))";
> > > > ```
> > > > 
> > > > And in `clang/lib/Tooling/Inclusions/HeaderIncludes.cpp` @owenpan uses 
> > > > it to initialize the final regex 
> > > > 
> > > > ```lang=c++
> > > > const llvm::Regex HeaderIncludes::IncludeRegex(IncludeRegexPattern); 
> > > > ```
> > > > 
> > > > The fact that we have two regex that are identical is an issue on its 
> > > > own that I tried to address with [my 
> > > > patch](https://reviews.llvm.org/D134733) as well. I didn't initialize 
> > > > the regex like @owenpan does here but I had a function to return it. 
> > > > Eventually a function makes it easier to apply the injection from a 
> > > > config file as you've suggested 
> > > > [here](https://reviews.llvm.org/D134733#3821957). So I favor my 
> > > > solution.
> > > > 
> > > > 
> > > > 
> > > > 
> > > > The fact that we have two regex that are identical is an issue on its 
> > > > own that I tried to address with [my 
> > > > patch](https://reviews.llvm.org/D134733) as well.
> > > 
> > > It should be addressed in a separate NFC patch such as this one.
> > > 
> > > > I didn't initialize the regex like @owenpan does here but I had a 
> > > > function to return it. Eventually a function makes it easier to apply 
> > > > the injection from a config file as you've suggested 
> > > > [here](https://reviews.llvm.org/D134733#3821957). So I favor my 
> > > > solution.
> > > 
> > > Making `IncludeRegex` a public static const member is one of the better 
> > > solutions when `IncludeRegexPattern` is fixed as it has been. If and when 
> > > we decide to support user specified patterns, we will make any necessary 
> > > changes then.
> > > > The fact that we have two regex that are identical is an issue on its 
> > > > own that I tried to address with [my 
> > > > patch](https://reviews.llvm.org/D134733) as well.
> > > 
> > > It should be addressed in a separate NFC patch such as this one.
> > 
> > Ehm, I thought I *did* create a separate NFC patch with D134733. I prefixed 
> > it with `[chore]` but that is as good as NFC. I can rename it if you want.  
> > 
> > > 
> > > > I didn't initialize the regex like @owenpan does here but I had a 
> > > > function to return it. Eventually a function makes it easier to apply 
> > > > the injection from a config file as you've suggested 
> > > > [here](https://reviews.llvm.org/D134733#3821957). So I favor my 
> > > > solution.
> > > 
> > > Making `IncludeRegex` a public static const member is one of the better 
> > > solutions when `IncludeRegexPattern` is fixed as it has been. If and when 
> > > we decide to support user specified patterns, we will make any necessary 
> > > changes then.
> > 
> > Okay, but you could have suggested that in D134733, no? I've made the 
> > change in D134733 here: 
> > https://reviews.llvm.org/D134733?vs=463205&id=464196#toc, so the regex is 
> > static const. But I've also outsourced the function for accessing the 
> > include name so the logic is at one place not scattered over and over and 
> > the trimming is also in its own function. Having everything going through 
> > that functions is easier for maintenance IMHO. Before I wondered why we had 
> > two include regex patterns (both the same btw.) and why an include name 
> > wasn't found when I had changed the `Matches[2]` to `Matches[3]` for 
> > example. That won't happen when its going through the function. You just 
> > change it in one place and not "plenty".
> > 
> > I hope we can agree that my change is now complete with additions from 
> > yours here. I most certainly don't want to disrupt your workflow and I 
> > apologize if I had. Unfortunately text can be misinterpreted way too much.
> > Ehm, I thought I *did* create a separate NFC patch with D134733. I prefixed 
> > it with `[chore]` but that is as good as NFC. I can rename it if you want.
> 
> I didn't know by `chore` you meant `NFC`. Thanks for renaming it.
> 
> > Okay, but you could have suggested that in D134733, no?
> 
> It would be too many places to point out as you can tell from this patch. 
> When mixed with other unrelated changes in D134733, it would be more 
> difficult for me to review and other people to follow. Making this patch 
> allows me to focus on the best way to solve the problem without worrying 
> about any additional "noise".
> 
> > I hope we can agre

[PATCH] D135011: Add builtin_elementwise_sin and builtin_elementwise_cos

2022-10-05 Thread Steve Canon via Phabricator via cfe-commits
scanon added inline comments.



Comment at: clang/docs/LanguageExtensions.rst:607
+ T __builtin_elementwise_cos(T x)return the ratio of the adjacent 
side length over thefloating point types
+ hypoteneuse side length, given 
the angle x in radians
  T __builtin_elementwise_floor(T x)  return the largest integral value 
less than or equal to xfloating point types

craig.topper wrote:
> hypotenuse*
As long as we're tweaking descriptions, please just call these "cosine" and 
"sine" instead of a cumbersome ratio description. "The cosine of x interpreted 
as an angle in radians" or similar.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135011

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


[PATCH] D135273: [Clang][ObjC] Add optionality to property attribute strings.

2022-10-05 Thread Alastair Houghton via Phabricator via cfe-commits
al45tair created this revision.
al45tair added reviewers: ahatanak, rjmccall, theraven.
Herald added a project: All.
al45tair requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Add a new attribute, "?", to the property attribute string for properties of 
protocols that are declared `@optional`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D135273

Files:
  clang/lib/AST/ASTContext.cpp
  clang/test/CodeGenObjC/objc-asm-attribute-test.m


Index: clang/test/CodeGenObjC/objc-asm-attribute-test.m
===
--- clang/test/CodeGenObjC/objc-asm-attribute-test.m
+++ clang/test/CodeGenObjC/objc-asm-attribute-test.m
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -no-opaque-pointers -emit-llvm -triple x86_64-apple-darwin 
%s -o - | FileCheck %s
+// RUN: %clang_cc1 -no-opaque-pointers -Wno-objc-root-class -emit-llvm -triple 
x86_64-apple-darwin %s -o - | FileCheck %s
 // rdar://16462586
 
 __attribute__((objc_runtime_name("MySecretNamespace.Protocol")))
@@ -11,10 +11,17 @@
 @protocol Protocol2
 - (void) MethodP2;
 + (void) ClsMethodP2;
+
+@optional
+@property(retain) id optionalProp;
+
 @end
 
+@class Message;
+
 __attribute__((objc_runtime_name("MySecretNamespace.Protocol3")))
 @protocol Protocol3
+
 @end
 
 __attribute__((objc_runtime_name("MySecretNamespace.Message")))
@@ -56,9 +63,13 @@
 }
 
 // CHECK: @"OBJC_IVAR_$_MySecretNamespace.Message.MyIVAR" ={{.*}} global i64 0
+
 // CHECK: @"OBJC_CLASS_$_MySecretNamespace.Message" ={{.*}} global 
%struct._class_t
 // CHECK: @"OBJC_METACLASS_$_MySecretNamespace.Message" ={{.*}} global 
%struct._class_t
 
+// CHECK: @OBJC_PROP_NAME_ATTR_ = private unnamed_addr constant [13 x i8] 
c"optionalProp\00", section "__TEXT,__objc_methname,cstring_literals", align 1
+// CHECK-NEXT: @OBJC_PROP_NAME_ATTR_.11 = private unnamed_addr constant [7 x 
i8] c"T@,?,&\00", section "__TEXT,__objc_methname,cstring_literals", align 1
+
 // CHECK: private unnamed_addr constant [42 x i8] 
c"T@\22MySecretNamespace.Message\22,&,V_msgProp\00"
 // CHECK: private unnamed_addr constant [76 x i8] 
c"T@\22MySecretNamespace.Message\22,&,V_msgProtoProp\00"
 // CHECK: private unnamed_addr constant [50 x i8] 
c"T@\22\22,&,V_idProtoProp\00"
Index: clang/lib/AST/ASTContext.cpp
===
--- clang/lib/AST/ASTContext.cpp
+++ clang/lib/AST/ASTContext.cpp
@@ -7828,6 +7828,7 @@
 /// kPropertyWeak = 'W'  // 'weak' property
 /// kPropertyStrong = 'P'// property GC'able
 /// kPropertyNonAtomic = 'N' // property non-atomic
+/// kPropertyOptional = '?'  // property optional
 /// };
 /// @endcode
 std::string
@@ -7853,6 +7854,10 @@
   // closely resembles encoding of ivars.
   getObjCEncodingForPropertyType(PD->getType(), S);
 
+  if (PD->isOptional()) {
+S += ",?";
+  }
+
   if (PD->isReadOnly()) {
 S += ",R";
 if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy)


Index: clang/test/CodeGenObjC/objc-asm-attribute-test.m
===
--- clang/test/CodeGenObjC/objc-asm-attribute-test.m
+++ clang/test/CodeGenObjC/objc-asm-attribute-test.m
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -no-opaque-pointers -emit-llvm -triple x86_64-apple-darwin %s -o - | FileCheck %s
+// RUN: %clang_cc1 -no-opaque-pointers -Wno-objc-root-class -emit-llvm -triple x86_64-apple-darwin %s -o - | FileCheck %s
 // rdar://16462586
 
 __attribute__((objc_runtime_name("MySecretNamespace.Protocol")))
@@ -11,10 +11,17 @@
 @protocol Protocol2
 - (void) MethodP2;
 + (void) ClsMethodP2;
+
+@optional
+@property(retain) id optionalProp;
+
 @end
 
+@class Message;
+
 __attribute__((objc_runtime_name("MySecretNamespace.Protocol3")))
 @protocol Protocol3
+
 @end
 
 __attribute__((objc_runtime_name("MySecretNamespace.Message")))
@@ -56,9 +63,13 @@
 }
 
 // CHECK: @"OBJC_IVAR_$_MySecretNamespace.Message.MyIVAR" ={{.*}} global i64 0
+
 // CHECK: @"OBJC_CLASS_$_MySecretNamespace.Message" ={{.*}} global %struct._class_t
 // CHECK: @"OBJC_METACLASS_$_MySecretNamespace.Message" ={{.*}} global %struct._class_t
 
+// CHECK: @OBJC_PROP_NAME_ATTR_ = private unnamed_addr constant [13 x i8] c"optionalProp\00", section "__TEXT,__objc_methname,cstring_literals", align 1
+// CHECK-NEXT: @OBJC_PROP_NAME_ATTR_.11 = private unnamed_addr constant [7 x i8] c"T@,?,&\00", section "__TEXT,__objc_methname,cstring_literals", align 1
+
 // CHECK: private unnamed_addr constant [42 x i8] c"T@\22MySecretNamespace.Message\22,&,V_msgProp\00"
 // CHECK: private unnamed_addr constant [76 x i8] c"T@\22MySecretNamespace.Message\22,&,V_msgProtoProp\00"
 // CHECK: private unnamed_addr constant [50 x i8] c"T@\22\22,&,V_idProtoProp\00"
Index: clang/lib/AST/ASTContext.cpp
===
--- clang/lib/AST/ASTContext.cpp
+++ clang/lib/AST/ASTContext.cpp
@@ -7828,6 

[PATCH] D134529: [C++20][Clang] P2468R2 The Equality Operator You Are Looking For

2022-10-05 Thread Utkarsh Saxena via Phabricator via cfe-commits
usaxena95 added inline comments.



Comment at: clang/include/clang/Sema/Overload.h:1024
   /// candidates for operator Op.
-  bool shouldAddReversed(OverloadedOperatorKind Op);
+  bool mayAddReversed(OverloadedOperatorKind Op);
 

ilya-biryukov wrote:
> I am not sure the new name adds clarity.
> It's unclear what the `true` return value means here. `should` clearly 
> indicated returning true means the code has to proceed with adding the 
> reversed operator. `may` means the code can choose to do so or not, I don't 
> think that's quite right. `should` was really a better choice here.
> 
> That said, I don't think the rename itself is a bad idea, maybe there is a 
> better name, but I couldn't come up with one.
Just to be clear, it is possible to not reverse the args even if this returns 
true now since we do not do full check for `==` here.

I renamed it `allowsReversed` on the same line of `AllowRewrittenCandidates`.

Intention is to convey that if this is true then reversing is allowed and you 
can choose not to do so as well.



Comment at: clang/lib/Sema/SemaOverload.cpp:976
 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
-ASTContext &Ctx, const FunctionDecl *FD) {
-  if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator()))
+Sema &S, ArrayRef Args, const FunctionDecl *FD) {
+  auto Op = FD->getOverloadedOperator();

ilya-biryukov wrote:
> NIT: same suggestion as before. Just pass `Expr* FirstOperand` as the 
> parameter instead of an array.
I would prefer not to use a `FirstOperand` for `shouldAddReversed` as it serves 
more than just `operator==`. 

It might be confusing/error-prone for the users as to what is the "first 
operand" here (Args[0] or Args[1] ? In reversed args or original args ?). I 
think it would be a better API to just have original args as the parameter let 
this function decide which is the `FirstOperand`.



Comment at: 
clang/test/CXX/over/over.match/over.match.funcs/over.match.oper/p3-2a.cpp:231
+bool c1 = B() == C(); // OK, calls 2; reversed 2 is not a candidate because 
search for operator!= in C finds #3
+bool c2 = C() == B();  // expected-warning {{ISO C++20 considers use of 
overloaded operator '==' (with operand types 'C' and 'B') to be ambiguous 
despite there being a unique best viable function}}
+

ilya-biryukov wrote:
> NIT: could you add a comment explaining why this is ambiguous? This seems 
> non-obvious.
> It's because the search for `operator!=` happens inside `B` and never finds 
> `3`, right?
Yes. That is correct.



Comment at: 
clang/test/CXX/over/over.match/over.match.funcs/over.match.oper/p3-2a.cpp:269
+};
+bool b = B() == B(); // ok. No rewrite due to const.
+

ilya-biryukov wrote:
> Also due to different parameter types (`T` vs `B`)?
> So the description is incomplete or am I missing something?
This verifies that adding `const` would solve the ambiguity without adding a 
matching `!=`. The `!=` here does not match because it is non-template and, 
yes, because of different param types.



Comment at: 
clang/test/CXX/over/over.match/over.match.funcs/over.match.oper/p3-2a.cpp:300
+} // using_decls
+// FIXME: Match requires clause.
+// namespace match_requires_clause {

ilya-biryukov wrote:
> NIT: maybe file a bug for this and mention the GH issue number?
> (could be done in the last iteration right before landing the change)
Sure. I can do this in a followup patch once this issue lands.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134529

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


[PATCH] D135247: [clang][analyzer] Add stream functions to StdLibraryFunctionsChecker.

2022-10-05 Thread Balázs Kéri via Phabricator via cfe-commits
balazske updated this revision to Diff 465423.
balazske added a comment.

Fixed failing tests.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135247

Files:
  clang/lib/StaticAnalyzer/Checkers/ErrnoChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/ErrnoModeling.cpp
  clang/lib/StaticAnalyzer/Checkers/ErrnoModeling.h
  clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
  clang/test/Analysis/Inputs/system-header-simulator.h
  clang/test/Analysis/std-c-library-functions-POSIX.c
  clang/test/Analysis/std-c-library-functions-vs-stream-checker.c
  clang/test/Analysis/stream-errno-note.c
  clang/test/Analysis/stream-errno.c
  clang/test/Analysis/stream-noopen.c

Index: clang/test/Analysis/stream-noopen.c
===
--- /dev/null
+++ clang/test/Analysis/stream-noopen.c
@@ -0,0 +1,97 @@
+// RUN: %clang_analyze_cc1 -verify %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=alpha.unix.Errno \
+// RUN:   -analyzer-checker=alpha.unix.Stream \
+// RUN:   -analyzer-checker=apiModeling.StdCLibraryFunctions \
+// RUN:   -analyzer-config apiModeling.StdCLibraryFunctions:ModelPOSIX=true \
+// RUN:   -analyzer-checker=debug.ExprInspection
+
+// enable only StdCLibraryFunctions checker
+// RUN: %clang_analyze_cc1 -verify %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=alpha.unix.Errno \
+// RUN:   -analyzer-checker=apiModeling.StdCLibraryFunctions \
+// RUN:   -analyzer-config apiModeling.StdCLibraryFunctions:ModelPOSIX=true \
+// RUN:   -analyzer-checker=debug.ExprInspection
+
+#include "Inputs/system-header-simulator.h"
+#include "Inputs/errno_var.h"
+
+void clang_analyzer_eval(int);
+
+const char *WBuf = "123456789";
+char RBuf[10];
+
+void test_freopen(FILE *F) {
+  F = freopen("xxx", "w", F);
+  if (F) {
+if (errno) {} // expected-warning{{undefined}}
+  } else {
+clang_analyzer_eval(errno != 0); // expected-warning {{TRUE}}
+  }
+}
+
+void test_fread(FILE *F) {
+  size_t Ret = fread(RBuf, 1, 10, F);
+  if (Ret == 10) {
+if (errno) {} // expected-warning{{undefined}}
+  } else {
+clang_analyzer_eval(errno != 0); // expected-warning {{TRUE}}
+  }
+  clang_analyzer_eval(feof(F)); // expected-warning {{UNKNOWN}}
+  clang_analyzer_eval(ferror(F)); // expected-warning {{UNKNOWN}}
+}
+
+void test_fwrite(FILE *F) {
+  size_t Ret = fwrite(WBuf, 1, 10, F);
+  if (Ret == 10) {
+if (errno) {} // expected-warning{{undefined}}
+  } else {
+clang_analyzer_eval(errno != 0); // expected-warning {{TRUE}}
+  }
+  clang_analyzer_eval(feof(F)); // expected-warning {{UNKNOWN}}
+  clang_analyzer_eval(ferror(F)); // expected-warning {{UNKNOWN}}
+}
+
+void test_fclose(FILE *F) {
+  int Ret = fclose(F);
+  if (Ret == 0) {
+if (errno) {} // expected-warning{{undefined}}
+  } else {
+clang_analyzer_eval(Ret == EOF); // expected-warning {{TRUE}}
+clang_analyzer_eval(errno != 0); // expected-warning {{TRUE}}
+  }
+  clang_analyzer_eval(feof(F)); // expected-warning {{UNKNOWN}}
+  clang_analyzer_eval(ferror(F)); // expected-warning {{UNKNOWN}}
+}
+
+void test_fseek(FILE *F) {
+  int Ret = fseek(F, SEEK_SET, 1);
+  if (Ret == 0) {
+if (errno) {} // expected-warning{{undefined}}
+  } else {
+clang_analyzer_eval(Ret == -1); // expected-warning {{TRUE}}
+clang_analyzer_eval(errno != 0); // expected-warning {{TRUE}}
+  }
+  clang_analyzer_eval(feof(F)); // expected-warning {{UNKNOWN}}
+  clang_analyzer_eval(ferror(F)); // expected-warning {{UNKNOWN}}
+}
+
+void freadwrite_zerosize(FILE *F) {
+  fwrite(WBuf, 1, 0, F);
+  clang_analyzer_eval(feof(F)); // expected-warning {{UNKNOWN}}
+  clang_analyzer_eval(ferror(F)); // expected-warning {{UNKNOWN}}
+  if (errno) {} // no-warning
+  fwrite(WBuf, 0, 1, F);
+  clang_analyzer_eval(feof(F)); // expected-warning {{UNKNOWN}}
+  clang_analyzer_eval(ferror(F)); // expected-warning {{UNKNOWN}}
+  if (errno) {} // no-warning
+  fread(RBuf, 1, 0, F);
+  clang_analyzer_eval(feof(F)); // expected-warning {{UNKNOWN}}
+  clang_analyzer_eval(ferror(F)); // expected-warning {{UNKNOWN}}
+  if (errno) {} // no-warning
+  fread(RBuf, 0, 1, F);
+  clang_analyzer_eval(feof(F)); // expected-warning {{UNKNOWN}}
+  clang_analyzer_eval(ferror(F)); // expected-warning {{UNKNOWN}}
+  if (errno) {} // no-warning
+}
Index: clang/test/Analysis/stream-errno.c
===
--- /dev/null
+++ clang/test/Analysis/stream-errno.c
@@ -0,0 +1,138 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.unix.Stream,alpha.unix.Errno,apiModeling.StdCLibraryFunctions,debug.ExprInspection \
+// RUN:   -analyzer-config apiModeling.StdCLibraryFunctions:ModelPOSIX=true -verify %s
+
+#include "Inputs/system-header-simulator.h"
+#include "Inputs/errno_func.h"
+
+extern void clang_analyzer_eval(int);
+extern 

[clang] 67268ee - [Syntax] Fix macro-arg handling in TokenBuffer::spelledForExpanded

2022-10-05 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2022-10-05T18:04:39+02:00
New Revision: 67268ee11c220b1dfdf84afb10a12371c5ae6400

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

LOG: [Syntax] Fix macro-arg handling in TokenBuffer::spelledForExpanded

A few cases were not handled correctly. Notably:
  #define ID(X) X
  #define HIDE a ID(b)
  HIDE
spelledForExpanded() would claim HIDE is an equivalent range of the 'b' it
contains, despite the fact that HIDE also covers 'a'.

While trying to fix this bug, I found findCommonRangeForMacroArgs hard
to understand (both the implementation and how it's used in spelledForExpanded).
It relies on details of the SourceLocation graph that are IMO fairly obscure.
So I've added/revised quite a lot of comments and made some naming tweaks.

Fixes https://github.com/clangd/clangd/issues/1289

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

Added: 


Modified: 
clang/lib/Tooling/Syntax/Tokens.cpp
clang/unittests/Tooling/Syntax/TokensTest.cpp

Removed: 




diff  --git a/clang/lib/Tooling/Syntax/Tokens.cpp 
b/clang/lib/Tooling/Syntax/Tokens.cpp
index 61e02b19fa83f..fe979afe6f951 100644
--- a/clang/lib/Tooling/Syntax/Tokens.cpp
+++ b/clang/lib/Tooling/Syntax/Tokens.cpp
@@ -55,45 +55,140 @@ getTokensCovering(llvm::ArrayRef Toks, 
SourceRange R,
   return {Begin, End};
 }
 
-// Finds the smallest expansion range that contains expanded tokens First and
-// Last, e.g.:
+// Finds the range within FID corresponding to expanded tokens [First, Last].
+// Prev precedes First and Next follows Last, these must *not* be included.
+// If no range satisfies the criteria, returns an invalid range.
+//
 // #define ID(x) x
 // ID(ID(ID(a1) a2))
 //  ~~   -> a1
 //  ~~   -> a2
 //   ~   -> a1 a2
-SourceRange findCommonRangeForMacroArgs(const syntax::Token &First,
-const syntax::Token &Last,
-const SourceManager &SM) {
-  SourceRange Res;
-  auto FirstLoc = First.location(), LastLoc = Last.location();
-  // Keep traversing up the spelling chain as longs as tokens are part of the
-  // same expansion.
-  while (!FirstLoc.isFileID() && !LastLoc.isFileID()) {
-auto ExpInfoFirst = SM.getSLocEntry(SM.getFileID(FirstLoc)).getExpansion();
-auto ExpInfoLast = SM.getSLocEntry(SM.getFileID(LastLoc)).getExpansion();
-// Stop if expansions have diverged.
-if (ExpInfoFirst.getExpansionLocStart() !=
-ExpInfoLast.getExpansionLocStart())
+SourceRange spelledForExpandedSlow(SourceLocation First, SourceLocation Last,
+   SourceLocation Prev, SourceLocation Next,
+   FileID TargetFile,
+   const SourceManager &SM) {
+  // There are two main parts to this algorithm:
+  //  - identifying which spelled range covers the expanded tokens
+  //  - validating that this range doesn't cover any extra tokens (First/Last)
+  //
+  // We do these in order. However as we transform the expanded range into the
+  // spelled one, we adjust First/Last so the validation remains simple.
+
+  assert(SM.getSLocEntry(TargetFile).isFile());
+  // In most cases, to select First and Last we must return their expansion
+  // range, i.e. the whole of any macros they are included in.
+  //
+  // When First and Last are part of the *same macro arg* of a macro written
+  // in TargetFile, we that slice of the arg, i.e. their spelling range.
+  //
+  // Unwrap such macro calls. If the target file has A(B(C)), the
+  // SourceLocation stack of a token inside C shows us the expansion of A 
first,
+  // then B, then any macros inside C's body, then C itself.
+  // (This is the reverse of the order the PP applies the expansions in).
+  while (First.isMacroID() && Last.isMacroID()) {
+auto DecFirst = SM.getDecomposedLoc(First);
+auto DecLast = SM.getDecomposedLoc(Last);
+auto &ExpFirst = SM.getSLocEntry(DecFirst.first).getExpansion();
+auto &ExpLast = SM.getSLocEntry(DecLast.first).getExpansion();
+
+if (!ExpFirst.isMacroArgExpansion() || !ExpLast.isMacroArgExpansion())
+  break;
+// Locations are in the same macro arg if they expand to the same place.
+// (They may still have 
diff erent FileIDs - an arg can have >1 chunks!)
+if (ExpFirst.getExpansionLocStart() != ExpLast.getExpansionLocStart())
   break;
-// Do not continue into macro bodies.
-if (!ExpInfoFirst.isMacroArgExpansion() ||
-!ExpInfoLast.isMacroArgExpansion())
+// Careful, given:
+//   #define HIDE ID(ID(a))
+//   ID(ID(HIDE))
+// The token `a` is wrapped in 4 arg-expansions, we only want to unwrap 2.
+// We distinguish them by whether the macro expands into the

[PATCH] D134618: [Syntax] Fix macro-arg handling in TokenBuffer::spelledForExpanded

2022-10-05 Thread Sam McCall via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
sammccall marked 5 inline comments as done.
Closed by commit rG67268ee11c22: [Syntax] Fix macro-arg handling in 
TokenBuffer::spelledForExpanded (authored by sammccall).

Changed prior to commit:
  https://reviews.llvm.org/D134618?vs=462781&id=465426#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134618

Files:
  clang/lib/Tooling/Syntax/Tokens.cpp
  clang/unittests/Tooling/Syntax/TokensTest.cpp

Index: clang/unittests/Tooling/Syntax/TokensTest.cpp
===
--- clang/unittests/Tooling/Syntax/TokensTest.cpp
+++ clang/unittests/Tooling/Syntax/TokensTest.cpp
@@ -743,6 +743,62 @@
   ValueIs(SameRange(findSpelled("ID2 ( a4 , a5 a6 a7 )";
   // Should fail, spans multiple invocations.
   EXPECT_EQ(Buffer.spelledForExpanded(findExpanded("a1 a2 a3 a4")), llvm::None);
+
+  // https://github.com/clangd/clangd/issues/1289
+  recordTokens(R"cpp(
+#define FOO(X) foo(X)
+#define INDIRECT FOO(y)
+INDIRECT // expands to foo(y)
+  )cpp");
+  EXPECT_EQ(Buffer.spelledForExpanded(findExpanded("y")), llvm::None);
+
+  recordTokens(R"cpp(
+#define FOO(X) a X b
+FOO(y)
+  )cpp");
+  EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("y")),
+  ValueIs(SameRange(findSpelled("y";
+
+  recordTokens(R"cpp(
+#define ID(X) X
+#define BAR ID(1)
+BAR
+  )cpp");
+  EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("1")),
+  ValueIs(SameRange(findSpelled(") BAR").drop_front(;
+
+  // Critical cases for mapping of Prev/Next in spelledForExpandedSlow.
+  recordTokens(R"cpp(
+#define ID(X) X
+ID(prev ID(good))
+#define LARGE ID(prev ID(bad))
+LARGE
+  )cpp");
+  EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("good")),
+  ValueIs(SameRange(findSpelled("good";
+  EXPECT_EQ(Buffer.spelledForExpanded(findExpanded("bad")), llvm::None);
+
+  recordTokens(R"cpp(
+#define PREV prev
+#define ID(X) X
+PREV ID(good)
+#define LARGE PREV ID(bad)
+LARGE
+  )cpp");
+  EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("good")),
+ValueIs(SameRange(findSpelled("good";
+  EXPECT_EQ(Buffer.spelledForExpanded(findExpanded("bad")), llvm::None);
+
+  recordTokens(R"cpp(
+#define ID(X) X
+#define ID2(X, Y) X Y
+ID2(prev, ID(good))
+#define LARGE ID2(prev, bad)
+LARGE
+  )cpp");
+  EXPECT_THAT(Buffer.spelledForExpanded(findExpanded("good")),
+ValueIs(SameRange(findSpelled("good";
+  EXPECT_EQ(Buffer.spelledForExpanded(findExpanded("bad")), llvm::None);
 }
 
 TEST_F(TokenBufferTest, ExpandedTokensForRange) {
Index: clang/lib/Tooling/Syntax/Tokens.cpp
===
--- clang/lib/Tooling/Syntax/Tokens.cpp
+++ clang/lib/Tooling/Syntax/Tokens.cpp
@@ -55,45 +55,140 @@
   return {Begin, End};
 }
 
-// Finds the smallest expansion range that contains expanded tokens First and
-// Last, e.g.:
+// Finds the range within FID corresponding to expanded tokens [First, Last].
+// Prev precedes First and Next follows Last, these must *not* be included.
+// If no range satisfies the criteria, returns an invalid range.
+//
 // #define ID(x) x
 // ID(ID(ID(a1) a2))
 //  ~~   -> a1
 //  ~~   -> a2
 //   ~   -> a1 a2
-SourceRange findCommonRangeForMacroArgs(const syntax::Token &First,
-const syntax::Token &Last,
-const SourceManager &SM) {
-  SourceRange Res;
-  auto FirstLoc = First.location(), LastLoc = Last.location();
-  // Keep traversing up the spelling chain as longs as tokens are part of the
-  // same expansion.
-  while (!FirstLoc.isFileID() && !LastLoc.isFileID()) {
-auto ExpInfoFirst = SM.getSLocEntry(SM.getFileID(FirstLoc)).getExpansion();
-auto ExpInfoLast = SM.getSLocEntry(SM.getFileID(LastLoc)).getExpansion();
-// Stop if expansions have diverged.
-if (ExpInfoFirst.getExpansionLocStart() !=
-ExpInfoLast.getExpansionLocStart())
+SourceRange spelledForExpandedSlow(SourceLocation First, SourceLocation Last,
+   SourceLocation Prev, SourceLocation Next,
+   FileID TargetFile,
+   const SourceManager &SM) {
+  // There are two main parts to this algorithm:
+  //  - identifying which spelled range covers the expanded tokens
+  //  - validating that this range doesn't cover any extra tokens (First/Last)
+  //
+  // We do these in order. However as we transform the expanded range into the
+  // spelled one, we adjust First/Last so the validation remains simple.
+
+  assert(SM.getSLocEntry(TargetFile).isFile());
+  // In most cases, to 

[PATCH] D134617: [HLSL] Support register binding attribute on global variable

2022-10-05 Thread Xiang Li via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
python3kgae marked an inline comment as done.
Closed by commit rG15aa64301ab1: [HLSL] Support register binding attribute on 
global variable (authored by python3kgae).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134617

Files:
  clang/include/clang/Basic/Attr.td
  clang/include/clang/Parse/Parser.h
  clang/lib/Parse/ParseDecl.cpp
  clang/test/AST/HLSL/resource_binding_attr.hlsl
  clang/test/SemaHLSL/resource_binding_attr_error.hlsl

Index: clang/test/SemaHLSL/resource_binding_attr_error.hlsl
===
--- clang/test/SemaHLSL/resource_binding_attr_error.hlsl
+++ clang/test/SemaHLSL/resource_binding_attr_error.hlsl
@@ -1,10 +1,6 @@
 // RUN: %clang_cc1 -triple dxil-pc-shadermodel6.3-library -x hlsl -o - -fsyntax-only %s -verify
 
-// expected-error@+5 {{expected ';' after top level declarator}}
-// expected-error@+4 {{expected ')'}}
-// expected-note@+3 {{to match this '('}}
-// expected-error@+2 {{a type specifier is required for all declarations}}
-// expected-error@+1 {{illegal storage class on file-scoped variable}}
+// expected-error@+1 {{invalid resource class specifier 'c' used; expected 'b', 's', 't', or 'u'}}
 float a : register(c0, space1);
 
 // expected-error@+1 {{invalid resource class specifier 'i' used; expected 'b', 's', 't', or 'u'}}
@@ -36,3 +32,29 @@
 // expected-error@+2 {{wrong argument format for hlsl attribute, use b2 instead}}
 // expected-error@+1 {{wrong argument format for hlsl attribute, use space3 instead}}
 cbuffer D : register(b 2, space 3) {}
+
+// expected-warning@+1 {{'register' attribute only applies to cbuffer/tbuffer and external global variables}}
+static RWBuffer U : register(u5);
+
+void foo() {
+  // expected-warning@+1 {{'register' attribute only applies to cbuffer/tbuffer and external global variables}}
+  RWBuffer U : register(u3);
+}
+void foo2() {
+  // expected-warning@+1 {{'register' attribute only applies to cbuffer/tbuffer and external global variables}}
+  extern RWBuffer U2 : register(u5);
+}
+// FIXME: expect-error once fix https://github.com/llvm/llvm-project/issues/57886.
+float b : register(u0, space1);
+
+// expected-warning@+1 {{'register' attribute only applies to cbuffer/tbuffer and external global variables}}
+void bar(RWBuffer U : register(u3)) {
+
+}
+
+struct S {
+  // FIXME: generate better error when support semantic on struct field.
+  // See https://github.com/llvm/llvm-project/issues/57889.
+  // expected-error@+1 {{expected expression}}
+  RWBuffer U : register(u3);
+};
Index: clang/test/AST/HLSL/resource_binding_attr.hlsl
===
--- clang/test/AST/HLSL/resource_binding_attr.hlsl
+++ clang/test/AST/HLSL/resource_binding_attr.hlsl
@@ -22,3 +22,16 @@
 // CHECK-NEXT: DeclRefExpr 0x{{[0-9a-f]+}}  'float' lvalue Var 0x[[B]] 'b' 'float'
   return a + b;
 }
+
+// CHECK: VarDecl 0x{{[0-9a-f]+}} <{{.*}}> col:17 UAV 'RWBuffer':'hlsl::RWBuffer<>' callinit
+// CHECK-NEXT:-CXXConstructExpr 0x{{[0-9a-f]+}}  'RWBuffer':'hlsl::RWBuffer<>' 'void ()'
+// CHECK-NEXT:-HLSLResourceBindingAttr 0x{{[0-9a-f]+}}  "u3" "space0"
+RWBuffer UAV : register(u3);
+
+// CHECK: -VarDecl 0x{{[0-9a-f]+}} <{{.*}}> col:17 UAV1 'RWBuffer':'hlsl::RWBuffer<>' callinit
+// CHECK-NEXT:-CXXConstructExpr 0x{{[0-9a-f]+}}  'RWBuffer':'hlsl::RWBuffer<>' 'void ()'
+// CHECK-NEXT:-HLSLResourceBindingAttr 0x{{[0-9a-f]+}}  "u2" "space0"
+// CHECK-NEXT:-VarDecl 0x{{[0-9a-f]+}}  col:38 UAV2 'RWBuffer':'hlsl::RWBuffer<>' callinit
+// CHECK-NEXT:-CXXConstructExpr 0x{{[0-9a-f]+}}  'RWBuffer':'hlsl::RWBuffer<>' 'void ()'
+// CHECK-NEXT:-HLSLResourceBindingAttr 0x{{[0-9a-f]+}}  "u4" "space0"
+RWBuffer UAV1 : register(u2), UAV2 : register(u4);
Index: clang/lib/Parse/ParseDecl.cpp
===
--- clang/lib/Parse/ParseDecl.cpp
+++ clang/lib/Parse/ParseDecl.cpp
@@ -2054,6 +2054,9 @@
 return nullptr;
   }
 
+  if (getLangOpts().HLSL)
+MaybeParseHLSLSemantics(D);
+
   if (Tok.is(tok::kw_requires))
 ParseTrailingRequiresClause(D);
 
@@ -2223,6 +2226,10 @@
   DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
 
 ParseDeclarator(D);
+
+if (getLangOpts().HLSL)
+  MaybeParseHLSLSemantics(D);
+
 if (!D.isInvalidType()) {
   // C++2a [dcl.decl]p1
   //init-declarator:
@@ -7165,7 +7172,8 @@
 
 // Parse GNU attributes, if present.
 MaybeParseGNUAttributes(ParmDeclarator);
-MaybeParseHLSLSemantics(DS.getAttributes());
+if (getLangOpts().HLSL)
+  MaybeParseHLSLSemantics(DS.getAttributes());
 
 if (Tok.is(tok::kw_requires)) {
   // User tried to define a requires clause in a parameter declaration,
Index: clang/include/clang/Parse/Parser.h
===
--- clang

[clang] 15aa643 - [HLSL] Support register binding attribute on global variable

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

Author: Xiang Li
Date: 2022-10-05T09:23:35-07:00
New Revision: 15aa64301ab146dec7c6ffcd0418ed834bf099e2

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

LOG: [HLSL] Support register binding attribute on global variable

Allow register binding attribute on variables.

Report warning when register binding attribute applies to local variable or 
static variable.
It will be ignored in this case.

Type check for register binding is tracked with 
https://github.com/llvm/llvm-project/issues/57886.

Reviewed By: aaron.ballman

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

Added: 


Modified: 
clang/include/clang/Basic/Attr.td
clang/include/clang/Parse/Parser.h
clang/lib/Parse/ParseDecl.cpp
clang/test/AST/HLSL/resource_binding_attr.hlsl
clang/test/SemaHLSL/resource_binding_attr_error.hlsl

Removed: 




diff  --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 1bfe4b6c48a2b..fa718b51d8134 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -133,6 +133,12 @@ def SharedVar : SubsetSubjecthasGlobalStorage()}], "global variables">;
 
+def ExternalGlobalVar : SubsetSubjecthasGlobalStorage() &&
+   S->getStorageClass()!=StorageClass::SC_Static &&
+   !S->isLocalExternDecl()}],
+ "external global variables">;
+
 def InlineFunction : SubsetSubjectisInlineSpecified()}], "inline functions">;
 
@@ -3992,7 +3998,7 @@ def HLSLSV_GroupIndex: HLSLAnnotationAttr {
 
 def HLSLResourceBinding: InheritableAttr {
   let Spellings = [HLSLSemantic<"register">];
-  let Subjects = SubjectList<[HLSLBufferObj, GlobalVar]>;
+  let Subjects = SubjectList<[HLSLBufferObj, ExternalGlobalVar]>;
   let LangOpts = [HLSL];
   let Args = [StringArgument<"Slot">, StringArgument<"Space", 1>];
   let Documentation = [HLSLResourceBindingDocs];

diff  --git a/clang/include/clang/Parse/Parser.h 
b/clang/include/clang/Parse/Parser.h
index cb396b8b54122..c518ce5487bd8 100644
--- a/clang/include/clang/Parse/Parser.h
+++ b/clang/include/clang/Parse/Parser.h
@@ -2881,8 +2881,19 @@ class Parser : public CodeCompletionHandler {
   Sema::AttributeCompletion Completion = Sema::AttributeCompletion::None,
   const IdentifierInfo *EnclosingScope = nullptr);
 
+  void MaybeParseHLSLSemantics(Declarator &D,
+   SourceLocation *EndLoc = nullptr) {
+assert(getLangOpts().HLSL && "MaybeParseHLSLSemantics is for HLSL only");
+if (Tok.is(tok::colon)) {
+  ParsedAttributes Attrs(AttrFactory);
+  ParseHLSLSemantics(Attrs, EndLoc);
+  D.takeAttributes(Attrs);
+}
+  }
+
   void MaybeParseHLSLSemantics(ParsedAttributes &Attrs,
SourceLocation *EndLoc = nullptr) {
+assert(getLangOpts().HLSL && "MaybeParseHLSLSemantics is for HLSL only");
 if (getLangOpts().HLSL && Tok.is(tok::colon))
   ParseHLSLSemantics(Attrs, EndLoc);
   }

diff  --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp
index dfedbf5b2d779..ddb83a8c6694d 100644
--- a/clang/lib/Parse/ParseDecl.cpp
+++ b/clang/lib/Parse/ParseDecl.cpp
@@ -2054,6 +2054,9 @@ Parser::DeclGroupPtrTy 
Parser::ParseDeclGroup(ParsingDeclSpec &DS,
 return nullptr;
   }
 
+  if (getLangOpts().HLSL)
+MaybeParseHLSLSemantics(D);
+
   if (Tok.is(tok::kw_requires))
 ParseTrailingRequiresClause(D);
 
@@ -2223,6 +2226,10 @@ Parser::DeclGroupPtrTy 
Parser::ParseDeclGroup(ParsingDeclSpec &DS,
   DiagnoseAndSkipExtendedMicrosoftTypeAttributes();
 
 ParseDeclarator(D);
+
+if (getLangOpts().HLSL)
+  MaybeParseHLSLSemantics(D);
+
 if (!D.isInvalidType()) {
   // C++2a [dcl.decl]p1
   //init-declarator:
@@ -7165,7 +7172,8 @@ void Parser::ParseParameterDeclarationClause(
 
 // Parse GNU attributes, if present.
 MaybeParseGNUAttributes(ParmDeclarator);
-MaybeParseHLSLSemantics(DS.getAttributes());
+if (getLangOpts().HLSL)
+  MaybeParseHLSLSemantics(DS.getAttributes());
 
 if (Tok.is(tok::kw_requires)) {
   // User tried to define a requires clause in a parameter declaration,

diff  --git a/clang/test/AST/HLSL/resource_binding_attr.hlsl 
b/clang/test/AST/HLSL/resource_binding_attr.hlsl
index ecb7e3ab98db5..683607197 100644
--- a/clang/test/AST/HLSL/resource_binding_attr.hlsl
+++ b/clang/test/AST/HLSL/resource_binding_attr.hlsl
@@ -22,3 +22,16 @@ float foo() {
 // CHECK-NEXT: DeclRefExpr 0x{{[0-9a-f]+}}  'float' lvalue Var 0x[[B]] 
'b' 'float'
   return a + b;
 }
+
+// CHECK: VarDecl 0x{{[0-9a-f]+}} <{{.*}}> col:17 UAV 
'RWBuffer':'hlsl::RWBuffer<>' callinit
+// CHECK-NEXT:-CXXConstructExpr 0x{{[0-9a-f]+}}  
'RWBuffer':'hlsl::RWBuffer<>' 'void ()'
+// CHECK-NEXT

[PATCH] D134685: Fix SourceManager::isBeforeInTranslationUnit bug with token-pasting

2022-10-05 Thread Sam McCall via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
sammccall marked an inline comment as done.
Closed by commit rG41b51007e637: Fix SourceManager::isBeforeInTranslationUnit 
bug with token-pasting (authored by sammccall).

Changed prior to commit:
  https://reviews.llvm.org/D134685?vs=463053&id=465437#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134685

Files:
  clang-tools-extra/clangd/unittests/SelectionTests.cpp
  clang/include/clang/Basic/SourceManager.h
  clang/lib/Basic/SourceManager.cpp
  clang/unittests/Basic/SourceManagerTest.cpp

Index: clang/unittests/Basic/SourceManagerTest.cpp
===
--- clang/unittests/Basic/SourceManagerTest.cpp
+++ clang/unittests/Basic/SourceManagerTest.cpp
@@ -171,6 +171,83 @@
   EXPECT_TRUE(SourceMgr.isBeforeInTranslationUnit(idLoc, macroExpEndLoc));
 }
 
+TEST_F(SourceManagerTest, isBeforeInTranslationUnitWithTokenSplit) {
+  const char *main = R"cpp(
+#define ID(X) X
+ID(
+  ID(a >> b)
+  c
+)
+  )cpp";
+
+  SourceMgr.setMainFileID(
+  SourceMgr.createFileID(llvm::MemoryBuffer::getMemBuffer(main)));
+
+  TrivialModuleLoader ModLoader;
+  HeaderSearch HeaderInfo(std::make_shared(), SourceMgr,
+  Diags, LangOpts, &*Target);
+  Preprocessor PP(std::make_shared(), Diags, LangOpts,
+  SourceMgr, HeaderInfo, ModLoader,
+  /*IILookup =*/nullptr,
+  /*OwnsHeaderSearch =*/false);
+  PP.Initialize(*Target);
+  PP.EnterMainSourceFile();
+  llvm::SmallString<8> Scratch;
+
+  std::vector toks;
+  while (1) {
+Token tok;
+PP.Lex(tok);
+if (tok.is(tok::eof))
+  break;
+toks.push_back(tok);
+  }
+
+  // Make sure we got the tokens that we expected.
+  ASSERT_EQ(4U, toks.size()) << "a >> b c";
+  // Sanity check their order.
+  for (unsigned I = 0; I < toks.size() - 1; ++I) {
+EXPECT_TRUE(SourceMgr.isBeforeInTranslationUnit(toks[I].getLocation(),
+toks[I + 1].getLocation()));
+EXPECT_FALSE(SourceMgr.isBeforeInTranslationUnit(toks[I + 1].getLocation(),
+ toks[I].getLocation()));
+  }
+
+  // Split the >> into two > tokens, as happens when parsing nested templates.
+  unsigned RightShiftIndex = 1;
+  SourceLocation RightShift = toks[RightShiftIndex].getLocation();
+  EXPECT_EQ(">>", Lexer::getSpelling(SourceMgr.getSpellingLoc(RightShift),
+ Scratch, SourceMgr, LangOpts));
+  SourceLocation Greater1 = PP.SplitToken(RightShift, /*Length=*/1);
+  SourceLocation Greater2 = RightShift.getLocWithOffset(1);
+  EXPECT_TRUE(Greater1.isMacroID());
+  EXPECT_EQ(">", Lexer::getSpelling(SourceMgr.getSpellingLoc(Greater1), Scratch,
+SourceMgr, LangOpts));
+  EXPECT_EQ(">", Lexer::getSpelling(SourceMgr.getSpellingLoc(Greater2), Scratch,
+SourceMgr, LangOpts));
+  EXPECT_EQ(SourceMgr.getImmediateExpansionRange(Greater1).getBegin(),
+RightShift);
+
+  for (unsigned I = 0; I < toks.size(); ++I) {
+SCOPED_TRACE("Token " + std::to_string(I));
+// Right-shift is the parent of Greater1, so it compares less.
+EXPECT_EQ(
+SourceMgr.isBeforeInTranslationUnit(toks[I].getLocation(), Greater1),
+I <= RightShiftIndex);
+EXPECT_EQ(
+SourceMgr.isBeforeInTranslationUnit(toks[I].getLocation(), Greater2),
+I <= RightShiftIndex);
+EXPECT_EQ(
+SourceMgr.isBeforeInTranslationUnit(Greater1, toks[I].getLocation()),
+RightShiftIndex < I);
+EXPECT_EQ(
+SourceMgr.isBeforeInTranslationUnit(Greater2, toks[I].getLocation()),
+RightShiftIndex < I);
+  }
+  EXPECT_TRUE(SourceMgr.isBeforeInTranslationUnit(Greater1, Greater2));
+  EXPECT_FALSE(SourceMgr.isBeforeInTranslationUnit(Greater2, Greater1));
+}
+
 TEST_F(SourceManagerTest, getColumnNumber) {
   const char *Source =
 "int x;\n"
Index: clang/lib/Basic/SourceManager.cpp
===
--- clang/lib/Basic/SourceManager.cpp
+++ clang/lib/Basic/SourceManager.cpp
@@ -1992,6 +1992,7 @@
   // This is a magic number for limiting the cache size.  It was experimentally
   // derived from a small Objective-C project (where the cache filled
   // out to ~250 items).  We can make it larger if necessary.
+  // FIXME: this is almost certainly full these days. Use an LRU cache?
   enum { MagicCacheSize = 300 };
   IsBeforeInTUCacheKey Key(LFID, RFID);
 
@@ -2000,7 +2001,7 @@
   // use.  When they update the value, the cache will get automatically
   // updated as well.
   if (IBTUCache.size() < MagicCacheSize)
-return IBTUCache[Key];
+return IBTUCache.try_emplace(Key, LFID, R

[clang] 41b5100 - Fix SourceManager::isBeforeInTranslationUnit bug with token-pasting

2022-10-05 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2022-10-05T18:29:01+02:00
New Revision: 41b51007e6376cba72b00fb655a63b06c554d4e1

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

LOG: Fix SourceManager::isBeforeInTranslationUnit bug with token-pasting

isBeforeInTranslationUnit compares SourceLocations across FileIDs by
mapping them onto a common ancestor file, following include/expansion edges.

It is possible to get a tie in the common ancestor, because multiple
"chunks" of a macro arg will expand to the same macro param token in the body:
  #define ID(X) X
  #define TWO 2
  ID(1 TWO)
Here two FileIDs both expand into `X` in ID's expansion:
 - one containing `1` and spelled on line 3
 - one containing `2` and spelled by the macro expansion of TWO
isBeforeInTranslationUnit breaks this tie by comparing the two FileIDs:
the one "on the left" is always created first and is numerically smaller.
This seems correct so far.

Prior to this patch it also takes a shortcut (unclear if intentionally).
Instead of comparing the two FileIDs that directly expand to the same location,
it compares the original FileIDs being compared. These may not be the
same if there are multiple macro expansions in between.
This *almost* always yields the right answer, because macro expansion
yields "trees" of FileIDs allocated in a contiguous range: when comparing tree A
to tree B, it doesn't matter what representative you pick.

However, the splitting of >> tokens is modeled as macro expansion (as if
the first '>' was a macro that expands to a '>' spelled a scratch buffer).
This splitting occurs retroactively when parsing, so the FileID allocated is
larger than expected if it were a real macro expansion performed during lexing.
As a result, macro tree A can be on the left of tree B, and yet contain
a token-split FileID whose numeric value is *greator* than those in B.
In this case the tiebreak gives the wrong answer.

Concretely:
  #define ID(X) X
  template  class S{};
  ID(
ID(S> x);
int y;
  )

  Given Greater = (typeloc of S).getEndLoc();
Y   = (decl of y).getLocation();
  isBeforeInTranslationUnit(Greater, Y) should return true, but returns false.

Here the common FileID of (Greater, Y) is the body of the outer ID
expansion, and they both expand to X within it.
With the current tiebreak rules, we compare the FileID of Greater (a split)
to the FileID of Y (a macro arg expansion into X of the outer ID).
The former is larger because the token split occurred relatively late.

This patch fixes the issue by removing the shortcut. It tracks the immediate
FileIDs used to reach the common file, and uses these IDs to break ties.
In the example, we now compare the macro arg expansion of the inner ID()
to the macro arg expansion of Y, and find that it is smaller.

This requires some changes to the InBeforeInTUCacheEntry (sic).
We store a little more data so it's probably slightly slower.
It was difficult to resist more invasive changes:
 - performance: the sizing is very suspicious, and once the cache "fills up"
   we're thrashing a single entry
 - API: the class seems to be needlessly complicated
However I tried to avoid mixing these with subtle behavior changes, and
will send a followup instead.

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

Added: 


Modified: 
clang-tools-extra/clangd/unittests/SelectionTests.cpp
clang/include/clang/Basic/SourceManager.h
clang/lib/Basic/SourceManager.cpp
clang/unittests/Basic/SourceManagerTest.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/unittests/SelectionTests.cpp 
b/clang-tools-extra/clangd/unittests/SelectionTests.cpp
index b44d9a6afe7ae..239566a35861e 100644
--- a/clang-tools-extra/clangd/unittests/SelectionTests.cpp
+++ b/clang-tools-extra/clangd/unittests/SelectionTests.cpp
@@ -706,8 +706,24 @@ TEST(SelectionTest, MacroArgExpansion) {
   Test = Annotations(Case);
   AST = TestTU::withCode(Test.code()).build();
   T = makeSelectionTree(Case, AST);
-
   EXPECT_EQ("IntegerLiteral", T.commonAncestor()->kind());
+
+  // Reduced from private bug involving RETURN_IF_ERROR.
+  // Due to >>-splitting and a bug in isBeforeInTranslationUnit, the inner
+  // S would claim way too many tokens.
+  Case = R"cpp(
+#define ID(x) x
+template  class S {};
+ID(
+  ID(S> x);
+  int ^y;
+)
+  )cpp";
+  Test = Annotations(Case);
+  AST = TestTU::withCode(Test.code()).build();
+  T = makeSelectionTree(Case, AST);
+  // not TemplateSpecializationTypeLoc!
+  EXPECT_EQ("VarDecl", T.commonAncestor()->kind());
 }
 
 TEST(SelectionTest, Implicit) {

diff  --git a/clang/include/clang/Basic/SourceManager.h 
b/clang/include/clang/Basic/SourceManager.h
index ad371da0560a3..8a737d6b4b398 100644
--- a/clang/include/clang/Basic/SourceManager.h
+++ b/

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

2022-10-05 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/include/clang/Sema/SemaConcept.h:51
+  // QualType of constrained template template parameter is not the same as
+  // its tailing version, so give it a pass here.
+  if (LHS.getKind() == TemplateArgument::Type &&

what do you mean by 'tailing' here?



Comment at: clang/include/clang/Sema/SemaConcept.h:58
+cast(RHS.getAsType())->getIndex())
+  continue;
+  }

What exactly is going on here?  I would expect the 'AdjustConstraintDepth' work 
to have already made these basically equal.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134128

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


[PATCH] D135226: [clangd] Optimize Dex::generateProximityURIs().

2022-10-05 Thread Adam Czachorowski via Phabricator via cfe-commits
adamcz added inline comments.



Comment at: clang-tools-extra/clangd/index/dex/Dex.cpp:358
+// Returns^
+const char *findPathInURI(const char *S) {
+  // Skip over scheme.

Is there a reason why you're doing this with manual manipulation of C-strings 
instead of StringRefs? I suspect passing StringRef here was not the problem, 
turning it into an std::string, from another std::string inside ParsedURI was.

Something like:
S = S.drop_while([](char c) { return c == ':'; });
S.consume_front(":");
if (S.consume_front("//")) {
  S = S.drop_while([](char c) { return c == '/'; });
  S.consume_front("/");
}

return S;

would be a bit more readable and less likely to have an off-by-one somewhere, 
imho.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135226

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


[PATCH] D135232: [modules] Allow to validate system headers less often with `-fmodules-validate-once-per-build-session`.

2022-10-05 Thread Juergen Ributzka via Phabricator via cfe-commits
ributzka added a comment.

This makes sense. We shouldn't re-validate system headers when 
`-fmodules-validate-once-per-build-session` is passed too.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135232

___
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-05 Thread Xiang Li via Phabricator via cfe-commits
python3kgae updated this revision to Diff 465441.
python3kgae added a comment.

Update to match comments


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


[PATCH] D135220: [clang] Update ModuleMap::getModuleMapFile* to use FileEntryRef

2022-10-05 Thread Ben Barham via Phabricator via cfe-commits
bnbarham accepted this revision.
bnbarham added inline comments.



Comment at: clang/include/clang/Basic/SourceManager.h:146-155
   /// References the file which the contents were actually loaded from.
   ///
   /// Can be different from 'Entry' if we overridden the contents of one file
   /// with the contents of another file.
   const FileEntry *ContentsEntry;
 
   /// The filename that is used to access OrigEntry.

I haven't checked all uses, but do we still need all of 
`OrigEntry`/`ContentsEntry`/`Filename`? Seems like a single `FileEntryRef` 
should encapsulate all the information we need there.



Comment at: clang/include/clang/Basic/SourceManager.h:1062
+Optional F = sloc.getFile().getContentCache().OrigEntry;
+return F ? &F->getFileEntry() : nullptr;
   }

jansvoboda11 wrote:
> Could you wrap `F` in `OptionalFileEntryRefDegradesToFileEntryPtr` to handle 
> the conversion for you?
`OrigEntry` is a `OptionalFileEntryRefDegradesToFileEntryPtr`, so this should 
just be able to be `return slot.getFile().getContentCache().OrigEntry`?



Comment at: clang/lib/Lex/ModuleMap.cpp:1030
+Optional ModuleMapRef = getModuleMapFileForUniquing(Parent);
+ModuleMapFile = ModuleMapRef ? *ModuleMapRef : nullptr;
+  }

jansvoboda11 wrote:
> Nit: Use `OptionalFileEntryRefDegradesToFileEntryPtr`? Maybe we should return 
> that from `getModuleMapFileForUniquing` in the first place.
I like the idea of returning `OptionalFileEntryRefDegradesToFileEntryPtr` until 
we move all this to use `FileEntryRef` as well.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135220

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


[PATCH] D135175: [clang] adds `__is_bounded_array` and `__is_unbounded_array` as builtins

2022-10-05 Thread Shafik Yaghmour via Phabricator via cfe-commits
shafik added a comment.

Looks good but let's have Aaron check it out.




Comment at: clang/lib/Sema/SemaExprCXX.cpp:24
 #include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/AST/Type.h"
 #include "clang/AST/TypeLoc.h"

Why also `Type.h`?



Comment at: clang/lib/Sema/SemaType.cpp:2630
 // CUDA device code and some other targets don't support VLAs.
-targetDiag(Loc, (getLangOpts().CUDA && getLangOpts().CUDAIsDevice)
-? diag::err_cuda_vla
-: diag::err_vla_unsupported)
-<< ((getLangOpts().CUDA && getLangOpts().CUDAIsDevice)
-? CurrentCUDATarget()
-: CFT_InvalidTarget);
+bool IsCUDADevice = (getLangOpts().CUDA && getLangOpts().CUDAIsDevice);
+targetDiag(Loc,

This feels like an unrelated change.

Is this diagnostic tested anywhere?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135175

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


[PATCH] D135011: Add builtin_elementwise_sin and builtin_elementwise_cos

2022-10-05 Thread Joshua Batista via Phabricator via cfe-commits
bob80905 updated this revision to Diff 465446.
bob80905 added a comment.

- shorten builtin description, group sin and cos


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135011

Files:
  clang/docs/LanguageExtensions.rst
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/Builtins.def
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Sema/SemaChecking.cpp
  clang/test/CodeGen/builtins-elementwise-math.c
  clang/test/Sema/aarch64-sve-vector-trig-ops.c
  clang/test/Sema/builtins-elementwise-math.c
  clang/test/Sema/riscv-sve-vector-trig-ops.c
  clang/test/SemaCXX/builtins-elementwise-math.cpp

Index: clang/test/SemaCXX/builtins-elementwise-math.cpp
===
--- clang/test/SemaCXX/builtins-elementwise-math.cpp
+++ clang/test/SemaCXX/builtins-elementwise-math.cpp
@@ -59,3 +59,17 @@
   static_assert(!is_const::value);
   static_assert(!is_const::value);
 }
+
+void test_builtin_elementwise_cos() {
+  const float a = 42.0;
+  float b = 42.3;
+  static_assert(!is_const::value);
+  static_assert(!is_const::value);
+}
+
+void test_builtin_elementwise_sin() {
+  const float a = 42.0;
+  float b = 42.3;
+  static_assert(!is_const::value);
+  static_assert(!is_const::value);
+}
Index: clang/test/Sema/riscv-sve-vector-trig-ops.c
===
--- /dev/null
+++ clang/test/Sema/riscv-sve-vector-trig-ops.c
@@ -0,0 +1,18 @@
+// RUN: %clang_cc1 -triple riscv64 -target-feature +f -target-feature +d \
+// RUN:   -target-feature +v -target-feature +zfh -target-feature +experimental-zvfh \
+// RUN:   -disable-O0-optnone -o - -fsyntax-only %s -verify 
+
+#include 
+
+
+vfloat32mf2_t test_sin_vv_i8mf8(vfloat32mf2_t v) {
+
+  return __builtin_elementwise_sin(v);
+  // expected-error@-1 {{1st argument must be a vector, integer or floating point type}}
+}
+
+vfloat32mf2_t test_cos_vv_i8mf8(vfloat32mf2_t v) {
+
+  return __builtin_elementwise_cos(v);
+  // expected-error@-1 {{1st argument must be a vector, integer or floating point type}}
+}
Index: clang/test/Sema/builtins-elementwise-math.c
===
--- clang/test/Sema/builtins-elementwise-math.c
+++ clang/test/Sema/builtins-elementwise-math.c
@@ -280,6 +280,27 @@
   // expected-error@-1 {{1st argument must be a floating point type (was 'unsigned4' (vector of 4 'unsigned int' values))}}
 }
 
+void test_builtin_elementwise_cos(int i, float f, double d, float4 v, int3 iv, unsigned u, unsigned4 uv) {
+
+  struct Foo s = __builtin_elementwise_cos(f);
+  // expected-error@-1 {{initializing 'struct Foo' with an expression of incompatible type 'float'}}
+
+  i = __builtin_elementwise_cos();
+  // expected-error@-1 {{too few arguments to function call, expected 1, have 0}}
+
+  i = __builtin_elementwise_cos(i);
+  // expected-error@-1 {{1st argument must be a floating point type (was 'int')}}
+
+  i = __builtin_elementwise_cos(f, f);
+  // expected-error@-1 {{too many arguments to function call, expected 1, have 2}}
+
+  u = __builtin_elementwise_cos(u);
+  // expected-error@-1 {{1st argument must be a floating point type (was 'unsigned int')}}
+
+  uv = __builtin_elementwise_cos(uv);
+  // expected-error@-1 {{1st argument must be a floating point type (was 'unsigned4' (vector of 4 'unsigned int' values))}}
+}
+
 void test_builtin_elementwise_floor(int i, float f, double d, float4 v, int3 iv, unsigned u, unsigned4 uv) {
 
   struct Foo s = __builtin_elementwise_floor(f);
@@ -322,6 +343,27 @@
   // expected-error@-1 {{1st argument must be a floating point type (was 'unsigned4' (vector of 4 'unsigned int' values))}}
 }
 
+void test_builtin_elementwise_sin(int i, float f, double d, float4 v, int3 iv, unsigned u, unsigned4 uv) {
+
+  struct Foo s = __builtin_elementwise_sin(f);
+  // expected-error@-1 {{initializing 'struct Foo' with an expression of incompatible type 'float'}}
+
+  i = __builtin_elementwise_sin();
+  // expected-error@-1 {{too few arguments to function call, expected 1, have 0}}
+
+  i = __builtin_elementwise_sin(i);
+  // expected-error@-1 {{1st argument must be a floating point type (was 'int')}}
+
+  i = __builtin_elementwise_sin(f, f);
+  // expected-error@-1 {{too many arguments to function call, expected 1, have 2}}
+
+  u = __builtin_elementwise_sin(u);
+  // expected-error@-1 {{1st argument must be a floating point type (was 'unsigned int')}}
+
+  uv = __builtin_elementwise_sin(uv);
+  // expected-error@-1 {{1st argument must be a floating point type (was 'unsigned4' (vector of 4 'unsigned int' values))}}
+}
+
 void test_builtin_elementwise_trunc(int i, float f, double d, float4 v, int3 iv, unsigned u, unsigned4 uv) {
 
   struct Foo s = __builtin_elementwise_trunc(f);
Index: clang/test/Sema/aarch64-sve-vector-trig-ops.c
===
--- /dev/null
+++ clang/te

[PATCH] D135285: [OpenMP] Make the exec_mode global have protected visibility

2022-10-05 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 created this revision.
jhuber6 added reviewers: jdoerfert, tianshilei1992, JonChesterfield, ronlieb, 
ABataev.
Herald added subscribers: mattd, asavonic, guansong, yaxunl.
Herald added a project: All.
jhuber6 requested review of this revision.
Herald added subscribers: cfe-commits, sstefan1.
Herald added a project: clang.

We use protected visibility for almost everything with offloading. This
is because it provides us with the ability to read things from the host
without the expectation that it will be preempted by a shared library
load, bugs related to this have happened when offloading to the host.
This patch just makes the `exec_mode` global generated for each plugin
have protected visibility.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D135285

Files:
  clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
  clang/test/OpenMP/nvptx_target_parallel_proc_bind_codegen.cpp
  clang/test/OpenMP/nvptx_target_parallel_reduction_codegen.cpp
  clang/test/OpenMP/nvptx_target_simd_codegen.cpp
  clang/test/OpenMP/nvptx_target_teams_distribute_simd_codegen.cpp


Index: clang/test/OpenMP/nvptx_target_teams_distribute_simd_codegen.cpp
===
--- clang/test/OpenMP/nvptx_target_teams_distribute_simd_codegen.cpp
+++ clang/test/OpenMP/nvptx_target_teams_distribute_simd_codegen.cpp
@@ -16,10 +16,10 @@
 #define HEADER
 
 // Check that the execution mode of all 2 target regions on the gpu is set to 
NonSPMD Mode.
-// CHECK-DAG: {{@__omp_offloading_.+l37}}_exec_mode = weak constant i8 2
-// CHECK-DAG: {{@__omp_offloading_.+l43}}_exec_mode = weak constant i8 2
-// CHECK-DAG: {{@__omp_offloading_.+l48}}_exec_mode = weak constant i8 2
-// CHECK-DAG: {{@__omp_offloading_.+l53}}_exec_mode = weak constant i8 2
+// CHECK-DAG: {{@__omp_offloading_.+l37}}_exec_mode = weak protected constant 
i8 2
+// CHECK-DAG: {{@__omp_offloading_.+l43}}_exec_mode = weak protected constant 
i8 2
+// CHECK-DAG: {{@__omp_offloading_.+l48}}_exec_mode = weak protected constant 
i8 2
+// CHECK-DAG: {{@__omp_offloading_.+l53}}_exec_mode = weak protected constant 
i8 2
 
 #define N 1000
 #define M 10
Index: clang/test/OpenMP/nvptx_target_simd_codegen.cpp
===
--- clang/test/OpenMP/nvptx_target_simd_codegen.cpp
+++ clang/test/OpenMP/nvptx_target_simd_codegen.cpp
@@ -16,10 +16,10 @@
 #define HEADER
 
 // Check that the execution mode of all 2 target regions on the gpu is set to 
NonSPMD Mode.
-// CHECK-DAG: {{@__omp_offloading_.+l32}}_exec_mode = weak constant i8 2
-// CHECK-DAG: {{@__omp_offloading_.+l37}}_exec_mode = weak constant i8 2
-// CHECK-DAG: {{@__omp_offloading_.+l42}}_exec_mode = weak constant i8 2
-// CHECK-DAG: {{@__omp_offloading_.+l47}}_exec_mode = weak constant i8 2
+// CHECK-DAG: {{@__omp_offloading_.+l32}}_exec_mode = weak protected constant 
i8 2
+// CHECK-DAG: {{@__omp_offloading_.+l37}}_exec_mode = weak protected constant 
i8 2
+// CHECK-DAG: {{@__omp_offloading_.+l42}}_exec_mode = weak protected constant 
i8 2
+// CHECK-DAG: {{@__omp_offloading_.+l47}}_exec_mode = weak protected constant 
i8 2
 
 #define N 1000
 
Index: clang/test/OpenMP/nvptx_target_parallel_reduction_codegen.cpp
===
--- clang/test/OpenMP/nvptx_target_parallel_reduction_codegen.cpp
+++ clang/test/OpenMP/nvptx_target_parallel_reduction_codegen.cpp
@@ -12,9 +12,9 @@
 // CHECK-DAG: [[TRANSFER_STORAGE:@.+]] = weak 
addrspace([[SHARED_ADDRSPACE:[0-9]+]]) global [32 x i32]
 
 // Check that the execution mode of all 3 target regions is set to Spmd Mode.
-// CHECK-DAG: {{@__omp_offloading_.+l27}}_exec_mode = weak constant i8 2
-// CHECK-DAG: {{@__omp_offloading_.+l32}}_exec_mode = weak constant i8 2
-// CHECK-DAG: {{@__omp_offloading_.+l38}}_exec_mode = weak constant i8 2
+// CHECK-DAG: {{@__omp_offloading_.+l27}}_exec_mode = weak protected constant 
i8 2
+// CHECK-DAG: {{@__omp_offloading_.+l32}}_exec_mode = weak protected constant 
i8 2
+// CHECK-DAG: {{@__omp_offloading_.+l38}}_exec_mode = weak protected constant 
i8 2
 
 template
 tx ftemplate(int n) {
Index: clang/test/OpenMP/nvptx_target_parallel_proc_bind_codegen.cpp
===
--- clang/test/OpenMP/nvptx_target_parallel_proc_bind_codegen.cpp
+++ clang/test/OpenMP/nvptx_target_parallel_proc_bind_codegen.cpp
@@ -16,9 +16,9 @@
 #define HEADER
 
 // Check that the execution mode of all 3 target regions on the gpu is set to 
SPMD Mode.
-// CHECK-DAG: {{@__omp_offloading_.+l29}}_exec_mode = weak constant i8 2
-// CHECK-DAG: {{@__omp_offloading_.+l33}}_exec_mode = weak constant i8 2
-// CHECK-DAG: {{@__omp_offloading_.+l38}}_exec_mode = weak constant i8 2
+// CHECK-DAG: {{@__omp_offloading_.+l29}}_exec_mode = weak protected constant 
i8 2
+// CHECK-DAG: {{@__omp_offloading_.+l33}}_exec_mode = weak protected constant 
i8 2
+// CHECK-DAG: {{@__omp_offloading_.+l38}}_exe

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

2022-10-05 Thread Zixu Wang via Phabricator via cfe-commits
zixuw added a subscriber: QuietMisdreavus.
zixuw added a comment.

In D134813#3836836 , @aaron.ballman 
wrote:

>> I'd guess we need some kind of change to CommentXML and ExtractAPI, but I 
>> don't know enough to be sure what it should be.
>
> Ping @dang @zixuw and @dexonsmith for questions about how to handle 
> ExtractAPI changes, and @gribozavr for questions about CommentXML

Thanks for the heads up! Looking.

At a glance it seems that ExtractAPI would like to fall back to the original 
formats to not break downstream tooling. But not sure if it's fine because it's 
still consistent. As far as I can tell this only affects anonymous `TagDecl`s. 
@QuietMisdreavus thoughts?

IMO we would still want to keep the ExtractAPI outputs unchanged if it's easy 
enough to do. We're using `getName()/getQualifiedNameAsString()` for names and 
`index::generateUSRForDecl()` for USRs. Is there a 'policy' or some 
alternatives to use? Or is the location info now part of the 'correct' format 
for USRs (seems a bit weird to see that as part of the USR)?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134813

___
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-05 Thread Artem Belevich via Phabricator via cfe-commits
tra added a comment.

Is there more info about the issue? What does AMDGPU currently emit for the 
test case?

AFAICT from running it on CE (https://godbolt.org/z/ccq3vnbrM) llvm optimizes 
it to essentially `*y = *x` and generates a 1-byte load+store for both NVPTX 
and AMDGPU.


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

https://reviews.llvm.org/D135269

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


[PATCH] D135284: RFC: [Driver] select alternative target containing . in executable name

2022-10-05 Thread Dan McGregor via Phabricator via cfe-commits
dankm created this revision.
Herald added subscribers: pengfei, krytarowski, arichardson, emaste.
Herald added a project: All.
dankm added reviewers: echristo, zarko.
dankm added a comment.
dankm published this revision for review.
Herald added subscribers: cfe-commits, MaskRay.
Herald added a project: clang.

I'd like comments on this approach to handle target names with a . in them. My 
assumption is that the way it was done (by finding the filename stem) was to 
strip any ".exe" string on Windows, but there may be other reasons.


The gcc compatible driver has support for selecting an alternative
target based on the driver's executable name, for instance
x86_64-unknown-linux-gnu-clang will set the target to linux on x86_64.

Previously, this failed when the target contains a minor version, for
example x86_64-unknown-freebsd13.1, so instead of finding the file's
stem, use the whole file name, but strip off any '.exe' from the tail.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D135284

Files:
  clang/lib/Driver/ToolChain.cpp


Index: clang/lib/Driver/ToolChain.cpp
===
--- clang/lib/Driver/ToolChain.cpp
+++ clang/lib/Driver/ToolChain.cpp
@@ -198,7 +198,7 @@
 /// Normalize the program name from argv[0] by stripping the file extension if
 /// present and lower-casing the string on Windows.
 static std::string normalizeProgramName(llvm::StringRef Argv0) {
-  std::string ProgName = std::string(llvm::sys::path::stem(Argv0));
+  std::string ProgName = std::string(llvm::sys::path::filename(Argv0));
   if (is_style_windows(llvm::sys::path::Style::native)) {
 // Transform to lowercase for case insensitive file systems.
 std::transform(ProgName.begin(), ProgName.end(), ProgName.begin(),
@@ -217,6 +217,13 @@
   // added via -target as implicit first argument.
   const DriverSuffix *DS = FindDriverSuffix(ProgName, Pos);
 
+  if (!DS && ProgName.endswith(".exe")) {
+// Try again after stripping the executable suffix:
+// clang++.exe -> clang++
+ProgName = ProgName.drop_back(StringRef(".exe").size());
+DS = FindDriverSuffix(ProgName, Pos);
+  }
+
   if (!DS) {
 // Try again after stripping any trailing version number:
 // clang++3.5 -> clang++


Index: clang/lib/Driver/ToolChain.cpp
===
--- clang/lib/Driver/ToolChain.cpp
+++ clang/lib/Driver/ToolChain.cpp
@@ -198,7 +198,7 @@
 /// Normalize the program name from argv[0] by stripping the file extension if
 /// present and lower-casing the string on Windows.
 static std::string normalizeProgramName(llvm::StringRef Argv0) {
-  std::string ProgName = std::string(llvm::sys::path::stem(Argv0));
+  std::string ProgName = std::string(llvm::sys::path::filename(Argv0));
   if (is_style_windows(llvm::sys::path::Style::native)) {
 // Transform to lowercase for case insensitive file systems.
 std::transform(ProgName.begin(), ProgName.end(), ProgName.begin(),
@@ -217,6 +217,13 @@
   // added via -target as implicit first argument.
   const DriverSuffix *DS = FindDriverSuffix(ProgName, Pos);
 
+  if (!DS && ProgName.endswith(".exe")) {
+// Try again after stripping the executable suffix:
+// clang++.exe -> clang++
+ProgName = ProgName.drop_back(StringRef(".exe").size());
+DS = FindDriverSuffix(ProgName, Pos);
+  }
+
   if (!DS) {
 // Try again after stripping any trailing version number:
 // clang++3.5 -> clang++
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D135287: Disallow dereferencing of void* in C++.

2022-10-05 Thread Erich Keane via Phabricator via cfe-commits
erichkeane created this revision.
erichkeane added a reviewer: clang-language-wg.
Herald added a project: All.
erichkeane requested review of this revision.

as Discussed:
https://discourse.llvm.org/t/rfc-can-we-stop-the-extension-to-allow-dereferencing-void-in-c/65708

There is no good reason to allow this when the other compilers all
reject this, and it messes with SFINAE/constraint checking.


https://reviews.llvm.org/D135287

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaExpr.cpp
  clang/test/CXX/temp/temp.decls/temp.class/temp.mem.func/p1inst.cpp
  clang/test/SemaCXX/disallow_void_deref.cpp
  clang/test/SemaCXX/reinterpret-cast.cpp

Index: clang/test/SemaCXX/reinterpret-cast.cpp
===
--- clang/test/SemaCXX/reinterpret-cast.cpp
+++ clang/test/SemaCXX/reinterpret-cast.cpp
@@ -214,11 +214,11 @@
   (void)*reinterpret_cast(v_ptr);
 
   // Casting to void pointer
-  (void)*reinterpret_cast(&a); // expected-warning {{ISO C++ does not allow}}
-  (void)*reinterpret_cast(&b); // expected-warning {{ISO C++ does not allow}}
-  (void)*reinterpret_cast(&l); // expected-warning {{ISO C++ does not allow}}
-  (void)*reinterpret_cast(&d); // expected-warning {{ISO C++ does not allow}}
-  (void)*reinterpret_cast(&f); // expected-warning {{ISO C++ does not allow}}
+  (void)*reinterpret_cast(&a); // expected-error {{ISO C++ does not allow}}
+  (void)*reinterpret_cast(&b); // expected-error {{ISO C++ does not allow}}
+  (void)*reinterpret_cast(&l); // expected-error {{ISO C++ does not allow}}
+  (void)*reinterpret_cast(&d); // expected-error {{ISO C++ does not allow}}
+  (void)*reinterpret_cast(&f); // expected-error {{ISO C++ does not allow}}
 }
 
 void reinterpret_cast_allowlist () {
Index: clang/test/SemaCXX/disallow_void_deref.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/disallow_void_deref.cpp
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -std=c++20 %s
+
+void f(void* p) {
+  (void)*p; // expected-error{{ISO C++ does not allow indirection on operand of type 'void *'}}
+}
+
+template
+concept deref = requires (T& t) {
+  { *t }; // #FAILED_REQ
+};
+
+static_assert(deref);
+// expected-error@-1{{static assertion failed}}
+// expected-note@-2{{because 'void *' does not satisfy 'deref'}}
+// expected-note@#FAILED_REQ{{because '*t' would be invalid: ISO C++ does not allow indirection on operand of type 'void *'}}
Index: clang/test/CXX/temp/temp.decls/temp.class/temp.mem.func/p1inst.cpp
===
--- clang/test/CXX/temp/temp.decls/temp.class/temp.mem.func/p1inst.cpp
+++ clang/test/CXX/temp/temp.decls/temp.class/temp.mem.func/p1inst.cpp
@@ -8,7 +8,7 @@
 
 template
 void X0::f(T *t, const U &u) {
-  *t = u; // expected-warning{{indirection on operand of type 'void *'}} expected-error{{not assignable}}
+  *t = u; // expected-error{{indirection on operand of type 'void *'}} expected-error{{not assignable}}
 }
 
 void test_f(X0 xfi, X0 xvi, float *fp, void *vp, int i) {
Index: clang/lib/Sema/SemaExpr.cpp
===
--- clang/lib/Sema/SemaExpr.cpp
+++ clang/lib/Sema/SemaExpr.cpp
@@ -14536,7 +14536,10 @@
 //   [...] the expression to which [the unary * operator] is applied shall
 //   be a pointer to an object type, or a pointer to a function type
 LangOptions LO = S.getLangOpts();
-if (LO.CPlusPlus || !(LO.C99 && (IsAfterAmp || S.isUnevaluatedContext(
+if (LO.CPlusPlus)
+  S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer_cpp)
+  << OpTy << Op->getSourceRange();
+else if (!(LO.C99 && (IsAfterAmp || S.isUnevaluatedContext(
   S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
   << LO.CPlusPlus << OpTy << Op->getSourceRange();
   }
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -6934,6 +6934,14 @@
 def ext_typecheck_indirection_through_void_pointer : ExtWarn<
   "ISO %select{C|C++}0 does not allow indirection on operand of type %1">,
   InGroup>;
+def ext_typecheck_indirection_through_void_pointer_cpp
+: ExtWarn<"ISO C++ does not allow indirection on operand of type %0">,
+  // Note: This uses a different diagnostics group than the C diagnostic
+  // so that projects that have disabled the above will get this diagnostic,
+  // and be aware of the deprecation.
+  InGroup>,
+  DefaultError,
+  SFINAEFailure;
 def warn_indirection_through_null : Warning<
   "indirection of non-volatile null pointer will be deleted, not trap">,
   InGroup;
Index: clang/docs/ReleaseNotes.rst
===

[PATCH] D135175: [clang] adds `__is_bounded_array` and `__is_unbounded_array` as builtins

2022-10-05 Thread Christopher Di Bella via Phabricator via cfe-commits
cjdb added inline comments.



Comment at: clang/lib/Sema/SemaType.cpp:2630
 // CUDA device code and some other targets don't support VLAs.
-targetDiag(Loc, (getLangOpts().CUDA && getLangOpts().CUDAIsDevice)
-? diag::err_cuda_vla
-: diag::err_vla_unsupported)
-<< ((getLangOpts().CUDA && getLangOpts().CUDAIsDevice)
-? CurrentCUDATarget()
-: CFT_InvalidTarget);
+bool IsCUDADevice = (getLangOpts().CUDA && getLangOpts().CUDAIsDevice);
+targetDiag(Loc,

shafik wrote:
> This feels like an unrelated change.
> 
> Is this diagnostic tested anywhere?
This change hardcodes the first option for `err_vla_unsupported`, since it now 
has a `%select`. No change in relevant tests necessary, since the existing 
tests should already catch this.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135175

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


[PATCH] D134772: [Clang] Make constraints of auto part of NTTP instead of AutoType

2022-10-05 Thread Yuanfang Chen via Phabricator via cfe-commits
ychen abandoned this revision.
ychen added a comment.

D135088  was landed instead.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134772

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


[PATCH] D135175: [clang] adds `__is_bounded_array` and `__is_unbounded_array` as builtins

2022-10-05 Thread Christopher Di Bella via Phabricator via cfe-commits
cjdb added inline comments.



Comment at: clang/lib/Sema/SemaExprCXX.cpp:24
 #include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/AST/Type.h"
 #include "clang/AST/TypeLoc.h"

shafik wrote:
> Why also `Type.h`?
The most likely reason is that it's come from D116280, and is actually 
important for one of the child patches (I'm not sure which off the top of my 
head). I can investigate and move it to the correct one before merging.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135175

___
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-05 Thread Zixu Wang via Phabricator via cfe-commits
zixuw added inline comments.



Comment at: clang/test/ExtractAPI/typedef_anonymous_record.c:74
 "interfaceLanguage": "objective-c",
-"precise": "c:@SA@MyStruct"
+"precise": "c:@S@MyStruct"
   },

Why is the `A` dropped here? Isn't this USR still referring to an anonymous 
struct (`typedef struct { } MyStruct;`)?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D134813

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


[PATCH] D135220: [clang] Update ModuleMap::getModuleMapFile* to use FileEntryRef

2022-10-05 Thread Ben Langmuir via Phabricator via cfe-commits
benlangmuir updated this revision to Diff 465457.
benlangmuir edited the summary of this revision.
benlangmuir added a comment.

- Used `OptionalFileEntryRefDegradesToFileEntryPtr` at two callsites
- Attempted to fix Windows path / vs \ in test.


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

https://reviews.llvm.org/D135220

Files:
  clang/include/clang/Basic/FileEntry.h
  clang/include/clang/Basic/SourceManager.h
  clang/include/clang/Lex/ModuleMap.h
  clang/lib/Basic/SourceManager.cpp
  clang/lib/Frontend/CompilerInstance.cpp
  clang/lib/Lex/HeaderSearch.cpp
  clang/lib/Lex/ModuleMap.cpp
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
  clang/test/Modules/malformed.cpp
  clang/tools/libclang/CIndexInclusionStack.cpp

Index: clang/tools/libclang/CIndexInclusionStack.cpp
===
--- clang/tools/libclang/CIndexInclusionStack.cpp
+++ clang/tools/libclang/CIndexInclusionStack.cpp
@@ -59,8 +59,8 @@
 
 // Callback to the client.
 // FIXME: We should have a function to construct CXFiles.
-CB(static_cast(
-   const_cast(FI.getContentCache().OrigEntry)),
+CB(static_cast(const_cast(
+   static_cast(FI.getContentCache().OrigEntry))),
InclusionStack.data(), InclusionStack.size(), clientData);
   }
 }
Index: clang/test/Modules/malformed.cpp
===
--- clang/test/Modules/malformed.cpp
+++ clang/test/Modules/malformed.cpp
@@ -3,9 +3,9 @@
 //
 // RUN: rm -rf %t
 // RUN: cd %S
-// RUN: not %clang_cc1 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -I Inputs/malformed -DHEADER="a1.h" %s 2>&1 | FileCheck %s --check-prefix=CHECK-A
-// RUN: not %clang_cc1 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -I Inputs/malformed -DHEADER="b1.h" %s 2>&1 | FileCheck %s --check-prefix=CHECK-B
-// RUN: not %clang_cc1 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -I Inputs/malformed -DHEADER="c.h" malformed.cpp 2>&1 | FileCheck %s --check-prefix=CHECK-C
+// RUN: not %clang_cc1 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -I Inputs/malformed -DHEADER="a1.h" %s 2>&1 | sed 's:\?:/:g' | FileCheck %s --check-prefix=CHECK-A
+// RUN: not %clang_cc1 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -I Inputs/malformed -DHEADER="b1.h" %s 2>&1 | sed 's:\?:/:g' | FileCheck %s --check-prefix=CHECK-B
+// RUN: not %clang_cc1 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -I Inputs/malformed -DHEADER="c.h" malformed.cpp 2>&1 | sed 's:\?:/:g' | FileCheck %s --check-prefix=CHECK-C
 
 #define STR2(x) #x
 #define STR(x) STR2(x)
Index: clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
===
--- clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
+++ clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
@@ -227,7 +227,7 @@
   if (llvm::any_of(CI.getFrontendOpts().Inputs, needsModules)) {
 Preprocessor &PP = ScanInstance.getPreprocessor();
 if (Module *CurrentModule = PP.getCurrentModuleImplementation())
-  if (const FileEntry *CurrentModuleMap =
+  if (Optional CurrentModuleMap =
   PP.getHeaderSearchInfo()
   .getModuleMap()
   .getModuleMapFileForUniquing(CurrentModule))
@@ -406,13 +406,13 @@
   MD.ImplicitModulePCMPath = std::string(M->getASTFile()->getName());
   MD.IsSystem = M->IsSystem;
 
-  const FileEntry *ModuleMap = MDC.ScanInstance.getPreprocessor()
-   .getHeaderSearchInfo()
-   .getModuleMap()
-   .getModuleMapFileForUniquing(M);
+  Optional ModuleMap = MDC.ScanInstance.getPreprocessor()
+ .getHeaderSearchInfo()
+ .getModuleMap()
+ .getModuleMapFileForUniquing(M);
 
   if (ModuleMap) {
-StringRef Path = ModuleMap->tryGetRealPathName();
+StringRef Path = ModuleMap->getFileEntry().tryGetRealPathName();
 if (Path.empty())
   Path = ModuleMap->getName();
 MD.ClangModuleMapFile = std::string(Path);
Index: clang/lib/Serialization/ASTWriter.cpp
===
--- clang/lib/Serialization/ASTWriter.cpp
+++ clang/lib/Serialization/ASTWriter.cpp
@@ -193,13 +193,13 @@
 auto *CurrentModule = ModulesToProcess.pop_back_val();
 ProcessedModules.insert(CurrentModule);
 
-auto *ModuleMapFile =
+Optional ModuleMapFile =
 HS.getModuleMap().getModuleMapFileForUniquing(CurrentModule);
 if (!ModuleMapFile) {
   continue;
 }
 
-ModuleMaps.insert(ModuleMapFile);
+ModuleMaps.insert(*ModuleMapFile);
 
 for (auto *ImportedModule : (CurrentModule)->Imports) {

[PATCH] D135287: Disallow dereferencing of void* in C++.

2022-10-05 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:6938
+def ext_typecheck_indirection_through_void_pointer_cpp
+: ExtWarn<"ISO C++ does not allow indirection on operand of type %0">,
+  // Note: This uses a different diagnostics group than the C diagnostic

Bikeshedding appreciated here :)  Note that the diagnostic ALSO will show up in 
SFINAE/Concepts explanations, so we can't just say "will be removed" or 
something.



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

https://reviews.llvm.org/D135287

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


[PATCH] D135220: [clang] Update ModuleMap::getModuleMapFile* to use FileEntryRef

2022-10-05 Thread Ben Langmuir via Phabricator via cfe-commits
benlangmuir added inline comments.



Comment at: clang/include/clang/Basic/SourceManager.h:146-155
   /// References the file which the contents were actually loaded from.
   ///
   /// Can be different from 'Entry' if we overridden the contents of one file
   /// with the contents of another file.
   const FileEntry *ContentsEntry;
 
   /// The filename that is used to access OrigEntry.

bnbarham wrote:
> I haven't checked all uses, but do we still need all of 
> `OrigEntry`/`ContentsEntry`/`Filename`? Seems like a single `FileEntryRef` 
> should encapsulate all the information we need there.
Yes, see my change to the FIXME above. Before we can get rid of Filename, 
`OrigEntry` has to be non-Optional, which means the code that works with 
virtual buffers needs to use a virtual file as well.  I don't think it's a huge 
deal, but it seemed orthogonal from the rest of this change.  `ContentsEntry` 
is unrelated, as it is not used for its filename only for its contents.



Comment at: clang/include/clang/Basic/SourceManager.h:1062
+Optional F = sloc.getFile().getContentCache().OrigEntry;
+return F ? &F->getFileEntry() : nullptr;
   }

bnbarham wrote:
> jansvoboda11 wrote:
> > Could you wrap `F` in `OptionalFileEntryRefDegradesToFileEntryPtr` to 
> > handle the conversion for you?
> `OrigEntry` is a `OptionalFileEntryRefDegradesToFileEntryPtr`, so this should 
> just be able to be `return slot.getFile().getContentCache().OrigEntry`?
Correct, this was just a leftover from before I decided to make OrigEntry use 
`OptionalFileEntryRefDegradesToFileEntryPtr`. 



Comment at: clang/lib/Lex/ModuleMap.cpp:1030
+Optional ModuleMapRef = getModuleMapFileForUniquing(Parent);
+ModuleMapFile = ModuleMapRef ? *ModuleMapRef : nullptr;
+  }

bnbarham wrote:
> jansvoboda11 wrote:
> > Nit: Use `OptionalFileEntryRefDegradesToFileEntryPtr`? Maybe we should 
> > return that from `getModuleMapFileForUniquing` in the first place.
> I like the idea of returning `OptionalFileEntryRefDegradesToFileEntryPtr` 
> until we move all this to use `FileEntryRef` as well.
I would prefer to keep returning `Optional`.  My reasoning is 
that `OptionalFileEntryRefDegradesToFileEntryPtr` should only be used on an API 
like this function when it would otherwise cause a lot of unnecessary 
workarounds at the callsites.  For `ContentCache::OrigEntry`, for example, that 
is clearly the case.  For `getModuleMapFileForUniquing` in my latest patch 
there are 11 total calls to this function, and only two of them would be 
improved by `OptionalFileEntryRefDegradesToFileEntryPtr`.  On balance, think 
it's better to just put the degrading pointer at those 2 callsites and keep the 
API itself clean. 


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

https://reviews.llvm.org/D135220

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


[PATCH] D135287: Disallow dereferencing of void* in C++.

2022-10-05 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a reviewer: clang-vendors.
aaron.ballman added a comment.

Adding the vendors group due to the potential to break existing code.


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

https://reviews.llvm.org/D135287

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


[PATCH] D135287: Disallow dereferencing of void* in C++.

2022-10-05 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added inline comments.



Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:6938
+def ext_typecheck_indirection_through_void_pointer_cpp
+: ExtWarn<"ISO C++ does not allow indirection on operand of type %0">,
+  // Note: This uses a different diagnostics group than the C diagnostic

erichkeane wrote:
> Bikeshedding appreciated here :)  Note that the diagnostic ALSO will show up 
> in SFINAE/Concepts explanations, so we can't just say "will be removed" or 
> something.
> 
The usual terminology is dereferencing. `"ISO C++ does not allow dereferencing 
a `void*`"


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

https://reviews.llvm.org/D135287

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


  1   2   3   >