[clang] [HLSL][RootSignature] Implement Lexing of DescriptorTables (PR #122981)

2025-02-03 Thread Justin Bogner via cfe-commits


@@ -0,0 +1,173 @@
+#include "clang/Parse/ParseHLSLRootSignature.h"
+
+namespace clang {
+namespace hlsl {
+
+// Lexer Definitions
+
+static bool IsNumberChar(char C) {
+  // TODO(#120472): extend for float support exponents
+  return isdigit(C); // integer support
+}
+
+bool RootSignatureLexer::LexNumber(RootSignatureToken &Result) {
+  // NumericLiteralParser does not handle the sign so we will manually apply it
+  bool Negative = Buffer.front() == '-';
+  bool Signed = Negative || Buffer.front() == '+';
+  if (Signed)
+AdvanceBuffer();
+
+  // Retrieve the possible number
+  StringRef NumSpelling = Buffer.take_while(IsNumberChar);
+
+  // Catch this now as the Literal Parser will accept it as valid
+  if (NumSpelling.empty()) {
+PP.getDiagnostics().Report(Result.TokLoc,
+   diag::err_hlsl_invalid_number_literal);
+return true;
+  }
+
+  // Parse the numeric value and do semantic checks on its specification
+  clang::NumericLiteralParser Literal(NumSpelling, SourceLoc,
+  PP.getSourceManager(), PP.getLangOpts(),
+  PP.getTargetInfo(), PP.getDiagnostics());
+  if (Literal.hadError)
+return true; // Error has already been reported so just return
+
+  if (!Literal.isIntegerLiteral()) {
+// Note: if IsNumberChar allows for hexidecimal we will need to turn this
+// into a diagnostics for potential fixed-point literals
+llvm_unreachable("IsNumberChar will only support digits");
+return true;
+  }
+
+  // Retrieve the number value to store into the token
+  Result.Kind = TokenKind::int_literal;
+
+  llvm::APSInt X = llvm::APSInt(32, !Signed);

bogner wrote:

What happens if we have a value like `+2147483648`? This would fit in an 
unsigned 32-bit int, but not a signed one. However, we're deciding that the 
value is signed if the `+` is present above. Will this error and tell us that 
there's overflow, treat the value as unsigned because of the range, or give us 
a garbage negative number?

If it's one of the first two options, does the one we're implementing match 
DXC's behaviour here?

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


[clang] [HLSL][RootSignature] Implement Lexing of DescriptorTables (PR #122981)

2025-02-03 Thread Justin Bogner via cfe-commits


@@ -0,0 +1,134 @@
+//=== ParseHLSLRootSignatureTest.cpp - Parse Root Signature tests 
-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/DiagnosticOptions.h"
+#include "clang/Basic/FileManager.h"
+#include "clang/Basic/LangOptions.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/SourceManager.h"
+#include "clang/Basic/TargetInfo.h"
+#include "clang/Lex/HeaderSearch.h"
+#include "clang/Lex/HeaderSearchOptions.h"
+#include "clang/Lex/Lexer.h"
+#include "clang/Lex/ModuleLoader.h"
+#include "clang/Lex/Preprocessor.h"
+#include "clang/Lex/PreprocessorOptions.h"
+
+#include "clang/Parse/ParseHLSLRootSignature.h"
+#include "gtest/gtest.h"
+
+using namespace clang;
+
+namespace {
+
+// The test fixture.
+class ParseHLSLRootSignatureTest : public ::testing::Test {
+protected:
+  ParseHLSLRootSignatureTest()
+  : FileMgr(FileMgrOpts), DiagID(new DiagnosticIDs()),
+Diags(DiagID, new DiagnosticOptions, new IgnoringDiagConsumer()),
+SourceMgr(Diags, FileMgr), TargetOpts(new TargetOptions) {
+TargetOpts->Triple = "x86_64-apple-darwin11.1.0";

bogner wrote:

This feels awfully specific for a "don't care" value - it probably deserves a 
comment to the effect that "we need a triple in order to create a target info, 
but which target doesn't matter for our purposes". Also I'd probably simplify 
this to either use a valid dxil triple or just "x86_64" (or "dxil"), just 
because the darwin triple in an HLSL test is likely to confuse people.

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


[clang] [HLSL][RootSignature] Implement Lexing of DescriptorTables (PR #122981)

2025-02-03 Thread Justin Bogner via cfe-commits


@@ -0,0 +1,173 @@
+#include "clang/Parse/ParseHLSLRootSignature.h"
+
+namespace clang {
+namespace hlsl {
+
+// Lexer Definitions
+
+static bool IsNumberChar(char C) {
+  // TODO(#120472): extend for float support exponents
+  return isdigit(C); // integer support
+}
+
+bool RootSignatureLexer::LexNumber(RootSignatureToken &Result) {
+  // NumericLiteralParser does not handle the sign so we will manually apply it
+  bool Negative = Buffer.front() == '-';
+  bool Signed = Negative || Buffer.front() == '+';
+  if (Signed)
+AdvanceBuffer();
+
+  // Retrieve the possible number
+  StringRef NumSpelling = Buffer.take_while(IsNumberChar);
+
+  // Catch this now as the Literal Parser will accept it as valid
+  if (NumSpelling.empty()) {
+PP.getDiagnostics().Report(Result.TokLoc,
+   diag::err_hlsl_invalid_number_literal);
+return true;
+  }
+
+  // Parse the numeric value and do semantic checks on its specification
+  clang::NumericLiteralParser Literal(NumSpelling, SourceLoc,
+  PP.getSourceManager(), PP.getLangOpts(),
+  PP.getTargetInfo(), PP.getDiagnostics());
+  if (Literal.hadError)
+return true; // Error has already been reported so just return
+
+  if (!Literal.isIntegerLiteral()) {
+// Note: if IsNumberChar allows for hexidecimal we will need to turn this
+// into a diagnostics for potential fixed-point literals
+llvm_unreachable("IsNumberChar will only support digits");
+return true;
+  }

bogner wrote:

`if (x) llvm_unreachable(...)` is a bit of a code smell. Better to simply 
`assert(x && ...)`

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


[clang] [llvm] [X86] Extend kCFI with a 3-bit arity indicator (PR #121070)

2025-02-03 Thread Sami Tolvanen via cfe-commits

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

Thank you for adding the command line flag. I agree that this should be 
sufficient to address compatibility concerns.

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


[clang] [Clang] Remove unnecessary Decl transform & profiles for SizeOfPackExpr (PR #124533)

2025-02-03 Thread Aaron Ballman via cfe-commits

AaronBallman wrote:

Thank you for the explanation, that makes more sense to me.

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


[clang] [Clang] Make `-Xarch_` handling generic for all toolchains (PR #125421)

2025-02-03 Thread Artem Belevich via cfe-commits


@@ -0,0 +1,31 @@
+// RUN: %clang -x cuda %s -Xarch_nvptx64 -O3 -S -nogpulib -nogpuinc -### 2>&1 
| FileCheck -check-prefix=O3ONCE %s
+// RUN: %clang -x hip %s -Xarch_amdgcn -O3 -S -nogpulib -nogpuinc -### 2>&1 | 
FileCheck -check-prefix=O3ONCE %s

Artem-B wrote:

> We have existing tests for those

We have a few scattered across hip-options.hip and openmp-offload-gpu.c and it 
would make sense to consolidate them here, now that we have the tests dedicated 
specifically to Xarch processing. 

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


[clang] [Clang][counted_by] Don't treat a __bdos argument as an array if it isn't (PR #125298)

2025-02-03 Thread Eli Friedman via cfe-commits

efriedma-quic wrote:

Sorry I didn't get around to re-reviewing #122198 earlier... it looks like this 
is the with lvalue-to-rvalue conversions I mentioned on the review.  You do not 
want to look through lvalue-to-rvalue conversions; the StructFieldAccess 
visitor should bail out if it sees one.

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


[clang] [llvm] [aarch64][x86][win] Add compiler support for MSVC's /funcoverride flag (Windows kernel loader replaceable functions) (PR #125320)

2025-02-03 Thread Daniel Paoliello via cfe-commits

https://github.com/dpaoliello updated 
https://github.com/llvm/llvm-project/pull/125320

>From f6b91ae8062ce1b8d1b6bb39b631a6971c06612b Mon Sep 17 00:00:00 2001
From: "Daniel Paoliello (HE/HIM)" 
Date: Fri, 31 Jan 2025 16:47:23 -0800
Subject: [PATCH] [aarch64][x86][win] Add support for MSVC's /funcoverride flag
 (Windows kernel loader replaceable functions)

---
 clang/include/clang/Basic/CodeGenOptions.h|  13 +++
 clang/include/clang/Driver/Options.td |   7 ++
 clang/lib/CodeGen/CGCall.cpp  |   4 +
 clang/lib/Driver/ToolChains/Clang.cpp |   6 +
 .../CodeGen/loader-replaceable-function.c |  14 +++
 clang/test/Driver/cl-options.c|   4 +
 llvm/include/llvm/CodeGen/AsmPrinter.h|  11 ++
 llvm/include/llvm/IR/Attributes.td|   1 +
 llvm/include/llvm/IR/Mangler.h|   2 +
 llvm/lib/Analysis/InlineCost.cpp  |   4 +
 llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp| 107 ++
 .../AArch64/AArch64Arm64ECCallLowering.cpp|   5 +-
 llvm/lib/Target/AArch64/AArch64AsmPrinter.cpp |  28 +
 llvm/lib/Target/X86/X86AsmPrinter.cpp |  37 +-
 .../win-loader-replaceable-function.ll|  40 +++
 .../X86/win-loader-replaceable-function.ll|  40 +++
 llvm/test/Transforms/Inline/attributes.ll |  12 ++
 17 files changed, 272 insertions(+), 63 deletions(-)
 create mode 100644 clang/test/CodeGen/loader-replaceable-function.c
 create mode 100644 llvm/test/CodeGen/AArch64/win-loader-replaceable-function.ll
 create mode 100644 llvm/test/CodeGen/X86/win-loader-replaceable-function.ll

diff --git a/clang/include/clang/Basic/CodeGenOptions.h 
b/clang/include/clang/Basic/CodeGenOptions.h
index c531c656f42b7e..579f50043369cb 100644
--- a/clang/include/clang/Basic/CodeGenOptions.h
+++ b/clang/include/clang/Basic/CodeGenOptions.h
@@ -489,6 +489,9 @@ class CodeGenOptions : public CodeGenOptionsBase {
   /// The name of a file to use with \c .secure_log_unique directives.
   std::string AsSecureLogFile;
 
+  /// A list of functions that are replacable by the loader.
+  std::vector LoaderReplaceableFunctionNames;
+
 public:
   // Define accessors/mutators for code generation options of enumeration type.
 #define CODEGENOPT(Name, Bits, Default)
@@ -561,6 +564,16 @@ class CodeGenOptions : public CodeGenOptionsBase {
   /// Reset all of the options that are not considered when building a
   /// module.
   void resetNonModularOptions(StringRef ModuleFormat);
+
+  // Is the given function name one of the functions that can be replaced by 
the
+  // loader?
+  bool isLoaderReplaceableFunctionName(StringRef FuncName) const {
+return std::any_of(LoaderReplaceableFunctionNames.begin(),
+   LoaderReplaceableFunctionNames.end(),
+   [&](const std::string &ReplaceableName) {
+ return FuncName == ReplaceableName;
+   });
+  }
 };
 
 }  // end namespace clang
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index d8123cc39fdc95..8dcf0558519185 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -7592,6 +7592,9 @@ def import_call_optimization : Flag<["-"], 
"import-call-optimization">,
  "by the Windows kernel to enable import call optimization">,
 MarshallingInfoFlag>;
 
+def replaceable_function: Joined<["-"], "loader-replaceable-function=">,
+  MarshallingInfoStringVector>;
+
 } // let Visibility = [CC1Option]
 
 
//===--===//
@@ -8838,6 +8841,10 @@ def _SLASH_Gregcall : CLFlag<"Gregcall">,
 def _SLASH_Gregcall4 : CLFlag<"Gregcall4">,
   HelpText<"Set __regcall4 as a default calling convention to respect 
__regcall ABI v.4">;
 
+def _SLASH_funcoverride : CLCompileJoined<"funcoverride:">,
+  HelpText<"Mark  as being replaceable by the Windows kernel 
loader">,
+  MetaVarName<"">;
+
 // GNU Driver aliases
 
 def : Separate<["-"], "Xmicrosoft-visualc-tools-root">, 
Alias<_SLASH_vctoolsdir>;
diff --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index 2dce86410db857..f8cc8108352852 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -2574,6 +2574,10 @@ void CodeGenModule::ConstructAttributeList(StringRef 
Name,
 GetCPUAndFeaturesAttributes(CalleeInfo.getCalleeDecl(), FuncAttrs);
   }
 
+  // Mark functions that are replaceable by the loader.
+  if (CodeGenOpts.isLoaderReplaceableFunctionName(Name))
+FuncAttrs.addAttribute("loader-replaceable");
+
   // Collect attributes from arguments and return values.
   ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
 
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 9b5132c5625faa..466bb42e557d41 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -8504,6 +8504,12 @

[clang] CodeGen: support static linking for libclosure (PR #125384)

2025-02-03 Thread Saleem Abdulrasool via cfe-commits

https://github.com/compnerd updated 
https://github.com/llvm/llvm-project/pull/125384

>From 33f361fda5b27964037c061d7944c01d3891d914 Mon Sep 17 00:00:00 2001
From: Saleem Abdulrasool 
Date: Sat, 1 Feb 2025 15:04:04 -0800
Subject: [PATCH] CodeGen: support static linking for libclosure

When building on Windows, dealing with the BlocksRuntime is slightly
more complicated. As we are not guaranteed a formward declaration for
the blocks runtime ABI symbols, we may generate the declarations for
them. In order to properly link against the well-known types, we always
annotated them as `__declspec(dllimport)`. This would require the
dynamic linking of the blocks runtime under all conditions. However,
this is the only the only possible way to us the library. We may be
building a fully sealed (static) executable. In such a case, the well
known symbols should not be marked as `dllimport` as they are assumed to
be statically available with the static linking to the BlocksRuntime.

Introduce a new driver/cc1 option `-static-libclosure` which mirrors the
myriad of similar options (`-static-libgcc`, `-static-libstdc++`,
-static-libsan`, etc).
---
 clang/include/clang/Basic/CodeGenOptions.def | 4 
 clang/include/clang/Driver/Options.td| 2 ++
 clang/lib/CodeGen/CGBlocks.cpp   | 4 ++--
 clang/lib/Driver/ToolChains/Clang.cpp| 2 ++
 clang/lib/Frontend/CompilerInvocation.cpp| 5 +
 clang/test/CodeGen/blocks-windows.c  | 7 +++
 6 files changed, 22 insertions(+), 2 deletions(-)

diff --git a/clang/include/clang/Basic/CodeGenOptions.def 
b/clang/include/clang/Basic/CodeGenOptions.def
index 386652d2efa9e1..9ca1fe6566d6ad 100644
--- a/clang/include/clang/Basic/CodeGenOptions.def
+++ b/clang/include/clang/Basic/CodeGenOptions.def
@@ -469,6 +469,10 @@ CODEGENOPT(CtorDtorReturnThis, 1, 0)
 /// by the Windows kernel to enable import call optimization.
 CODEGENOPT(ImportCallOptimization, 1, 0)
 
+/// Controls whether we generate code for static linking of libclosure
+/// (BlocksRuntime) on Windows.
+CODEGENOPT(StaticClosure, 1, 0)
+
 /// FIXME: Make DebugOptions its own top-level .def file.
 #include "DebugOptions.def"
 
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 0ab923fcdd5838..7f2b8b74bce79c 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -5825,6 +5825,8 @@ def start_no_unused_arguments : Flag<["--"], 
"start-no-unused-arguments">,
   HelpText<"Don't emit warnings about unused arguments for the following 
arguments">;
 def static_libgcc : Flag<["-"], "static-libgcc">;
 def static_libstdcxx : Flag<["-"], "static-libstdc++">;
+def static_libclosure : Flag<["-"], "static-libclosure">,
+Visibility<[ClangOption, CC1Option]>;
 def static : Flag<["-", "--"], "static">, Group,
   Visibility<[ClangOption, FlangOption]>,
   Flags<[NoArgumentUnused]>;
diff --git a/clang/lib/CodeGen/CGBlocks.cpp b/clang/lib/CodeGen/CGBlocks.cpp
index a7584a95c8ca7b..aaba354c08547d 100644
--- a/clang/lib/CodeGen/CGBlocks.cpp
+++ b/clang/lib/CodeGen/CGBlocks.cpp
@@ -2800,7 +2800,8 @@ static void configureBlocksRuntimeObject(CodeGenModule 
&CGM,
  llvm::Constant *C) {
   auto *GV = cast(C->stripPointerCasts());
 
-  if (CGM.getTarget().getTriple().isOSBinFormatCOFF()) {
+  if (!CGM.getCodeGenOpts().StaticClosure &&
+  CGM.getTarget().getTriple().isOSBinFormatCOFF()) {
 const IdentifierInfo &II = CGM.getContext().Idents.get(C->getName());
 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
@@ -2815,7 +2816,6 @@ static void configureBlocksRuntimeObject(CodeGenModule 
&CGM,
   (ND = dyn_cast(Result)))
 break;
 
-// TODO: support static blocks runtime
 if (GV->isDeclaration() && (!ND || !ND->hasAttr())) {
   GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
   GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 9b5132c5625faa..ad73ac4dd8f73d 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -5580,6 +5580,8 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
   if (Args.hasArg(options::OPT_static))
 CmdArgs.push_back("-static-define");
 
+  Args.AddLastArg(CmdArgs, options::OPT_static_libclosure);
+
   if (Args.hasArg(options::OPT_municode))
 CmdArgs.push_back("-DUNICODE");
 
diff --git a/clang/lib/Frontend/CompilerInvocation.cpp 
b/clang/lib/Frontend/CompilerInvocation.cpp
index 11fd6ab7f52a79..de31c3c40fecf0 100644
--- a/clang/lib/Frontend/CompilerInvocation.cpp
+++ b/clang/lib/Frontend/CompilerInvocation.cpp
@@ -1843,6 +1843,9 @@ void CompilerInvocationBase::GenerateCodeGenArgs(const 
CodeGenOptions &Opts,
 GenerateArg(Consumer, OPT_fno_finite_loops);

[clang] [HLSL] Make memory representation of boolean vectors in HLSL, vectors of i32. Add support for boolean swizzling. (PR #123977)

2025-02-03 Thread Sarah Spall via cfe-commits


@@ -2016,8 +2016,9 @@ TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const 
{
   case Type::Vector: {
 const auto *VT = cast(T);
 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
-Width = VT->isExtVectorBoolType() ? VT->getNumElements()
-  : EltInfo.Width * VT->getNumElements();
+Width = (VT->isExtVectorBoolType() && !getLangOpts().HLSL)

spall wrote:

I will investigate doing this because I also don't like all the special case 
checking for HLSL. 

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


[clang] [Hexagon][Docs] document the change in the default target (PR #125584)

2025-02-03 Thread Ikhlas Ajbar via cfe-commits

https://github.com/iajbar created 
https://github.com/llvm/llvm-project/pull/125584

None

>From 59b76081f1c15c38f2b58ffce062dadce12d5811 Mon Sep 17 00:00:00 2001
From: Ikhlas Ajbar 
Date: Mon, 3 Feb 2025 12:47:22 -0800
Subject: [PATCH] [Hexagon][Docs] document the change in the default target

---
 clang/docs/ReleaseNotes.rst | 5 +
 1 file changed, 5 insertions(+)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 4266d6c523ab97..33a37bdf3f328a 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -161,6 +161,11 @@ AMDGPU Support
 NVPTX Support
 ^^
 
+Hexagon Support
+^^^
+
+-  The default compilation target has been changed from V60 to V68.
+
 X86 Support
 ^^^
 

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


[clang] [Hexagon][Docs] document the change in the default target (PR #125584)

2025-02-03 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Ikhlas Ajbar (iajbar)


Changes



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


1 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+5) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 4266d6c523ab97..33a37bdf3f328a 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -161,6 +161,11 @@ AMDGPU Support
 NVPTX Support
 ^^
 
+Hexagon Support
+^^^
+
+-  The default compilation target has been changed from V60 to V68.
+
 X86 Support
 ^^^
 

``




https://github.com/llvm/llvm-project/pull/125584
___
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 performance-redundant-lookup check (PR #125420)

2025-02-03 Thread Balazs Benics via cfe-commits

steakhal wrote:

> Performance looks good. Everything under 5% is acceptable.
> 
> The top three entries should probably get tickets so they get looked into. 
> The amount seems too much for what it actually provides.

Yea, my idea was to give a bit of context of how it compares to the resr of the 
checks. Good to know its acceptable! Thanks.

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


[clang] [clang] Remove an incorrect assertion in ConstantFoldAttrs (PR #105789)

2025-02-03 Thread Aaron Ballman via cfe-commits

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

LGTM aside from the missing release note.

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


[clang] [Clang] Make `-Xarch_` handling generic for all toolchains (PR #125421)

2025-02-03 Thread Artem Belevich via cfe-commits


@@ -0,0 +1,31 @@
+// RUN: %clang -x cuda %s -Xarch_nvptx64 -O3 -S -nogpulib -nogpuinc -### 2>&1 
| FileCheck -check-prefix=O3ONCE %s
+// RUN: %clang -x hip %s -Xarch_amdgcn -O3 -S -nogpulib -nogpuinc -### 2>&1 | 
FileCheck -check-prefix=O3ONCE %s

Artem-B wrote:

More test cases are needed to handle combinations of `-Xarch_host/device` and 
`-Xarch-`. 



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


[clang] [Clang] Make `-Xarch_` handling generic for all toolchains (PR #125421)

2025-02-03 Thread Artem Belevich via cfe-commits


@@ -1697,19 +1721,17 @@ llvm::opt::DerivedArgList 
*ToolChain::TranslateXarchArgs(
 } else if (A->getOption().matches(options::OPT_Xarch_host)) {
   NeedTrans = !IsDevice;
   Skip = IsDevice;
-} else if (A->getOption().matches(options::OPT_Xarch__) && IsDevice) {
-  // Do not translate -Xarch_ options for non CUDA/HIP toolchain since
-  // they may need special translation.
-  // Skip this argument unless the architecture matches BoundArch
-  if (BoundArch.empty() || A->getValue(0) != BoundArch)
-Skip = true;
-  else
-NeedTrans = true;
+} else if (A->getOption().matches(options::OPT_Xarch__)) {

Artem-B wrote:

Use of `-Xarch_host/device` should not block `-Xarch_`.


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


[clang] [Clang] Make `-Xarch_` handling generic for all toolchains (PR #125421)

2025-02-03 Thread Artem Belevich via cfe-commits

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


[clang] [Clang] Make `-Xarch_` handling generic for all toolchains (PR #125421)

2025-02-03 Thread Artem Belevich via cfe-commits

https://github.com/Artem-B commented:

LGTM overall, with a few nits. 

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


[clang] [Clang] Make `-Xarch_` handling generic for all toolchains (PR #125421)

2025-02-03 Thread Joseph Huber via cfe-commits


@@ -0,0 +1,31 @@
+// RUN: %clang -x cuda %s -Xarch_nvptx64 -O3 -S -nogpulib -nogpuinc -### 2>&1 
| FileCheck -check-prefix=O3ONCE %s
+// RUN: %clang -x hip %s -Xarch_amdgcn -O3 -S -nogpulib -nogpuinc -### 2>&1 | 
FileCheck -check-prefix=O3ONCE %s

jhuber6 wrote:

We have tests for that in `openmp-offload-gpu.c` and `hip-options.hip` so I 
figured it wasn't necessary, but can add them if it will get the PR moving.

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


[clang] [Clang] Make `-Xarch_` handling generic for all toolchains (PR #125421)

2025-02-03 Thread Joseph Huber via cfe-commits


@@ -1115,14 +1117,13 @@ def fno_convergent_functions : Flag<["-"], 
"fno-convergent-functions">,
 
 // Common offloading options
 let Group = offload_Group in {
-def offload_arch_EQ : Joined<["--"], "offload-arch=">, Flags<[NoXarchOption]>,

jhuber6 wrote:

Overloaded term that means different things in different places. The `arch` in 
the LLVM triple refers to `amdgcn` in `amdgcn-amd-amdhsa` since that's the 
actual CPU microarchitecture. The `arch` in `-march` refers to the specific 
machine name for the processor that's being targeted. `-Xarch_gfx908` is valid 
because the `-Xarch_` option in non-offloading use also minds to `-march=` 
arguments AFAICT.

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


[clang] [compiler-rt] Rtsan fbsd (PR #125389)

2025-02-03 Thread Brooks Davis via cfe-commits

brooksdavis wrote:

rtsan seems like something we'd want on FreeBSD. If this is all that's required 
it seems like a no-brainer.

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


[clang] [Clang] Make `-Xarch_` handling generic for all toolchains (PR #125421)

2025-02-03 Thread Joseph Huber via cfe-commits


@@ -0,0 +1,31 @@
+// RUN: %clang -x cuda %s -Xarch_nvptx64 -O3 -S -nogpulib -nogpuinc -### 2>&1 
| FileCheck -check-prefix=O3ONCE %s
+// RUN: %clang -x hip %s -Xarch_amdgcn -O3 -S -nogpulib -nogpuinc -### 2>&1 | 
FileCheck -check-prefix=O3ONCE %s

jhuber6 wrote:

I added tests to make sure that `-Xarch-device` is equivalent to 
`-Xarch_nvptx64` and that `-Xarch_host` doesn't interfere with `-Xarch_nvptx64`.

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


[clang] [Clang] Introduce '--offload-targets=' to generically target toolchains (PR #125556)

2025-02-03 Thread Joseph Huber via cfe-commits

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


[clang] [Clang][counted_by] Don't treat a __bdos argument as an array if it isn't (PR #125298)

2025-02-03 Thread Bill Wendling via cfe-commits

bwendling wrote:

@efriedma-quic Thanks, I'll send a patch.

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


[clang] [Clang] Make `-Xarch_` handling generic for all toolchains (PR #125421)

2025-02-03 Thread Shilei Tian via cfe-commits


@@ -1115,14 +1117,13 @@ def fno_convergent_functions : Flag<["-"], 
"fno-convergent-functions">,
 
 // Common offloading options
 let Group = offload_Group in {
-def offload_arch_EQ : Joined<["--"], "offload-arch=">, Flags<[NoXarchOption]>,

shiltian wrote:

then @yxsamliu made a very good point of avoiding use cases like that. that 
should be checked and errored out.

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


[clang] [Win/X86] Make _m_prefetch[w] builtins to avoid winnt.h conflicts (PR #115099)

2025-02-03 Thread Reid Kleckner via cfe-commits

https://github.com/rnk updated https://github.com/llvm/llvm-project/pull/115099

>From e5f485ad8000c296229794346fdd627b90e504d2 Mon Sep 17 00:00:00 2001
From: Reid Kleckner 
Date: Tue, 5 Nov 2024 16:05:53 -0800
Subject: [PATCH 1/7] [Win/X86] Make _m_prefetch[w] builtins to avoid winnt.h
 conflicts

---
 clang/include/clang/Basic/BuiltinsX86.td |  7 ++-
 clang/lib/CodeGen/CGBuiltin.cpp  | 10 ++
 clang/lib/Headers/prfchwintrin.h | 23 ++-
 3 files changed, 26 insertions(+), 14 deletions(-)

diff --git a/clang/include/clang/Basic/BuiltinsX86.td 
b/clang/include/clang/Basic/BuiltinsX86.td
index 572ac7235be02f..00bee2051caa85 100644
--- a/clang/include/clang/Basic/BuiltinsX86.td
+++ b/clang/include/clang/Basic/BuiltinsX86.td
@@ -146,10 +146,15 @@ let Attributes = [Const, NoThrow, 
RequiredVectorWidth<256>], Features = "avx" in
 // current formulation is based on what was easiest to recognize from the
 // pre-TableGen version.
 
-let Features = "mmx", Attributes = [NoThrow, Const] in {
+let Features = "mmx", Header = "immintrin.h", Attributes = [NoThrow, Const] in 
{
   def _mm_prefetch : X86NoPrefixBuiltin<"void(char const *, int)">;
 }
 
+let Features = "mmx", Header = "intrin.h", Attributes = [NoThrow, Const] in {
+  def _m_prefetch : X86NoPrefixBuiltin<"void(void *)">;
+  def _m_prefetchw : X86NoPrefixBuiltin<"void(const void *)">;
+}
+
 let Features = "sse", Attributes = [NoThrow] in {
   def ldmxcsr : X86Builtin<"void(unsigned int)">;
 }
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 7ec9d59bfed5cf..0224238d976193 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -15254,6 +15254,16 @@ Value *CodeGenFunction::EmitX86BuiltinExpr(unsigned 
BuiltinID,
 Function *F = CGM.getIntrinsic(Intrinsic::prefetch, Address->getType());
 return Builder.CreateCall(F, {Address, RW, Locality, Data});
   }
+  case X86::BI_m_prefetch:
+  case X86::BI_m_prefetchw: {
+Value *Address = Ops[0];
+// The 'w' suffix implies write.
+Value *RW = ConstantInt::get(Int32Ty, BuiltinID == X86::BI_m_prefetchw ? 1 
: 0);
+Value *Locality = ConstantInt::get(Int32Ty, 0x3);
+Value *Data = ConstantInt::get(Int32Ty, 1);
+Function *F = CGM.getIntrinsic(Intrinsic::prefetch, Address->getType());
+return Builder.CreateCall(F, {Address, RW, Locality, Data});
+  }
   case X86::BI_mm_clflush: {
 return Builder.CreateCall(CGM.getIntrinsic(Intrinsic::x86_sse2_clflush),
   Ops[0]);
diff --git a/clang/lib/Headers/prfchwintrin.h b/clang/lib/Headers/prfchwintrin.h
index eaea5f3cf8febf..8ec55d7073716f 100644
--- a/clang/lib/Headers/prfchwintrin.h
+++ b/clang/lib/Headers/prfchwintrin.h
@@ -14,6 +14,10 @@
 #ifndef __PRFCHWINTRIN_H
 #define __PRFCHWINTRIN_H
 
+#if defined(__cplusplus)
+extern "C" {
+#endif
+
 /// Loads a memory sequence containing the specified memory address into
 ///all data cache levels.
 ///
@@ -26,11 +30,7 @@
 ///
 /// \param __P
 ///A pointer specifying the memory address to be prefetched.
-static __inline__ void __attribute__((__always_inline__, __nodebug__))
-_m_prefetch(void *__P)
-{
-  __builtin_prefetch (__P, 0, 3 /* _MM_HINT_T0 */);
-}
+void _m_prefetch(void *__P);
 
 /// Loads a memory sequence containing the specified memory address into
 ///the L1 data cache and sets the cache-coherency state to modified.
@@ -48,13 +48,10 @@ _m_prefetch(void *__P)
 ///
 /// \param __P
 ///A pointer specifying the memory address to be prefetched.
-static __inline__ void __attribute__((__always_inline__, __nodebug__))
-_m_prefetchw(volatile const void *__P)
-{
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wcast-qual"
-  __builtin_prefetch ((const void*)__P, 1, 3 /* _MM_HINT_T0 */);
-#pragma clang diagnostic pop
-}
+void _m_prefetchw(volatile const void *__P);
+
+#if defined(__cplusplus)
+} // extern "C"
+#endif
 
 #endif /* __PRFCHWINTRIN_H */

>From 80e6138ccc1e970d12c86be937562a2ac96e8685 Mon Sep 17 00:00:00 2001
From: Reid Kleckner 
Date: Wed, 6 Nov 2024 00:45:51 +
Subject: [PATCH 2/7] format

---
 clang/lib/CodeGen/CGBuiltin.cpp | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 0224238d976193..ce3b9f1d99c947 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -15258,7 +15258,8 @@ Value *CodeGenFunction::EmitX86BuiltinExpr(unsigned 
BuiltinID,
   case X86::BI_m_prefetchw: {
 Value *Address = Ops[0];
 // The 'w' suffix implies write.
-Value *RW = ConstantInt::get(Int32Ty, BuiltinID == X86::BI_m_prefetchw ? 1 
: 0);
+Value *RW =
+ConstantInt::get(Int32Ty, BuiltinID == X86::BI_m_prefetchw ? 1 : 0);
 Value *Locality = ConstantInt::get(Int32Ty, 0x3);
 Value *Data = ConstantInt::get(Int32Ty, 1);
 Function *F = CGM.getIntrinsic(Intrinsic::prefetch, Address->getType());


[clang] Reland: [clang] Track function template instantiation from definition (PR #125266)

2025-02-03 Thread Matheus Izvekov via cfe-commits


@@ -2298,6 +2298,13 @@ class FunctionDecl : public DeclaratorDecl,
 FunctionDeclBits.IsLateTemplateParsed = ILT;
   }
 
+  bool isInstantiatedFromMemberTemplate() const {
+return FunctionDeclBits.IsInstantiatedFromMemberTemplate;
+  }
+  void setInstantiatedFromMemberTemplate(bool Val = true) {
+FunctionDeclBits.IsInstantiatedFromMemberTemplate = Val;
+  }
+

mizvekov wrote:

Thanks, I have added a further comment explaining more things.

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


[clang] [Sema] Migrate away from PointerUnion::dyn_cast (NFC) (PR #125630)

2025-02-03 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Kazu Hirata (kazutakahirata)


Changes

Note that PointerUnion::dyn_cast has been soft deprecated in
PointerUnion.h:

  // FIXME: Replace the uses of is(), get() and dyn_cast() with
  //isa, cast and the llvm::dyn_cast

Literal migration would result in dyn_cast_if_present (see the
definition of PointerUnion::dyn_cast), but this patch uses dyn_cast
because we expect *Found to be nonnull.  Note that if *Found were
null, cast(TransformedDecl) would trigger an assertion error.


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


1 Files Affected:

- (modified) clang/lib/Sema/SemaTemplateInstantiate.cpp (+1-1) 


``diff
diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index dc3bfa97eff399..44bca0d667f764 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -2438,7 +2438,7 @@ 
TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
   assert(Found && "no instantiation for parameter pack");
 
   Decl *TransformedDecl;
-  if (DeclArgumentPack *Pack = Found->dyn_cast()) {
+  if (DeclArgumentPack *Pack = dyn_cast(*Found)) {
 // If this is a reference to a function parameter pack which we can
 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
 if (getSema().ArgumentPackSubstitutionIndex == -1) {

``




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


[clang] [Sema] Migrate away from PointerUnion::dyn_cast (NFC) (PR #125630)

2025-02-03 Thread Kazu Hirata via cfe-commits

https://github.com/kazutakahirata created 
https://github.com/llvm/llvm-project/pull/125630

Note that PointerUnion::dyn_cast has been soft deprecated in
PointerUnion.h:

  // FIXME: Replace the uses of is(), get() and dyn_cast() with
  //isa, cast and the llvm::dyn_cast

Literal migration would result in dyn_cast_if_present (see the
definition of PointerUnion::dyn_cast), but this patch uses dyn_cast
because we expect *Found to be nonnull.  Note that if *Found were
null, cast(TransformedDecl) would trigger an assertion error.


>From 39b5e3693ebe165c4ae2f24bd532bc66e282828b Mon Sep 17 00:00:00 2001
From: Kazu Hirata 
Date: Mon, 3 Feb 2025 16:29:00 -0800
Subject: [PATCH] [Sema] Migrate away from PointerUnion::dyn_cast (NFC)

Note that PointerUnion::dyn_cast has been soft deprecated in
PointerUnion.h:

  // FIXME: Replace the uses of is(), get() and dyn_cast() with
  //isa, cast and the llvm::dyn_cast

Literal migration would result in dyn_cast_if_present (see the
definition of PointerUnion::dyn_cast), but this patch uses dyn_cast
because we expect *Found to be nonnull.  Note that if *Found were
null, cast(TransformedDecl) would trigger an assertion error.
---
 clang/lib/Sema/SemaTemplateInstantiate.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index dc3bfa97eff399..44bca0d667f764 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -2438,7 +2438,7 @@ 
TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
   assert(Found && "no instantiation for parameter pack");
 
   Decl *TransformedDecl;
-  if (DeclArgumentPack *Pack = Found->dyn_cast()) {
+  if (DeclArgumentPack *Pack = dyn_cast(*Found)) {
 // If this is a reference to a function parameter pack which we can
 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
 if (getSema().ArgumentPackSubstitutionIndex == -1) {

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


[clang] [libclang] Migrate away from PointerUnion::dyn_cast (NFC) (PR #125631)

2025-02-03 Thread Kazu Hirata via cfe-commits

https://github.com/kazutakahirata created 
https://github.com/llvm/llvm-project/pull/125631

Note that PointerUnion::dyn_cast has been soft deprecated in
PointerUnion.h:

  // FIXME: Replace the uses of is(), get() and dyn_cast() with
  //isa, cast and the llvm::dyn_cast

Literal migration would result in dyn_cast_if_present (see the
definition of PointerUnion::dyn_cast), but this patch uses dyn_cast
because we expect Storage to be nonnull.  Note that if Storage were
null, dereferencing Ovl would trigger a segfault.


>From d1f18339591a14da97a6300959f5b0284c19acfe Mon Sep 17 00:00:00 2001
From: Kazu Hirata 
Date: Mon, 3 Feb 2025 17:37:21 -0800
Subject: [PATCH] [libclang] Migrate away from PointerUnion::dyn_cast (NFC)

Note that PointerUnion::dyn_cast has been soft deprecated in
PointerUnion.h:

  // FIXME: Replace the uses of is(), get() and dyn_cast() with
  //isa, cast and the llvm::dyn_cast

Literal migration would result in dyn_cast_if_present (see the
definition of PointerUnion::dyn_cast), but this patch uses dyn_cast
because we expect Storage to be nonnull.  Note that if Storage were
null, dereferencing Ovl would trigger a segfault.
---
 clang/tools/libclang/CIndex.cpp | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/clang/tools/libclang/CIndex.cpp b/clang/tools/libclang/CIndex.cpp
index 697cc4776839dc..6f0e9f2a9688c6 100644
--- a/clang/tools/libclang/CIndex.cpp
+++ b/clang/tools/libclang/CIndex.cpp
@@ -5370,12 +5370,12 @@ CXString clang_getCursorSpelling(CXCursor C) {
 
 case CXCursor_OverloadedDeclRef: {
   OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
-  if (const Decl *D = Storage.dyn_cast()) {
+  if (const Decl *D = dyn_cast(Storage)) {
 if (const NamedDecl *ND = dyn_cast(D))
   return cxstring::createDup(ND->getNameAsString());
 return cxstring::createEmpty();
   }
-  if (const OverloadExpr *E = Storage.dyn_cast())
+  if (const OverloadExpr *E = dyn_cast(Storage))
 return cxstring::createDup(E->getName().getAsString());
   OverloadedTemplateStorage *Ovl =
   cast(Storage);

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


[clang] [libclang] Migrate away from PointerUnion::dyn_cast (NFC) (PR #125631)

2025-02-03 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Kazu Hirata (kazutakahirata)


Changes

Note that PointerUnion::dyn_cast has been soft deprecated in
PointerUnion.h:

  // FIXME: Replace the uses of is(), get() and dyn_cast() with
  //isa, cast and the llvm::dyn_cast

Literal migration would result in dyn_cast_if_present (see the
definition of PointerUnion::dyn_cast), but this patch uses dyn_cast
because we expect Storage to be nonnull.  Note that if Storage were
null, dereferencing Ovl would trigger a segfault.


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


1 Files Affected:

- (modified) clang/tools/libclang/CIndex.cpp (+2-2) 


``diff
diff --git a/clang/tools/libclang/CIndex.cpp b/clang/tools/libclang/CIndex.cpp
index 697cc4776839dc..6f0e9f2a9688c6 100644
--- a/clang/tools/libclang/CIndex.cpp
+++ b/clang/tools/libclang/CIndex.cpp
@@ -5370,12 +5370,12 @@ CXString clang_getCursorSpelling(CXCursor C) {
 
 case CXCursor_OverloadedDeclRef: {
   OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
-  if (const Decl *D = Storage.dyn_cast()) {
+  if (const Decl *D = dyn_cast(Storage)) {
 if (const NamedDecl *ND = dyn_cast(D))
   return cxstring::createDup(ND->getNameAsString());
 return cxstring::createEmpty();
   }
-  if (const OverloadExpr *E = Storage.dyn_cast())
+  if (const OverloadExpr *E = dyn_cast(Storage))
 return cxstring::createDup(E->getName().getAsString());
   OverloadedTemplateStorage *Ovl =
   cast(Storage);

``




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


[clang] Remove some false negatives in StackAddrEscapeChecker (PR #125638)

2025-02-03 Thread Michael Flanders via cfe-commits

https://github.com/Flandini created 
https://github.com/llvm/llvm-project/pull/125638

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

Previously, when the StackAddrEscapeChecker checked return values, it did not 
scan into the structure of the return SVal. Now it does, and we can catch some 
more false negatives that were already mocked out in the tests in addition to 
those mentioned in https://github.com/llvm/llvm-project/issues/123459.

The warning message at the moment for these newly caught leaks is not great. I 
think they would be better if they had a better trace of why and how the region 
leaks. If y'all are happy with these changes, I would try to improve these 
warnings and work on normalizing this SVal checking on the `checkEndFunction` 
side of the checker also.

Two of the stack address leak test cases now have two warnings, one warning 
from return expression checking and another from` checkEndFunction` 
`iterBindings` checking. For these two cases, I prefer the warnings from the 
return expression checking, but I couldn't figure out a way to drop the 
`checkEndFunction` without breaking other `checkEndFunction` warnings that we 
do want. Thoughts here?

Tagging @steakhal @NagyDonat @Xazax-hun @haoNoQ for review.

>From 0674909f03703a70c3e259acd0590f50cea4615f Mon Sep 17 00:00:00 2001
From: Michael Flanders 
Date: Mon, 27 Jan 2025 11:35:03 -0600
Subject: [PATCH 01/20] wip

---
 .../Checkers/StackAddrEscapeChecker.cpp   | 45 ++-
 1 file changed, 44 insertions(+), 1 deletion(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
index f4de3b500499c4..59b47371df0d29 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
@@ -20,6 +20,7 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/SValVisitor.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/Support/raw_ostream.h"
 using namespace clang;
@@ -233,6 +234,43 @@ void StackAddrEscapeChecker::checkReturnedBlockCaptures(
   }
 }
 
+class FindEscapingStackAddrsVisitor : public 
FullSValVisitor
+{
+  const StackFrameContext *Ctxt;
+
+  SmallVector Escaped;
+
+  bool IsTopFrame;
+
+public:
+  explicit FindEscapingStackAddrsVisitor(CheckerContext &CC, bool IsTopFrame) 
: 
+Ctxt(CC.getStackFrame()), IsTopFrame(IsTopFrame) {}
+
+  bool CheckForEscapes(SVal V) { return Visit(V); }
+
+  bool VisitSymbolVal(nonloc::SymbolVal SymV) {
+return Visit(SymV.getSymbol());
+  }
+
+  bool VisitLocAsInteger(nonloc::LocAsInteger LAI) {
+return Visit(LAI.getAsRegion());
+  }
+
+  bool VisitMemRegionVal(loc::MemRegionVal MRVal) {
+return Visit(MRVal.getRegion());
+  }
+
+  bool VisitMemRegion(const MemRegion *R) {
+const MemSpaceRegion *MS = R->getMemorySpace();
+const StackSpaceRegion *SSR = dyn_cast(MS);
+if (SSR && Ctxt == SSR->getStackFrame()) {
+  Escaped.push_back(R);
+  return true;
+}
+return false;
+  }
+};
+
 void StackAddrEscapeChecker::checkPreCall(const CallEvent &Call,
   CheckerContext &C) const {
   if (!ChecksEnabled[CK_StackAddrAsyncEscapeChecker])
@@ -257,7 +295,12 @@ void StackAddrEscapeChecker::checkPreStmt(const ReturnStmt 
*RS,
 return;
   RetE = RetE->IgnoreParens();
 
+  FindEscapingStackAddrsVisitor EscapeFinder(C, 
C.getPredecessor()->getLocationContext()->inTopFrame());
+
   SVal V = C.getSVal(RetE);
+
+  bool AnyEscapes = EscapeFinder.CheckForEscapes(V);
+
   const MemRegion *R = V.getAsRegion();
   if (!R)
 return;
@@ -402,7 +445,7 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
 bool checkForDanglingStackVariable(const MemRegion *Referrer,
const MemRegion *Referred) {
   const auto *ReferrerMemSpace = getStackOrGlobalSpaceRegion(Referrer);
-  const auto *ReferredMemSpace =
+  const auto *ReferredMemSpace = 
   Referred->getMemorySpace()->getAs();
 
   if (!ReferrerMemSpace || !ReferredMemSpace)

>From 0a26f83cd5f4a42238ba4fadb3436fec83e4bfcb Mon Sep 17 00:00:00 2001
From: Michael Flanders 
Date: Wed, 29 Jan 2025 00:34:45 -0600
Subject: [PATCH 02/20] wip

---
 .../Checkers/StackAddrEscapeChecker.cpp   | 143 ++
 clang/test/Analysis/stack-addr-ps.cpp |  73 ++---
 clang/test/Analysis/stackaddrleak.cpp |   2 +-
 3 files changed, 136 insertions(+), 82 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
index 59b47371df0d29..b6ef375936 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
+++ b/clan

[clang] [analyzer] Remove some false negatives in StackAddrEscapeChecker (PR #125638)

2025-02-03 Thread Michael Flanders via cfe-commits

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


[clang] [clang-format] Hanlde qualified type name for `QualifierAlignment` (PR #125327)

2025-02-03 Thread Owen Pan via cfe-commits

https://github.com/owenca updated 
https://github.com/llvm/llvm-project/pull/125327

>From af3d964d74634f0dd9f7216572c1d852b7a549dc Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Fri, 31 Jan 2025 18:32:33 -0800
Subject: [PATCH 1/3] [clang-format] Hanlde qualified type names

Fixes #125178.
---
 clang/lib/Format/QualifierAlignmentFixer.cpp  |  8 +++-
 clang/unittests/Format/QualifierFixerTest.cpp | 12 
 2 files changed, 19 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Format/QualifierAlignmentFixer.cpp 
b/clang/lib/Format/QualifierAlignmentFixer.cpp
index 21fb5074b4928f7..f777ac2a89f755a 100644
--- a/clang/lib/Format/QualifierAlignmentFixer.cpp
+++ b/clang/lib/Format/QualifierAlignmentFixer.cpp
@@ -132,8 +132,10 @@ static void rotateTokens(const SourceManager &SourceMgr,
   // Then move through the other tokens.
   auto *Tok = Begin;
   while (Tok != End) {
-if (!NewText.empty() && !endsWithSpace(NewText))
+if (!NewText.empty() && !endsWithSpace(NewText) &&
+Tok->isNot(tok::coloncolon)) {
   NewText += " ";
+}
 
 NewText += Tok->TokenText;
 Tok = Tok->Next;
@@ -412,6 +414,10 @@ const FormatToken 
*LeftRightQualifierAlignmentFixer::analyzeLeft(
   // The case `const long long volatile int` -> `const volatile long long int`
   // The case `long volatile long int const` -> `const volatile long long int`
   if (TypeToken->isTypeName(LangOpts)) {
+if (const auto *Prev = TypeToken->getPreviousNonComment();
+Prev && Prev->endsSequence(tok::coloncolon, tok::identifier)) {
+  TypeToken = Prev->getPreviousNonComment();
+}
 const FormatToken *LastSimpleTypeSpecifier = TypeToken;
 while (isConfiguredQualifierOrType(
 LastSimpleTypeSpecifier->getPreviousNonComment(),
diff --git a/clang/unittests/Format/QualifierFixerTest.cpp 
b/clang/unittests/Format/QualifierFixerTest.cpp
index 129828b0d187a91..530587bbf2ca744 100644
--- a/clang/unittests/Format/QualifierFixerTest.cpp
+++ b/clang/unittests/Format/QualifierFixerTest.cpp
@@ -1291,6 +1291,18 @@ TEST_F(QualifierFixerTest, WithCpp11Attribute) {
"[[maybe_unused]] constexpr static int A", Style);
 }
 
+TEST_F(QualifierFixerTest, WithQualifiedTypeName) {
+  auto Style = getLLVMStyle();
+  Style.QualifierAlignment = FormatStyle::QAS_Custom;
+  Style.QualifierOrder = {"constexpr", "type", "const"};
+
+  verifyFormat("constexpr std::int64_t x{123};",
+   "std::int64_t constexpr x{123};", Style);
+
+  Style.TypeNames.push_back("bar");
+  verifyFormat("constexpr foo::bar x{12};", "foo::bar constexpr x{12};", 
Style);
+}
+
 TEST_F(QualifierFixerTest, DisableRegions) {
   FormatStyle Style = getLLVMStyle();
   Style.QualifierAlignment = FormatStyle::QAS_Custom;

>From 5cc042e560bf620f283c93e8f25f3013f385d17c Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Sun, 2 Feb 2025 01:20:45 -0800
Subject: [PATCH 2/3] Handle ::type and ::foo::type

---
 clang/lib/Format/QualifierAlignmentFixer.cpp  | 11 ---
 clang/unittests/Format/QualifierFixerTest.cpp |  3 +++
 2 files changed, 11 insertions(+), 3 deletions(-)

diff --git a/clang/lib/Format/QualifierAlignmentFixer.cpp 
b/clang/lib/Format/QualifierAlignmentFixer.cpp
index f777ac2a89f755a..edef95f965edb7a 100644
--- a/clang/lib/Format/QualifierAlignmentFixer.cpp
+++ b/clang/lib/Format/QualifierAlignmentFixer.cpp
@@ -414,9 +414,14 @@ const FormatToken 
*LeftRightQualifierAlignmentFixer::analyzeLeft(
   // The case `const long long volatile int` -> `const volatile long long int`
   // The case `long volatile long int const` -> `const volatile long long int`
   if (TypeToken->isTypeName(LangOpts)) {
-if (const auto *Prev = TypeToken->getPreviousNonComment();
-Prev && Prev->endsSequence(tok::coloncolon, tok::identifier)) {
-  TypeToken = Prev->getPreviousNonComment();
+for (const auto *Prev = TypeToken->getPreviousNonComment();
+ Prev && Prev->is(tok::coloncolon);
+ Prev = Prev->getPreviousNonComment()) {
+  TypeToken = Prev;
+  Prev = Prev->getPreviousNonComment();
+  if (!(Prev && Prev->is(tok::identifier)))
+break;
+  TypeToken = Prev;
 }
 const FormatToken *LastSimpleTypeSpecifier = TypeToken;
 while (isConfiguredQualifierOrType(
diff --git a/clang/unittests/Format/QualifierFixerTest.cpp 
b/clang/unittests/Format/QualifierFixerTest.cpp
index 530587bbf2ca744..3eae39f267c3e08 100644
--- a/clang/unittests/Format/QualifierFixerTest.cpp
+++ b/clang/unittests/Format/QualifierFixerTest.cpp
@@ -1296,8 +1296,11 @@ TEST_F(QualifierFixerTest, WithQualifiedTypeName) {
   Style.QualifierAlignment = FormatStyle::QAS_Custom;
   Style.QualifierOrder = {"constexpr", "type", "const"};
 
+  verifyFormat("constexpr ::int64_t x{1};", "::int64_t constexpr x{1};", 
Style);
   verifyFormat("constexpr std::int64_t x{123};",
"std::int64_t constexpr x{123};", Style);
+  verifyFormat("constexpr ::std::int64_t x{123};",
+   "::std::int64_t constexpr x

[clang] [clang-format] Hanlde qualified type name for `QualifierAlignment` (PR #125327)

2025-02-03 Thread Owen Pan via cfe-commits


@@ -412,6 +414,15 @@ const FormatToken 
*LeftRightQualifierAlignmentFixer::analyzeLeft(
   // The case `const long long volatile int` -> `const volatile long long int`
   // The case `long volatile long int const` -> `const volatile long long int`
   if (TypeToken->isTypeName(LangOpts)) {
+for (const auto *Prev = TypeToken->getPreviousNonComment();
+ Prev && Prev->is(tok::coloncolon);
+ Prev = Prev->getPreviousNonComment()) {
+  TypeToken = Prev;
+  Prev = Prev->getPreviousNonComment();

owenca wrote:

```suggestion
for (const auto *Prev = TypeToken->Previous;
 Prev && Prev->is(tok::coloncolon);
 Prev = Prev->Previous) {
  TypeToken = Prev;
  Prev = Prev->Previous;
```

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


[clang] [clang] Force AttributedStmtClass to not be scope parents (PR #125370)

2025-02-03 Thread David Blaikie via cfe-commits

dwblaikie wrote:

Could you add a test case - check in clang/test to see if other tests for the 
diagnostic text in the original bug, and add a test case for that nearby (maybe 
the same file the diagnostic is already tested in)?

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


[clang] [WIP][clang]: Implement a conditional lifetimebound_if builtin. (PR #125520)

2025-02-03 Thread Haojian Wu via cfe-commits

https://github.com/hokein created 
https://github.com/llvm/llvm-project/pull/125520

This WIP PR explores the idea of introducing `[[clang::lifetimebound_if()]]`,  a built-in attribute that conditionally applies 
`[[clang::lifetimebound]]` based  on the given boolean expression.  

One of the key challenges in adopting `[[clang::lifetimebound]]` and  
`[[clang::lifetime_capture_by]]` is that these attributes should only apply to 
pointer-like types. Currently, we handle this by introducing multiple 
overloads, which increases code complexity and compilation overhead.  

This new attribute aims to simplify the implementation by enabling  conditional 
application, reducing the need for overloads.  

cc @usx95 @Xazax-hun @ilya-biryukov @higher-performance 

>From 4bf3dbe3d28e5ea5886f0a47ba4ff18a110e1c06 Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Mon, 3 Feb 2025 16:32:26 +0100
Subject: [PATCH] [WIP][clang]: Implement a conditional lifetimebound_if
 builtin.

---
 clang/include/clang/Basic/Attr.td |  8 +++
 clang/lib/Sema/CheckExprLifetime.cpp  | 21 +--
 clang/lib/Sema/SemaDeclAttr.cpp   |  7 +++
 .../lib/Sema/SemaTemplateInstantiateDecl.cpp  | 21 +++
 4 files changed, 55 insertions(+), 2 deletions(-)

diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 2a3a29bd2ee1cf..eb2a89487144c3 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -3472,6 +3472,14 @@ def DiagnoseIf : InheritableAttr {
   let Documentation = [DiagnoseIfDocs];
 }
 
+def LifetimeBoundIf : Attr {
+  let Spellings = [Clang<"lifetimebound_if">];
+  let Subjects = SubjectList<[ParmVar, ImplicitObjectParameter], ErrorDiag>;
+  let Args = [ExprArgument<"Cond">];
+  // FIXME: add documentation
+  let Documentation = [InternalOnly];
+}
+
 def NoSpecializations : InheritableAttr {
   let Spellings = [Clang<"no_specializations", /*AllowInC*/0>];
   let Args = [StringArgument<"Message", 1>];
diff --git a/clang/lib/Sema/CheckExprLifetime.cpp 
b/clang/lib/Sema/CheckExprLifetime.cpp
index 8963cad86dbcae..fa9c850865a228 100644
--- a/clang/lib/Sema/CheckExprLifetime.cpp
+++ b/clang/lib/Sema/CheckExprLifetime.cpp
@@ -557,6 +557,23 @@ bool implicitObjectParamIsLifetimeBound(const FunctionDecl 
*FD) {
   return isNormalAssignmentOperator(FD);
 }
 
+static bool hasLifetimeBoundAttribute(const Decl *D) {
+  if (D->hasAttr())
+return true;
+  if (const auto *AI = D->getAttr()) {
+bool Result;
+// FIXME: we pay the cost of evaluating the binary condition everytime we
+// check the existence of the attribute. Cache the result.
+if (AI->getCond()->EvaluateAsBooleanCondition(Result, D->getASTContext())) 
{
+  if (Result)
+return true;
+} else {
+  // FIXME: emits an error.
+}
+  }
+  return false;
+}
+
 // Visit lifetimebound or gsl-pointer arguments.
 static void visitFunctionCallArguments(IndirectLocalPath &Path, Expr *Call,
LocalVisitor Visit) {
@@ -659,7 +676,7 @@ static void visitFunctionCallArguments(IndirectLocalPath 
&Path, Expr *Call,
   Arg = DAE->getExpr();
 }
 if (CheckCoroCall ||
-CanonCallee->getParamDecl(I)->hasAttr())
+hasLifetimeBoundAttribute(CanonCallee->getParamDecl(I)))
   VisitLifetimeBoundArg(CanonCallee->getParamDecl(I), Arg);
 else if (const auto *CaptureAttr =
  
CanonCallee->getParamDecl(I)->getAttr();
@@ -1278,7 +1295,7 @@ static AnalysisResult analyzePathForGSLPointer(const 
IndirectLocalPath &Path,
 static bool isAssignmentOperatorLifetimeBound(const CXXMethodDecl *CMD) {
   CMD = getDeclWithMergedLifetimeBoundAttrs(CMD);
   return CMD && isNormalAssignmentOperator(CMD) && CMD->param_size() == 1 &&
- CMD->getParamDecl(0)->hasAttr();
+ hasLifetimeBoundAttribute(CMD->getParamDecl(0));
 }
 
 static bool shouldRunGSLAssignmentAnalysis(const Sema &SemaRef,
diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index 9d7d22590bce4b..b290e729c87c38 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -3975,6 +3975,10 @@ static void handleLifetimeCaptureByAttr(Sema &S, Decl *D,
 D->addAttr(CaptureByAttr);
 }
 
+static void handleLifetimeBoundIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
+  D->addAttr(LifetimeBoundIfAttr::Create(S.Context, AL.getArgAsExpr(0)));
+}
+
 void Sema::LazyProcessLifetimeCaptureByParams(FunctionDecl *FD) {
   bool HasImplicitThisParam = isInstanceMethod(FD);
   SmallVector Attrs;
@@ -6823,6 +6827,9 @@ ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D, 
const ParsedAttr &AL,
   case ParsedAttr::AT_LifetimeCaptureBy:
 handleLifetimeCaptureByAttr(S, D, AL);
 break;
+  case ParsedAttr::AT_LifetimeBoundIf:
+handleLifetimeBoundIfAttr(S, D, AL);
+break;
   case ParsedAttr::AT_CalledOnce:
 handleCalledOnceAttr(S, D, AL);
 break;
diff --git a

[clang] [analyzer] Do not destruct fields of unions (PR #122330)

2025-02-03 Thread Balazs Benics via cfe-commits

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


[libclc] [libclc] Move mad_sat to CLC; optimize for vector types (PR #125517)

2025-02-03 Thread Fraser Cormack via cfe-commits


@@ -0,0 +1,119 @@
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#define __CLC_CONVERT_TY(X, TY) __builtin_convertvector(X, TY)
+
+// Macro for defining mad_sat variants for char/uchar/short/ushort
+// FIXME: Once using __clc_convert_ty, can easily unify scalar and vector defs
+#define _CLC_DEFINE_SIMPLE_MAD_SAT(TYPE, UP_TYPE, LIT_PREFIX)  
\

frasercrmck wrote:

Yeah, glad you agree. It's been something I want to look into.

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


[clang] [compiler-rt] Rtsan fbsd (PR #125389)

2025-02-03 Thread Chris Apple via cfe-commits

cjappl wrote:

> @devnexen in principle, I'm of course not opposed to rtsan supporting FreeBSD 
> - is there any motivation in particular for why you propose adding it here? 
> Is this the first of many patches that are needed, or is it the only one that 
> you can foresee? I'd like to make sure that the maintenance overhead will be 
> worth it going forwards.
> 
> @cjappl have you got any concerns with introducing FreeBSD support?

I have no specific concerns, but I agree we should be sure any maintenance cost 
is worth enabling it. Maybe we can keep this PR open and see if it attracts any 
comments by people wanting it?

I don't think we should enable it just to enable it. We have had strong signals 
of support on MacOS, Linux and (not implemented) Windows. We have not had any 
feedback asking for support on the BSD flavors yet.

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


[clang] [clang] handle fp options in __builtin_convertvector (PR #125522)

2025-02-03 Thread Jakub Ficek via cfe-commits

https://github.com/ficol created 
https://github.com/llvm/llvm-project/pull/125522

None

>From fc40a0fddd830aa1fdfaafa1618acc5c2d0ee5fa Mon Sep 17 00:00:00 2001
From: "Ficek, Jakub" 
Date: Mon, 3 Feb 2025 16:45:17 +0100
Subject: [PATCH] [clang] handle fp options in __builtin_convertvector

---
 clang/include/clang/AST/Expr.h| 80 +--
 clang/include/clang/AST/Stmt.h| 15 +
 clang/include/clang/AST/TextNodeDumper.h  |  1 +
 clang/lib/AST/ASTImporter.cpp |  7 +-
 clang/lib/AST/Expr.cpp| 20 ++
 clang/lib/AST/TextNodeDumper.cpp  |  6 ++
 clang/lib/CodeGen/CGExprScalar.cpp|  2 +
 clang/lib/Sema/SemaChecking.cpp   |  4 +-
 clang/lib/Serialization/ASTReaderStmt.cpp | 13 +++-
 clang/lib/Serialization/ASTWriterStmt.cpp |  4 ++
 clang/test/AST/ast-dump-fpfeatures.cpp| 14 +++-
 clang/test/CodeGen/pragma-fenv_access.c   |  9 +++
 12 files changed, 163 insertions(+), 12 deletions(-)

diff --git a/clang/include/clang/AST/Expr.h b/clang/include/clang/AST/Expr.h
index 7be4022649329b..1e944277483548 100644
--- a/clang/include/clang/AST/Expr.h
+++ b/clang/include/clang/AST/Expr.h
@@ -4579,25 +4579,97 @@ class ShuffleVectorExpr : public Expr {
 /// ConvertVectorExpr - Clang builtin function __builtin_convertvector
 /// This AST node provides support for converting a vector type to another
 /// vector type of the same arity.
-class ConvertVectorExpr : public Expr {
+class ConvertVectorExpr final
+: public Expr,
+  private llvm::TrailingObjects {
 private:
   Stmt *SrcExpr;
   TypeSourceInfo *TInfo;
   SourceLocation BuiltinLoc, RParenLoc;
 
+  friend TrailingObjects;
   friend class ASTReader;
   friend class ASTStmtReader;
-  explicit ConvertVectorExpr(EmptyShell Empty) : Expr(ConvertVectorExprClass, 
Empty) {}
+  explicit ConvertVectorExpr(bool HasFPFeatures, EmptyShell Empty)
+  : Expr(ConvertVectorExprClass, Empty) {
+ConvertVectorExprBits.HasFPFeatures = HasFPFeatures;
+  }
 
-public:
   ConvertVectorExpr(Expr *SrcExpr, TypeSourceInfo *TI, QualType DstType,
 ExprValueKind VK, ExprObjectKind OK,
-SourceLocation BuiltinLoc, SourceLocation RParenLoc)
+SourceLocation BuiltinLoc, SourceLocation RParenLoc,
+FPOptionsOverride FPFeatures)
   : Expr(ConvertVectorExprClass, DstType, VK, OK), SrcExpr(SrcExpr),
 TInfo(TI), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {
+ConvertVectorExprBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
+if (hasStoredFPFeatures())
+  setStoredFPFeatures(FPFeatures);
 setDependence(computeDependence(this));
   }
 
+  size_t numTrailingObjects(OverloadToken) const {
+return ConvertVectorExprBits.HasFPFeatures ? 1 : 0;
+  }
+
+  FPOptionsOverride &getTrailingFPFeatures() {
+assert(ConvertVectorExprBits.HasFPFeatures);
+return *getTrailingObjects();
+  }
+
+  const FPOptionsOverride &getTrailingFPFeatures() const {
+assert(ConvertVectorExprBits.HasFPFeatures);
+return *getTrailingObjects();
+  }
+
+public:
+  static ConvertVectorExpr *CreateEmpty(const ASTContext &C,
+bool hasFPFeatures);
+
+  static ConvertVectorExpr *Create(const ASTContext &C, Expr *SrcExpr,
+   TypeSourceInfo *TI, QualType DstType,
+   ExprValueKind VK, ExprObjectKind OK,
+   SourceLocation BuiltinLoc,
+   SourceLocation RParenLoc,
+   FPOptionsOverride FPFeatures);
+
+  /// Get the FP contractibility status of this operator. Only meaningful for
+  /// operations on floating point types.
+  bool isFPContractableWithinStatement(const LangOptions &LO) const {
+return getFPFeaturesInEffect(LO).allowFPContractWithinStatement();
+  }
+
+  /// Is FPFeatures in Trailing Storage?
+  bool hasStoredFPFeatures() const {
+return ConvertVectorExprBits.HasFPFeatures;
+  }
+
+  /// Get FPFeatures from trailing storage.
+  FPOptionsOverride getStoredFPFeatures() const {
+return getTrailingFPFeatures();
+  }
+
+  /// Get the store FPOptionsOverride or default if not stored.
+  FPOptionsOverride getStoredFPFeaturesOrDefault() const {
+return hasStoredFPFeatures() ? getStoredFPFeatures() : FPOptionsOverride();
+  }
+
+  /// Set FPFeatures in trailing storage, used by Serialization & ASTImporter.
+  void setStoredFPFeatures(FPOptionsOverride F) { getTrailingFPFeatures() = F; 
}
+
+  /// Get the FP features status of this operator. Only meaningful for
+  /// operations on floating point types.
+  FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
+if (ConvertVectorExprBits.HasFPFeatures)
+  return getStoredFPFeatures().applyOverrides(LO);
+return FPOptions::defaultWithoutTrailingStorage(LO);
+  }
+
+  FPOptionsOverride getFPOptionsOverride() const {
+if (C

[clang] [clang] handle fp options in __builtin_convertvector (PR #125522)

2025-02-03 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/125522
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [analyzer] Add option assume-one-iteration (PR #125494)

2025-02-03 Thread Donát Nagy via cfe-commits

NagyDonat wrote:

> My preference would be to not have NFC tags for off by default features.

OK, I removed the [NFC] tag from the PR title and adjusted the description 
accordingly.

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


[clang] [WIP][clang]: Implement a conditional lifetimebound_if builtin. (PR #125520)

2025-02-03 Thread Haojian Wu via cfe-commits

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


[clang] [analyzer] Add option assume-one-iteration (PR #125494)

2025-02-03 Thread Balazs Benics via cfe-commits


@@ -294,6 +294,16 @@ ANALYZER_OPTION(
 bool, ShouldUnrollLoops, "unroll-loops",
 "Whether the analysis should try to unroll loops with known bounds.", 
false)
 
+ANALYZER_OPTION(
+bool, ShouldAssumeOneIteration, "assume-one-iteration",
+"Whether the analyzer should always assume at least one iteration in "

steakhal wrote:

How about the naive "assume-at-least-one-iteration"?
"assume" already implies the part that the condition was opaque, otherwise we 
wouldn't assume anything there.

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


[clang] [analyzer] Add time-trace scopes for high-level analyzer steps (PR #125508)

2025-02-03 Thread Oliver Stöneberg via cfe-commits

firewave wrote:

Does this also work when CSA is called through clang-tidy? The analyzer 
profiling data in missing in the `--enable-check-profile` output - see #73673?

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


[clang] Reland: [clang] Track function template instantiation from definition (PR #125266)

2025-02-03 Thread via cfe-commits


@@ -2298,6 +2298,13 @@ class FunctionDecl : public DeclaratorDecl,
 FunctionDeclBits.IsLateTemplateParsed = ILT;
   }
 
+  bool isInstantiatedFromMemberTemplate() const {
+return FunctionDeclBits.IsInstantiatedFromMemberTemplate;
+  }
+  void setInstantiatedFromMemberTemplate(bool Val = true) {
+FunctionDeclBits.IsInstantiatedFromMemberTemplate = Val;
+  }
+

cor3ntin wrote:

I had a chat with @erichkeane - I think I understand a bit more now.
At least I understand why `RedeclarableTemplateDecl` is not suitable

However, why is `FunctionDecl::getInstantiatedFromDecl` / 
`FunctionDecl::getMemberSpecializationInfo`  not what we want?

If we can't use that, why are we storing a bit in FunctionDecl and not in 
`FunctionTemplateSpecializationInfo` for example?

I think we need comments somewhere explaining all of that because It's not 
trivial.









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


[clang] Warn when unique objects might be duplicated in shared libraries (PR #117622)

2025-02-03 Thread Devon Loehr via cfe-commits

DKLoehr wrote:

Thanks @zmodem for merging (and also reverting). Follow-up PR with the fix is 
#125526.

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


[clang] Warn when unique objects might be duplicated in shared libraries (PR #125526)

2025-02-03 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Devon Loehr (DKLoehr)


Changes

This is attempt 2 to merge this, the first one is #117622. This 
properly disables the tests when building for playstation, since the warning is 
disabled there.

When a hidden object is built into multiple shared libraries, each instance of 
the library will get its own copy. If
the object was supposed to be globally unique (e.g. a global variable or static 
data member), this can cause very subtle bugs.

An object might be incorrectly duplicated if it:

Is defined in a header (so it might appear in multiple TUs), and
Has external linkage (otherwise it's supposed to be duplicated), and
Has hidden visibility (or else the dynamic linker will handle it)
The duplication is only a problem semantically if one of the following is true:

The object is mutable (the copies won't be in sync), or
Its initialization has side effects (it may now run more than once), or
The value of its address is used (different copies have different addresses).
To detect this, we add a new -Wunique-object-duplication warning. It warns on 
cases (1) and (2) above. To be conservative, we only warn in case (2) if we are 
certain the initializer has side effects, and we don't warn on new because the 
only side effect is some extra memory usage.

We don't currently warn on case (3) because doing so is prone to false 
positives: there are many reasons for taking the address which aren't 
inherently problematic (e.g. passing to a function that expects a pointer). We 
only run into problems if the code inspects the value of the address.

The check is currently disabled for windows, which uses its own analogue of 
visibility (declimport/declexport). The check is also disabled inside 
templates, since it can give false positives if a template is never 
instantiated.

Resolving the warning
The warning can be fixed in several ways:

If the object in question doesn't need to be mutable, it should be made const. 
Note that the variable must be completely immutable, e.g. we'll warn on const 
int* p because the pointer itself is mutable. To silence the warning, it should 
instead be const int* const p.
If the object must be mutable, it (or the enclosing function, in the case of 
static local variables) should be made visible using 
__attribute((visibility("default")))
If the object is supposed to be duplicated, it should be be given internal 
linkage.
Testing
I've tested the warning by running it on clang itself, as well as on chromium. 
Compiling clang resulted in [10 warnings across 6 
files](https://github.com/user-attachments/files/17908069/clang-warnings.txt), 
while Chromium resulted in [160 warnings across 85 
files](https://github.com/user-attachments/files/17908072/chromium-warnings.txt),
 mostly in third-party code. Almost all warnings were due to mutable variables.

I evaluated the warnings by manual inspection. I believe all the resulting 
warnings are true positives, i.e. they represent potentially-problematic code 
where duplication might cause a problem. For the clang warnings, I also 
validated them by either adding const or visibility annotations as appropriate.

Limitations
I am aware of four main limitations with the current warning:

We do not warn when the address of a duplicated object is taken, since doing so 
is prone to false positives. I'm hopeful that we can create a refined version 
in the future, however.
We only warn for side-effectful initialization if we are certain side effects 
exist. Warning on potential side effects produced a huge number of false 
positives; I don't expect there's much that can be done about this in modern 
C++ code bases, since proving a lack of side effects is difficult.
Windows uses a different system (declexport/import) instead of visibility. From 
manual testing, it seems to behave analogously to the visibility system for the 
purposes of this warning, but to keep things simple the warning is disabled on 
windows for now.
We don't warn on code inside templates. This is unfortuate, since it masks many 
real issues, e.g. a templated variable which is implicitly instantiated the 
same way in multiple TUs should be globally unique, but may accidentally be 
duplicated. Unfortunately, we found some potential false positives during 
testing that caused us to disable the warning for now.

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


7 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+4) 
- (modified) clang/include/clang/Basic/DiagnosticGroups.td (+30) 
- (modified) clang/include/clang/Basic/DiagnosticSemaKinds.td (+9) 
- (modified) clang/include/clang/Sema/Sema.h (+6) 
- (modified) clang/lib/Sema/SemaDecl.cpp (+101) 
- (added) clang/test/SemaCXX/unique_object_duplication.cpp (+16) 
- (added) clang/test/SemaCXX/unique_object_duplication.h (+157) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 7fafe2807bd3883..e607ef488f653e3 100644

[clang] [llvm] [Hexagon] Set the default compilation target to V68 (PR #125239)

2025-02-03 Thread Brian Cain via cfe-commits

androm3da wrote:

> Done. Thanks Brian.

Are you sure the release notes change has landed?  I don't see a commit on 
`main` with it yet.

https://github.com/llvm/llvm-project/blob/main/llvm/docs/ReleaseNotes.md#changes-to-the-hexagon-backend

Is there a pull req open for this change?

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


[clang] Warn when unique objects might be duplicated in shared libraries (PR #125526)

2025-02-03 Thread Hans Wennborg via cfe-commits

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


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


[clang] [llvm] [Hexagon] Set the default compilation target to V68 (PR #125239)

2025-02-03 Thread Brian Cain via cfe-commits

androm3da wrote:

> > Done. Thanks Brian.
> 
> Are you sure the release notes change has landed? I don't see a commit on 
> `main` with it yet.
> 
> https://github.com/llvm/llvm-project/blob/main/llvm/docs/ReleaseNotes.md#changes-to-the-hexagon-backend
> 
> Is there a pull req open for this change?

oh whoops - this was a clang change and not an llvm one.  So I guess we'd 
expect to see it in the clang release notes?

https://github.com/llvm/llvm-project/blob/main/clang/docs/ReleaseNotes.rst#target-specific-changes



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


[clang] [analyzer] Do not destruct fields of unions (PR #122330)

2025-02-03 Thread Jameson Nash via cfe-commits

https://github.com/vtjnash updated 
https://github.com/llvm/llvm-project/pull/122330

>From 829e1c89ce869f782cb802a1d618003770c0d074 Mon Sep 17 00:00:00 2001
From: Jameson Nash 
Date: Thu, 9 Jan 2025 17:10:08 +
Subject: [PATCH 1/3] [Sema] do not destruct fields of unions

The C++ standard prohibits this implicit destructor call, leading to
incorrect reports from clang-analyzer. This causes projects that use
std::option (including llvm) to fail the cplusplus.NewDelete test
incorrectly when run through the analyzer.

Fixes #119415
---
 clang/lib/Analysis/CFG.cpp|  2 ++
 .../test/Analysis/NewDelete-checker-test.cpp  | 28 +++
 clang/test/Analysis/dtor-array.cpp| 24 
 3 files changed, 54 insertions(+)

diff --git a/clang/lib/Analysis/CFG.cpp b/clang/lib/Analysis/CFG.cpp
index 304bbb2b422c61..3e144395cffc6f 100644
--- a/clang/lib/Analysis/CFG.cpp
+++ b/clang/lib/Analysis/CFG.cpp
@@ -2041,6 +2041,8 @@ void CFGBuilder::addImplicitDtorsForDestructor(const 
CXXDestructorDecl *DD) {
   }
 
   // First destroy member objects.
+  if (RD->isUnion())
+return;
   for (auto *FI : RD->fields()) {
 // Check for constant size array. Set type to array element type.
 QualType QT = FI->getType();
diff --git a/clang/test/Analysis/NewDelete-checker-test.cpp 
b/clang/test/Analysis/NewDelete-checker-test.cpp
index 21b4cf817b5df6..806edd47840fc1 100644
--- a/clang/test/Analysis/NewDelete-checker-test.cpp
+++ b/clang/test/Analysis/NewDelete-checker-test.cpp
@@ -441,3 +441,31 @@ void testLeakBecauseNTTPIsNotDeallocation() {
   void* p = ::operator new(10);
   deallocate_via_nttp(p);
 }  // leak-warning{{Potential leak of memory pointed to by 'p'}}
+
+namespace optional_union {
+  template 
+  class unique_ptr {
+T *q;
+  public:
+unique_ptr() : q(new T) {}
+~unique_ptr() {
+  delete q;
+}
+  };
+
+  union custom_union_t {
+unique_ptr present;
+char notpresent;
+custom_union_t() : present(unique_ptr()) {}
+~custom_union_t() {};
+  };
+
+  void testUnionCorrect() {
+custom_union_t a;
+a.present.~unique_ptr();
+  }
+
+  void testUnionLeak() {
+custom_union_t a;
+  } // leak-warning{{Potential leak of memory pointed to by 'a.present.q'}}
+}
diff --git a/clang/test/Analysis/dtor-array.cpp 
b/clang/test/Analysis/dtor-array.cpp
index 84a34af9225169..1bbe55c09ee7e2 100644
--- a/clang/test/Analysis/dtor-array.cpp
+++ b/clang/test/Analysis/dtor-array.cpp
@@ -377,3 +377,27 @@ void directUnknownSymbol() {
 }
 
 }
+
+void testUnionDtor() {
+  static int unionDtorCalled;
+  InlineDtor::cnt = 0;
+  InlineDtor::dtorCalled = 0;
+  unionDtorCalled = 0;
+  {
+  union UnionDtor {
+  InlineDtor kind1;
+  char kind2;
+  ~UnionDtor() { unionDtorCalled++; }
+  };
+  UnionDtor u1{.kind1{}};
+  UnionDtor u2{.kind2{}};
+  auto u3 = new UnionDtor{.kind1{}};
+  auto u4 = new UnionDtor{.kind2{}};
+  delete u3;
+  delete u4;
+  }
+
+  clang_analyzer_eval(unionDtorCalled == 4); // expected-warning {{TRUE}}
+  clang_analyzer_eval(InlineDtor::dtorCalled != 4); // expected-warning 
{{TRUE}}
+  clang_analyzer_eval(InlineDtor::dtorCalled == 0); // expected-warning 
{{TRUE}}
+}

>From 032315608bca99b3da9a74cb1d7f497bce66b47d Mon Sep 17 00:00:00 2001
From: Jameson Nash 
Date: Wed, 29 Jan 2025 19:24:39 +
Subject: [PATCH 2/3] fixup! [Sema] do not destruct fields of unions

---
 clang/docs/ReleaseNotes.rst | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 7fafe2807bd388..1c23b48d8a1df2 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -103,6 +103,8 @@ Attribute Changes in Clang
 Improvements to Clang's diagnostics
 ---
 
+- Fixed a bug where Clang's Analysis did not correctly model the destructor 
behavior of ``union`` members (#GH119415).
+
 Improvements to Clang's time-trace
 --
 

>From d8a6ab76553d301c63e0c3bc60870655cd428ea1 Mon Sep 17 00:00:00 2001
From: Jameson Nash 
Date: Mon, 3 Feb 2025 11:31:16 -0500
Subject: [PATCH 3/3] Update clang/test/Analysis/dtor-array.cpp

Co-authored-by: Balazs Benics 
---
 clang/test/Analysis/dtor-array.cpp | 1 -
 1 file changed, 1 deletion(-)

diff --git a/clang/test/Analysis/dtor-array.cpp 
b/clang/test/Analysis/dtor-array.cpp
index 1bbe55c09ee7e2..942cba4a2e046d 100644
--- a/clang/test/Analysis/dtor-array.cpp
+++ b/clang/test/Analysis/dtor-array.cpp
@@ -398,6 +398,5 @@ void testUnionDtor() {
   }
 
   clang_analyzer_eval(unionDtorCalled == 4); // expected-warning {{TRUE}}
-  clang_analyzer_eval(InlineDtor::dtorCalled != 4); // expected-warning 
{{TRUE}}
   clang_analyzer_eval(InlineDtor::dtorCalled == 0); // expected-warning 
{{TRUE}}
 }

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

[clang] [Clang] disallow attributes on void parameters (PR #124920)

2025-02-03 Thread Aaron Ballman via cfe-commits


@@ -50,8 +50,8 @@ struct testRecoverStrictnessStruct { };
 
 #pragma clang attribute pop
 
-#pragma clang attribute push (__attribute__((abi_tag("a"))), apply_to = 
any(function, record(unless(is_union)), variable, enum))
-// expected-error@-1 {{attribute 'abi_tag' cannot be applied to 'enum'}}
+#pragma clang attribute push (__attribute__((abi_tag("a"))), apply_to = 
any(function, record(unless(is_union)), variable, enum)) // expected-warning 
{{attribute 'abi_tag' cannot be applied to a 'void' parameter}}
+   
  // expected-error@-1 
{{attribute 'abi_tag' cannot be applied to 'enum'}}

AaronBallman wrote:

> @AaronBallman if we're considering changes to `Attr.td`, 

I don't think we need changes in Attr.td itself; the changes should be limited 
to just the tablegen bits (or the part consuming the tablegen bits).

> it seems that `[Var]` and `[ParmVar]` should be extended to `AttrSubject`, 
> since `AttrSubjectMatcherRule` only accepts a list of `AttrSubject`. I'm 
> unsure if this qualifies as a `Subject`, though...

Those already are an `AttrSubject`; we have attributes using them already.

> https://github.com/llvm/llvm-project/blob/50082773223b9eced296d8223ca4e4a79ecdeb9b/clang/include/clang/Basic/Attr.td#L560-L567

I think that's correct as-is.

> or explicitly add a helper to exclude void parameters and use it with
> 
> https://github.com/llvm/llvm-project/blob/d00579be39e8a470d7a0ff79ff6deadf9e003781/clang/lib/Sema/ParsedAttr.cpp#L172-L175

I think that's what needs to be changed to exclude `void` parameters (or 
somewhere nearby that call).

> > Side note: pragma clang attribute push diagnostics are THE WORST here...
> 
> I suppose the diagnostic for void parameters will be skipped if the rules 
> exclude them, or should the diagnostic still handle this case?

The goal is to get rid of the diagnostics about `void` parameters. e.g., `// 
expected-warning {{attribute 'abi_tag' cannot be applied to a 'void' 
parameter}}` shouldn't be fired.

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


[clang] [analyzer] Do not destruct fields of unions (PR #122330)

2025-02-03 Thread Jameson Nash via cfe-commits


@@ -377,3 +377,27 @@ void directUnknownSymbol() {
 }
 
 }
+
+void testUnionDtor() {
+  static int unionDtorCalled;
+  InlineDtor::cnt = 0;
+  InlineDtor::dtorCalled = 0;
+  unionDtorCalled = 0;
+  {
+  union UnionDtor {
+  InlineDtor kind1;
+  char kind2;
+  ~UnionDtor() { unionDtorCalled++; }
+  };
+  UnionDtor u1{.kind1{}};
+  UnionDtor u2{.kind2{}};
+  auto u3 = new UnionDtor{.kind1{}};
+  auto u4 = new UnionDtor{.kind2{}};
+  delete u3;
+  delete u4;
+  }
+
+  clang_analyzer_eval(unionDtorCalled == 4); // expected-warning {{TRUE}}
+  clang_analyzer_eval(InlineDtor::dtorCalled != 4); // expected-warning 
{{TRUE}}

vtjnash wrote:

Sure, makes sense. I had left it in as a hint of what the expected bad result 
would look like in case it breaks, but not necessary

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


[clang] [clang-format] Hanlde qualified type name for `QualifierAlignment` (PR #125327)

2025-02-03 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 b8734797a3f605c4aaa37fcb5007baa273565460 
8052b1553eb05767db6f080d6ee4bbd515994f93 --extensions cpp -- 
clang/lib/Format/QualifierAlignmentFixer.cpp 
clang/unittests/Format/QualifierFixerTest.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Format/QualifierAlignmentFixer.cpp 
b/clang/lib/Format/QualifierAlignmentFixer.cpp
index e2e0c863f7..23e8b44eee 100644
--- a/clang/lib/Format/QualifierAlignmentFixer.cpp
+++ b/clang/lib/Format/QualifierAlignmentFixer.cpp
@@ -415,8 +415,7 @@ const FormatToken 
*LeftRightQualifierAlignmentFixer::analyzeLeft(
   // The case `long volatile long int const` -> `const volatile long long int`
   if (TypeToken->isTypeName(LangOpts)) {
 for (const auto *Prev = TypeToken->Previous;
- Prev && Prev->is(tok::coloncolon);
- Prev = Prev->Previous) {
+ Prev && Prev->is(tok::coloncolon); Prev = Prev->Previous) {
   TypeToken = Prev;
   Prev = Prev->Previous;
   if (!(Prev && Prev->is(tok::identifier)))

``




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


[clang] [clang] handle fp options in __builtin_convertvector (PR #125522)

2025-02-03 Thread Jakub Ficek via cfe-commits

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


[clang] [Clang][counted_by] Don't treat a __bdos argument as an array if it isn't (PR #125298)

2025-02-03 Thread Bill Wendling via cfe-commits

https://github.com/bwendling updated 
https://github.com/llvm/llvm-project/pull/125298

>From df6b80c82f1a9ce4f1eef580f008c86fd691ba71 Mon Sep 17 00:00:00 2001
From: Bill Wendling 
Date: Fri, 31 Jan 2025 12:48:36 -0800
Subject: [PATCH 1/4] [Clang][counted_by] Don't treat a pointer as an array

If the __bdos field isn't an array, don't process it. We'll default to
using the llvm.objectsize intrinsic.
---
 clang/lib/CodeGen/CGBuiltin.cpp | 30 --
 1 file changed, 24 insertions(+), 6 deletions(-)

diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 11fa295dad9524c..21faf85a16e2d25 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -1319,12 +1319,36 @@ CodeGenFunction::emitCountedByMemberSize(const Expr *E, 
llvm::Value *EmittedE,
 
   //  size_t field_offset = offsetof (struct s, field);
   Value *FieldOffset = nullptr;
+  llvm::ConstantInt *FieldBaseSize = nullptr;
   if (FlexibleArrayMemberFD != FD) {
 std::optional Offset = GetFieldOffset(Ctx, RD, FD);
 if (!Offset)
   return nullptr;
 FieldOffset =
 llvm::ConstantInt::get(ResType, *Offset / CharWidth, IsSigned);
+
+if (Idx) {
+  // From option (4):
+  //  size_t field_base_size = sizeof (*ptr->field_array);
+  if (!FieldTy->isArrayType())
+// The field isn't an array. For example:
+//
+// struct {
+// int count;
+// char *string;
+// int array[] __counted_by(count);
+// } x;
+//
+// __builtin_dynamic_object_size(x.string[42], 0);
+//
+// If built with '-Wno-int-conversion', FieldTy won't be an array here.
+return nullptr;
+
+  const ArrayType *ArrayTy = Ctx.getAsArrayType(FieldTy);
+  CharUnits BaseSize = Ctx.getTypeSizeInChars(ArrayTy->getElementType());
+  FieldBaseSize =
+  llvm::ConstantInt::get(ResType, BaseSize.getQuantity(), IsSigned);
+}
   }
 
   //  size_t count = (size_t) ptr->count;
@@ -1376,12 +1400,6 @@ CodeGenFunction::emitCountedByMemberSize(const Expr *E, 
llvm::Value *EmittedE,
 llvm::ConstantInt::get(ResType, Size.getKnownMinValue() / CharWidth);
 
 if (Idx) { // Option (4) '&ptr->field_array[idx]'
-  //  size_t field_base_size = sizeof (*ptr->field_array);
-  const ArrayType *ArrayTy = Ctx.getAsArrayType(FieldTy);
-  CharUnits BaseSize = Ctx.getTypeSizeInChars(ArrayTy->getElementType());
-  auto *FieldBaseSize =
-  llvm::ConstantInt::get(ResType, BaseSize.getQuantity(), IsSigned);
-
   //  field_offset += index * field_base_size;
   Value *Mul = Builder.CreateMul(Index, FieldBaseSize, "field_offset",
  !IsSigned, IsSigned);

>From c79f5a6f828be21910fb8a86b835474206786185 Mon Sep 17 00:00:00 2001
From: Bill Wendling 
Date: Fri, 31 Jan 2025 16:05:18 -0800
Subject: [PATCH 2/4] Add testcases.

---
 clang/test/CodeGen/attr-counted-by-bug.c | 85 
 1 file changed, 85 insertions(+)
 create mode 100644 clang/test/CodeGen/attr-counted-by-bug.c

diff --git a/clang/test/CodeGen/attr-counted-by-bug.c 
b/clang/test/CodeGen/attr-counted-by-bug.c
new file mode 100644
index 000..6cf1e3cbbdc001b
--- /dev/null
+++ b/clang/test/CodeGen/attr-counted-by-bug.c
@@ -0,0 +1,85 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --version 5
+// RUN: %clang_cc1 -triple aarch64-unknown-linux-gnu -DCOUNTED_BY -O2 -Wall 
-Wno-int-conversion -fsanitize=array-bounds,object-size,local-bounds 
-fstrict-flex-arrays=3 -emit-llvm -o - %s | FileCheck 
--check-prefix=SANITIZE-WITH-ATTR %s
+// RUN: %clang_cc1 -triple aarch64-unknown-linux-gnu -DCOUNTED_BY -O2 -Wall 
-Wno-int-conversion -fsanitize=array-bounds,object-size,local-bounds 
-fstrict-flex-arrays=3 -emit-llvm -o - %s | FileCheck 
--check-prefix=NO-SANITIZE-WITH-ATTR %s
+// RUN: %clang_cc1 -triple aarch64-unknown-linux-gnu -O2 -Wall 
-Wno-int-conversion -fsanitize=array-bounds,object-size,local-bounds 
-fstrict-flex-arrays=3 -emit-llvm -o - %s | FileCheck 
--check-prefix=SANITIZE-WITHOUT-ATTR %s
+// RUN: %clang_cc1 -triple aarch64-unknown-linux-gnu -O2 -Wall 
-Wno-int-conversion -fsanitize=array-bounds,object-size,local-bounds 
-fstrict-flex-arrays=3 -emit-llvm -o - %s | FileCheck 
--check-prefix=NO-SANITIZE-WITHOUT-ATTR %s
+
+// See https://github.com/llvm/llvm-project/pull/122198#issuecomment-2627868702
+
+#if !__has_attribute(counted_by)
+#error "has attribute broken"
+#endif
+
+#ifdef COUNTED_BY
+#define __counted_by(member)   __attribute__((__counted_by__(member)))
+#else
+#define __counted_by(member)
+#endif
+
+#define __bdos(P)  __builtin_dynamic_object_size(P, 0)
+
+typedef long unsigned int size_t;
+
+struct test1_struct {
+  int a;
+  char *b;
+  char c[] __counted_by(a);
+} d;
+
+// SANITIZE-WITH-ATTR-LABEL: define dso_local i64 @test1(
+// SANITIZE-WITH-

[clang] [HLSL] Make memory representation of boolean vectors in HLSL, vectors of i32. Add support for boolean swizzling. (PR #123977)

2025-02-03 Thread Sarah Spall via cfe-commits


@@ -2016,8 +2016,9 @@ TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const 
{
   case Type::Vector: {
 const auto *VT = cast(T);
 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
-Width = VT->isExtVectorBoolType() ? VT->getNumElements()
-  : EltInfo.Width * VT->getNumElements();
+Width = (VT->isExtVectorBoolType() && !getLangOpts().HLSL)
+? VT->getNumElements()
+: EltInfo.Width * VT->getNumElements();

spall wrote:

EltInfo.Width should be the size of the Element type in the vector, and that is 
set to be an i32 in CodeGenTypes. If that changed in the future to be an 
integer of a different size, this would still be correct.

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


[clang] [Clang][counted_by] Don't treat a __bdos argument as an array if it isn't (PR #125298)

2025-02-03 Thread Bill Wendling via cfe-commits


@@ -0,0 +1,85 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --version 5
+// RUN: %clang_cc1 -triple aarch64-unknown-linux-gnu -DCOUNTED_BY -O2 -Wall 
-Wno-int-conversion -fsanitize=array-bounds,object-size,local-bounds 
-fstrict-flex-arrays=3 -emit-llvm -o - %s | FileCheck 
--check-prefix=SANITIZE-WITH-ATTR %s
+// RUN: %clang_cc1 -triple aarch64-unknown-linux-gnu -DCOUNTED_BY -O2 -Wall 
-Wno-int-conversion -fsanitize=array-bounds,object-size,local-bounds 
-fstrict-flex-arrays=3 -emit-llvm -o - %s | FileCheck 
--check-prefix=NO-SANITIZE-WITH-ATTR %s
+// RUN: %clang_cc1 -triple aarch64-unknown-linux-gnu -O2 -Wall 
-Wno-int-conversion -fsanitize=array-bounds,object-size,local-bounds 
-fstrict-flex-arrays=3 -emit-llvm -o - %s | FileCheck 
--check-prefix=SANITIZE-WITHOUT-ATTR %s
+// RUN: %clang_cc1 -triple aarch64-unknown-linux-gnu -O2 -Wall 
-Wno-int-conversion -fsanitize=array-bounds,object-size,local-bounds 
-fstrict-flex-arrays=3 -emit-llvm -o - %s | FileCheck 
--check-prefix=NO-SANITIZE-WITHOUT-ATTR %s
+
+// See https://github.com/llvm/llvm-project/pull/122198#issuecomment-2627868702
+
+#if !__has_attribute(counted_by)
+#error "has attribute broken"
+#endif
+
+#ifdef COUNTED_BY
+#define __counted_by(member)   __attribute__((__counted_by__(member)))
+#else
+#define __counted_by(member)
+#endif
+
+#define __bdos(P)  __builtin_dynamic_object_size(P, 0)
+
+typedef long unsigned int size_t;
+
+struct test1_struct {
+  int a;
+  char *b;
+  char c[] __counted_by(a);
+} d;
+
+// SANITIZE-WITH-ATTR-LABEL: define dso_local i64 @test1(
+// SANITIZE-WITH-ATTR-SAME: ) local_unnamed_addr #[[ATTR0:[0-9]+]] {
+// SANITIZE-WITH-ATTR-NEXT:  [[ENTRY:.*:]]
+// SANITIZE-WITH-ATTR-NEXT:ret i64 -1
+//
+// NO-SANITIZE-WITH-ATTR-LABEL: define dso_local i64 @test1(
+// NO-SANITIZE-WITH-ATTR-SAME: ) local_unnamed_addr #[[ATTR0:[0-9]+]] {
+// NO-SANITIZE-WITH-ATTR-NEXT:  [[ENTRY:.*:]]
+// NO-SANITIZE-WITH-ATTR-NEXT:ret i64 -1
+//
+// SANITIZE-WITHOUT-ATTR-LABEL: define dso_local i64 @test1(
+// SANITIZE-WITHOUT-ATTR-SAME: ) local_unnamed_addr #[[ATTR0:[0-9]+]] {
+// SANITIZE-WITHOUT-ATTR-NEXT:  [[ENTRY:.*:]]
+// SANITIZE-WITHOUT-ATTR-NEXT:ret i64 -1
+//
+// NO-SANITIZE-WITHOUT-ATTR-LABEL: define dso_local i64 @test1(
+// NO-SANITIZE-WITHOUT-ATTR-SAME: ) local_unnamed_addr #[[ATTR0:[0-9]+]] {
+// NO-SANITIZE-WITHOUT-ATTR-NEXT:  [[ENTRY:.*:]]
+// NO-SANITIZE-WITHOUT-ATTR-NEXT:ret i64 -1
+//
+size_t test1(void) {
+  return __builtin_dynamic_object_size(d.b[4], 0);
+}
+
+typedef struct {
+  char __padding[0];
+} spinlock_t;
+struct {
+  int priv_len;
+  spinlock_t addr_list_lock;
+  char *dev_addr;
+  char priv[] __attribute__((__counted_by__(priv_len)));
+} x;
+
+// SANITIZE-WITH-ATTR-LABEL: define dso_local i64 
@falcon_reconfigure_xmac_core(

bwendling wrote:

Oops! Done.

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


[clang] [C++20][Modules][Serialization] Delay marking pending incomplete decl chains until the end of `finishPendingActions`. (PR #121245)

2025-02-03 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder 
`openmp-offload-amdgpu-runtime` running on `omp-vega20-0` while building 
`clang` at step 7 "Add check check-offload".

Full details are available at: 
https://lab.llvm.org/buildbot/#/builders/30/builds/15158


Here is the relevant piece of the build log for the reference

```
Step 7 (Add check check-offload) failure: test (failure)
 TEST 'libomptarget :: amdgcn-amd-amdhsa :: 
api/omp_host_call.c' FAILED 
Exit Code: 2

Command Output (stdout):
--
# RUN: at line 1
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/./bin/clang 
-fopenmp-I 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.src/offload/test -I 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/openmp/runtime/src
 -L 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload
 -L /home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/./lib -L 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/openmp/runtime/src
  -nogpulib 
-Wl,-rpath,/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload
 
-Wl,-rpath,/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/openmp/runtime/src
 -Wl,-rpath,/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/./lib 
 -fopenmp-targets=amdgcn-amd-amdhsa 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.src/offload/test/api/omp_host_call.c
 -o 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload/test/amdgcn-amd-amdhsa/api/Output/omp_host_call.c.tmp
 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/./lib/libomptarget.devicertl.a
 && 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload/test/amdgcn-amd-amdhsa/api/Output/omp_host_call.c.tmp
 | 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/./bin/FileCheck 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.src/offload/test/api/omp_host_call.c
# executed command: 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/./bin/clang 
-fopenmp -I 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.src/offload/test -I 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/openmp/runtime/src
 -L 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload
 -L /home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/./lib -L 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/openmp/runtime/src
 -nogpulib 
-Wl,-rpath,/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload
 
-Wl,-rpath,/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/openmp/runtime/src
 -Wl,-rpath,/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/./lib 
-fopenmp-targets=amdgcn-amd-amdhsa 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.src/offload/test/api/omp_host_call.c
 -o 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload/test/amdgcn-amd-amdhsa/api/Output/omp_host_call.c.tmp
 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/./lib/libomptarget.devicertl.a
# note: command had no output on stdout or stderr
# executed command: 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload/test/amdgcn-amd-amdhsa/api/Output/omp_host_call.c.tmp
# note: command had no output on stdout or stderr
# error: command failed with exit status: -11
# executed command: 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/./bin/FileCheck 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.src/offload/test/api/omp_host_call.c
# .---command stderr
# | FileCheck error: '' is empty.
# | FileCheck command line:  
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.build/./bin/FileCheck 
/home/ompworker/bbot/openmp-offload-amdgpu-runtime/llvm.src/offload/test/api/omp_host_call.c
# `-
# error: command failed with exit status: 2

--




```



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


[clang] Add clang atomic control options and attribute (PR #114841)

2025-02-03 Thread Erich Keane via cfe-commits


@@ -1096,6 +1100,177 @@ inline void FPOptions::applyChanges(FPOptionsOverride 
FPO) {
   *this = FPO.applyOverrides(*this);
 }
 
+/// Atomic control options
+class AtomicOptionsOverride;
+class AtomicOptions {
+public:
+  using storage_type = uint16_t;
+
+  static constexpr unsigned StorageBitSize = 8 * sizeof(storage_type);
+
+  static constexpr storage_type FirstShift = 0, FirstWidth = 0;
+#define OPTION(NAME, STR, TYPE, WIDTH, PREVIOUS)   
\
+  static constexpr storage_type NAME##Shift =  
\
+  PREVIOUS##Shift + PREVIOUS##Width;   
\
+  static constexpr storage_type NAME##Width = WIDTH;   
\
+  static constexpr storage_type NAME##Mask = ((1 << NAME##Width) - 1)  
\
+ << NAME##Shift;
+#include "clang/Basic/AtomicOptions.def"
+
+  static constexpr storage_type TotalWidth = 0
+#define OPTION(NAME, STR, TYPE, WIDTH, PREVIOUS) +WIDTH

erichkeane wrote:

This whole thing just seems too cute for me.  Could we instead generate this as 
a type with bitfields, so that only the width is important/necessary? 

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


[clang] Add clang atomic control options and attribute (PR #114841)

2025-02-03 Thread Erich Keane via cfe-commits


@@ -1096,6 +1100,177 @@ inline void FPOptions::applyChanges(FPOptionsOverride 
FPO) {
   *this = FPO.applyOverrides(*this);
 }
 
+/// Atomic control options
+class AtomicOptionsOverride;
+class AtomicOptions {
+public:
+  using storage_type = uint16_t;
+
+  static constexpr unsigned StorageBitSize = 8 * sizeof(storage_type);
+
+  static constexpr storage_type FirstShift = 0, FirstWidth = 0;
+#define OPTION(NAME, STR, TYPE, WIDTH, PREVIOUS)   
\

erichkeane wrote:

This `PREVIOUS` is incredibly error-prone, and IMO, something we shouldn't do 
(at least manually).  I'd perhaps be ok with tablegen for this one, but 
frankly, I'm not convinced it is necessary.  

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


[clang] Add clang atomic control options and attribute (PR #114841)

2025-02-03 Thread Erich Keane via cfe-commits


@@ -5958,6 +5968,58 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
 
   RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA);
 
+  if (Arg *AtomicArg = Args.getLastArg(options::OPT_fatomic_EQ)) {

erichkeane wrote:

IMO, we need a separate function for this, given how complicated this is.  
WHICH also makes me wonder; why are we letting this be this complicated.  DO we 
do something similar/that would be sufficient for other flags?  This whole 
thing below is really getting complicated.

ALSO, we need to make sure these round-trip, so make sure that they go th rough 
the 'Render' stuff correctly.

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


[clang] Add clang atomic control options and attribute (PR #114841)

2025-02-03 Thread Erich Keane via cfe-commits


@@ -764,6 +764,73 @@ void Parser::ParseGNUAttributeArgs(
ScopeLoc, Form);
 }
 
+void Parser::ParseAtomicAttribute(

erichkeane wrote:

I'm very much beginning to dislike the syntax for this, if it needs this much 
special handling.  We shoudl find a way to spell this attribute in a way that 
WORKS with our existing attribute formats.  Else this becomes REALLY difficult 
for other compilers to ignore.

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


[clang] Add clang atomic control options and attribute (PR #114841)

2025-02-03 Thread Erich Keane via cfe-commits


@@ -0,0 +1,19 @@
+//===--- AtomicOptions.def - Atomic Options database -*- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+// This file defines the Atomic language options. Users of this file
+// must define the OPTION macro to make use of this information.
+#ifndef OPTION

erichkeane wrote:

```suggestion
#ifndef ATOMIC_OPTION
```

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


[clang] [HLSL] Make memory representation of boolean vectors in HLSL, vectors of i32. Add support for boolean swizzling. (PR #123977)

2025-02-03 Thread Eli Friedman via cfe-commits


@@ -1984,6 +1984,15 @@ llvm::Constant 
*ConstantEmitter::emitForMemory(CodeGenModule &CGM,
 return Res;
   }
 
+  // In HLSL bool vectors are stored in memory as a vector of i32
+  if (destType->isExtVectorBoolType() && CGM.getContext().getLangOpts().HLSL) {
+llvm::Type *boolVecTy = CGM.getTypes().ConvertTypeForMem(destType);

efriedma-quic wrote:

Do we need special handling for non-hlsl ext-bool-vector types?

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


[clang] [HLSL] Make memory representation of boolean vectors in HLSL, vectors of i32. Add support for boolean swizzling. (PR #123977)

2025-02-03 Thread Eli Friedman via cfe-commits


@@ -2016,8 +2016,9 @@ TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const 
{
   case Type::Vector: {
 const auto *VT = cast(T);
 TypeInfo EltInfo = getTypeInfo(VT->getElementType());
-Width = VT->isExtVectorBoolType() ? VT->getNumElements()
-  : EltInfo.Width * VT->getNumElements();
+Width = (VT->isExtVectorBoolType() && !getLangOpts().HLSL)

efriedma-quic wrote:

Maybe we should add VectorType::isPackedBoolType() or something like that?  
Then we can refactor the code so it doesn't explicitly check for HLSL all over 
the place.

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


[clang] [Clang] Make `-Xarch_` handling generic for all toolchains (PR #125421)

2025-02-03 Thread Artem Belevich via cfe-commits

Artem-B wrote:

> Summary: Currently, `-Xarch_` is used to forward argument specially to 
> certain toolchains. Currently, this is only supported by the Darwin 
> toolchain. We want to be able to use this generically, and for offloading 
> too. This patch moves the handling out of the Darwin Toolchain and places it 
> in the `getArgsForToolchain` helper which is run before the arguments get 
> passed to the tools.

I think this could use some editing. `-Xarch` is intended to set flags per 
*target*. Same toolchain may handle more than one target. Perhaps rephrase 
along the lines of "forward argument to the toolchain used for the given target 
architecture"?

> this is only supported by the Darwin toolchain.

This is the confusing part. I'm pretty sure `-Xarch_host` `-Xarch_device` and 
variety of `-Xarch_{gfx,sm}..` variants are also supported by HIP/Cuda 
toolchains right now. 

IMO, a better way to describe the situation is that MachO is the last remaining 
special case implementation of Xarch and the patch folds it into a common 
`Xarch` handling that's already used by offloading toolchains.


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


[clang] [Clang] disallow attributes on void parameters (PR #124920)

2025-02-03 Thread Oleksandr T. via cfe-commits

https://github.com/a-tarasyuk updated 
https://github.com/llvm/llvm-project/pull/124920

>From bd731e4be65fc9c1746aa6a8f63d206eb54bb2be Mon Sep 17 00:00:00 2001
From: Oleksandr T 
Date: Wed, 29 Jan 2025 15:17:06 +0200
Subject: [PATCH 1/9] [Clang] disallow attributes on void parameters

---
 clang/docs/ReleaseNotes.rst| 2 ++
 clang/lib/Parse/ParseDecl.cpp  | 7 +++
 clang/test/Parser/cxx0x-attributes.cpp | 9 +
 3 files changed, 18 insertions(+)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 7fafe2807bd388..0c87e52007d546 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -100,6 +100,8 @@ Removed Compiler Flags
 Attribute Changes in Clang
 --
 
+- Clang now disallows the use of attributes on void parameters. (#GH108819)
+
 Improvements to Clang's diagnostics
 ---
 
diff --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp
index f136d5007e8a5f..0b88dd4449b1e2 100644
--- a/clang/lib/Parse/ParseDecl.cpp
+++ b/clang/lib/Parse/ParseDecl.cpp
@@ -7986,6 +7986,13 @@ void Parser::ParseParameterDeclarationClause(
 if (getLangOpts().HLSL)
   MaybeParseHLSLAnnotations(DS.getAttributes());
 
+if (ParmDeclarator.getIdentifier() == nullptr &&
+ParmDeclarator.getDeclarationAttributes().size() &&
+ParmDeclarator.getDeclSpec().getTypeSpecType() == DeclSpec::TST_void) {
+  SourceRange AttrRange = ParmDeclarator.getDeclarationAttributes().Range;
+  Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed) << 
AttrRange;
+}
+
 if (Tok.is(tok::kw_requires)) {
   // User tried to define a requires clause in a parameter declaration,
   // which is surely not a function declaration.
diff --git a/clang/test/Parser/cxx0x-attributes.cpp 
b/clang/test/Parser/cxx0x-attributes.cpp
index fad3010c98b9c2..13fcdd142fa841 100644
--- a/clang/test/Parser/cxx0x-attributes.cpp
+++ b/clang/test/Parser/cxx0x-attributes.cpp
@@ -453,3 +453,12 @@ namespace P2361 {
 }
 
 alignas(int) struct AlignAsAttribute {}; // expected-error {{misplaced 
attributes; expected attributes here}}
+
+namespace GH108819 {
+void a([[maybe_unused]] void) {} // expected-error {{an 
attribute list cannot appear here}} \
+ // expected-warning {{use of 
the 'maybe_unused' attribute is a C++17 extension}}
+void b([[deprecated]] void) {}   // expected-error {{an 
attribute list cannot appear here}} \
+ // expected-warning {{use of 
the 'deprecated' attribute is a C++14 extension}}
+void c([[clang::lifetimebound]] void) {} // expected-error {{an 
attribute list cannot appear here}}
+void d([[clang::annotate("a", "b", 1)]] void) {} // expected-error {{an 
attribute list cannot appear here}}
+}

>From 063f76730ebfd289f5340d0d8477a43a5ea965c2 Mon Sep 17 00:00:00 2001
From: Oleksandr T 
Date: Wed, 29 Jan 2025 15:54:48 +0200
Subject: [PATCH 2/9] remove unnecessary name check

---
 clang/lib/Parse/ParseDecl.cpp | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)

diff --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp
index 0b88dd4449b1e2..934c16c9591520 100644
--- a/clang/lib/Parse/ParseDecl.cpp
+++ b/clang/lib/Parse/ParseDecl.cpp
@@ -7986,8 +7986,7 @@ void Parser::ParseParameterDeclarationClause(
 if (getLangOpts().HLSL)
   MaybeParseHLSLAnnotations(DS.getAttributes());
 
-if (ParmDeclarator.getIdentifier() == nullptr &&
-ParmDeclarator.getDeclarationAttributes().size() &&
+if (ParmDeclarator.getDeclarationAttributes().size() &&
 ParmDeclarator.getDeclSpec().getTypeSpecType() == DeclSpec::TST_void) {
   SourceRange AttrRange = ParmDeclarator.getDeclarationAttributes().Range;
   Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed) << 
AttrRange;

>From 3f3431513ad59111794953d27e64608b3ce2e6e1 Mon Sep 17 00:00:00 2001
From: Oleksandr T 
Date: Wed, 29 Jan 2025 16:07:18 +0200
Subject: [PATCH 3/9] use empty instead of size

---
 clang/lib/Parse/ParseDecl.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp
index 934c16c9591520..963b59565953d4 100644
--- a/clang/lib/Parse/ParseDecl.cpp
+++ b/clang/lib/Parse/ParseDecl.cpp
@@ -7986,7 +7986,7 @@ void Parser::ParseParameterDeclarationClause(
 if (getLangOpts().HLSL)
   MaybeParseHLSLAnnotations(DS.getAttributes());
 
-if (ParmDeclarator.getDeclarationAttributes().size() &&
+if (!ParmDeclarator.getDeclarationAttributes().empty() &&
 ParmDeclarator.getDeclSpec().getTypeSpecType() == DeclSpec::TST_void) {
   SourceRange AttrRange = ParmDeclarator.getDeclarationAttributes().Range;
   Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed) << 
AttrRange;

>From 9919006df9ec32023b2bf179b72f9ebaf977bd08 Mon Sep 17 00:0

[clang] [Clang] Make `-Xarch_` handling generic for all toolchains (PR #125421)

2025-02-03 Thread Joseph Huber via cfe-commits


@@ -1115,14 +1117,13 @@ def fno_convergent_functions : Flag<["-"], 
"fno-convergent-functions">,
 
 // Common offloading options
 let Group = offload_Group in {
-def offload_arch_EQ : Joined<["--"], "offload-arch=">, Flags<[NoXarchOption]>,

jhuber6 wrote:

I don't think there's actually a way to do that unfortunately. When we query 
the like of active `--offload-arch` kinds we don't have a bound architecture 
yet. There's no way to know if the string *is* a CPU argument. So, the only 
case would be to reject usage of this altogether, which is clearly not useful 
because we have `-Xopenmp-target=` which is just a dumber version of this 
handling.

So, there's no way to detect the usage here and rejecting it flatly isn't 
desirable. The current behavior is that `-Xarch_gfx90a --offload-arch=gfx90a` 
will be unused.

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


[clang] 070c338 - Fix "not all control paths return a value" warning; NFC

2025-02-03 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2025-02-03T15:15:33-05:00
New Revision: 070c3386618f1edffefe6519dc2741bba7938ae9

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

LOG: Fix "not all control paths return a value" warning; NFC

Added: 


Modified: 
clang/include/clang/Basic/OpenACCKinds.h

Removed: 




diff  --git a/clang/include/clang/Basic/OpenACCKinds.h 
b/clang/include/clang/Basic/OpenACCKinds.h
index 739422caad6459..c2d7732123ef2b 100644
--- a/clang/include/clang/Basic/OpenACCKinds.h
+++ b/clang/include/clang/Basic/OpenACCKinds.h
@@ -188,6 +188,7 @@ inline StreamTy &printOpenACCAtomicKind(StreamTy &Out, 
OpenACCAtomicKind AK) {
   case OpenACCAtomicKind::None:
 return Out << "";
   }
+  llvm_unreachable("unknown atomic kind");
 }
 inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &Out,
  OpenACCAtomicKind AK) {



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


[clang] [Clang] disallow attributes on void parameters (PR #124920)

2025-02-03 Thread Oleksandr T. via cfe-commits

https://github.com/a-tarasyuk updated 
https://github.com/llvm/llvm-project/pull/124920

>From bd731e4be65fc9c1746aa6a8f63d206eb54bb2be Mon Sep 17 00:00:00 2001
From: Oleksandr T 
Date: Wed, 29 Jan 2025 15:17:06 +0200
Subject: [PATCH 1/9] [Clang] disallow attributes on void parameters

---
 clang/docs/ReleaseNotes.rst| 2 ++
 clang/lib/Parse/ParseDecl.cpp  | 7 +++
 clang/test/Parser/cxx0x-attributes.cpp | 9 +
 3 files changed, 18 insertions(+)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 7fafe2807bd3883..0c87e52007d5463 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -100,6 +100,8 @@ Removed Compiler Flags
 Attribute Changes in Clang
 --
 
+- Clang now disallows the use of attributes on void parameters. (#GH108819)
+
 Improvements to Clang's diagnostics
 ---
 
diff --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp
index f136d5007e8a5f0..0b88dd4449b1e28 100644
--- a/clang/lib/Parse/ParseDecl.cpp
+++ b/clang/lib/Parse/ParseDecl.cpp
@@ -7986,6 +7986,13 @@ void Parser::ParseParameterDeclarationClause(
 if (getLangOpts().HLSL)
   MaybeParseHLSLAnnotations(DS.getAttributes());
 
+if (ParmDeclarator.getIdentifier() == nullptr &&
+ParmDeclarator.getDeclarationAttributes().size() &&
+ParmDeclarator.getDeclSpec().getTypeSpecType() == DeclSpec::TST_void) {
+  SourceRange AttrRange = ParmDeclarator.getDeclarationAttributes().Range;
+  Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed) << 
AttrRange;
+}
+
 if (Tok.is(tok::kw_requires)) {
   // User tried to define a requires clause in a parameter declaration,
   // which is surely not a function declaration.
diff --git a/clang/test/Parser/cxx0x-attributes.cpp 
b/clang/test/Parser/cxx0x-attributes.cpp
index fad3010c98b9c28..13fcdd142fa841f 100644
--- a/clang/test/Parser/cxx0x-attributes.cpp
+++ b/clang/test/Parser/cxx0x-attributes.cpp
@@ -453,3 +453,12 @@ namespace P2361 {
 }
 
 alignas(int) struct AlignAsAttribute {}; // expected-error {{misplaced 
attributes; expected attributes here}}
+
+namespace GH108819 {
+void a([[maybe_unused]] void) {} // expected-error {{an 
attribute list cannot appear here}} \
+ // expected-warning {{use of 
the 'maybe_unused' attribute is a C++17 extension}}
+void b([[deprecated]] void) {}   // expected-error {{an 
attribute list cannot appear here}} \
+ // expected-warning {{use of 
the 'deprecated' attribute is a C++14 extension}}
+void c([[clang::lifetimebound]] void) {} // expected-error {{an 
attribute list cannot appear here}}
+void d([[clang::annotate("a", "b", 1)]] void) {} // expected-error {{an 
attribute list cannot appear here}}
+}

>From 063f76730ebfd289f5340d0d8477a43a5ea965c2 Mon Sep 17 00:00:00 2001
From: Oleksandr T 
Date: Wed, 29 Jan 2025 15:54:48 +0200
Subject: [PATCH 2/9] remove unnecessary name check

---
 clang/lib/Parse/ParseDecl.cpp | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)

diff --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp
index 0b88dd4449b1e28..934c16c95915203 100644
--- a/clang/lib/Parse/ParseDecl.cpp
+++ b/clang/lib/Parse/ParseDecl.cpp
@@ -7986,8 +7986,7 @@ void Parser::ParseParameterDeclarationClause(
 if (getLangOpts().HLSL)
   MaybeParseHLSLAnnotations(DS.getAttributes());
 
-if (ParmDeclarator.getIdentifier() == nullptr &&
-ParmDeclarator.getDeclarationAttributes().size() &&
+if (ParmDeclarator.getDeclarationAttributes().size() &&
 ParmDeclarator.getDeclSpec().getTypeSpecType() == DeclSpec::TST_void) {
   SourceRange AttrRange = ParmDeclarator.getDeclarationAttributes().Range;
   Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed) << 
AttrRange;

>From 3f3431513ad59111794953d27e64608b3ce2e6e1 Mon Sep 17 00:00:00 2001
From: Oleksandr T 
Date: Wed, 29 Jan 2025 16:07:18 +0200
Subject: [PATCH 3/9] use empty instead of size

---
 clang/lib/Parse/ParseDecl.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp
index 934c16c95915203..963b59565953d45 100644
--- a/clang/lib/Parse/ParseDecl.cpp
+++ b/clang/lib/Parse/ParseDecl.cpp
@@ -7986,7 +7986,7 @@ void Parser::ParseParameterDeclarationClause(
 if (getLangOpts().HLSL)
   MaybeParseHLSLAnnotations(DS.getAttributes());
 
-if (ParmDeclarator.getDeclarationAttributes().size() &&
+if (!ParmDeclarator.getDeclarationAttributes().empty() &&
 ParmDeclarator.getDeclSpec().getTypeSpecType() == DeclSpec::TST_void) {
   SourceRange AttrRange = ParmDeclarator.getDeclarationAttributes().Range;
   Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed) << 
AttrRange;

>From 9919006df9ec32023b2bf179b72f9ebaf977bd08 Mon S

[clang] [compiler-rt] [profile] Add `%b` `LLVM_PROFILE_FILE` option for binary ID (PR #123963)

2025-02-03 Thread David Li via cfe-commits


@@ -855,6 +856,15 @@ static int parseFilenamePattern(const char *FilenamePat,
 FilenamePat);
   return -1;
 }
+  } else if (FilenamePat[I] == 'b') {
+if (!NumBinaryIds++) {
+  if (__llvm_write_binary_ids(NULL) <= 0) {

david-xl wrote:

Add a code comment to indicate it reads the size of the binary ids.

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


[clang] [compiler-rt] [profile] Add `%b` `LLVM_PROFILE_FILE` option for binary ID (PR #123963)

2025-02-03 Thread David Li via cfe-commits


@@ -0,0 +1,37 @@
+// REQUIRES: linux
+// RUN: split-file %s %t.dir
+// RUN: %clang_profgen -Wl,--build-id=sha1 -o %t.dir/foo %t.dir/foo.c
+// RUN: %clang_profgen -Wl,--build-id=sha1 -o %t.dir/bar %t.dir/bar.c
+
+// Check that foo and bar have the same signatures.
+// RUN: rm -rf %t.profdir
+// RUN: env LLVM_PROFILE_FILE=%t.profdir/%m.profraw %run %t.dir/foo
+// RUN: env LLVM_PROFILE_FILE=%t.profdir/%m.profraw %run %t.dir/bar 2>&1 | 
FileCheck %s --check-prefix=MERGE-ERROR
+
+// Check that foo and bar have different binary IDs.
+// RUN: rm -rf %t.profdir %t.profdata
+// RUN: env LLVM_PROFILE_FILE=%t.profdir/%b.profraw %run %t.dir/foo
+// RUN: env LLVM_PROFILE_FILE=%t.profdir/%b.profraw %run %t.dir/bar
+// RUN: llvm-profdata merge -o %t.profdata %t.profdir
+// RUN: llvm-profdata show %t.profdata | FileCheck %s --check-prefix=BINARY-ID

david-xl wrote:

check the binary ids after merging?

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


[clang] [Clang][counted-by] Bail out of visitor for LValueToRValue cast (PR #125571)

2025-02-03 Thread Bill Wendling via cfe-commits

https://github.com/bwendling updated 
https://github.com/llvm/llvm-project/pull/125571

>From f5086e8af7b370aae43bee98493ded9c9f7aa9b2 Mon Sep 17 00:00:00 2001
From: Bill Wendling 
Date: Mon, 3 Feb 2025 12:15:07 -0800
Subject: [PATCH 1/2] [Clang][counted-by] Bail out of visitor for
 LValueToRValue cast

An LValueToRValue cast shouldn't be ignored, so bail out of the visitor
if we encounter one.
---
 clang/lib/CodeGen/CGBuiltin.cpp | 18 ++
 1 file changed, 10 insertions(+), 8 deletions(-)

diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 11fa295dad9524c..339bcd14c5bc8c9 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -1055,20 +1055,20 @@ namespace {
 /// StructFieldAccess is a simple visitor class to grab the first MemberExpr
 /// from an Expr. It records any ArraySubscriptExpr we meet along the way.
 class StructFieldAccess
-: public ConstStmtVisitor {
+: public ConstStmtVisitor {
   bool AddrOfSeen = false;
 
 public:
   const ArraySubscriptExpr *ASE = nullptr;
 
-  const MemberExpr *VisitMemberExpr(const MemberExpr *E) {
+  const Expr *VisitMemberExpr(const MemberExpr *E) {
 if (AddrOfSeen && E->getType()->isArrayType())
   // Avoid forms like '&ptr->array'.
   return nullptr;
 return E;
   }
 
-  const MemberExpr *VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
+  const Expr *VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
 if (ASE)
   // We don't support multiple subscripts.
   return nullptr;
@@ -1077,17 +1077,19 @@ class StructFieldAccess
 ASE = E;
 return Visit(E->getBase());
   }
-  const MemberExpr *VisitCastExpr(const CastExpr *E) {
+  const Expr *VisitCastExpr(const CastExpr *E) {
+if (E->getCastKind() == CK_LValueToRValue)
+  return E;
 return Visit(E->getSubExpr());
   }
-  const MemberExpr *VisitParenExpr(const ParenExpr *E) {
+  const Expr *VisitParenExpr(const ParenExpr *E) {
 return Visit(E->getSubExpr());
   }
-  const MemberExpr *VisitUnaryAddrOf(const clang::UnaryOperator *E) {
+  const Expr *VisitUnaryAddrOf(const clang::UnaryOperator *E) {
 AddrOfSeen = true;
 return Visit(E->getSubExpr());
   }
-  const MemberExpr *VisitUnaryDeref(const clang::UnaryOperator *E) {
+  const Expr *VisitUnaryDeref(const clang::UnaryOperator *E) {
 AddrOfSeen = false;
 return Visit(E->getSubExpr());
   }
@@ -1188,7 +1190,7 @@ CodeGenFunction::emitCountedByMemberSize(const Expr *E, 
llvm::Value *EmittedE,
   // GCC does for consistency's sake.
 
   StructFieldAccess Visitor;
-  const MemberExpr *ME = Visitor.Visit(E);
+  const MemberExpr *ME = dyn_cast_if_present(Visitor.Visit(E));
   if (!ME)
 return nullptr;
 

>From 1da4577ca6f43b9b84afaf9b1d9aa9ccb2a293b6 Mon Sep 17 00:00:00 2001
From: Bill Wendling 
Date: Mon, 3 Feb 2025 16:15:23 -0800
Subject: [PATCH 2/2] Add testcase from a bug report.

---
 clang/test/CodeGen/attr-counted-by.c | 145 +--
 1 file changed, 91 insertions(+), 54 deletions(-)

diff --git a/clang/test/CodeGen/attr-counted-by.c 
b/clang/test/CodeGen/attr-counted-by.c
index feb6f1543985995..e85f3db1121afff 100644
--- a/clang/test/CodeGen/attr-counted-by.c
+++ b/clang/test/CodeGen/attr-counted-by.c
@@ -68,7 +68,7 @@ struct anon_struct {
 // SANITIZE-WITH-ATTR-NEXT:[[TMP1:%.*]] = icmp ult i64 [[IDXPROM]], 
[[TMP0]], !nosanitize [[META2]]
 // SANITIZE-WITH-ATTR-NEXT:br i1 [[TMP1]], label [[CONT3:%.*]], label 
[[HANDLER_OUT_OF_BOUNDS:%.*]], !prof [[PROF3:![0-9]+]], !nosanitize [[META2]]
 // SANITIZE-WITH-ATTR:   handler.out_of_bounds:
-// SANITIZE-WITH-ATTR-NEXT:tail call void 
@__ubsan_handle_out_of_bounds_abort(ptr nonnull @[[GLOB1:[0-9]+]], i64 
[[IDXPROM]]) #[[ATTR7:[0-9]+]], !nosanitize [[META2]]
+// SANITIZE-WITH-ATTR-NEXT:tail call void 
@__ubsan_handle_out_of_bounds_abort(ptr nonnull @[[GLOB1:[0-9]+]], i64 
[[IDXPROM]]) #[[ATTR8:[0-9]+]], !nosanitize [[META2]]
 // SANITIZE-WITH-ATTR-NEXT:unreachable, !nosanitize [[META2]]
 // SANITIZE-WITH-ATTR:   cont3:
 // SANITIZE-WITH-ATTR-NEXT:[[ARRAY:%.*]] = getelementptr inbounds nuw i8, 
ptr [[P]], i64 12
@@ -116,7 +116,7 @@ void test1(struct annotated *p, int index, int val) {
 // SANITIZE-WITH-ATTR-NEXT:[[TMP1:%.*]] = icmp ult i64 [[INDEX]], 
[[TMP0]], !nosanitize [[META2]]
 // SANITIZE-WITH-ATTR-NEXT:br i1 [[TMP1]], label [[CONT6:%.*]], label 
[[HANDLER_OUT_OF_BOUNDS:%.*]], !prof [[PROF3]], !nosanitize [[META2]]
 // SANITIZE-WITH-ATTR:   handler.out_of_bounds:
-// SANITIZE-WITH-ATTR-NEXT:tail call void 
@__ubsan_handle_out_of_bounds_abort(ptr nonnull @[[GLOB3:[0-9]+]], i64 
[[INDEX]]) #[[ATTR7]], !nosanitize [[META2]]
+// SANITIZE-WITH-ATTR-NEXT:tail call void 
@__ubsan_handle_out_of_bounds_abort(ptr nonnull @[[GLOB3:[0-9]+]], i64 
[[INDEX]]) #[[ATTR8]], !nosanitize [[META2]]
 // SANITIZE-WITH-ATTR-NEXT:unreachable, !nosanitize [[META2]]
 // SANITIZE-WITH-ATTR:   cont6:
 // SANI

[clang] [clang] print correct context for diagnostics suppressed by deduction (PR #125453)

2025-02-03 Thread Matheus Izvekov via cfe-commits


@@ -1909,7 +1909,19 @@ class Sema final : public SemaBase {
   /// '\#pragma clang attribute push' directives to the given declaration.
   void AddPragmaAttributes(Scope *S, Decl *D);
 
-  void PrintPragmaAttributeInstantiationPoint();
+  using DiagFuncRef =
+  llvm::function_ref;
+  auto getDefaultDiagFunc() {
+return [this](SourceLocation Loc, PartialDiagnostic PD) {
+  DiagnosticBuilder Builder(Diags.Report(Loc, PD.getDiagID()));

mizvekov wrote:

This bypasses a lot of the things `this->Diag(Loc, PD)` does, like SFINAE 
handling, ignoring notes attached to ignored diagnostics, adding instantiation 
context notes, and more, because we have already done them before storing the 
suppressed diagnostics, and we are just attaching notes to them.

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


[clang] [llvm] [HLSL] [DXIL] Implement the `AddUint64` HLSL function and the `UAddc` DXIL op (PR #125319)

2025-02-03 Thread Deric Cheung via cfe-commits


@@ -19105,6 +19105,51 @@ Value *CodeGenFunction::EmitHLSLBuiltinExpr(unsigned 
BuiltinID,
 return nullptr;
 
   switch (BuiltinID) {
+  case Builtin::BI__builtin_hlsl_adduint64: {

Icohedron wrote:

`__builtin_addc` was not able to be used to implement `AddUint64` in 
`hlsl_intrinsics.h` and (by extension) `hlsl_detail.h` because its `carryout` 
argument is a pointer (as documented 
[here](https://github.com/llvm/llvm-project/blob/main/clang/lib/CodeGen/CGBuiltin.cpp#L5508)).

Since pointers are not supported in HLSL, an error is emitted when running HLSL 
codegen tests with an example implementation like the following in 
`hlsl_intrinsics.h`.

```cpp
_HLSL_AVAILABILITY(shadermodel, 6.0)
const inline uint32_t2 AddUint64(uint32_t2 a, uint32_t2 b) {
  uint32_t carry;
  uint32_t low_sum = __builtin_addc(a.x, b.x, 0, &carry);
  uint32_t high_sum = __builtin_addc(a.y, b.y, carry, nullptr);
  return uint32_t2(low_sum, high_sum);
}
```

```
build/lib/clang/20/include/hlsl/hlsl_intrinsics.h:158:50: error: the '&' 
operator is unsupported in HLSL
  158 |   uint32_t low_sum = __builtin_addc(a.x, b.x, 0, &carry);
```


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


[clang] [clang] print correct context for diagnostics suppressed by deduction (PR #125453)

2025-02-03 Thread Matheus Izvekov via cfe-commits


@@ -1909,7 +1909,19 @@ class Sema final : public SemaBase {
   /// '\#pragma clang attribute push' directives to the given declaration.
   void AddPragmaAttributes(Scope *S, Decl *D);
 
-  void PrintPragmaAttributeInstantiationPoint();
+  using DiagFuncRef =
+  llvm::function_ref;
+  auto getDefaultDiagFunc() {
+return [this](SourceLocation Loc, PartialDiagnostic PD) {

mizvekov wrote:

Yeah I know, but nothing we are using takes it, so it doesn't buy much.

I am passing both things for consistency with existing practice, but I don't 
understand why we have PartialDiagnosticsAt if the PartialDiagnostic already 
has a SourceLocation. I may look into that at some point.

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


[clang] [compiler-rt] [Sanitizers] the access size (8 bytes) exceeds the max lock-free size (4 bytes) for 32-bit (PR #125388)

2025-02-03 Thread Vitaly Buka via cfe-commits

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

for compiler-rt/lib/sanitizer_common/CMakeLists.txt

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


[clang] [clang] print correct context for diagnostics suppressed by deduction (PR #125453)

2025-02-03 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/125453

>From ff34c10553ed645fc8277cb72247f6cb67a024e6 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Sun, 2 Feb 2025 23:47:15 -0300
Subject: [PATCH] [clang] print correct context for diagnostics suppressed by
 deduction

This patch makes it so the correct instantiation context is printed
for diagnostics suppessed by template argument deduction.

The context is saved along with the suppressed diagnostic, and
when the declaration they were attached to becomes used, we print
the correct context, instead of whatever context was at this point.
---
 clang/docs/ReleaseNotes.rst   |   3 +
 clang/include/clang/Sema/Sema.h   |  26 +-
 clang/lib/Sema/Sema.cpp   |  13 +-
 clang/lib/Sema/SemaAttr.cpp   |   6 +-
 clang/lib/Sema/SemaExpr.cpp   |   7 +-
 clang/lib/Sema/SemaTemplateInstantiate.cpp| 271 +-
 clang/test/CXX/drs/cwg0xx.cpp |   5 +
 clang/test/CXX/drs/cwg4xx.cpp |   3 +-
 .../CXX/temp/temp.arg/temp.arg.type/p2.cpp|   9 +-
 clang/test/SemaCXX/anonymous-struct.cpp   |   5 +-
 clang/test/SemaCXX/bool-increment-SFINAE.cpp  |   4 +-
 clang/test/SemaCXX/cxx98-compat-flags.cpp |   2 +
 clang/test/SemaCXX/cxx98-compat.cpp   |   2 +
 clang/test/SemaCXX/deprecated.cpp |   4 +-
 clang/test/SemaCXX/lambda-expressions.cpp |   2 +
 clang/test/SemaCXX/undefined-internal.cpp |   6 +-
 clang/test/SemaTemplate/recovery-crash.cpp|   1 +
 clang/test/SemaTemplate/temp_arg_nontype.cpp  |   1 +
 18 files changed, 209 insertions(+), 161 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 8be1ea2fb01455f..70c3b062d977177 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -128,6 +128,9 @@ Bug Fixes to Attribute Support
 Bug Fixes to C++ Support
 
 
+- Clang now prints the correct instantiation context for diagnostics suppressed
+  by template argument deduction.
+
 Bug Fixes to AST Handling
 ^
 
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 472a0e25adc9752..7d01dc1aa4c00bd 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -1909,7 +1909,19 @@ class Sema final : public SemaBase {
   /// '\#pragma clang attribute push' directives to the given declaration.
   void AddPragmaAttributes(Scope *S, Decl *D);
 
-  void PrintPragmaAttributeInstantiationPoint();
+  using DiagFuncRef =
+  llvm::function_ref;
+  auto getDefaultDiagFunc() {
+return [this](SourceLocation Loc, PartialDiagnostic PD) {
+  DiagnosticBuilder Builder(Diags.Report(Loc, PD.getDiagID()));
+  PD.Emit(Builder);
+};
+  }
+
+  void PrintPragmaAttributeInstantiationPoint(DiagFuncRef DiagFunc);
+  void PrintPragmaAttributeInstantiationPoint() {
+PrintPragmaAttributeInstantiationPoint(getDefaultDiagFunc());
+  }
 
   void DiagnoseUnterminatedPragmaAttribute();
 
@@ -13260,18 +13272,22 @@ class Sema final : public SemaBase {
   void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
   void popCodeSynthesisContext();
 
-  void PrintContextStack() {
+  void PrintContextStack(DiagFuncRef DiagFunc) {
 if (!CodeSynthesisContexts.empty() &&
 CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
-  PrintInstantiationStack();
+  PrintInstantiationStack(DiagFunc);
   LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
 }
 if (PragmaAttributeCurrentTargetDecl)
-  PrintPragmaAttributeInstantiationPoint();
+  PrintPragmaAttributeInstantiationPoint(DiagFunc);
   }
+  void PrintContextStack() { PrintContextStack(getDefaultDiagFunc()); }
   /// Prints the current instantiation stack through a series of
   /// notes.
-  void PrintInstantiationStack();
+  void PrintInstantiationStack(DiagFuncRef DiagFunc);
+  void PrintInstantiationStack() {
+PrintInstantiationStack(getDefaultDiagFunc());
+  }
 
   /// Determines whether we are currently in a context where
   /// template argument substitution failures are not considered
diff --git a/clang/lib/Sema/Sema.cpp b/clang/lib/Sema/Sema.cpp
index 9507d7602aa401a..33e2bd1e030513f 100644
--- a/clang/lib/Sema/Sema.cpp
+++ b/clang/lib/Sema/Sema.cpp
@@ -1654,11 +1654,20 @@ void Sema::EmitDiagnostic(unsigned DiagID, const 
DiagnosticBuilder &DB) {
 }
 
 case DiagnosticIDs::SFINAE_Suppress:
+  if (DiagnosticsEngine::Level Level = getDiagnostics().getDiagnosticLevel(
+  DiagInfo.getID(), DiagInfo.getLocation());
+  Level == DiagnosticsEngine::Ignored)
+return;
   // Make a copy of this suppressed diagnostic and store it with the
   // template-deduction information;
   if (*Info) {
-(*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
-  

[clang] Patch series to reapply #118734 and substantially improve it (PR #120534)

2025-02-03 Thread Chandler Carruth via cfe-commits

chandlerc wrote:

Thanks @rnk !

I've fixed the one style nit (doh!) and a few surrounding variables.

I'm working on rebasing everything now.

But one specific question: would you prefer me to land as a series of commits 
or a single squashed commit for the entire PR? I'm happy either way. My mild 
preference is to prefer the series of commits, but open to suggestions here.

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


[clang] [llvm] [llvm] Create() functions for ConvergenceControlInst (PR #125627)

2025-02-03 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 6303563b40f9d7896f0d44380f397560143da26b 
5d6d4fbbfabf5e33ec366ea113a0e6c93ba46bf4 --extensions h,cpp -- 
clang/lib/CodeGen/CGStmt.cpp llvm/include/llvm/IR/IntrinsicInst.h 
llvm/lib/IR/IntrinsicInst.cpp
``





View the diff from clang-format here.


``diff
diff --git a/llvm/include/llvm/IR/IntrinsicInst.h 
b/llvm/include/llvm/IR/IntrinsicInst.h
index ba7a0219eb..93750d6e38 100644
--- a/llvm/include/llvm/IR/IntrinsicInst.h
+++ b/llvm/include/llvm/IR/IntrinsicInst.h
@@ -1883,9 +1883,10 @@ public:
 return getIntrinsicID() == Intrinsic::experimental_convergence_loop;
   }
 
-  static ConvergenceControlInst* CreateAnchor(BasicBlock &BB);
-  static ConvergenceControlInst* CreateEntry(BasicBlock &BB);
-  static ConvergenceControlInst* CreateLoop(BasicBlock &BB, 
ConvergenceControlInst *Parent);
+  static ConvergenceControlInst *CreateAnchor(BasicBlock &BB);
+  static ConvergenceControlInst *CreateEntry(BasicBlock &BB);
+  static ConvergenceControlInst *CreateLoop(BasicBlock &BB,
+ConvergenceControlInst *Parent);
 };
 
 } // end namespace llvm
diff --git a/llvm/lib/IR/IntrinsicInst.cpp b/llvm/lib/IR/IntrinsicInst.cpp
index eb358b9fde..256bce1abe 100644
--- a/llvm/lib/IR/IntrinsicInst.cpp
+++ b/llvm/lib/IR/IntrinsicInst.cpp
@@ -888,21 +888,26 @@ Value *GCRelocateInst::getDerivedPtr() const {
 
 ConvergenceControlInst *ConvergenceControlInst::CreateAnchor(BasicBlock &BB) {
   Module *M = BB.getModule();
-  Function *Fn = Intrinsic::getOrInsertDeclaration(M, 
llvm::Intrinsic::experimental_convergence_anchor);
+  Function *Fn = Intrinsic::getOrInsertDeclaration(
+  M, llvm::Intrinsic::experimental_convergence_anchor);
   auto *Call = CallInst::Create(Fn, "", BB.getFirstInsertionPt());
   return cast(Call);
 }
 
 ConvergenceControlInst *ConvergenceControlInst::CreateEntry(BasicBlock &BB) {
   Module *M = BB.getModule();
-  Function *Fn = Intrinsic::getOrInsertDeclaration(M, 
llvm::Intrinsic::experimental_convergence_entry);
+  Function *Fn = Intrinsic::getOrInsertDeclaration(
+  M, llvm::Intrinsic::experimental_convergence_entry);
   auto *Call = CallInst::Create(Fn, "", BB.getFirstInsertionPt());
   return cast(Call);
 }
 
-ConvergenceControlInst *ConvergenceControlInst::CreateLoop(BasicBlock &BB, 
ConvergenceControlInst *ParentToken) {
+ConvergenceControlInst *
+ConvergenceControlInst::CreateLoop(BasicBlock &BB,
+   ConvergenceControlInst *ParentToken) {
   Module *M = BB.getModule();
-  Function *Fn = Intrinsic::getOrInsertDeclaration(M, 
llvm::Intrinsic::experimental_convergence_loop);
+  Function *Fn = Intrinsic::getOrInsertDeclaration(
+  M, llvm::Intrinsic::experimental_convergence_loop);
   llvm::Value *BundleArgs[] = {ParentToken};
   llvm::OperandBundleDef OB("convergencectrl", BundleArgs);
   auto *Call = CallInst::Create(Fn, {}, {OB}, "", BB.getFirstInsertionPt());

``




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


[clang] Patch series to reapply #118734 and substantially improve it (PR #120534)

2025-02-03 Thread Chandler Carruth via cfe-commits


@@ -482,17 +488,42 @@ void clang::EmitClangBuiltins(const RecordKeeper 
&Records, raw_ostream &OS) {
   for (const auto *BuiltinRecord :
Records.getAllDerivedDefinitions("AtomicBuiltin"))
 collectBuiltins(BuiltinRecord, Builtins);
-
   unsigned NumAtomicBuiltins = Builtins.size();
 
   for (const auto *BuiltinRecord :
Records.getAllDerivedDefinitions("Builtin")) {
 if (BuiltinRecord->isSubClassOf("AtomicBuiltin"))
   continue;
+// Prefixed builtins are also special and we emit them last so they can 
have
+// their own representation that skips the prefix.
+if (BuiltinRecord->getValueAsOptionalDef("RequiredNamePrefix"))
+  continue;
+
 collectBuiltins(BuiltinRecord, Builtins);
   }
 
+  // Now collect (and count) the prefixed builtins.
+  unsigned NumPrefixedBuiltins = Builtins.size();
+  const Record *first_prefix = nullptr;

chandlerc wrote:

Doh, just an accident, sorry. Out of the habits of LLVM style, fixed.

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


[clang] Warn when unique objects might be duplicated in shared libraries (PR #125526)

2025-02-03 Thread Devon Loehr via cfe-commits

https://github.com/DKLoehr updated 
https://github.com/llvm/llvm-project/pull/125526

>From 486c3297f1a316a103c6583daf732af2d00d0b96 Mon Sep 17 00:00:00 2001
From: Devon Loehr 
Date: Thu, 21 Nov 2024 19:29:00 +
Subject: [PATCH 1/6] Warn when unique objects might be duplicated in shared
 libraries

When a hidden object is built into multiple shared libraries, each
instance of the library will get its own copy. If
the object was supposed to be globally unique (e.g. a global
variable or static member), this can cause very subtle bugs.

An object might be incorrectly duplicated if it:
- Is defined in a header (so it might appear in multiple TUs), and
- Has external linkage (otherwise it's supposed to be duplicated), and
- Has hidden visibility (or else the dynamic linker will handle it)

The duplication is only a problem if one of the following is true:
1. The object is mutable (the copies won't be in sync), or
2. Its initialization has side effects (it may now run more than once), or
3. The value of its address is used (which one?).

To detect this, we add a new -Wunique-object-duplication warning.
It warns on cases (1) and (2) above. To be conservative, we only
warn in case (2) if we are certain the initializer has side effects,
and we don't warn on `new` because the only side effect is some
extra memory usage.

We don't currently warn on case (3) because doing so is prone to
false positives: there are many reasons for taking the address which
aren't inherently problematic (e.g. passing to a function that expects
a pointer). We only run into problems if the code inspects the value
of the address.

The check is currently disabled for windows, which uses its own analogue
of visibility (declimport/declexport). The check is also disabled inside
templates, since it can give false positives if a template is never
instantiated.

Because the warning fires in several places, included third-party
libraries, it is currently disabled-by-default until all these
instances have been fixed. It should be enabled-by-default afterwards.
---
 clang/include/clang/Basic/DiagnosticGroups.td |   1 +
 .../clang/Basic/DiagnosticSemaKinds.td|   9 +
 clang/include/clang/Sema/Sema.h   |   6 +
 clang/lib/Sema/SemaDecl.cpp   | 101 ++
 .../SemaCXX/unique_object_duplication.cpp |  16 ++
 .../test/SemaCXX/unique_object_duplication.h  | 187 ++
 6 files changed, 320 insertions(+)
 create mode 100644 clang/test/SemaCXX/unique_object_duplication.cpp
 create mode 100644 clang/test/SemaCXX/unique_object_duplication.h

diff --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index abb575002e1182..d63827cf39b06c 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -694,6 +694,7 @@ def SuspiciousMemaccess : DiagGroup<"suspicious-memaccess",
NonTrivialMemaccess, MemsetTransposedArgs, SuspiciousBzero]>;
 def StaticInInline : DiagGroup<"static-in-inline">;
 def StaticLocalInInline : DiagGroup<"static-local-in-inline">;
+def UniqueObjectDuplication : DiagGroup<"unique-object-duplication">;
 def GNUStaticFloatInit : DiagGroup<"gnu-static-float-init">;
 def StaticFloatInit : DiagGroup<"static-float-init", [GNUStaticFloatInit]>;
 // Allow differentiation between GNU statement expressions in a macro versus
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 5876b2a6ae0eab..6b7fdfbb3cbb6c 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -6169,6 +6169,15 @@ def warn_static_local_in_extern_inline : Warning<
 def note_convert_inline_to_static : Note<
   "use 'static' to give inline function %0 internal linkage">;
 
+def warn_possible_object_duplication_mutable : Warning<
+  "%0 is mutable, has hidden visibility, and external linkage; it may be "
+  "duplicated when built into a shared library">,
+  InGroup, DefaultIgnore;
+def warn_possible_object_duplication_init : Warning<
+  "%0 has hidden visibility, and external linkage; its initialization may run "
+  "more than once when built into a shared library">,
+  InGroup, DefaultIgnore;
+
 def ext_redefinition_of_typedef : ExtWarn<
   "redefinition of typedef %0 is a C11 feature">,
   InGroup >;
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 472a0e25adc975..f04f5dccc39401 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -3664,6 +3664,12 @@ class Sema final : public SemaBase {
  NonTrivialCUnionContext UseContext,
  unsigned NonTrivialKind);
 
+  /// Certain globally-unique variables might be accidentally duplicated if
+  /// built into multiple shared libraries with hidden visibility. This can
+  /// cause problems if the variable is mutable, its initialization is
+  

[clang] [Clang] Make `-Xarch_` handling generic for all toolchains (PR #125421)

2025-02-03 Thread Artem Belevich via cfe-commits


@@ -0,0 +1,31 @@
+// RUN: %clang -x cuda %s -Xarch_nvptx64 -O3 -S -nogpulib -nogpuinc -### 2>&1 
| FileCheck -check-prefix=O3ONCE %s
+// RUN: %clang -x hip %s -Xarch_amdgcn -O3 -S -nogpulib -nogpuinc -### 2>&1 | 
FileCheck -check-prefix=O3ONCE %s

Artem-B wrote:

Checks for host/device would still be useful, regardless of my confusion about 
argument processing above. 

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


[clang] [Clang] Make `-Xarch_` handling generic for all toolchains (PR #125421)

2025-02-03 Thread Joseph Huber via cfe-commits


@@ -0,0 +1,31 @@
+// RUN: %clang -x cuda %s -Xarch_nvptx64 -O3 -S -nogpulib -nogpuinc -### 2>&1 
| FileCheck -check-prefix=O3ONCE %s
+// RUN: %clang -x hip %s -Xarch_amdgcn -O3 -S -nogpulib -nogpuinc -### 2>&1 | 
FileCheck -check-prefix=O3ONCE %s

jhuber6 wrote:

We have existing tests for those, should I add more?

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


[clang] [Clang] Make `-Xarch_` handling generic for all toolchains (PR #125421)

2025-02-03 Thread Artem Belevich via cfe-commits


@@ -1697,19 +1721,17 @@ llvm::opt::DerivedArgList 
*ToolChain::TranslateXarchArgs(
 } else if (A->getOption().matches(options::OPT_Xarch_host)) {
   NeedTrans = !IsDevice;
   Skip = IsDevice;
-} else if (A->getOption().matches(options::OPT_Xarch__) && IsDevice) {
-  // Do not translate -Xarch_ options for non CUDA/HIP toolchain since
-  // they may need special translation.
-  // Skip this argument unless the architecture matches BoundArch
-  if (BoundArch.empty() || A->getValue(0) != BoundArch)
-Skip = true;
-  else
-NeedTrans = true;
+} else if (A->getOption().matches(options::OPT_Xarch__)) {

Artem-B wrote:

Ugh... Never mind, my brain was on vacation, apparently. Not sure if I need 
more coffee, or less coffee this morning. 

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


[clang] [Clang] Make `-Xarch_` handling generic for all toolchains (PR #125421)

2025-02-03 Thread Shilei Tian via cfe-commits


@@ -1115,14 +1117,13 @@ def fno_convergent_functions : Flag<["-"], 
"fno-convergent-functions">,
 
 // Common offloading options
 let Group = offload_Group in {
-def offload_arch_EQ : Joined<["--"], "offload-arch=">, Flags<[NoXarchOption]>,

shiltian wrote:

If that's the case, what does the `arch` mean in `-Xarch_`? It looks like it 
means both, which I'm not sure if that's a good idea.

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


[clang] [clang][X86] Support __attribute__((model("small"/"large"))) (PR #124834)

2025-02-03 Thread Arthur Eubanks via cfe-commits

https://github.com/aeubanks updated 
https://github.com/llvm/llvm-project/pull/124834

>From 7c40169ec7430ec64aaeb053e423eca1ceff7f0d Mon Sep 17 00:00:00 2001
From: Arthur Eubanks 
Date: Tue, 28 Jan 2025 20:36:58 +
Subject: [PATCH 1/5] [clang][X86] Support
 __attribute__((model("small"/"large")))

Following up #72078, on x86-64 this allows a global to be considered
small or large regardless of the code model. For example, x86-64's
medium code model by default classifies globals as small or large
depending on their size relative to -mlarge-data-threshold.
---
 clang/docs/ReleaseNotes.rst  |  5 +
 clang/include/clang/Basic/Attr.td| 13 +
 clang/lib/Sema/SemaDeclAttr.cpp  | 11 ++-
 clang/test/CodeGen/X86/codemodel.cpp | 27 +++
 clang/test/Sema/attr-model.cpp   | 22 ++
 5 files changed, 61 insertions(+), 17 deletions(-)
 create mode 100644 clang/test/CodeGen/X86/codemodel.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 7b5562a80a35a6..dba3ed593dae28 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -657,6 +657,11 @@ Attribute Changes in Clang
 
 - Clang now disallows the use of attributes after the namespace name. 
(#GH121407)
 
+- Clang now allows ``__attribute__((model("small")))`` and
+  ``__attribute__((model("large")))`` on non-TLS globals in x86-64 
compilations.
+  This forces the global to be considered small or large in regards to the
+  x86-64 code model, regardless of the code model specified for the 
compilation.
+
 Improvements to Clang's diagnostics
 ---
 
diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index f4ba2bc3c6de31..092dc751d79f22 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -462,6 +462,7 @@ def TargetMSP430 : TargetArch<["msp430"]>;
 def TargetM68k : TargetArch<["m68k"]>;
 def TargetRISCV : TargetArch<["riscv32", "riscv64"]>;
 def TargetX86 : TargetArch<["x86"]>;
+def TargetX86_64 : TargetArch<["x86_64"]>;
 def TargetAnyX86 : TargetArch<["x86", "x86_64"]>;
 def TargetWebAssembly : TargetArch<["wasm32", "wasm64"]>;
 def TargetNVPTX : TargetArch<["nvptx", "nvptx64"]>;
@@ -3117,11 +3118,15 @@ def PragmaClangTextSection : InheritableAttr {
   let Documentation = [InternalOnly];
 }
 
-def CodeModel : InheritableAttr, TargetSpecificAttr {
+def CodeModel : InheritableAttr,
+TargetSpecificAttr> {
   let Spellings = [GCC<"model">];
-  let Args = [EnumArgument<"Model", "llvm::CodeModel::Model", /*is_string=*/1,
-  ["normal", "medium", "extreme"], ["Small", "Medium", "Large"],
-  /*opt=*/0, /*fake=*/0, /*isExternalType=*/1, /*isCovered=*/0>];
+  let Args = [EnumArgument<
+  "Model", "llvm::CodeModel::Model",
+  /*is_string=*/1, ["small", "normal", "medium", "large", "extreme"],
+  ["Small", "Small", "Medium", "Large", "Large"],
+  /*opt=*/0, /*fake=*/0, /*isExternalType=*/1, /*isCovered=*/0>];
   let Subjects = SubjectList<[NonTLSGlobalVar], ErrorDiag>;
   let Documentation = [CodeModelDocs];
 }
diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index 9d7d22590bce4b..e2c752df06c25a 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -64,6 +64,7 @@
 #include "llvm/IR/DerivedTypes.h"
 #include "llvm/MC/MCSectionMachO.h"
 #include "llvm/Support/Error.h"
+#include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/MathExtras.h"
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/TargetParser/Triple.h"
@@ -2949,6 +2950,13 @@ static void handleSectionAttr(Sema &S, Decl *D, const 
ParsedAttr &AL) {
   }
 }
 
+static bool isValidCodeModelAttr(Sema &S, StringRef Str) {
+  bool IsX8664Target =
+  S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64;
+  bool IsX8664Spelling = Str == "small" || Str == "large";
+  return IsX8664Target == IsX8664Spelling;
+}
+
 static void handleCodeModelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
   StringRef Str;
   SourceLocation LiteralLoc;
@@ -2957,7 +2965,8 @@ static void handleCodeModelAttr(Sema &S, Decl *D, const 
ParsedAttr &AL) {
 return;
 
   llvm::CodeModel::Model CM;
-  if (!CodeModelAttr::ConvertStrToModel(Str, CM)) {
+  if (!CodeModelAttr::ConvertStrToModel(Str, CM) ||
+  !isValidCodeModelAttr(S, Str)) {
 S.Diag(LiteralLoc, diag::err_attr_codemodel_arg) << Str;
 return;
   }
diff --git a/clang/test/CodeGen/X86/codemodel.cpp 
b/clang/test/CodeGen/X86/codemodel.cpp
new file mode 100644
index 00..60a840665b49cd
--- /dev/null
+++ b/clang/test/CodeGen/X86/codemodel.cpp
@@ -0,0 +1,27 @@
+// RUN: %clang_cc1 -emit-llvm -triple x86_64-unknown-unknown %s -o - | 
FileCheck %s
+
+// CHECK: @_ZL2v1 ={{.*}} global i32 0, code_model "small"
+static int v1 __attribute__((model("small")));
+
+void use1() {
+  v1 = 1;
+}
+
+// CHECK: @v2 ={{.*

[clang] [clang][X86] Support __attribute__((model("small"/"large"))) (PR #124834)

2025-02-03 Thread Arthur Eubanks via cfe-commits

aeubanks wrote:

I've allowed the attribute for NVPTX targets and ignored it in SemaDeclAttr 
rather than figure out how to conditionally emit a warning during codegen, does 
that work?

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


[clang] [Clang] Introduce '--offload-targets=' to genericall target toolchains (PR #125556)

2025-02-03 Thread Joseph Huber via cfe-commits

jhuber6 wrote:

Contains two dependent commits, last one is the patch. Might need to have some 
additional error handling to reject known broken architectures, also need to 
correctly handle things like 
`--offload-targets=spirv64-amd-amdhsa,amdgcn-amd-amdhsa` in the new driver.

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


[clang] [CUDA] Increment VTable index for device thunks (PR #124989)

2025-02-03 Thread Yaxun Liu via cfe-commits

yxsamliu wrote:

> _ No description provided. _

Pls add a commit message about the issue this PR is addressing and a summary of 
what it does.

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


[clang] [CUDA] Increment VTable index for device thunks (PR #124989)

2025-02-03 Thread Yaxun Liu via cfe-commits


@@ -0,0 +1,41 @@
+// RUN: %clang_cc1 -fcuda-is-device -triple amdgcn-amd-amdhsa -target-cpu 
gfx942 \
+// RUN:   -emit-llvm -xhip %s -o - | FileCheck %s --check-prefix=GCN
+// RUN: %clang_cc1 -fcuda-is-device -triple spirv64-amd-amdhsa \
+// RUN:   -emit-llvm -xhip %s -o - | FileCheck %s --check-prefix=SPIRV
+
+// GCN: @_ZTV1C = linkonce_odr unnamed_addr addrspace(1) constant { [5 x ptr 
addrspace(1)], [4 x ptr addrspace(1)] } { [5 x ptr addrspace(1)] [ptr 
addrspace(1) null, ptr addrspace(1) null, ptr addrspace(1) addrspacecast (ptr 
@_ZN1B2f2Ev to ptr addrspace(1)), ptr addrspace(1) null, ptr addrspace(1) 
addrspacecast (ptr @_ZN1C2f1Ev to ptr addrspace(1))], [4 x ptr addrspace(1)] 
[ptr addrspace(1) inttoptr (i64 -8 to ptr addrspace(1)), ptr addrspace(1) null, 
ptr addrspace(1) null, ptr addrspace(1) addrspacecast (ptr @_ZThn8_N1C2f1Ev to 
ptr addrspace(1))] }, comdat, align 8
+// GCN: @_ZTV1B = linkonce_odr unnamed_addr addrspace(1) constant { [3 x ptr 
addrspace(1)] } { [3 x ptr addrspace(1)] [ptr addrspace(1) null, ptr 
addrspace(1) null, ptr addrspace(1) addrspacecast (ptr @_ZN1B2f2Ev to ptr 
addrspace(1))] }, comdat, align 8
+// GCN: @_ZTV1A = linkonce_odr unnamed_addr addrspace(1) constant { [4 x ptr 
addrspace(1)] } { [4 x ptr addrspace(1)] [ptr addrspace(1) null, ptr 
addrspace(1) null, ptr addrspace(1) null, ptr addrspace(1) addrspacecast (ptr 
@__cxa_pure_virtual to ptr addrspace(1))] }, comdat, align 8
+// GCN: @__hip_cuid_ = addrspace(1) global i8 0

yxsamliu wrote:

line 9-11 and 16-17 seem not related to the change

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


[clang] [clang] print correct context for diagnostics suppressed by deduction (PR #125453)

2025-02-03 Thread Matheus Izvekov via cfe-commits

mizvekov wrote:

> Thank you for tackling this longstanding issue! How much does saving this 
> extra state add to the runtime and memory usage on a template-heavy 
> compilation?

I tried building stdexec, the difference is within the noise.
Do you have any other examples of template-heavy code in mind?

> If the cost is concerning, one other option we could consider here would be 
> performing pending local instantiations eagerly when we reach the end of a 
> region in which we have a context note -- that'd mean we don't need to save 
> state for later. That's subtly behavior changing because it will pick an 
> earlier point of instantiation for those local instantiations, but it's a 
> permitted point of instantiation; we could try it and see if it works well 
> enough in practice. We could also delay implicit definitions of special 
> members like we do for template instantiations to reduce the impact.

Sounds worth a try, if we can find any concerns.

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


[clang] [clang][X86] Support __attribute__((model("small"/"large"))) (PR #124834)

2025-02-03 Thread Artem Belevich via cfe-commits

https://github.com/Artem-B approved this pull request.

LGTM.

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


[clang] ee92122 - [Win/X86] Make _m_prefetch[w] builtins to avoid winnt.h conflicts (#115099)

2025-02-03 Thread via cfe-commits

Author: Reid Kleckner
Date: 2025-02-03T14:05:58-08:00
New Revision: ee92122b53c7af26bb766e89e1d30ceb2fd5bb93

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

LOG: [Win/X86] Make _m_prefetch[w] builtins to avoid winnt.h conflicts (#115099)

This is similar in spirit to previous changes to make _mm_mfence
builtins to avoid conflicts with winnt.h and other MSVC ecosystem
headers that pre-declare compiler intrinsics as extern "C" symbols.

Also update the feature flag for _mm_prefetch to sse, which is more accurate 
than mmx.

This should fix issue #87515.

Added: 


Modified: 
clang/include/clang/Basic/BuiltinsX86.td
clang/lib/CodeGen/CGBuiltin.cpp
clang/lib/Headers/prfchwintrin.h
clang/lib/Headers/xmmintrin.h

Removed: 




diff  --git a/clang/include/clang/Basic/BuiltinsX86.td 
b/clang/include/clang/Basic/BuiltinsX86.td
index 572ac7235be02f..bb24069dff29b0 100644
--- a/clang/include/clang/Basic/BuiltinsX86.td
+++ b/clang/include/clang/Basic/BuiltinsX86.td
@@ -130,6 +130,10 @@ let Attributes = [Const, NoThrow, 
RequiredVectorWidth<128>] in {
   }
 }
 
+let Features = "sse", Header = "xmmintrin.h", Attributes = [NoThrow, Const] in 
{
+  def _mm_prefetch : X86LibBuiltin<"void(void const *, int)">;
+}
+
 // AVX
 let Attributes = [Const, NoThrow, RequiredVectorWidth<256>], Features = "avx" 
in {
   foreach Op = ["addsub", "hadd", "hsub", "max", "min"] in {
@@ -138,6 +142,12 @@ let Attributes = [Const, NoThrow, 
RequiredVectorWidth<256>], Features = "avx" in
   }
 }
 
+// PRFCHW
+let Features = "prfchw", Header = "x86intrin.h", Attributes = [NoThrow, Const] 
in {
+  def _m_prefetch : X86LibBuiltin<"void(void *)">;
+  def _m_prefetchw : X86LibBuiltin<"void(void volatile const *)">;
+}
+
 
 // Mechanically ported builtins from the original `.def` file.
 //
@@ -146,10 +156,6 @@ let Attributes = [Const, NoThrow, 
RequiredVectorWidth<256>], Features = "avx" in
 // current formulation is based on what was easiest to recognize from the
 // pre-TableGen version.
 
-let Features = "mmx", Attributes = [NoThrow, Const] in {
-  def _mm_prefetch : X86NoPrefixBuiltin<"void(char const *, int)">;
-}
-
 let Features = "sse", Attributes = [NoThrow] in {
   def ldmxcsr : X86Builtin<"void(unsigned int)">;
 }

diff  --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 11fa295dad9524..4d3d9e9897c148 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -15374,6 +15374,17 @@ Value *CodeGenFunction::EmitX86BuiltinExpr(unsigned 
BuiltinID,
 Function *F = CGM.getIntrinsic(Intrinsic::prefetch, Address->getType());
 return Builder.CreateCall(F, {Address, RW, Locality, Data});
   }
+  case X86::BI_m_prefetch:
+  case X86::BI_m_prefetchw: {
+Value *Address = Ops[0];
+// The 'w' suffix implies write.
+Value *RW =
+ConstantInt::get(Int32Ty, BuiltinID == X86::BI_m_prefetchw ? 1 : 0);
+Value *Locality = ConstantInt::get(Int32Ty, 0x3);
+Value *Data = ConstantInt::get(Int32Ty, 1);
+Function *F = CGM.getIntrinsic(Intrinsic::prefetch, Address->getType());
+return Builder.CreateCall(F, {Address, RW, Locality, Data});
+  }
   case X86::BI_mm_clflush: {
 return Builder.CreateCall(CGM.getIntrinsic(Intrinsic::x86_sse2_clflush),
   Ops[0]);

diff  --git a/clang/lib/Headers/prfchwintrin.h 
b/clang/lib/Headers/prfchwintrin.h
index eaea5f3cf8febf..8ec55d7073716f 100644
--- a/clang/lib/Headers/prfchwintrin.h
+++ b/clang/lib/Headers/prfchwintrin.h
@@ -14,6 +14,10 @@
 #ifndef __PRFCHWINTRIN_H
 #define __PRFCHWINTRIN_H
 
+#if defined(__cplusplus)
+extern "C" {
+#endif
+
 /// Loads a memory sequence containing the specified memory address into
 ///all data cache levels.
 ///
@@ -26,11 +30,7 @@
 ///
 /// \param __P
 ///A pointer specifying the memory address to be prefetched.
-static __inline__ void __attribute__((__always_inline__, __nodebug__))
-_m_prefetch(void *__P)
-{
-  __builtin_prefetch (__P, 0, 3 /* _MM_HINT_T0 */);
-}
+void _m_prefetch(void *__P);
 
 /// Loads a memory sequence containing the specified memory address into
 ///the L1 data cache and sets the cache-coherency state to modified.
@@ -48,13 +48,10 @@ _m_prefetch(void *__P)
 ///
 /// \param __P
 ///A pointer specifying the memory address to be prefetched.
-static __inline__ void __attribute__((__always_inline__, __nodebug__))
-_m_prefetchw(volatile const void *__P)
-{
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wcast-qual"
-  __builtin_prefetch ((const void*)__P, 1, 3 /* _MM_HINT_T0 */);
-#pragma clang diagnostic pop
-}
+void _m_prefetchw(volatile const void *__P);
+
+#if defined(__cplusplus)
+} // extern "C"
+#endif
 
 #endif /* __PRFCHWINTRIN_H */

diff  --git a/clang/lib/Headers/xm

[clang] [Win/X86] Make _m_prefetch[w] builtins to avoid winnt.h conflicts (PR #115099)

2025-02-03 Thread Reid Kleckner via cfe-commits

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


[clang] [Win/X86] Make _m_prefetch[w] builtins to avoid winnt.h conflicts (PR #115099)

2025-02-03 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder 
`sanitizer-aarch64-linux-fuzzer` running on `sanitizer-buildbot12` while 
building `clang` at step 2 "annotate".

Full details are available at: 
https://lab.llvm.org/buildbot/#/builders/159/builds/15333


Here is the relevant piece of the build log for the reference

```
Step 2 (annotate) failure: 'python 
../sanitizer_buildbot/sanitizers/zorg/buildbot/builders/sanitizers/buildbot_selector.py'
 (failure)
...
-- Performing Test HAVE_PTHREAD_AFFINITY -- success
-- Configuring done (4.0s)
-- Generating done (2.8s)
-- Build files have been written to: 
/home/b/sanitizer-aarch64-linux-fuzzer/build/llvm_build0
+ ninja
[1/181] Generating VCSRevision.h
[2/119] Building CXX object 
tools/llvm-config/CMakeFiles/llvm-config.dir/llvm-config.cpp.o
[3/119] Copying clang's prfchwintrin.h...
[4/119] Copying clang's xmmintrin.h...
[5/119] Building BuiltinsX86.inc...
FAILED: tools/clang/include/clang/Basic/BuiltinsX86.inc 
/home/b/sanitizer-aarch64-linux-fuzzer/build/llvm_build0/tools/clang/include/clang/Basic/BuiltinsX86.inc
 
cd /home/b/sanitizer-aarch64-linux-fuzzer/build/llvm_build0 && 
/home/b/sanitizer-aarch64-linux-fuzzer/build/llvm_build0/bin/clang-tblgen 
-gen-clang-builtins -I 
/home/b/sanitizer-aarch64-linux-fuzzer/build/llvm-project/clang/include/clang/Basic
 -I/home/b/sanitizer-aarch64-linux-fuzzer/build/llvm-project/clang/include 
-I/home/b/sanitizer-aarch64-linux-fuzzer/build/llvm_build0/tools/clang/include 
-I/home/b/sanitizer-aarch64-linux-fuzzer/build/llvm_build0/include 
-I/home/b/sanitizer-aarch64-linux-fuzzer/build/llvm-project/llvm/include 
/home/b/sanitizer-aarch64-linux-fuzzer/build/llvm-project/clang/include/clang/Basic/BuiltinsX86.td
 --write-if-changed -o tools/clang/include/clang/Basic/BuiltinsX86.inc -d 
tools/clang/include/clang/Basic/BuiltinsX86.inc.d
/home/b/sanitizer-aarch64-linux-fuzzer/build/llvm-project/clang/include/clang/Basic/BuiltinsX86.td:147:7:
 error: Unexpected header name
  def _m_prefetch : X86LibBuiltin<"void(void *)">;
  ^
[6/119] Linking CXX shared module unittests/Analysis/InlineAdvisorPlugin.so
[7/119] Linking CXX shared module unittests/Passes/Plugins/DoublerPlugin.so
[8/119] Generating VCSVersion.inc
[9/117] Linking CXX shared module unittests/Support/DynamicLibrary/SecondLib.so
[10/117] Linking CXX shared module unittests/Support/DynamicLibrary/PipSqueak.so
[11/117] Linking CXX shared module unittests/Analysis/InlineOrderPlugin.so
[12/117] Linking CXX shared module unittests/Passes/Plugins/TestPlugin.so
[13/117] Linking CXX executable bin/llvm-config
[14/117] Building CXX object 
lib/Target/RISCV/CMakeFiles/LLVMRISCVCodeGen.dir/RISCVISelLowering.cpp.o
ninja: build stopped: subcommand failed.
+ touch llvm_build0/delete_next_time
+ return 1
Step 7 (stage1 build all) failure: stage1 build all (failure)
...
-- Performing Test HAVE_PTHREAD_AFFINITY -- success
-- Configuring done (4.0s)
-- Generating done (2.8s)
-- Build files have been written to: 
/home/b/sanitizer-aarch64-linux-fuzzer/build/llvm_build0
+ ninja
[1/181] Generating VCSRevision.h
[2/119] Building CXX object 
tools/llvm-config/CMakeFiles/llvm-config.dir/llvm-config.cpp.o
[3/119] Copying clang's prfchwintrin.h...
[4/119] Copying clang's xmmintrin.h...
[5/119] Building BuiltinsX86.inc...
FAILED: tools/clang/include/clang/Basic/BuiltinsX86.inc 
/home/b/sanitizer-aarch64-linux-fuzzer/build/llvm_build0/tools/clang/include/clang/Basic/BuiltinsX86.inc
 
cd /home/b/sanitizer-aarch64-linux-fuzzer/build/llvm_build0 && 
/home/b/sanitizer-aarch64-linux-fuzzer/build/llvm_build0/bin/clang-tblgen 
-gen-clang-builtins -I 
/home/b/sanitizer-aarch64-linux-fuzzer/build/llvm-project/clang/include/clang/Basic
 -I/home/b/sanitizer-aarch64-linux-fuzzer/build/llvm-project/clang/include 
-I/home/b/sanitizer-aarch64-linux-fuzzer/build/llvm_build0/tools/clang/include 
-I/home/b/sanitizer-aarch64-linux-fuzzer/build/llvm_build0/include 
-I/home/b/sanitizer-aarch64-linux-fuzzer/build/llvm-project/llvm/include 
/home/b/sanitizer-aarch64-linux-fuzzer/build/llvm-project/clang/include/clang/Basic/BuiltinsX86.td
 --write-if-changed -o tools/clang/include/clang/Basic/BuiltinsX86.inc -d 
tools/clang/include/clang/Basic/BuiltinsX86.inc.d
/home/b/sanitizer-aarch64-linux-fuzzer/build/llvm-project/clang/include/clang/Basic/BuiltinsX86.td:147:7:
 error: Unexpected header name
  def _m_prefetch : X86LibBuiltin<"void(void *)">;
  ^
[6/119] Linking CXX shared module unittests/Analysis/InlineAdvisorPlugin.so
[7/119] Linking CXX shared module unittests/Passes/Plugins/DoublerPlugin.so
[8/119] Generating VCSVersion.inc
[9/117] Linking CXX shared module unittests/Support/DynamicLibrary/SecondLib.so
[10/117] Linking CXX shared module unittests/Support/DynamicLibrary/PipSqueak.so
[11/117] Linking CXX shared module unittests/Analysis/InlineOrderPlugin.so
[12/117] Linking CXX shared module unittests/Passes/Plugins/TestPlugin.so
[13/117] Linking CXX executable bin/llvm-config
[14/117] Bui

[clang] [Win/X86] Make _m_prefetch[w] builtins to avoid winnt.h conflicts (PR #115099)

2025-02-03 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder `lldb-x86_64-debian` 
running on `lldb-x86_64-debian` while building `clang` at step 4 "build".

Full details are available at: 
https://lab.llvm.org/buildbot/#/builders/162/builds/15504


Here is the relevant piece of the build log for the reference

```
Step 4 (build) failure: build (failure)
1.006 [172/5/1] Copying clang's prfchwintrin.h...
1.007 [172/4/2] Copying clang's xmmintrin.h...
1.009 [172/3/3] Building BuiltinsX86.inc...
FAILED: tools/clang/include/clang/Basic/BuiltinsX86.inc 
/home/worker/2.0.1/lldb-x86_64-debian/build/tools/clang/include/clang/Basic/BuiltinsX86.inc
 
cd /home/worker/2.0.1/lldb-x86_64-debian/build && 
/home/worker/2.0.1/lldb-x86_64-debian/build/bin/clang-tblgen 
-gen-clang-builtins -I 
/home/worker/2.0.1/lldb-x86_64-debian/llvm-project/clang/include/clang/Basic 
-I/home/worker/2.0.1/lldb-x86_64-debian/llvm-project/clang/include 
-I/home/worker/2.0.1/lldb-x86_64-debian/build/tools/clang/include 
-I/home/worker/2.0.1/lldb-x86_64-debian/build/include 
-I/home/worker/2.0.1/lldb-x86_64-debian/llvm-project/llvm/include 
/home/worker/2.0.1/lldb-x86_64-debian/llvm-project/clang/include/clang/Basic/BuiltinsX86.td
 --write-if-changed -o tools/clang/include/clang/Basic/BuiltinsX86.inc -d 
tools/clang/include/clang/Basic/BuiltinsX86.inc.d
/home/worker/2.0.1/lldb-x86_64-debian/llvm-project/clang/include/clang/Basic/BuiltinsX86.td:147:7:
 error: Unexpected header name
  def _m_prefetch : X86LibBuiltin<"void(void *)">;
  ^
1.033 [172/2/4] Generating VCSRevision.h
2.647 [172/1/5] Building CXX object 
tools/llvm-config/CMakeFiles/llvm-config.dir/llvm-config.cpp.o
ninja: build stopped: subcommand failed.

```



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


  1   2   3   4   5   >