[clang] [llvm] [InstCombine] Canonicalize `(sitofp x)` -> `(uitofp x)` if `x >= 0` (PR #82404)

2024-03-21 Thread Craig Topper via cfe-commits

topperc wrote:

> > Apart from the correctness issues, we've seen some regressions on various 
> > benchmarks from LLVM Test Suite after this patch. Specifically, around 3-5% 
> > regression on x86-64 in various metrics of the 
> > [Interpolation](https://github.com/llvm/llvm-test-suite/tree/main/MicroBenchmarks/ImageProcessing/Interpolation)
> >  benchmarks, and up to 30% regression on a number of floating point-centric 
> > benchmarks from 
> > https://github.com/llvm/llvm-test-suite/tree/main/SingleSource/Benchmarks/Misc
> >  (flops-4.c, flops-5.c, flops-6.c, flops-8.c, fp-convert.c). The numbers 
> > vary depending on the microarchitecture, with Skylake being less affected 
> > (on the order of ~10%) and AMD Rome showing larger regressions (up to 30%).
> 
> FYI this patch saves ~3% instructions for some benchmarks from 
> LLVM-test-suite on RISC-V. 
> [dtcxzyw/llvm-ci#1115](https://github.com/dtcxzyw/llvm-ci/issues/1115) 
> [dtcxzyw/llvm-ci#1114](https://github.com/dtcxzyw/llvm-ci/issues/1114)

Are you able to extract a reproducer that I can look at?

https://github.com/llvm/llvm-project/pull/82404
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [WebAssembly] Implement an alternative translation for -wasm-enable-sjlj (PR #84137)

2024-03-21 Thread Heejin Ahn via cfe-commits

aheejin wrote:

@yamt Given that this PR is not large and we already went through it anyway, 
nevermind what I said about rebasing, and please use whatever method you are 
convenient with. But just FYI  you can do `git merge` to avoid rebasing (I'm 
not asking you to do it here; just in case you aren't aware)

https://github.com/llvm/llvm-project/pull/84137
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-format] Add --fail-on-incomplete-format. (PR #84346)

2024-03-21 Thread Owen Pan via cfe-commits

https://github.com/owenca closed https://github.com/llvm/llvm-project/pull/84346
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-format] Add --fail-on-incomplete-format. (PR #84346)

2024-03-21 Thread via cfe-commits

github-actions[bot] wrote:



@gigaroby Congratulations on having your first Pull Request (PR) merged into 
the LLVM Project!

Your changes will be combined with recent changes from other authors, then 
tested
by our [build bots](https://lab.llvm.org/buildbot/). If there is a problem with 
a build, you may recieve a report in an email or a comment on this PR.

Please check whether problems have been caused by your change specifically, as
the builds can include changes from many authors. It is not uncommon for your
change to be included in a build that fails due to someone else's changes, or
infrastructure issues.

How to do this, and the rest of the post-merge process, is covered in detail 
[here](https://llvm.org/docs/MyFirstTypoFix.html#myfirsttypofix-issues-after-landing-your-pr).

If your change does cause a problem, it may be reverted, or you can revert it 
yourself.
This is a normal part of [LLVM 
development](https://llvm.org/docs/DeveloperPolicy.html#patch-reversion-policy).
 You can fix your changes and open a new PR to merge them again.

If you don't get any reports, no action is required from you. Your changes are 
working as expected, well done!


https://github.com/llvm/llvm-project/pull/84346
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][RISCV] Enable RVV with function attribute __attribute__((target("arch=+v"))) (PR #83674)

2024-03-21 Thread Luke Lau via cfe-commits


@@ -8927,8 +8927,13 @@ void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
 }
   }
 
-  if (T->isRVVSizelessBuiltinType())
-checkRVVTypeSupport(T, NewVD->getLocation(), cast(CurContext));
+  if (T->isRVVSizelessBuiltinType() && isa(CurContext)) {
+const FunctionDecl *FD = cast(CurContext);
+llvm::StringMap CallerFeatureMap;
+Context.getFunctionFeatureMap(CallerFeatureMap, FD);

lukel97 wrote:

> > @4vtomat if the MCPU has a feature but the function explicitly disables it 
> > then I think we want the `-`
> 
> Why don't we just remove it from feature map?

We also need the negative extensions if the target attribute string is a 
complete arch, e.g. `__attribute__((target="arch=rv64i")))`, because any 
extensions from mcpu need to be turned off.

https://github.com/llvm/llvm-project/pull/83674
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] a29e9e3 - [clang-format] Add --fail-on-incomplete-format. (#84346)

2024-03-21 Thread via cfe-commits

Author: Roberto Bampi
Date: 2024-03-21T01:29:25-07:00
New Revision: a29e9e32c50273abffc53e3700bbc23985f0a7af

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

LOG: [clang-format] Add --fail-on-incomplete-format. (#84346)

At the moment clang-format will return exit code 0 on incomplete
results. In scripts it would sometimes be useful if clang-format would
instead fail in those cases, signalling that there was something wrong
with the code being formatted.

-

Co-authored-by: Björn Schäpers 
Co-authored-by: Owen Pan 

Added: 
clang/test/Format/fail-on-incomplete.cpp

Modified: 
clang/docs/ClangFormat.rst
clang/tools/clang-format/ClangFormat.cpp

Removed: 




diff  --git a/clang/docs/ClangFormat.rst b/clang/docs/ClangFormat.rst
index 819d9ee9f9cde1..80dc38a075c8fc 100644
--- a/clang/docs/ClangFormat.rst
+++ b/clang/docs/ClangFormat.rst
@@ -61,6 +61,7 @@ to format C/C++/Java/JavaScript/JSON/Objective-C/Protobuf/C# 
code.
 --dry-run  - If set, do not actually make the 
formatting changes
 --dump-config  - Dump configuration options to stdout and 
exit.
  Can be used with -style option.
+--fail-on-incomplete-format- If set, fail with exit code 1 on 
incomplete format.
 --fallback-style=  - The name of the predefined style used as a
  fallback in case clang-format is invoked 
with
  -style=file, but can not find the 
.clang-format

diff  --git a/clang/test/Format/fail-on-incomplete.cpp 
b/clang/test/Format/fail-on-incomplete.cpp
new file mode 100644
index 00..ccd77af4d59947
--- /dev/null
+++ b/clang/test/Format/fail-on-incomplete.cpp
@@ -0,0 +1,4 @@
+// RUN: not clang-format -style=LLVM -fail-on-incomplete-format %s
+// RUN: clang-format -style=LLVM %s
+
+int a(

diff  --git a/clang/tools/clang-format/ClangFormat.cpp 
b/clang/tools/clang-format/ClangFormat.cpp
index e122cea50f7268..ed401135ad8433 100644
--- a/clang/tools/clang-format/ClangFormat.cpp
+++ b/clang/tools/clang-format/ClangFormat.cpp
@@ -205,6 +205,11 @@ static cl::list FileNames(cl::Positional,
cl::desc("[@] [ ...]"),
cl::cat(ClangFormatCategory));
 
+static cl::opt FailOnIncompleteFormat(
+"fail-on-incomplete-format",
+cl::desc("If set, fail with exit code 1 on incomplete format."),
+cl::init(false), cl::cat(ClangFormatCategory));
+
 namespace clang {
 namespace format {
 
@@ -399,7 +404,7 @@ class ClangFormatDiagConsumer : public DiagnosticConsumer {
 };
 
 // Returns true on error.
-static bool format(StringRef FileName) {
+static bool format(StringRef FileName, bool ErrorOnIncompleteFormat = false) {
   const bool IsSTDIN = FileName == "-";
   if (!OutputXML && Inplace && IsSTDIN) {
 errs() << "error: cannot use -i when reading from stdin.\n";
@@ -535,7 +540,7 @@ static bool format(StringRef FileName) {
   Rewrite.getEditBuffer(ID).write(outs());
 }
   }
-  return false;
+  return ErrorOnIncompleteFormat && !Status.FormatComplete;
 }
 
 } // namespace format
@@ -699,7 +704,7 @@ int main(int argc, const char **argv) {
   }
 
   if (FileNames.empty())
-return clang::format::format("-");
+return clang::format::format("-", FailOnIncompleteFormat);
 
   if (FileNames.size() > 1 &&
   (!Offsets.empty() || !Lengths.empty() || !LineRanges.empty())) {
@@ -717,7 +722,7 @@ int main(int argc, const char **argv) {
   errs() << "Formatting [" << FileNo++ << "/" << FileNames.size() << "] "
  << FileName << "\n";
 }
-Error |= clang::format::format(FileName);
+Error |= clang::format::format(FileName, FailOnIncompleteFormat);
   }
   return Error ? 1 : 0;
 }



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


[clang] [clang][analyzer] Model more getline/getdelim pre and postconditions (PR #83027)

2024-03-21 Thread Alejandro Álvarez Ayllón via cfe-commits


@@ -1204,6 +1204,20 @@ void StreamChecker::evalGetdelim(const FnDescription 
*Desc,
 State->BindExpr(E.CE, C.getLocationContext(), RetVal);
 StateNotFailed =
 E.assumeBinOpNN(StateNotFailed, BO_GE, RetVal, E.getZeroVal(Call));
+// The buffer size `*n` must be enough to hold the whole line, and
+// greater than the return value, since it has to account for '\0'.
+auto SizePtrSval = Call.getArgSVal(1);

alejandro-alvarez-sonarsource wrote:

Changed.

https://github.com/llvm/llvm-project/pull/83027
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][analyzer] Model more getline/getdelim pre and postconditions (PR #83027)

2024-03-21 Thread Alejandro Álvarez Ayllón via cfe-commits


@@ -1179,6 +1195,113 @@ void StreamChecker::evalUngetc(const FnDescription 
*Desc, const CallEvent &Call,
   C.addTransition(StateFailed);
 }
 
+ProgramStateRef StreamChecker::ensureGetdelimBufferAndSizeCorrect(
+SVal LinePtrPtrSVal, SVal SizePtrSVal, const Expr *LinePtrPtrExpr,
+const Expr *SizePtrExpr, CheckerContext &C, ProgramStateRef State) const {
+  static constexpr char SizeGreaterThanBufferSize[] =

alejandro-alvarez-sonarsource wrote:

Now it uses `llvm:StringLiteral`, but I think it (relatively) is. Most existing 
uses of `constexpr llvm::StringLiteral` in llvm are with `static`. And, IIUC, 
without `static`, the variable is going to live on the stack and be created 
each time (even though its value was already computed at compile time).

Probably a moot point, though, since this is not part of a hotpath. For 
consistency with other uses, I'd rather keep it, though.

https://github.com/llvm/llvm-project/pull/83027
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][analyzer] Model more getline/getdelim pre and postconditions (PR #83027)

2024-03-21 Thread Alejandro Álvarez Ayllón via cfe-commits


@@ -1204,6 +1204,20 @@ void StreamChecker::evalGetdelim(const FnDescription 
*Desc,
 State->BindExpr(E.CE, C.getLocationContext(), RetVal);
 StateNotFailed =
 E.assumeBinOpNN(StateNotFailed, BO_GE, RetVal, E.getZeroVal(Call));
+// The buffer size `*n` must be enough to hold the whole line, and
+// greater than the return value, since it has to account for '\0'.
+auto SizePtrSval = Call.getArgSVal(1);
+auto NVal = getPointeeVal(SizePtrSval, State);
+if (NVal) {
+  StateNotFailed = StateNotFailed->assume(
+  E.SVB
+  .evalBinOp(StateNotFailed, BO_GT, *NVal, RetVal,
+ E.SVB.getConditionType())
+  .castAs(),
+  true);
+  StateNotFailed =
+  StateNotFailed->BindExpr(E.CE, C.getLocationContext(), RetVal);
+}

alejandro-alvarez-sonarsource wrote:

In `stream.c`, the test `getline_buffer_size_invariant`

https://github.com/llvm/llvm-project/pull/83027
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][analyzer] Model more getline/getdelim pre and postconditions (PR #83027)

2024-03-21 Thread Alejandro Álvarez Ayllón via cfe-commits

https://github.com/alejandro-alvarez-sonarsource updated 
https://github.com/llvm/llvm-project/pull/83027

From a061464b75ac02c21e5d74fc4dff8d8afdbba66b Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Alejandro=20=C3=81lvarez=20Ayll=C3=B3n?=
 
Date: Wed, 20 Mar 2024 10:49:08 +0100
Subject: [PATCH 01/20] [NFC] UnixAPIMisuseChecker inherits from
 Checker

---
 .../Checkers/UnixAPIChecker.cpp   | 60 +--
 1 file changed, 30 insertions(+), 30 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
index 19f1ca2dc824c9..599e5e6cedc606 100644
--- a/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
@@ -17,6 +17,7 @@
 #include "clang/StaticAnalyzer/Core/BugReporter/CommonBugCategories.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
 #include "llvm/ADT/STLExtras.h"
@@ -41,8 +42,7 @@ enum class OpenVariant {
 namespace {
 
 class UnixAPIMisuseChecker
-: public Checker,
- check::ASTDecl> {
+: public Checker> {
   const BugType BT_open{this, "Improper use of 'open'", categories::UnixAPI};
   const BugType BT_pthreadOnce{this, "Improper use of 'pthread_once'",
categories::UnixAPI};
@@ -52,14 +52,14 @@ class UnixAPIMisuseChecker
   void checkASTDecl(const TranslationUnitDecl *TU, AnalysisManager &Mgr,
 BugReporter &BR) const;
 
-  void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
+  void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
 
-  void CheckOpen(CheckerContext &C, const CallExpr *CE) const;
-  void CheckOpenAt(CheckerContext &C, const CallExpr *CE) const;
-  void CheckPthreadOnce(CheckerContext &C, const CallExpr *CE) const;
+  void CheckOpen(CheckerContext &C, const CallEvent &Call) const;
+  void CheckOpenAt(CheckerContext &C, const CallEvent &Call) const;
+  void CheckPthreadOnce(CheckerContext &C, const CallEvent &Call) const;
 
-  void CheckOpenVariant(CheckerContext &C,
-const CallExpr *CE, OpenVariant Variant) const;
+  void CheckOpenVariant(CheckerContext &C, const CallEvent &Call,
+OpenVariant Variant) const;
 
   void ReportOpenBug(CheckerContext &C, ProgramStateRef State, const char *Msg,
  SourceRange SR) const;
@@ -113,9 +113,9 @@ void UnixAPIMisuseChecker::checkASTDecl(const 
TranslationUnitDecl *TU,
 // "open" (man 2 open)
 //===--===/
 
-void UnixAPIMisuseChecker::checkPreStmt(const CallExpr *CE,
+void UnixAPIMisuseChecker::checkPreCall(const CallEvent &Call,
 CheckerContext &C) const {
-  const FunctionDecl *FD = C.getCalleeDecl(CE);
+  const FunctionDecl *FD = dyn_cast_if_present(Call.getDecl());
   if (!FD || FD->getKind() != Decl::Function)
 return;
 
@@ -130,13 +130,13 @@ void UnixAPIMisuseChecker::checkPreStmt(const CallExpr 
*CE,
 return;
 
   if (FName == "open")
-CheckOpen(C, CE);
+CheckOpen(C, Call);
 
   else if (FName == "openat")
-CheckOpenAt(C, CE);
+CheckOpenAt(C, Call);
 
   else if (FName == "pthread_once")
-CheckPthreadOnce(C, CE);
+CheckPthreadOnce(C, Call);
 }
 void UnixAPIMisuseChecker::ReportOpenBug(CheckerContext &C,
  ProgramStateRef State,
@@ -152,17 +152,17 @@ void UnixAPIMisuseChecker::ReportOpenBug(CheckerContext 
&C,
 }
 
 void UnixAPIMisuseChecker::CheckOpen(CheckerContext &C,
- const CallExpr *CE) const {
-  CheckOpenVariant(C, CE, OpenVariant::Open);
+ const CallEvent &Call) const {
+  CheckOpenVariant(C, Call, OpenVariant::Open);
 }
 
 void UnixAPIMisuseChecker::CheckOpenAt(CheckerContext &C,
-   const CallExpr *CE) const {
-  CheckOpenVariant(C, CE, OpenVariant::OpenAt);
+   const CallEvent &Call) const {
+  CheckOpenVariant(C, Call, OpenVariant::OpenAt);
 }
 
 void UnixAPIMisuseChecker::CheckOpenVariant(CheckerContext &C,
-const CallExpr *CE,
+const CallEvent &Call,
 OpenVariant Variant) const {
   // The index of the argument taking the flags open flags (O_RDONLY,
   // O_WRONLY, O_CREAT, etc.),
@@ -191,11 +191,11 @@ void 
UnixAPIMisuseChecker::CheckOpenVariant(CheckerContext &C,
 
   ProgramStateRef state = C.getState();
 
-  if (CE->getNumArgs() < MinArgCount) {
+  if (Call.getNumArgs() < MinArgCount) {
 // The frontend

[clang] [clang][analyzer] Model more getline/getdelim pre and postconditions (PR #83027)

2024-03-21 Thread Alejandro Álvarez Ayllón via cfe-commits

https://github.com/alejandro-alvarez-sonarsource commented:

Applied the feedback.
By the way, when `StdLibraryFunctionsChecker` is refactored, I'd be happy to 
give a hand if you need updating these checkers (UnixAPI and Stream).

https://github.com/llvm/llvm-project/pull/83027
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][analyzer] Model more getline/getdelim pre and postconditions (PR #83027)

2024-03-21 Thread Alejandro Álvarez Ayllón via cfe-commits


@@ -1204,6 +1204,20 @@ void StreamChecker::evalGetdelim(const FnDescription 
*Desc,
 State->BindExpr(E.CE, C.getLocationContext(), RetVal);
 StateNotFailed =
 E.assumeBinOpNN(StateNotFailed, BO_GE, RetVal, E.getZeroVal(Call));
+// The buffer size `*n` must be enough to hold the whole line, and
+// greater than the return value, since it has to account for '\0'.
+auto SizePtrSval = Call.getArgSVal(1);
+auto NVal = getPointeeVal(SizePtrSval, State);
+if (NVal) {
+  StateNotFailed = StateNotFailed->assume(
+  E.SVB
+  .evalBinOp(StateNotFailed, BO_GT, *NVal, RetVal,
+ E.SVB.getConditionType())
+  .castAs(),
+  true);
+  StateNotFailed =
+  StateNotFailed->BindExpr(E.CE, C.getLocationContext(), RetVal);

alejandro-alvarez-sonarsource wrote:

Replaced, thanks!

https://github.com/llvm/llvm-project/pull/83027
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][analyzer] Model more getline/getdelim pre and postconditions (PR #83027)

2024-03-21 Thread Alejandro Álvarez Ayllón via cfe-commits


@@ -1217,6 +1231,11 @@ void StreamChecker::evalGetdelim(const FnDescription 
*Desc,
   E.isStreamEof() ? ErrorFEof : ErrorFEof | ErrorFError;
   StateFailed = E.setStreamState(
   StateFailed, StreamState::getOpened(Desc, NewES, !NewES.isFEof()));
+  // On failure, the content of the buffer is undefined.
+  if (auto NewLinePtr = getPointeeVal(Call.getArgSVal(0), State)) {
+StateFailed = StateFailed->bindLoc(*NewLinePtr, UndefinedVal(),
+   C.getLocationContext());
+  }

alejandro-alvarez-sonarsource wrote:

Removed.

https://github.com/llvm/llvm-project/pull/83027
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][CodeGen] Allow memcpy replace with trivial auto var init (PR #84230)

2024-03-21 Thread Antonio Frighetto via cfe-commits

https://github.com/antoniofrighetto updated 
https://github.com/llvm/llvm-project/pull/84230

>From bfc29a350458e9b8d20d7398595c3f36503e2d72 Mon Sep 17 00:00:00 2001
From: Antonio Frighetto 
Date: Thu, 7 Mar 2024 07:49:40 +0100
Subject: [PATCH] [clang][CodeGen] Allow `memcpy` replace with trivial auto var
 init

When emitting the storage (or memory copy operations) for constant
initializers, the decision whether to split a constant structure or
array store into a sequence of field stores or to use `memcpy` is
based upon the optimization level and the size of the initializer.
In afe8b93ffdfef5d8879e1894b9d7dda40dee2b8d, we extended this by
allowing constants to be split when the array (or struct) type does
not match the type of data the address to the object (constant) is
expected to contain. This may happen when `emitStoresForConstant` is
called by `EmitAutoVarInit`, as the element type of the address gets
shrunk. When this occurs, let the initializer be split into a bunch
of stores only under `-ftrivial-auto-var-init=pattern`.

Fixes: https://github.com/llvm/llvm-project/issues/84178.
---
 clang/lib/CodeGen/CGDecl.cpp  | 43 ++-
 clang/test/CodeGen/aapcs-align.cpp|  4 +--
 clang/test/CodeGen/aapcs64-align.cpp  |  8 ++---
 clang/test/CodeGen/attr-counted-by.c  | 26 --
 clang/test/CodeGenCXX/auto-var-init.cpp   | 27 +++---
 clang/test/CodeGenOpenCL/amdgpu-printf.cl |  9 +
 clang/test/OpenMP/bug54082.c  |  4 +--
 7 files changed, 56 insertions(+), 65 deletions(-)

diff --git a/clang/lib/CodeGen/CGDecl.cpp b/clang/lib/CodeGen/CGDecl.cpp
index dc42faf8dbb9fd..2ef5ed04af30b6 100644
--- a/clang/lib/CodeGen/CGDecl.cpp
+++ b/clang/lib/CodeGen/CGDecl.cpp
@@ -1242,27 +1242,38 @@ static void emitStoresForConstant(CodeGenModule &CGM, 
const VarDecl &D,
 return;
   }
 
-  // If the initializer is small, use a handful of stores.
+  // If the initializer is small or trivialAutoVarInit is set, use a handful of
+  // stores.
+  bool IsTrivialAutoVarInitPattern =
+  CGM.getContext().getLangOpts().getTrivialAutoVarInit() ==
+  LangOptions::TrivialAutoVarInitKind::Pattern;
   if (shouldSplitConstantStore(CGM, ConstantSize)) {
 if (auto *STy = dyn_cast(Ty)) {
-  const llvm::StructLayout *Layout =
-  CGM.getDataLayout().getStructLayout(STy);
-  for (unsigned i = 0; i != constant->getNumOperands(); i++) {
-CharUnits CurOff = 
CharUnits::fromQuantity(Layout->getElementOffset(i));
-Address EltPtr = Builder.CreateConstInBoundsByteGEP(
-Loc.withElementType(CGM.Int8Ty), CurOff);
-emitStoresForConstant(CGM, D, EltPtr, isVolatile, Builder,
-  constant->getAggregateElement(i), IsAutoInit);
+  if (STy == Loc.getElementType() ||
+  (STy != Loc.getElementType() && IsTrivialAutoVarInitPattern)) {
+const llvm::StructLayout *Layout =
+CGM.getDataLayout().getStructLayout(STy);
+for (unsigned i = 0; i != constant->getNumOperands(); i++) {
+  CharUnits CurOff =
+  CharUnits::fromQuantity(Layout->getElementOffset(i));
+  Address EltPtr = Builder.CreateConstInBoundsByteGEP(
+  Loc.withElementType(CGM.Int8Ty), CurOff);
+  emitStoresForConstant(CGM, D, EltPtr, isVolatile, Builder,
+constant->getAggregateElement(i), IsAutoInit);
+}
+return;
   }
-  return;
 } else if (auto *ATy = dyn_cast(Ty)) {
-  for (unsigned i = 0; i != ATy->getNumElements(); i++) {
-Address EltPtr = Builder.CreateConstGEP(
-Loc.withElementType(ATy->getElementType()), i);
-emitStoresForConstant(CGM, D, EltPtr, isVolatile, Builder,
-  constant->getAggregateElement(i), IsAutoInit);
+  if (ATy == Loc.getElementType() ||
+  (ATy != Loc.getElementType() && IsTrivialAutoVarInitPattern)) {
+for (unsigned i = 0; i != ATy->getNumElements(); i++) {
+  Address EltPtr = Builder.CreateConstGEP(
+  Loc.withElementType(ATy->getElementType()), i);
+  emitStoresForConstant(CGM, D, EltPtr, isVolatile, Builder,
+constant->getAggregateElement(i), IsAutoInit);
+}
+return;
   }
-  return;
 }
   }
 
diff --git a/clang/test/CodeGen/aapcs-align.cpp 
b/clang/test/CodeGen/aapcs-align.cpp
index 2886a32974b066..4f393d9e6b7f32 100644
--- a/clang/test/CodeGen/aapcs-align.cpp
+++ b/clang/test/CodeGen/aapcs-align.cpp
@@ -134,8 +134,8 @@ void g6() {
   f6m(1, 2, 3, 4, 5, s);
 }
 // CHECK: define{{.*}} void @g6
-// CHECK: call void @f6(i32 noundef 1, [4 x i32] [i32 6, i32 7, i32 0, i32 0])
-// CHECK: call void @f6m(i32 noundef 1, i32 noundef 2, i32 noundef 3, i32 
noundef 4, i32 noundef 5, [4 x i32] [i32 6, i32 7, i32 0, i32 0])
+// CHECK: call void @f6(i32 noundef 1, [4 x i32] [i32 6, i32 7, i32 0, i32 
undef])
+// CHECK: call

[clang] [clang][CodeGen] Allow memcpy replace with trivial auto var init (PR #84230)

2024-03-21 Thread Antonio Frighetto via cfe-commits

https://github.com/antoniofrighetto updated 
https://github.com/llvm/llvm-project/pull/84230

>From b433076fcbacba8a3b91446390bbea5843322bcd Mon Sep 17 00:00:00 2001
From: Antonio Frighetto 
Date: Thu, 7 Mar 2024 07:49:40 +0100
Subject: [PATCH] [clang][CodeGen] Allow `memcpy` replace with trivial auto var
 init

When emitting the storage (or memory copy operations) for constant
initializers, the decision whether to split a constant structure or
array store into a sequence of field stores or to use `memcpy` is
based upon the optimization level and the size of the initializer.
In afe8b93ffdfef5d8879e1894b9d7dda40dee2b8d, we extended this by
allowing constants to be split when the array (or struct) type does
not match the type of data the address to the object (constant) is
expected to contain. This may happen when `emitStoresForConstant` is
called by `EmitAutoVarInit`, as the element type of the address gets
shrunk. When this occurs, let the initializer be split into a bunch
of stores only under `-ftrivial-auto-var-init=pattern`.

Fixes: https://github.com/llvm/llvm-project/issues/84178.
---
 clang/lib/CodeGen/CGDecl.cpp  | 43 ++-
 clang/test/CodeGen/aapcs-align.cpp|  4 +--
 clang/test/CodeGen/aapcs64-align.cpp  |  8 ++---
 clang/test/CodeGen/attr-counted-by.c  | 26 --
 clang/test/CodeGenCXX/auto-var-init.cpp   | 27 +++---
 clang/test/CodeGenOpenCL/amdgpu-printf.cl |  9 +
 clang/test/OpenMP/bug54082.c  |  4 +--
 7 files changed, 56 insertions(+), 65 deletions(-)

diff --git a/clang/lib/CodeGen/CGDecl.cpp b/clang/lib/CodeGen/CGDecl.cpp
index dc42faf8dbb9fd..2ef5ed04af30b6 100644
--- a/clang/lib/CodeGen/CGDecl.cpp
+++ b/clang/lib/CodeGen/CGDecl.cpp
@@ -1242,27 +1242,38 @@ static void emitStoresForConstant(CodeGenModule &CGM, 
const VarDecl &D,
 return;
   }
 
-  // If the initializer is small, use a handful of stores.
+  // If the initializer is small or trivialAutoVarInit is set, use a handful of
+  // stores.
+  bool IsTrivialAutoVarInitPattern =
+  CGM.getContext().getLangOpts().getTrivialAutoVarInit() ==
+  LangOptions::TrivialAutoVarInitKind::Pattern;
   if (shouldSplitConstantStore(CGM, ConstantSize)) {
 if (auto *STy = dyn_cast(Ty)) {
-  const llvm::StructLayout *Layout =
-  CGM.getDataLayout().getStructLayout(STy);
-  for (unsigned i = 0; i != constant->getNumOperands(); i++) {
-CharUnits CurOff = 
CharUnits::fromQuantity(Layout->getElementOffset(i));
-Address EltPtr = Builder.CreateConstInBoundsByteGEP(
-Loc.withElementType(CGM.Int8Ty), CurOff);
-emitStoresForConstant(CGM, D, EltPtr, isVolatile, Builder,
-  constant->getAggregateElement(i), IsAutoInit);
+  if (STy == Loc.getElementType() ||
+  (STy != Loc.getElementType() && IsTrivialAutoVarInitPattern)) {
+const llvm::StructLayout *Layout =
+CGM.getDataLayout().getStructLayout(STy);
+for (unsigned i = 0; i != constant->getNumOperands(); i++) {
+  CharUnits CurOff =
+  CharUnits::fromQuantity(Layout->getElementOffset(i));
+  Address EltPtr = Builder.CreateConstInBoundsByteGEP(
+  Loc.withElementType(CGM.Int8Ty), CurOff);
+  emitStoresForConstant(CGM, D, EltPtr, isVolatile, Builder,
+constant->getAggregateElement(i), IsAutoInit);
+}
+return;
   }
-  return;
 } else if (auto *ATy = dyn_cast(Ty)) {
-  for (unsigned i = 0; i != ATy->getNumElements(); i++) {
-Address EltPtr = Builder.CreateConstGEP(
-Loc.withElementType(ATy->getElementType()), i);
-emitStoresForConstant(CGM, D, EltPtr, isVolatile, Builder,
-  constant->getAggregateElement(i), IsAutoInit);
+  if (ATy == Loc.getElementType() ||
+  (ATy != Loc.getElementType() && IsTrivialAutoVarInitPattern)) {
+for (unsigned i = 0; i != ATy->getNumElements(); i++) {
+  Address EltPtr = Builder.CreateConstGEP(
+  Loc.withElementType(ATy->getElementType()), i);
+  emitStoresForConstant(CGM, D, EltPtr, isVolatile, Builder,
+constant->getAggregateElement(i), IsAutoInit);
+}
+return;
   }
-  return;
 }
   }
 
diff --git a/clang/test/CodeGen/aapcs-align.cpp 
b/clang/test/CodeGen/aapcs-align.cpp
index 2886a32974b066..4f393d9e6b7f32 100644
--- a/clang/test/CodeGen/aapcs-align.cpp
+++ b/clang/test/CodeGen/aapcs-align.cpp
@@ -134,8 +134,8 @@ void g6() {
   f6m(1, 2, 3, 4, 5, s);
 }
 // CHECK: define{{.*}} void @g6
-// CHECK: call void @f6(i32 noundef 1, [4 x i32] [i32 6, i32 7, i32 0, i32 0])
-// CHECK: call void @f6m(i32 noundef 1, i32 noundef 2, i32 noundef 3, i32 
noundef 4, i32 noundef 5, [4 x i32] [i32 6, i32 7, i32 0, i32 0])
+// CHECK: call void @f6(i32 noundef 1, [4 x i32] [i32 6, i32 7, i32 0, i32 
undef])
+// CHECK: call

[clang] [clang][CodeGen] Allow memcpy replace with trivial auto var init (PR #84230)

2024-03-21 Thread Antonio Frighetto via cfe-commits

https://github.com/antoniofrighetto closed 
https://github.com/llvm/llvm-project/pull/84230
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] b433076 - [clang][CodeGen] Allow `memcpy` replace with trivial auto var init

2024-03-21 Thread Antonio Frighetto via cfe-commits

Author: Antonio Frighetto
Date: 2024-03-21T09:55:04+01:00
New Revision: b433076fcbacba8a3b91446390bbea5843322bcd

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

LOG: [clang][CodeGen] Allow `memcpy` replace with trivial auto var init

When emitting the storage (or memory copy operations) for constant
initializers, the decision whether to split a constant structure or
array store into a sequence of field stores or to use `memcpy` is
based upon the optimization level and the size of the initializer.
In afe8b93ffdfef5d8879e1894b9d7dda40dee2b8d, we extended this by
allowing constants to be split when the array (or struct) type does
not match the type of data the address to the object (constant) is
expected to contain. This may happen when `emitStoresForConstant` is
called by `EmitAutoVarInit`, as the element type of the address gets
shrunk. When this occurs, let the initializer be split into a bunch
of stores only under `-ftrivial-auto-var-init=pattern`.

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

Added: 


Modified: 
clang/lib/CodeGen/CGDecl.cpp
clang/test/CodeGen/aapcs-align.cpp
clang/test/CodeGen/aapcs64-align.cpp
clang/test/CodeGen/attr-counted-by.c
clang/test/CodeGenCXX/auto-var-init.cpp
clang/test/CodeGenOpenCL/amdgpu-printf.cl
clang/test/OpenMP/bug54082.c

Removed: 




diff  --git a/clang/lib/CodeGen/CGDecl.cpp b/clang/lib/CodeGen/CGDecl.cpp
index dc42faf8dbb9fd..2ef5ed04af30b6 100644
--- a/clang/lib/CodeGen/CGDecl.cpp
+++ b/clang/lib/CodeGen/CGDecl.cpp
@@ -1242,27 +1242,38 @@ static void emitStoresForConstant(CodeGenModule &CGM, 
const VarDecl &D,
 return;
   }
 
-  // If the initializer is small, use a handful of stores.
+  // If the initializer is small or trivialAutoVarInit is set, use a handful of
+  // stores.
+  bool IsTrivialAutoVarInitPattern =
+  CGM.getContext().getLangOpts().getTrivialAutoVarInit() ==
+  LangOptions::TrivialAutoVarInitKind::Pattern;
   if (shouldSplitConstantStore(CGM, ConstantSize)) {
 if (auto *STy = dyn_cast(Ty)) {
-  const llvm::StructLayout *Layout =
-  CGM.getDataLayout().getStructLayout(STy);
-  for (unsigned i = 0; i != constant->getNumOperands(); i++) {
-CharUnits CurOff = 
CharUnits::fromQuantity(Layout->getElementOffset(i));
-Address EltPtr = Builder.CreateConstInBoundsByteGEP(
-Loc.withElementType(CGM.Int8Ty), CurOff);
-emitStoresForConstant(CGM, D, EltPtr, isVolatile, Builder,
-  constant->getAggregateElement(i), IsAutoInit);
+  if (STy == Loc.getElementType() ||
+  (STy != Loc.getElementType() && IsTrivialAutoVarInitPattern)) {
+const llvm::StructLayout *Layout =
+CGM.getDataLayout().getStructLayout(STy);
+for (unsigned i = 0; i != constant->getNumOperands(); i++) {
+  CharUnits CurOff =
+  CharUnits::fromQuantity(Layout->getElementOffset(i));
+  Address EltPtr = Builder.CreateConstInBoundsByteGEP(
+  Loc.withElementType(CGM.Int8Ty), CurOff);
+  emitStoresForConstant(CGM, D, EltPtr, isVolatile, Builder,
+constant->getAggregateElement(i), IsAutoInit);
+}
+return;
   }
-  return;
 } else if (auto *ATy = dyn_cast(Ty)) {
-  for (unsigned i = 0; i != ATy->getNumElements(); i++) {
-Address EltPtr = Builder.CreateConstGEP(
-Loc.withElementType(ATy->getElementType()), i);
-emitStoresForConstant(CGM, D, EltPtr, isVolatile, Builder,
-  constant->getAggregateElement(i), IsAutoInit);
+  if (ATy == Loc.getElementType() ||
+  (ATy != Loc.getElementType() && IsTrivialAutoVarInitPattern)) {
+for (unsigned i = 0; i != ATy->getNumElements(); i++) {
+  Address EltPtr = Builder.CreateConstGEP(
+  Loc.withElementType(ATy->getElementType()), i);
+  emitStoresForConstant(CGM, D, EltPtr, isVolatile, Builder,
+constant->getAggregateElement(i), IsAutoInit);
+}
+return;
   }
-  return;
 }
   }
 

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

[clang] [llvm] [clang][HLSL][SPRI-V] Add convergence intrinsics (PR #80680)

2024-03-21 Thread Matt Arsenault via cfe-commits
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= 
Message-ID:
In-Reply-To: 



@@ -1295,11 +1295,13 @@ double4 trunc(double4);
 /// true, across all active lanes in the current wave.
 _HLSL_AVAILABILITY(shadermodel, 6.0)
 _HLSL_BUILTIN_ALIAS(__builtin_hlsl_wave_active_count_bits)
+__attribute__((convergent))

arsenm wrote:

Convergence requires all transitive callers to also be convergent. No real code 
is going to do this. The existence of convergence operations means you have a 
convergent language and must optimize to known-not-convergent 

https://github.com/llvm/llvm-project/pull/80680
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [clang][HLSL][SPRI-V] Add convergence intrinsics (PR #80680)

2024-03-21 Thread Matt Arsenault via cfe-commits
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= 
Message-ID:
In-Reply-To: 



@@ -1295,11 +1295,13 @@ double4 trunc(double4);
 /// true, across all active lanes in the current wave.
 _HLSL_AVAILABILITY(shadermodel, 6.0)
 _HLSL_BUILTIN_ALIAS(__builtin_hlsl_wave_active_count_bits)
+__attribute__((convergent))

arsenm wrote:

For today you just have to put convergent on every function, you're just stuck 
with the crappy IR design decisions we have now. The noconvergent patch cleans 
this up to be a less bug prone state consistent with all the other optimization 
attributes, this doesn't need to wait for that. You just have to follow along 
with OpenCL/HIP/CUDA/OpenMP and say yes for 
LangOpts.assumeFunctionsAreConvergent

https://github.com/llvm/llvm-project/pull/80680
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [CodeGen][LLVM] Make the `va_list` related intrinsics generic. (PR #85460)

2024-03-21 Thread Matt Arsenault via cfe-commits


@@ -700,10 +700,13 @@ class MSBuiltin {
 //===--- Variable Argument Handling Intrinsics 
===//
 //
 
-def int_vastart : DefaultAttrsIntrinsic<[], [llvm_ptr_ty], [], 
"llvm.va_start">;
-def int_vacopy  : DefaultAttrsIntrinsic<[], [llvm_ptr_ty, llvm_ptr_ty], [],
-"llvm.va_copy">;
-def int_vaend   : DefaultAttrsIntrinsic<[], [llvm_ptr_ty], [], "llvm.va_end">;
+def int_vastart : DefaultAttrsIntrinsic<[],
+[llvm_anyptr_ty], [], "llvm.va_start">;
+def int_vacopy  : DefaultAttrsIntrinsic<[],
+[llvm_anyptr_ty, llvm_anyptr_ty], [],
+"llvm.va_copy">;

arsenm wrote:

Would it make sense to emit these as p5.p0 pairs, such that we're assuming it's 
writing to the stack from an arbitrary pointer an optimize down to 
stack-to-stack copies? 

https://github.com/llvm/llvm-project/pull/85460
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [X86][Headers] Specify result of NaN comparisons (PR #85862)

2024-03-21 Thread Simon Pilgrim via cfe-commits


@@ -207,6 +207,8 @@ _mm256_div_ps(__m256 __a, __m256 __b)
 /// Compares two 256-bit vectors of [4 x double] and returns the greater
 ///of each pair of values.
 ///
+///If either value in a comparison is NaN, returns the value from \a __b.

RKSimon wrote:

I don't think so either - we don't need to start explaining general fp 
comparison behaviour, just any x86/sse quirks.

https://github.com/llvm/llvm-project/pull/85862
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [compiler-rt] [llvm] Add numerical sanitizer (PR #85916)

2024-03-21 Thread Matt Arsenault via cfe-commits


@@ -0,0 +1,2261 @@
+//===-- NumericalStabilitySanitizer.cpp 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This file is a part of NumericalStabilitySanitizer.
+//
+//===--===//
+
+#include "llvm/Transforms/Instrumentation/NumericalStabilitySanitizer.h"
+
+#include 
+#include 
+
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/Statistic.h"
+#include "llvm/ADT/StringExtras.h"
+#include "llvm/Analysis/CaptureTracking.h"
+#include "llvm/Analysis/TargetLibraryInfo.h"
+#include "llvm/Analysis/ValueTracking.h"
+#include "llvm/IR/DataLayout.h"
+#include "llvm/IR/Function.h"
+#include "llvm/IR/IRBuilder.h"
+#include "llvm/IR/IntrinsicInst.h"
+#include "llvm/IR/Intrinsics.h"
+#include "llvm/IR/LLVMContext.h"
+#include "llvm/IR/Metadata.h"
+#include "llvm/IR/Module.h"
+#include "llvm/IR/Type.h"
+#include "llvm/InitializePasses.h"
+#include "llvm/ProfileData/InstrProf.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Support/Debug.h"
+#include "llvm/Support/MathExtras.h"
+#include "llvm/Support/Regex.h"
+#include "llvm/Support/raw_ostream.h"
+#include "llvm/Transforms/Instrumentation.h"
+#include "llvm/Transforms/Utils/BasicBlockUtils.h"
+#include "llvm/Transforms/Utils/EscapeEnumerator.h"
+#include "llvm/Transforms/Utils/Local.h"
+#include "llvm/Transforms/Utils/ModuleUtils.h"
+
+using namespace llvm;
+
+#define DEBUG_TYPE "nsan"
+
+STATISTIC(NumInstrumentedFTLoads,
+  "Number of instrumented floating-point loads");
+
+STATISTIC(NumInstrumentedFTCalls,
+  "Number of instrumented floating-point calls");
+STATISTIC(NumInstrumentedFTRets,
+  "Number of instrumented floating-point returns");
+STATISTIC(NumInstrumentedFTStores,
+  "Number of instrumented floating-point stores");
+STATISTIC(NumInstrumentedNonFTStores,
+  "Number of instrumented non floating-point stores");
+STATISTIC(
+NumInstrumentedNonFTMemcpyStores,
+"Number of instrumented non floating-point stores with memcpy semantics");
+STATISTIC(NumInstrumentedFCmp, "Number of instrumented fcmps");
+
+// Using smaller shadow types types can help improve speed. For example, `dlq`
+// is 3x slower to 5x faster in opt mode and 2-6x faster in dbg mode compared 
to
+// `dqq`.
+static cl::opt ClShadowMapping(
+"nsan-shadow-type-mapping", cl::init("dqq"),
+cl::desc("One shadow type id for each of `float`, `double`, `long double`. 
"
+ "`d`,`l`,`q`,`e` mean double, x86_fp80, fp128 (quad) and "
+ "ppc_fp128 (extended double) respectively. The default is to "
+ "shadow `float` as `double`, and `double` and `x86_fp80` as "
+ "`fp128`"),
+cl::Hidden);
+
+static cl::opt
+ClInstrumentFCmp("nsan-instrument-fcmp", cl::init(true),
+ cl::desc("Instrument floating-point comparisons"),
+ cl::Hidden);
+
+static cl::opt ClCheckFunctionsFilter(
+"check-functions-filter",
+cl::desc("Only emit checks for arguments of functions "
+ "whose names match the given regular expression"),
+cl::value_desc("regex"));
+
+static cl::opt ClTruncateFCmpEq(
+"nsan-truncate-fcmp-eq", cl::init(true),
+cl::desc(
+"This flag controls the behaviour of fcmp equality comparisons:"
+"For equality comparisons such as `x == 0.0f`, we can perform the "
+"shadow check in the shadow (`x_shadow == 0.0) == (x == 0.0f)`) or app 
"
+" domain (`(trunc(x_shadow) == 0.0f) == (x == 0.0f)`). This helps "
+"catch the case when `x_shadow` is accurate enough (and therefore "
+"close enough to zero) so that `trunc(x_shadow)` is zero even though "
+"both `x` and `x_shadow` are not. "),
+cl::Hidden);
+
+// When there is external, uninstrumented code writing to memory, the shadow
+// memory can get out of sync with the application memory. Enabling this flag
+// emits consistency checks for loads to catch this situation.
+// When everything is instrumented, this is not strictly necessary because any
+// load should have a corresponding store, but can help debug cases when the
+// framework did a bad job at tracking shadow memory modifications by failing 
on
+// load rather than store.
+// FIXME: provide a way to resume computations from the FT value when the load
+// is inconsistent. This ensures that further computations are not polluted.
+static cl::opt ClCheckLoads("nsan-check-loads", cl::init(false),
+  cl::desc("Check floating-point load"),
+  cl::Hidden);
+
+static 

[clang] [compiler-rt] [llvm] Add numerical sanitizer (PR #85916)

2024-03-21 Thread Matt Arsenault via cfe-commits


@@ -0,0 +1,2261 @@
+//===-- NumericalStabilitySanitizer.cpp 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This file is a part of NumericalStabilitySanitizer.
+//
+//===--===//
+
+#include "llvm/Transforms/Instrumentation/NumericalStabilitySanitizer.h"
+
+#include 
+#include 
+
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/Statistic.h"
+#include "llvm/ADT/StringExtras.h"
+#include "llvm/Analysis/CaptureTracking.h"
+#include "llvm/Analysis/TargetLibraryInfo.h"
+#include "llvm/Analysis/ValueTracking.h"
+#include "llvm/IR/DataLayout.h"
+#include "llvm/IR/Function.h"
+#include "llvm/IR/IRBuilder.h"
+#include "llvm/IR/IntrinsicInst.h"
+#include "llvm/IR/Intrinsics.h"
+#include "llvm/IR/LLVMContext.h"
+#include "llvm/IR/Metadata.h"
+#include "llvm/IR/Module.h"
+#include "llvm/IR/Type.h"
+#include "llvm/InitializePasses.h"
+#include "llvm/ProfileData/InstrProf.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Support/Debug.h"
+#include "llvm/Support/MathExtras.h"
+#include "llvm/Support/Regex.h"
+#include "llvm/Support/raw_ostream.h"
+#include "llvm/Transforms/Instrumentation.h"
+#include "llvm/Transforms/Utils/BasicBlockUtils.h"
+#include "llvm/Transforms/Utils/EscapeEnumerator.h"
+#include "llvm/Transforms/Utils/Local.h"
+#include "llvm/Transforms/Utils/ModuleUtils.h"
+
+using namespace llvm;
+
+#define DEBUG_TYPE "nsan"
+
+STATISTIC(NumInstrumentedFTLoads,
+  "Number of instrumented floating-point loads");
+
+STATISTIC(NumInstrumentedFTCalls,
+  "Number of instrumented floating-point calls");
+STATISTIC(NumInstrumentedFTRets,
+  "Number of instrumented floating-point returns");
+STATISTIC(NumInstrumentedFTStores,
+  "Number of instrumented floating-point stores");
+STATISTIC(NumInstrumentedNonFTStores,
+  "Number of instrumented non floating-point stores");
+STATISTIC(
+NumInstrumentedNonFTMemcpyStores,
+"Number of instrumented non floating-point stores with memcpy semantics");
+STATISTIC(NumInstrumentedFCmp, "Number of instrumented fcmps");
+
+// Using smaller shadow types types can help improve speed. For example, `dlq`
+// is 3x slower to 5x faster in opt mode and 2-6x faster in dbg mode compared 
to
+// `dqq`.
+static cl::opt ClShadowMapping(
+"nsan-shadow-type-mapping", cl::init("dqq"),
+cl::desc("One shadow type id for each of `float`, `double`, `long double`. 
"
+ "`d`,`l`,`q`,`e` mean double, x86_fp80, fp128 (quad) and "
+ "ppc_fp128 (extended double) respectively. The default is to "
+ "shadow `float` as `double`, and `double` and `x86_fp80` as "
+ "`fp128`"),
+cl::Hidden);
+
+static cl::opt
+ClInstrumentFCmp("nsan-instrument-fcmp", cl::init(true),
+ cl::desc("Instrument floating-point comparisons"),
+ cl::Hidden);
+
+static cl::opt ClCheckFunctionsFilter(
+"check-functions-filter",
+cl::desc("Only emit checks for arguments of functions "
+ "whose names match the given regular expression"),
+cl::value_desc("regex"));
+
+static cl::opt ClTruncateFCmpEq(
+"nsan-truncate-fcmp-eq", cl::init(true),
+cl::desc(
+"This flag controls the behaviour of fcmp equality comparisons:"
+"For equality comparisons such as `x == 0.0f`, we can perform the "
+"shadow check in the shadow (`x_shadow == 0.0) == (x == 0.0f)`) or app 
"
+" domain (`(trunc(x_shadow) == 0.0f) == (x == 0.0f)`). This helps "
+"catch the case when `x_shadow` is accurate enough (and therefore "
+"close enough to zero) so that `trunc(x_shadow)` is zero even though "
+"both `x` and `x_shadow` are not. "),
+cl::Hidden);
+
+// When there is external, uninstrumented code writing to memory, the shadow
+// memory can get out of sync with the application memory. Enabling this flag
+// emits consistency checks for loads to catch this situation.
+// When everything is instrumented, this is not strictly necessary because any
+// load should have a corresponding store, but can help debug cases when the
+// framework did a bad job at tracking shadow memory modifications by failing 
on
+// load rather than store.
+// FIXME: provide a way to resume computations from the FT value when the load
+// is inconsistent. This ensures that further computations are not polluted.
+static cl::opt ClCheckLoads("nsan-check-loads", cl::init(false),
+  cl::desc("Check floating-point load"),
+  cl::Hidden);
+
+static 

[clang] [compiler-rt] [llvm] Add numerical sanitizer (PR #85916)

2024-03-21 Thread Matt Arsenault via cfe-commits


@@ -0,0 +1,2261 @@
+//===-- NumericalStabilitySanitizer.cpp 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This file is a part of NumericalStabilitySanitizer.
+//
+//===--===//
+
+#include "llvm/Transforms/Instrumentation/NumericalStabilitySanitizer.h"
+
+#include 
+#include 
+
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/Statistic.h"
+#include "llvm/ADT/StringExtras.h"
+#include "llvm/Analysis/CaptureTracking.h"
+#include "llvm/Analysis/TargetLibraryInfo.h"
+#include "llvm/Analysis/ValueTracking.h"
+#include "llvm/IR/DataLayout.h"
+#include "llvm/IR/Function.h"
+#include "llvm/IR/IRBuilder.h"
+#include "llvm/IR/IntrinsicInst.h"
+#include "llvm/IR/Intrinsics.h"
+#include "llvm/IR/LLVMContext.h"
+#include "llvm/IR/Metadata.h"
+#include "llvm/IR/Module.h"
+#include "llvm/IR/Type.h"
+#include "llvm/InitializePasses.h"
+#include "llvm/ProfileData/InstrProf.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Support/Debug.h"
+#include "llvm/Support/MathExtras.h"
+#include "llvm/Support/Regex.h"
+#include "llvm/Support/raw_ostream.h"
+#include "llvm/Transforms/Instrumentation.h"
+#include "llvm/Transforms/Utils/BasicBlockUtils.h"
+#include "llvm/Transforms/Utils/EscapeEnumerator.h"
+#include "llvm/Transforms/Utils/Local.h"
+#include "llvm/Transforms/Utils/ModuleUtils.h"
+
+using namespace llvm;
+
+#define DEBUG_TYPE "nsan"
+
+STATISTIC(NumInstrumentedFTLoads,
+  "Number of instrumented floating-point loads");
+
+STATISTIC(NumInstrumentedFTCalls,
+  "Number of instrumented floating-point calls");
+STATISTIC(NumInstrumentedFTRets,
+  "Number of instrumented floating-point returns");
+STATISTIC(NumInstrumentedFTStores,
+  "Number of instrumented floating-point stores");
+STATISTIC(NumInstrumentedNonFTStores,
+  "Number of instrumented non floating-point stores");
+STATISTIC(
+NumInstrumentedNonFTMemcpyStores,
+"Number of instrumented non floating-point stores with memcpy semantics");
+STATISTIC(NumInstrumentedFCmp, "Number of instrumented fcmps");
+
+// Using smaller shadow types types can help improve speed. For example, `dlq`
+// is 3x slower to 5x faster in opt mode and 2-6x faster in dbg mode compared 
to
+// `dqq`.
+static cl::opt ClShadowMapping(
+"nsan-shadow-type-mapping", cl::init("dqq"),
+cl::desc("One shadow type id for each of `float`, `double`, `long double`. 
"
+ "`d`,`l`,`q`,`e` mean double, x86_fp80, fp128 (quad) and "
+ "ppc_fp128 (extended double) respectively. The default is to "
+ "shadow `float` as `double`, and `double` and `x86_fp80` as "
+ "`fp128`"),
+cl::Hidden);
+
+static cl::opt
+ClInstrumentFCmp("nsan-instrument-fcmp", cl::init(true),
+ cl::desc("Instrument floating-point comparisons"),
+ cl::Hidden);
+
+static cl::opt ClCheckFunctionsFilter(
+"check-functions-filter",
+cl::desc("Only emit checks for arguments of functions "
+ "whose names match the given regular expression"),
+cl::value_desc("regex"));
+
+static cl::opt ClTruncateFCmpEq(
+"nsan-truncate-fcmp-eq", cl::init(true),
+cl::desc(
+"This flag controls the behaviour of fcmp equality comparisons:"
+"For equality comparisons such as `x == 0.0f`, we can perform the "
+"shadow check in the shadow (`x_shadow == 0.0) == (x == 0.0f)`) or app 
"
+" domain (`(trunc(x_shadow) == 0.0f) == (x == 0.0f)`). This helps "
+"catch the case when `x_shadow` is accurate enough (and therefore "
+"close enough to zero) so that `trunc(x_shadow)` is zero even though "
+"both `x` and `x_shadow` are not. "),
+cl::Hidden);
+
+// When there is external, uninstrumented code writing to memory, the shadow
+// memory can get out of sync with the application memory. Enabling this flag
+// emits consistency checks for loads to catch this situation.
+// When everything is instrumented, this is not strictly necessary because any
+// load should have a corresponding store, but can help debug cases when the
+// framework did a bad job at tracking shadow memory modifications by failing 
on
+// load rather than store.
+// FIXME: provide a way to resume computations from the FT value when the load
+// is inconsistent. This ensures that further computations are not polluted.
+static cl::opt ClCheckLoads("nsan-check-loads", cl::init(false),
+  cl::desc("Check floating-point load"),
+  cl::Hidden);
+
+static 

[clang] [compiler-rt] [llvm] Add numerical sanitizer (PR #85916)

2024-03-21 Thread Matt Arsenault via cfe-commits


@@ -0,0 +1,2261 @@
+//===-- NumericalStabilitySanitizer.cpp 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This file is a part of NumericalStabilitySanitizer.
+//
+//===--===//
+
+#include "llvm/Transforms/Instrumentation/NumericalStabilitySanitizer.h"
+
+#include 
+#include 
+
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/Statistic.h"
+#include "llvm/ADT/StringExtras.h"
+#include "llvm/Analysis/CaptureTracking.h"
+#include "llvm/Analysis/TargetLibraryInfo.h"
+#include "llvm/Analysis/ValueTracking.h"
+#include "llvm/IR/DataLayout.h"
+#include "llvm/IR/Function.h"
+#include "llvm/IR/IRBuilder.h"
+#include "llvm/IR/IntrinsicInst.h"
+#include "llvm/IR/Intrinsics.h"
+#include "llvm/IR/LLVMContext.h"
+#include "llvm/IR/Metadata.h"
+#include "llvm/IR/Module.h"
+#include "llvm/IR/Type.h"
+#include "llvm/InitializePasses.h"
+#include "llvm/ProfileData/InstrProf.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Support/Debug.h"
+#include "llvm/Support/MathExtras.h"
+#include "llvm/Support/Regex.h"
+#include "llvm/Support/raw_ostream.h"
+#include "llvm/Transforms/Instrumentation.h"
+#include "llvm/Transforms/Utils/BasicBlockUtils.h"
+#include "llvm/Transforms/Utils/EscapeEnumerator.h"
+#include "llvm/Transforms/Utils/Local.h"
+#include "llvm/Transforms/Utils/ModuleUtils.h"
+
+using namespace llvm;
+
+#define DEBUG_TYPE "nsan"
+
+STATISTIC(NumInstrumentedFTLoads,
+  "Number of instrumented floating-point loads");
+
+STATISTIC(NumInstrumentedFTCalls,
+  "Number of instrumented floating-point calls");
+STATISTIC(NumInstrumentedFTRets,
+  "Number of instrumented floating-point returns");
+STATISTIC(NumInstrumentedFTStores,
+  "Number of instrumented floating-point stores");
+STATISTIC(NumInstrumentedNonFTStores,
+  "Number of instrumented non floating-point stores");
+STATISTIC(
+NumInstrumentedNonFTMemcpyStores,
+"Number of instrumented non floating-point stores with memcpy semantics");
+STATISTIC(NumInstrumentedFCmp, "Number of instrumented fcmps");
+
+// Using smaller shadow types types can help improve speed. For example, `dlq`
+// is 3x slower to 5x faster in opt mode and 2-6x faster in dbg mode compared 
to
+// `dqq`.
+static cl::opt ClShadowMapping(
+"nsan-shadow-type-mapping", cl::init("dqq"),
+cl::desc("One shadow type id for each of `float`, `double`, `long double`. 
"
+ "`d`,`l`,`q`,`e` mean double, x86_fp80, fp128 (quad) and "
+ "ppc_fp128 (extended double) respectively. The default is to "
+ "shadow `float` as `double`, and `double` and `x86_fp80` as "
+ "`fp128`"),
+cl::Hidden);
+
+static cl::opt
+ClInstrumentFCmp("nsan-instrument-fcmp", cl::init(true),
+ cl::desc("Instrument floating-point comparisons"),
+ cl::Hidden);
+
+static cl::opt ClCheckFunctionsFilter(
+"check-functions-filter",
+cl::desc("Only emit checks for arguments of functions "
+ "whose names match the given regular expression"),
+cl::value_desc("regex"));
+
+static cl::opt ClTruncateFCmpEq(
+"nsan-truncate-fcmp-eq", cl::init(true),
+cl::desc(
+"This flag controls the behaviour of fcmp equality comparisons:"
+"For equality comparisons such as `x == 0.0f`, we can perform the "
+"shadow check in the shadow (`x_shadow == 0.0) == (x == 0.0f)`) or app 
"
+" domain (`(trunc(x_shadow) == 0.0f) == (x == 0.0f)`). This helps "
+"catch the case when `x_shadow` is accurate enough (and therefore "
+"close enough to zero) so that `trunc(x_shadow)` is zero even though "
+"both `x` and `x_shadow` are not. "),
+cl::Hidden);
+
+// When there is external, uninstrumented code writing to memory, the shadow
+// memory can get out of sync with the application memory. Enabling this flag
+// emits consistency checks for loads to catch this situation.
+// When everything is instrumented, this is not strictly necessary because any
+// load should have a corresponding store, but can help debug cases when the
+// framework did a bad job at tracking shadow memory modifications by failing 
on
+// load rather than store.
+// FIXME: provide a way to resume computations from the FT value when the load
+// is inconsistent. This ensures that further computations are not polluted.
+static cl::opt ClCheckLoads("nsan-check-loads", cl::init(false),
+  cl::desc("Check floating-point load"),
+  cl::Hidden);
+
+static 

[clang] [compiler-rt] [llvm] Add numerical sanitizer (PR #85916)

2024-03-21 Thread Matt Arsenault via cfe-commits


@@ -0,0 +1,2261 @@
+//===-- NumericalStabilitySanitizer.cpp 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This file is a part of NumericalStabilitySanitizer.
+//
+//===--===//
+
+#include "llvm/Transforms/Instrumentation/NumericalStabilitySanitizer.h"
+
+#include 
+#include 
+
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/Statistic.h"
+#include "llvm/ADT/StringExtras.h"
+#include "llvm/Analysis/CaptureTracking.h"
+#include "llvm/Analysis/TargetLibraryInfo.h"
+#include "llvm/Analysis/ValueTracking.h"
+#include "llvm/IR/DataLayout.h"
+#include "llvm/IR/Function.h"
+#include "llvm/IR/IRBuilder.h"
+#include "llvm/IR/IntrinsicInst.h"
+#include "llvm/IR/Intrinsics.h"
+#include "llvm/IR/LLVMContext.h"
+#include "llvm/IR/Metadata.h"
+#include "llvm/IR/Module.h"
+#include "llvm/IR/Type.h"
+#include "llvm/InitializePasses.h"
+#include "llvm/ProfileData/InstrProf.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Support/Debug.h"
+#include "llvm/Support/MathExtras.h"
+#include "llvm/Support/Regex.h"
+#include "llvm/Support/raw_ostream.h"
+#include "llvm/Transforms/Instrumentation.h"
+#include "llvm/Transforms/Utils/BasicBlockUtils.h"
+#include "llvm/Transforms/Utils/EscapeEnumerator.h"
+#include "llvm/Transforms/Utils/Local.h"
+#include "llvm/Transforms/Utils/ModuleUtils.h"
+
+using namespace llvm;
+
+#define DEBUG_TYPE "nsan"
+
+STATISTIC(NumInstrumentedFTLoads,
+  "Number of instrumented floating-point loads");
+
+STATISTIC(NumInstrumentedFTCalls,
+  "Number of instrumented floating-point calls");
+STATISTIC(NumInstrumentedFTRets,
+  "Number of instrumented floating-point returns");
+STATISTIC(NumInstrumentedFTStores,
+  "Number of instrumented floating-point stores");
+STATISTIC(NumInstrumentedNonFTStores,
+  "Number of instrumented non floating-point stores");
+STATISTIC(
+NumInstrumentedNonFTMemcpyStores,
+"Number of instrumented non floating-point stores with memcpy semantics");
+STATISTIC(NumInstrumentedFCmp, "Number of instrumented fcmps");
+
+// Using smaller shadow types types can help improve speed. For example, `dlq`
+// is 3x slower to 5x faster in opt mode and 2-6x faster in dbg mode compared 
to
+// `dqq`.
+static cl::opt ClShadowMapping(
+"nsan-shadow-type-mapping", cl::init("dqq"),
+cl::desc("One shadow type id for each of `float`, `double`, `long double`. 
"
+ "`d`,`l`,`q`,`e` mean double, x86_fp80, fp128 (quad) and "
+ "ppc_fp128 (extended double) respectively. The default is to "
+ "shadow `float` as `double`, and `double` and `x86_fp80` as "
+ "`fp128`"),
+cl::Hidden);
+
+static cl::opt
+ClInstrumentFCmp("nsan-instrument-fcmp", cl::init(true),
+ cl::desc("Instrument floating-point comparisons"),
+ cl::Hidden);
+
+static cl::opt ClCheckFunctionsFilter(
+"check-functions-filter",
+cl::desc("Only emit checks for arguments of functions "
+ "whose names match the given regular expression"),
+cl::value_desc("regex"));
+
+static cl::opt ClTruncateFCmpEq(
+"nsan-truncate-fcmp-eq", cl::init(true),
+cl::desc(
+"This flag controls the behaviour of fcmp equality comparisons:"
+"For equality comparisons such as `x == 0.0f`, we can perform the "
+"shadow check in the shadow (`x_shadow == 0.0) == (x == 0.0f)`) or app 
"
+" domain (`(trunc(x_shadow) == 0.0f) == (x == 0.0f)`). This helps "
+"catch the case when `x_shadow` is accurate enough (and therefore "
+"close enough to zero) so that `trunc(x_shadow)` is zero even though "
+"both `x` and `x_shadow` are not. "),
+cl::Hidden);
+
+// When there is external, uninstrumented code writing to memory, the shadow
+// memory can get out of sync with the application memory. Enabling this flag
+// emits consistency checks for loads to catch this situation.
+// When everything is instrumented, this is not strictly necessary because any
+// load should have a corresponding store, but can help debug cases when the
+// framework did a bad job at tracking shadow memory modifications by failing 
on
+// load rather than store.
+// FIXME: provide a way to resume computations from the FT value when the load
+// is inconsistent. This ensures that further computations are not polluted.
+static cl::opt ClCheckLoads("nsan-check-loads", cl::init(false),
+  cl::desc("Check floating-point load"),
+  cl::Hidden);
+
+static 

[clang] [compiler-rt] [llvm] Add numerical sanitizer (PR #85916)

2024-03-21 Thread Matt Arsenault via cfe-commits


@@ -0,0 +1,2261 @@
+//===-- NumericalStabilitySanitizer.cpp 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This file is a part of NumericalStabilitySanitizer.
+//
+//===--===//
+
+#include "llvm/Transforms/Instrumentation/NumericalStabilitySanitizer.h"
+
+#include 
+#include 
+
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/Statistic.h"
+#include "llvm/ADT/StringExtras.h"
+#include "llvm/Analysis/CaptureTracking.h"
+#include "llvm/Analysis/TargetLibraryInfo.h"
+#include "llvm/Analysis/ValueTracking.h"
+#include "llvm/IR/DataLayout.h"
+#include "llvm/IR/Function.h"
+#include "llvm/IR/IRBuilder.h"
+#include "llvm/IR/IntrinsicInst.h"
+#include "llvm/IR/Intrinsics.h"
+#include "llvm/IR/LLVMContext.h"
+#include "llvm/IR/Metadata.h"
+#include "llvm/IR/Module.h"
+#include "llvm/IR/Type.h"
+#include "llvm/InitializePasses.h"
+#include "llvm/ProfileData/InstrProf.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Support/Debug.h"
+#include "llvm/Support/MathExtras.h"
+#include "llvm/Support/Regex.h"
+#include "llvm/Support/raw_ostream.h"
+#include "llvm/Transforms/Instrumentation.h"
+#include "llvm/Transforms/Utils/BasicBlockUtils.h"
+#include "llvm/Transforms/Utils/EscapeEnumerator.h"
+#include "llvm/Transforms/Utils/Local.h"
+#include "llvm/Transforms/Utils/ModuleUtils.h"
+
+using namespace llvm;
+
+#define DEBUG_TYPE "nsan"
+
+STATISTIC(NumInstrumentedFTLoads,
+  "Number of instrumented floating-point loads");
+
+STATISTIC(NumInstrumentedFTCalls,
+  "Number of instrumented floating-point calls");
+STATISTIC(NumInstrumentedFTRets,
+  "Number of instrumented floating-point returns");
+STATISTIC(NumInstrumentedFTStores,
+  "Number of instrumented floating-point stores");
+STATISTIC(NumInstrumentedNonFTStores,
+  "Number of instrumented non floating-point stores");
+STATISTIC(
+NumInstrumentedNonFTMemcpyStores,
+"Number of instrumented non floating-point stores with memcpy semantics");
+STATISTIC(NumInstrumentedFCmp, "Number of instrumented fcmps");
+
+// Using smaller shadow types types can help improve speed. For example, `dlq`
+// is 3x slower to 5x faster in opt mode and 2-6x faster in dbg mode compared 
to
+// `dqq`.
+static cl::opt ClShadowMapping(
+"nsan-shadow-type-mapping", cl::init("dqq"),
+cl::desc("One shadow type id for each of `float`, `double`, `long double`. 
"
+ "`d`,`l`,`q`,`e` mean double, x86_fp80, fp128 (quad) and "
+ "ppc_fp128 (extended double) respectively. The default is to "
+ "shadow `float` as `double`, and `double` and `x86_fp80` as "
+ "`fp128`"),
+cl::Hidden);
+
+static cl::opt
+ClInstrumentFCmp("nsan-instrument-fcmp", cl::init(true),
+ cl::desc("Instrument floating-point comparisons"),
+ cl::Hidden);
+
+static cl::opt ClCheckFunctionsFilter(
+"check-functions-filter",
+cl::desc("Only emit checks for arguments of functions "
+ "whose names match the given regular expression"),
+cl::value_desc("regex"));
+
+static cl::opt ClTruncateFCmpEq(
+"nsan-truncate-fcmp-eq", cl::init(true),
+cl::desc(
+"This flag controls the behaviour of fcmp equality comparisons:"
+"For equality comparisons such as `x == 0.0f`, we can perform the "
+"shadow check in the shadow (`x_shadow == 0.0) == (x == 0.0f)`) or app 
"
+" domain (`(trunc(x_shadow) == 0.0f) == (x == 0.0f)`). This helps "
+"catch the case when `x_shadow` is accurate enough (and therefore "
+"close enough to zero) so that `trunc(x_shadow)` is zero even though "
+"both `x` and `x_shadow` are not. "),
+cl::Hidden);
+
+// When there is external, uninstrumented code writing to memory, the shadow
+// memory can get out of sync with the application memory. Enabling this flag
+// emits consistency checks for loads to catch this situation.
+// When everything is instrumented, this is not strictly necessary because any
+// load should have a corresponding store, but can help debug cases when the
+// framework did a bad job at tracking shadow memory modifications by failing 
on
+// load rather than store.
+// FIXME: provide a way to resume computations from the FT value when the load
+// is inconsistent. This ensures that further computations are not polluted.
+static cl::opt ClCheckLoads("nsan-check-loads", cl::init(false),
+  cl::desc("Check floating-point load"),
+  cl::Hidden);
+
+static 

[clang] [compiler-rt] [llvm] Add numerical sanitizer (PR #85916)

2024-03-21 Thread Matt Arsenault via cfe-commits


@@ -0,0 +1,2261 @@
+//===-- NumericalStabilitySanitizer.cpp 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This file is a part of NumericalStabilitySanitizer.
+//
+//===--===//
+
+#include "llvm/Transforms/Instrumentation/NumericalStabilitySanitizer.h"
+
+#include 
+#include 
+
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/Statistic.h"
+#include "llvm/ADT/StringExtras.h"
+#include "llvm/Analysis/CaptureTracking.h"
+#include "llvm/Analysis/TargetLibraryInfo.h"
+#include "llvm/Analysis/ValueTracking.h"
+#include "llvm/IR/DataLayout.h"
+#include "llvm/IR/Function.h"
+#include "llvm/IR/IRBuilder.h"
+#include "llvm/IR/IntrinsicInst.h"
+#include "llvm/IR/Intrinsics.h"
+#include "llvm/IR/LLVMContext.h"
+#include "llvm/IR/Metadata.h"
+#include "llvm/IR/Module.h"
+#include "llvm/IR/Type.h"
+#include "llvm/InitializePasses.h"
+#include "llvm/ProfileData/InstrProf.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Support/Debug.h"
+#include "llvm/Support/MathExtras.h"
+#include "llvm/Support/Regex.h"
+#include "llvm/Support/raw_ostream.h"
+#include "llvm/Transforms/Instrumentation.h"
+#include "llvm/Transforms/Utils/BasicBlockUtils.h"
+#include "llvm/Transforms/Utils/EscapeEnumerator.h"
+#include "llvm/Transforms/Utils/Local.h"
+#include "llvm/Transforms/Utils/ModuleUtils.h"
+
+using namespace llvm;
+
+#define DEBUG_TYPE "nsan"
+
+STATISTIC(NumInstrumentedFTLoads,
+  "Number of instrumented floating-point loads");
+
+STATISTIC(NumInstrumentedFTCalls,
+  "Number of instrumented floating-point calls");
+STATISTIC(NumInstrumentedFTRets,
+  "Number of instrumented floating-point returns");
+STATISTIC(NumInstrumentedFTStores,
+  "Number of instrumented floating-point stores");
+STATISTIC(NumInstrumentedNonFTStores,
+  "Number of instrumented non floating-point stores");
+STATISTIC(
+NumInstrumentedNonFTMemcpyStores,
+"Number of instrumented non floating-point stores with memcpy semantics");
+STATISTIC(NumInstrumentedFCmp, "Number of instrumented fcmps");
+
+// Using smaller shadow types types can help improve speed. For example, `dlq`
+// is 3x slower to 5x faster in opt mode and 2-6x faster in dbg mode compared 
to
+// `dqq`.
+static cl::opt ClShadowMapping(
+"nsan-shadow-type-mapping", cl::init("dqq"),
+cl::desc("One shadow type id for each of `float`, `double`, `long double`. 
"
+ "`d`,`l`,`q`,`e` mean double, x86_fp80, fp128 (quad) and "
+ "ppc_fp128 (extended double) respectively. The default is to "
+ "shadow `float` as `double`, and `double` and `x86_fp80` as "
+ "`fp128`"),
+cl::Hidden);
+
+static cl::opt
+ClInstrumentFCmp("nsan-instrument-fcmp", cl::init(true),
+ cl::desc("Instrument floating-point comparisons"),
+ cl::Hidden);
+
+static cl::opt ClCheckFunctionsFilter(
+"check-functions-filter",
+cl::desc("Only emit checks for arguments of functions "
+ "whose names match the given regular expression"),
+cl::value_desc("regex"));
+
+static cl::opt ClTruncateFCmpEq(
+"nsan-truncate-fcmp-eq", cl::init(true),
+cl::desc(
+"This flag controls the behaviour of fcmp equality comparisons:"
+"For equality comparisons such as `x == 0.0f`, we can perform the "
+"shadow check in the shadow (`x_shadow == 0.0) == (x == 0.0f)`) or app 
"
+" domain (`(trunc(x_shadow) == 0.0f) == (x == 0.0f)`). This helps "
+"catch the case when `x_shadow` is accurate enough (and therefore "
+"close enough to zero) so that `trunc(x_shadow)` is zero even though "
+"both `x` and `x_shadow` are not. "),
+cl::Hidden);
+
+// When there is external, uninstrumented code writing to memory, the shadow
+// memory can get out of sync with the application memory. Enabling this flag
+// emits consistency checks for loads to catch this situation.
+// When everything is instrumented, this is not strictly necessary because any
+// load should have a corresponding store, but can help debug cases when the
+// framework did a bad job at tracking shadow memory modifications by failing 
on
+// load rather than store.
+// FIXME: provide a way to resume computations from the FT value when the load
+// is inconsistent. This ensures that further computations are not polluted.
+static cl::opt ClCheckLoads("nsan-check-loads", cl::init(false),
+  cl::desc("Check floating-point load"),
+  cl::Hidden);
+
+static 

[clang] [compiler-rt] [llvm] Add numerical sanitizer (PR #85916)

2024-03-21 Thread Matt Arsenault via cfe-commits


@@ -0,0 +1,2261 @@
+//===-- NumericalStabilitySanitizer.cpp 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This file is a part of NumericalStabilitySanitizer.
+//
+//===--===//
+
+#include "llvm/Transforms/Instrumentation/NumericalStabilitySanitizer.h"
+
+#include 
+#include 
+
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/Statistic.h"
+#include "llvm/ADT/StringExtras.h"
+#include "llvm/Analysis/CaptureTracking.h"
+#include "llvm/Analysis/TargetLibraryInfo.h"
+#include "llvm/Analysis/ValueTracking.h"
+#include "llvm/IR/DataLayout.h"
+#include "llvm/IR/Function.h"
+#include "llvm/IR/IRBuilder.h"
+#include "llvm/IR/IntrinsicInst.h"
+#include "llvm/IR/Intrinsics.h"
+#include "llvm/IR/LLVMContext.h"
+#include "llvm/IR/Metadata.h"
+#include "llvm/IR/Module.h"
+#include "llvm/IR/Type.h"
+#include "llvm/InitializePasses.h"
+#include "llvm/ProfileData/InstrProf.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Support/Debug.h"
+#include "llvm/Support/MathExtras.h"
+#include "llvm/Support/Regex.h"
+#include "llvm/Support/raw_ostream.h"
+#include "llvm/Transforms/Instrumentation.h"
+#include "llvm/Transforms/Utils/BasicBlockUtils.h"
+#include "llvm/Transforms/Utils/EscapeEnumerator.h"
+#include "llvm/Transforms/Utils/Local.h"
+#include "llvm/Transforms/Utils/ModuleUtils.h"
+
+using namespace llvm;
+
+#define DEBUG_TYPE "nsan"
+
+STATISTIC(NumInstrumentedFTLoads,
+  "Number of instrumented floating-point loads");
+
+STATISTIC(NumInstrumentedFTCalls,
+  "Number of instrumented floating-point calls");
+STATISTIC(NumInstrumentedFTRets,
+  "Number of instrumented floating-point returns");
+STATISTIC(NumInstrumentedFTStores,
+  "Number of instrumented floating-point stores");
+STATISTIC(NumInstrumentedNonFTStores,
+  "Number of instrumented non floating-point stores");
+STATISTIC(
+NumInstrumentedNonFTMemcpyStores,
+"Number of instrumented non floating-point stores with memcpy semantics");
+STATISTIC(NumInstrumentedFCmp, "Number of instrumented fcmps");
+
+// Using smaller shadow types types can help improve speed. For example, `dlq`
+// is 3x slower to 5x faster in opt mode and 2-6x faster in dbg mode compared 
to
+// `dqq`.
+static cl::opt ClShadowMapping(
+"nsan-shadow-type-mapping", cl::init("dqq"),
+cl::desc("One shadow type id for each of `float`, `double`, `long double`. 
"
+ "`d`,`l`,`q`,`e` mean double, x86_fp80, fp128 (quad) and "
+ "ppc_fp128 (extended double) respectively. The default is to "
+ "shadow `float` as `double`, and `double` and `x86_fp80` as "
+ "`fp128`"),
+cl::Hidden);
+
+static cl::opt
+ClInstrumentFCmp("nsan-instrument-fcmp", cl::init(true),
+ cl::desc("Instrument floating-point comparisons"),
+ cl::Hidden);
+
+static cl::opt ClCheckFunctionsFilter(
+"check-functions-filter",
+cl::desc("Only emit checks for arguments of functions "
+ "whose names match the given regular expression"),
+cl::value_desc("regex"));
+
+static cl::opt ClTruncateFCmpEq(
+"nsan-truncate-fcmp-eq", cl::init(true),
+cl::desc(
+"This flag controls the behaviour of fcmp equality comparisons:"
+"For equality comparisons such as `x == 0.0f`, we can perform the "
+"shadow check in the shadow (`x_shadow == 0.0) == (x == 0.0f)`) or app 
"
+" domain (`(trunc(x_shadow) == 0.0f) == (x == 0.0f)`). This helps "
+"catch the case when `x_shadow` is accurate enough (and therefore "
+"close enough to zero) so that `trunc(x_shadow)` is zero even though "
+"both `x` and `x_shadow` are not. "),
+cl::Hidden);
+
+// When there is external, uninstrumented code writing to memory, the shadow
+// memory can get out of sync with the application memory. Enabling this flag
+// emits consistency checks for loads to catch this situation.
+// When everything is instrumented, this is not strictly necessary because any
+// load should have a corresponding store, but can help debug cases when the
+// framework did a bad job at tracking shadow memory modifications by failing 
on
+// load rather than store.
+// FIXME: provide a way to resume computations from the FT value when the load
+// is inconsistent. This ensures that further computations are not polluted.
+static cl::opt ClCheckLoads("nsan-check-loads", cl::init(false),
+  cl::desc("Check floating-point load"),
+  cl::Hidden);
+
+static 

[clang] [compiler-rt] [llvm] Add numerical sanitizer (PR #85916)

2024-03-21 Thread Matt Arsenault via cfe-commits


@@ -0,0 +1,2261 @@
+//===-- NumericalStabilitySanitizer.cpp 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This file is a part of NumericalStabilitySanitizer.
+//
+//===--===//
+
+#include "llvm/Transforms/Instrumentation/NumericalStabilitySanitizer.h"
+
+#include 
+#include 
+
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/Statistic.h"
+#include "llvm/ADT/StringExtras.h"
+#include "llvm/Analysis/CaptureTracking.h"
+#include "llvm/Analysis/TargetLibraryInfo.h"
+#include "llvm/Analysis/ValueTracking.h"
+#include "llvm/IR/DataLayout.h"
+#include "llvm/IR/Function.h"
+#include "llvm/IR/IRBuilder.h"
+#include "llvm/IR/IntrinsicInst.h"
+#include "llvm/IR/Intrinsics.h"
+#include "llvm/IR/LLVMContext.h"
+#include "llvm/IR/Metadata.h"
+#include "llvm/IR/Module.h"
+#include "llvm/IR/Type.h"
+#include "llvm/InitializePasses.h"
+#include "llvm/ProfileData/InstrProf.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Support/Debug.h"
+#include "llvm/Support/MathExtras.h"
+#include "llvm/Support/Regex.h"
+#include "llvm/Support/raw_ostream.h"
+#include "llvm/Transforms/Instrumentation.h"
+#include "llvm/Transforms/Utils/BasicBlockUtils.h"
+#include "llvm/Transforms/Utils/EscapeEnumerator.h"
+#include "llvm/Transforms/Utils/Local.h"
+#include "llvm/Transforms/Utils/ModuleUtils.h"
+
+using namespace llvm;
+
+#define DEBUG_TYPE "nsan"
+
+STATISTIC(NumInstrumentedFTLoads,
+  "Number of instrumented floating-point loads");
+
+STATISTIC(NumInstrumentedFTCalls,
+  "Number of instrumented floating-point calls");
+STATISTIC(NumInstrumentedFTRets,
+  "Number of instrumented floating-point returns");
+STATISTIC(NumInstrumentedFTStores,
+  "Number of instrumented floating-point stores");
+STATISTIC(NumInstrumentedNonFTStores,
+  "Number of instrumented non floating-point stores");
+STATISTIC(
+NumInstrumentedNonFTMemcpyStores,
+"Number of instrumented non floating-point stores with memcpy semantics");
+STATISTIC(NumInstrumentedFCmp, "Number of instrumented fcmps");
+
+// Using smaller shadow types types can help improve speed. For example, `dlq`
+// is 3x slower to 5x faster in opt mode and 2-6x faster in dbg mode compared 
to
+// `dqq`.
+static cl::opt ClShadowMapping(
+"nsan-shadow-type-mapping", cl::init("dqq"),
+cl::desc("One shadow type id for each of `float`, `double`, `long double`. 
"
+ "`d`,`l`,`q`,`e` mean double, x86_fp80, fp128 (quad) and "
+ "ppc_fp128 (extended double) respectively. The default is to "
+ "shadow `float` as `double`, and `double` and `x86_fp80` as "
+ "`fp128`"),
+cl::Hidden);
+
+static cl::opt
+ClInstrumentFCmp("nsan-instrument-fcmp", cl::init(true),
+ cl::desc("Instrument floating-point comparisons"),
+ cl::Hidden);
+
+static cl::opt ClCheckFunctionsFilter(
+"check-functions-filter",
+cl::desc("Only emit checks for arguments of functions "
+ "whose names match the given regular expression"),
+cl::value_desc("regex"));
+
+static cl::opt ClTruncateFCmpEq(
+"nsan-truncate-fcmp-eq", cl::init(true),
+cl::desc(
+"This flag controls the behaviour of fcmp equality comparisons:"
+"For equality comparisons such as `x == 0.0f`, we can perform the "
+"shadow check in the shadow (`x_shadow == 0.0) == (x == 0.0f)`) or app 
"
+" domain (`(trunc(x_shadow) == 0.0f) == (x == 0.0f)`). This helps "
+"catch the case when `x_shadow` is accurate enough (and therefore "
+"close enough to zero) so that `trunc(x_shadow)` is zero even though "
+"both `x` and `x_shadow` are not. "),
+cl::Hidden);
+
+// When there is external, uninstrumented code writing to memory, the shadow
+// memory can get out of sync with the application memory. Enabling this flag
+// emits consistency checks for loads to catch this situation.
+// When everything is instrumented, this is not strictly necessary because any
+// load should have a corresponding store, but can help debug cases when the
+// framework did a bad job at tracking shadow memory modifications by failing 
on
+// load rather than store.
+// FIXME: provide a way to resume computations from the FT value when the load
+// is inconsistent. This ensures that further computations are not polluted.
+static cl::opt ClCheckLoads("nsan-check-loads", cl::init(false),
+  cl::desc("Check floating-point load"),
+  cl::Hidden);
+
+static 

[clang] [RISCV][FMV] Support target_clones (PR #85786)

2024-03-21 Thread Luke Lau via cfe-commits

lukel97 wrote:

Can this land until #85790 lands?

https://github.com/llvm/llvm-project/pull/85786
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Improves -print-library-module-manifest-path. (PR #85943)

2024-03-21 Thread Mark de Wever via cfe-commits


@@ -3,20 +3,29 @@
 // RUN: rm -rf %t && split-file %s %t && cd %t
 // RUN: mkdir -p %t/Inputs/usr/lib/x86_64-linux-gnu
 // RUN: touch %t/Inputs/usr/lib/x86_64-linux-gnu/libc++.so
+// RUN: touch %t/Inputs/usr/lib/x86_64-linux-gnu/libc++.a
 
 // RUN: %clang -print-library-module-manifest-path \
 // RUN: -stdlib=libc++ \
 // RUN: -resource-dir=%t/Inputs/usr/lib/x86_64-linux-gnu \
 // RUN: --target=x86_64-linux-gnu 2>&1 \
 // RUN:   | FileCheck libcxx-no-module-json.cpp
 
-// RUN: touch %t/Inputs/usr/lib/x86_64-linux-gnu/modules.json
+// RUN: touch %t/Inputs/usr/lib/x86_64-linux-gnu/libc++.modules.json
 // RUN: %clang -print-library-module-manifest-path \
 // RUN: -stdlib=libc++ \
 // RUN: -resource-dir=%t/Inputs/usr/lib/x86_64-linux-gnu \
 // RUN: --target=x86_64-linux-gnu 2>&1 \
 // RUN:   | FileCheck libcxx.cpp
 
+// RUN: rm %t/Inputs/usr/lib/x86_64-linux-gnu/libc++.so

mordante wrote:

Note this test is a bit tricky since it may find other `libc++.so` files in 
Clang's search path. I didn't find a way to remove the "default" search path.

https://github.com/llvm/llvm-project/pull/85943
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Improves -print-library-module-manifest-path. (PR #85943)

2024-03-21 Thread Mark de Wever via cfe-commits

https://github.com/mordante ready_for_review 
https://github.com/llvm/llvm-project/pull/85943
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Improves -print-library-module-manifest-path. (PR #85943)

2024-03-21 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-driver

Author: Mark de Wever (mordante)


Changes

This adds a libc++ to modules.json as is currently used by libc++. When 
libc++.so is not found the function will search for libc++.a as fallback.

---
Full diff: https://github.com/llvm/llvm-project/pull/85943.diff


2 Files Affected:

- (modified) clang/lib/Driver/Driver.cpp (+28-21) 
- (modified) clang/test/Driver/modules-print-library-module-manifest-path.cpp 
(+17-2) 


``diff
diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 1daf588142b3b4..94dd1aa27e256b 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -6199,28 +6199,35 @@ std::string Driver::GetStdModuleManifestPath(const 
Compilation &C,
 
   switch (TC.GetCXXStdlibType(C.getArgs())) {
   case ToolChain::CST_Libcxx: {
-std::string lib = GetFilePath("libc++.so", TC);
-
-// Note when there are multiple flavours of libc++ the module json needs to
-// look at the command-line arguments for the proper json.
-// These flavours do not exist at the moment, but there are plans to
-// provide a variant that is built with sanitizer instrumentation enabled.
-
-// For example
-//  StringRef modules = [&] {
-//const SanitizerArgs &Sanitize = TC.getSanitizerArgs(C.getArgs());
-//if (Sanitize.needsAsanRt())
-//  return "modules-asan.json";
-//return "modules.json";
-//  }();
-
-SmallString<128> path(lib.begin(), lib.end());
-llvm::sys::path::remove_filename(path);
-llvm::sys::path::append(path, "modules.json");
-if (TC.getVFS().exists(path))
-  return static_cast(path);
+auto evaluate = [&](const char *library) -> std::optional {
+  std::string lib = GetFilePath(library, TC);
+
+  // Note when there are multiple flavours of libc++ the module json needs
+  // to look at the command-line arguments for the proper json. These
+  // flavours do not exist at the moment, but there are plans to provide a
+  // variant that is built with sanitizer instrumentation enabled.
+
+  // For example
+  //  StringRef modules = [&] {
+  //const SanitizerArgs &Sanitize = TC.getSanitizerArgs(C.getArgs());
+  //if (Sanitize.needsAsanRt())
+  //  return "libc++.modules-asan.json";
+  //return "libc++.modules.json";
+  //  }();
+
+  SmallString<128> path(lib.begin(), lib.end());
+  llvm::sys::path::remove_filename(path);
+  llvm::sys::path::append(path, "libc++.modules.json");
+  if (TC.getVFS().exists(path))
+return static_cast(path);
+
+  return {};
+};
 
-return error;
+if (std::optional result = evaluate("libc++.so"); result)
+  return *result;
+
+return evaluate("libc++.a").value_or(error);
   }
 
   case ToolChain::CST_Libstdcxx:
diff --git a/clang/test/Driver/modules-print-library-module-manifest-path.cpp 
b/clang/test/Driver/modules-print-library-module-manifest-path.cpp
index 24797002b80f53..3ba2709ad95cc8 100644
--- a/clang/test/Driver/modules-print-library-module-manifest-path.cpp
+++ b/clang/test/Driver/modules-print-library-module-manifest-path.cpp
@@ -3,6 +3,7 @@
 // RUN: rm -rf %t && split-file %s %t && cd %t
 // RUN: mkdir -p %t/Inputs/usr/lib/x86_64-linux-gnu
 // RUN: touch %t/Inputs/usr/lib/x86_64-linux-gnu/libc++.so
+// RUN: touch %t/Inputs/usr/lib/x86_64-linux-gnu/libc++.a
 
 // RUN: %clang -print-library-module-manifest-path \
 // RUN: -stdlib=libc++ \
@@ -10,13 +11,21 @@
 // RUN: --target=x86_64-linux-gnu 2>&1 \
 // RUN:   | FileCheck libcxx-no-module-json.cpp
 
-// RUN: touch %t/Inputs/usr/lib/x86_64-linux-gnu/modules.json
+// RUN: touch %t/Inputs/usr/lib/x86_64-linux-gnu/libc++.modules.json
 // RUN: %clang -print-library-module-manifest-path \
 // RUN: -stdlib=libc++ \
 // RUN: -resource-dir=%t/Inputs/usr/lib/x86_64-linux-gnu \
 // RUN: --target=x86_64-linux-gnu 2>&1 \
 // RUN:   | FileCheck libcxx.cpp
 
+// RUN: rm %t/Inputs/usr/lib/x86_64-linux-gnu/libc++.so
+// RUN: touch %t/Inputs/usr/lib/x86_64-linux-gnu/libc++.a
+// RUN: %clang -print-library-module-manifest-path \
+// RUN: -stdlib=libc++ \
+// RUN: -resource-dir=%t/Inputs/usr/lib/x86_64-linux-gnu \
+// RUN: --target=x86_64-linux-gnu 2>&1 \
+// RUN:   | FileCheck libcxx-no-shared-lib.cpp
+
 // RUN: %clang -print-library-module-manifest-path \
 // RUN: -stdlib=libstdc++ \
 // RUN: -resource-dir=%t/Inputs/usr/lib/x86_64-linux-gnu \
@@ -29,7 +38,13 @@
 
 //--- libcxx.cpp
 
-// CHECK: {{.*}}/Inputs/usr/lib/x86_64-linux-gnu{{/|\\}}modules.json
+// CHECK: {{.*}}/Inputs/usr/lib/x86_64-linux-gnu{{/|\\}}libc++.modules.json
+
+//--- libcxx-no-shared-lib.cpp
+
+// Note this might find a different path depending whether search path
+// contains a different libc++.so.
+// CHECK: {{.*}}libc++.modules.json
 
 //--- libstdcxx.cpp
 

``




https://github.com/llvm/llvm-project/pull/85943
_

[clang] [llvm] [AsmPrinter,X86] Hard code AT&T syntax input for module-level inline assembly for MSVC triples (PR #85668)

2024-03-21 Thread Nico Weber via cfe-commits

nico wrote:

Looks like we could fix code on our end and this here isn't needed. But maybe 
the current behavior isn't 100% ideal.

Here's what I think the situation currently is (please correct me if I'm wrong):
* With clang-cl, you get intel assembly output by default with `/FA`. That's 
good.
* With clang, you get AT&T assembly output by default with `-S`, and intel 
assembly output with -masm=intel. That's good.
* With clang, the syntax for `asm()` is AT&T by default, and intel with 
-masm=intel. That's good.
* With clang-cl, `__asm { ... }` blocks always use Intel syntax. That's good.
* With clang-cl, the syntax for `asm()` is intel by default, and there's no way 
to change this. (This is now consistent between module-level assembly and 
function-local assembly. It's good that they're consistent, that's better than 
before.)

The last point seems suboptimal to me. cl.exe doesn't support `asm()`, only 
`__asm {}`. So users that use `asm()` with clang-cl probably want to share that 
code with other platforms where they use `asm()` too.

Ideally, clang-cl could use intel asm output by default, intel asm input for 
`__asm {}` blocks, but at&t style asm input for `asm()`. And ideally it could 
also offer a flag to opt in to intel style asm input for `asm()`. (And the 
pragma mentioned in https://reviews.llvm.org/D113707 might be nice too.)

Does that sound right?

(I'm not saying you have to do any of this! Just want to check if we agree on 
this assessment of the state of the world.)

https://github.com/llvm/llvm-project/pull/85668
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 2699072 - [clang] Accept lambdas in C++03 as an extensions (#73376)

2024-03-21 Thread via cfe-commits

Author: Nikolas Klauser
Date: 2024-03-21T12:57:24+01:00
New Revision: 2699072b4bc8d8d5e84eb66af38face73ceeb4d3

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

LOG: [clang] Accept lambdas in C++03 as an extensions (#73376)

Implements
https://discourse.llvm.org/t/rfc-allow-c-11-lambdas-in-c-03-as-an-extension/75262

Added: 
clang/test/Parser/cxx03-lambda-extension.cpp

Modified: 
clang/docs/LanguageExtensions.rst
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/DiagnosticParseKinds.td
clang/include/clang/Basic/Features.def
clang/lib/Parse/ParseExpr.cpp
clang/lib/Parse/ParseExprCXX.cpp
clang/lib/Parse/ParseInit.cpp
clang/lib/Sema/SemaDecl.cpp
clang/lib/Sema/SemaDeclCXX.cpp
clang/test/Lexer/has_extension_cxx.cpp
clang/test/OpenMP/declare_reduction_messages.cpp
clang/test/OpenMP/openmp_check.cpp
clang/test/Parser/cxx0x-lambda-expressions.cpp
clang/test/Parser/cxx2b-lambdas.cpp
clang/test/Parser/objcxx-lambda-expressions-neg.mm
clang/test/ParserHLSL/group_shared.hlsl
clang/test/SemaCXX/cxx2a-template-lambdas.cpp
clang/test/SemaCXX/lambda-expressions.cpp
clang/test/SemaCXX/lambda-implicit-this-capture.cpp
clang/test/SemaCXX/lambda-invalid-capture.cpp
clang/test/SemaCXX/new-delete.cpp

Removed: 




diff  --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index 13d7261d83d7f1..201a4c27f7dd8b 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -1459,40 +1459,45 @@ More information could be found `here 

 Language Extensions Back-ported to Previous Standards
 =
 
-==  
= =
-FeatureFeature Test Macro   
Introduced In Backported To
-==  
= =
-variadic templates __cpp_variadic_templates C++11  
   C++03
-Alias templates__cpp_alias_templatesC++11  
   C++03
-Non-static data member initializers__cpp_nsdmi  C++11  
   C++03
-Range-based ``for`` loop   __cpp_range_based_forC++11  
   C++03
-RValue references  __cpp_rvalue_references  C++11  
   C++03
-Attributes __cpp_attributes C++11  
   C++03
-variable templates __cpp_variable_templates C++14  
   C++03
-Binary literals__cpp_binary_literalsC++14  
   C++03
-Relaxed constexpr  __cpp_constexpr  C++14  
   C++11
-``if constexpr``   __cpp_if_constexpr   C++17  
   C++11
-fold expressions   __cpp_fold_expressions   C++17  
   C++03
-Lambda capture of \*this by value  __cpp_capture_star_this  C++17  
   C++11
-Attributes on enums__cpp_enumerator_attributes  C++17  
   C++03
-Guaranteed copy elision__cpp_guaranteed_copy_elisionC++17  
   C++03
-Hexadecimal floating literals  __cpp_hex_float  C++17  
   C++03
-``inline`` variables   __cpp_inline_variables   C++17  
   C++03
-Attributes on namespaces   __cpp_namespace_attributes   C++17  
   C++11
-Structured bindings__cpp_structured_bindingsC++17  
   C++03
-template template arguments__cpp_template_template_args C++17  
   C++03
-``static operator[]``  __cpp_multidimensional_subscript C++20  
   C++03
-Designated initializers__cpp_designated_initializersC++20  
   C++03
-Conditional ``explicit``   __cpp_conditional_explicit   C++20  
   C++03
-``using enum`` __cpp_using_enum C++20  
   C++03
-``if consteval``   __cpp_if_consteval   C++23  
   C++20
-``static operator()``  __cpp_static_call_operator   C++23  
   C++03
-Attributes on Lambda-ExpressionsC++23  
   C++11
---  
- -
-Designated initializers (N494)  C99
   C89
-Array & element qualification (N2607)   C23
   C89
-Att

[clang] [clang] Accept lambdas in C++03 as an extensions (PR #73376)

2024-03-21 Thread Nikolas Klauser via cfe-commits

https://github.com/philnik777 closed 
https://github.com/llvm/llvm-project/pull/73376
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] move -Wcast-function-type under -Wextra (PR #77178)

2024-03-21 Thread Aaron Ballman via cfe-commits

AaronBallman wrote:

I'm confused as to how this code ever compiled in the first place... In each 
case, this is C++ code that's failing:
```
/home/buildbots/llvm-external-buildbots/workers/ppc64le-clang-rhel-test/clang-ppc64le-rhel/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_posix_libcdep.cpp:219:25:
 error: cast from 'SignalHandlerType' (aka 'void (*)(int, void *, void *)') to 
'sa_sigaction_t' (aka 'void (*)(int, siginfo_t *, void *)') converts to 
incompatible function type [-Werror,-Wcast-function-type-strict]

/home/buildbots/llvm-external-buildbots/workers/ppc64le-clang-rhel-test/clang-ppc64le-rhel/llvm-project/compiler-rt/lib/tsan/rtl/tsan_interceptors_posix.cpp:437:4:
 error: cast from 'void (*)()' to 'void (*)(void *)' converts to incompatible 
function type [-Werror,-Wcast-function-type-strict]

/home/buildbots/llvm-external-buildbots/workers/ppc64le-clang-rhel-test/clang-ppc64le-rhel/llvm-project/compiler-rt/lib/tsan/rtl/tsan_interceptors_posix.cpp:460:54:
 error: cast from 'void (*)(void *)' to 'void (*)()' converts to incompatible 
function type [-Werror,-Wcast-function-type-strict]
```
All of which is being compiled in `-std=c++17` and none of which are valid in 
C++ and the behavior is the same between Clang 18, trunk, and GCC: 
https://godbolt.org/z/WY9zvsa8z

@amy-kwan we may need some help from you with investigating this; but in the 
meantime, this commit can be reverted to get the bots back to green if that's 
blocking you.


https://github.com/llvm/llvm-project/pull/77178
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][PowerPC] Add flag to enable compatibility with GNU for complex arguments (PR #77732)

2024-03-21 Thread zhijian lin via cfe-commits

https://github.com/diggerlin edited 
https://github.com/llvm/llvm-project/pull/77732
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][PowerPC] Add flag to enable compatibility with GNU for complex arguments (PR #77732)

2024-03-21 Thread zhijian lin via cfe-commits

https://github.com/diggerlin edited 
https://github.com/llvm/llvm-project/pull/77732
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] move -Wcast-function-type under -Wextra (PR #77178)

2024-03-21 Thread Abhin P Jose via cfe-commits

Abhinkop wrote:

> I'm confused as to how this code ever compiled in the first place... In each 
> case, this is C++ code that's failing:
> 
> ```
> /home/buildbots/llvm-external-buildbots/workers/ppc64le-clang-rhel-test/clang-ppc64le-rhel/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_posix_libcdep.cpp:219:25:
>  error: cast from 'SignalHandlerType' (aka 'void (*)(int, void *, void *)') 
> to 'sa_sigaction_t' (aka 'void (*)(int, siginfo_t *, void *)') converts to 
> incompatible function type [-Werror,-Wcast-function-type-strict]
> 
> /home/buildbots/llvm-external-buildbots/workers/ppc64le-clang-rhel-test/clang-ppc64le-rhel/llvm-project/compiler-rt/lib/tsan/rtl/tsan_interceptors_posix.cpp:437:4:
>  error: cast from 'void (*)()' to 'void (*)(void *)' converts to incompatible 
> function type [-Werror,-Wcast-function-type-strict]
> 
> /home/buildbots/llvm-external-buildbots/workers/ppc64le-clang-rhel-test/clang-ppc64le-rhel/llvm-project/compiler-rt/lib/tsan/rtl/tsan_interceptors_posix.cpp:460:54:
>  error: cast from 'void (*)(void *)' to 'void (*)()' converts to incompatible 
> function type [-Werror,-Wcast-function-type-strict]
> ```
> 
> All of which is being compiled in `-std=c++17` and none of which are valid in 
> C++ and the behavior is the same between Clang 18, trunk, and GCC: 
> https://godbolt.org/z/WY9zvsa8z
> 
> @amy-kwan we may need some help from you with investigating this; but in the 
> meantime, this commit can be reverted to get the bots back to green if that's 
> blocking you.

@AaronBallman There was a forced/explicit typecasting done, and hence the 
compiler didn't complain. for example, https://godbolt.org/z/G94r7qvxh . When 
the -Werror flag coupled with -Wextra flag caught this conversion, for example, 
https://godbolt.org/z/6bMrdfe4n. I hope this might help to provide some context.

https://github.com/llvm/llvm-project/pull/77178
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Improves -print-library-module-manifest-path. (PR #85943)

2024-03-21 Thread Chuanqi Xu via cfe-commits

https://github.com/ChuanqiXu9 approved this pull request.

LGTM

https://github.com/llvm/llvm-project/pull/85943
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 49b5208 - [X86][Headers] Specify result of NaN comparisons (#85862)

2024-03-21 Thread via cfe-commits

Author: Paul T Robinson
Date: 2024-03-21T09:09:34-04:00
New Revision: 49b520856967c2354339d3c2a05fcf1d2d637f30

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

LOG: [X86][Headers] Specify result of NaN comparisons (#85862)

Make sure all float/double comparison intrinsics specify what happens
with a NaN input. Update some existing descriptions of comparison
results to make them all consistent.

Also replace "yields" with "returns" throughout.

Added: 


Modified: 
clang/lib/Headers/avxintrin.h
clang/lib/Headers/emmintrin.h
clang/lib/Headers/xmmintrin.h

Removed: 




diff  --git a/clang/lib/Headers/avxintrin.h b/clang/lib/Headers/avxintrin.h
index a8882e82e171af..be7a0b247e03d4 100644
--- a/clang/lib/Headers/avxintrin.h
+++ b/clang/lib/Headers/avxintrin.h
@@ -207,6 +207,8 @@ _mm256_div_ps(__m256 __a, __m256 __b)
 /// Compares two 256-bit vectors of [4 x double] and returns the greater
 ///of each pair of values.
 ///
+///If either value in a comparison is NaN, returns the value from \a __b.
+///
 /// \headerfile 
 ///
 /// This intrinsic corresponds to the  VMAXPD  instruction.
@@ -226,6 +228,8 @@ _mm256_max_pd(__m256d __a, __m256d __b)
 /// Compares two 256-bit vectors of [8 x float] and returns the greater
 ///of each pair of values.
 ///
+///If either value in a comparison is NaN, returns the value from \a __b.
+///
 /// \headerfile 
 ///
 /// This intrinsic corresponds to the  VMAXPS  instruction.
@@ -245,6 +249,8 @@ _mm256_max_ps(__m256 __a, __m256 __b)
 /// Compares two 256-bit vectors of [4 x double] and returns the lesser
 ///of each pair of values.
 ///
+///If either value in a comparison is NaN, returns the value from \a __b.
+///
 /// \headerfile 
 ///
 /// This intrinsic corresponds to the  VMINPD  instruction.
@@ -264,6 +270,8 @@ _mm256_min_pd(__m256d __a, __m256d __b)
 /// Compares two 256-bit vectors of [8 x float] and returns the lesser
 ///of each pair of values.
 ///
+///If either value in a comparison is NaN, returns the value from \a __b.
+///
 /// \headerfile 
 ///
 /// This intrinsic corresponds to the  VMINPS  instruction.
@@ -1604,9 +1612,9 @@ _mm256_blendv_ps(__m256 __a, __m256 __b, __m256 __c)
 ///128-bit vectors of [2 x double], using the operation specified by the
 ///immediate integer operand.
 ///
-///Returns a [2 x double] vector consisting of two doubles corresponding to
-///the two comparison results: zero if the comparison is false, and all 1's
-///if the comparison is true.
+///Each comparison returns 0x0 for false, 0x for true.
+///If either value in a comparison is NaN, comparisons that are ordered
+///return false, and comparisons that are unordered return true.
 ///
 /// \headerfile 
 ///
@@ -1663,9 +1671,9 @@ _mm256_blendv_ps(__m256 __a, __m256 __b, __m256 __c)
 ///[4 x float], using the operation specified by the immediate integer
 ///operand.
 ///
-///Returns a [4 x float] vector consisting of four floats corresponding to
-///the four comparison results: zero if the comparison is false, and all 
1's
-///if the comparison is true.
+///Each comparison returns 0x0 for false, 0x for true.
+///If either value in a comparison is NaN, comparisons that are ordered
+///return false, and comparisons that are unordered return true.
 ///
 /// \headerfile 
 ///
@@ -1721,9 +1729,9 @@ _mm256_blendv_ps(__m256 __a, __m256 __b, __m256 __c)
 ///256-bit vectors of [4 x double], using the operation specified by the
 ///immediate integer operand.
 ///
-///Returns a [4 x double] vector consisting of four doubles corresponding 
to
-///the four comparison results: zero if the comparison is false, and all 
1's
-///if the comparison is true.
+///Each comparison returns 0x0 for false, 0x for true.
+///If either value in a comparison is NaN, comparisons that are ordered
+///return false, and comparisons that are unordered return true.
 ///
 /// \headerfile 
 ///
@@ -1781,9 +1789,9 @@ _mm256_blendv_ps(__m256 __a, __m256 __b, __m256 __c)
 ///[8 x float], using the operation specified by the immediate integer
 ///operand.
 ///
-///Returns a [8 x float] vector consisting of eight floats corresponding to
-///the eight comparison results: zero if the comparison is false, and all
-///1's if the comparison is true.
+///Each comparison returns 0x0 for false, 0x for true.
+///If either value in a comparison is NaN, comparisons that are ordered
+///return false, and comparisons that are unordered return true.
 ///
 /// \headerfile 
 ///
@@ -1842,8 +1850,9 @@ _mm256_blendv_ps(__m256 __a, __m256 __b, __m256 __c)
 ///two 128-bit vectors of [2 x double], using th

[clang] [X86][Headers] Specify result of NaN comparisons (PR #85862)

2024-03-21 Thread Paul T Robinson via cfe-commits

https://github.com/pogo59 closed https://github.com/llvm/llvm-project/pull/85862
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] move -Wcast-function-type under -Wextra (PR #77178)

2024-03-21 Thread Amy Kwan via cfe-commits

amy-kwan wrote:

> I'm confused as to how this code ever compiled in the first place... In each 
> case, this is C++ code that's failing:
> 
> ```
> /home/buildbots/llvm-external-buildbots/workers/ppc64le-clang-rhel-test/clang-ppc64le-rhel/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_posix_libcdep.cpp:219:25:
>  error: cast from 'SignalHandlerType' (aka 'void (*)(int, void *, void *)') 
> to 'sa_sigaction_t' (aka 'void (*)(int, siginfo_t *, void *)') converts to 
> incompatible function type [-Werror,-Wcast-function-type-strict]
> 
> /home/buildbots/llvm-external-buildbots/workers/ppc64le-clang-rhel-test/clang-ppc64le-rhel/llvm-project/compiler-rt/lib/tsan/rtl/tsan_interceptors_posix.cpp:437:4:
>  error: cast from 'void (*)()' to 'void (*)(void *)' converts to incompatible 
> function type [-Werror,-Wcast-function-type-strict]
> 
> /home/buildbots/llvm-external-buildbots/workers/ppc64le-clang-rhel-test/clang-ppc64le-rhel/llvm-project/compiler-rt/lib/tsan/rtl/tsan_interceptors_posix.cpp:460:54:
>  error: cast from 'void (*)(void *)' to 'void (*)()' converts to incompatible 
> function type [-Werror,-Wcast-function-type-strict]
> ```
> 
> All of which is being compiled in `-std=c++17` and none of which are valid in 
> C++ and the behavior is the same between Clang 18, trunk, and GCC: 
> https://godbolt.org/z/WY9zvsa8z
> 
> @amy-kwan we may need some help from you with investigating this; but in the 
> meantime, this commit can be reverted to get the bots back to green if that's 
> blocking you.

@AaronBallman Sounds good. I am ok with this commit being reverted and we can 
investigate on the side.


https://github.com/llvm/llvm-project/pull/77178
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] move -Wcast-function-type under -Wextra (PR #77178)

2024-03-21 Thread Aaron Ballman via cfe-commits

AaronBallman wrote:

> > I'm confused as to how this code ever compiled in the first place... In 
> > each case, this is C++ code that's failing:
> > ```
> > /home/buildbots/llvm-external-buildbots/workers/ppc64le-clang-rhel-test/clang-ppc64le-rhel/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_posix_libcdep.cpp:219:25:
> >  error: cast from 'SignalHandlerType' (aka 'void (*)(int, void *, void *)') 
> > to 'sa_sigaction_t' (aka 'void (*)(int, siginfo_t *, void *)') converts to 
> > incompatible function type [-Werror,-Wcast-function-type-strict]
> > 
> > /home/buildbots/llvm-external-buildbots/workers/ppc64le-clang-rhel-test/clang-ppc64le-rhel/llvm-project/compiler-rt/lib/tsan/rtl/tsan_interceptors_posix.cpp:437:4:
> >  error: cast from 'void (*)()' to 'void (*)(void *)' converts to 
> > incompatible function type [-Werror,-Wcast-function-type-strict]
> > 
> > /home/buildbots/llvm-external-buildbots/workers/ppc64le-clang-rhel-test/clang-ppc64le-rhel/llvm-project/compiler-rt/lib/tsan/rtl/tsan_interceptors_posix.cpp:460:54:
> >  error: cast from 'void (*)(void *)' to 'void (*)()' converts to 
> > incompatible function type [-Werror,-Wcast-function-type-strict]
> > ```
> > 
> > 
> > 
> >   
> > 
> > 
> >   
> > 
> > 
> > 
> >   
> > All of which is being compiled in `-std=c++17` and none of which are valid 
> > in C++ and the behavior is the same between Clang 18, trunk, and GCC: 
> > https://godbolt.org/z/WY9zvsa8z
> > @amy-kwan we may need some help from you with investigating this; but in 
> > the meantime, this commit can be reverted to get the bots back to green if 
> > that's blocking you.
> 
> @AaronBallman There was a forced/explicit typecasting done, and hence the 
> compiler didn't complain. for example, https://godbolt.org/z/G94r7qvxh . When 
> the -Werror flag coupled with -Wextra flag caught this conversion, for 
> example, https://godbolt.org/z/6bMrdfe4n. I hope this might help to provide 
> some context.

Ah! That does provide the context I needed, thank you! And I think I see the 
issue:

https://github.com/llvm/llvm-project/blob/734026347cca85cf0e242ef5f04896f55e0ac113/clang/include/clang/Basic/DiagnosticGroups.td#L576

`-Wcast-function-type` also includes `-Wcast-function-type-strict`; we don't 
want the strict warning in `-Wextra`, just the base warning. I'm looking to see 
if there's a reasonable way to accomplish this.

https://github.com/llvm/llvm-project/pull/77178
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-repl] Fix Value for platforms where unqualified char is unsigned (PR #86118)

2024-03-21 Thread Stefan Gränitz via cfe-commits

https://github.com/weliveindetail created 
https://github.com/llvm/llvm-project/pull/86118

Signedness of unqualified `char` is unspecified and varies between platforms. 
This patch adds `Char_U` in `REPL_BUILTIN_TYPES` to account for platforms that 
default to `unsigned char`.

From e0cdd176e35d0bd255d1394eff6bee314c0e3cd6 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Stefan=20Gr=C3=A4nitz?= 
Date: Thu, 21 Mar 2024 14:04:10 +0100
Subject: [PATCH 1/3] Add reproducer

---
 clang/unittests/Interpreter/InterpreterTest.cpp | 5 +
 1 file changed, 5 insertions(+)

diff --git a/clang/unittests/Interpreter/InterpreterTest.cpp 
b/clang/unittests/Interpreter/InterpreterTest.cpp
index e76c0677db5ead..25f6e4f900c882 100644
--- a/clang/unittests/Interpreter/InterpreterTest.cpp
+++ b/clang/unittests/Interpreter/InterpreterTest.cpp
@@ -340,6 +340,11 @@ TEST(InterpreterTest, Value) {
   EXPECT_EQ(V1.getKind(), Value::K_Int);
   EXPECT_FALSE(V1.isManuallyAlloc());
 
+  Value V1b;
+  llvm::cantFail(Interp->ParseAndExecute("char x = 42;"));
+  llvm::cantFail(Interp->ParseAndExecute("c", &V1b));
+  EXPECT_TRUE(V1b.getKind() == Value::K_Char_S);
+
   Value V2;
   llvm::cantFail(Interp->ParseAndExecute("double y = 3.14;"));
   llvm::cantFail(Interp->ParseAndExecute("y", &V2));

From fa3d6e1973c5d2fe13c85993cf851f18e41f0f32 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Stefan=20Gr=C3=A4nitz?= 
Date: Thu, 21 Mar 2024 14:05:05 +0100
Subject: [PATCH 2/3] Add missing REPL_BUILTIN_TYPE

---
 clang/include/clang/Interpreter/Value.h | 1 +
 1 file changed, 1 insertion(+)

diff --git a/clang/include/clang/Interpreter/Value.h 
b/clang/include/clang/Interpreter/Value.h
index c380cd91550def..d70e8f8719026b 100644
--- a/clang/include/clang/Interpreter/Value.h
+++ b/clang/include/clang/Interpreter/Value.h
@@ -76,6 +76,7 @@ class QualType;
   X(bool, Bool)
\
   X(char, Char_S)  
\
   X(signed char, SChar)
\
+  X(unsigned char, Char_U) 
\
   X(unsigned char, UChar)  
\
   X(short, Short)  
\
   X(unsigned short, UShort)
\

From 3ade711f907758814d13852edae71cec746fcb7b Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Stefan=20Gr=C3=A4nitz?= 
Date: Thu, 21 Mar 2024 14:33:50 +0100
Subject: [PATCH 3/3] Accept signed or unsigned for unqualified char in
 reproducer

---
 clang/unittests/Interpreter/InterpreterTest.cpp | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/clang/unittests/Interpreter/InterpreterTest.cpp 
b/clang/unittests/Interpreter/InterpreterTest.cpp
index 25f6e4f900c882..4b5d73769e5da7 100644
--- a/clang/unittests/Interpreter/InterpreterTest.cpp
+++ b/clang/unittests/Interpreter/InterpreterTest.cpp
@@ -343,7 +343,8 @@ TEST(InterpreterTest, Value) {
   Value V1b;
   llvm::cantFail(Interp->ParseAndExecute("char x = 42;"));
   llvm::cantFail(Interp->ParseAndExecute("c", &V1b));
-  EXPECT_TRUE(V1b.getKind() == Value::K_Char_S);
+  EXPECT_TRUE(V1b.getKind() == Value::K_Char_S ||
+  V1b.getKind() == Value::K_Char_U);
 
   Value V2;
   llvm::cantFail(Interp->ParseAndExecute("double y = 3.14;"));

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


[clang] [clang-repl] Fix Value for platforms where unqualified char is unsigned (PR #86118)

2024-03-21 Thread via cfe-commits
Stefan =?utf-8?q?Gränitz?= ,
Stefan =?utf-8?q?Gränitz?= 
Message-ID:
In-Reply-To: 


llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Stefan Gränitz (weliveindetail)


Changes

Signedness of unqualified `char` is unspecified and varies between platforms. 
This patch adds `Char_U` in `REPL_BUILTIN_TYPES` to account for platforms that 
default to `unsigned char`.

---
Full diff: https://github.com/llvm/llvm-project/pull/86118.diff


2 Files Affected:

- (modified) clang/include/clang/Interpreter/Value.h (+1) 
- (modified) clang/unittests/Interpreter/InterpreterTest.cpp (+6) 


``diff
diff --git a/clang/include/clang/Interpreter/Value.h 
b/clang/include/clang/Interpreter/Value.h
index c380cd91550def..d70e8f8719026b 100644
--- a/clang/include/clang/Interpreter/Value.h
+++ b/clang/include/clang/Interpreter/Value.h
@@ -76,6 +76,7 @@ class QualType;
   X(bool, Bool)
\
   X(char, Char_S)  
\
   X(signed char, SChar)
\
+  X(unsigned char, Char_U) 
\
   X(unsigned char, UChar)  
\
   X(short, Short)  
\
   X(unsigned short, UShort)
\
diff --git a/clang/unittests/Interpreter/InterpreterTest.cpp 
b/clang/unittests/Interpreter/InterpreterTest.cpp
index e76c0677db5ead..4b5d73769e5da7 100644
--- a/clang/unittests/Interpreter/InterpreterTest.cpp
+++ b/clang/unittests/Interpreter/InterpreterTest.cpp
@@ -340,6 +340,12 @@ TEST(InterpreterTest, Value) {
   EXPECT_EQ(V1.getKind(), Value::K_Int);
   EXPECT_FALSE(V1.isManuallyAlloc());
 
+  Value V1b;
+  llvm::cantFail(Interp->ParseAndExecute("char x = 42;"));
+  llvm::cantFail(Interp->ParseAndExecute("c", &V1b));
+  EXPECT_TRUE(V1b.getKind() == Value::K_Char_S ||
+  V1b.getKind() == Value::K_Char_U);
+
   Value V2;
   llvm::cantFail(Interp->ParseAndExecute("double y = 3.14;"));
   llvm::cantFail(Interp->ParseAndExecute("y", &V2));

``




https://github.com/llvm/llvm-project/pull/86118
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] move -Wcast-function-type under -Wextra (PR #77178)

2024-03-21 Thread Abhin P Jose via cfe-commits

Abhinkop wrote:

> > > I'm confused as to how this code ever compiled in the first place... In 
> > > each case, this is C++ code that's failing:
> > > ```
> > > /home/buildbots/llvm-external-buildbots/workers/ppc64le-clang-rhel-test/clang-ppc64le-rhel/llvm-project/compiler-rt/lib/sanitizer_common/sanitizer_posix_libcdep.cpp:219:25:
> > >  error: cast from 'SignalHandlerType' (aka 'void (*)(int, void *, void 
> > > *)') to 'sa_sigaction_t' (aka 'void (*)(int, siginfo_t *, void *)') 
> > > converts to incompatible function type 
> > > [-Werror,-Wcast-function-type-strict]
> > > 
> > > /home/buildbots/llvm-external-buildbots/workers/ppc64le-clang-rhel-test/clang-ppc64le-rhel/llvm-project/compiler-rt/lib/tsan/rtl/tsan_interceptors_posix.cpp:437:4:
> > >  error: cast from 'void (*)()' to 'void (*)(void *)' converts to 
> > > incompatible function type [-Werror,-Wcast-function-type-strict]
> > > 
> > > /home/buildbots/llvm-external-buildbots/workers/ppc64le-clang-rhel-test/clang-ppc64le-rhel/llvm-project/compiler-rt/lib/tsan/rtl/tsan_interceptors_posix.cpp:460:54:
> > >  error: cast from 'void (*)(void *)' to 'void (*)()' converts to 
> > > incompatible function type [-Werror,-Wcast-function-type-strict]
> > > ```
> > > 
> > > 
> > > 
> > >   
> > > 
> > > 
> > >   
> > > 
> > > 
> > > 
> > >   
> > > All of which is being compiled in `-std=c++17` and none of which are 
> > > valid in C++ and the behavior is the same between Clang 18, trunk, and 
> > > GCC: https://godbolt.org/z/WY9zvsa8z
> > > @amy-kwan we may need some help from you with investigating this; but in 
> > > the meantime, this commit can be reverted to get the bots back to green 
> > > if that's blocking you.
> > 
> > 
> > @AaronBallman There was a forced/explicit typecasting done, and hence the 
> > compiler didn't complain. for example, https://godbolt.org/z/G94r7qvxh . 
> > When the -Werror flag coupled with -Wextra flag caught this conversion, for 
> > example, https://godbolt.org/z/6bMrdfe4n. I hope this might help to provide 
> > some context.
> 
> Ah! That does provide the context I needed, thank you! And I think I see the 
> issue:
> 
> https://github.com/llvm/llvm-project/blob/734026347cca85cf0e242ef5f04896f55e0ac113/clang/include/clang/Basic/DiagnosticGroups.td#L576
> 
> `-Wcast-function-type` also includes `-Wcast-function-type-strict`; we don't 
> want the strict warning in `-Wextra`, just the base warning. I'm looking to 
> see if there's a reasonable way to accomplish this.

Change def CastFunctionType : DiagGroup<"cast-function-type", 
[CastFunctionTypeStrict]>; to def  CastFunctionType : 
DiagGroup<"cast-function-type">; and introduce a new one def 
CastFunctionTypeDefault : DiagGroup<[CastFunctionType], 
[CastFunctionTypeStrict]>; and some how pass this on where CastFunctionType was 
used earlier?

https://github.com/llvm/llvm-project/pull/77178
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-repl] Fix Value for platforms where unqualified char is unsigned (PR #86118)

2024-03-21 Thread Vassil Vassilev via cfe-commits
Stefan =?utf-8?q?Gr=C3=A4nitz?= ,
Stefan =?utf-8?q?Gr=C3=A4nitz?= 
Message-ID:
In-Reply-To: 


https://github.com/vgvassilev approved this pull request.

Good catch! Thank you, @weliveindetail!

https://github.com/llvm/llvm-project/pull/86118
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-repl] Factor out CreateJITBuilder() and allow specialization in derived classes (PR #84461)

2024-03-21 Thread Vassil Vassilev via cfe-commits

https://github.com/vgvassilev approved this pull request.

LGTM!

https://github.com/llvm/llvm-project/pull/84461
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] move -Wcast-function-type under -Wextra (PR #77178)

2024-03-21 Thread Aaron Ballman via cfe-commits

AaronBallman wrote:

Yeah, I was hoping to avoid having to introduce another diagnostic group, but I 
think that's going to be the best way forward. I've got a patch in progress to 
add `-Wcast-function-type-mismatch` so we end up with:
```
-Wcast-function-type
|- -Wcast-function-type-mismatch
|- -Wcast-function-type-strict
```
and then add `-Wcast-function-type-mismatch` to `-Wextra`, but still thinking 
through the changes and whether there's a different approach.

https://github.com/llvm/llvm-project/pull/77178
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [libcxx] [libc++] Implement LWG3528 (`make_from_tuple` can perform (the equivalent of) a C-style cast) (PR #85263)

2024-03-21 Thread Mark de Wever via cfe-commits


@@ -1386,9 +1386,19 @@ inline _LIBCPP_HIDE_FROM_ABI constexpr decltype(auto) 
apply(_Fn&& __f, _Tuple&&
 std::forward<_Tuple>(__t),
 typename 
__make_tuple_indices>>::type{}))
 
+#if _LIBCPP_STD_VER >= 20
 template 
 inline _LIBCPP_HIDE_FROM_ABI constexpr _Tp __make_from_tuple_impl(_Tuple&& 
__t, __tuple_indices<_Idx...>)
+  noexcept(noexcept(_Tp(std::get<_Idx>(std::forward<_Tuple>(__t))...)))
+  requires is_constructible_v<_Tp, 
decltype(std::get<_Idx>(std::forward<_Tuple>(__t)))...> {
+  return _Tp(std::get<_Idx>(std::forward<_Tuple>(__t))...);
+}
+#else
+template 
+inline _LIBCPP_HIDE_FROM_ABI constexpr _Tp __make_from_tuple_impl(_Tuple&& 
__t, __tuple_indices<_Idx...>, 
+enable_if_t(std::forward<_Tuple>(__t)))...>> * = nullptr)
 _LIBCPP_NOEXCEPT_RETURN(_Tp(std::get<_Idx>(std::forward<_Tuple>(__t))...))
+#endif // _LIBCPP_STD_VER >= 20
 
 template 

mordante wrote:

Based on http://eel.is/c++draft/description#structure.requirements-9 this seems 
to be allowed. Then we can write "proper" SFINAE tests. I agree with 
@frederick-vs-ja the current way gives horrible diagnostics based on 
`noexcept`. 

https://github.com/llvm/llvm-project/pull/85263
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] a11d9b4 - Disable driver tests on macosx that are currently disabled on darwin (#85990)

2024-03-21 Thread via cfe-commits

Author: Akira Hatanaka
Date: 2024-03-21T07:10:42-07:00
New Revision: a11d9b463966d31ecedb373115abdcca54f704c3

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

LOG: Disable driver tests on macosx that are currently disabled on darwin 
(#85990)

macosx and darwin in triples are equivalent.

rdar://124246653

Added: 


Modified: 
clang/test/Driver/clang-offload-bundler-asserts-on.c
clang/test/Driver/clang-offload-bundler-standardize.c
clang/test/Driver/clang-offload-bundler.c
clang/test/Driver/fat-archive-unbundle-ext.c

Removed: 




diff  --git a/clang/test/Driver/clang-offload-bundler-asserts-on.c 
b/clang/test/Driver/clang-offload-bundler-asserts-on.c
index 521c8641ff5468..eb11d5fbbee4a7 100644
--- a/clang/test/Driver/clang-offload-bundler-asserts-on.c
+++ b/clang/test/Driver/clang-offload-bundler-asserts-on.c
@@ -1,6 +1,6 @@
 // REQUIRES: x86-registered-target
 // REQUIRES: asserts
-// UNSUPPORTED: target={{.*}}-darwin{{.*}}, target={{.*}}-aix{{.*}}
+// UNSUPPORTED: target={{.*}}-macosx{{.*}}, target={{.*}}-darwin{{.*}}, 
target={{.*}}-aix{{.*}}
 
 // Generate the file we can bundle.
 // RUN: %clang -O0 -target %itanium_abi_triple %s -c -o %t.o

diff  --git a/clang/test/Driver/clang-offload-bundler-standardize.c 
b/clang/test/Driver/clang-offload-bundler-standardize.c
index 6a24968c30efd6..91dc8947aabb9a 100644
--- a/clang/test/Driver/clang-offload-bundler-standardize.c
+++ b/clang/test/Driver/clang-offload-bundler-standardize.c
@@ -1,6 +1,6 @@
 // REQUIRES: x86-registered-target
 // REQUIRES: asserts
-// UNSUPPORTED: target={{.*}}-darwin{{.*}}, target={{.*}}-aix{{.*}}
+// UNSUPPORTED: target={{.*}}-macosx{{.*}}, target={{.*}}-darwin{{.*}}, 
target={{.*}}-aix{{.*}}
 // REQUIRES: asserts
 
 // Generate the file we can bundle.

diff  --git a/clang/test/Driver/clang-offload-bundler.c 
b/clang/test/Driver/clang-offload-bundler.c
index f3cd2493e05277..a56a5424abf88d 100644
--- a/clang/test/Driver/clang-offload-bundler.c
+++ b/clang/test/Driver/clang-offload-bundler.c
@@ -1,5 +1,5 @@
 // REQUIRES: x86-registered-target
-// UNSUPPORTED: target={{.*}}-darwin{{.*}}, target={{.*}}-aix{{.*}}
+// UNSUPPORTED: target={{.*}}-macosx{{.*}}, target={{.*}}-darwin{{.*}}, 
target={{.*}}-aix{{.*}}
 
 //
 // Generate all the types of files we can bundle.

diff  --git a/clang/test/Driver/fat-archive-unbundle-ext.c 
b/clang/test/Driver/fat-archive-unbundle-ext.c
index b409aa6313b1ea..e98b872f0c0c31 100644
--- a/clang/test/Driver/fat-archive-unbundle-ext.c
+++ b/clang/test/Driver/fat-archive-unbundle-ext.c
@@ -1,5 +1,5 @@
 // REQUIRES: x86-registered-target
-// UNSUPPORTED: target={{.*-windows.*}}, target={{.*-darwin.*}}, 
target={{.*}}-aix{{.*}}
+// UNSUPPORTED: target={{.*-windows.*}}, target={{.*}}-macosx{{.*}}, 
target={{.*-darwin.*}}, target={{.*}}-aix{{.*}}
 
 // Generate dummy fat object
 // RUN: %clang -O0 -target %itanium_abi_triple %s -c -o %t.host.o



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


[clang] Disable driver tests on macosx that are currently disabled on darwin (PR #85990)

2024-03-21 Thread Akira Hatanaka via cfe-commits

https://github.com/ahatanak closed 
https://github.com/llvm/llvm-project/pull/85990
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-repl] Factor out CreateJITBuilder() and allow specialization in derived classes (PR #84461)

2024-03-21 Thread Stefan Gränitz via cfe-commits

https://github.com/weliveindetail updated 
https://github.com/llvm/llvm-project/pull/84461

From fae2f46d25650b8480f9d3135f33a0d6532f43ca Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Stefan=20Gr=C3=A4nitz?= 
Date: Thu, 7 Mar 2024 23:04:22 +0100
Subject: [PATCH] [clang-repl] Add CreateJITBuilder() for specialization in
 derived classes

The LLJITBuilder interface provides a very convenient way to configure the JIT.
---
 clang/include/clang/Interpreter/Interpreter.h |   9 ++
 clang/lib/Interpreter/IncrementalExecutor.cpp |  33 ++---
 clang/lib/Interpreter/IncrementalExecutor.h   |   9 +-
 clang/lib/Interpreter/Interpreter.cpp |  26 +++-
 .../Interpreter/InterpreterExtensionsTest.cpp | 117 +-
 5 files changed, 173 insertions(+), 21 deletions(-)

diff --git a/clang/include/clang/Interpreter/Interpreter.h 
b/clang/include/clang/Interpreter/Interpreter.h
index 1dcba1ef967980..33ce4bbf5bea10 100644
--- a/clang/include/clang/Interpreter/Interpreter.h
+++ b/clang/include/clang/Interpreter/Interpreter.h
@@ -29,7 +29,9 @@
 
 namespace llvm {
 namespace orc {
+class JITTargetMachineBuilder;
 class LLJIT;
+class LLJITBuilder;
 class ThreadSafeContext;
 } // namespace orc
 } // namespace llvm
@@ -127,6 +129,13 @@ class Interpreter {
   // custom runtime.
   virtual std::unique_ptr FindRuntimeInterface();
 
+  // Lazily construct thev ORCv2 JITBuilder. This called when the internal
+  // IncrementalExecutor is created. The default implementation populates an
+  // in-process JIT with debugging support. Override this to configure the JIT
+  // engine used for execution.
+  virtual llvm::Expected>
+  CreateJITBuilder(CompilerInstance &CI);
+
 public:
   virtual ~Interpreter();
 
diff --git a/clang/lib/Interpreter/IncrementalExecutor.cpp 
b/clang/lib/Interpreter/IncrementalExecutor.cpp
index 40bcef94797d43..6f036107c14a9c 100644
--- a/clang/lib/Interpreter/IncrementalExecutor.cpp
+++ b/clang/lib/Interpreter/IncrementalExecutor.cpp
@@ -20,6 +20,7 @@
 #include "llvm/ExecutionEngine/Orc/Debugging/DebuggerSupport.h"
 #include "llvm/ExecutionEngine/Orc/ExecutionUtils.h"
 #include "llvm/ExecutionEngine/Orc/IRCompileLayer.h"
+#include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h"
 #include "llvm/ExecutionEngine/Orc/LLJIT.h"
 #include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h"
 #include "llvm/ExecutionEngine/Orc/TargetProcess/JITLoaderGDB.h"
@@ -36,26 +37,28 @@ LLVM_ATTRIBUTE_USED void linkComponents() {
 
 namespace clang {
 
+llvm::Expected>
+IncrementalExecutor::createDefaultJITBuilder(
+llvm::orc::JITTargetMachineBuilder JTMB) {
+  auto JITBuilder = std::make_unique();
+  JITBuilder->setJITTargetMachineBuilder(std::move(JTMB));
+  JITBuilder->setPrePlatformSetup([](llvm::orc::LLJIT &J) {
+// Try to enable debugging of JIT'd code (only works with JITLink for
+// ELF and MachO).
+consumeError(llvm::orc::enableDebuggerSupport(J));
+return llvm::Error::success();
+  });
+  return std::move(JITBuilder);
+}
+
 IncrementalExecutor::IncrementalExecutor(llvm::orc::ThreadSafeContext &TSC,
- llvm::Error &Err,
- const clang::TargetInfo &TI)
+ llvm::orc::LLJITBuilder &JITBuilder,
+ llvm::Error &Err)
 : TSCtx(TSC) {
   using namespace llvm::orc;
   llvm::ErrorAsOutParameter EAO(&Err);
 
-  auto JTMB = JITTargetMachineBuilder(TI.getTriple());
-  JTMB.addFeatures(TI.getTargetOpts().Features);
-  LLJITBuilder Builder;
-  Builder.setJITTargetMachineBuilder(JTMB);
-  Builder.setPrePlatformSetup(
-  [](LLJIT &J) {
-// Try to enable debugging of JIT'd code (only works with JITLink for
-// ELF and MachO).
-consumeError(enableDebuggerSupport(J));
-return llvm::Error::success();
-  });
-
-  if (auto JitOrErr = Builder.create())
+  if (auto JitOrErr = JITBuilder.create())
 Jit = std::move(*JitOrErr);
   else {
 Err = JitOrErr.takeError();
diff --git a/clang/lib/Interpreter/IncrementalExecutor.h 
b/clang/lib/Interpreter/IncrementalExecutor.h
index dd0a210a061415..b4347209e14fe3 100644
--- a/clang/lib/Interpreter/IncrementalExecutor.h
+++ b/clang/lib/Interpreter/IncrementalExecutor.h
@@ -23,7 +23,9 @@
 namespace llvm {
 class Error;
 namespace orc {
+class JITTargetMachineBuilder;
 class LLJIT;
+class LLJITBuilder;
 class ThreadSafeContext;
 } // namespace orc
 } // namespace llvm
@@ -44,8 +46,8 @@ class IncrementalExecutor {
 public:
   enum SymbolNameKind { IRName, LinkerName };
 
-  IncrementalExecutor(llvm::orc::ThreadSafeContext &TSC, llvm::Error &Err,
-  const clang::TargetInfo &TI);
+  IncrementalExecutor(llvm::orc::ThreadSafeContext &TSC,
+  llvm::orc::LLJITBuilder &JITBuilder, llvm::Error &Err);
   ~IncrementalExecutor();
 
   llvm::Error addModule(PartialTranslationUnit &PTU);
@@ -56,6 +58,9 @@ class IncrementalExecutor {
   getSymbolAddre

[clang] Raise an error on namespace aliases with qualified names. (PR #86122)

2024-03-21 Thread via cfe-commits

github-actions[bot] wrote:



Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be
notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this 
page.

If this is not working for you, it is probably because you do not have write
permissions for the repository. In which case you can instead tag reviewers by
name in a comment by using `@` followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review
by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate
is once a week. Please remember that you are asking for valuable time from 
other developers.

If you have further questions, they may be answered by the [LLVM GitHub User 
Guide](https://llvm.org/docs/GitHub.html).

You can also ask questions in a comment on this PR, on the [LLVM 
Discord](https://discord.com/invite/xS7Z362) or on the 
[forums](https://discourse.llvm.org/).

https://github.com/llvm/llvm-project/pull/86122
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 2152094 - [clang] Improves -print-library-module-manifest-path. (#85943)

2024-03-21 Thread via cfe-commits

Author: Mark de Wever
Date: 2024-03-21T15:11:45+01:00
New Revision: 2152094a45af98c9ccfef6d5913f38c66ab8b165

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

LOG: [clang] Improves -print-library-module-manifest-path. (#85943)

This adds a libc++ to modules.json as is currently used by libc++. When
libc++.so is not found the function will search for libc++.a as
fallback.

Added: 


Modified: 
clang/lib/Driver/Driver.cpp
clang/test/Driver/modules-print-library-module-manifest-path.cpp

Removed: 




diff  --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 767c1cd47e8cd9..7a53764364ce4d 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -6203,28 +6203,35 @@ std::string Driver::GetStdModuleManifestPath(const 
Compilation &C,
 
   switch (TC.GetCXXStdlibType(C.getArgs())) {
   case ToolChain::CST_Libcxx: {
-std::string lib = GetFilePath("libc++.so", TC);
-
-// Note when there are multiple flavours of libc++ the module json needs to
-// look at the command-line arguments for the proper json.
-// These flavours do not exist at the moment, but there are plans to
-// provide a variant that is built with sanitizer instrumentation enabled.
-
-// For example
-//  StringRef modules = [&] {
-//const SanitizerArgs &Sanitize = TC.getSanitizerArgs(C.getArgs());
-//if (Sanitize.needsAsanRt())
-//  return "modules-asan.json";
-//return "modules.json";
-//  }();
-
-SmallString<128> path(lib.begin(), lib.end());
-llvm::sys::path::remove_filename(path);
-llvm::sys::path::append(path, "modules.json");
-if (TC.getVFS().exists(path))
-  return static_cast(path);
+auto evaluate = [&](const char *library) -> std::optional {
+  std::string lib = GetFilePath(library, TC);
+
+  // Note when there are multiple flavours of libc++ the module json needs
+  // to look at the command-line arguments for the proper json. These
+  // flavours do not exist at the moment, but there are plans to provide a
+  // variant that is built with sanitizer instrumentation enabled.
+
+  // For example
+  //  StringRef modules = [&] {
+  //const SanitizerArgs &Sanitize = TC.getSanitizerArgs(C.getArgs());
+  //if (Sanitize.needsAsanRt())
+  //  return "libc++.modules-asan.json";
+  //return "libc++.modules.json";
+  //  }();
+
+  SmallString<128> path(lib.begin(), lib.end());
+  llvm::sys::path::remove_filename(path);
+  llvm::sys::path::append(path, "libc++.modules.json");
+  if (TC.getVFS().exists(path))
+return static_cast(path);
+
+  return {};
+};
 
-return error;
+if (std::optional result = evaluate("libc++.so"); result)
+  return *result;
+
+return evaluate("libc++.a").value_or(error);
   }
 
   case ToolChain::CST_Libstdcxx:

diff  --git a/clang/test/Driver/modules-print-library-module-manifest-path.cpp 
b/clang/test/Driver/modules-print-library-module-manifest-path.cpp
index 24797002b80f53..3ba2709ad95cc8 100644
--- a/clang/test/Driver/modules-print-library-module-manifest-path.cpp
+++ b/clang/test/Driver/modules-print-library-module-manifest-path.cpp
@@ -3,6 +3,7 @@
 // RUN: rm -rf %t && split-file %s %t && cd %t
 // RUN: mkdir -p %t/Inputs/usr/lib/x86_64-linux-gnu
 // RUN: touch %t/Inputs/usr/lib/x86_64-linux-gnu/libc++.so
+// RUN: touch %t/Inputs/usr/lib/x86_64-linux-gnu/libc++.a
 
 // RUN: %clang -print-library-module-manifest-path \
 // RUN: -stdlib=libc++ \
@@ -10,13 +11,21 @@
 // RUN: --target=x86_64-linux-gnu 2>&1 \
 // RUN:   | FileCheck libcxx-no-module-json.cpp
 
-// RUN: touch %t/Inputs/usr/lib/x86_64-linux-gnu/modules.json
+// RUN: touch %t/Inputs/usr/lib/x86_64-linux-gnu/libc++.modules.json
 // RUN: %clang -print-library-module-manifest-path \
 // RUN: -stdlib=libc++ \
 // RUN: -resource-dir=%t/Inputs/usr/lib/x86_64-linux-gnu \
 // RUN: --target=x86_64-linux-gnu 2>&1 \
 // RUN:   | FileCheck libcxx.cpp
 
+// RUN: rm %t/Inputs/usr/lib/x86_64-linux-gnu/libc++.so
+// RUN: touch %t/Inputs/usr/lib/x86_64-linux-gnu/libc++.a
+// RUN: %clang -print-library-module-manifest-path \
+// RUN: -stdlib=libc++ \
+// RUN: -resource-dir=%t/Inputs/usr/lib/x86_64-linux-gnu \
+// RUN: --target=x86_64-linux-gnu 2>&1 \
+// RUN:   | FileCheck libcxx-no-shared-lib.cpp
+
 // RUN: %clang -print-library-module-manifest-path \
 // RUN: -stdlib=libstdc++ \
 // RUN: -resource-dir=%t/Inputs/usr/lib/x86_64-linux-gnu \
@@ -29,7 +38,13 @@
 
 //--- libcxx.cpp
 
-// CHECK: {{.*}}/Inputs/usr/lib/x86_64-linux-gnu{{/|\\}}modules.json
+// CHECK: {{.*}}/Inputs/usr/lib/x86_64-linux-gnu{{/|\\}}libc++.modules.json
+
+//--- libcxx-no-shared-lib.cpp
+
+// Note this m

[clang] [Doc][HLSL] Add documentation for root signature. (PR #83933)

2024-03-21 Thread Xiang Li via cfe-commits


@@ -0,0 +1,258 @@
+
+HLSL Root Signatures
+
+
+.. contents::
+   :local:
+
+Usage
+=
+
+In HLSL, the `root signature
+`_ 
+defines what types of resources are bound to the graphics pipeline. 
+
+A root signature can be specified in HLSL as a `string
+`_.
 
+The string contains a collection of comma-separated clauses that describe root 
+signature constituent components. 
+
+There are two mechanisms to compile an HLSL root signature. First, it is 
+possible to attach a root signature string to a particular shader via the 
+RootSignature attribute (in the following example, using the MyRS1 entry 
+point):
+
+.. code-block:: c++
+
+#define RS "RootFlags( ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT | " \ 
+  "DENY_VERTEX_SHADER_ROOT_ACCESS), " \ 
+  "CBV(b0, space = 1, flags = DATA_STATIC), " \ 
+  "SRV(t0), " \ 
+  "UAV(u0), " \ 
+  "DescriptorTable( CBV(b1), " \ 
+  " SRV(t1, numDescriptors = 8, " \ 
+  " flags = DESCRIPTORS_VOLATILE), " \ 
+  " UAV(u1, numDescriptors = unbounded, " \ 
+  " flags = DESCRIPTORS_VOLATILE)), " \ 
+  "DescriptorTable(Sampler(s0, space=1, numDescriptors = 4)), " \ 
+  "RootConstants(num32BitConstants=3, b10), " \ 
+  "StaticSampler(s1)," \ 
+  "StaticSampler(s2, " \ 
+  "  addressU = TEXTURE_ADDRESS_CLAMP, " \ 
+  "  filter = FILTER_MIN_MAG_MIP_LINEAR )"
+
+[RootSignature(RS)]
+float4 main(float4 coord : COORD) : SV_Target
+{
+…
+}
+
+The compiler will create and verify the root signature blob for the shader and 
+embed it alongside the shader byte code into the shader blob. 
+
+The other mechanism is to create a standalone root signature blob, perhaps to 
+reuse it with a large set of shaders, saving space. The name of the define 
+string is specified via the usual -E argument. For example:
+
+.. code-block:: c++
+
+  dxc.exe -T rootsig_1_1 MyRS1.hlsl -E MyRS1 -Fo MyRS1.fxo
+
+Note that the root signature string define can also be passed on the command 
+line, e.g, -D MyRS1=”…”.
+
+Root Signature Grammar
+==
+
+.. code-block:: c++
+
+RootSignature : (RootElement(,RootElement)?)?
+
+RootElement : RootFlags | RootConstants | RootCBV | RootSRV | RootUAV |
+  DescriptorTable | StaticSampler
+
+RootFlags : 'RootFlags' '(' (RootFlag(|RootFlag)?)? ')'
+
+RootFlag : 'ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT' | 
+   'DENY_VERTEX_SHADER_ROOT_ACCESS'
+
+RootConstants : 'RootConstants' '(' 'num32BitConstants' '=' NUMBER ',' 
+   bReg (',' 'space' '=' NUMBER)? 
+   (',' 'visibility' '=' SHADER_VISIBILITY)? ')'
+
+RootCBV : 'CBV' '(' bReg (',' 'space' '=' NUMBER)? 
+  (',' 'visibility' '=' SHADER_VISIBILITY)? 
+  (',' 'flags' '=' DATA_FLAGS)? ')'
+
+RootSRV : 'SRV' '(' tReg (',' 'space' '=' NUMBER)? 
+  (',' 'visibility' '=' SHADER_VISIBILITY)? 
+  (',' 'flags' '=' DATA_FLAGS)? ')'
+
+RootUAV : 'UAV' '(' uReg (',' 'space' '=' NUMBER)? 
+  (',' 'visibility' '=' SHADER_VISIBILITY)? 
+  (',' 'flags' '=' DATA_FLAGS)? ')'
+
+DescriptorTable : 'DescriptorTable' '(' (DTClause(|DTClause)?)? 
+  (',' 'visibility' '=' SHADER_VISIBILITY)? ')'
+
+DTClause : CBV | SRV | UAV | Sampler
+
+CBV : 'CBV' '(' bReg (',' 'numDescriptors' '=' NUMBER)? 
+  (',' 'space' '=' NUMBER)? 
+  (',' 'offset' '=' DESCRIPTOR_RANGE_OFFSET)? 
+  (',' 'flags' '=' DATA_FLAGS)? ')'
+
+SRV : 'SRV' '(' tReg (',' 'numDescriptors' '=' NUMBER)? 
+(',' 'space' '=' NUMBER)? 
+  (',' 'offset' '=' DESCRIPTOR_RANGE_OFFSET)? 
+  (',' 'flags' '=' DATA_FLAGS)? ')'
+
+UAV : 'UAV' '(' uReg (',' 'numDescriptors' '=' NUMBER)? 
+  (',' 'space' '=' NUMBER)? 
+  (',' 'offset' '=' DESCRIPTOR_RANGE_OFFSET)? 
+  (',' 'flags' '=' DATA_FLAGS)? ')'
+
+Sampler : 'Sampler' '(' sReg (',' 'numDescriptors' '=' NUMBER)? 
+  (',' 'space' '=' NUMBER)? 
+  (',' 'offset' '=' DESCRIPTOR_RANGE_OFFSET)? (',' 'flags' '=' 
NUMBER)? ')'
+
+
+SHADER_VISIBILITY : 'SHADER_VISIBILITY_ALL' | 'SHADER_VISIBILITY_VERTEX' | 
+'SHADER_VISIBILITY_HULL' | 
+'SHADER_VISIBILITY_DOMAIN' | 
+'SHADER_VISIBILITY_GEOMETRY' | 
+'SHADER_VISIBILITY_PIXEL' | 
+'SHADER_VISIBILITY_AMPLIFICATION' | 
+'SHADER_VISIBILITY_MESH'
+
+DATA_FLAGS : 'DATA_STATIC_WH

[clang] [Doc][HLSL] Add documentation for root signature. (PR #83933)

2024-03-21 Thread Xiang Li via cfe-commits


@@ -0,0 +1,258 @@
+
+HLSL Root Signatures
+
+
+.. contents::
+   :local:
+
+Usage
+=
+
+In HLSL, the `root signature
+`_ 
+defines what types of resources are bound to the graphics pipeline. 
+
+A root signature can be specified in HLSL as a `string
+`_.
 
+The string contains a collection of comma-separated clauses that describe root 
+signature constituent components. 
+
+There are two mechanisms to compile an HLSL root signature. First, it is 
+possible to attach a root signature string to a particular shader via the 
+RootSignature attribute (in the following example, using the MyRS1 entry 
+point):
+
+.. code-block:: c++
+
+#define RS "RootFlags( ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT | " \ 
+  "DENY_VERTEX_SHADER_ROOT_ACCESS), " \ 
+  "CBV(b0, space = 1, flags = DATA_STATIC), " \ 
+  "SRV(t0), " \ 
+  "UAV(u0), " \ 
+  "DescriptorTable( CBV(b1), " \ 
+  " SRV(t1, numDescriptors = 8, " \ 
+  " flags = DESCRIPTORS_VOLATILE), " \ 
+  " UAV(u1, numDescriptors = unbounded, " \ 
+  " flags = DESCRIPTORS_VOLATILE)), " \ 
+  "DescriptorTable(Sampler(s0, space=1, numDescriptors = 4)), " \ 
+  "RootConstants(num32BitConstants=3, b10), " \ 
+  "StaticSampler(s1)," \ 
+  "StaticSampler(s2, " \ 
+  "  addressU = TEXTURE_ADDRESS_CLAMP, " \ 
+  "  filter = FILTER_MIN_MAG_MIP_LINEAR )"
+
+[RootSignature(RS)]
+float4 main(float4 coord : COORD) : SV_Target
+{
+…
+}
+
+The compiler will create and verify the root signature blob for the shader and 
+embed it alongside the shader byte code into the shader blob. 
+
+The other mechanism is to create a standalone root signature blob, perhaps to 
+reuse it with a large set of shaders, saving space. The name of the define 
+string is specified via the usual -E argument. For example:
+
+.. code-block:: c++
+
+  dxc.exe -T rootsig_1_1 MyRS1.hlsl -E MyRS1 -Fo MyRS1.fxo
+
+Note that the root signature string define can also be passed on the command 
+line, e.g, -D MyRS1=”…”.
+
+Root Signature Grammar
+==
+
+.. code-block:: c++
+
+RootSignature : (RootElement(,RootElement)?)?
+
+RootElement : RootFlags | RootConstants | RootCBV | RootSRV | RootUAV |
+  DescriptorTable | StaticSampler
+
+RootFlags : 'RootFlags' '(' (RootFlag(|RootFlag)?)? ')'
+
+RootFlag : 'ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT' | 
+   'DENY_VERTEX_SHADER_ROOT_ACCESS'
+
+RootConstants : 'RootConstants' '(' 'num32BitConstants' '=' NUMBER ',' 
+   bReg (',' 'space' '=' NUMBER)? 
+   (',' 'visibility' '=' SHADER_VISIBILITY)? ')'
+
+RootCBV : 'CBV' '(' bReg (',' 'space' '=' NUMBER)? 
+  (',' 'visibility' '=' SHADER_VISIBILITY)? 
+  (',' 'flags' '=' DATA_FLAGS)? ')'
+
+RootSRV : 'SRV' '(' tReg (',' 'space' '=' NUMBER)? 
+  (',' 'visibility' '=' SHADER_VISIBILITY)? 
+  (',' 'flags' '=' DATA_FLAGS)? ')'
+
+RootUAV : 'UAV' '(' uReg (',' 'space' '=' NUMBER)? 
+  (',' 'visibility' '=' SHADER_VISIBILITY)? 
+  (',' 'flags' '=' DATA_FLAGS)? ')'
+
+DescriptorTable : 'DescriptorTable' '(' (DTClause(|DTClause)?)? 
+  (',' 'visibility' '=' SHADER_VISIBILITY)? ')'
+
+DTClause : CBV | SRV | UAV | Sampler
+
+CBV : 'CBV' '(' bReg (',' 'numDescriptors' '=' NUMBER)? 
+  (',' 'space' '=' NUMBER)? 
+  (',' 'offset' '=' DESCRIPTOR_RANGE_OFFSET)? 
+  (',' 'flags' '=' DATA_FLAGS)? ')'
+
+SRV : 'SRV' '(' tReg (',' 'numDescriptors' '=' NUMBER)? 
+(',' 'space' '=' NUMBER)? 
+  (',' 'offset' '=' DESCRIPTOR_RANGE_OFFSET)? 
+  (',' 'flags' '=' DATA_FLAGS)? ')'
+
+UAV : 'UAV' '(' uReg (',' 'numDescriptors' '=' NUMBER)? 
+  (',' 'space' '=' NUMBER)? 
+  (',' 'offset' '=' DESCRIPTOR_RANGE_OFFSET)? 
+  (',' 'flags' '=' DATA_FLAGS)? ')'
+
+Sampler : 'Sampler' '(' sReg (',' 'numDescriptors' '=' NUMBER)? 
+  (',' 'space' '=' NUMBER)? 
+  (',' 'offset' '=' DESCRIPTOR_RANGE_OFFSET)? (',' 'flags' '=' 
NUMBER)? ')'
+
+
+SHADER_VISIBILITY : 'SHADER_VISIBILITY_ALL' | 'SHADER_VISIBILITY_VERTEX' | 
+'SHADER_VISIBILITY_HULL' | 
+'SHADER_VISIBILITY_DOMAIN' | 
+'SHADER_VISIBILITY_GEOMETRY' | 
+'SHADER_VISIBILITY_PIXEL' | 
+'SHADER_VISIBILITY_AMPLIFICATION' | 
+'SHADER_VISIBILITY_MESH'
+
+DATA_FLAGS : 'DATA_STATIC_WH

[clang] [Doc][HLSL] Add documentation for root signature. (PR #83933)

2024-03-21 Thread Xiang Li via cfe-commits


@@ -0,0 +1,258 @@
+
+HLSL Root Signatures
+
+
+.. contents::
+   :local:
+
+Usage
+=
+
+In HLSL, the `root signature
+`_ 
+defines what types of resources are bound to the graphics pipeline. 
+
+A root signature can be specified in HLSL as a `string
+`_.
 
+The string contains a collection of comma-separated clauses that describe root 
+signature constituent components. 
+
+There are two mechanisms to compile an HLSL root signature. First, it is 
+possible to attach a root signature string to a particular shader via the 
+RootSignature attribute (in the following example, using the MyRS1 entry 
+point):
+
+.. code-block:: c++
+
+#define RS "RootFlags( ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT | " \ 
+  "DENY_VERTEX_SHADER_ROOT_ACCESS), " \ 
+  "CBV(b0, space = 1, flags = DATA_STATIC), " \ 
+  "SRV(t0), " \ 
+  "UAV(u0), " \ 
+  "DescriptorTable( CBV(b1), " \ 
+  " SRV(t1, numDescriptors = 8, " \ 
+  " flags = DESCRIPTORS_VOLATILE), " \ 
+  " UAV(u1, numDescriptors = unbounded, " \ 
+  " flags = DESCRIPTORS_VOLATILE)), " \ 
+  "DescriptorTable(Sampler(s0, space=1, numDescriptors = 4)), " \ 
+  "RootConstants(num32BitConstants=3, b10), " \ 
+  "StaticSampler(s1)," \ 
+  "StaticSampler(s2, " \ 
+  "  addressU = TEXTURE_ADDRESS_CLAMP, " \ 
+  "  filter = FILTER_MIN_MAG_MIP_LINEAR )"
+
+[RootSignature(RS)]
+float4 main(float4 coord : COORD) : SV_Target
+{
+…
+}
+
+The compiler will create and verify the root signature blob for the shader and 
+embed it alongside the shader byte code into the shader blob. 
+
+The other mechanism is to create a standalone root signature blob, perhaps to 
+reuse it with a large set of shaders, saving space. The name of the define 
+string is specified via the usual -E argument. For example:
+
+.. code-block:: c++
+
+  dxc.exe -T rootsig_1_1 MyRS1.hlsl -E MyRS1 -Fo MyRS1.fxo
+
+Note that the root signature string define can also be passed on the command 
+line, e.g, -D MyRS1=”…”.
+
+Root Signature Grammar
+==
+
+.. code-block:: c++
+
+RootSignature : (RootElement(,RootElement)?)?
+
+RootElement : RootFlags | RootConstants | RootCBV | RootSRV | RootUAV |
+  DescriptorTable | StaticSampler
+
+RootFlags : 'RootFlags' '(' (RootFlag(|RootFlag)?)? ')'
+
+RootFlag : 'ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT' | 
+   'DENY_VERTEX_SHADER_ROOT_ACCESS'
+
+RootConstants : 'RootConstants' '(' 'num32BitConstants' '=' NUMBER ',' 
+   bReg (',' 'space' '=' NUMBER)? 
+   (',' 'visibility' '=' SHADER_VISIBILITY)? ')'
+
+RootCBV : 'CBV' '(' bReg (',' 'space' '=' NUMBER)? 
+  (',' 'visibility' '=' SHADER_VISIBILITY)? 
+  (',' 'flags' '=' DATA_FLAGS)? ')'
+
+RootSRV : 'SRV' '(' tReg (',' 'space' '=' NUMBER)? 
+  (',' 'visibility' '=' SHADER_VISIBILITY)? 
+  (',' 'flags' '=' DATA_FLAGS)? ')'
+
+RootUAV : 'UAV' '(' uReg (',' 'space' '=' NUMBER)? 
+  (',' 'visibility' '=' SHADER_VISIBILITY)? 
+  (',' 'flags' '=' DATA_FLAGS)? ')'
+
+DescriptorTable : 'DescriptorTable' '(' (DTClause(|DTClause)?)? 
+  (',' 'visibility' '=' SHADER_VISIBILITY)? ')'
+
+DTClause : CBV | SRV | UAV | Sampler
+
+CBV : 'CBV' '(' bReg (',' 'numDescriptors' '=' NUMBER)? 
+  (',' 'space' '=' NUMBER)? 
+  (',' 'offset' '=' DESCRIPTOR_RANGE_OFFSET)? 
+  (',' 'flags' '=' DATA_FLAGS)? ')'
+
+SRV : 'SRV' '(' tReg (',' 'numDescriptors' '=' NUMBER)? 
+(',' 'space' '=' NUMBER)? 
+  (',' 'offset' '=' DESCRIPTOR_RANGE_OFFSET)? 
+  (',' 'flags' '=' DATA_FLAGS)? ')'
+
+UAV : 'UAV' '(' uReg (',' 'numDescriptors' '=' NUMBER)? 
+  (',' 'space' '=' NUMBER)? 
+  (',' 'offset' '=' DESCRIPTOR_RANGE_OFFSET)? 
+  (',' 'flags' '=' DATA_FLAGS)? ')'
+
+Sampler : 'Sampler' '(' sReg (',' 'numDescriptors' '=' NUMBER)? 
+  (',' 'space' '=' NUMBER)? 
+  (',' 'offset' '=' DESCRIPTOR_RANGE_OFFSET)? (',' 'flags' '=' 
NUMBER)? ')'
+
+
+SHADER_VISIBILITY : 'SHADER_VISIBILITY_ALL' | 'SHADER_VISIBILITY_VERTEX' | 
+'SHADER_VISIBILITY_HULL' | 
+'SHADER_VISIBILITY_DOMAIN' | 
+'SHADER_VISIBILITY_GEOMETRY' | 
+'SHADER_VISIBILITY_PIXEL' | 
+'SHADER_VISIBILITY_AMPLIFICATION' | 
+'SHADER_VISIBILITY_MESH'
+
+DATA_FLAGS : 'DATA_STATIC_WH

[clang] [libcxx] [libc++] Implement LWG3528 (`make_from_tuple` can perform (the equivalent of) a C-style cast) (PR #85263)

2024-03-21 Thread via cfe-commits

https://github.com/yronglin updated 
https://github.com/llvm/llvm-project/pull/85263

>From fc8c1a24f09c8860269fbdcfb0b285ffd19f427c Mon Sep 17 00:00:00 2001
From: yronglin 
Date: Fri, 15 Mar 2024 00:48:08 +0800
Subject: [PATCH 1/9] [libc++] Implement LWG3528 (`make_from_tuple` can perform
 (the equivalent of) a C-style cast)

Signed-off-by: yronglin 
---
 libcxx/docs/Status/Cxx23Issues.csv|  2 +-
 libcxx/include/tuple  | 12 ++-
 .../tuple.apply/make_from_tuple.verify.cpp| 74 +++
 3 files changed, 85 insertions(+), 3 deletions(-)
 create mode 100644 
libcxx/test/std/utilities/tuple/tuple.tuple/tuple.apply/make_from_tuple.verify.cpp

diff --git a/libcxx/docs/Status/Cxx23Issues.csv 
b/libcxx/docs/Status/Cxx23Issues.csv
index e00345533b865d..0fd58649b0cf64 100644
--- a/libcxx/docs/Status/Cxx23Issues.csv
+++ b/libcxx/docs/Status/Cxx23Issues.csv
@@ -77,7 +77,7 @@
 `3523 `__,"``iota_view::sentinel`` is not always 
``iota_view``'s sentinel","June 2021","","","|ranges|"
 `3526 `__,"Return types of 
``uses_allocator_construction_args`` unspecified","June 2021","",""
 `3527 `__,"``uses_allocator_construction_args`` 
handles rvalue pairs of rvalue references incorrectly","June 2021","",""
-`3528 `__,"``make_from_tuple`` can perform (the 
equivalent of) a C-style cast","June 2021","",""
+`3528 `__,"``make_from_tuple`` can perform (the 
equivalent of) a C-style cast","June 2021","|Complete|","19.0"
 `3529 `__,"``priority_queue(first, last)`` should 
construct ``c`` with ``(first, last)``","June 2021","|Complete|","14.0"
 `3530 `__,"``BUILTIN-PTR-MEOW`` should not opt the 
type out of syntactic checks","June 2021","",""
 `3532 `__,"``split_view::inner-iterator::operator++(int)`` should depend on ``Base``","June 
2021","","","|ranges|"
diff --git a/libcxx/include/tuple b/libcxx/include/tuple
index 8808db6739fb9b..1ef546c5b2153d 100644
--- a/libcxx/include/tuple
+++ b/libcxx/include/tuple
@@ -1423,8 +1423,16 @@ inline _LIBCPP_HIDE_FROM_ABI constexpr decltype(auto) 
apply(_Fn&& __f, _Tuple&&
 typename 
__make_tuple_indices>>::type{}))
 
 template 
-inline _LIBCPP_HIDE_FROM_ABI constexpr _Tp __make_from_tuple_impl(_Tuple&& 
__t, __tuple_indices<_Idx...>)
-_LIBCPP_NOEXCEPT_RETURN(_Tp(std::get<_Idx>(std::forward<_Tuple>(__t))...))
+inline _LIBCPP_HIDE_FROM_ABI constexpr _Tp __make_from_tuple_impl(_Tuple&& 
__t, __tuple_indices<_Idx...>) 
+  noexcept(noexcept(_Tp(std::get<_Idx>(std::forward<_Tuple>(__t))...)))
+#if _LIBCPP_STD_VER >= 20
+  requires is_constructible_v<_Tp, 
decltype(std::get<_Idx>(std::forward<_Tuple>(__t)))...>
+#endif
+{
+  static_assert(is_constructible_v<_Tp, 
decltype(std::get<_Idx>(std::forward<_Tuple>(__t)))...>, 
+"Cannot constructible target type from the fields of the 
argument tuple.");
+  return _Tp(std::get<_Idx>(std::forward<_Tuple>(__t))...);
+}
 
 template 
 inline _LIBCPP_HIDE_FROM_ABI constexpr _Tp make_from_tuple(_Tuple&& __t)
diff --git 
a/libcxx/test/std/utilities/tuple/tuple.tuple/tuple.apply/make_from_tuple.verify.cpp
 
b/libcxx/test/std/utilities/tuple/tuple.tuple/tuple.apply/make_from_tuple.verify.cpp
new file mode 100644
index 00..9bdca4dc7813cb
--- /dev/null
+++ 
b/libcxx/test/std/utilities/tuple/tuple.tuple/tuple.apply/make_from_tuple.verify.cpp
@@ -0,0 +1,74 @@
+//===--===//
+//
+// 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
+//
+//===--===//
+
+// UNSUPPORTED: c++03, c++11, c++14
+
+// 
+
+// template  constexpr T make_from_tuple(Tuple&&);
+
+#include 
+
+int main() {
+  // clang-format off
+#if _LIBCPP_STD_VER <= 20
+  // reinterpret_cast
+  {
+struct B { int b; } b;
+std::tuple t{&b};
+auto a = std::make_from_tuple(t); // expected-error-re@*:* {{static 
assertion failed {{.*}}Cannot constructible target type from the fields of the 
argument tuple.}}
+(void)a;
+  }
+
+  // const_cast
+  {
+const char *str = "Hello";
+std::tuple t{str};
+auto a = std::make_from_tuple(t); // expected-error-re@*:* 
{{static assertion failed {{.*}}Cannot constructible target type from the 
fields of the argument tuple.}}
+(void)a;
+  }
+
+  // static_cast
+  {
+struct B {};
+struct C : public B {} c;
+B &br = c;
+std::tuple t{br};
+auto a = std::make_from_tuple(t); // expected-error-re@*:* 
{{static assertion failed {{.*}}Cannot constructible target type from the 
fields of the argument tuple.}}
+(void)a;
+  }
+#else
+  // reinterpret_cast
+  {
+s

[clang] Raise an error on namespace aliases with qualified names. (PR #86122)

2024-03-21 Thread Daniel M. Katz via cfe-commits

https://github.com/katzdm created 
https://github.com/llvm/llvm-project/pull/86122

Clang's current behavior is to ignore the trailing qualifiers, but the 
[grammar](https://eel.is/c++draft/namespace.alias#nt:namespace-alias-definition)
 for `namespace-alias-definition` requires an `identifier` without 
qualification.

https://godbolt.org/z/1zvW5q4f8

>From 319b7d99b4010514a1680ffd99fb0586b5e7221d Mon Sep 17 00:00:00 2001
From: Dan Katz 
Date: Thu, 21 Mar 2024 09:47:04 -0400
Subject: [PATCH] Raise an error on namespace aliases with qualified names.

Current behavior is to ignore the trailing qualifiers, but the grammar
for `namespace-alias-definition` requires an `identifier` without
qualification.

https://godbolt.org/z/1zvW5q4f8

https://eel.is/c++draft/namespace.alias#nt:namespace-alias-definition
---
 clang/include/clang/Basic/DiagnosticParseKinds.td | 2 ++
 clang/lib/Parse/ParseDeclCXX.cpp  | 5 +
 clang/test/SemaCXX/namespace-alias.cpp| 2 ++
 3 files changed, 9 insertions(+)

diff --git a/clang/include/clang/Basic/DiagnosticParseKinds.td 
b/clang/include/clang/Basic/DiagnosticParseKinds.td
index 816c3ff5f8b2aa..d45a1f0b6ad1c0 100644
--- a/clang/include/clang/Basic/DiagnosticParseKinds.td
+++ b/clang/include/clang/Basic/DiagnosticParseKinds.td
@@ -268,6 +268,8 @@ def err_expected_semi_after_namespace_name : Error<
   "expected ';' after namespace name">;
 def err_unexpected_namespace_attributes_alias : Error<
   "attributes cannot be specified on namespace alias">;
+def err_unexpected_qualified_namespace_alias : Error<
+  "unexpected nested name specifier in namespace alias definition">;
 def err_unexpected_nested_namespace_attribute : Error<
   "attributes cannot be specified on a nested namespace definition">;
 def err_inline_namespace_alias : Error<"namespace alias cannot be inline">;
diff --git a/clang/lib/Parse/ParseDeclCXX.cpp b/clang/lib/Parse/ParseDeclCXX.cpp
index 77d2382ea6d907..0ef2f2fad2a9d1 100644
--- a/clang/lib/Parse/ParseDeclCXX.cpp
+++ b/clang/lib/Parse/ParseDeclCXX.cpp
@@ -140,6 +140,11 @@ Parser::DeclGroupPtrTy 
Parser::ParseNamespace(DeclaratorContext Context,
   SkipUntil(tok::semi);
   return nullptr;
 }
+if (!ExtraNSs.empty()) {
+  Diag(IdentLoc, diag::err_unexpected_qualified_namespace_alias);
+  SkipUntil(tok::semi);
+  return nullptr;
+}
 if (attrLoc.isValid())
   Diag(attrLoc, diag::err_unexpected_namespace_attributes_alias);
 if (InlineLoc.isValid())
diff --git a/clang/test/SemaCXX/namespace-alias.cpp 
b/clang/test/SemaCXX/namespace-alias.cpp
index 281ee9962e8b52..10d2e8beeccaa0 100644
--- a/clang/test/SemaCXX/namespace-alias.cpp
+++ b/clang/test/SemaCXX/namespace-alias.cpp
@@ -47,6 +47,8 @@ namespace I {
   namespace A1 { int i; }
   
   namespace A2 = A1;
+
+  namespace A3::extra::specifiers = A2;  // expected-error {{unexpected nested 
name specifier}}
 }
 
 int f() {

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


[clang] Raise an error on namespace aliases with qualified names. (PR #86122)

2024-03-21 Thread via cfe-commits


@@ -268,6 +268,8 @@ def err_expected_semi_after_namespace_name : Error<
   "expected ';' after namespace name">;
 def err_unexpected_namespace_attributes_alias : Error<
   "attributes cannot be specified on namespace alias">;
+def err_unexpected_qualified_namespace_alias : Error<
+  "unexpected nested name specifier in namespace alias definition">;

Sirraide wrote:

I’m not sure how many people would know what a ‘nested name specifier’ is—or at 
least it requires a bit of thinking. Maybe something like ‘namespace alias must 
be a single identifier’ would be a bit more obvious?

https://github.com/llvm/llvm-project/pull/86122
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Raise an error on namespace aliases with qualified names. (PR #86122)

2024-03-21 Thread via cfe-commits

https://github.com/Sirraide requested changes to this pull request.

Thanks for contributing! This needs a release note (in 
`clang/docs/ReleaseNotes.rst`) and some changes to the diagnostics, but other 
than that it looks fine to me.

https://github.com/llvm/llvm-project/pull/86122
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Raise an error on namespace aliases with qualified names. (PR #86122)

2024-03-21 Thread via cfe-commits


@@ -140,6 +140,11 @@ Parser::DeclGroupPtrTy 
Parser::ParseNamespace(DeclaratorContext Context,
   SkipUntil(tok::semi);
   return nullptr;
 }
+if (!ExtraNSs.empty()) {
+  Diag(IdentLoc, diag::err_unexpected_qualified_namespace_alias);

Sirraide wrote:

This is more of a cosmetic thing, but it would be nice to `<<` a `SourceRange` 
here that contains everything from the first `::` to the last identifier (e.g. 
in `namespace a::b::c = d`, that would be `::b::c`) so we underline it in the 
diagnostic, and maybe also use the location of the first `::` as the location 
for the diagnostic.

https://github.com/llvm/llvm-project/pull/86122
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Raise an error on namespace aliases with qualified names. (PR #86122)

2024-03-21 Thread via cfe-commits

https://github.com/Sirraide edited 
https://github.com/llvm/llvm-project/pull/86122
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Raise an error on namespace aliases with qualified names. (PR #86122)

2024-03-21 Thread Daniel M. Katz via cfe-commits


@@ -268,6 +268,8 @@ def err_expected_semi_after_namespace_name : Error<
   "expected ';' after namespace name">;
 def err_unexpected_namespace_attributes_alias : Error<
   "attributes cannot be specified on namespace alias">;
+def err_unexpected_qualified_namespace_alias : Error<
+  "unexpected nested name specifier in namespace alias definition">;

katzdm wrote:

Sounds good - I was trying to think of the right phrasing and had found some 
references to "nested name specifiers" in other diagnostics. But I like your 
suggested phrasing 👍 

https://github.com/llvm/llvm-project/pull/86122
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Improves -print-library-module-manifest-path. (PR #85943)

2024-03-21 Thread Mark de Wever via cfe-commits

https://github.com/mordante closed 
https://github.com/llvm/llvm-project/pull/85943
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Raise an error on namespace aliases with qualified names. (PR #86122)

2024-03-21 Thread via cfe-commits


@@ -140,6 +140,11 @@ Parser::DeclGroupPtrTy 
Parser::ParseNamespace(DeclaratorContext Context,
   SkipUntil(tok::semi);
   return nullptr;
 }
+if (!ExtraNSs.empty()) {
+  Diag(IdentLoc, diag::err_unexpected_qualified_namespace_alias);

Sirraide wrote:

If you want to, you could also consider adding a fix-it hint to remove the 
extra `::`+*nested-name-specifier*, but I doubt that this would be a common 
error (seeing as this bug has been in Clang for a long time w/o anyone 
noticing), so I don’t think it’s really that necessary here. Just the error 
would also be enough imo.

https://github.com/llvm/llvm-project/pull/86122
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Improves -print-library-module-manifest-path. (PR #85943)

2024-03-21 Thread Mark de Wever via cfe-commits

mordante wrote:

Thanks!

https://github.com/llvm/llvm-project/pull/85943
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Raise an error on namespace aliases with qualified names. (PR #86122)

2024-03-21 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Daniel M. Katz (katzdm)


Changes

Clang's current behavior is to ignore the trailing qualifiers, but the 
[grammar](https://eel.is/c++draft/namespace.alias#nt:namespace-alias-definition)
 for `namespace-alias-definition` requires an `identifier` without 
qualification.

https://godbolt.org/z/1zvW5q4f8

---
Full diff: https://github.com/llvm/llvm-project/pull/86122.diff


3 Files Affected:

- (modified) clang/include/clang/Basic/DiagnosticParseKinds.td (+2) 
- (modified) clang/lib/Parse/ParseDeclCXX.cpp (+5) 
- (modified) clang/test/SemaCXX/namespace-alias.cpp (+2) 


``diff
diff --git a/clang/include/clang/Basic/DiagnosticParseKinds.td 
b/clang/include/clang/Basic/DiagnosticParseKinds.td
index 816c3ff5f8b2aa..d45a1f0b6ad1c0 100644
--- a/clang/include/clang/Basic/DiagnosticParseKinds.td
+++ b/clang/include/clang/Basic/DiagnosticParseKinds.td
@@ -268,6 +268,8 @@ def err_expected_semi_after_namespace_name : Error<
   "expected ';' after namespace name">;
 def err_unexpected_namespace_attributes_alias : Error<
   "attributes cannot be specified on namespace alias">;
+def err_unexpected_qualified_namespace_alias : Error<
+  "unexpected nested name specifier in namespace alias definition">;
 def err_unexpected_nested_namespace_attribute : Error<
   "attributes cannot be specified on a nested namespace definition">;
 def err_inline_namespace_alias : Error<"namespace alias cannot be inline">;
diff --git a/clang/lib/Parse/ParseDeclCXX.cpp b/clang/lib/Parse/ParseDeclCXX.cpp
index 77d2382ea6d907..0ef2f2fad2a9d1 100644
--- a/clang/lib/Parse/ParseDeclCXX.cpp
+++ b/clang/lib/Parse/ParseDeclCXX.cpp
@@ -140,6 +140,11 @@ Parser::DeclGroupPtrTy 
Parser::ParseNamespace(DeclaratorContext Context,
   SkipUntil(tok::semi);
   return nullptr;
 }
+if (!ExtraNSs.empty()) {
+  Diag(IdentLoc, diag::err_unexpected_qualified_namespace_alias);
+  SkipUntil(tok::semi);
+  return nullptr;
+}
 if (attrLoc.isValid())
   Diag(attrLoc, diag::err_unexpected_namespace_attributes_alias);
 if (InlineLoc.isValid())
diff --git a/clang/test/SemaCXX/namespace-alias.cpp 
b/clang/test/SemaCXX/namespace-alias.cpp
index 281ee9962e8b52..10d2e8beeccaa0 100644
--- a/clang/test/SemaCXX/namespace-alias.cpp
+++ b/clang/test/SemaCXX/namespace-alias.cpp
@@ -47,6 +47,8 @@ namespace I {
   namespace A1 { int i; }
   
   namespace A2 = A1;
+
+  namespace A3::extra::specifiers = A2;  // expected-error {{unexpected nested 
name specifier}}
 }
 
 int f() {

``




https://github.com/llvm/llvm-project/pull/86122
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Raise an error on namespace aliases with qualified names. (PR #86122)

2024-03-21 Thread via cfe-commits

https://github.com/Sirraide edited 
https://github.com/llvm/llvm-project/pull/86122
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Sema] Don't drop weak_import from a declaration that follows a declaration directly contained in a linkage-specification (PR #85886)

2024-03-21 Thread Akira Hatanaka via cfe-commits

https://github.com/ahatanak updated 
https://github.com/llvm/llvm-project/pull/85886

>From d39667c7e65c10babb478d8f8d54fecb66d90568 Mon Sep 17 00:00:00 2001
From: Akira Hatanaka 
Date: Tue, 19 Mar 2024 15:50:00 -0700
Subject: [PATCH] [Sema] Don't drop weak_import from a declaration that follows
 a declaration directly contained in a linkage-specification

Only drop it if the declaration follows a definition. I believe this is
what 33e022650adee965c65f9aea086ee74f3fd1bad5 was trying to do.

rdar://61865848
---
 clang/lib/Sema/SemaDecl.cpp  | 3 +--
 clang/test/SemaCXX/attr-weak.cpp | 7 +++
 2 files changed, 8 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 5850cd0ab6b9aa..2e45f1191273a4 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -4613,8 +4613,7 @@ void Sema::MergeVarDecl(VarDecl *New, LookupResult 
&Previous) {
   mergeDeclAttributes(New, Old);
   // Warn if an already-declared variable is made a weak_import in a subsequent
   // declaration
-  if (New->hasAttr() &&
-  Old->getStorageClass() == SC_None &&
+  if (New->hasAttr() && Old->isThisDeclarationADefinition() &&
   !Old->hasAttr()) {
 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
 Diag(Old->getLocation(), diag::note_previous_declaration);
diff --git a/clang/test/SemaCXX/attr-weak.cpp b/clang/test/SemaCXX/attr-weak.cpp
index f065bfd9483f8a..a2c5fd4abd35f6 100644
--- a/clang/test/SemaCXX/attr-weak.cpp
+++ b/clang/test/SemaCXX/attr-weak.cpp
@@ -55,3 +55,10 @@ constexpr bool weak_method_is_non_null = 
&WithWeakMember::weak_method != nullptr
 // virtual member function is present.
 constexpr bool virtual_weak_method_is_non_null = 
&WithWeakMember::virtual_weak_method != nullptr; // expected-error {{must be 
initialized by a constant expression}}
 // expected-note@-1 {{comparison against pointer to weak member 
'WithWeakMember::virtual_weak_method' can only be performed at runtime}}
+
+// Check that no warnings are emitted.
+extern "C" int g0;
+extern int g0 __attribute__((weak_import));
+
+extern "C" int g1 = 0; // expected-note {{previous definition is here}}
+extern int g1 __attribute__((weak_import)); // expected-warning {{attribute 
declaration must precede definition}}

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


[clang] [llvm] [WebAssembly] Implement an alternative translation for -wasm-enable-sjlj (PR #84137)

2024-03-21 Thread YAMAMOTO Takashi via cfe-commits

yamt wrote:

> @yamt Given that this PR is not large and we already went through it anyway, 
> nevermind what I said about rebasing, and please use whatever method you are 
> convenient with. But just FYI you can do `git merge` to avoid rebasing (I'm 
> not asking you to do it here; just in case you aren't aware)

ok. i just rebased + force pushed.

i usually avoid merge commits in a PR because i personally feel it's rather 
complicated to review.
is it a common practice in this repo?


https://github.com/llvm/llvm-project/pull/84137
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][AST][NFC] Add '[[fallthrough]]' to cases fall through (PR #85921)

2024-03-21 Thread via cfe-commits

https://github.com/Sirraide approved this pull request.

LGTM

https://github.com/llvm/llvm-project/pull/85921
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Constexpr for __builtin_shufflevector and __builtin_convertvector (PR #76615)

2024-03-21 Thread Simon Pilgrim via cfe-commits
Pol Marcet =?utf-8?q?Sard=C3=A0?= ,
Pol Marcet =?utf-8?q?Sard=C3=A0?= ,Pol M
 
Message-ID:
In-Reply-To: 


RKSimon wrote:

@Destroyerrrocket reverse-ping - are you still working on this?

https://github.com/llvm/llvm-project/pull/76615
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] add new check readability-enum-initial-value (PR #86129)

2024-03-21 Thread Congcong Cai via cfe-commits

https://github.com/HerrCai0907 created 
https://github.com/llvm/llvm-project/pull/86129

Fixes: #85243.


>From 4e0845a143a820d4a68ffbdced206654c7593359 Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Fri, 15 Mar 2024 08:07:47 +0800
Subject: [PATCH] [clang-tidy] add new check readability-enum-initial-value

Fixes: #85243.
---
 .../clang-tidy/readability/CMakeLists.txt |  1 +
 .../readability/EnumInitialValueCheck.cpp | 82 +++
 .../readability/EnumInitialValueCheck.h   | 31 +++
 .../readability/ReadabilityTidyModule.cpp |  3 +
 clang-tools-extra/docs/ReleaseNotes.rst   |  6 ++
 .../docs/clang-tidy/checks/list.rst   |  1 +
 .../checks/readability/enum-initial-value.rst | 45 ++
 .../checkers/readability/enum-initial-value.c | 27 ++
 .../readability/enum-initial-value.cpp| 27 ++
 9 files changed, 223 insertions(+)
 create mode 100644 
clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/readability/enum-initial-value.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/readability/enum-initial-value.c
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/readability/enum-initial-value.cpp

diff --git a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
index 5728c9970fb65d..dd772d69202548 100644
--- a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
@@ -17,6 +17,7 @@ add_clang_library(clangTidyReadabilityModule
   DeleteNullPointerCheck.cpp
   DuplicateIncludeCheck.cpp
   ElseAfterReturnCheck.cpp
+  EnumInitialValueCheck.cpp
   FunctionCognitiveComplexityCheck.cpp
   FunctionSizeCheck.cpp
   IdentifierLengthCheck.cpp
diff --git a/clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.cpp
new file mode 100644
index 00..78d5101d439dde
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.cpp
@@ -0,0 +1,82 @@
+//===--- EnumInitialValueCheck.cpp - clang-tidy 
---===//
+//
+// 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 "EnumInitialValueCheck.h"
+#include "../utils/LexerUtils.h"
+#include "clang/AST/Decl.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Basic/Diagnostic.h"
+#include "llvm/ADT/SmallString.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::readability {
+
+namespace {
+
+AST_MATCHER(EnumDecl, isNoneEnumeratorsInitialized) {
+  return llvm::all_of(Node.enumerators(), [](EnumConstantDecl const *ECD) {
+return ECD->getInitExpr() == nullptr;
+  });
+}
+
+AST_MATCHER(EnumDecl, isOnlyFirstEnumeratorsInitialized) {
+  for (EnumConstantDecl const *ECD : Node.enumerators())
+if (ECD == *Node.enumerator_begin()) {
+  if (ECD->getInitExpr() == nullptr)
+return false;
+} else {
+  if (ECD->getInitExpr() != nullptr)
+return false;
+}
+  return true;
+}
+
+AST_MATCHER(EnumDecl, isAllEnumeratorsInitialized) {
+  return llvm::all_of(Node.enumerators(), [](EnumConstantDecl const *ECD) {
+return ECD->getInitExpr() != nullptr;
+  });
+}
+
+} // namespace
+
+void EnumInitialValueCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(enumDecl(unless(anyOf(isNoneEnumeratorsInitialized(),
+   isOnlyFirstEnumeratorsInitialized(),
+   isAllEnumeratorsInitialized(
+ .bind("enum"),
+ this);
+}
+
+void EnumInitialValueCheck::check(const MatchFinder::MatchResult &Result) {
+  const auto *Enum = Result.Nodes.getNodeAs("enum");
+  assert(Enum != nullptr);
+  SourceLocation Loc = Enum->getBeginLoc();
+  if (Loc.isInvalid() || Loc.isMacroID())
+return;
+  DiagnosticBuilder Diag =
+  diag(Loc, "inital value in enum %0 has readability issue, "
+"explicit initialization of all of enumerators")
+  << Enum->getName();
+  for (EnumConstantDecl const *ECD : Enum->enumerators())
+if (ECD->getInitExpr() == nullptr) {
+  SourceLocation ECDLoc = ECD->getEndLoc();
+  if (ECDLoc.isInvalid() || ECDLoc.isMacroID())
+continue;
+  std::optional Next = utils::lexer::findNextTokenSkippingComments(
+  ECDLoc, *Result.SourceManager, getLangOpts());
+  if (!Next.has_value() || Next->getLocation().isMacroID())
+continue;
+  llvm::SmallString<

[clang-tools-extra] [clang-tidy] add new check readability-enum-initial-value (PR #86129)

2024-03-21 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-tidy

Author: Congcong Cai (HerrCai0907)


Changes

Fixes: #85243.


---
Full diff: https://github.com/llvm/llvm-project/pull/86129.diff


9 Files Affected:

- (modified) clang-tools-extra/clang-tidy/readability/CMakeLists.txt (+1) 
- (added) clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.cpp 
(+82) 
- (added) clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.h 
(+31) 
- (modified) clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp 
(+3) 
- (modified) clang-tools-extra/docs/ReleaseNotes.rst (+6) 
- (modified) clang-tools-extra/docs/clang-tidy/checks/list.rst (+1) 
- (added) 
clang-tools-extra/docs/clang-tidy/checks/readability/enum-initial-value.rst 
(+45) 
- (added) 
clang-tools-extra/test/clang-tidy/checkers/readability/enum-initial-value.c 
(+27) 
- (added) 
clang-tools-extra/test/clang-tidy/checkers/readability/enum-initial-value.cpp 
(+27) 


``diff
diff --git a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
index 5728c9970fb65d..dd772d69202548 100644
--- a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
@@ -17,6 +17,7 @@ add_clang_library(clangTidyReadabilityModule
   DeleteNullPointerCheck.cpp
   DuplicateIncludeCheck.cpp
   ElseAfterReturnCheck.cpp
+  EnumInitialValueCheck.cpp
   FunctionCognitiveComplexityCheck.cpp
   FunctionSizeCheck.cpp
   IdentifierLengthCheck.cpp
diff --git a/clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.cpp
new file mode 100644
index 00..78d5101d439dde
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.cpp
@@ -0,0 +1,82 @@
+//===--- EnumInitialValueCheck.cpp - clang-tidy 
---===//
+//
+// 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 "EnumInitialValueCheck.h"
+#include "../utils/LexerUtils.h"
+#include "clang/AST/Decl.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Basic/Diagnostic.h"
+#include "llvm/ADT/SmallString.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::readability {
+
+namespace {
+
+AST_MATCHER(EnumDecl, isNoneEnumeratorsInitialized) {
+  return llvm::all_of(Node.enumerators(), [](EnumConstantDecl const *ECD) {
+return ECD->getInitExpr() == nullptr;
+  });
+}
+
+AST_MATCHER(EnumDecl, isOnlyFirstEnumeratorsInitialized) {
+  for (EnumConstantDecl const *ECD : Node.enumerators())
+if (ECD == *Node.enumerator_begin()) {
+  if (ECD->getInitExpr() == nullptr)
+return false;
+} else {
+  if (ECD->getInitExpr() != nullptr)
+return false;
+}
+  return true;
+}
+
+AST_MATCHER(EnumDecl, isAllEnumeratorsInitialized) {
+  return llvm::all_of(Node.enumerators(), [](EnumConstantDecl const *ECD) {
+return ECD->getInitExpr() != nullptr;
+  });
+}
+
+} // namespace
+
+void EnumInitialValueCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(enumDecl(unless(anyOf(isNoneEnumeratorsInitialized(),
+   isOnlyFirstEnumeratorsInitialized(),
+   isAllEnumeratorsInitialized(
+ .bind("enum"),
+ this);
+}
+
+void EnumInitialValueCheck::check(const MatchFinder::MatchResult &Result) {
+  const auto *Enum = Result.Nodes.getNodeAs("enum");
+  assert(Enum != nullptr);
+  SourceLocation Loc = Enum->getBeginLoc();
+  if (Loc.isInvalid() || Loc.isMacroID())
+return;
+  DiagnosticBuilder Diag =
+  diag(Loc, "inital value in enum %0 has readability issue, "
+"explicit initialization of all of enumerators")
+  << Enum->getName();
+  for (EnumConstantDecl const *ECD : Enum->enumerators())
+if (ECD->getInitExpr() == nullptr) {
+  SourceLocation ECDLoc = ECD->getEndLoc();
+  if (ECDLoc.isInvalid() || ECDLoc.isMacroID())
+continue;
+  std::optional Next = utils::lexer::findNextTokenSkippingComments(
+  ECDLoc, *Result.SourceManager, getLangOpts());
+  if (!Next.has_value() || Next->getLocation().isMacroID())
+continue;
+  llvm::SmallString<8> Str{" = "};
+  ECD->getInitVal().toString(Str);
+  Diag << FixItHint::CreateInsertion(Next->getLocation(), Str);
+}
+}
+
+} // namespace clang::tidy::readability
diff --git a/clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.h 
b/clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.h
new file mode 100644
index 00..6b4e0e28e35be0
--- /dev/null
+++ 

[clang-tools-extra] [clang-tidy] add new check readability-enum-initial-value (PR #86129)

2024-03-21 Thread via cfe-commits

github-actions[bot] wrote:




:warning: C/C++ code formatter, clang-format found issues in your code. 
:warning:



You can test this locally with the following command:


``bash
git-clang-format --diff ffe41819e58365dfbe85a22556c0d9d284e746b9 
4e0845a143a820d4a68ffbdced206654c7593359 -- 
clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.cpp 
clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.h 
clang-tools-extra/test/clang-tidy/checkers/readability/enum-initial-value.c 
clang-tools-extra/test/clang-tidy/checkers/readability/enum-initial-value.cpp 
clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.h 
b/clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.h
index 6b4e0e28e3..8a0ddd2b38 100644
--- a/clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.h
+++ b/clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.h
@@ -13,8 +13,8 @@
 
 namespace clang::tidy::readability {
 
-/// Detects explicit initialization of a part of enumerators in an 
enumeration, and
-/// relying on compiler to initialize the others.
+/// Detects explicit initialization of a part of enumerators in an enumeration,
+/// and relying on compiler to initialize the others.
 ///
 /// For the user-facing documentation see:
 /// 
http://clang.llvm.org/extra/clang-tidy/checks/readability/enum-initial-value.html

``




https://github.com/llvm/llvm-project/pull/86129
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][AST][NFC] Add '[[fallthrough]]' to cases fall through (PR #85921)

2024-03-21 Thread Aaron Ballman via cfe-commits

https://github.com/AaronBallman commented:

Is this addressing a diagnostic you're seeing in the wild? This shouldn't be 
necessary because the `case` statements are adjacent to one another with only 
comments/whitespace between them: https://godbolt.org/z/oM7x65hq9

(I'd like to understand the motivation better because I don't think we want to 
add `[[fallthrough]]` to all adjacent cases in the code base, so this seems 
inconsistent.)

https://github.com/llvm/llvm-project/pull/85921
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][analyzer] Model more getline/getdelim pre and postconditions (PR #83027)

2024-03-21 Thread Balázs Kéri via cfe-commits


@@ -376,3 +377,122 @@ void fflush_on_open_failed_stream(void) {
   }
   fclose(F);
 }
+
+void getline_null_file() {
+  char *buffer = NULL;
+  size_t n = 0;
+  getline(&buffer, &n, NULL); // expected-warning {{Stream pointer might be 
NULL}}
+}
+
+void getdelim_null_file() {
+  char *buffer = NULL;
+  size_t n = 0;
+  getdelim(&buffer, &n, '\n', NULL); // expected-warning {{Stream pointer 
might be NULL}}
+}
+
+void getline_no_return_check() {
+  FILE *file = fopen("file.txt", "r");
+  if (file == NULL) {
+return;
+  }
+
+  char *line = NULL;
+  size_t len = 0;
+  getline(&line, &len, file);
+
+  if (line[0] == '\0') {} // expected-warning {{The left operand of '==' is a 
garbage value}}
+
+  free(line);
+  fclose(file);
+}
+
+void getline_after_eof() {
+  FILE *file = fopen("file.txt", "r");
+  if (file == NULL) {
+return;
+  }
+
+  size_t n = 10;
+  char *buffer = malloc(n);
+  ssize_t read = fread(buffer, n, 1, file);
+  if (!feof(file)) {
+getline(&buffer, &n, file); // expected-warning {{File position of the 
stream might be 'indeterminate' after a failed operation. Can cause undefined 
behavior}}
+  }
+  fclose(file);
+  free(buffer);
+}
+
+void getline_feof() {
+  FILE *file = fopen("file.txt", "r");
+  if (file == NULL) {
+return;
+  }
+
+  size_t n = 10;
+  char *buffer = malloc(n);
+  ssize_t read = fread(buffer, n, 1, file);
+  getline(&buffer, &n, file); // expected-warning {{File position of the 
stream might be 'indeterminate' after a failed operation. Can cause undefined 
behavior}} \\
+  expected-warning {{Read function called when stream is in EOF state. 
Function has no effect}}
+  fclose(file);
+  free(buffer);
+}
+
+void getline_feof_check() {
+  FILE *file = fopen("file.txt", "r");
+  if (file == NULL) {
+return;
+  }
+
+  char *line = NULL;
+  size_t len = 0;
+  ssize_t r = getline(&line, &len, file);
+
+  if (r != -1) {
+// success, end-of-file is not possible
+int f = feof(file);
+clang_analyzer_eval(f == 0); // expected-warning {{TRUE}}
+  } else {
+// failure, end-of-file is possible, but not the only reason to fail
+int f = feof(file);
+clang_analyzer_eval(f == 0); // expected-warning {{TRUE}} \\
+expected-warning {{FALSE}}
+  }
+  free(line);
+  fclose(file);
+}
+
+void getline_ret_value() {
+  FILE *file = fopen("file.txt", "r");
+  if (file == NULL) {
+return;
+  }
+
+  size_t n = 0;
+  char *buffer = NULL;
+  ssize_t r = getline(&buffer, &n, file);
+
+  if (r > -1) {
+// The return value does *not* include the terminating null byte.
+// The buffer must be large enough to include it.
+clang_analyzer_eval(n > r); // expected-warning{{TRUE}}

balazske wrote:

Should check that `buffer != NULL` is true.

https://github.com/llvm/llvm-project/pull/83027
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][analyzer] Model more getline/getdelim pre and postconditions (PR #83027)

2024-03-21 Thread Balázs Kéri via cfe-commits


@@ -376,3 +377,122 @@ void fflush_on_open_failed_stream(void) {
   }
   fclose(F);
 }
+
+void getline_null_file() {
+  char *buffer = NULL;
+  size_t n = 0;
+  getline(&buffer, &n, NULL); // expected-warning {{Stream pointer might be 
NULL}}
+}
+
+void getdelim_null_file() {
+  char *buffer = NULL;
+  size_t n = 0;
+  getdelim(&buffer, &n, '\n', NULL); // expected-warning {{Stream pointer 
might be NULL}}
+}
+
+void getline_no_return_check() {
+  FILE *file = fopen("file.txt", "r");
+  if (file == NULL) {
+return;
+  }
+
+  char *line = NULL;
+  size_t len = 0;
+  getline(&line, &len, file);
+
+  if (line[0] == '\0') {} // expected-warning {{The left operand of '==' is a 
garbage value}}
+
+  free(line);
+  fclose(file);
+}
+
+void getline_after_eof() {
+  FILE *file = fopen("file.txt", "r");
+  if (file == NULL) {
+return;
+  }
+
+  size_t n = 10;
+  char *buffer = malloc(n);
+  ssize_t read = fread(buffer, n, 1, file);
+  if (!feof(file)) {
+getline(&buffer, &n, file); // expected-warning {{File position of the 
stream might be 'indeterminate' after a failed operation. Can cause undefined 
behavior}}
+  }
+  fclose(file);
+  free(buffer);
+}
+
+void getline_feof() {
+  FILE *file = fopen("file.txt", "r");
+  if (file == NULL) {
+return;
+  }
+
+  size_t n = 10;
+  char *buffer = malloc(n);
+  ssize_t read = fread(buffer, n, 1, file);
+  getline(&buffer, &n, file); // expected-warning {{File position of the 
stream might be 'indeterminate' after a failed operation. Can cause undefined 
behavior}} \\
+  expected-warning {{Read function called when stream is in EOF state. 
Function has no effect}}
+  fclose(file);
+  free(buffer);
+}
+
+void getline_feof_check() {
+  FILE *file = fopen("file.txt", "r");
+  if (file == NULL) {
+return;
+  }
+
+  char *line = NULL;
+  size_t len = 0;
+  ssize_t r = getline(&line, &len, file);
+
+  if (r != -1) {
+// success, end-of-file is not possible
+int f = feof(file);
+clang_analyzer_eval(f == 0); // expected-warning {{TRUE}}
+  } else {
+// failure, end-of-file is possible, but not the only reason to fail
+int f = feof(file);
+clang_analyzer_eval(f == 0); // expected-warning {{TRUE}} \\
+expected-warning {{FALSE}}
+  }
+  free(line);
+  fclose(file);
+}
+
+void getline_ret_value() {
+  FILE *file = fopen("file.txt", "r");
+  if (file == NULL) {
+return;
+  }
+
+  size_t n = 0;
+  char *buffer = NULL;
+  ssize_t r = getline(&buffer, &n, file);
+
+  if (r > -1) {
+// The return value does *not* include the terminating null byte.
+// The buffer must be large enough to include it.
+clang_analyzer_eval(n > r); // expected-warning{{TRUE}}
+  }
+
+  fclose(file);
+  free(buffer);
+}
+
+
+void getline_buffer_size_invariant(char *buffer) {

balazske wrote:

This test looks interesting: It is not really different from the previous one, 
except that the buffer is not an initialized value. Because `n` is -1 the 
buffer should be assumed to be NULL before the call. This is not a realistic 
code because `n` should be an indication of the buffer size but this value is 
not known to the function. I think this test (in this form) is not needed.

https://github.com/llvm/llvm-project/pull/83027
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Split -Wcast-function-type into a separate group (PR #86131)

2024-03-21 Thread Aaron Ballman via cfe-commits

https://github.com/AaronBallman created 
https://github.com/llvm/llvm-project/pull/86131

We want to add -Wcast-function-type to -Wextra (as done in 
1de7e6c8cba27296f3fc16d107822ea0ee856759), but we do not want to add 
-Wcast-function-type-strict in at the same time 
(https://lab.llvm.org/buildbot/#/builders/57/builds/33601/steps/5/logs/stdio).

This moves the existing warning to a new group (-Wcast-function-type-mismatch), 
puts the new group under the existing -Wcast-function-type warning group, and 
adds -Wcast-function-type-mismatch to -Wextra.

>From 9b41d75aa47bc9a8a24f7cc4e0f467e2540a0601 Mon Sep 17 00:00:00 2001
From: Aaron Ballman 
Date: Thu, 21 Mar 2024 11:07:50 -0400
Subject: [PATCH] Split -Wcast-function-type into a separate group

We want to add -Wcast-function-type to -Wextra (as done in
1de7e6c8cba27296f3fc16d107822ea0ee856759), but we do not want to add
-Wcast-function-type-strict in at the same time
(https://lab.llvm.org/buildbot/#/builders/57/builds/33601/steps/5/logs/stdio).

This moves the existing warning to a new group
(-Wcast-function-type-mismatch), puts the new group under the existing
-Wcast-function-type warning group, and adds
-Wcast-function-type-mismatch to -Wextra
---
 clang/docs/ReleaseNotes.rst   | 20 ++-
 clang/include/clang/Basic/DiagnosticGroups.td |  7 +--
 .../clang/Basic/DiagnosticSemaKinds.td|  2 +-
 .../Sema/warn-cast-function-type-strict.c | 12 +--
 .../warn-cast-function-type-strict.cpp| 10 +-
 5 files changed, 36 insertions(+), 15 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index a9c55ef662a0b9..6939fb5b4bc953 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -196,7 +196,25 @@ Modified Compiler Flags
   ``-Wreturn-type``, and moved some of the diagnostics previously controlled by
   ``-Wreturn-type`` under this new flag. Fixes #GH72116.
 
-- Added ``-Wcast-function-type`` as a warning enabled by ``-Wextra``. #GH76872
+- Added ``-Wcast-function-type-mismatch`` under the ``-Wcast-function-type``
+  warning group. Moved the diagnostic previously controlled by
+  ``-Wcast-function-type`` to the new warning group and added
+  ``-Wcast-function-type-mismatch`` to ``-Wextra``. #GH76872
+
+  .. code-block:: c
+
+ int x(long);
+ typedef int (f2)(void*);
+ typedef int (f3)();
+
+ void func(void) {
+   // Diagnoses under -Wcast-function-type, -Wcast-function-type-mismatch,
+   // -Wcast-function-type-strict, -Wextra
+   f2 *b = (f2 *)x;
+   // Diagnoses under -Wcast-function-type, -Wcast-function-type-strict
+   f3 *c = (f3 *)x;
+ }
+
 
 Removed Compiler Flags
 -
diff --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index bf03d4e8f67ee1..44035e2fd16f2e 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -573,7 +573,10 @@ def SelTypeCast : DiagGroup<"cast-of-sel-type">;
 def FunctionDefInObjCContainer : DiagGroup<"function-def-in-objc-container">;
 def BadFunctionCast : DiagGroup<"bad-function-cast">;
 def CastFunctionTypeStrict : DiagGroup<"cast-function-type-strict">;
-def CastFunctionType : DiagGroup<"cast-function-type", 
[CastFunctionTypeStrict]>;
+def CastFunctionTypeMismatch : DiagGroup<"cast-function-type-mismatch">;
+def CastFunctionType : DiagGroup<"cast-function-type",
+ [CastFunctionTypeStrict,
+  CastFunctionTypeMismatch]>;
 def ObjCPropertyImpl : DiagGroup<"objc-property-implementation">;
 def ObjCPropertyNoAttribute : DiagGroup<"objc-property-no-attribute">;
 def ObjCPropertyAssignOnObjectType : 
DiagGroup<"objc-property-assign-on-object-type">;
@@ -1038,7 +1041,7 @@ def Extra : DiagGroup<"extra", [
 EmptyInitStatement,
 StringConcatation,
 FUseLdPath,
-CastFunctionType,
+CastFunctionTypeMismatch,
   ]>;
 
 def Most : DiagGroup<"most", [
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 2646942a53e30d..3d8d1e420ccfef 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -9058,7 +9058,7 @@ def warn_bad_function_cast : Warning<
   InGroup, DefaultIgnore;
 def warn_cast_function_type : Warning<
   "cast %diff{from $ to $ |}0,1converts to incompatible function type">,
-  InGroup, DefaultIgnore;
+  InGroup, DefaultIgnore;
 def warn_cast_function_type_strict : Warning,
   InGroup, DefaultIgnore;
 def err_cast_pointer_to_non_pointer_int : Error<
diff --git a/clang/test/Sema/warn-cast-function-type-strict.c 
b/clang/test/Sema/warn-cast-function-type-strict.c
index 8c88f275d2b336..b0a70cf324b711 100644
--- a/clang/test/Sema/warn-cast-function-type-strict.c
+++ b/clang/test/Sema/warn-cast-function-type-strict.c
@@ -1,5 +1,5 @@
-// RUN: %

[clang] Split -Wcast-function-type into a separate group (PR #86131)

2024-03-21 Thread Aaron Ballman via cfe-commits

AaronBallman wrote:

CC @Abhinkop 

https://github.com/llvm/llvm-project/pull/86131
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Split -Wcast-function-type into a separate group (PR #86131)

2024-03-21 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Aaron Ballman (AaronBallman)


Changes

We want to add -Wcast-function-type to -Wextra (as done in 
1de7e6c8cba27296f3fc16d107822ea0ee856759), but we do not want to add 
-Wcast-function-type-strict in at the same time 
(https://lab.llvm.org/buildbot/#/builders/57/builds/33601/steps/5/logs/stdio).

This moves the existing warning to a new group (-Wcast-function-type-mismatch), 
puts the new group under the existing -Wcast-function-type warning group, and 
adds -Wcast-function-type-mismatch to -Wextra.

---
Full diff: https://github.com/llvm/llvm-project/pull/86131.diff


5 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+19-1) 
- (modified) clang/include/clang/Basic/DiagnosticGroups.td (+5-2) 
- (modified) clang/include/clang/Basic/DiagnosticSemaKinds.td (+1-1) 
- (modified) clang/test/Sema/warn-cast-function-type-strict.c (+6-6) 
- (modified) clang/test/SemaCXX/warn-cast-function-type-strict.cpp (+5-5) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index a9c55ef662a0b9..6939fb5b4bc953 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -196,7 +196,25 @@ Modified Compiler Flags
   ``-Wreturn-type``, and moved some of the diagnostics previously controlled by
   ``-Wreturn-type`` under this new flag. Fixes #GH72116.
 
-- Added ``-Wcast-function-type`` as a warning enabled by ``-Wextra``. #GH76872
+- Added ``-Wcast-function-type-mismatch`` under the ``-Wcast-function-type``
+  warning group. Moved the diagnostic previously controlled by
+  ``-Wcast-function-type`` to the new warning group and added
+  ``-Wcast-function-type-mismatch`` to ``-Wextra``. #GH76872
+
+  .. code-block:: c
+
+ int x(long);
+ typedef int (f2)(void*);
+ typedef int (f3)();
+
+ void func(void) {
+   // Diagnoses under -Wcast-function-type, -Wcast-function-type-mismatch,
+   // -Wcast-function-type-strict, -Wextra
+   f2 *b = (f2 *)x;
+   // Diagnoses under -Wcast-function-type, -Wcast-function-type-strict
+   f3 *c = (f3 *)x;
+ }
+
 
 Removed Compiler Flags
 -
diff --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index bf03d4e8f67ee1..44035e2fd16f2e 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -573,7 +573,10 @@ def SelTypeCast : DiagGroup<"cast-of-sel-type">;
 def FunctionDefInObjCContainer : DiagGroup<"function-def-in-objc-container">;
 def BadFunctionCast : DiagGroup<"bad-function-cast">;
 def CastFunctionTypeStrict : DiagGroup<"cast-function-type-strict">;
-def CastFunctionType : DiagGroup<"cast-function-type", 
[CastFunctionTypeStrict]>;
+def CastFunctionTypeMismatch : DiagGroup<"cast-function-type-mismatch">;
+def CastFunctionType : DiagGroup<"cast-function-type",
+ [CastFunctionTypeStrict,
+  CastFunctionTypeMismatch]>;
 def ObjCPropertyImpl : DiagGroup<"objc-property-implementation">;
 def ObjCPropertyNoAttribute : DiagGroup<"objc-property-no-attribute">;
 def ObjCPropertyAssignOnObjectType : 
DiagGroup<"objc-property-assign-on-object-type">;
@@ -1038,7 +1041,7 @@ def Extra : DiagGroup<"extra", [
 EmptyInitStatement,
 StringConcatation,
 FUseLdPath,
-CastFunctionType,
+CastFunctionTypeMismatch,
   ]>;
 
 def Most : DiagGroup<"most", [
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 2646942a53e30d..3d8d1e420ccfef 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -9058,7 +9058,7 @@ def warn_bad_function_cast : Warning<
   InGroup, DefaultIgnore;
 def warn_cast_function_type : Warning<
   "cast %diff{from $ to $ |}0,1converts to incompatible function type">,
-  InGroup, DefaultIgnore;
+  InGroup, DefaultIgnore;
 def warn_cast_function_type_strict : Warning,
   InGroup, DefaultIgnore;
 def err_cast_pointer_to_non_pointer_int : Error<
diff --git a/clang/test/Sema/warn-cast-function-type-strict.c 
b/clang/test/Sema/warn-cast-function-type-strict.c
index 8c88f275d2b336..b0a70cf324b711 100644
--- a/clang/test/Sema/warn-cast-function-type-strict.c
+++ b/clang/test/Sema/warn-cast-function-type-strict.c
@@ -1,5 +1,5 @@
-// RUN: %clang_cc1 %s -fsyntax-only -Wcast-function-type -verify
-// RUN: %clang_cc1 %s -fsyntax-only -Wcast-function-type-strict -verify
+// RUN: %clang_cc1 %s -fsyntax-only -Wcast-function-type 
-verify=expected,strict
+// RUN: %clang_cc1 %s -fsyntax-only -Wcast-function-type-strict 
-verify=expected,strict
 // RUN: %clang_cc1 %s -fsyntax-only -Wextra -Wno-ignored-qualifiers -verify
 
 int t(int array[static 12]);
@@ -32,13 +32,13 @@ f10 *j;
 void foo(void) {
   a = (f1 *)x;
   b = (f2 *)x; /* expected-warning {{cast from 'int (*)(long)' to 'f2 *' (aka 
'int (*)(void *)') converts to in

[clang] [clang] move -Wcast-function-type under -Wextra (PR #77178)

2024-03-21 Thread Aaron Ballman via cfe-commits

AaronBallman wrote:

I've put up a PR for review at https://github.com/llvm/llvm-project/pull/86131

https://github.com/llvm/llvm-project/pull/77178
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][analyzer] Model more getline/getdelim pre and postconditions (PR #83027)

2024-03-21 Thread Balázs Kéri via cfe-commits


@@ -376,3 +377,122 @@ void fflush_on_open_failed_stream(void) {
   }
   fclose(F);
 }
+
+void getline_null_file() {
+  char *buffer = NULL;
+  size_t n = 0;
+  getline(&buffer, &n, NULL); // expected-warning {{Stream pointer might be 
NULL}}
+}
+
+void getdelim_null_file() {
+  char *buffer = NULL;
+  size_t n = 0;
+  getdelim(&buffer, &n, '\n', NULL); // expected-warning {{Stream pointer 
might be NULL}}
+}
+
+void getline_no_return_check() {
+  FILE *file = fopen("file.txt", "r");
+  if (file == NULL) {
+return;
+  }
+
+  char *line = NULL;
+  size_t len = 0;
+  getline(&line, &len, file);
+
+  if (line[0] == '\0') {} // expected-warning {{The left operand of '==' is a 
garbage value}}
+
+  free(line);
+  fclose(file);
+}
+
+void getline_after_eof() {

balazske wrote:

I think `getline_after_eof`, `getline_feof`, `getline_feof_check` are checking 
not much more cases than `error_getline` (and `error_getdelim`) in 
_stream_error.c_ and can be removed. Even if not removed, such tests (that 
check `feof` and `ferror` and related warnings) should put into 
_stream_error.c_.

https://github.com/llvm/llvm-project/pull/83027
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [ValueTracking] Convert `isKnownNonZero` to use SimplifyQuery (PR #85863)

2024-03-21 Thread Yingwei Zheng via cfe-commits

https://github.com/dtcxzyw updated 
https://github.com/llvm/llvm-project/pull/85863

>From bacdc24af088560a986028824a0ac43e929c2f1b Mon Sep 17 00:00:00 2001
From: Yingwei Zheng 
Date: Thu, 21 Mar 2024 21:10:46 +0800
Subject: [PATCH 1/2] [ValueTracking] Add pre-commit tests. NFC.

---
 llvm/test/Transforms/InstCombine/icmp-dom.ll | 139 +++
 1 file changed, 139 insertions(+)

diff --git a/llvm/test/Transforms/InstCombine/icmp-dom.ll 
b/llvm/test/Transforms/InstCombine/icmp-dom.ll
index f4b9022d14349b..138254d912b259 100644
--- a/llvm/test/Transforms/InstCombine/icmp-dom.ll
+++ b/llvm/test/Transforms/InstCombine/icmp-dom.ll
@@ -403,3 +403,142 @@ truelabel:
 falselabel:
   ret i8 0
 }
+
+define i1 @and_mask1_eq(i32 %conv) {
+; CHECK-LABEL: @and_mask1_eq(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:[[AND:%.*]] = and i32 [[CONV:%.*]], 1
+; CHECK-NEXT:[[CMP:%.*]] = icmp eq i32 [[AND]], 0
+; CHECK-NEXT:br i1 [[CMP]], label [[THEN:%.*]], label [[ELSE:%.*]]
+; CHECK:   then:
+; CHECK-NEXT:ret i1 false
+; CHECK:   else:
+; CHECK-NEXT:[[AND1:%.*]] = and i32 [[CONV]], 3
+; CHECK-NEXT:[[CMP1:%.*]] = icmp eq i32 [[AND1]], 0
+; CHECK-NEXT:ret i1 [[CMP1]]
+;
+entry:
+  %and = and i32 %conv, 1
+  %cmp = icmp eq i32 %and, 0
+  br i1 %cmp, label %then, label %else
+
+then:
+  ret i1 0
+
+else:
+  %and1 = and i32 %conv, 3
+  %cmp1 = icmp eq i32 %and1, 0
+  ret i1 %cmp1
+}
+
+define i1 @and_mask1_ne(i32 %conv) {
+; CHECK-LABEL: @and_mask1_ne(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:[[AND:%.*]] = and i32 [[CONV:%.*]], 1
+; CHECK-NEXT:[[CMP:%.*]] = icmp eq i32 [[AND]], 0
+; CHECK-NEXT:br i1 [[CMP]], label [[THEN:%.*]], label [[ELSE:%.*]]
+; CHECK:   then:
+; CHECK-NEXT:ret i1 false
+; CHECK:   else:
+; CHECK-NEXT:[[AND1:%.*]] = and i32 [[CONV]], 3
+; CHECK-NEXT:[[CMP1:%.*]] = icmp ne i32 [[AND1]], 0
+; CHECK-NEXT:ret i1 [[CMP1]]
+;
+entry:
+  %and = and i32 %conv, 1
+  %cmp = icmp eq i32 %and, 0
+  br i1 %cmp, label %then, label %else
+
+then:
+  ret i1 0
+
+else:
+  %and1 = and i32 %conv, 3
+  %cmp1 = icmp ne i32 %and1, 0
+  ret i1 %cmp1
+}
+
+define i1 @and_mask2(i32 %conv) {
+; CHECK-LABEL: @and_mask2(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:[[AND:%.*]] = and i32 [[CONV:%.*]], 4
+; CHECK-NEXT:[[CMP:%.*]] = icmp eq i32 [[AND]], 0
+; CHECK-NEXT:br i1 [[CMP]], label [[THEN:%.*]], label [[ELSE:%.*]]
+; CHECK:   then:
+; CHECK-NEXT:ret i1 false
+; CHECK:   else:
+; CHECK-NEXT:[[AND1:%.*]] = and i32 [[CONV]], 3
+; CHECK-NEXT:[[CMP1:%.*]] = icmp eq i32 [[AND1]], 0
+; CHECK-NEXT:ret i1 [[CMP1]]
+;
+entry:
+  %and = and i32 %conv, 4
+  %cmp = icmp eq i32 %and, 0
+  br i1 %cmp, label %then, label %else
+
+then:
+  ret i1 0
+
+else:
+  %and1 = and i32 %conv, 3
+  %cmp1 = icmp eq i32 %and1, 0
+  ret i1 %cmp1
+}
+
+; TODO: %cmp1 can be folded into false.
+
+define i1 @and_mask3(i32 %conv) {
+; CHECK-LABEL: @and_mask3(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:[[AND:%.*]] = and i32 [[CONV:%.*]], 3
+; CHECK-NEXT:[[CMP:%.*]] = icmp eq i32 [[AND]], 0
+; CHECK-NEXT:br i1 [[CMP]], label [[THEN:%.*]], label [[ELSE:%.*]]
+; CHECK:   then:
+; CHECK-NEXT:ret i1 false
+; CHECK:   else:
+; CHECK-NEXT:[[AND1:%.*]] = and i32 [[CONV]], 7
+; CHECK-NEXT:[[CMP1:%.*]] = icmp eq i32 [[AND1]], 0
+; CHECK-NEXT:ret i1 [[CMP1]]
+;
+entry:
+  %and = and i32 %conv, 3
+  %cmp = icmp eq i32 %and, 0
+  br i1 %cmp, label %then, label %else
+
+then:
+  ret i1 0
+
+else:
+  %and1 = and i32 %conv, 7
+  %cmp1 = icmp eq i32 %and1, 0
+  ret i1 %cmp1
+}
+
+; TODO: %cmp1 can be folded into false.
+
+define i1 @and_mask4(i32 %conv) {
+; CHECK-LABEL: @and_mask4(
+; CHECK-NEXT:  entry:
+; CHECK-NEXT:[[AND:%.*]] = and i32 [[CONV:%.*]], 4
+; CHECK-NEXT:[[CMP:%.*]] = icmp eq i32 [[AND]], 0
+; CHECK-NEXT:br i1 [[CMP]], label [[THEN:%.*]], label [[ELSE:%.*]]
+; CHECK:   then:
+; CHECK-NEXT:ret i1 false
+; CHECK:   else:
+; CHECK-NEXT:[[AND1:%.*]] = and i32 [[CONV]], 7
+; CHECK-NEXT:[[CMP1:%.*]] = icmp eq i32 [[AND1]], 0
+; CHECK-NEXT:ret i1 [[CMP1]]
+;
+entry:
+  %and = and i32 %conv, 4
+  %cmp = icmp eq i32 %and, 0
+  br i1 %cmp, label %then, label %else
+
+then:
+  ret i1 0
+
+else:
+  %and1 = and i32 %conv, 7
+  %cmp1 = icmp eq i32 %and1, 0
+  ret i1 %cmp1
+}

>From 746f3cc306d2cddb222904e73157daf29114a3f3 Mon Sep 17 00:00:00 2001
From: Yingwei Zheng 
Date: Thu, 21 Mar 2024 21:21:13 +0800
Subject: [PATCH 2/2] [ValueTracking] Convert `isKnownNonZero` to use
 SimplifyQuery

---
 clang/lib/CodeGen/CGCall.cpp  |  4 +--
 llvm/include/llvm/Analysis/ValueTracking.h|  6 +---
 llvm/lib/Analysis/BasicAliasAnalysis.cpp  |  3 +-
 llvm/lib/Analysis/InstructionSimplify.cpp | 29 ---
 llvm/lib/Analysis/LazyValueInfo.cpp   |  5 ++--
 llvm/lib/Analysis/Loads.cpp   |  6 ++--
 llvm/lib/Analysis/ScalarEvolution.cpp |  2 +-
 llvm/lib/Analysis/ValueTrack

[clang-tools-extra] [clang-tidy] add new check readability-enum-initial-value (PR #86129)

2024-03-21 Thread Congcong Cai via cfe-commits

https://github.com/HerrCai0907 updated 
https://github.com/llvm/llvm-project/pull/86129

>From 4e0845a143a820d4a68ffbdced206654c7593359 Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Fri, 15 Mar 2024 08:07:47 +0800
Subject: [PATCH 1/2] [clang-tidy] add new check readability-enum-initial-value

Fixes: #85243.
---
 .../clang-tidy/readability/CMakeLists.txt |  1 +
 .../readability/EnumInitialValueCheck.cpp | 82 +++
 .../readability/EnumInitialValueCheck.h   | 31 +++
 .../readability/ReadabilityTidyModule.cpp |  3 +
 clang-tools-extra/docs/ReleaseNotes.rst   |  6 ++
 .../docs/clang-tidy/checks/list.rst   |  1 +
 .../checks/readability/enum-initial-value.rst | 45 ++
 .../checkers/readability/enum-initial-value.c | 27 ++
 .../readability/enum-initial-value.cpp| 27 ++
 9 files changed, 223 insertions(+)
 create mode 100644 
clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/readability/enum-initial-value.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/readability/enum-initial-value.c
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/readability/enum-initial-value.cpp

diff --git a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
index 5728c9970fb65d..dd772d69202548 100644
--- a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
@@ -17,6 +17,7 @@ add_clang_library(clangTidyReadabilityModule
   DeleteNullPointerCheck.cpp
   DuplicateIncludeCheck.cpp
   ElseAfterReturnCheck.cpp
+  EnumInitialValueCheck.cpp
   FunctionCognitiveComplexityCheck.cpp
   FunctionSizeCheck.cpp
   IdentifierLengthCheck.cpp
diff --git a/clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.cpp
new file mode 100644
index 00..78d5101d439dde
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/readability/EnumInitialValueCheck.cpp
@@ -0,0 +1,82 @@
+//===--- EnumInitialValueCheck.cpp - clang-tidy 
---===//
+//
+// 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 "EnumInitialValueCheck.h"
+#include "../utils/LexerUtils.h"
+#include "clang/AST/Decl.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Basic/Diagnostic.h"
+#include "llvm/ADT/SmallString.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::readability {
+
+namespace {
+
+AST_MATCHER(EnumDecl, isNoneEnumeratorsInitialized) {
+  return llvm::all_of(Node.enumerators(), [](EnumConstantDecl const *ECD) {
+return ECD->getInitExpr() == nullptr;
+  });
+}
+
+AST_MATCHER(EnumDecl, isOnlyFirstEnumeratorsInitialized) {
+  for (EnumConstantDecl const *ECD : Node.enumerators())
+if (ECD == *Node.enumerator_begin()) {
+  if (ECD->getInitExpr() == nullptr)
+return false;
+} else {
+  if (ECD->getInitExpr() != nullptr)
+return false;
+}
+  return true;
+}
+
+AST_MATCHER(EnumDecl, isAllEnumeratorsInitialized) {
+  return llvm::all_of(Node.enumerators(), [](EnumConstantDecl const *ECD) {
+return ECD->getInitExpr() != nullptr;
+  });
+}
+
+} // namespace
+
+void EnumInitialValueCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(enumDecl(unless(anyOf(isNoneEnumeratorsInitialized(),
+   isOnlyFirstEnumeratorsInitialized(),
+   isAllEnumeratorsInitialized(
+ .bind("enum"),
+ this);
+}
+
+void EnumInitialValueCheck::check(const MatchFinder::MatchResult &Result) {
+  const auto *Enum = Result.Nodes.getNodeAs("enum");
+  assert(Enum != nullptr);
+  SourceLocation Loc = Enum->getBeginLoc();
+  if (Loc.isInvalid() || Loc.isMacroID())
+return;
+  DiagnosticBuilder Diag =
+  diag(Loc, "inital value in enum %0 has readability issue, "
+"explicit initialization of all of enumerators")
+  << Enum->getName();
+  for (EnumConstantDecl const *ECD : Enum->enumerators())
+if (ECD->getInitExpr() == nullptr) {
+  SourceLocation ECDLoc = ECD->getEndLoc();
+  if (ECDLoc.isInvalid() || ECDLoc.isMacroID())
+continue;
+  std::optional Next = utils::lexer::findNextTokenSkippingComments(
+  ECDLoc, *Result.SourceManager, getLangOpts());
+  if (!Next.has_value() || Next->getLocation().isMacroID())
+continue;
+  llvm::SmallString<8> Str{" = "}

[clang] [llvm] Update documentation and release notes for llvm-profgen COFF support (PR #84864)

2024-03-21 Thread Wei Xiao via cfe-commits

https://github.com/williamweixiao approved this pull request.


https://github.com/llvm/llvm-project/pull/84864
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] Update documentation and release notes for llvm-profgen COFF support (PR #84864)

2024-03-21 Thread Wei Xiao via cfe-commits

williamweixiao wrote:

please resolve the conflicts.

https://github.com/llvm/llvm-project/pull/84864
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [libcxx] [libc++] Implement LWG3528 (`make_from_tuple` can perform (the equivalent of) a C-style cast) (PR #85263)

2024-03-21 Thread via cfe-commits


@@ -1386,9 +1386,19 @@ inline _LIBCPP_HIDE_FROM_ABI constexpr decltype(auto) 
apply(_Fn&& __f, _Tuple&&
 std::forward<_Tuple>(__t),
 typename 
__make_tuple_indices>>::type{}))
 
+#if _LIBCPP_STD_VER >= 20
 template 
 inline _LIBCPP_HIDE_FROM_ABI constexpr _Tp __make_from_tuple_impl(_Tuple&& 
__t, __tuple_indices<_Idx...>)
+  noexcept(noexcept(_Tp(std::get<_Idx>(std::forward<_Tuple>(__t))...)))
+  requires is_constructible_v<_Tp, 
decltype(std::get<_Idx>(std::forward<_Tuple>(__t)))...> {
+  return _Tp(std::get<_Idx>(std::forward<_Tuple>(__t))...);
+}
+#else
+template 
+inline _LIBCPP_HIDE_FROM_ABI constexpr _Tp __make_from_tuple_impl(_Tuple&& 
__t, __tuple_indices<_Idx...>, 
+enable_if_t(std::forward<_Tuple>(__t)))...>> * = nullptr)
 _LIBCPP_NOEXCEPT_RETURN(_Tp(std::get<_Idx>(std::forward<_Tuple>(__t))...))
+#endif // _LIBCPP_STD_VER >= 20
 
 template 

yronglin wrote:

Thanks, I've move the constraints in `std::__make_from_tuple` to 
`std::make_from_tuple`

https://github.com/llvm/llvm-project/pull/85263
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [ValueTracking] Convert `isKnownNonZero` to use SimplifyQuery (PR #85863)

2024-03-21 Thread Yingwei Zheng via cfe-commits

dtcxzyw wrote:

> Can you please fix the clang build?

Done.

https://github.com/llvm/llvm-project/pull/85863
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [libcxx] [libc++] Implement LWG3528 (`make_from_tuple` can perform (the equivalent of) a C-style cast) (PR #85263)

2024-03-21 Thread via cfe-commits

https://github.com/yronglin edited 
https://github.com/llvm/llvm-project/pull/85263
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [libcxx] [libc++] Implement LWG3528 (`make_from_tuple` can perform (the equivalent of) a C-style cast) (PR #85263)

2024-03-21 Thread via cfe-commits

https://github.com/yronglin updated 
https://github.com/llvm/llvm-project/pull/85263

>From fc8c1a24f09c8860269fbdcfb0b285ffd19f427c Mon Sep 17 00:00:00 2001
From: yronglin 
Date: Fri, 15 Mar 2024 00:48:08 +0800
Subject: [PATCH 01/10] [libc++] Implement LWG3528 (`make_from_tuple` can
 perform (the equivalent of) a C-style cast)

Signed-off-by: yronglin 
---
 libcxx/docs/Status/Cxx23Issues.csv|  2 +-
 libcxx/include/tuple  | 12 ++-
 .../tuple.apply/make_from_tuple.verify.cpp| 74 +++
 3 files changed, 85 insertions(+), 3 deletions(-)
 create mode 100644 
libcxx/test/std/utilities/tuple/tuple.tuple/tuple.apply/make_from_tuple.verify.cpp

diff --git a/libcxx/docs/Status/Cxx23Issues.csv 
b/libcxx/docs/Status/Cxx23Issues.csv
index e00345533b865d..0fd58649b0cf64 100644
--- a/libcxx/docs/Status/Cxx23Issues.csv
+++ b/libcxx/docs/Status/Cxx23Issues.csv
@@ -77,7 +77,7 @@
 `3523 `__,"``iota_view::sentinel`` is not always 
``iota_view``'s sentinel","June 2021","","","|ranges|"
 `3526 `__,"Return types of 
``uses_allocator_construction_args`` unspecified","June 2021","",""
 `3527 `__,"``uses_allocator_construction_args`` 
handles rvalue pairs of rvalue references incorrectly","June 2021","",""
-`3528 `__,"``make_from_tuple`` can perform (the 
equivalent of) a C-style cast","June 2021","",""
+`3528 `__,"``make_from_tuple`` can perform (the 
equivalent of) a C-style cast","June 2021","|Complete|","19.0"
 `3529 `__,"``priority_queue(first, last)`` should 
construct ``c`` with ``(first, last)``","June 2021","|Complete|","14.0"
 `3530 `__,"``BUILTIN-PTR-MEOW`` should not opt the 
type out of syntactic checks","June 2021","",""
 `3532 `__,"``split_view::inner-iterator::operator++(int)`` should depend on ``Base``","June 
2021","","","|ranges|"
diff --git a/libcxx/include/tuple b/libcxx/include/tuple
index 8808db6739fb9b..1ef546c5b2153d 100644
--- a/libcxx/include/tuple
+++ b/libcxx/include/tuple
@@ -1423,8 +1423,16 @@ inline _LIBCPP_HIDE_FROM_ABI constexpr decltype(auto) 
apply(_Fn&& __f, _Tuple&&
 typename 
__make_tuple_indices>>::type{}))
 
 template 
-inline _LIBCPP_HIDE_FROM_ABI constexpr _Tp __make_from_tuple_impl(_Tuple&& 
__t, __tuple_indices<_Idx...>)
-_LIBCPP_NOEXCEPT_RETURN(_Tp(std::get<_Idx>(std::forward<_Tuple>(__t))...))
+inline _LIBCPP_HIDE_FROM_ABI constexpr _Tp __make_from_tuple_impl(_Tuple&& 
__t, __tuple_indices<_Idx...>) 
+  noexcept(noexcept(_Tp(std::get<_Idx>(std::forward<_Tuple>(__t))...)))
+#if _LIBCPP_STD_VER >= 20
+  requires is_constructible_v<_Tp, 
decltype(std::get<_Idx>(std::forward<_Tuple>(__t)))...>
+#endif
+{
+  static_assert(is_constructible_v<_Tp, 
decltype(std::get<_Idx>(std::forward<_Tuple>(__t)))...>, 
+"Cannot constructible target type from the fields of the 
argument tuple.");
+  return _Tp(std::get<_Idx>(std::forward<_Tuple>(__t))...);
+}
 
 template 
 inline _LIBCPP_HIDE_FROM_ABI constexpr _Tp make_from_tuple(_Tuple&& __t)
diff --git 
a/libcxx/test/std/utilities/tuple/tuple.tuple/tuple.apply/make_from_tuple.verify.cpp
 
b/libcxx/test/std/utilities/tuple/tuple.tuple/tuple.apply/make_from_tuple.verify.cpp
new file mode 100644
index 00..9bdca4dc7813cb
--- /dev/null
+++ 
b/libcxx/test/std/utilities/tuple/tuple.tuple/tuple.apply/make_from_tuple.verify.cpp
@@ -0,0 +1,74 @@
+//===--===//
+//
+// 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
+//
+//===--===//
+
+// UNSUPPORTED: c++03, c++11, c++14
+
+// 
+
+// template  constexpr T make_from_tuple(Tuple&&);
+
+#include 
+
+int main() {
+  // clang-format off
+#if _LIBCPP_STD_VER <= 20
+  // reinterpret_cast
+  {
+struct B { int b; } b;
+std::tuple t{&b};
+auto a = std::make_from_tuple(t); // expected-error-re@*:* {{static 
assertion failed {{.*}}Cannot constructible target type from the fields of the 
argument tuple.}}
+(void)a;
+  }
+
+  // const_cast
+  {
+const char *str = "Hello";
+std::tuple t{str};
+auto a = std::make_from_tuple(t); // expected-error-re@*:* 
{{static assertion failed {{.*}}Cannot constructible target type from the 
fields of the argument tuple.}}
+(void)a;
+  }
+
+  // static_cast
+  {
+struct B {};
+struct C : public B {} c;
+B &br = c;
+std::tuple t{br};
+auto a = std::make_from_tuple(t); // expected-error-re@*:* 
{{static assertion failed {{.*}}Cannot constructible target type from the 
fields of the argument tuple.}}
+(void)a;
+  }
+#else
+  // reinterpret_cast
+  {
+   

[clang] [Clang][Sema]: Allow flexible arrays in unions and alone in structs (PR #84428)

2024-03-21 Thread Kees Cook via cfe-commits

kees wrote:

> > because we don't yet support non-zero initialization (as described in 
> > commit 
> > [5955a0f](https://github.com/llvm/llvm-project/commit/5955a0f9375a8c0b134eeb4a8de5155dcce7c94f))
> 
> I'm confused. We support non-zero init, and there are tests for non-zero init 
> in that commit. The commit message mentions dynamic initialization, but 
> that's not non-zero; that's "requires code to run at program startup".

I guess I'm confused about this test:

```
  // Flexible array initialization is currently not supported by constant
  // evaluation. Make sure we emit an error message, for now.
  constexpr A c = {1, 2, 3}; // expected-error {{constexpr variable 'c' must be 
initialized by a constant expression}}
```

Why is 1, 2, 3 not considered a constant expression here? (Am I confusing 
"integer constant expression" for something else?)


https://github.com/llvm/llvm-project/pull/84428
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][analyzer] Model more getline/getdelim pre and postconditions (PR #83027)

2024-03-21 Thread Balázs Kéri via cfe-commits


@@ -376,3 +377,122 @@ void fflush_on_open_failed_stream(void) {
   }
   fclose(F);
 }
+
+void getline_null_file() {
+  char *buffer = NULL;
+  size_t n = 0;
+  getline(&buffer, &n, NULL); // expected-warning {{Stream pointer might be 
NULL}}
+}
+
+void getdelim_null_file() {
+  char *buffer = NULL;
+  size_t n = 0;
+  getdelim(&buffer, &n, '\n', NULL); // expected-warning {{Stream pointer 
might be NULL}}
+}
+
+void getline_no_return_check() {
+  FILE *file = fopen("file.txt", "r");
+  if (file == NULL) {
+return;
+  }
+
+  char *line = NULL;
+  size_t len = 0;
+  getline(&line, &len, file);
+
+  if (line[0] == '\0') {} // expected-warning {{The left operand of '==' is a 
garbage value}}

balazske wrote:

I like better if this check is included only in the failure case:
```
if (getline(&line, &len, file) == -1) {
  if (line[0] == '\0') {} // expected-warning {{The left operand of '==' is a 
garbage value}}
} else {
  if (line[0] == '\0') {} // no warning
}

```

https://github.com/llvm/llvm-project/pull/83027
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][AST][NFC] Add '[[fallthrough]]' to cases fall through (PR #85921)

2024-03-21 Thread via cfe-commits

Sirraide wrote:

E.g:
https://github.com/llvm/llvm-project/blob/50801f1095d33e712c3a51fdeef82569bd09007f/clang/lib/Interpreter/IncrementalParser.cpp#L141-L151

https://github.com/llvm/llvm-project/pull/85921
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [Clang][OpenMP] Port clang codegen code for openmp porject (PR #85795)

2024-03-21 Thread via cfe-commits

https://github.com/TSWorld1314 updated 
https://github.com/llvm/llvm-project/pull/85795

>From c44d8c1c7986fad6370273aca55e2db99d47387a Mon Sep 17 00:00:00 2001
From: "Harrison,Hao" 
Date: Tue, 19 Mar 2024 13:18:07 +
Subject: [PATCH 1/2] [Clang][OpenMP] Port clang codegen code for GPU First
 project

---
 clang/include/clang/Basic/LangOptions.def |   1 +
 clang/lib/CodeGen/CGBuilder.h |   9 +
 clang/lib/CodeGen/CGDecl.cpp  | 218 +-
 clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp  |  45 ++--
 .../include/llvm/Frontend/OpenMP/OMPKinds.def |   9 +
 5 files changed, 156 insertions(+), 126 deletions(-)

diff --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index 8ef6700ecdc78e..64b87ecdc97524 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -260,6 +260,7 @@ LANGOPT(OpenMPTargetDebug , 32, 0, "Enable debugging in the 
OpenMP offloading de
 LANGOPT(OpenMPOptimisticCollapse  , 1, 0, "Use at most 32 bits to represent 
the collapsed loop nest counter.")
 LANGOPT(OpenMPThreadSubscription  , 1, 0, "Assume work-shared loops do not 
have more iterations than participating threads.")
 LANGOPT(OpenMPTeamSubscription  , 1, 0, "Assume distributed loops do not have 
more iterations than participating teams.")
+LANGOPT(OpenMPGlobalizeToGlobalSpace  , 1, 0, "Globalize to global space for 
the globalized variables")
 LANGOPT(OpenMPNoThreadState  , 1, 0, "Assume that no thread in a parallel 
region will modify an ICV.")
 LANGOPT(OpenMPNoNestedParallelism  , 1, 0, "Assume that no thread in a 
parallel region will encounter a parallel region")
 LANGOPT(OpenMPOffloadMandatory  , 1, 0, "Assert that offloading is mandatory 
and do not create a host fallback.")
diff --git a/clang/lib/CodeGen/CGBuilder.h b/clang/lib/CodeGen/CGBuilder.h
index bf5ab171d720d9..fe5beff05134ac 100644
--- a/clang/lib/CodeGen/CGBuilder.h
+++ b/clang/lib/CodeGen/CGBuilder.h
@@ -152,6 +152,15 @@ class CGBuilderTy : public CGBuilderBaseTy {
 Addr.isKnownNonNull());
   }
 
+  /// Cast the element type of the given address to a different type,
+  /// preserving information like the alignment and address space.
+  Address CreateElementBitCast(Address Addr, llvm::Type *Ty,
+   const llvm::Twine &Name = "") {
+auto *PtrTy = Ty->getPointerTo(Addr.getAddressSpace());
+return Address(CreateBitCast(Addr.getPointer(), PtrTy, Name), Ty,
+   Addr.getAlignment(), Addr.isKnownNonNull());
+  }
+  
   using CGBuilderBaseTy::CreatePointerBitCastOrAddrSpaceCast;
   Address CreatePointerBitCastOrAddrSpaceCast(Address Addr, llvm::Type *Ty,
   llvm::Type *ElementTy,
diff --git a/clang/lib/CodeGen/CGDecl.cpp b/clang/lib/CodeGen/CGDecl.cpp
index dc42faf8dbb9fd..691af33dc239d6 100644
--- a/clang/lib/CodeGen/CGDecl.cpp
+++ b/clang/lib/CodeGen/CGDecl.cpp
@@ -2531,48 +2531,7 @@ void CodeGenFunction::EmitParmDecl(const VarDecl &D, 
ParamValue Arg,
 (IPD->getParameterKind() == ImplicitParamKind::ThreadPrivateVar);
   }
 
-  Address DeclPtr = Address::invalid();
-  Address AllocaPtr = Address::invalid();
-  bool DoStore = false;
-  bool IsScalar = hasScalarEvaluationKind(Ty);
-  bool UseIndirectDebugAddress = false;
-
-  // If we already have a pointer to the argument, reuse the input pointer.
-  if (Arg.isIndirect()) {
-DeclPtr = Arg.getIndirectAddress();
-DeclPtr = DeclPtr.withElementType(ConvertTypeForMem(Ty));
-// Indirect argument is in alloca address space, which may be different
-// from the default address space.
-auto AllocaAS = CGM.getASTAllocaAddressSpace();
-auto *V = DeclPtr.getPointer();
-AllocaPtr = DeclPtr;
-
-// For truly ABI indirect arguments -- those that are not `byval` -- store
-// the address of the argument on the stack to preserve debug information.
-ABIArgInfo ArgInfo = CurFnInfo->arguments()[ArgNo - 1].info;
-if (ArgInfo.isIndirect())
-  UseIndirectDebugAddress = !ArgInfo.getIndirectByVal();
-if (UseIndirectDebugAddress) {
-  auto PtrTy = getContext().getPointerType(Ty);
-  AllocaPtr = CreateMemTemp(PtrTy, getContext().getTypeAlignInChars(PtrTy),
-D.getName() + ".indirect_addr");
-  EmitStoreOfScalar(V, AllocaPtr, /* Volatile */ false, PtrTy);
-}
-
-auto SrcLangAS = getLangOpts().OpenCL ? LangAS::opencl_private : AllocaAS;
-auto DestLangAS =
-getLangOpts().OpenCL ? LangAS::opencl_private : LangAS::Default;
-if (SrcLangAS != DestLangAS) {
-  assert(getContext().getTargetAddressSpace(SrcLangAS) ==
- CGM.getDataLayout().getAllocaAddrSpace());
-  auto DestAS = getContext().getTargetAddressSpace(DestLangAS);
-  auto *T = llvm::PointerType::get(getLLVMContext(), DestAS);
-  DeclPtr =
-  DeclPtr.withPointer(getTargetHooks().performAdd

  1   2   3   4   >