[clang] [ClangRepl] Type Directed Code Completion (PR #67349)

2023-11-23 Thread Vassil Vassilev via cfe-commits

vgvassilev wrote:

@capfredf, can you rebase the PR to trigger a rebuild - the test failure seems 
unrelated to our changes but maybe it was fixed meanwhile.

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


[libcxx] [libcxxabi] [lld] [compiler-rt] [clang] [llvm] [clang-tools-extra] [libc] [libunwind] [flang] [PowerPC] Combine sub within setcc back to sext (PR #66978)

2023-11-23 Thread Kai Luo via cfe-commits


@@ -14428,15 +14431,53 @@ SDValue PPCTargetLowering::combineSetCC(SDNode *N,
 // x != 0-y --> x+y != 0
 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
 RHS.hasOneUse()) {
-  SDLoc DL(N);
-  SelectionDAG &DAG = DCI.DAG;
-  EVT VT = N->getValueType(0);
-  EVT OpVT = LHS.getValueType();
   SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
   return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
 }
   }
 
+  if (CC == ISD::SETULT && isa(RHS)) {
+uint64_t RHSVal = cast(RHS)->getZExtValue();
+if (LHS.getOpcode() == ISD::ADD && isa(LHS.getOperand(1))) 
{
+  uint64_t Addend = 
cast(LHS.getOperand(1))->getZExtValue();
+  if (OpVT == MVT::i64) {
+// (a-2^(M-1)) => sext(trunc(a, M), 64)
+uint64_t ShiftVal = ~Addend + 1;
+uint64_t CmpVal = ~RHSVal + 1;
+if (isPowerOf2_64(ShiftVal) && ShiftVal << 1 == CmpVal) {
+  unsigned DestBits = Log2_64(CmpVal);
+  if (DestBits == 8 || DestBits == 16 || DestBits == 32) {
+SDValue Conv = DAG.getSExtOrTrunc(
+DAG.getSExtOrTrunc(LHS.getOperand(0), DL,
+   MVT::getIntegerVT(DestBits)),
+DL, OpVT);
+return DAG.getSetCC(DL, VT, LHS.getOperand(0), Conv, ISD::SETNE);
+  }
+}
+  } else if (OpVT == MVT::i32) {
+if (RHSVal == 0xff00 && Addend == 0xff80) {
+  SDValue Conv = DAG.getSExtOrTrunc(
+  DAG.getSExtOrTrunc(LHS.getOperand(0), DL, MVT::i8), DL, OpVT);
+  return DAG.getSetCC(DL, VT, LHS.getOperand(0), Conv, ISD::SETNE);
+}
+  }
+} else if (LHS.getOpcode() == ISD::SRL &&
+   LHS.getOperand(0).getOpcode() == ISD::ADD &&
+   isa(LHS.getOperand(1)) &&
+   isa(LHS.getOperand(0).getOperand(1))) {
+  if (RHSVal == 65535 &&

bzEq wrote:

```suggestion
  if (RHSVal == 0xff &&
```

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


[libcxx] [libcxxabi] [lld] [compiler-rt] [clang] [llvm] [clang-tools-extra] [libc] [libunwind] [flang] [PowerPC] Combine sub within setcc back to sext (PR #66978)

2023-11-23 Thread Kai Luo via cfe-commits

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


[clang] [llvm] ms inline asm: Fix {call,jmp} fptr (PR #73207)

2023-11-23 Thread Shengchen Kan via cfe-commits

KanRobert wrote:

Investigating, I almost forgot the mechanism of MS inline asm support...

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


[libcxx] [libcxxabi] [lld] [compiler-rt] [clang] [llvm] [clang-tools-extra] [libc] [libunwind] [flang] [PowerPC] Combine sub within setcc back to sext (PR #66978)

2023-11-23 Thread Kai Luo via cfe-commits


@@ -14428,15 +14431,53 @@ SDValue PPCTargetLowering::combineSetCC(SDNode *N,
 // x != 0-y --> x+y != 0
 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
 RHS.hasOneUse()) {
-  SDLoc DL(N);
-  SelectionDAG &DAG = DCI.DAG;
-  EVT VT = N->getValueType(0);
-  EVT OpVT = LHS.getValueType();
   SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
   return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
 }
   }
 
+  if (CC == ISD::SETULT && isa(RHS)) {
+uint64_t RHSVal = cast(RHS)->getZExtValue();
+if (LHS.getOpcode() == ISD::ADD && isa(LHS.getOperand(1))) 
{
+  uint64_t Addend = 
cast(LHS.getOperand(1))->getZExtValue();
+  if (OpVT == MVT::i64) {
+// (a-2^(M-1)) => sext(trunc(a, M), 64)

bzEq wrote:

When is this equation hold?

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


[clang] [clang] Add partial-inlining options (PR #73210)

2023-11-23 Thread via cfe-commits

https://github.com/Jolyon0202 updated 
https://github.com/llvm/llvm-project/pull/73210

>From d5679e5dba708e8a54c63d63f3da6c92a6cf0aeb Mon Sep 17 00:00:00 2001
From: Jian Yang 
Date: Thu, 23 Nov 2023 12:54:52 +0800
Subject: [PATCH] [clang] Add partial-inlining options

Adaptation of adding -fpartial-inlining and -fno-partial-inlining options with 
GCC.
---
 clang/include/clang/Driver/Options.td |  4 
 clang/lib/Driver/ToolChains/Clang.cpp | 12 
 clang/test/Driver/clang_f_opts.c  |  5 +
 3 files changed, 21 insertions(+)

diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index b2f2bcb6ac37910..7dbf2363fe17b6b 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -3134,6 +3134,10 @@ def fno_inline_functions : Flag<["-"], 
"fno-inline-functions">, Group;
 def fno_inline : Flag<["-"], "fno-inline">, Group,
   Visibility<[ClangOption, CC1Option]>;
+def fpartial_inlining : Flag<["-"], "fpartial-inlining">, Group,
+  Visibility<[ClangOption, CC1Option]>;
+def fno_partial_inlining : Flag<["-"], "fno-partial-inlining">, 
Group,
+  Visibility<[ClangOption, CC1Option]>;
 def fno_global_isel : Flag<["-"], "fno-global-isel">, Group,
   HelpText<"Disables the global instruction selector">;
 def fno_experimental_isel : Flag<["-"], "fno-experimental-isel">, 
Group,
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 6dec117aed1056b..028204140d1265f 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -6923,6 +6923,18 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
 
   Args.AddLastArg(CmdArgs, options::OPT_finline_max_stacksize_EQ);
 
+  // Adaptation of partial-inlining option with GCC.
+  if (Arg *A = Args.getLastArg(options::OPT_fno_partial_inlining,
+   options::OPT_fpartial_inlining)) {
+if (A->getOption().matches(options::OPT_fno_partial_inlining)) {
+  CmdArgs.push_back("-mllvm");
+  CmdArgs.push_back("-disable-partial-inlining");
+} else if (A->getOption().matches(options::OPT_fpartial_inlining)) {
+  CmdArgs.push_back("-mllvm");
+  CmdArgs.push_back("-enable-partial-inlining");
+}
+  }
+
   // FIXME: Find a better way to determine whether we are in C++20.
   bool HaveCxx20 =
   Std &&
diff --git a/clang/test/Driver/clang_f_opts.c b/clang/test/Driver/clang_f_opts.c
index ebe8a0520bf0fca..bab1ea33dd7c941 100644
--- a/clang/test/Driver/clang_f_opts.c
+++ b/clang/test/Driver/clang_f_opts.c
@@ -611,3 +611,8 @@
 // CHECK-INT-OBJEMITTER-NOT: unsupported option '-fintegrated-objemitter' for 
target
 // RUN: not %clang -### -fno-integrated-objemitter --target=x86_64 %s 2>&1 | 
FileCheck -check-prefix=CHECK-NOINT-OBJEMITTER %s
 // CHECK-NOINT-OBJEMITTER: unsupported option '-fno-integrated-objemitter' for 
target
+
+// RUN: %clang -### -S -fpartial-inlining %s 2>&1 | FileCheck 
-check-prefix=CHECK-PARTIAL-INLINING %s
+// CHECK-PARTIAL-INLINING: "-mllvm" "-enable-partial-inlining"
+// RUN: %clang -### -S -fno-partial-inlining %s 2>&1 | FileCheck 
-check-prefix=CHECK-NO-PARTIAL-INLINING %s
+// CHECK-NO-PARTIAL-INLINING: "-mllvm" "-disable-partial-inlining"

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


[clang] [clang][AST][ASTMerge] prevent AST nodes from being deallocated early (PR #73096)

2023-11-23 Thread Qizhi Hu via cfe-commits

jcsxky wrote:

> > Debug the #72783 can prove it. Address interval (local from 0x3a9a00 to 
> > 0x3aaa00) allocated by allocator contains a IdentifierInfo variable (local 
> > address:0x3aa190) whose address is freed early.
> 
> In this case, it looks better to extract the use-after-free variable only 
> instead of extracting the whole ASTUnit.

- From my local debugging, it's a `IdentifierInfo` type variable which is freed 
by allocator. The variable is subnode of AST. Thanks to `ASTUnit` is out of 
scope, some related memory is freed (which is allocated by 
`SpecificBumpPtrAllocator`) as destructor called and we can't extract only 
`IdentifierInfo` type variable.


> 
> > As system header like stdio.h or math.h can't be put into test, it's hard 
> > to add testcase. Could anyone give me some guidance? Thanks in advance!
> 
> Generally, we need to reduce them in this case. e.g., we need to preprocess 
> them, and remove unncessary parts until we can't. It is time consuming but it 
> is worthy.

- Small piece of code can't reproduce the crash. The crash is caused by growing 
of size of `OnDiskChainedHashTableGenerator` when add `IdentifierInfo` type 
variable. As mentioned in the 
[issue](https://github.com/llvm/llvm-project/issues/72783), when remove header 
file, it runs OK. Small-scale code wouldn't cause resize of 
`OnDiskChainedHashTableGenerator`


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


[clang] [clang-format] Fix a bug in formating `#define A x:` (PR #73220)

2023-11-23 Thread Owen Pan via cfe-commits

https://github.com/owenca created 
https://github.com/llvm/llvm-project/pull/73220

Fixed #70789.

>From 0a8459053be654313efff8002ff3e171d8cd9d18 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Thu, 23 Nov 2023 00:41:41 -0800
Subject: [PATCH] [clang-format] Fix a bug in formating `#define A x:`

Fixed #70789.
---
 clang/lib/Format/UnwrappedLineParser.cpp | 7 +++
 clang/unittests/Format/FormatTest.cpp| 2 ++
 2 files changed, 9 insertions(+)

diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index c870ff01605e725..0f841e0bee50b6c 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -1171,6 +1171,13 @@ void UnwrappedLineParser::parsePPDefine() {
   assert((int)Line->PPLevel >= 0);
   Line->InMacroBody = true;
 
+  if (FormatTok->is(tok::identifier) &&
+  Tokens->peekNextToken()->is(tok::colon)) {
+nextToken();
+nextToken();
+addUnwrappedLine();
+  }
+
   // Errors during a preprocessor directive can only affect the layout of the
   // preprocessor directive, and thus we ignore them. An alternative approach
   // would be to use the same approach we use on the file level (no
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 67423f9b06fbc37..d095a2b751defe3 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -1863,6 +1863,8 @@ TEST_F(FormatTest, UnderstandsMacros) {
   verifyFormat("MACRO(something##something)");
   verifyFormat("MACRO(return##something)");
   verifyFormat("MACRO(co_return##something)");
+
+  verifyFormat("#define A x:");
 }
 
 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) {

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


[clang] [clang-format] Fix a bug in formating `#define A x:` (PR #73220)

2023-11-23 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-format

Author: Owen Pan (owenca)


Changes

Fixed #70789.

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


2 Files Affected:

- (modified) clang/lib/Format/UnwrappedLineParser.cpp (+7) 
- (modified) clang/unittests/Format/FormatTest.cpp (+2) 


``diff
diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index c870ff01605e725..0f841e0bee50b6c 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -1171,6 +1171,13 @@ void UnwrappedLineParser::parsePPDefine() {
   assert((int)Line->PPLevel >= 0);
   Line->InMacroBody = true;
 
+  if (FormatTok->is(tok::identifier) &&
+  Tokens->peekNextToken()->is(tok::colon)) {
+nextToken();
+nextToken();
+addUnwrappedLine();
+  }
+
   // Errors during a preprocessor directive can only affect the layout of the
   // preprocessor directive, and thus we ignore them. An alternative approach
   // would be to use the same approach we use on the file level (no
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 67423f9b06fbc37..d095a2b751defe3 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -1863,6 +1863,8 @@ TEST_F(FormatTest, UnderstandsMacros) {
   verifyFormat("MACRO(something##something)");
   verifyFormat("MACRO(return##something)");
   verifyFormat("MACRO(co_return##something)");
+
+  verifyFormat("#define A x:");
 }
 
 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) {

``




https://github.com/llvm/llvm-project/pull/73220
___
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 check hicpp-ignored-remove-result (PR #73119)

2023-11-23 Thread Björn Svensson via cfe-commits

https://github.com/bjosv updated https://github.com/llvm/llvm-project/pull/73119

From 91cf412abcfd231ab399c3e44c6a9bc14109537c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Bj=C3=B6rn=20Svensson?= 
Date: Tue, 21 Nov 2023 23:30:07 +0100
Subject: [PATCH 1/2] [clang-tidy] Add check hicpp-ignored-remove-result

This check implements the rule 17.5.1 of the HICPP standard
which states:

- Do not ignore the result of std::remove, std::remove_if or std::unique

  The mutating algorithms std::remove, std::remove_if and both overloads of
  std::unique operate by swapping or moving elements of the range they are
  operating over. On completion, they return an iterator to the last valid 
element.
  In the majority of cases the correct behavior is to use this result as the
  first operand in a call to std::erase.

Suppressing issues by casting to `void` is enabled by default, but can be
disabled by setting `AllowCastToVoid` option to `false`.
---
 .../clang-tidy/hicpp/HICPPTidyModule.cpp  | 20 
 clang-tools-extra/docs/ReleaseNotes.rst   |  4 ++
 .../checks/hicpp/ignored-remove-result.rst| 20 
 .../docs/clang-tidy/checks/list.rst   |  1 +
 .../checkers/hicpp/ignored-remove-result.cpp  | 47 +++
 5 files changed, 92 insertions(+)
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/hicpp/ignored-remove-result.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/hicpp/ignored-remove-result.cpp

diff --git a/clang-tools-extra/clang-tidy/hicpp/HICPPTidyModule.cpp 
b/clang-tools-extra/clang-tidy/hicpp/HICPPTidyModule.cpp
index 3749796877120ed..09d15ccab3f29c2 100644
--- a/clang-tools-extra/clang-tidy/hicpp/HICPPTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/hicpp/HICPPTidyModule.cpp
@@ -10,6 +10,7 @@
 #include "../ClangTidyModule.h"
 #include "../ClangTidyModuleRegistry.h"
 #include "../bugprone/UndelegatedConstructorCheck.h"
+#include "../bugprone/UnusedReturnValueCheck.h"
 #include "../bugprone/UseAfterMoveCheck.h"
 #include "../cppcoreguidelines/AvoidGotoCheck.h"
 #include "../cppcoreguidelines/NoMallocCheck.h"
@@ -41,6 +42,15 @@
 #include "NoAssemblerCheck.h"
 #include "SignedBitwiseCheck.h"
 
+namespace {
+
+// Checked functions for hicpp-ignored-remove-result.
+const llvm::StringRef CheckedFunctions = "::std::remove;"
+ "::std::remove_if;"
+ "::std::unique;";
+
+} // namespace
+
 namespace clang::tidy {
 namespace hicpp {
 
@@ -64,6 +74,8 @@ class HICPPModule : public ClangTidyModule {
 "hicpp-explicit-conversions");
 CheckFactories.registerCheck(
 "hicpp-function-size");
+CheckFactories.registerCheck(
+"hicpp-ignored-remove-result");
 CheckFactories.registerCheck(
 "hicpp-named-parameter");
 CheckFactories.registerCheck(
@@ -107,6 +119,14 @@ class HICPPModule : public ClangTidyModule {
 CheckFactories.registerCheck(
 "hicpp-vararg");
   }
+
+  ClangTidyOptions getModuleOptions() override {
+ClangTidyOptions Options;
+ClangTidyOptions::OptionMap &Opts = Options.CheckOptions;
+Opts["hicpp-ignored-remove-result.CheckedFunctions"] = CheckedFunctions;
+Opts["hicpp-ignored-remove-result.AllowCastToVoid"] = "true";
+return Options;
+  }
 };
 
 // Register the HICPPModule using this statically initialized variable.
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 6d5f49dc0625451..c940025df1c63cd 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -205,6 +205,10 @@ New check aliases
   ` to 
:doc:`modernize-macro-to-enum
   ` was added.
 
+- New alias :doc:`hicpp-ignored-remove-result
+  ` to 
:doc:`bugprone-unused-return-value
+  ` was added.
+
 Changes in existing checks
 ^^
 
diff --git 
a/clang-tools-extra/docs/clang-tidy/checks/hicpp/ignored-remove-result.rst 
b/clang-tools-extra/docs/clang-tidy/checks/hicpp/ignored-remove-result.rst
new file mode 100644
index 000..4b6188b886db124
--- /dev/null
+++ b/clang-tools-extra/docs/clang-tidy/checks/hicpp/ignored-remove-result.rst
@@ -0,0 +1,20 @@
+.. title:: clang-tidy - hicpp-ignored-remove-result
+
+hicpp-ignored-remove-result
+===
+
+Ensure that the result of ``std::remove``, ``std::remove_if`` and 
``std::unique``
+are not ignored according to
+`rule 17.5.1 
`_.
+
+The mutating algorithms ``std::remove``, ``std::remove_if`` and both overloads
+of ``std::unique`` operate by swapping or moving elements of the range they are
+operating over. On completion, they return an iterator to the last valid
+element. In the majority of cases the correct behavior is to use this result as
+the first operand in a call to std::erase.
+
+This check is an alias of check :doc:`bugprone-unused-return-value 
<../bugp

[clang] [clang] Add missing LinkageSpec case to getCursorKindForDecl (PR #72401)

2023-11-23 Thread Sebastian Poeplau via cfe-commits

sebastianpoeplau wrote:

It should, yes.

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


[clang] fix: C++ empty record with align lead to va_list out of sync (PR #72197)

2023-11-23 Thread via cfe-commits

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


[clang] fix: C++ empty record with align lead to va_list out of sync (PR #72197)

2023-11-23 Thread via cfe-commits

https://github.com/hstk30-hw updated 
https://github.com/llvm/llvm-project/pull/72197

>From 18c2151e870b757fe3238cc4031597352ecc440e Mon Sep 17 00:00:00 2001
From: hstk30-hw 
Date: Sat, 18 Nov 2023 11:00:29 +
Subject: [PATCH] fix: empty record size > 64 with align let va_list get out of
 sync

---
 clang/lib/CodeGen/Targets/AArch64.cpp | 11 ---
 clang/test/CodeGen/aarch64-args.cpp   | 19 +++
 2 files changed, 27 insertions(+), 3 deletions(-)

diff --git a/clang/lib/CodeGen/Targets/AArch64.cpp 
b/clang/lib/CodeGen/Targets/AArch64.cpp
index be5145daa00b7f5..46583e7c570a5d9 100644
--- a/clang/lib/CodeGen/Targets/AArch64.cpp
+++ b/clang/lib/CodeGen/Targets/AArch64.cpp
@@ -295,8 +295,12 @@ AArch64ABIInfo::classifyArgumentType(QualType Ty, bool 
IsVariadic,
  CGCXXABI::RAA_DirectInMemory);
   }
 
-  // Empty records are always ignored on Darwin, but actually passed in C++ 
mode
-  // elsewhere for GNU compatibility.
+  // AAPCS64 does not say that empty records are ignored as arguments,
+  // but other compilers do so in certain situations, and we copy that 
behavior.
+  // Those situations are in fact language-mode-specific, which seems really
+  // unfortunate, but it's something we just have to accept. If this doesn't
+  // apply, just fall through to the standard argument-handling path.
+  // Darwin overrides the psABI here to ignore all empty records in all modes.
   uint64_t Size = getContext().getTypeSize(Ty);
   bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
   if (IsEmpty || Size == 0) {
@@ -307,7 +311,8 @@ AArch64ABIInfo::classifyArgumentType(QualType Ty, bool 
IsVariadic,
 // 0.
 if (IsEmpty && Size == 0)
   return ABIArgInfo::getIgnore();
-return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
+if (Size <= 64)
+  return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
   }
 
   // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
diff --git a/clang/test/CodeGen/aarch64-args.cpp 
b/clang/test/CodeGen/aarch64-args.cpp
index fe1298cc683a404..1fc1b89785fee81 100644
--- a/clang/test/CodeGen/aarch64-args.cpp
+++ b/clang/test/CodeGen/aarch64-args.cpp
@@ -65,3 +65,22 @@ EXTERNC struct SortOfEmpty sort_of_empty_ret(void) {
   struct SortOfEmpty e;
   return e;
 }
+
+// CHECK-GNU-CXX: define{{.*}} i32 @empty_align8_arg(i8 %a.coerce, i32 noundef 
%b)
+struct EmptyAlign8 { int __attribute__((aligned(8))) : 0; };
+EXTERNC int empty_align8_arg(struct EmptyAlign8 a, int b) {
+  return b;
+}
+
+// CHECK-GNU-CXX: define{{.*}} i32 @empty_align16_arg(i128 %a.coerce, i32 
noundef %b)
+struct EmptyAlign16 { long long int __attribute__((aligned(16))) : 0; };
+EXTERNC int empty_align16_arg(struct EmptyAlign16 a, int b) {
+  return b;
+}
+
+// CHECK-GNU-CXX: define{{.*}} i32 @empty_align32_arg(ptr noundef %a, i32 
noundef %b)
+struct EmptyAlign32 { long long int __attribute__((aligned(32))) : 0; };
+EXTERNC int empty_align32_arg(struct EmptyAlign32 a, int b) {
+  return b;
+}
+

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


[clang] [clang][analyzer] Move `security.cert.env.InvalidPtr` out of `alpha` (PR #71912)

2023-11-23 Thread Endre Fülöp via cfe-commits

https://github.com/gamesh411 updated 
https://github.com/llvm/llvm-project/pull/71912

From 977e421008c1247d54f4cb67967ed2a353935c03 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Endre=20F=C3=BCl=C3=B6p?= 
Date: Fri, 10 Nov 2023 10:08:58 +0100
Subject: [PATCH 1/3] [analyzer] Move security.cert.env.InvalidPtr out of alpha

Thanks to recent improvements in #67663, InvalidPtr checker does
not emit any false positives on the following OS projects:
memcached, tmux, curl, twin, vim, openssl, sqlite, ffmpeg, postgres,
tinyxml2, libwebm, xerces, bitcoin, protobuf, qtbase, contour, acid,
openrct2
---
 clang/docs/analyzer/checkers.rst  | 138 +-
 .../clang/StaticAnalyzer/Checkers/Checkers.td |  28 ++--
 clang/test/Analysis/analyzer-config.c |   2 +-
 clang/test/Analysis/cert/env31-c.c|  10 +-
 .../Analysis/cert/env34-c-cert-examples.c |  10 +-
 clang/test/Analysis/cert/env34-c.c|   4 +-
 clang/test/Analysis/invalid-ptr-checker.c |   8 +-
 7 files changed, 101 insertions(+), 99 deletions(-)

diff --git a/clang/docs/analyzer/checkers.rst b/clang/docs/analyzer/checkers.rst
index 40aa06724ccb75c..e922ee3c9f4e239 100644
--- a/clang/docs/analyzer/checkers.rst
+++ b/clang/docs/analyzer/checkers.rst
@@ -755,6 +755,75 @@ security
 
 Security related checkers.
 
+.. _security-cert-env-InvalidPtr:
+
+security.cert.env.InvalidPtr
+""
+
+Corresponds to SEI CERT Rules ENV31-C and ENV34-C.
+
+ENV31-C:
+Rule is about the possible problem with `main` function's third argument, 
environment pointer,
+"envp". When environment array is modified using some modification function
+such as putenv, setenv or others, It may happen that memory is reallocated,
+however "envp" is not updated to reflect the changes and points to old memory
+region.
+
+ENV34-C:
+Some functions return a pointer to a statically allocated buffer.
+Consequently, subsequent call of these functions will invalidate previous
+pointer. These functions include: getenv, localeconv, asctime, setlocale, 
strerror
+
+.. code-block:: c
+
+  int main(int argc, const char *argv[], const char *envp[]) {
+if (setenv("MY_NEW_VAR", "new_value", 1) != 0) {
+  // setenv call may invalidate 'envp'
+  /* Handle error */
+}
+if (envp != NULL) {
+  for (size_t i = 0; envp[i] != NULL; ++i) {
+puts(envp[i]);
+// envp may no longer point to the current environment
+// this program has unanticipated behavior, since envp
+// does not reflect changes made by setenv function.
+  }
+}
+return 0;
+  }
+
+  void previous_call_invalidation() {
+char *p, *pp;
+
+p = getenv("VAR");
+setenv("SOMEVAR", "VALUE", /*overwrite = */1);
+// call to 'setenv' may invalidate p
+
+*p;
+// dereferencing invalid pointer
+  }
+
+
+The ``InvalidatingGetEnv`` option is available for treating getenv calls as
+invalidating. When enabled, the checker issues a warning if getenv is called
+multiple times and their results are used without first creating a copy.
+This level of strictness might be considered overly pedantic for the commonly
+used getenv implementations.
+
+To enable this option, use:
+``-analyzer-config security.cert.env.InvalidPtr:InvalidatingGetEnv=true``.
+
+By default, this option is set to *false*.
+
+When this option is enabled, warnings will be generated for scenarios like the
+following:
+
+.. code-block:: c
+
+  char* p = getenv("VAR");
+  char* pp = getenv("VAR2"); // assumes this call can invalidate `env`
+  strlen(p); // warns about accessing invalid ptr
+
 .. _security-FloatLoopCounter:
 
 security.FloatLoopCounter (C)
@@ -2549,75 +2618,6 @@ alpha.security.cert.env
 
 SEI CERT checkers of `Environment C coding rules 
`_.
 
-.. _alpha-security-cert-env-InvalidPtr:
-
-alpha.security.cert.env.InvalidPtr
-""
-
-Corresponds to SEI CERT Rules ENV31-C and ENV34-C.
-
-ENV31-C:
-Rule is about the possible problem with `main` function's third argument, 
environment pointer,
-"envp". When environment array is modified using some modification function
-such as putenv, setenv or others, It may happen that memory is reallocated,
-however "envp" is not updated to reflect the changes and points to old memory
-region.
-
-ENV34-C:
-Some functions return a pointer to a statically allocated buffer.
-Consequently, subsequent call of these functions will invalidate previous
-pointer. These functions include: getenv, localeconv, asctime, setlocale, 
strerror
-
-.. code-block:: c
-
-  int main(int argc, const char *argv[], const char *envp[]) {
-if (setenv("MY_NEW_VAR", "new_value", 1) != 0) {
-  // setenv call may invalidate 'envp'
-  /* Handle error */
-}
-if (envp != NULL) {
-  for (size_t i = 0; envp[i] != NULL; ++i) {
-puts(envp[i]);
-// envp may no longer point to the current environment
-// this program ha

[clang] [Driver][MachineOutliner] Support -moutline option for aarch64_be (PR #73223)

2023-11-23 Thread dong jianqiang via cfe-commits

https://github.com/dongjianqiang2 created 
https://github.com/llvm/llvm-project/pull/73223

This patch propagates the -moutline flag when target is aarch64_be, 
fix warning: 'aarch64_be' does not support '-moutline'; flag ignored 
[-Woption-ignored]

>From 1492725fb3bb60f400264f718972ce249ec3eda8 Mon Sep 17 00:00:00 2001
From: dong jianqiang 
Date: Thu, 23 Nov 2023 16:58:11 +0800
Subject: [PATCH] [Driver][MachineOutliner] Support outlining option with LTO
 for aarch64_be

This patch propagates the -moutline flag when target is aarch64_be,
fix warning: 'aarch64_be' does not support '-moutline'; flag ignored 
[-Woption-ignored]
---
 clang/lib/Driver/ToolChains/CommonArgs.cpp | 3 ++-
 clang/test/Driver/aarch64-outliner.c   | 2 ++
 2 files changed, 4 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Driver/ToolChains/CommonArgs.cpp 
b/clang/lib/Driver/ToolChains/CommonArgs.cpp
index 5d2cd1959b06925..078f2ff80a21939 100644
--- a/clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ b/clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -2436,7 +2436,8 @@ void tools::addMachineOutlinerArgs(const Driver &D,
   // Otherwise, add the proper mllvm flags.
   if (!(Triple.isARM() || Triple.isThumb() ||
 Triple.getArch() == llvm::Triple::aarch64 ||
-Triple.getArch() == llvm::Triple::aarch64_32)) {
+Triple.getArch() == llvm::Triple::aarch64_32 ||
+Triple.getArch() == llvm::Triple::aarch64_be)) {
 D.Diag(diag::warn_drv_moutline_unsupported_opt) << 
Triple.getArchName();
   } else {
 addArg(Twine("-enable-machine-outliner"));
diff --git a/clang/test/Driver/aarch64-outliner.c 
b/clang/test/Driver/aarch64-outliner.c
index 42e43b433e282d3..06e5de11ec49ecd 100644
--- a/clang/test/Driver/aarch64-outliner.c
+++ b/clang/test/Driver/aarch64-outliner.c
@@ -1,7 +1,9 @@
 // REQUIRES: aarch64-registered-target
 // RUN: %clang --target=aarch64 -moutline -S %s -### 2>&1 | FileCheck %s 
-check-prefix=ON
+// RUN: %clang --target=aarch64_be -moutline -S %s -### 2>&1 | FileCheck %s 
-check-prefix=ON
 // ON: "-mllvm" "-enable-machine-outliner"
 // RUN: %clang --target=aarch64 -moutline -mno-outline -S %s -### 2>&1 | 
FileCheck %s -check-prefix=OFF
+// RUN: %clang --target=aarch64_be -moutline -mno-outline -S %s -### 2>&1 | 
FileCheck %s -check-prefix=OFF
 // OFF: "-mllvm" "-enable-machine-outliner=never"
 // RUN: %clang --target=x86_64 -moutline -S %s -### 2>&1 | FileCheck %s 
-check-prefix=WARN
 // WARN: warning: 'x86_64' does not support '-moutline'; flag ignored 
[-Woption-ignored]

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


[clang] [Driver][MachineOutliner] Support -moutline option for aarch64_be (PR #73223)

2023-11-23 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-driver

Author: dong jianqiang (dongjianqiang2)


Changes

This patch propagates the -moutline flag when target is aarch64_be, 
fix warning: 'aarch64_be' does not support '-moutline'; flag ignored 
[-Woption-ignored]

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


2 Files Affected:

- (modified) clang/lib/Driver/ToolChains/CommonArgs.cpp (+2-1) 
- (modified) clang/test/Driver/aarch64-outliner.c (+2) 


``diff
diff --git a/clang/lib/Driver/ToolChains/CommonArgs.cpp 
b/clang/lib/Driver/ToolChains/CommonArgs.cpp
index 5d2cd1959b06925..078f2ff80a21939 100644
--- a/clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ b/clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -2436,7 +2436,8 @@ void tools::addMachineOutlinerArgs(const Driver &D,
   // Otherwise, add the proper mllvm flags.
   if (!(Triple.isARM() || Triple.isThumb() ||
 Triple.getArch() == llvm::Triple::aarch64 ||
-Triple.getArch() == llvm::Triple::aarch64_32)) {
+Triple.getArch() == llvm::Triple::aarch64_32 ||
+Triple.getArch() == llvm::Triple::aarch64_be)) {
 D.Diag(diag::warn_drv_moutline_unsupported_opt) << 
Triple.getArchName();
   } else {
 addArg(Twine("-enable-machine-outliner"));
diff --git a/clang/test/Driver/aarch64-outliner.c 
b/clang/test/Driver/aarch64-outliner.c
index 42e43b433e282d3..06e5de11ec49ecd 100644
--- a/clang/test/Driver/aarch64-outliner.c
+++ b/clang/test/Driver/aarch64-outliner.c
@@ -1,7 +1,9 @@
 // REQUIRES: aarch64-registered-target
 // RUN: %clang --target=aarch64 -moutline -S %s -### 2>&1 | FileCheck %s 
-check-prefix=ON
+// RUN: %clang --target=aarch64_be -moutline -S %s -### 2>&1 | FileCheck %s 
-check-prefix=ON
 // ON: "-mllvm" "-enable-machine-outliner"
 // RUN: %clang --target=aarch64 -moutline -mno-outline -S %s -### 2>&1 | 
FileCheck %s -check-prefix=OFF
+// RUN: %clang --target=aarch64_be -moutline -mno-outline -S %s -### 2>&1 | 
FileCheck %s -check-prefix=OFF
 // OFF: "-mllvm" "-enable-machine-outliner=never"
 // RUN: %clang --target=x86_64 -moutline -S %s -### 2>&1 | FileCheck %s 
-check-prefix=WARN
 // WARN: warning: 'x86_64' does not support '-moutline'; flag ignored 
[-Woption-ignored]

``




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


[clang] [clang][analyzer] Move `security.cert.env.InvalidPtr` out of `alpha` (PR #71912)

2023-11-23 Thread Endre Fülöp via cfe-commits

https://github.com/gamesh411 updated 
https://github.com/llvm/llvm-project/pull/71912

From 80c1f88244b22aaa4badb26384a971d19759b660 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Endre=20F=C3=BCl=C3=B6p?= 
Date: Fri, 10 Nov 2023 10:08:58 +0100
Subject: [PATCH 1/3] [analyzer] Move security.cert.env.InvalidPtr out of alpha

Thanks to recent improvements in #67663, InvalidPtr checker does
not emit any false positives on the following OS projects:
memcached, tmux, curl, twin, vim, openssl, sqlite, ffmpeg, postgres,
tinyxml2, libwebm, xerces, bitcoin, protobuf, qtbase, contour, acid,
openrct2
---
 clang/docs/analyzer/checkers.rst  | 138 +-
 .../clang/StaticAnalyzer/Checkers/Checkers.td |  28 ++--
 clang/test/Analysis/analyzer-config.c |   2 +-
 clang/test/Analysis/cert/env31-c.c|  10 +-
 .../Analysis/cert/env34-c-cert-examples.c |  10 +-
 clang/test/Analysis/cert/env34-c.c|   4 +-
 clang/test/Analysis/invalid-ptr-checker.c |   8 +-
 7 files changed, 101 insertions(+), 99 deletions(-)

diff --git a/clang/docs/analyzer/checkers.rst b/clang/docs/analyzer/checkers.rst
index 40aa06724ccb75c..e922ee3c9f4e239 100644
--- a/clang/docs/analyzer/checkers.rst
+++ b/clang/docs/analyzer/checkers.rst
@@ -755,6 +755,75 @@ security
 
 Security related checkers.
 
+.. _security-cert-env-InvalidPtr:
+
+security.cert.env.InvalidPtr
+""
+
+Corresponds to SEI CERT Rules ENV31-C and ENV34-C.
+
+ENV31-C:
+Rule is about the possible problem with `main` function's third argument, 
environment pointer,
+"envp". When environment array is modified using some modification function
+such as putenv, setenv or others, It may happen that memory is reallocated,
+however "envp" is not updated to reflect the changes and points to old memory
+region.
+
+ENV34-C:
+Some functions return a pointer to a statically allocated buffer.
+Consequently, subsequent call of these functions will invalidate previous
+pointer. These functions include: getenv, localeconv, asctime, setlocale, 
strerror
+
+.. code-block:: c
+
+  int main(int argc, const char *argv[], const char *envp[]) {
+if (setenv("MY_NEW_VAR", "new_value", 1) != 0) {
+  // setenv call may invalidate 'envp'
+  /* Handle error */
+}
+if (envp != NULL) {
+  for (size_t i = 0; envp[i] != NULL; ++i) {
+puts(envp[i]);
+// envp may no longer point to the current environment
+// this program has unanticipated behavior, since envp
+// does not reflect changes made by setenv function.
+  }
+}
+return 0;
+  }
+
+  void previous_call_invalidation() {
+char *p, *pp;
+
+p = getenv("VAR");
+setenv("SOMEVAR", "VALUE", /*overwrite = */1);
+// call to 'setenv' may invalidate p
+
+*p;
+// dereferencing invalid pointer
+  }
+
+
+The ``InvalidatingGetEnv`` option is available for treating getenv calls as
+invalidating. When enabled, the checker issues a warning if getenv is called
+multiple times and their results are used without first creating a copy.
+This level of strictness might be considered overly pedantic for the commonly
+used getenv implementations.
+
+To enable this option, use:
+``-analyzer-config security.cert.env.InvalidPtr:InvalidatingGetEnv=true``.
+
+By default, this option is set to *false*.
+
+When this option is enabled, warnings will be generated for scenarios like the
+following:
+
+.. code-block:: c
+
+  char* p = getenv("VAR");
+  char* pp = getenv("VAR2"); // assumes this call can invalidate `env`
+  strlen(p); // warns about accessing invalid ptr
+
 .. _security-FloatLoopCounter:
 
 security.FloatLoopCounter (C)
@@ -2549,75 +2618,6 @@ alpha.security.cert.env
 
 SEI CERT checkers of `Environment C coding rules 
`_.
 
-.. _alpha-security-cert-env-InvalidPtr:
-
-alpha.security.cert.env.InvalidPtr
-""
-
-Corresponds to SEI CERT Rules ENV31-C and ENV34-C.
-
-ENV31-C:
-Rule is about the possible problem with `main` function's third argument, 
environment pointer,
-"envp". When environment array is modified using some modification function
-such as putenv, setenv or others, It may happen that memory is reallocated,
-however "envp" is not updated to reflect the changes and points to old memory
-region.
-
-ENV34-C:
-Some functions return a pointer to a statically allocated buffer.
-Consequently, subsequent call of these functions will invalidate previous
-pointer. These functions include: getenv, localeconv, asctime, setlocale, 
strerror
-
-.. code-block:: c
-
-  int main(int argc, const char *argv[], const char *envp[]) {
-if (setenv("MY_NEW_VAR", "new_value", 1) != 0) {
-  // setenv call may invalidate 'envp'
-  /* Handle error */
-}
-if (envp != NULL) {
-  for (size_t i = 0; envp[i] != NULL; ++i) {
-puts(envp[i]);
-// envp may no longer point to the current environment
-// this program ha

[clang] [clang][analyzer] Move `security.cert.env.InvalidPtr` out of `alpha` (PR #71912)

2023-11-23 Thread Endre Fülöp via cfe-commits

gamesh411 wrote:

cleaned up the commiter email, as it was pointing to an old address

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


[clang] [clang][analyzer] Support `fgetc` in StreamChecker (PR #72627)

2023-11-23 Thread Balázs Kéri via cfe-commits

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


[clang] [clang][analyzer] Support `fgetc` in StreamChecker (PR #72627)

2023-11-23 Thread Balázs Kéri via cfe-commits


@@ -101,6 +101,30 @@ void error_fwrite(void) {
   Ret = fwrite(0, 1, 10, F); // expected-warning {{Stream might be already 
closed}}
 }
 
+void error_fgetc(void) {
+  FILE *F = tmpfile();
+  if (!F)
+return;
+  int Ret = fgetc(F);
+  if (0 <= Ret && Ret <= 255) {
+clang_analyzer_eval(feof(F) || ferror(F)); // expected-warning {{FALSE}}
+  } else {
+clang_analyzer_eval(Ret == EOF);  // expected-warning {{TRUE}}
+if (feof(F)) {
+  clang_analyzer_warnIfReached(); // expected-warning {{REACHABLE}}

balazske wrote:

These `warnIfReached` calls are not necessary, because the presence of the next 
warning tells anyway that the code is reachable.

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


[clang] [clang][analyzer] Support `fgetc` in StreamChecker (PR #72627)

2023-11-23 Thread Balázs Kéri via cfe-commits


@@ -259,14 +283,33 @@ void error_indeterminate_clearerr(void) {
   fclose(F);
 }
 
+void error_indeterminate_fgetc(void) {
+  FILE *F = fopen("file", "r+");
+  if (!F)
+return;
+  int rc = fseek(F, 0, SEEK_SET);
+  if (rc) {
+if (feof(F)) {

balazske wrote:

First branch of `if` is not needed. But I still think that these tests (with 
`fgetc` and `fputc`) are not testing different conditions than the other test 
(the condition that we have a warning for _might be 'indeterminate'_), 
therefore can be removed.

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


[clang] [clang][analyzer] Support `fgetc` in StreamChecker (PR #72627)

2023-11-23 Thread Balázs Kéri via cfe-commits


@@ -303,3 +346,29 @@ void error_indeterminate_feof2(void) {
   }
   fclose(F);
 }
+
+void error_indeterminate_feof3(void) {
+  FILE *F = fopen("file", "r+");
+  if (!F)
+return;
+  if (fgetc(F) == EOF) {
+if (feof(F)) {
+  // error is feof, should be non-indeterminate
+  fputc('A', F); // no warning
+}
+  }
+  fclose(F);
+}
+
+void error_indeterminate_feof4(void) {

balazske wrote:

This test seems to be not necessary (previous tests cover these conditions), 
otherwise a more meaningful name should be chosen for it.

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


[clang] [clang][analyzer] Support `fgetc` in StreamChecker (PR #72627)

2023-11-23 Thread Balázs Kéri via cfe-commits

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


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


[clang] [clang][analyzer] Support `fgetc` in StreamChecker (PR #72627)

2023-11-23 Thread Balázs Kéri via cfe-commits


@@ -303,3 +346,29 @@ void error_indeterminate_feof2(void) {
   }
   fclose(F);
 }
+
+void error_indeterminate_feof3(void) {

balazske wrote:

This test seems to be not necessary (previous tests cover these conditions), 
otherwise a more meaningful name should be chosen for it.

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


[clang] [clang][analyzer] Support `fgetc` in StreamChecker (PR #72627)

2023-11-23 Thread Balázs Kéri via cfe-commits


@@ -259,14 +283,33 @@ void error_indeterminate_clearerr(void) {
   fclose(F);
 }
 
+void error_indeterminate_fgetc(void) {
+  FILE *F = fopen("file", "r+");
+  if (!F)
+return;
+  int rc = fseek(F, 0, SEEK_SET);
+  if (rc) {
+if (feof(F)) {
+  clang_analyzer_warnIfReached(); // no warning
+  fgetc(F);   // no warning
+} else if (ferror(F)) {
+  fgetc(F); // expected-warning {{might be 'indeterminate'}}
+} else {
+  fgetc(F); // expected-warning {{might be 'indeterminate'}}
+}
+  }
+  fclose(F);
+}
+
 void error_indeterminate_fputc(void) {
   FILE *F = fopen("file", "r+");
   if (!F)
 return;
   int rc = fseek(F, 0, SEEK_SET);
   if (rc) {
 if (feof(F)) {

balazske wrote:

The branch `feof(F)` is not needed at all here. There is a previous test case 
that tells that `feof(F)` is never true when fseek to a 0 position is called.

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


[clang] [clang][analyzer] Support `fgetc` in StreamChecker (PR #72627)

2023-11-23 Thread Balázs Kéri via cfe-commits


@@ -101,6 +101,30 @@ void error_fwrite(void) {
   Ret = fwrite(0, 1, 10, F); // expected-warning {{Stream might be already 
closed}}
 }
 
+void error_fgetc(void) {
+  FILE *F = tmpfile();
+  if (!F)
+return;
+  int Ret = fgetc(F);
+  if (0 <= Ret && Ret <= 255) {
+clang_analyzer_eval(feof(F) || ferror(F)); // expected-warning {{FALSE}}
+  } else {
+clang_analyzer_eval(Ret == EOF);  // expected-warning {{TRUE}}

balazske wrote:

A line `clang_analyzer_eval(feof(F) || ferror(F)); // expected-warning 
{{FALSE}}` can be added to check that no state is produced when none of the 
state flags are set.

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


[clang] [clang][analyzer] Support `fgetc` in StreamChecker (PR #72627)

2023-11-23 Thread Balázs Kéri via cfe-commits


@@ -768,26 +772,65 @@ void StreamChecker::evalFputc(const FnDescription *Desc, 
const CallEvent &Call,
 
   assertStreamStateOpened(OldSS);
 
+  // `fgetc` returns the read character on success, otherwise returns EOF.
   // `fputc` returns the written character on success, otherwise returns EOF.
 
-  // Generate a transition for the success state.
-  std::optional PutVal = Call.getArgSVal(0).getAs();
-  if (!PutVal)
-return;
-  ProgramStateRef StateNotFailed =
-  State->BindExpr(CE, C.getLocationContext(), *PutVal);
-  StateNotFailed =
-  StateNotFailed->set(StreamSym, StreamState::getOpened(Desc));
-  C.addTransition(StateNotFailed);
+  // Generate a transition for the success state of fputc.
+  if (!IsRead) {
+std::optional PutVal = Call.getArgSVal(0).getAs();
+if (!PutVal)
+  return;
+ProgramStateRef StateNotFailed =
+State->BindExpr(CE, C.getLocationContext(), *PutVal);
+StateNotFailed =
+StateNotFailed->set(StreamSym, 
StreamState::getOpened(Desc));
+C.addTransition(StateNotFailed);
+  }
+  // Generate a transition for the success state of fgetc.
+  // If we know the state to be FEOF at fgetc, do not add a success state.
+  else if (OldSS->ErrorState != ErrorFEof) {
+NonLoc RetVal = makeRetVal(C, CE).castAs();
+ProgramStateRef StateNotFailed =
+State->BindExpr(CE, C.getLocationContext(), RetVal);
+SValBuilder &SVB = C.getSValBuilder();
+// The returned 'unsigned char' of `fgetc` is converted to 'int',
+// so we need to check if it is in range [0, 255].
+auto CondLow = SVB.evalBinOp(State, BO_GE, RetVal,
+ SVB.makeZeroVal(C.getASTContext().IntTy),
+ SVB.getConditionType())
+   .getAs();
+auto CondHigh = SVB.evalBinOp(State, BO_LE, RetVal,
+  SVB.makeIntVal(255, C.getASTContext().IntTy),
+  SVB.getConditionType())
+.getAs();

balazske wrote:

Value "255" can be replaced with 
`SVB.getBasicValueFactory().getMaxValue(C.getASTContext().UnsignedCharTy).getLimitedValue()`
 (this is probably not always 255). Probably ASTContext can be saved into a 
variable.

https://github.com/llvm/llvm-project/pull/72627
___
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 check hicpp-ignored-remove-result (PR #73119)

2023-11-23 Thread Piotr Zegar via cfe-commits
=?utf-8?q?Bj=C3=B6rn?= Svensson 
Message-ID:
In-Reply-To: 



@@ -41,6 +42,15 @@
 #include "NoAssemblerCheck.h"
 #include "SignedBitwiseCheck.h"
 
+namespace {
+
+// Checked functions for hicpp-ignored-remove-result.
+const llvm::StringRef CheckedFunctions = "::std::remove;"

PiotrZSL wrote:

mvoe this to getModuleOptions

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


[llvm] [flang] [compiler-rt] [libcxx] [mlir] [clang] [libc] [AMDGPU] Define new targets gfx1200 and gfx1201 (PR #73133)

2023-11-23 Thread Jay Foad via cfe-commits

https://github.com/jayfoad updated 
https://github.com/llvm/llvm-project/pull/73133

>From 1011b8e7da174146dfb4c9a4bf54468ea021 Mon Sep 17 00:00:00 2001
From: Jay Foad 
Date: Tue, 21 Nov 2023 15:46:04 +
Subject: [PATCH 1/2] [AMDGPU] Define new targets gfx1200 and gfx1201

Define target names and ELF numbers for new GFX12 targets gfx1200 and
gfx1201. For now they behave identically to GFX11.
---
 clang/include/clang/Basic/Cuda.h  |  2 +
 clang/lib/Basic/Cuda.cpp  |  2 +
 clang/lib/Basic/Targets/NVPTX.cpp |  2 +
 clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp  |  2 +
 clang/test/CodeGenOpenCL/amdgpu-features.cl   |  4 +
 clang/test/Driver/amdgpu-macros.cl|  2 +
 clang/test/Driver/amdgpu-mcpu.cl  |  4 +
 clang/test/Misc/target-invalid-cpu-note.c |  4 +-
 llvm/docs/AMDGPUUsage.rst | 18 -
 llvm/include/llvm/BinaryFormat/ELF.h  |  6 +-
 llvm/include/llvm/TargetParser/TargetParser.h |  5 +-
 llvm/lib/Object/ELFObjectFile.cpp |  6 ++
 llvm/lib/ObjectYAML/ELFYAML.cpp   |  2 +
 llvm/lib/Target/AMDGPU/AMDGPU.td  | 75 ++-
 llvm/lib/Target/AMDGPU/AMDGPUSubtarget.h  |  3 +-
 llvm/lib/Target/AMDGPU/GCNProcessors.td   | 12 +++
 llvm/lib/Target/AMDGPU/GCNSubtarget.h |  1 +
 .../MCTargetDesc/AMDGPUTargetStreamer.cpp |  4 +
 llvm/lib/Target/AMDGPU/SIDefines.h|  1 +
 llvm/lib/Target/AMDGPU/SIInstrInfo.cpp|  8 ++
 llvm/lib/Target/AMDGPU/SIInstrInfo.td |  4 +-
 .../Target/AMDGPU/Utils/AMDGPUBaseInfo.cpp| 26 ++-
 llvm/lib/Target/AMDGPU/Utils/AMDGPUBaseInfo.h |  6 ++
 llvm/lib/TargetParser/TargetParser.cpp| 27 +++
 .../CodeGen/AMDGPU/directive-amdgcn-target.ll |  4 +
 .../CodeGen/AMDGPU/elf-header-flags-mach.ll   |  4 +
 .../Object/AMDGPU/elf-header-flags-mach.yaml  | 14 
 .../llvm-objdump/ELF/AMDGPU/subtarget.ll  | 12 +++
 .../llvm-readobj/ELF/amdgpu-elf-headers.test  | 18 +
 llvm/tools/llvm-readobj/ELFDumper.cpp |  4 +
 30 files changed, 272 insertions(+), 10 deletions(-)

diff --git a/clang/include/clang/Basic/Cuda.h b/clang/include/clang/Basic/Cuda.h
index 878f8d70f90c0a9..2d912bdbbd1bc59 100644
--- a/clang/include/clang/Basic/Cuda.h
+++ b/clang/include/clang/Basic/Cuda.h
@@ -113,6 +113,8 @@ enum class CudaArch {
   GFX1103,
   GFX1150,
   GFX1151,
+  GFX1200,
+  GFX1201,
   Generic, // A processor model named 'generic' if the target backend defines a
// public one.
   LAST,
diff --git a/clang/lib/Basic/Cuda.cpp b/clang/lib/Basic/Cuda.cpp
index 2307352bd3becef..65840b9f20252b6 100644
--- a/clang/lib/Basic/Cuda.cpp
+++ b/clang/lib/Basic/Cuda.cpp
@@ -135,6 +135,8 @@ static const CudaArchToStringMap arch_names[] = {
 GFX(1103), // gfx1103
 GFX(1150), // gfx1150
 GFX(1151), // gfx1151
+GFX(1200), // gfx1200
+GFX(1201), // gfx1201
 {CudaArch::Generic, "generic", ""},
 // clang-format on
 };
diff --git a/clang/lib/Basic/Targets/NVPTX.cpp 
b/clang/lib/Basic/Targets/NVPTX.cpp
index a9fc88295700b89..3a4a75b0348f209 100644
--- a/clang/lib/Basic/Targets/NVPTX.cpp
+++ b/clang/lib/Basic/Targets/NVPTX.cpp
@@ -214,6 +214,8 @@ void NVPTXTargetInfo::getTargetDefines(const LangOptions 
&Opts,
   case CudaArch::GFX1103:
   case CudaArch::GFX1150:
   case CudaArch::GFX1151:
+  case CudaArch::GFX1200:
+  case CudaArch::GFX1201:
   case CudaArch::Generic:
   case CudaArch::LAST:
 break;
diff --git a/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
index 2f7dd83bd2d65c9..9b8fbbdf8046787 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
@@ -3540,6 +3540,8 @@ void CGOpenMPRuntimeGPU::processRequiresDirective(
   case CudaArch::GFX1103:
   case CudaArch::GFX1150:
   case CudaArch::GFX1151:
+  case CudaArch::GFX1200:
+  case CudaArch::GFX1201:
   case CudaArch::Generic:
   case CudaArch::UNUSED:
   case CudaArch::UNKNOWN:
diff --git a/clang/test/CodeGenOpenCL/amdgpu-features.cl 
b/clang/test/CodeGenOpenCL/amdgpu-features.cl
index 03c20ae46faaa46..8959634572b44e9 100644
--- a/clang/test/CodeGenOpenCL/amdgpu-features.cl
+++ b/clang/test/CodeGenOpenCL/amdgpu-features.cl
@@ -49,6 +49,8 @@
 // RUN: %clang_cc1 -triple amdgcn -target-cpu gfx1103 -S -emit-llvm -o - %s | 
FileCheck --check-prefix=GFX1103 %s
 // RUN: %clang_cc1 -triple amdgcn -target-cpu gfx1150 -S -emit-llvm -o - %s | 
FileCheck --check-prefix=GFX1150 %s
 // RUN: %clang_cc1 -triple amdgcn -target-cpu gfx1151 -S -emit-llvm -o - %s | 
FileCheck --check-prefix=GFX1151 %s
+// RUN: %clang_cc1 -triple amdgcn -target-cpu gfx1200 -S -emit-llvm -o - %s | 
FileCheck --check-prefix=GFX1200 %s
+// RUN: %clang_cc1 -triple amdgcn -target-cpu gfx1201 -S -emit-llvm -o - %s | 
FileCheck --check-prefix=GFX1201 %s
 
 // RUN: %clang_cc1 -triple amdgcn -target-cpu gfx1103 -targ

[clang-tools-extra] [clang-tidy] Add check hicpp-ignored-remove-result (PR #73119)

2023-11-23 Thread Piotr Zegar via cfe-commits
=?utf-8?q?Björn?= Svensson 
Message-ID:
In-Reply-To: 



@@ -107,6 +119,14 @@ class HICPPModule : public ClangTidyModule {
 CheckFactories.registerCheck(
 "hicpp-vararg");
   }
+
+  ClangTidyOptions getModuleOptions() override {
+ClangTidyOptions Options;
+ClangTidyOptions::OptionMap &Opts = Options.CheckOptions;
+Opts["hicpp-ignored-remove-result.CheckedFunctions"] = CheckedFunctions;

PiotrZSL wrote:

Personally I'm not fan of such aliases. For me those should be simply new 
checks (aka check that inherit from a base class, override configuration and 
such configuration should not be visible outside)

https://github.com/llvm/llvm-project/pull/73119
___
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 check hicpp-ignored-remove-result (PR #73119)

2023-11-23 Thread Piotr Zegar via cfe-commits
=?utf-8?q?Björn?= Svensson 
Message-ID:
In-Reply-To: 



@@ -226,6 +226,7 @@ Clang-Tidy Checks
:doc:`google-runtime-operator `,
:doc:`google-upgrade-googletest-case `, 
"Yes"
:doc:`hicpp-exception-baseclass `,
+   :doc:`hicpp-ignored-remove-result `,

PiotrZSL wrote:

you added this as new check, not as an alias, aliases are listed bellow, that's 
why this is confusing.

https://github.com/llvm/llvm-project/pull/73119
___
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 check hicpp-ignored-remove-result (PR #73119)

2023-11-23 Thread Piotr Zegar via cfe-commits
=?utf-8?q?Björn?= Svensson 
Message-ID:
In-Reply-To: 


https://github.com/PiotrZSL commented:

Looks fine, as we got already such checks that are and are not aliases.
But consider doing this as an actually separate check instead of using an alias 
functionality.
Simply change original check, add other constructor, split storeOptions method, 
so in this check list of functions would not be configurable by end user.

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


[clang] [clang][Interp] Add inline descriptor to global variables (PR #72892)

2023-11-23 Thread Timm Baeder via cfe-commits
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= 
Message-ID:
In-Reply-To: 


https://github.com/tbaederr updated 
https://github.com/llvm/llvm-project/pull/72892

>From b5360dd44bd5d8f10287e0a3641b0846e051a5c4 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Mon, 20 Nov 2023 11:53:40 +0100
Subject: [PATCH 1/3] [clang][Interp] Add inline descriptor to global variables

---
 clang/lib/AST/Interp/ByteCodeExprGen.cpp | 15 ++-
 clang/lib/AST/Interp/Descriptor.cpp  | 27 ++--
 clang/lib/AST/Interp/Descriptor.h|  6 ++-
 clang/lib/AST/Interp/Interp.cpp  | 16 +++
 clang/lib/AST/Interp/Interp.h| 23 +++---
 clang/lib/AST/Interp/Pointer.cpp |  4 +-
 clang/lib/AST/Interp/Pointer.h   | 30 +
 clang/lib/AST/Interp/Program.cpp | 56 +---
 clang/test/AST/Interp/cxx17.cpp  | 23 --
 clang/test/AST/Interp/cxx23.cpp  | 27 +++-
 clang/test/AST/Interp/literals.cpp   | 17 +++
 11 files changed, 185 insertions(+), 59 deletions(-)

diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 5dc1f9dfb10ff32..180749a75ebd22e 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -662,13 +662,26 @@ bool ByteCodeExprGen::VisitInitListExpr(const 
InitListExpr *E) {
 return this->visitInitList(E->inits(), E);
 
   if (T->isArrayType()) {
-// FIXME: Array fillers.
 unsigned ElementIndex = 0;
 for (const Expr *Init : E->inits()) {
   if (!this->visitArrayElemInit(ElementIndex, Init))
 return false;
   ++ElementIndex;
 }
+
+// Expand the filler expression.
+// FIXME: This should go away.
+if (const Expr *Filler = E->getArrayFiller()) {
+  const ConstantArrayType *CAT =
+  Ctx.getASTContext().getAsConstantArrayType(E->getType());
+  uint64_t NumElems = CAT->getSize().getZExtValue();
+
+  for (; ElementIndex != NumElems; ++ElementIndex) {
+if (!this->visitArrayElemInit(ElementIndex, Filler))
+  return false;
+  }
+}
+
 return true;
   }
 
diff --git a/clang/lib/AST/Interp/Descriptor.cpp 
b/clang/lib/AST/Interp/Descriptor.cpp
index 59a952135a2d809..7330295132618ed 100644
--- a/clang/lib/AST/Interp/Descriptor.cpp
+++ b/clang/lib/AST/Interp/Descriptor.cpp
@@ -243,18 +243,19 @@ Descriptor::Descriptor(const DeclTy &D, PrimType Type, 
MetadataSize MD,
bool IsMutable)
 : Source(D), ElemSize(primSize(Type)), Size(ElemSize * NumElems),
   MDSize(MD.value_or(0)),
-  AllocSize(align(Size) + sizeof(InitMapPtr) + MDSize), IsConst(IsConst),
-  IsMutable(IsMutable), IsTemporary(IsTemporary), IsArray(true),
-  CtorFn(getCtorArrayPrim(Type)), DtorFn(getDtorArrayPrim(Type)),
-  MoveFn(getMoveArrayPrim(Type)) {
+  AllocSize(align(MDSize) + align(Size) + sizeof(InitMapPtr)),
+  IsConst(IsConst), IsMutable(IsMutable), IsTemporary(IsTemporary),
+  IsArray(true), CtorFn(getCtorArrayPrim(Type)),
+  DtorFn(getDtorArrayPrim(Type)), MoveFn(getMoveArrayPrim(Type)) {
   assert(Source && "Missing source");
 }
 
 /// Primitive unknown-size arrays.
-Descriptor::Descriptor(const DeclTy &D, PrimType Type, bool IsTemporary,
-   UnknownSize)
-: Source(D), ElemSize(primSize(Type)), Size(UnknownSizeMark), MDSize(0),
-  AllocSize(alignof(void *) + sizeof(InitMapPtr)), IsConst(true),
+Descriptor::Descriptor(const DeclTy &D, PrimType Type, MetadataSize MD,
+   bool IsTemporary, UnknownSize)
+: Source(D), ElemSize(primSize(Type)), Size(UnknownSizeMark),
+  MDSize(MD.value_or(0)),
+  AllocSize(MDSize + sizeof(InitMapPtr) + alignof(void *)), IsConst(true),
   IsMutable(false), IsTemporary(IsTemporary), IsArray(true),
   CtorFn(getCtorArrayPrim(Type)), DtorFn(getDtorArrayPrim(Type)),
   MoveFn(getMoveArrayPrim(Type)) {
@@ -275,12 +276,12 @@ Descriptor::Descriptor(const DeclTy &D, const Descriptor 
*Elem, MetadataSize MD,
 }
 
 /// Unknown-size arrays of composite elements.
-Descriptor::Descriptor(const DeclTy &D, Descriptor *Elem, bool IsTemporary,
-   UnknownSize)
+Descriptor::Descriptor(const DeclTy &D, Descriptor *Elem, MetadataSize MD,
+   bool IsTemporary, UnknownSize)
 : Source(D), ElemSize(Elem->getAllocSize() + sizeof(InlineDescriptor)),
-  Size(UnknownSizeMark), MDSize(0),
-  AllocSize(alignof(void *) + sizeof(InitMapPtr)), ElemDesc(Elem),
-  IsConst(true), IsMutable(false), IsTemporary(IsTemporary), IsArray(true),
+  Size(UnknownSizeMark), MDSize(MD.value_or(0)),
+  AllocSize(MDSize + alignof(void *)), ElemDesc(Elem), IsConst(true),
+  IsMutable(false), IsTemporary(IsTemporary), IsArray(true),
   CtorFn(ctorArrayDesc), DtorFn(dtorArrayDesc), MoveFn(moveArrayDesc) {
   assert(Source && "Missing source");
 }
diff --git a/clang/l

[clang] 272812c - Revert "[clang] Avoid memcopy for small structure with padding under -ftrivial-auto-var-init (#71677)"

2023-11-23 Thread Muhammad Omair Javaid via cfe-commits

Author: Muhammad Omair Javaid
Date: 2023-11-23T15:45:00+05:00
New Revision: 272812c7e43d8a45f19ea7b4a3b2667e7fb9e67a

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

LOG: Revert "[clang] Avoid memcopy for small structure with padding under 
-ftrivial-auto-var-init (#71677)"

This reverts commit 0d2860b795879f4dd152963b52f969b53b136899.

This change appears to have broken several clang tests on following buildbots:
https://lab.llvm.org/buildbot/#/builders/245
https://lab.llvm.org/buildbot/#/builders/188
https://lab.llvm.org/buildbot/#/builders/186
https://lab.llvm.org/buildbot/#/builders/183

Added: 


Modified: 
clang/lib/CodeGen/CGDecl.cpp
clang/test/CodeGenCXX/auto-var-init.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGDecl.cpp b/clang/lib/CodeGen/CGDecl.cpp
index a5da0aa2965a000..e5795d811c76de7 100644
--- a/clang/lib/CodeGen/CGDecl.cpp
+++ b/clang/lib/CodeGen/CGDecl.cpp
@@ -1244,24 +1244,29 @@ static void emitStoresForConstant(CodeGenModule &CGM, 
const VarDecl &D,
   // If the initializer is small, use a handful of stores.
   if (shouldSplitConstantStore(CGM, ConstantSize)) {
 if (auto *STy = dyn_cast(Ty)) {
-  const llvm::StructLayout *Layout =
-  CGM.getDataLayout().getStructLayout(STy);
-  for (unsigned i = 0; i != constant->getNumOperands(); i++) {
-CharUnits CurOff = 
CharUnits::fromQuantity(Layout->getElementOffset(i));
-Address EltPtr = Builder.CreateConstInBoundsByteGEP(
-Loc.withElementType(CGM.Int8Ty), CurOff);
-emitStoresForConstant(CGM, D, EltPtr, isVolatile, Builder,
-  constant->getAggregateElement(i), IsAutoInit);
+  // FIXME: handle the case when STy != Loc.getElementType().
+  if (STy == Loc.getElementType()) {
+for (unsigned i = 0; i != constant->getNumOperands(); i++) {
+  Address EltPtr = Builder.CreateStructGEP(Loc, i);
+  emitStoresForConstant(
+  CGM, D, EltPtr, isVolatile, Builder,
+  cast(Builder.CreateExtractValue(constant, i)),
+  IsAutoInit);
+}
+return;
   }
-  return;
 } else if (auto *ATy = dyn_cast(Ty)) {
-  for (unsigned i = 0; i != ATy->getNumElements(); i++) {
-Address EltPtr = Builder.CreateConstGEP(
-Loc.withElementType(ATy->getElementType()), i);
-emitStoresForConstant(CGM, D, EltPtr, isVolatile, Builder,
-  constant->getAggregateElement(i), IsAutoInit);
+  // FIXME: handle the case when ATy != Loc.getElementType().
+  if (ATy == Loc.getElementType()) {
+for (unsigned i = 0; i != ATy->getNumElements(); i++) {
+  Address EltPtr = Builder.CreateConstArrayGEP(Loc, i);
+  emitStoresForConstant(
+  CGM, D, EltPtr, isVolatile, Builder,
+  cast(Builder.CreateExtractValue(constant, i)),
+  IsAutoInit);
+}
+return;
   }
-  return;
 }
   }
 

diff  --git a/clang/test/CodeGenCXX/auto-var-init.cpp 
b/clang/test/CodeGenCXX/auto-var-init.cpp
index e5a9d015f22f276..6cb18528ebadcdf 100644
--- a/clang/test/CodeGenCXX/auto-var-init.cpp
+++ b/clang/test/CodeGenCXX/auto-var-init.cpp
@@ -89,14 +89,22 @@ struct padded { char c; int i; };
 // PATTERN-O1-NOT: @__const.test_paddednullinit_custom.custom
 struct paddednullinit { char c = 0; int i = 0; };
 // PATTERN-O0: @__const.test_paddedpacked_uninit.uninit = private unnamed_addr 
constant %struct.paddedpacked <{ i8 [[I8]], i32 [[I32]] }>, align 1
+// PATTERN: @__const.test_paddedpacked_custom.custom = private unnamed_addr 
constant %struct.paddedpacked <{ i8 42, i32 13371337 }>, align 1
+// ZERO: @__const.test_paddedpacked_custom.custom = private unnamed_addr 
constant %struct.paddedpacked <{ i8 42, i32 13371337 }>, align 1
 struct paddedpacked { char c; int i; } __attribute__((packed));
 // PATTERN-O0: @__const.test_paddedpackedarray_uninit.uninit = private 
unnamed_addr constant %struct.paddedpackedarray { [2 x %struct.paddedpacked] 
[%struct.paddedpacked <{ i8 [[I8]], i32 [[I32]] }>, %struct.paddedpacked <{ i8 
[[I8]], i32 [[I32]] }>] }, align 1
+// PATTERN: @__const.test_paddedpackedarray_custom.custom = private 
unnamed_addr constant %struct.paddedpackedarray { [2 x %struct.paddedpacked] 
[%struct.paddedpacked <{ i8 42, i32 13371337 }>, %struct.paddedpacked <{ i8 43, 
i32 13371338 }>] }, align 1
+// ZERO: @__const.test_paddedpackedarray_custom.custom = private unnamed_addr 
constant %struct.paddedpackedarray { [2 x %struct.paddedpacked] 
[%struct.paddedpacked <{ i8 42, i32 13371337 }>, %struct.paddedpacked <{ i8 43, 
i32 13371338 }>] }, align 1
 struct paddedpackedarray { struct paddedpacked p[2]; };
 // PATTERN-O0: @__const.test_unpackedinpacked_uninit.uninit =

[clang] [clang][AST][ASTMerge] prevent AST nodes from being deallocated early (PR #73096)

2023-11-23 Thread Balázs Kéri via cfe-commits

balazske wrote:

You have found that reason for the crash is that references to `IdentifierInfo` 
are remaining in `OnDiskChainedHashTableGenerator` and previously deallocated 
by `ASTUnit` destruction? In this case why is the `ASTUnit` (or something in 
it, probably `ASTContext`) the owner of the data, and not 
`OnDiskChainedHashTableGenerator`?
By using `ASTImporter` it is possible that it moves data from the "old" AST to 
the "new" without copy (if yes this is a bug) and such a situation can cause 
memory errors.

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


[clang] [clang][ASTImporter] Fix import of variable template redeclarations. (PR #72841)

2023-11-23 Thread Balázs Kéri via cfe-commits

balazske wrote:

I plan to fix import of `VarTemplateSpecializationDecl` in a different PR. The 
indicated assertion "Missing call to MapImported?" is likely to related to this 
part.

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


[flang] [clang] [flang] Enable alias tags pass by default (PR #73111)

2023-11-23 Thread Andrzej Warzyński via cfe-commits

https://github.com/banach-space commented:

Makes sense, but the summary should document when exactly the alias analysis is 
enabled/disabled. And the relationship between `-f{no}-alias-analysis` and the 
optimisation flags. 

Could you also add a note whether the implemented behaviour is consistent with 
Clang? 

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


[clang] [flang] [flang] Enable alias tags pass by default (PR #73111)

2023-11-23 Thread Andrzej Warzyński via cfe-commits


@@ -242,10 +242,24 @@ static void 
parseCodeGenArgs(Fortran::frontend::CodeGenOptions &opts,
clang::driver::options::OPT_fno_loop_versioning, false))
 opts.LoopVersioning = 1;
 
-  opts.AliasAnalysis =
-  args.hasFlag(clang::driver::options::OPT_falias_analysis,
-   clang::driver::options::OPT_fno_alias_analysis,
-   /*default=*/false);
+  bool aliasAnalysis = false;
+  bool noAliasAnalysis = false;
+  if (auto *arg =
+  args.getLastArg(clang::driver::options::OPT_falias_analysis,
+  clang::driver::options::OPT_fno_alias_analysis)) {
+if (arg->getOption().matches(clang::driver::options::OPT_falias_analysis))
+  aliasAnalysis = true;
+else
+  noAliasAnalysis = true;
+  }
+  opts.AliasAnalysis = 0;
+  if (opts.OptimizationLevel > 0) {
+if (!noAliasAnalysis)
+  opts.AliasAnalysis = 1;
+  } else {
+if (aliasAnalysis)
+  opts.AliasAnalysis = 1;
+  }

banach-space wrote:

```suggestion
  if (auto *arg =
  args.getLastArg(clang::driver::options::OPT_falias_analysis,
  clang::driver::options::OPT_fno_alias_analysis)) {
opts.AliasAnalysis = 
(arg->getOption().matches(clang::driver::options::OPT_falias_analysis)) ? : 0;
  }
```
Why wouldn't this work?

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


[clang] [flang] [flang] Enable alias tags pass by default (PR #73111)

2023-11-23 Thread Andrzej Warzyński via cfe-commits

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


[clang] [flang] [flang] Enable alias tags pass by default (PR #73111)

2023-11-23 Thread Andrzej Warzyński via cfe-commits


@@ -142,6 +142,26 @@ void Flang::addCodegenOptions(const ArgList &Args,
   if (shouldLoopVersion(Args))
 CmdArgs.push_back("-fversion-loops-for-stride");
 
+  Arg *aliasAnalysis = Args.getLastArg(options::OPT_falias_analysis,
+   options::OPT_fno_alias_analysis);
+  Arg *optLevel =
+  Args.getLastArg(options::OPT_Ofast, options::OPT_O, options::OPT_O4);

banach-space wrote:

> But I want there to still be a separate flag available to override this 
> default behavior.

That's fine, but then one has to decide whether `-f{no}-alias-analysis` 
overrides `-O{n}` or not? I think that "explicit" request from a user should 
always take precedence. This leads to (pseudo code):
```
opts.AliasAnalysis = 0;
if (opt level requiring alias analysis)
  opts.AliasAnalysis  = 1;

// User request takes precedence when it comes to alias analysis.
if (-falias-analysis or -fno-alias-analysis) then
  "do whatever the user requested"
```

Separately, could you check what Clang does and make sure that that would be 
consistent?

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


[clang] [flang] [flang] Enable alias tags pass by default (PR #73111)

2023-11-23 Thread Tom Eccles via cfe-commits


@@ -242,10 +242,24 @@ static void 
parseCodeGenArgs(Fortran::frontend::CodeGenOptions &opts,
clang::driver::options::OPT_fno_loop_versioning, false))
 opts.LoopVersioning = 1;
 
-  opts.AliasAnalysis =
-  args.hasFlag(clang::driver::options::OPT_falias_analysis,
-   clang::driver::options::OPT_fno_alias_analysis,
-   /*default=*/false);
+  bool aliasAnalysis = false;
+  bool noAliasAnalysis = false;
+  if (auto *arg =
+  args.getLastArg(clang::driver::options::OPT_falias_analysis,
+  clang::driver::options::OPT_fno_alias_analysis)) {
+if (arg->getOption().matches(clang::driver::options::OPT_falias_analysis))
+  aliasAnalysis = true;
+else
+  noAliasAnalysis = true;
+  }
+  opts.AliasAnalysis = 0;
+  if (opts.OptimizationLevel > 0) {
+if (!noAliasAnalysis)
+  opts.AliasAnalysis = 1;
+  } else {
+if (aliasAnalysis)
+  opts.AliasAnalysis = 1;
+  }

tblah wrote:

Then opts.AliasAnalysis would be false whenever -falias-analysis is not 
present. We want to enable it by default when optimizing.

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


[clang] [flang] [flang] Enable alias tags pass by default (PR #73111)

2023-11-23 Thread Andrzej Warzyński via cfe-commits


@@ -242,10 +242,24 @@ static void 
parseCodeGenArgs(Fortran::frontend::CodeGenOptions &opts,
clang::driver::options::OPT_fno_loop_versioning, false))
 opts.LoopVersioning = 1;
 
-  opts.AliasAnalysis =
-  args.hasFlag(clang::driver::options::OPT_falias_analysis,
-   clang::driver::options::OPT_fno_alias_analysis,
-   /*default=*/false);
+  bool aliasAnalysis = false;
+  bool noAliasAnalysis = false;
+  if (auto *arg =
+  args.getLastArg(clang::driver::options::OPT_falias_analysis,
+  clang::driver::options::OPT_fno_alias_analysis)) {
+if (arg->getOption().matches(clang::driver::options::OPT_falias_analysis))
+  aliasAnalysis = true;
+else
+  noAliasAnalysis = true;
+  }
+  opts.AliasAnalysis = 0;
+  if (opts.OptimizationLevel > 0) {
+if (!noAliasAnalysis)
+  opts.AliasAnalysis = 1;
+  } else {
+if (aliasAnalysis)
+  opts.AliasAnalysis = 1;
+  }

banach-space wrote:

It won't if you implement this logic: 
https://github.com/llvm/llvm-project/pull/73111#discussion_r1403215158

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


[llvm] [clang] [flang] [Flang] Add code-object-version option (PR #72638)

2023-11-23 Thread Andrzej Warzyński via cfe-commits

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


[flang] [llvm] [clang] [Flang] Add code-object-version option (PR #72638)

2023-11-23 Thread Andrzej Warzyński via cfe-commits


@@ -85,6 +85,19 @@ class CodeGenOptions : public CodeGenOptionsBase {
 RK_WithPattern, // Remark pattern specified via '-Rgroup=regexp'.
   };
 
+  /// \brief Enumeration value for AMDGPU code object version, which is the
+  /// code object version times 100.
+  enum class CodeObjectVersionKind {
+COV_None,
+COV_2 = 200, // Unsupported.
+COV_3 = 300, // Unsupported.

banach-space wrote:

> BTW. Is it possible to set the default version for Flang in similar way as it 
> is done for Clang? 

Sadly, ATM, Flang does not use the "option marshaling" logic/macros. I am not 
aware of anyone working on this.

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


[flang] [clang] [llvm] [Flang] Add code-object-version option (PR #72638)

2023-11-23 Thread Andrzej Warzyński via cfe-commits


@@ -121,6 +121,16 @@ namespace llvm {
 Never,
   };
 
+  /// \brief Enumeration value for AMDGPU code object version, which is the
+  /// code object version times 100.

banach-space wrote:

[nit] 
```suggestion
  /// \brief Enumeration value for AMDGPU code object version (COV), which is 
the
  /// code object version times 100.
```

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


[clang] [llvm] [flang] [Flang] Add code-object-version option (PR #72638)

2023-11-23 Thread Andrzej Warzyński via cfe-commits

https://github.com/banach-space approved this pull request.

Thanks for addressing my comments, the driver changes LGTM!

Please wait for other reviewers to approve before landing this. In particular, 
I am not qualified to tell whether the bits specific to AMD GPUs  are correct 
:) 

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


[clang] [flang] [flang] Enable alias tags pass by default (PR #73111)

2023-11-23 Thread Tom Eccles via cfe-commits


@@ -242,10 +242,24 @@ static void 
parseCodeGenArgs(Fortran::frontend::CodeGenOptions &opts,
clang::driver::options::OPT_fno_loop_versioning, false))
 opts.LoopVersioning = 1;
 
-  opts.AliasAnalysis =
-  args.hasFlag(clang::driver::options::OPT_falias_analysis,
-   clang::driver::options::OPT_fno_alias_analysis,
-   /*default=*/false);
+  bool aliasAnalysis = false;
+  bool noAliasAnalysis = false;
+  if (auto *arg =
+  args.getLastArg(clang::driver::options::OPT_falias_analysis,
+  clang::driver::options::OPT_fno_alias_analysis)) {
+if (arg->getOption().matches(clang::driver::options::OPT_falias_analysis))
+  aliasAnalysis = true;
+else
+  noAliasAnalysis = true;
+  }
+  opts.AliasAnalysis = 0;
+  if (opts.OptimizationLevel > 0) {
+if (!noAliasAnalysis)
+  opts.AliasAnalysis = 1;
+  } else {
+if (aliasAnalysis)
+  opts.AliasAnalysis = 1;
+  }

tblah wrote:

I don't really understand how that differs from what I already have. But sure 
I'll do it if you think it is clearer.

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


[clang] [clang-format] Fix a bug in formating `#define A x:` (PR #73220)

2023-11-23 Thread Björn Schäpers via cfe-commits


@@ -1171,6 +1171,13 @@ void UnwrappedLineParser::parsePPDefine() {
   assert((int)Line->PPLevel >= 0);
   Line->InMacroBody = true;
 
+  if (FormatTok->is(tok::identifier) &&
+  Tokens->peekNextToken()->is(tok::colon)) {
+nextToken();
+nextToken();
+addUnwrappedLine();

HazardyKnusperkeks wrote:

Why that new line?

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


[clang] [SystemZ] Move new test into existing CodeGen test. (PR #73230)

2023-11-23 Thread Jonas Paulsson via cfe-commits

https://github.com/JonPsson1 created 
https://github.com/llvm/llvm-project/pull/73230

The test for emitted alignments is better placed in CodeGen.


>From 72e252610893f919d25916b800d2afd1f8b0b9a4 Mon Sep 17 00:00:00 2001
From: Jonas Paulsson 
Date: Thu, 23 Nov 2023 12:33:11 +0100
Subject: [PATCH] [SystemZ] Move new test into existing CodeGen test.

---
 clang/test/CodeGen/SystemZ/align-systemz.c | 13 +
 clang/test/Driver/systemz-alignment.c  | 32 --
 2 files changed, 13 insertions(+), 32 deletions(-)
 delete mode 100644 clang/test/Driver/systemz-alignment.c

diff --git a/clang/test/CodeGen/SystemZ/align-systemz.c 
b/clang/test/CodeGen/SystemZ/align-systemz.c
index 5ba446665fef803..9daff6ee9760974 100644
--- a/clang/test/CodeGen/SystemZ/align-systemz.c
+++ b/clang/test/CodeGen/SystemZ/align-systemz.c
@@ -25,6 +25,19 @@ void func (void)
   s = es;
 }
 
+// Test that a global variable with an incomplete type gets the minimum
+// alignment of 2 per the ABI if no alignment was specified by user.
+//
+// CHECK-DAG: @VarNoAl {{.*}} align 2
+// CHECK-DAG: @VarExplAl1  {{.*}} align 1
+// CHECK-DAG: @VarExplAl4  {{.*}} align 4
+struct incomplete_ty;
+extern struct incomplete_ty VarNoAl;
+extern struct incomplete_ty __attribute__((aligned(1))) VarExplAl1;
+extern struct incomplete_ty __attribute__((aligned(4))) VarExplAl4;
+struct incomplete_ty *fun0 (void) { return &VarNoAl; }
+struct incomplete_ty *fun1 (void) { return &VarExplAl1; }
+struct incomplete_ty *fun2 (void) { return &VarExplAl4; }
 
 // The SystemZ ABI aligns __int128_t to only eight bytes.
 
diff --git a/clang/test/Driver/systemz-alignment.c 
b/clang/test/Driver/systemz-alignment.c
deleted file mode 100644
index 6f3b2bc38be3688..000
--- a/clang/test/Driver/systemz-alignment.c
+++ /dev/null
@@ -1,32 +0,0 @@
-// RUN: %clang --target=s390x-linux -S -emit-llvm -o - %s | FileCheck %s
-//
-// Test that a global variable with an incomplete type gets the minimum
-// alignment of 2 per the ABI if no alignment was specified by user.
-//
-// CHECK:  @VarNoAl {{.*}} align 2
-// CHECK-NEXT: @VarExplAl1  {{.*}} align 1
-// CHECK-NEXT: @VarExplAl4  {{.*}} align 4
-
-// No alignemnt specified by user.
-struct incomplete_ty_noal;
-extern struct incomplete_ty_noal VarNoAl;
-struct incomplete_ty_noal *fun0 (void)
-{
-  return &VarNoAl;
-}
-
-// User-specified alignment of 1.
-struct incomplete_ty_al1;
-extern struct incomplete_ty_al1 __attribute__((aligned(1))) VarExplAl1;
-struct incomplete_ty_al1 *fun1 (void)
-{
-  return &VarExplAl1;
-}
-
-// User-specified alignment of 4.
-struct incomplete_ty_al4;
-extern struct incomplete_ty_al4 __attribute__((aligned(4))) VarExplAl4;
-struct incomplete_ty_al4 *fun2 (void)
-{
-  return &VarExplAl4;
-}

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


[clang] [SystemZ] Move new test into existing CodeGen test. (PR #73230)

2023-11-23 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang

@llvm/pr-subscribers-clang-driver

Author: Jonas Paulsson (JonPsson1)


Changes

The test for emitted alignments is better placed in CodeGen.


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


2 Files Affected:

- (modified) clang/test/CodeGen/SystemZ/align-systemz.c (+13) 
- (removed) clang/test/Driver/systemz-alignment.c (-32) 


``diff
diff --git a/clang/test/CodeGen/SystemZ/align-systemz.c 
b/clang/test/CodeGen/SystemZ/align-systemz.c
index 5ba446665fef803..9daff6ee9760974 100644
--- a/clang/test/CodeGen/SystemZ/align-systemz.c
+++ b/clang/test/CodeGen/SystemZ/align-systemz.c
@@ -25,6 +25,19 @@ void func (void)
   s = es;
 }
 
+// Test that a global variable with an incomplete type gets the minimum
+// alignment of 2 per the ABI if no alignment was specified by user.
+//
+// CHECK-DAG: @VarNoAl {{.*}} align 2
+// CHECK-DAG: @VarExplAl1  {{.*}} align 1
+// CHECK-DAG: @VarExplAl4  {{.*}} align 4
+struct incomplete_ty;
+extern struct incomplete_ty VarNoAl;
+extern struct incomplete_ty __attribute__((aligned(1))) VarExplAl1;
+extern struct incomplete_ty __attribute__((aligned(4))) VarExplAl4;
+struct incomplete_ty *fun0 (void) { return &VarNoAl; }
+struct incomplete_ty *fun1 (void) { return &VarExplAl1; }
+struct incomplete_ty *fun2 (void) { return &VarExplAl4; }
 
 // The SystemZ ABI aligns __int128_t to only eight bytes.
 
diff --git a/clang/test/Driver/systemz-alignment.c 
b/clang/test/Driver/systemz-alignment.c
deleted file mode 100644
index 6f3b2bc38be3688..000
--- a/clang/test/Driver/systemz-alignment.c
+++ /dev/null
@@ -1,32 +0,0 @@
-// RUN: %clang --target=s390x-linux -S -emit-llvm -o - %s | FileCheck %s
-//
-// Test that a global variable with an incomplete type gets the minimum
-// alignment of 2 per the ABI if no alignment was specified by user.
-//
-// CHECK:  @VarNoAl {{.*}} align 2
-// CHECK-NEXT: @VarExplAl1  {{.*}} align 1
-// CHECK-NEXT: @VarExplAl4  {{.*}} align 4
-
-// No alignemnt specified by user.
-struct incomplete_ty_noal;
-extern struct incomplete_ty_noal VarNoAl;
-struct incomplete_ty_noal *fun0 (void)
-{
-  return &VarNoAl;
-}
-
-// User-specified alignment of 1.
-struct incomplete_ty_al1;
-extern struct incomplete_ty_al1 __attribute__((aligned(1))) VarExplAl1;
-struct incomplete_ty_al1 *fun1 (void)
-{
-  return &VarExplAl1;
-}
-
-// User-specified alignment of 4.
-struct incomplete_ty_al4;
-extern struct incomplete_ty_al4 __attribute__((aligned(4))) VarExplAl4;
-struct incomplete_ty_al4 *fun2 (void)
-{
-  return &VarExplAl4;
-}

``




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


[clang] [clang] Ensure minimal alignment of global vars of incomplete type. (PR #72886)

2023-11-23 Thread Jonas Paulsson via cfe-commits


@@ -0,0 +1,32 @@
+// RUN: %clang --target=s390x-linux -S -emit-llvm -o - %s | FileCheck %s

JonPsson1 wrote:

Sorry, my bad. There is a SystemZ test for this already, so I moved these tests 
into it instead. I created a new PR: 
https://github.com/llvm/llvm-project/pull/73230.


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


[clang] [SystemZ] Move new test into existing CodeGen test. (PR #73230)

2023-11-23 Thread Jonas Paulsson via cfe-commits

JonPsson1 wrote:

Moving recently added tests from Driver to CodeGen, per discussion for original 
PR (https://github.com/llvm/llvm-project/pull/72886).


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


[clang] [flang] [flang] Enable alias tags pass by default (PR #73111)

2023-11-23 Thread Tom Eccles via cfe-commits


@@ -142,6 +142,26 @@ void Flang::addCodegenOptions(const ArgList &Args,
   if (shouldLoopVersion(Args))
 CmdArgs.push_back("-fversion-loops-for-stride");
 
+  Arg *aliasAnalysis = Args.getLastArg(options::OPT_falias_analysis,
+   options::OPT_fno_alias_analysis);
+  Arg *optLevel =
+  Args.getLastArg(options::OPT_Ofast, options::OPT_O, options::OPT_O4);

tblah wrote:

It turns out flang doesn't support `-Os`. Probably a bug here 
https://github.com/llvm/llvm-project/blob/main/flang/lib/Frontend/CompilerInvocation.cpp#L110

https://github.com/llvm/llvm-project/pull/73111
___
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 check hicpp-ignored-remove-result (PR #73119)

2023-11-23 Thread Björn Svensson via cfe-commits

bjosv wrote:

Great, I'll have a go at it to move it into a separate check.
I used `cert-err33-c` as a blueprint and maybe that check can be updated later 
as well if we find a good model.

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


[clang] [Driver] Add support for -export-dynamic which can match GCC behavior. (PR #72781)

2023-11-23 Thread dong jianqiang via cfe-commits

dongjianqiang2 wrote:

> export-dynamic

In that case, we have got to change `-exxx` to `-e xxx`, and `-export-dynamic` 
to `-rdynamic`. LGTM, and it follows GCC's official documented spec : )

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


[clang] [Clang] Improve support for expression messages in `static_assert` (PR #73234)

2023-11-23 Thread via cfe-commits

https://github.com/cor3ntin created 
https://github.com/llvm/llvm-project/pull/73234

- Support non-member functions and callable objects for size and data(). We 
previously tried to (badly) pick the best overload ourselves, in a way that 
would only support member functions. We now leave clamg construct an unresolved 
member expression and call that, properly performing overload resolution with 
callable objects and static functions, cojnsistent with the logic for `get` 
calls for structured bindings.
- Support UDLs as message expression.
- Add tests and mark CWG2798 as resolved

>From c8f8e6d0a88b9fd1d905ca0a09ffe6e0415ab90e Mon Sep 17 00:00:00 2001
From: Corentin Jabot 
Date: Thu, 23 Nov 2023 12:51:46 +0100
Subject: [PATCH] [Clang] Improve support for expression messages in
 `static_assert`

- Support non-member functions and callable objects for size and data().
  We previously tried to (badly) pick the best overload ourselves,
  in a way that would only support member functions.
  We now leave clamg construct an unresolved member expression and call that,
  properly performing overload resolution with callable objects and
  static functions, cojnsistent with the logic for `get` calls for structured 
bindings.
- Support UDLs as message expression.
- Add tests and mark CWG2798 as resolved
---
 clang/docs/ReleaseNotes.rst|  3 ++
 clang/lib/Parse/ParseDeclCXX.cpp   |  2 +-
 clang/lib/Sema/SemaDeclCXX.cpp | 24 ++
 clang/test/CXX/drs/dr27xx.cpp  | 30 
 clang/test/SemaCXX/static-assert-cxx26.cpp | 54 ++
 clang/www/cxx_dr_status.html   |  2 +-
 6 files changed, 82 insertions(+), 33 deletions(-)
 create mode 100644 clang/test/CXX/drs/dr27xx.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 7e2c990d03e7f27..5a8e63be1258a28 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -617,6 +617,9 @@ Bug Fixes in This Version
 - Fix crash during code generation of C++ coroutine initial suspend when the 
return
   type of await_resume is not trivially destructible.
   Fixes (`#63803 `_)
+- Fix crash when the object used as a ``static_asssert`` message has ``size`` 
or ``data`` members
+  which are not member functions.
+- Support UDLs in ``static_asssert`` message.
 
 Bug Fixes to Compiler Builtins
 ^^
diff --git a/clang/lib/Parse/ParseDeclCXX.cpp b/clang/lib/Parse/ParseDeclCXX.cpp
index d9125955fda2783..910112ecae964cc 100644
--- a/clang/lib/Parse/ParseDeclCXX.cpp
+++ b/clang/lib/Parse/ParseDeclCXX.cpp
@@ -1023,7 +1023,7 @@ Decl *Parser::ParseStaticAssertDeclaration(SourceLocation 
&DeclEnd) {
 const Token &T = GetLookAheadToken(I);
 if (T.is(tok::r_paren))
   break;
-if (!tokenIsLikeStringLiteral(T, getLangOpts())) {
+if (!tokenIsLikeStringLiteral(T, getLangOpts()) || T.hasUDSuffix()) {
   ParseAsExpression = true;
   break;
 }
diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 3688192e6cbe5c5..01e2be3a45be85a 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -17291,33 +17291,15 @@ bool Sema::EvaluateStaticAssertMessageAsString(Expr 
*Message,
 
   auto FindMember = [&](StringRef Member, bool &Empty,
 bool Diag = false) -> std::optional {
-QualType ObjectType = Message->getType();
-Expr::Classification ObjectClassification =
-Message->Classify(getASTContext());
-
 DeclarationName DN = PP.getIdentifierInfo(Member);
 LookupResult MemberLookup(*this, DN, Loc, Sema::LookupMemberName);
 LookupQualifiedName(MemberLookup, RD);
 Empty = MemberLookup.empty();
 OverloadCandidateSet Candidates(MemberLookup.getNameLoc(),
 OverloadCandidateSet::CSK_Normal);
-for (NamedDecl *D : MemberLookup) {
-  AddMethodCandidate(DeclAccessPair::make(D, D->getAccess()), ObjectType,
- ObjectClassification, /*Args=*/{}, Candidates);
-}
-OverloadCandidateSet::iterator Best;
-switch (Candidates.BestViableFunction(*this, Loc, Best)) {
-case OR_Success:
-  return std::move(MemberLookup);
-default:
-  if (Diag)
-Candidates.NoteCandidates(
-PartialDiagnosticAt(
-Loc, PDiag(diag::err_static_assert_invalid_mem_fn_ret_ty)
- << (Member == "data")),
-*this, OCD_AllCandidates, /*Args=*/{});
-}
-return std::nullopt;
+if(MemberLookup.empty())
+  return std::nullopt;
+return MemberLookup;
   };
 
   bool SizeNotFound, DataNotFound;
diff --git a/clang/test/CXX/drs/dr27xx.cpp b/clang/test/CXX/drs/dr27xx.cpp
new file mode 100644
index 000..f17726eb045f933
--- /dev/null
+++ b/clang/test/CXX/drs/dr27xx.cpp
@@ -0,0 +1,30 @@
+// RUN: %clang_cc1 -std=c++2c

[clang] [Clang] Improve support for expression messages in `static_assert` (PR #73234)

2023-11-23 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: cor3ntin (cor3ntin)


Changes

- Support non-member functions and callable objects for size and data(). We 
previously tried to (badly) pick the best overload ourselves, in a way that 
would only support member functions. We now leave clamg construct an unresolved 
member expression and call that, properly performing overload resolution with 
callable objects and static functions, cojnsistent with the logic for `get` 
calls for structured bindings.
- Support UDLs as message expression.
- Add tests and mark CWG2798 as resolved

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


6 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+3) 
- (modified) clang/lib/Parse/ParseDeclCXX.cpp (+1-1) 
- (modified) clang/lib/Sema/SemaDeclCXX.cpp (+3-21) 
- (added) clang/test/CXX/drs/dr27xx.cpp (+30) 
- (modified) clang/test/SemaCXX/static-assert-cxx26.cpp (+44-10) 
- (modified) clang/www/cxx_dr_status.html (+1-1) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 7e2c990d03e7f27..5a8e63be1258a28 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -617,6 +617,9 @@ Bug Fixes in This Version
 - Fix crash during code generation of C++ coroutine initial suspend when the 
return
   type of await_resume is not trivially destructible.
   Fixes (`#63803 `_)
+- Fix crash when the object used as a ``static_asssert`` message has ``size`` 
or ``data`` members
+  which are not member functions.
+- Support UDLs in ``static_asssert`` message.
 
 Bug Fixes to Compiler Builtins
 ^^
diff --git a/clang/lib/Parse/ParseDeclCXX.cpp b/clang/lib/Parse/ParseDeclCXX.cpp
index d9125955fda2783..910112ecae964cc 100644
--- a/clang/lib/Parse/ParseDeclCXX.cpp
+++ b/clang/lib/Parse/ParseDeclCXX.cpp
@@ -1023,7 +1023,7 @@ Decl *Parser::ParseStaticAssertDeclaration(SourceLocation 
&DeclEnd) {
 const Token &T = GetLookAheadToken(I);
 if (T.is(tok::r_paren))
   break;
-if (!tokenIsLikeStringLiteral(T, getLangOpts())) {
+if (!tokenIsLikeStringLiteral(T, getLangOpts()) || T.hasUDSuffix()) {
   ParseAsExpression = true;
   break;
 }
diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 3688192e6cbe5c5..01e2be3a45be85a 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -17291,33 +17291,15 @@ bool Sema::EvaluateStaticAssertMessageAsString(Expr 
*Message,
 
   auto FindMember = [&](StringRef Member, bool &Empty,
 bool Diag = false) -> std::optional {
-QualType ObjectType = Message->getType();
-Expr::Classification ObjectClassification =
-Message->Classify(getASTContext());
-
 DeclarationName DN = PP.getIdentifierInfo(Member);
 LookupResult MemberLookup(*this, DN, Loc, Sema::LookupMemberName);
 LookupQualifiedName(MemberLookup, RD);
 Empty = MemberLookup.empty();
 OverloadCandidateSet Candidates(MemberLookup.getNameLoc(),
 OverloadCandidateSet::CSK_Normal);
-for (NamedDecl *D : MemberLookup) {
-  AddMethodCandidate(DeclAccessPair::make(D, D->getAccess()), ObjectType,
- ObjectClassification, /*Args=*/{}, Candidates);
-}
-OverloadCandidateSet::iterator Best;
-switch (Candidates.BestViableFunction(*this, Loc, Best)) {
-case OR_Success:
-  return std::move(MemberLookup);
-default:
-  if (Diag)
-Candidates.NoteCandidates(
-PartialDiagnosticAt(
-Loc, PDiag(diag::err_static_assert_invalid_mem_fn_ret_ty)
- << (Member == "data")),
-*this, OCD_AllCandidates, /*Args=*/{});
-}
-return std::nullopt;
+if(MemberLookup.empty())
+  return std::nullopt;
+return MemberLookup;
   };
 
   bool SizeNotFound, DataNotFound;
diff --git a/clang/test/CXX/drs/dr27xx.cpp b/clang/test/CXX/drs/dr27xx.cpp
new file mode 100644
index 000..f17726eb045f933
--- /dev/null
+++ b/clang/test/CXX/drs/dr27xx.cpp
@@ -0,0 +1,30 @@
+// RUN: %clang_cc1 -std=c++2c -verify %s
+
+namespace dr2798 { // dr2798: 17 drafting
+#if __cpp_static_assert >= 202306
+struct string {
+constexpr string() {
+data_ = new char[6]();
+__builtin_memcpy(data_, "Hello", 5);
+data_[5] = 0;
+}
+constexpr ~string() {
+delete[] data_;
+}
+constexpr unsigned long size() const {
+return 5;
+};
+constexpr const char* data() const {
+return data_;
+}
+
+char* data_;
+};
+struct X {
+string s;
+};
+consteval X f() { return {}; }
+
+static_assert(false, f().s); // expected-error {{static assertion failed: 
Hello}}
+#endif
+}
diff --git a/clang/test/SemaCXX/static-assert-cxx26.cpp 
b/clang/test/SemaCXX/static-assert-cxx26.cpp
index b19aac6cabd1324..f4ede

[clang] [flang] [flang] Enable alias tags pass by default (PR #73111)

2023-11-23 Thread Tom Eccles via cfe-commits

https://github.com/tblah updated https://github.com/llvm/llvm-project/pull/73111

>From 617d6d23b2f861cd6dceb82f54a2685059b6 Mon Sep 17 00:00:00 2001
From: Tom Eccles 
Date: Thu, 14 Sep 2023 09:09:29 +
Subject: [PATCH 1/6] [flang] Enable alias tags pass by default

Enable by default when optimizing for speed.

For simplicity, only forward the flag to the frontend driver when it
contradicts what is implied by the optimization level.
---
 clang/lib/Driver/ToolChains/Flang.cpp | 20 
 flang/include/flang/Tools/CLOptions.inc   |  8 
 flang/lib/Frontend/CompilerInvocation.cpp | 22 ++
 flang/test/Driver/falias-analysis.f90 |  4 
 flang/test/Driver/mlir-pass-pipeline.f90  |  2 ++
 flang/test/Driver/optimization-remark.f90 | 22 +-
 flang/test/Fir/basic-program.fir  |  4 
 flang/tools/tco/tco.cpp   |  1 +
 8 files changed, 62 insertions(+), 21 deletions(-)

diff --git a/clang/lib/Driver/ToolChains/Flang.cpp 
b/clang/lib/Driver/ToolChains/Flang.cpp
index 8bdd920c3dcbb79..9382433b94dadfd 100644
--- a/clang/lib/Driver/ToolChains/Flang.cpp
+++ b/clang/lib/Driver/ToolChains/Flang.cpp
@@ -142,6 +142,26 @@ void Flang::addCodegenOptions(const ArgList &Args,
   if (shouldLoopVersion(Args))
 CmdArgs.push_back("-fversion-loops-for-stride");
 
+  Arg *aliasAnalysis = Args.getLastArg(options::OPT_falias_analysis,
+   options::OPT_fno_alias_analysis);
+  Arg *optLevel =
+  Args.getLastArg(options::OPT_Ofast, options::OPT_O, options::OPT_O4);
+  if (aliasAnalysis) {
+bool falias_analysis =
+aliasAnalysis->getOption().matches(options::OPT_falias_analysis);
+// only pass on the argument if it does not match that implied by the
+// optimization level
+if (optLevel) {
+  if (!falias_analysis) {
+CmdArgs.push_back("-fno-alias-analysis");
+  }
+} else {
+  if (falias_analysis)
+// requested alias analysis but no optimization enabled
+CmdArgs.push_back("-falias-analysis");
+}
+  }
+
   Args.addAllArgs(CmdArgs, {options::OPT_flang_experimental_hlfir,
 options::OPT_flang_deprecated_no_hlfir,
 options::OPT_flang_experimental_polymorphism,
diff --git a/flang/include/flang/Tools/CLOptions.inc 
b/flang/include/flang/Tools/CLOptions.inc
index c452c023b4a80ce..5a17385fb3dae87 100644
--- a/flang/include/flang/Tools/CLOptions.inc
+++ b/flang/include/flang/Tools/CLOptions.inc
@@ -157,11 +157,11 @@ inline void addDebugFoundationPass(mlir::PassManager &pm) 
{
   [&]() { return fir::createAddDebugFoundationPass(); });
 }
 
-inline void addFIRToLLVMPass(
-mlir::PassManager &pm, llvm::OptimizationLevel optLevel = defaultOptLevel) 
{
+inline void addFIRToLLVMPass(mlir::PassManager &pm,
+llvm::OptimizationLevel optLevel = defaultOptLevel, bool applyTbaa = true) 
{
   fir::FIRToLLVMPassOptions options;
   options.ignoreMissingTypeDescriptors = ignoreMissingTypeDescriptors;
-  options.applyTBAA = optLevel.isOptimizingForSpeed();
+  options.applyTBAA = applyTbaa;
   options.forceUnifiedTBAATree = useOldAliasTags;
   addPassConditionally(pm, disableFirToLlvmIr,
   [&]() { return fir::createFIRToLLVMPass(options); });
@@ -311,7 +311,7 @@ inline void createDefaultFIRCodeGenPassPipeline(
   if (config.VScaleMin != 0)
 pm.addPass(fir::createVScaleAttrPass({config.VScaleMin, 
config.VScaleMax}));
 
-  fir::addFIRToLLVMPass(pm, config.OptLevel);
+  fir::addFIRToLLVMPass(pm, config.OptLevel, config.AliasAnalysis);
 }
 
 /// Create a pass pipeline for lowering from MLIR to LLVM IR
diff --git a/flang/lib/Frontend/CompilerInvocation.cpp 
b/flang/lib/Frontend/CompilerInvocation.cpp
index cb4f2d6a6225205..cfb1dd91ead3056 100644
--- a/flang/lib/Frontend/CompilerInvocation.cpp
+++ b/flang/lib/Frontend/CompilerInvocation.cpp
@@ -242,10 +242,24 @@ static void 
parseCodeGenArgs(Fortran::frontend::CodeGenOptions &opts,
clang::driver::options::OPT_fno_loop_versioning, false))
 opts.LoopVersioning = 1;
 
-  opts.AliasAnalysis =
-  args.hasFlag(clang::driver::options::OPT_falias_analysis,
-   clang::driver::options::OPT_fno_alias_analysis,
-   /*default=*/false);
+  bool aliasAnalysis = false;
+  bool noAliasAnalysis = false;
+  if (auto *arg =
+  args.getLastArg(clang::driver::options::OPT_falias_analysis,
+  clang::driver::options::OPT_fno_alias_analysis)) {
+if (arg->getOption().matches(clang::driver::options::OPT_falias_analysis))
+  aliasAnalysis = true;
+else
+  noAliasAnalysis = true;
+  }
+  opts.AliasAnalysis = 0;
+  if (opts.OptimizationLevel > 0) {
+if (!noAliasAnalysis)
+  opts.AliasAnalysis = 1;
+  } else {
+if (aliasAnalysis)
+  opts.AliasAnalysis = 1;
+  }
 
   for (auto *a : args.filtered(clang::driver::options::OPT_fpass_plugin_EQ))
 opts

[clang] [Clang] Improve support for expression messages in `static_assert` (PR #73234)

2023-11-23 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 c43c88501e3bc273a7c1074a19e86dc305ad7234 
c8f8e6d0a88b9fd1d905ca0a09ffe6e0415ab90e -- clang/test/CXX/drs/dr27xx.cpp 
clang/lib/Parse/ParseDeclCXX.cpp clang/lib/Sema/SemaDeclCXX.cpp 
clang/test/SemaCXX/static-assert-cxx26.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 01e2be3a45..1d9e4a0ac4 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -17297,7 +17297,7 @@ bool Sema::EvaluateStaticAssertMessageAsString(Expr 
*Message,
 Empty = MemberLookup.empty();
 OverloadCandidateSet Candidates(MemberLookup.getNameLoc(),
 OverloadCandidateSet::CSK_Normal);
-if(MemberLookup.empty())
+if (MemberLookup.empty())
   return std::nullopt;
 return MemberLookup;
   };

``




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


[clang] [Driver] Allow -e entry but reject -eentry (PR #72804)

2023-11-23 Thread dong jianqiang via cfe-commits

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

LGTM.

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


[clang] [Clang] Improve support for expression messages in `static_assert` (PR #73234)

2023-11-23 Thread via cfe-commits

https://github.com/cor3ntin updated 
https://github.com/llvm/llvm-project/pull/73234

>From c274d62d03e1ab390284b26d6e23a23d099a98f6 Mon Sep 17 00:00:00 2001
From: Corentin Jabot 
Date: Thu, 23 Nov 2023 12:51:46 +0100
Subject: [PATCH] [Clang] Improve support for expression messages in
 `static_assert`

- Support non-member functions and callable objects for size and data().
  We previously tried to (badly) pick the best overload ourselves,
  in a way that would only support member functions.
  We now leave clamg construct an unresolved member expression and call that,
  properly performing overload resolution with callable objects and
  static functions, cojnsistent with the logic for `get` calls for structured 
bindings.
- Support UDLs as message expression.
- Add tests and mark CWG2798 as resolved
---
 clang/docs/ReleaseNotes.rst|  3 ++
 clang/lib/Parse/ParseDeclCXX.cpp   |  2 +-
 clang/lib/Sema/SemaDeclCXX.cpp | 24 ++
 clang/test/CXX/drs/dr27xx.cpp  | 30 
 clang/test/SemaCXX/static-assert-cxx26.cpp | 54 ++
 clang/www/cxx_dr_status.html   |  2 +-
 6 files changed, 82 insertions(+), 33 deletions(-)
 create mode 100644 clang/test/CXX/drs/dr27xx.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 7e2c990d03e7f27..5a8e63be1258a28 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -617,6 +617,9 @@ Bug Fixes in This Version
 - Fix crash during code generation of C++ coroutine initial suspend when the 
return
   type of await_resume is not trivially destructible.
   Fixes (`#63803 `_)
+- Fix crash when the object used as a ``static_asssert`` message has ``size`` 
or ``data`` members
+  which are not member functions.
+- Support UDLs in ``static_asssert`` message.
 
 Bug Fixes to Compiler Builtins
 ^^
diff --git a/clang/lib/Parse/ParseDeclCXX.cpp b/clang/lib/Parse/ParseDeclCXX.cpp
index d9125955fda2783..910112ecae964cc 100644
--- a/clang/lib/Parse/ParseDeclCXX.cpp
+++ b/clang/lib/Parse/ParseDeclCXX.cpp
@@ -1023,7 +1023,7 @@ Decl *Parser::ParseStaticAssertDeclaration(SourceLocation 
&DeclEnd) {
 const Token &T = GetLookAheadToken(I);
 if (T.is(tok::r_paren))
   break;
-if (!tokenIsLikeStringLiteral(T, getLangOpts())) {
+if (!tokenIsLikeStringLiteral(T, getLangOpts()) || T.hasUDSuffix()) {
   ParseAsExpression = true;
   break;
 }
diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 3688192e6cbe5c5..1d9e4a0ac46fffe 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -17291,33 +17291,15 @@ bool Sema::EvaluateStaticAssertMessageAsString(Expr 
*Message,
 
   auto FindMember = [&](StringRef Member, bool &Empty,
 bool Diag = false) -> std::optional {
-QualType ObjectType = Message->getType();
-Expr::Classification ObjectClassification =
-Message->Classify(getASTContext());
-
 DeclarationName DN = PP.getIdentifierInfo(Member);
 LookupResult MemberLookup(*this, DN, Loc, Sema::LookupMemberName);
 LookupQualifiedName(MemberLookup, RD);
 Empty = MemberLookup.empty();
 OverloadCandidateSet Candidates(MemberLookup.getNameLoc(),
 OverloadCandidateSet::CSK_Normal);
-for (NamedDecl *D : MemberLookup) {
-  AddMethodCandidate(DeclAccessPair::make(D, D->getAccess()), ObjectType,
- ObjectClassification, /*Args=*/{}, Candidates);
-}
-OverloadCandidateSet::iterator Best;
-switch (Candidates.BestViableFunction(*this, Loc, Best)) {
-case OR_Success:
-  return std::move(MemberLookup);
-default:
-  if (Diag)
-Candidates.NoteCandidates(
-PartialDiagnosticAt(
-Loc, PDiag(diag::err_static_assert_invalid_mem_fn_ret_ty)
- << (Member == "data")),
-*this, OCD_AllCandidates, /*Args=*/{});
-}
-return std::nullopt;
+if (MemberLookup.empty())
+  return std::nullopt;
+return MemberLookup;
   };
 
   bool SizeNotFound, DataNotFound;
diff --git a/clang/test/CXX/drs/dr27xx.cpp b/clang/test/CXX/drs/dr27xx.cpp
new file mode 100644
index 000..f17726eb045f933
--- /dev/null
+++ b/clang/test/CXX/drs/dr27xx.cpp
@@ -0,0 +1,30 @@
+// RUN: %clang_cc1 -std=c++2c -verify %s
+
+namespace dr2798 { // dr2798: 17 drafting
+#if __cpp_static_assert >= 202306
+struct string {
+constexpr string() {
+data_ = new char[6]();
+__builtin_memcpy(data_, "Hello", 5);
+data_[5] = 0;
+}
+constexpr ~string() {
+delete[] data_;
+}
+constexpr unsigned long size() const {
+return 5;
+};
+constexpr const char* data() const {
+return data_;
+}
+
+char* data_;
+};
+struct X {
+string s;
+};
+

[clang] [llvm] [SystemZ][z/OS] This change adds support for the PPA2 section in zOS (PR #68926)

2023-11-23 Thread Ulrich Weigand via cfe-commits


@@ -1026,6 +1030,72 @@ void SystemZAsmPrinter::emitADASection() {
   OutStreamer->popSection();
 }
 
+static std::string getProductID(Module &M) {
+  std::string ProductID;
+  if (auto *MD = M.getModuleFlag("zos_product_id"))
+ProductID = cast(MD)->getString().str();
+  if (ProductID.empty())
+ProductID = "LLVM";
+  return ProductID;
+}
+
+static uint32_t getProductVersion(Module &M) {
+  if (auto *VersionVal = mdconst::extract_or_null(
+  M.getModuleFlag("zos_product_major_version")))
+return VersionVal->getZExtValue();
+  return LLVM_VERSION_MAJOR;
+}
+
+static uint32_t getProductRelease(Module &M) {
+  if (auto *ReleaseVal = mdconst::extract_or_null(
+  M.getModuleFlag("zos_product_minor_version")))
+return ReleaseVal->getZExtValue();
+  return LLVM_VERSION_MINOR;
+}
+
+static uint32_t getProductPatch(Module &M) {
+  if (auto *PatchVal = mdconst::extract_or_null(
+  M.getModuleFlag("zos_product_patchlevel")))
+return PatchVal->getZExtValue();
+  return LLVM_VERSION_PATCH;
+}
+
+static time_t getTranslationTime(Module &M) {
+  std::time_t Time = 0;
+  if (auto *Val = mdconst::extract_or_null(
+  M.getModuleFlag("zos_translation_time"))) {
+long SecondsSinceEpoch =  Val->getSExtValue();
+Time = static_cast(SecondsSinceEpoch);
+  }
+  return Time;
+}
+
+void SystemZAsmPrinter::emitIDRLSection(Module &M) {
+  OutStreamer->pushSection();
+  OutStreamer->switchSection(getObjFileLowering().getIDRLSection());
+  constexpr unsigned IDRLDataLength = 30;
+  std::time_t Time = getTranslationTime(M);
+
+  uint32_t ProductVersion = getProductVersion(M);
+  uint32_t ProductRelease = getProductRelease(M);
+
+  std::string ProductID = getProductID(M);
+
+  SmallString TempStr;
+  raw_svector_ostream O(TempStr);
+  O << formatv("{0}{1,0-2:d}{2,0-2:d}{3:%Y-%m-%d %H:%M:%S}",
+   ProductID.substr(0, 10).c_str(), ProductVersion, ProductRelease,
+   llvm::sys::toUtcTime(Time));
+  SmallString Data;
+  ConverterEBCDIC::convertToEBCDIC(TempStr, Data);
+
+  OutStreamer->emitInt8(0);   // Reserved.
+  OutStreamer->emitInt8(3);   // Format.
+  OutStreamer->emitInt16(IDRLDataLength); // Length.
+  OutStreamer->emitBytes(Data.str());

uweigand wrote:

One more question about this string - the Length field is hardcoded to 30.  
Does that mean that there are exactly 30 bytes supposed to always follow here?  
 I'm not sure this is guaranteed by the formatv above ...

Also, there doesn't seem to be any test that verifies the layout of this IDRL 
section, I think we definitely need one.

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


[clang] [Driver][MachineOutliner] Support -moutline option for aarch64_be (PR #73223)

2023-11-23 Thread dong jianqiang via cfe-commits

https://github.com/dongjianqiang2 updated 
https://github.com/llvm/llvm-project/pull/73223

>From 5742f71b9077a038cfefe4c74290d7e9d2f42d3f Mon Sep 17 00:00:00 2001
From: dong jianqiang 
Date: Thu, 23 Nov 2023 16:58:11 +0800
Subject: [PATCH] [Driver][MachineOutliner] Support outlining option with LTO
 for aarch64_be

This patch propagates the -moutline option when target is aarch64_be,
fix warning: 'aarch64_be' does not support '-moutline'; flag ignored 
[-Woption-ignored]
---
 clang/lib/Driver/ToolChains/CommonArgs.cpp | 3 ++-
 clang/test/Driver/aarch64-outliner.c   | 2 ++
 2 files changed, 4 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Driver/ToolChains/CommonArgs.cpp 
b/clang/lib/Driver/ToolChains/CommonArgs.cpp
index 5d2cd1959b06925..078f2ff80a21939 100644
--- a/clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ b/clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -2436,7 +2436,8 @@ void tools::addMachineOutlinerArgs(const Driver &D,
   // Otherwise, add the proper mllvm flags.
   if (!(Triple.isARM() || Triple.isThumb() ||
 Triple.getArch() == llvm::Triple::aarch64 ||
-Triple.getArch() == llvm::Triple::aarch64_32)) {
+Triple.getArch() == llvm::Triple::aarch64_32 ||
+Triple.getArch() == llvm::Triple::aarch64_be)) {
 D.Diag(diag::warn_drv_moutline_unsupported_opt) << 
Triple.getArchName();
   } else {
 addArg(Twine("-enable-machine-outliner"));
diff --git a/clang/test/Driver/aarch64-outliner.c 
b/clang/test/Driver/aarch64-outliner.c
index 42e43b433e282d3..06e5de11ec49ecd 100644
--- a/clang/test/Driver/aarch64-outliner.c
+++ b/clang/test/Driver/aarch64-outliner.c
@@ -1,7 +1,9 @@
 // REQUIRES: aarch64-registered-target
 // RUN: %clang --target=aarch64 -moutline -S %s -### 2>&1 | FileCheck %s 
-check-prefix=ON
+// RUN: %clang --target=aarch64_be -moutline -S %s -### 2>&1 | FileCheck %s 
-check-prefix=ON
 // ON: "-mllvm" "-enable-machine-outliner"
 // RUN: %clang --target=aarch64 -moutline -mno-outline -S %s -### 2>&1 | 
FileCheck %s -check-prefix=OFF
+// RUN: %clang --target=aarch64_be -moutline -mno-outline -S %s -### 2>&1 | 
FileCheck %s -check-prefix=OFF
 // OFF: "-mllvm" "-enable-machine-outliner=never"
 // RUN: %clang --target=x86_64 -moutline -S %s -### 2>&1 | FileCheck %s 
-check-prefix=WARN
 // WARN: warning: 'x86_64' does not support '-moutline'; flag ignored 
[-Woption-ignored]

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


[clang] [SystemZ] Move new test into existing CodeGen test. (PR #73230)

2023-11-23 Thread Ulrich Weigand via cfe-commits

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

LGTM, thanks!

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


[clang] 521b468 - [SystemZ] Move new test into existing CodeGen test. (#73230)

2023-11-23 Thread via cfe-commits

Author: Jonas Paulsson
Date: 2023-11-23T13:27:05+01:00
New Revision: 521b4682a55eb735b75e08d5f71c8cbe47395e40

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

LOG: [SystemZ] Move new test into existing CodeGen test. (#73230)

The test for emitted alignments is better placed in CodeGen.

Added: 


Modified: 
clang/test/CodeGen/SystemZ/align-systemz.c

Removed: 
clang/test/Driver/systemz-alignment.c



diff  --git a/clang/test/CodeGen/SystemZ/align-systemz.c 
b/clang/test/CodeGen/SystemZ/align-systemz.c
index 5ba446665fef803..9daff6ee9760974 100644
--- a/clang/test/CodeGen/SystemZ/align-systemz.c
+++ b/clang/test/CodeGen/SystemZ/align-systemz.c
@@ -25,6 +25,19 @@ void func (void)
   s = es;
 }
 
+// Test that a global variable with an incomplete type gets the minimum
+// alignment of 2 per the ABI if no alignment was specified by user.
+//
+// CHECK-DAG: @VarNoAl {{.*}} align 2
+// CHECK-DAG: @VarExplAl1  {{.*}} align 1
+// CHECK-DAG: @VarExplAl4  {{.*}} align 4
+struct incomplete_ty;
+extern struct incomplete_ty VarNoAl;
+extern struct incomplete_ty __attribute__((aligned(1))) VarExplAl1;
+extern struct incomplete_ty __attribute__((aligned(4))) VarExplAl4;
+struct incomplete_ty *fun0 (void) { return &VarNoAl; }
+struct incomplete_ty *fun1 (void) { return &VarExplAl1; }
+struct incomplete_ty *fun2 (void) { return &VarExplAl4; }
 
 // The SystemZ ABI aligns __int128_t to only eight bytes.
 

diff  --git a/clang/test/Driver/systemz-alignment.c 
b/clang/test/Driver/systemz-alignment.c
deleted file mode 100644
index 6f3b2bc38be3688..000
--- a/clang/test/Driver/systemz-alignment.c
+++ /dev/null
@@ -1,32 +0,0 @@
-// RUN: %clang --target=s390x-linux -S -emit-llvm -o - %s | FileCheck %s
-//
-// Test that a global variable with an incomplete type gets the minimum
-// alignment of 2 per the ABI if no alignment was specified by user.
-//
-// CHECK:  @VarNoAl {{.*}} align 2
-// CHECK-NEXT: @VarExplAl1  {{.*}} align 1
-// CHECK-NEXT: @VarExplAl4  {{.*}} align 4
-
-// No alignemnt specified by user.
-struct incomplete_ty_noal;
-extern struct incomplete_ty_noal VarNoAl;
-struct incomplete_ty_noal *fun0 (void)
-{
-  return &VarNoAl;
-}
-
-// User-specified alignment of 1.
-struct incomplete_ty_al1;
-extern struct incomplete_ty_al1 __attribute__((aligned(1))) VarExplAl1;
-struct incomplete_ty_al1 *fun1 (void)
-{
-  return &VarExplAl1;
-}
-
-// User-specified alignment of 4.
-struct incomplete_ty_al4;
-extern struct incomplete_ty_al4 __attribute__((aligned(4))) VarExplAl4;
-struct incomplete_ty_al4 *fun2 (void)
-{
-  return &VarExplAl4;
-}



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


[clang] [SystemZ] Move new test into existing CodeGen test. (PR #73230)

2023-11-23 Thread Jonas Paulsson via cfe-commits

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


[clang] [llvm] [MemProf] Expand optimization scope to internal linakge function (PR #73236)

2023-11-23 Thread via cfe-commits

https://github.com/lifengxiang1025 created 
https://github.com/llvm/llvm-project/pull/73236

Now MemProf can't do IR annotation right in the local linkage function and 
global initial function __cxx_global_var_init. In llvm-profdata which convert 
raw memory profile to memory profile, it uses function name in dwarf to create 
GUID. But when llvm consumes memory profile,  it use `getIRPGOFuncName` or 
`getPGOFuncName` which returns local linkage function as 
`FileName;FunctionName` or `FileName:FunctionName`  to get function name and 
create GUID. So profile creator's GUID is not same as profile consumer.
So I think MemProf should be used with `unique-internal-linkage-names` and  
don't use PGOFuncName.
__cxx_global_var_init is created later than where UniqueInternalLinkageNames 
works. So I add uniq suffix to __cxx_global_var_init additionally.

>From 9dd4626612f706b8df08ee5a1f43a6b59ae47acf Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E6=9D=8E=E5=87=A4=E7=A5=A5?=
 
Date: Thu, 23 Nov 2023 20:13:24 +0800
Subject: [PATCH] [MemProf] Expand optimization scope to internal linakge
 function

---
 clang/lib/CodeGen/CGDeclCXX.cpp  |  3 +++
 .../Transforms/Instrumentation/MemProfiler.cpp   | 16 +---
 2 files changed, 4 insertions(+), 15 deletions(-)

diff --git a/clang/lib/CodeGen/CGDeclCXX.cpp b/clang/lib/CodeGen/CGDeclCXX.cpp
index e08a1e5f42df20c..ae45c23c9e6811c 100644
--- a/clang/lib/CodeGen/CGDeclCXX.cpp
+++ b/clang/lib/CodeGen/CGDeclCXX.cpp
@@ -538,6 +538,9 @@ CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl 
*D,
   {
 llvm::raw_svector_ostream Out(FnName);
 getCXXABI().getMangleContext().mangleDynamicInitializer(D, Out);
+if (getCodeGenOpts().UniqueInternalLinkageNames) {
+  Out << getModuleNameHash();
+}
   }
 
   // Create a variable initialization function.
diff --git a/llvm/lib/Transforms/Instrumentation/MemProfiler.cpp 
b/llvm/lib/Transforms/Instrumentation/MemProfiler.cpp
index c6134ce77136364..97db0122be7c8e7 100644
--- a/llvm/lib/Transforms/Instrumentation/MemProfiler.cpp
+++ b/llvm/lib/Transforms/Instrumentation/MemProfiler.cpp
@@ -677,24 +677,10 @@ static void readMemprof(Module &M, Function &F,
 const TargetLibraryInfo &TLI) {
   auto &Ctx = M.getContext();
 
-  auto FuncName = getIRPGOFuncName(F);
+  auto FuncName = F.getName();
   auto FuncGUID = Function::getGUID(FuncName);
   std::optional MemProfRec;
   auto Err = MemProfReader->getMemProfRecord(FuncGUID).moveInto(MemProfRec);
-  if (Err) {
-// If we don't find getIRPGOFuncName(), try getPGOFuncName() to handle
-// profiles built by older compilers
-Err = handleErrors(std::move(Err), [&](const InstrProfError &IE) -> Error {
-  if (IE.get() != instrprof_error::unknown_function)
-return make_error(IE);
-  auto FuncName = getPGOFuncName(F);
-  auto FuncGUID = Function::getGUID(FuncName);
-  if (auto Err =
-  MemProfReader->getMemProfRecord(FuncGUID).moveInto(MemProfRec))
-return Err;
-  return Error::success();
-});
-  }
   if (Err) {
 handleAllErrors(std::move(Err), [&](const InstrProfError &IPE) {
   auto Err = IPE.get();

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


[clang] [llvm] [MemProf] Expand optimization scope to internal linakge function (PR #73236)

2023-11-23 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: None (lifengxiang1025)


Changes

Now MemProf can't do IR annotation right in the local linkage function and 
global initial function __cxx_global_var_init. In llvm-profdata which convert 
raw memory profile to memory profile, it uses function name in dwarf to create 
GUID. But when llvm consumes memory profile,  it use `getIRPGOFuncName` or 
`getPGOFuncName` which returns local linkage function as 
`FileName;FunctionName` or `FileName:FunctionName`  to get function name and 
create GUID. So profile creator's GUID is not same as profile consumer.
So I think MemProf should be used with `unique-internal-linkage-names` and  
don't use PGOFuncName.
__cxx_global_var_init is created later than where UniqueInternalLinkageNames 
works. So I add uniq suffix to __cxx_global_var_init additionally.

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


2 Files Affected:

- (modified) clang/lib/CodeGen/CGDeclCXX.cpp (+3) 
- (modified) llvm/lib/Transforms/Instrumentation/MemProfiler.cpp (+1-15) 


``diff
diff --git a/clang/lib/CodeGen/CGDeclCXX.cpp b/clang/lib/CodeGen/CGDeclCXX.cpp
index e08a1e5f42df20c..ae45c23c9e6811c 100644
--- a/clang/lib/CodeGen/CGDeclCXX.cpp
+++ b/clang/lib/CodeGen/CGDeclCXX.cpp
@@ -538,6 +538,9 @@ CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl 
*D,
   {
 llvm::raw_svector_ostream Out(FnName);
 getCXXABI().getMangleContext().mangleDynamicInitializer(D, Out);
+if (getCodeGenOpts().UniqueInternalLinkageNames) {
+  Out << getModuleNameHash();
+}
   }
 
   // Create a variable initialization function.
diff --git a/llvm/lib/Transforms/Instrumentation/MemProfiler.cpp 
b/llvm/lib/Transforms/Instrumentation/MemProfiler.cpp
index c6134ce77136364..97db0122be7c8e7 100644
--- a/llvm/lib/Transforms/Instrumentation/MemProfiler.cpp
+++ b/llvm/lib/Transforms/Instrumentation/MemProfiler.cpp
@@ -677,24 +677,10 @@ static void readMemprof(Module &M, Function &F,
 const TargetLibraryInfo &TLI) {
   auto &Ctx = M.getContext();
 
-  auto FuncName = getIRPGOFuncName(F);
+  auto FuncName = F.getName();
   auto FuncGUID = Function::getGUID(FuncName);
   std::optional MemProfRec;
   auto Err = MemProfReader->getMemProfRecord(FuncGUID).moveInto(MemProfRec);
-  if (Err) {
-// If we don't find getIRPGOFuncName(), try getPGOFuncName() to handle
-// profiles built by older compilers
-Err = handleErrors(std::move(Err), [&](const InstrProfError &IE) -> Error {
-  if (IE.get() != instrprof_error::unknown_function)
-return make_error(IE);
-  auto FuncName = getPGOFuncName(F);
-  auto FuncGUID = Function::getGUID(FuncName);
-  if (auto Err =
-  MemProfReader->getMemProfRecord(FuncGUID).moveInto(MemProfRec))
-return Err;
-  return Error::success();
-});
-  }
   if (Err) {
 handleAllErrors(std::move(Err), [&](const InstrProfError &IPE) {
   auto Err = IPE.get();

``




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


[llvm] [clang] [MemProf] Expand optimization scope to internal linakge function (PR #73236)

2023-11-23 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-llvm-transforms

Author: None (lifengxiang1025)


Changes

Now MemProf can't do IR annotation right in the local linkage function and 
global initial function __cxx_global_var_init. In llvm-profdata which convert 
raw memory profile to memory profile, it uses function name in dwarf to create 
GUID. But when llvm consumes memory profile,  it use `getIRPGOFuncName` or 
`getPGOFuncName` which returns local linkage function as 
`FileName;FunctionName` or `FileName:FunctionName`  to get function name and 
create GUID. So profile creator's GUID is not same as profile consumer.
So I think MemProf should be used with `unique-internal-linkage-names` and  
don't use PGOFuncName.
__cxx_global_var_init is created later than where UniqueInternalLinkageNames 
works. So I add uniq suffix to __cxx_global_var_init additionally.

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


2 Files Affected:

- (modified) clang/lib/CodeGen/CGDeclCXX.cpp (+3) 
- (modified) llvm/lib/Transforms/Instrumentation/MemProfiler.cpp (+1-15) 


``diff
diff --git a/clang/lib/CodeGen/CGDeclCXX.cpp b/clang/lib/CodeGen/CGDeclCXX.cpp
index e08a1e5f42df20c..ae45c23c9e6811c 100644
--- a/clang/lib/CodeGen/CGDeclCXX.cpp
+++ b/clang/lib/CodeGen/CGDeclCXX.cpp
@@ -538,6 +538,9 @@ CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl 
*D,
   {
 llvm::raw_svector_ostream Out(FnName);
 getCXXABI().getMangleContext().mangleDynamicInitializer(D, Out);
+if (getCodeGenOpts().UniqueInternalLinkageNames) {
+  Out << getModuleNameHash();
+}
   }
 
   // Create a variable initialization function.
diff --git a/llvm/lib/Transforms/Instrumentation/MemProfiler.cpp 
b/llvm/lib/Transforms/Instrumentation/MemProfiler.cpp
index c6134ce77136364..97db0122be7c8e7 100644
--- a/llvm/lib/Transforms/Instrumentation/MemProfiler.cpp
+++ b/llvm/lib/Transforms/Instrumentation/MemProfiler.cpp
@@ -677,24 +677,10 @@ static void readMemprof(Module &M, Function &F,
 const TargetLibraryInfo &TLI) {
   auto &Ctx = M.getContext();
 
-  auto FuncName = getIRPGOFuncName(F);
+  auto FuncName = F.getName();
   auto FuncGUID = Function::getGUID(FuncName);
   std::optional MemProfRec;
   auto Err = MemProfReader->getMemProfRecord(FuncGUID).moveInto(MemProfRec);
-  if (Err) {
-// If we don't find getIRPGOFuncName(), try getPGOFuncName() to handle
-// profiles built by older compilers
-Err = handleErrors(std::move(Err), [&](const InstrProfError &IE) -> Error {
-  if (IE.get() != instrprof_error::unknown_function)
-return make_error(IE);
-  auto FuncName = getPGOFuncName(F);
-  auto FuncGUID = Function::getGUID(FuncName);
-  if (auto Err =
-  MemProfReader->getMemProfRecord(FuncGUID).moveInto(MemProfRec))
-return Err;
-  return Error::success();
-});
-  }
   if (Err) {
 handleAllErrors(std::move(Err), [&](const InstrProfError &IPE) {
   auto Err = IPE.get();

``




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


[clang] [Clang] Improve support for expression messages in `static_assert` (PR #73234)

2023-11-23 Thread via cfe-commits


@@ -617,6 +617,9 @@ Bug Fixes in This Version
 - Fix crash during code generation of C++ coroutine initial suspend when the 
return
   type of await_resume is not trivially destructible.
   Fixes (`#63803 `_)
+- Fix crash when the object used as a ``static_asssert`` message has ``size`` 
or ``data`` members
+  which are not member functions.
+- Support UDLs in ``static_asssert`` message.

oliverscherf-tomtom wrote:

```suggestion
- Fix crash when the object used as a ``static_assert`` message has ``size`` or 
``data`` members
  which are not member functions.
- Support UDLs in ``static_assert`` message.
```

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


[llvm] [clang] [MemProf] Expand optimization scope to internal linakge function (PR #73236)

2023-11-23 Thread via cfe-commits

https://github.com/lifengxiang1025 updated 
https://github.com/llvm/llvm-project/pull/73236

>From fdce13021329985b7c3cb8748ee4f8f7f83a2730 Mon Sep 17 00:00:00 2001
From: lifengxiang 
Date: Thu, 23 Nov 2023 20:32:25 +0800
Subject: [PATCH] [MemProf] Expand optimization scope to internal linakge
 function

---
 clang/lib/CodeGen/CGDeclCXX.cpp  |  3 +++
 .../Transforms/Instrumentation/MemProfiler.cpp   | 16 +---
 2 files changed, 4 insertions(+), 15 deletions(-)

diff --git a/clang/lib/CodeGen/CGDeclCXX.cpp b/clang/lib/CodeGen/CGDeclCXX.cpp
index e08a1e5f42df20c..ae45c23c9e6811c 100644
--- a/clang/lib/CodeGen/CGDeclCXX.cpp
+++ b/clang/lib/CodeGen/CGDeclCXX.cpp
@@ -538,6 +538,9 @@ CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl 
*D,
   {
 llvm::raw_svector_ostream Out(FnName);
 getCXXABI().getMangleContext().mangleDynamicInitializer(D, Out);
+if (getCodeGenOpts().UniqueInternalLinkageNames) {
+  Out << getModuleNameHash();
+}
   }
 
   // Create a variable initialization function.
diff --git a/llvm/lib/Transforms/Instrumentation/MemProfiler.cpp 
b/llvm/lib/Transforms/Instrumentation/MemProfiler.cpp
index c6134ce77136364..97db0122be7c8e7 100644
--- a/llvm/lib/Transforms/Instrumentation/MemProfiler.cpp
+++ b/llvm/lib/Transforms/Instrumentation/MemProfiler.cpp
@@ -677,24 +677,10 @@ static void readMemprof(Module &M, Function &F,
 const TargetLibraryInfo &TLI) {
   auto &Ctx = M.getContext();
 
-  auto FuncName = getIRPGOFuncName(F);
+  auto FuncName = F.getName();
   auto FuncGUID = Function::getGUID(FuncName);
   std::optional MemProfRec;
   auto Err = MemProfReader->getMemProfRecord(FuncGUID).moveInto(MemProfRec);
-  if (Err) {
-// If we don't find getIRPGOFuncName(), try getPGOFuncName() to handle
-// profiles built by older compilers
-Err = handleErrors(std::move(Err), [&](const InstrProfError &IE) -> Error {
-  if (IE.get() != instrprof_error::unknown_function)
-return make_error(IE);
-  auto FuncName = getPGOFuncName(F);
-  auto FuncGUID = Function::getGUID(FuncName);
-  if (auto Err =
-  MemProfReader->getMemProfRecord(FuncGUID).moveInto(MemProfRec))
-return Err;
-  return Error::success();
-});
-  }
   if (Err) {
 handleAllErrors(std::move(Err), [&](const InstrProfError &IPE) {
   auto Err = IPE.get();

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


[llvm] [clang] [MemProf] Expand optimization scope to internal linakge function (PR #73236)

2023-11-23 Thread via cfe-commits

lifengxiang1025 wrote:

@teresajohnson  Can you take a look and provide your insights? I'm learning how 
to write tests and will upload test cases soon.

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


[clang] [compiler-rt] [llvm] [lld] [libc] [flang] [libcxx] Fix ISel crash when lowering BUILD_VECTOR (PR #73186)

2023-11-23 Thread Simon Pilgrim via cfe-commits


@@ -7254,6 +7255,10 @@ static SDValue 
lowerBuildVectorAsBroadcast(BuildVectorSDNode *BVOp,
 EVT CVT = Ld.getValueType();
 assert(!CVT.isVector() && "Must not broadcast a vector type");
 
+// 512 bit vpbroadcastw is only available with AVX512BW
+if (ScalarSize == 16 && IsGT256 && !Subtarget.hasBWI())
+  return SDValue();

RKSimon wrote:

Isn't X86DAGToDAGISel::PreprocessISelDAG() is supposed to handle this?

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


[libcxx] [llvm] [compiler-rt] [libc] [lld] [clang] [flang] Fix ISel crash when lowering BUILD_VECTOR (PR #73186)

2023-11-23 Thread Simon Pilgrim via cfe-commits

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


[clang] [clang] Fix sorting module headers (PR #73146)

2023-11-23 Thread Tulio Magno Quites Machado Filho via cfe-commits

https://github.com/tuliom updated 
https://github.com/llvm/llvm-project/pull/73146

>From d0a86b80256a45bfdee790a7aec5a48d2d71e6bb Mon Sep 17 00:00:00 2001
From: Tulio Magno Quites Machado Filho 
Date: Wed, 22 Nov 2023 14:01:24 -0300
Subject: [PATCH 1/3] [clang] Fix sorting module headers

Struct Module::Header is not a POD type. As such, qsort() and
llvm::array_pod_sort() must not be used to sort it. This became an issue
with the new implementation of qsort() in glibc 2.39 that is not
guaranteed to be a stable sort, causing Headers to be re-ordered and
corrupted.

Replace the usage of llvm::array_pod_sort() with std::stable_sort() in
order to fix this issue.  The signature of compareModuleHeaders() has to
be modified.

This commit also fixes commit d3676d4b666ead794fc58bbc7e07aa406dcf487a
that caused all headers to have NameAsWritten set to a 0-length string
without adapting compareModuleHeaders() to the new field.

Fixes #73145.
---
 clang/lib/Lex/ModuleMap.cpp | 10 ++
 1 file changed, 6 insertions(+), 4 deletions(-)

diff --git a/clang/lib/Lex/ModuleMap.cpp b/clang/lib/Lex/ModuleMap.cpp
index 00e13c9be4a7d73..7ba5a5f8cbf973d 100644
--- a/clang/lib/Lex/ModuleMap.cpp
+++ b/clang/lib/Lex/ModuleMap.cpp
@@ -2509,9 +2509,11 @@ void ModuleMapParser::parseHeaderDecl(MMToken::TokenKind 
LeadingToken,
   << FixItHint::CreateReplacement(CurrModuleDeclLoc, "framework module");
 }
 
-static int compareModuleHeaders(const Module::Header *A,
-const Module::Header *B) {
-  return A->NameAsWritten.compare(B->NameAsWritten);
+static bool compareModuleHeaders(const Module::Header &A,
+const Module::Header &B) {
+  return A.NameAsWritten < B.NameAsWritten ||
+(A.NameAsWritten == B.NameAsWritten &&
+ A.PathRelativeToRootModuleDirectory < 
B.PathRelativeToRootModuleDirectory);
 }
 
 /// Parse an umbrella directory declaration.
@@ -2574,7 +2576,7 @@ void ModuleMapParser::parseUmbrellaDirDecl(SourceLocation 
UmbrellaLoc) {
 }
 
 // Sort header paths so that the pcm doesn't depend on iteration order.
-llvm::array_pod_sort(Headers.begin(), Headers.end(), compareModuleHeaders);
+std::stable_sort(Headers.begin(), Headers.end(), compareModuleHeaders);
 
 for (auto &Header : Headers)
   Map.addHeader(ActiveModule, std::move(Header), ModuleMap::TextualHeader);

>From 6e2e45c2bfcd3846d91184a57bb2fe39fe745b25 Mon Sep 17 00:00:00 2001
From: Tulio Magno Quites Machado Filho 
Date: Wed, 22 Nov 2023 14:32:52 -0300
Subject: [PATCH 2/3] fixup! [clang] Fix sorting module headers

---
 clang/lib/Lex/ModuleMap.cpp | 7 ---
 1 file changed, 4 insertions(+), 3 deletions(-)

diff --git a/clang/lib/Lex/ModuleMap.cpp b/clang/lib/Lex/ModuleMap.cpp
index 7ba5a5f8cbf973d..591bd97075b87a9 100644
--- a/clang/lib/Lex/ModuleMap.cpp
+++ b/clang/lib/Lex/ModuleMap.cpp
@@ -2510,10 +2510,11 @@ void 
ModuleMapParser::parseHeaderDecl(MMToken::TokenKind LeadingToken,
 }
 
 static bool compareModuleHeaders(const Module::Header &A,
-const Module::Header &B) {
+ const Module::Header &B) {
   return A.NameAsWritten < B.NameAsWritten ||
-(A.NameAsWritten == B.NameAsWritten &&
- A.PathRelativeToRootModuleDirectory < 
B.PathRelativeToRootModuleDirectory);
+ (A.NameAsWritten == B.NameAsWritten &&
+  A.PathRelativeToRootModuleDirectory <
+  B.PathRelativeToRootModuleDirectory);
 }
 
 /// Parse an umbrella directory declaration.

>From d8c2a15b74adcea94f76ccc7e1bff507bb2b799e Mon Sep 17 00:00:00 2001
From: Tulio Magno Quites Machado Filho 
Date: Thu, 23 Nov 2023 10:09:16 -0300
Subject: [PATCH 3/3] fixup! [clang] Fix sorting module headers

---
 clang/lib/Lex/ModuleMap.cpp | 5 +
 1 file changed, 1 insertion(+), 4 deletions(-)

diff --git a/clang/lib/Lex/ModuleMap.cpp b/clang/lib/Lex/ModuleMap.cpp
index 591bd97075b87a9..1d67e275cb4775a 100644
--- a/clang/lib/Lex/ModuleMap.cpp
+++ b/clang/lib/Lex/ModuleMap.cpp
@@ -2511,10 +2511,7 @@ void ModuleMapParser::parseHeaderDecl(MMToken::TokenKind 
LeadingToken,
 
 static bool compareModuleHeaders(const Module::Header &A,
  const Module::Header &B) {
-  return A.NameAsWritten < B.NameAsWritten ||
- (A.NameAsWritten == B.NameAsWritten &&
-  A.PathRelativeToRootModuleDirectory <
-  B.PathRelativeToRootModuleDirectory);
+  return A.NameAsWritten < B.NameAsWritten;
 }
 
 /// Parse an umbrella directory declaration.

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


[clang] [clang] Fix sorting module headers (PR #73146)

2023-11-23 Thread Tulio Magno Quites Machado Filho via cfe-commits

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


[clang] [clang] Fix sorting module headers (PR #73146)

2023-11-23 Thread Tulio Magno Quites Machado Filho via cfe-commits

tuliom wrote:

OK. I modified this PR in order to only make the changes that fix #73145 .
Sorting will remain broken as it has been since 2021. I will provide another PR 
after this one gets merged.

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


[clang] [flang] [flang] Enable alias tags pass by default (PR #73111)

2023-11-23 Thread Tom Eccles via cfe-commits

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


[clang] [clang][analyzer] Support `fgetc` in StreamChecker (PR #72627)

2023-11-23 Thread Ben Shi via cfe-commits

https://github.com/benshi001 updated 
https://github.com/llvm/llvm-project/pull/72627

>From 81973987254f037f1682b7f0cd7a970177051f04 Mon Sep 17 00:00:00 2001
From: Ben Shi 
Date: Fri, 17 Nov 2023 17:22:10 +0800
Subject: [PATCH] [clang][analyzer] Support `fgetc` in StreamChecker

---
 .../StaticAnalyzer/Checkers/StreamChecker.cpp | 84 +++
 .../Analysis/Inputs/system-header-simulator.h |  1 +
 clang/test/Analysis/stream-error.c| 40 +
 clang/test/Analysis/stream.c  |  6 ++
 4 files changed, 96 insertions(+), 35 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index 1d53e59ca067c27..8eca989d7bcdea4 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -250,9 +250,12 @@ class StreamChecker : public Checker PutVal = Call.getArgSVal(0).getAs();
-  if (!PutVal)
-return;
-  ProgramStateRef StateNotFailed =
-  State->BindExpr(CE, C.getLocationContext(), *PutVal);
-  StateNotFailed =
-  StateNotFailed->set(StreamSym, StreamState::getOpened(Desc));
-  C.addTransition(StateNotFailed);
+  // Generate a transition for the success state of fputc.
+  if (!IsRead) {
+std::optional PutVal = Call.getArgSVal(0).getAs();
+if (!PutVal)
+  return;
+ProgramStateRef StateNotFailed =
+State->BindExpr(CE, C.getLocationContext(), *PutVal);
+StateNotFailed =
+StateNotFailed->set(StreamSym, 
StreamState::getOpened(Desc));
+C.addTransition(StateNotFailed);
+  }
+  // Generate a transition for the success state of fgetc.
+  // If we know the state to be FEOF at fgetc, do not add a success state.
+  else if (OldSS->ErrorState != ErrorFEof) {
+NonLoc RetVal = makeRetVal(C, CE).castAs();
+ProgramStateRef StateNotFailed =
+State->BindExpr(CE, C.getLocationContext(), RetVal);
+SValBuilder &SVB = C.getSValBuilder();
+auto &ASTC = C.getASTContext();
+// The returned 'unsigned char' of `fgetc` is converted to 'int',
+// so we need to check if it is in range [0, 255].
+auto CondLow =
+SVB.evalBinOp(State, BO_GE, RetVal, SVB.makeZeroVal(ASTC.IntTy),
+  SVB.getConditionType())
+.getAs();
+auto CondHigh =
+SVB.evalBinOp(State, BO_LE, RetVal,
+  SVB.makeIntVal(SVB.getBasicValueFactory()
+ .getMaxValue(ASTC.UnsignedCharTy)
+ .getLimitedValue(),
+ ASTC.IntTy),
+  SVB.getConditionType())
+.getAs();
+if (!CondLow || !CondHigh)
+  return;
+StateNotFailed = StateNotFailed->assume(*CondLow, true);
+if (!StateNotFailed)
+  return;
+StateNotFailed = StateNotFailed->assume(*CondHigh, true);
+if (!StateNotFailed)
+  return;
+C.addTransition(StateNotFailed);
+  }
 
   // Add transition for the failed state.
+  ProgramStateRef StateFailed = bindInt(*EofVal, State, C, CE);
+
   // If a (non-EOF) error occurs, the resulting value of the file position
   // indicator for the stream is indeterminate.
-  ProgramStateRef StateFailed = bindInt(*EofVal, State, C, CE);
-  StreamState NewSS = StreamState::getOpened(
-  Desc, ErrorFError, /*IsFilePositionIndeterminate*/ true);
+  StreamErrorState NewES;
+  if (IsRead)
+NewES =
+OldSS->ErrorState == ErrorFEof ? ErrorFEof : ErrorFEof | ErrorFError;
+  else
+NewES = ErrorFError;
+  StreamState NewSS = StreamState::getOpened(Desc, NewES, !NewES.isFEof());
   StateFailed = StateFailed->set(StreamSym, NewSS);
-  C.addTransition(StateFailed);
+  if (IsRead && OldSS->ErrorState != ErrorFEof)
+C.addTransition(StateFailed, constructSetEofNoteTag(C, StreamSym));
+  else
+C.addTransition(StateFailed);
 }
 
 void StreamChecker::preFseek(const FnDescription *Desc, const CallEvent &Call,
diff --git a/clang/test/Analysis/Inputs/system-header-simulator.h 
b/clang/test/Analysis/Inputs/system-header-simulator.h
index 8924103f5046ea2..fc57e8bdc3d30c3 100644
--- a/clang/test/Analysis/Inputs/system-header-simulator.h
+++ b/clang/test/Analysis/Inputs/system-header-simulator.h
@@ -48,6 +48,7 @@ FILE *freopen(const char *restrict pathname, const char 
*restrict mode, FILE *re
 int fclose(FILE *fp);
 size_t fread(void *restrict, size_t, size_t, FILE *restrict);
 size_t fwrite(const void *restrict, size_t, size_t, FILE *restrict);
+int fgetc(FILE *stream);
 int fputc(int ch, FILE *stream);
 int fseek(FILE *__stream, long int __off, int __whence);
 long int ftell(FILE *__stream);
diff --git a/clang/test/Analysis/stream-error.c 
b/clang/test/Analysis/stream-error.c
index 5ebdc32bb1b92ff..51bb600c6d024e3 100644
--- a/clang/test/Analysis/stream-error.c
+++ b/clang/test/Analysis/stream-error.c
@@ -101,6 +101,29 @@ void error_fwrite(void) {
   Ret = fwrite(0, 1, 10, F); // expected-war

[clang] [clang][analyzer] Support `fgetc` in StreamChecker (PR #72627)

2023-11-23 Thread Ben Shi via cfe-commits

https://github.com/benshi001 updated 
https://github.com/llvm/llvm-project/pull/72627

>From 5c3cb2cfbb91ac462633aa223ebeecc1d7790138 Mon Sep 17 00:00:00 2001
From: Ben Shi 
Date: Fri, 17 Nov 2023 17:22:10 +0800
Subject: [PATCH] [clang][analyzer] Support `fgetc` in StreamChecker

---
 .../StaticAnalyzer/Checkers/StreamChecker.cpp | 84 +++
 .../Analysis/Inputs/system-header-simulator.h |  1 +
 clang/test/Analysis/stream-error.c| 39 +
 clang/test/Analysis/stream.c  |  6 ++
 4 files changed, 95 insertions(+), 35 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index 1d53e59ca067c27..8eca989d7bcdea4 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -250,9 +250,12 @@ class StreamChecker : public Checker PutVal = Call.getArgSVal(0).getAs();
-  if (!PutVal)
-return;
-  ProgramStateRef StateNotFailed =
-  State->BindExpr(CE, C.getLocationContext(), *PutVal);
-  StateNotFailed =
-  StateNotFailed->set(StreamSym, StreamState::getOpened(Desc));
-  C.addTransition(StateNotFailed);
+  // Generate a transition for the success state of fputc.
+  if (!IsRead) {
+std::optional PutVal = Call.getArgSVal(0).getAs();
+if (!PutVal)
+  return;
+ProgramStateRef StateNotFailed =
+State->BindExpr(CE, C.getLocationContext(), *PutVal);
+StateNotFailed =
+StateNotFailed->set(StreamSym, 
StreamState::getOpened(Desc));
+C.addTransition(StateNotFailed);
+  }
+  // Generate a transition for the success state of fgetc.
+  // If we know the state to be FEOF at fgetc, do not add a success state.
+  else if (OldSS->ErrorState != ErrorFEof) {
+NonLoc RetVal = makeRetVal(C, CE).castAs();
+ProgramStateRef StateNotFailed =
+State->BindExpr(CE, C.getLocationContext(), RetVal);
+SValBuilder &SVB = C.getSValBuilder();
+auto &ASTC = C.getASTContext();
+// The returned 'unsigned char' of `fgetc` is converted to 'int',
+// so we need to check if it is in range [0, 255].
+auto CondLow =
+SVB.evalBinOp(State, BO_GE, RetVal, SVB.makeZeroVal(ASTC.IntTy),
+  SVB.getConditionType())
+.getAs();
+auto CondHigh =
+SVB.evalBinOp(State, BO_LE, RetVal,
+  SVB.makeIntVal(SVB.getBasicValueFactory()
+ .getMaxValue(ASTC.UnsignedCharTy)
+ .getLimitedValue(),
+ ASTC.IntTy),
+  SVB.getConditionType())
+.getAs();
+if (!CondLow || !CondHigh)
+  return;
+StateNotFailed = StateNotFailed->assume(*CondLow, true);
+if (!StateNotFailed)
+  return;
+StateNotFailed = StateNotFailed->assume(*CondHigh, true);
+if (!StateNotFailed)
+  return;
+C.addTransition(StateNotFailed);
+  }
 
   // Add transition for the failed state.
+  ProgramStateRef StateFailed = bindInt(*EofVal, State, C, CE);
+
   // If a (non-EOF) error occurs, the resulting value of the file position
   // indicator for the stream is indeterminate.
-  ProgramStateRef StateFailed = bindInt(*EofVal, State, C, CE);
-  StreamState NewSS = StreamState::getOpened(
-  Desc, ErrorFError, /*IsFilePositionIndeterminate*/ true);
+  StreamErrorState NewES;
+  if (IsRead)
+NewES =
+OldSS->ErrorState == ErrorFEof ? ErrorFEof : ErrorFEof | ErrorFError;
+  else
+NewES = ErrorFError;
+  StreamState NewSS = StreamState::getOpened(Desc, NewES, !NewES.isFEof());
   StateFailed = StateFailed->set(StreamSym, NewSS);
-  C.addTransition(StateFailed);
+  if (IsRead && OldSS->ErrorState != ErrorFEof)
+C.addTransition(StateFailed, constructSetEofNoteTag(C, StreamSym));
+  else
+C.addTransition(StateFailed);
 }
 
 void StreamChecker::preFseek(const FnDescription *Desc, const CallEvent &Call,
diff --git a/clang/test/Analysis/Inputs/system-header-simulator.h 
b/clang/test/Analysis/Inputs/system-header-simulator.h
index 8924103f5046ea2..fc57e8bdc3d30c3 100644
--- a/clang/test/Analysis/Inputs/system-header-simulator.h
+++ b/clang/test/Analysis/Inputs/system-header-simulator.h
@@ -48,6 +48,7 @@ FILE *freopen(const char *restrict pathname, const char 
*restrict mode, FILE *re
 int fclose(FILE *fp);
 size_t fread(void *restrict, size_t, size_t, FILE *restrict);
 size_t fwrite(const void *restrict, size_t, size_t, FILE *restrict);
+int fgetc(FILE *stream);
 int fputc(int ch, FILE *stream);
 int fseek(FILE *__stream, long int __off, int __whence);
 long int ftell(FILE *__stream);
diff --git a/clang/test/Analysis/stream-error.c 
b/clang/test/Analysis/stream-error.c
index 5ebdc32bb1b92ff..38e6b77b9bb5053 100644
--- a/clang/test/Analysis/stream-error.c
+++ b/clang/test/Analysis/stream-error.c
@@ -101,6 +101,28 @@ void error_fwrite(void) {
   Ret = fwrite(0, 1, 10, F); // expected-war

[clang] [clang][AArch64] Pass down stack clash protection options to LLVM/Backend (PR #68993)

2023-11-23 Thread Momchil Velikov via cfe-commits

https://github.com/momchil-velikov updated 
https://github.com/llvm/llvm-project/pull/68993

>From 553f647e3f8460e376b8a09233b23a0bd6b12ead Mon Sep 17 00:00:00 2001
From: Momchil Velikov 
Date: Wed, 11 Oct 2023 17:22:51 +0100
Subject: [PATCH 1/2] [clang][AArch64] Pass down stack clash protection options
 to LLVM/Backend

---
 clang/lib/CodeGen/CodeGenModule.cpp | 12 +++-
 clang/lib/Driver/ToolChains/Clang.cpp   |  2 +-
 clang/test/CodeGen/stack-clash-protection.c | 16 
 3 files changed, 24 insertions(+), 6 deletions(-)

diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 7cdf50a281cd278..f4416f298b71188 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -1085,6 +1085,16 @@ void CodeGenModule::Release() {
 "sign-return-address-with-bkey", 1);
   }
 
+  if (Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_be) {
+auto *InlineAsm = llvm::MDString::get(TheModule.getContext(), 
"inline-asm");
+if (CodeGenOpts.StackClashProtector)
+  getModule().addModuleFlag(llvm::Module::Override, "probe-stack",
+InlineAsm);
+if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096)
+  getModule().addModuleFlag(llvm::Module::Min, "stack-probe-size",
+CodeGenOpts.StackProbeSize);
+  }
+
   if (!CodeGenOpts.MemoryProfileOutput.empty()) {
 llvm::LLVMContext &Ctx = TheModule.getContext();
 getModule().addModuleFlag(
@@ -2296,7 +2306,7 @@ void 
CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
   if ((!D || !D->hasAttr()) && CodeGenOpts.UnwindTables)
 B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables));
 
-  if (CodeGenOpts.StackClashProtector)
+  if (CodeGenOpts.StackClashProtector && !getTarget().getTriple().isAArch64())
 B.addAttribute("probe-stack", "inline-asm");
 
   if (!hasUnwindExceptions(LangOpts))
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 6dec117aed1056b..5da573a6e13b2c8 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -3507,7 +3507,7 @@ static void RenderSCPOptions(const ToolChain &TC, const 
ArgList &Args,
 return;
 
   if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
-  !EffectiveTriple.isPPC64())
+  !EffectiveTriple.isPPC64() && !EffectiveTriple.isAArch64())
 return;
 
   Args.addOptInFlag(CmdArgs, options::OPT_fstack_clash_protection,
diff --git a/clang/test/CodeGen/stack-clash-protection.c 
b/clang/test/CodeGen/stack-clash-protection.c
index 67571f5cdb2c14c..2f502ef453d42f4 100644
--- a/clang/test/CodeGen/stack-clash-protection.c
+++ b/clang/test/CodeGen/stack-clash-protection.c
@@ -1,10 +1,12 @@
 // Check the correct function attributes are generated
-// RUN: %clang_cc1 -triple x86_64-linux -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection | FileCheck %s
-// RUN: %clang_cc1 -triple s390x-linux-gnu -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection | FileCheck %s
-// RUN: %clang_cc1 -triple powerpc64le-linux-gnu -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection | FileCheck %s
-// RUN: %clang_cc1 -triple powerpc64-linux-gnu -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-linux -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection -mstack-probe-size=8192 | FileCheck %s
+// RUN: %clang_cc1 -triple s390x-linux-gnu -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection -mstack-probe-size=8192 | FileCheck %s
+// RUN: %clang_cc1 -triple powerpc64le-linux-gnu -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection -mstack-probe-size=8192 | FileCheck %s
+// RUN: %clang_cc1 -triple powerpc64-linux-gnu -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection -mstack-probe-size=8192 | FileCheck %s
+// RUN: %clang_cc1 -triple aarch64-linux-gnu -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection -mstack-probe-size=8192 | FileCheck %s 
--check-prefixes CHECK-AARCH64
 
 // CHECK: define{{.*}} void @large_stack() #[[A:.*]] {
+// CHECK-AARCH64: define{{.*}} void @large_stack() #[[A:.*]] {
 void large_stack(void) {
   volatile int stack[2], i;
   for (i = 0; i < sizeof(stack) / sizeof(int); ++i)
@@ -12,14 +14,20 @@ void large_stack(void) {
 }
 
 // CHECK: define{{.*}} void @vla({{.*}}) #[[A:.*]] {
+// CHECK-AARCH64: define{{.*}} void @vla({{.*}}) #[[A:.*]] {
 void vla(int n) {
   volatile int vla[n];
   __builtin_memset(&vla[0], 0, 1);
 }
 
 // CHECK: define{{.*}} void @builtin_alloca({{.*}}) #[[A:.*]] {
+// CHECK-AARCH64: define{{.*}} void @builtin_alloca({{.*}}) #[[A:.*]] {
 void builtin_alloca(int n) {
   volatile void *mem = __builtin_alloca(n);
 }
 
 // CHECK: attributes #[[A]] = {{.*}} "probe-stack"="inline-asm"
+// CHECK-AARCH64-NOT: attributes #[[A]] = {{.*}} "probe-stack"
+
+// CHECK-AARCH64: !{i32 4, !"probe-stack", !"inline-asm"}
+// CHECK-AARCH64:

[clang-tools-extra] [llvm] [clang] [clang] Fix false positive -Wmissing-field-initializer for anonymous unions (PR #70829)

2023-11-23 Thread Mariya Podchishchaeva via cfe-commits


@@ -727,6 +729,44 @@ void InitListChecker::FillInEmptyInitForField(unsigned 
Init, FieldDecl *Field,
 if (hadError || VerifyOnly) {
   // Do nothing
 } else if (Init < NumInits) {

Fznamznon wrote:

It seems `Init < NumInits` is always true for non-`VerifyOnly` mode only for 
structs. So, removing lines `684-685, 704-707, 772-778` breaks a number of 
tests with unions. The assertion on line 676 confirms:
```
if (Init >= NumInits || !ILE->getInit(Init)) {
  if (const RecordType *RType = ILE->getType()->getAs())
if (!RType->getDecl()->isUnion())
  assert((Init < NumInits || VerifyOnly) &&
 "This ILE should have been expanded");
```
I can still put warning emission out of `Init < NumInits` check though if that 
seems more correct.

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


[clang-tools-extra] [llvm] [clang] [clang] Fix false positive -Wmissing-field-initializer for anonymous unions (PR #70829)

2023-11-23 Thread Mariya Podchishchaeva via cfe-commits

https://github.com/Fznamznon updated 
https://github.com/llvm/llvm-project/pull/70829

>From ac30780250875802d13450d17e6959f9e2ad3a70 Mon Sep 17 00:00:00 2001
From: "Podchishchaeva, Mariya" 
Date: Tue, 31 Oct 2023 09:27:51 -0700
Subject: [PATCH 1/5] [clang] Fix false positive -Wmissing-field-initializer
 for anonymous unions

Normally warning is not reported when a field has default initializer.
Do so for anonymous unions with default initializers as well.
No release note since it is a regression in clang 18.

Fixes https://github.com/llvm/llvm-project/issues/70384
---
 clang/lib/Sema/SemaInit.cpp   | 99 +++
 .../SemaCXX/cxx2a-initializer-aggregates.cpp  | 66 -
 2 files changed, 122 insertions(+), 43 deletions(-)

diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index ec796def96ad3d8..881e67587e430e7 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -349,17 +349,13 @@ class InitListChecker {
   bool SubobjectIsDesignatorContext, unsigned &Index,
   InitListExpr *StructuredList,
   unsigned &StructuredIndex);
-  bool CheckDesignatedInitializer(const InitializedEntity &Entity,
-  InitListExpr *IList, DesignatedInitExpr *DIE,
-  unsigned DesigIdx,
-  QualType &CurrentObjectType,
-  RecordDecl::field_iterator *NextField,
-  llvm::APSInt *NextElementIndex,
-  unsigned &Index,
-  InitListExpr *StructuredList,
-  unsigned &StructuredIndex,
-  bool FinishSubobjectInit,
-  bool TopLevelObject);
+  bool CheckDesignatedInitializer(
+  const InitializedEntity &Entity, InitListExpr *IList,
+  DesignatedInitExpr *DIE, unsigned DesigIdx, QualType &CurrentObjectType,
+  RecordDecl::field_iterator *NextField, llvm::APSInt *NextElementIndex,
+  unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex,
+  bool FinishSubobjectInit, bool TopLevelObject,
+  llvm::SmallPtrSetImpl *InitializedFields = nullptr);
   InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
QualType CurrentObjectType,
InitListExpr *StructuredList,
@@ -2248,7 +2244,8 @@ void InitListChecker::CheckStructUnionTypes(
   // the next field that we'll be initializing.
   bool DesignatedInitFailed = CheckDesignatedInitializer(
   Entity, IList, DIE, 0, DeclType, &Field, nullptr, Index,
-  StructuredList, StructuredIndex, true, TopLevelObject);
+  StructuredList, StructuredIndex, true, TopLevelObject,
+  &InitializedFields);
   if (DesignatedInitFailed)
 hadError = true;
 
@@ -2256,7 +2253,6 @@ void InitListChecker::CheckStructUnionTypes(
   DesignatedInitExpr::Designator *D = DIE->getDesignator(0);
   if (!VerifyOnly && D->isFieldDesignator()) {
 FieldDecl *F = D->getFieldDecl();
-InitializedFields.insert(F);
 if (!DesignatedInitFailed) {
   QualType ET = SemaRef.Context.getBaseElementType(F->getType());
   if (checkDestructorReference(ET, InitLoc, SemaRef)) {
@@ -2365,21 +2361,43 @@ void InitListChecker::CheckStructUnionTypes(
   !RD->isUnion()) {
 // It is possible we have one or more unnamed bitfields remaining.
 // Find first (if any) named field and emit warning.
-for (RecordDecl::field_iterator it = HasDesignatedInit ? RD->field_begin()
-   : Field,
-end = RD->field_end();
- it != end; ++it) {
-  if (HasDesignatedInit && InitializedFields.count(*it))
-continue;
+auto MissingFieldCheck = [&](const RecordDecl *Record,
+ RecordDecl::field_iterator StartField,
+ auto &&MissingFieldCheck) -> bool {
+  FieldDecl *FirstUninitialized = nullptr;
+  for (RecordDecl::field_iterator it = StartField,
+  end = Record->field_end();
+   it != end; ++it) {
+bool AllSet = false;
+if (it->isAnonymousStructOrUnion()) {
+  RecordDecl *RDAnon = it->getType()->getAsRecordDecl();
+  AllSet = MissingFieldCheck(RDAnon, RDAnon->field_begin(),
+ MissingFieldCheck);
+}
+
+if ((HasDesignatedInit && InitializedFields.count(*it)) ||
+it->hasInClassInitializer() || AllSet) {
+  if (Record->isUnion())
+return true;
+  continue;
+}
 
-  if (!it->isUnnamedBitfield() && !it->hasInClassInitializer() &&

[flang] [clang] [flang] Add runtimes using --dependent-lib on MSVC targets (PR #72519)

2023-11-23 Thread David Truby via cfe-commits




DavidTruby wrote:

I've had to add it as just `-fc1` because of the way lit does argument passing 
on Windows (it puts the "flang-new" and "-fc1" in quotes, but only sometimes :))

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


[flang] [clang] [flang] Add runtimes using --dependent-lib on MSVC targets (PR #72519)

2023-11-23 Thread David Truby via cfe-commits

https://github.com/DavidTruby updated 
https://github.com/llvm/llvm-project/pull/72519

>From eeb1e7c7b7905d541c9359bd1800fdfb70f0219e Mon Sep 17 00:00:00 2001
From: David Truby 
Date: Thu, 16 Nov 2023 14:32:27 +
Subject: [PATCH 1/3] [flang] Add runtimes using --dependent-lib on MSVC
 targets

This patch uses the added --dependent-lib support to add the relevant
runtimes on MSVC targets as `/DEFAULTLIB:` sections in the object file
rather than on the link line. This should help CMake support for flang
on Windows.
---
 clang/lib/Driver/ToolChains/CommonArgs.cpp| 43 +-
 clang/lib/Driver/ToolChains/CommonArgs.h  |  2 +-
 clang/lib/Driver/ToolChains/Darwin.cpp|  2 +-
 clang/lib/Driver/ToolChains/DragonFly.cpp |  2 +-
 clang/lib/Driver/ToolChains/Flang.cpp | 57 +++
 clang/lib/Driver/ToolChains/FreeBSD.cpp   |  2 +-
 clang/lib/Driver/ToolChains/Gnu.cpp   |  2 +-
 clang/lib/Driver/ToolChains/Haiku.cpp |  2 +-
 clang/lib/Driver/ToolChains/MSVC.cpp  |  2 +-
 clang/lib/Driver/ToolChains/MinGW.cpp |  2 +-
 clang/lib/Driver/ToolChains/NetBSD.cpp|  2 +-
 clang/lib/Driver/ToolChains/OpenBSD.cpp   |  2 +-
 clang/lib/Driver/ToolChains/Solaris.cpp   |  2 +-
 flang/test/Driver/linker-flags.f90| 35 
 .../test/Driver/msvc-dependent-lib-flags.f90  | 36 
 15 files changed, 107 insertions(+), 86 deletions(-)
 create mode 100644 flang/test/Driver/msvc-dependent-lib-flags.f90

diff --git a/clang/lib/Driver/ToolChains/CommonArgs.cpp 
b/clang/lib/Driver/ToolChains/CommonArgs.cpp
index 5d2cd1959b06925..55951162df50a75 100644
--- a/clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ b/clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -977,47 +977,10 @@ bool tools::addOpenMPRuntime(ArgStringList &CmdArgs, 
const ToolChain &TC,
   return true;
 }
 
-void tools::addFortranRuntimeLibs(const ToolChain &TC, const ArgList &Args,
+void tools::addFortranRuntimeLibs(const ToolChain &TC,
   llvm::opt::ArgStringList &CmdArgs) {
-  if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
-CmdArgs.push_back(Args.MakeArgString(
-"/DEFAULTLIB:" + TC.getCompilerRTBasename(Args, "builtins")));
-unsigned RTOptionID = options::OPT__SLASH_MT;
-if (auto *rtl = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
-  RTOptionID = llvm::StringSwitch(rtl->getValue())
-   .Case("static", options::OPT__SLASH_MT)
-   .Case("static_dbg", options::OPT__SLASH_MTd)
-   .Case("dll", options::OPT__SLASH_MD)
-   .Case("dll_dbg", options::OPT__SLASH_MDd)
-   .Default(options::OPT__SLASH_MT);
-}
-switch (RTOptionID) {
-case options::OPT__SLASH_MT:
-  CmdArgs.push_back("/DEFAULTLIB:libcmt");
-  CmdArgs.push_back("Fortran_main.static.lib");
-  CmdArgs.push_back("FortranRuntime.static.lib");
-  CmdArgs.push_back("FortranDecimal.static.lib");
-  break;
-case options::OPT__SLASH_MTd:
-  CmdArgs.push_back("/DEFAULTLIB:libcmtd");
-  CmdArgs.push_back("Fortran_main.static_dbg.lib");
-  CmdArgs.push_back("FortranRuntime.static_dbg.lib");
-  CmdArgs.push_back("FortranDecimal.static_dbg.lib");
-  break;
-case options::OPT__SLASH_MD:
-  CmdArgs.push_back("/DEFAULTLIB:msvcrt");
-  CmdArgs.push_back("Fortran_main.dynamic.lib");
-  CmdArgs.push_back("FortranRuntime.dynamic.lib");
-  CmdArgs.push_back("FortranDecimal.dynamic.lib");
-  break;
-case options::OPT__SLASH_MDd:
-  CmdArgs.push_back("/DEFAULTLIB:msvcrtd");
-  CmdArgs.push_back("Fortran_main.dynamic_dbg.lib");
-  CmdArgs.push_back("FortranRuntime.dynamic_dbg.lib");
-  CmdArgs.push_back("FortranDecimal.dynamic_dbg.lib");
-  break;
-}
-  } else {
+  // These are handled by adding link options to the object file on Windows
+  if (!TC.getTriple().isKnownWindowsMSVCEnvironment()) {
 CmdArgs.push_back("-lFortran_main");
 CmdArgs.push_back("-lFortranRuntime");
 CmdArgs.push_back("-lFortranDecimal");
diff --git a/clang/lib/Driver/ToolChains/CommonArgs.h 
b/clang/lib/Driver/ToolChains/CommonArgs.h
index 0a0951c5386e601..f364c9793c9be62 100644
--- a/clang/lib/Driver/ToolChains/CommonArgs.h
+++ b/clang/lib/Driver/ToolChains/CommonArgs.h
@@ -116,7 +116,7 @@ bool addOpenMPRuntime(llvm::opt::ArgStringList &CmdArgs, 
const ToolChain &TC,
   bool IsOffloadingHost = false, bool GompNeedsRT = false);
 
 /// Adds Fortran runtime libraries to \p CmdArgs.
-void addFortranRuntimeLibs(const ToolChain &TC, const llvm::opt::ArgList &Args,
+void addFortranRuntimeLibs(const ToolChain &TC,
llvm::opt::ArgStringList &CmdArgs);
 
 /// Adds the path for the Fortran runtime libraries to \p CmdArgs.
diff --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index 7c3d4982d8f6a

[libc] [llvm] [libcxx] [compiler-rt] [flang] [lld] [clang] Fix ISel crash when lowering BUILD_VECTOR (PR #73186)

2023-11-23 Thread Phoebe Wang via cfe-commits


@@ -7254,6 +7255,10 @@ static SDValue 
lowerBuildVectorAsBroadcast(BuildVectorSDNode *BVOp,
 EVT CVT = Ld.getValueType();
 assert(!CVT.isVector() && "Must not broadcast a vector type");
 
+// 512 bit vpbroadcastw is only available with AVX512BW
+if (ScalarSize == 16 && IsGT256 && !Subtarget.hasBWI())
+  return SDValue();

phoebewang wrote:

The problem only exists for `v32f16` which is not handled by 
`PreprocessISelDAG`. Maybe we need add `v32f16` support there.

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


[clang] 0bc7cd4 - [flang] Add runtimes using --dependent-lib on MSVC targets (#72519)

2023-11-23 Thread via cfe-commits

Author: David Truby
Date: 2023-11-23T14:19:57Z
New Revision: 0bc7cd4d51226344a54da5929d87184730e73e83

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

LOG: [flang] Add runtimes using --dependent-lib on MSVC targets (#72519)

This patch uses the added --dependent-lib support to add the relevant
runtimes on MSVC targets as `/DEFAULTLIB:` sections in the object file
rather than on the link line. This should help CMake support for flang
on Windows.

Fixes #63741 
Fixes #68017

Added: 
flang/test/Driver/msvc-dependent-lib-flags.f90

Modified: 
clang/lib/Driver/ToolChains/CommonArgs.cpp
clang/lib/Driver/ToolChains/CommonArgs.h
clang/lib/Driver/ToolChains/Darwin.cpp
clang/lib/Driver/ToolChains/DragonFly.cpp
clang/lib/Driver/ToolChains/Flang.cpp
clang/lib/Driver/ToolChains/FreeBSD.cpp
clang/lib/Driver/ToolChains/Gnu.cpp
clang/lib/Driver/ToolChains/Haiku.cpp
clang/lib/Driver/ToolChains/MSVC.cpp
clang/lib/Driver/ToolChains/MinGW.cpp
clang/lib/Driver/ToolChains/NetBSD.cpp
clang/lib/Driver/ToolChains/OpenBSD.cpp
clang/lib/Driver/ToolChains/Solaris.cpp
flang/test/Driver/linker-flags.f90

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/CommonArgs.cpp 
b/clang/lib/Driver/ToolChains/CommonArgs.cpp
index 5d2cd1959b06925..1f31c6395206ee8 100644
--- a/clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ b/clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -977,47 +977,11 @@ bool tools::addOpenMPRuntime(ArgStringList &CmdArgs, 
const ToolChain &TC,
   return true;
 }
 
-void tools::addFortranRuntimeLibs(const ToolChain &TC, const ArgList &Args,
+void tools::addFortranRuntimeLibs(const ToolChain &TC,
   llvm::opt::ArgStringList &CmdArgs) {
-  if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
-CmdArgs.push_back(Args.MakeArgString(
-"/DEFAULTLIB:" + TC.getCompilerRTBasename(Args, "builtins")));
-unsigned RTOptionID = options::OPT__SLASH_MT;
-if (auto *rtl = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
-  RTOptionID = llvm::StringSwitch(rtl->getValue())
-   .Case("static", options::OPT__SLASH_MT)
-   .Case("static_dbg", options::OPT__SLASH_MTd)
-   .Case("dll", options::OPT__SLASH_MD)
-   .Case("dll_dbg", options::OPT__SLASH_MDd)
-   .Default(options::OPT__SLASH_MT);
-}
-switch (RTOptionID) {
-case options::OPT__SLASH_MT:
-  CmdArgs.push_back("/DEFAULTLIB:libcmt");
-  CmdArgs.push_back("Fortran_main.static.lib");
-  CmdArgs.push_back("FortranRuntime.static.lib");
-  CmdArgs.push_back("FortranDecimal.static.lib");
-  break;
-case options::OPT__SLASH_MTd:
-  CmdArgs.push_back("/DEFAULTLIB:libcmtd");
-  CmdArgs.push_back("Fortran_main.static_dbg.lib");
-  CmdArgs.push_back("FortranRuntime.static_dbg.lib");
-  CmdArgs.push_back("FortranDecimal.static_dbg.lib");
-  break;
-case options::OPT__SLASH_MD:
-  CmdArgs.push_back("/DEFAULTLIB:msvcrt");
-  CmdArgs.push_back("Fortran_main.dynamic.lib");
-  CmdArgs.push_back("FortranRuntime.dynamic.lib");
-  CmdArgs.push_back("FortranDecimal.dynamic.lib");
-  break;
-case options::OPT__SLASH_MDd:
-  CmdArgs.push_back("/DEFAULTLIB:msvcrtd");
-  CmdArgs.push_back("Fortran_main.dynamic_dbg.lib");
-  CmdArgs.push_back("FortranRuntime.dynamic_dbg.lib");
-  CmdArgs.push_back("FortranDecimal.dynamic_dbg.lib");
-  break;
-}
-  } else {
+  // These are handled earlier on Windows by telling the frontend driver to add
+  // the correct libraries to link against as dependents in the object file.
+  if (!TC.getTriple().isKnownWindowsMSVCEnvironment()) {
 CmdArgs.push_back("-lFortran_main");
 CmdArgs.push_back("-lFortranRuntime");
 CmdArgs.push_back("-lFortranDecimal");

diff  --git a/clang/lib/Driver/ToolChains/CommonArgs.h 
b/clang/lib/Driver/ToolChains/CommonArgs.h
index 0a0951c5386e601..f364c9793c9be62 100644
--- a/clang/lib/Driver/ToolChains/CommonArgs.h
+++ b/clang/lib/Driver/ToolChains/CommonArgs.h
@@ -116,7 +116,7 @@ bool addOpenMPRuntime(llvm::opt::ArgStringList &CmdArgs, 
const ToolChain &TC,
   bool IsOffloadingHost = false, bool GompNeedsRT = false);
 
 /// Adds Fortran runtime libraries to \p CmdArgs.
-void addFortranRuntimeLibs(const ToolChain &TC, const llvm::opt::ArgList &Args,
+void addFortranRuntimeLibs(const ToolChain &TC,
llvm::opt::ArgStringList &CmdArgs);
 
 /// Adds the path for the Fortran runtime libraries to \p CmdArgs.

diff  --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index 7c3d4982d8f6a8c..1f61bb02c6ae226 100644
--- a/clang/lib/Dr

[clang] [flang] [flang] Add runtimes using --dependent-lib on MSVC targets (PR #72519)

2023-11-23 Thread David Truby via cfe-commits

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


[clang] [Clang] Fix `-Wdocumentation` warning (NFC) (PR #73243)

2023-11-23 Thread Egor Zhdan via cfe-commits

https://github.com/egorzhdan created 
https://github.com/llvm/llvm-project/pull/73243

```
llvm-project/clang/include/clang/AST/OpenMPClause.h:7762:14: warning: parameter 
'Modifier' not found in the function declaration [-Wdocumentation]
  /// \param Modifier The modifier applied to 'order' clause.
 ^~~~
llvm-project/clang/include/clang/AST/OpenMPClause.h:7762:14: note: did you mean 
'M'?
  /// \param Modifier The modifier applied to 'order' clause.
```

>From d1a1245492950601c8513c1a80b2d361b1ededc5 Mon Sep 17 00:00:00 2001
From: Egor Zhdan 
Date: Thu, 23 Nov 2023 14:19:17 +
Subject: [PATCH] [Clang] Fix `-Wdocumentation` warning (NFC)

```
llvm-project/clang/include/clang/AST/OpenMPClause.h:7762:14: warning: parameter 
'Modifier' not found in the function declaration [-Wdocumentation]
  /// \param Modifier The modifier applied to 'order' clause.
 ^~~~
llvm-project/clang/include/clang/AST/OpenMPClause.h:7762:14: note: did you mean 
'M'?
  /// \param Modifier The modifier applied to 'order' clause.
```
---
 clang/include/clang/AST/OpenMPClause.h | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/clang/include/clang/AST/OpenMPClause.h 
b/clang/include/clang/AST/OpenMPClause.h
index 549f12e87df597a..51155e63dcb8f7d 100644
--- a/clang/include/clang/AST/OpenMPClause.h
+++ b/clang/include/clang/AST/OpenMPClause.h
@@ -7776,10 +7776,10 @@ class OMPOrderClause final : public OMPClause {
   /// \param MLoc Location of the modifier
   OMPOrderClause(OpenMPOrderClauseKind A, SourceLocation ALoc,
  SourceLocation StartLoc, SourceLocation LParenLoc,
- SourceLocation EndLoc, OpenMPOrderClauseModifier M,
+ SourceLocation EndLoc, OpenMPOrderClauseModifier Modifier,
  SourceLocation MLoc)
   : OMPClause(llvm::omp::OMPC_order, StartLoc, EndLoc),
-LParenLoc(LParenLoc), Kind(A), KindKwLoc(ALoc), Modifier(M),
+LParenLoc(LParenLoc), Kind(A), KindKwLoc(ALoc), Modifier(Modifier),
 ModifierKwLoc(MLoc) {}
 
   /// Build an empty clause.

___
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 check hicpp-ignored-remove-result (PR #73119)

2023-11-23 Thread Piotr Zegar via cfe-commits
=?utf-8?q?Björn?= Svensson 
Message-ID:
In-Reply-To: 


PiotrZSL wrote:

by separate check I mean "Create class that derive from oryginal check, move 
some code in oryginal check  (config) to protected methods (mainly storeConfig) 
and just override config in parent class. SImply if you call --dump-config, 
then for your check list of functions shouldn't be configurable.

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


[clang] [Clang] Fix `-Wdocumentation` warning (NFC) (PR #73243)

2023-11-23 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Egor Zhdan (egorzhdan)


Changes

```
llvm-project/clang/include/clang/AST/OpenMPClause.h:7762:14: warning: parameter 
'Modifier' not found in the function declaration [-Wdocumentation]
  /// \param Modifier The modifier applied to 'order' clause.
 ^~~~
llvm-project/clang/include/clang/AST/OpenMPClause.h:7762:14: note: did you mean 
'M'?
  /// \param Modifier The modifier applied to 'order' clause.
```

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


1 Files Affected:

- (modified) clang/include/clang/AST/OpenMPClause.h (+2-2) 


``diff
diff --git a/clang/include/clang/AST/OpenMPClause.h 
b/clang/include/clang/AST/OpenMPClause.h
index 549f12e87df597a..51155e63dcb8f7d 100644
--- a/clang/include/clang/AST/OpenMPClause.h
+++ b/clang/include/clang/AST/OpenMPClause.h
@@ -7776,10 +7776,10 @@ class OMPOrderClause final : public OMPClause {
   /// \param MLoc Location of the modifier
   OMPOrderClause(OpenMPOrderClauseKind A, SourceLocation ALoc,
  SourceLocation StartLoc, SourceLocation LParenLoc,
- SourceLocation EndLoc, OpenMPOrderClauseModifier M,
+ SourceLocation EndLoc, OpenMPOrderClauseModifier Modifier,
  SourceLocation MLoc)
   : OMPClause(llvm::omp::OMPC_order, StartLoc, EndLoc),
-LParenLoc(LParenLoc), Kind(A), KindKwLoc(ALoc), Modifier(M),
+LParenLoc(LParenLoc), Kind(A), KindKwLoc(ALoc), Modifier(Modifier),
 ModifierKwLoc(MLoc) {}
 
   /// Build an empty clause.

``




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


[clang] [llvm] [AArch64] Stack probing for function prologues (PR #66524)

2023-11-23 Thread Momchil Velikov via cfe-commits


@@ -1757,46 +1826,55 @@ void AArch64FrameLowering::emitPrologue(MachineFunction 
&MF,
 }
   }
 
-  StackOffset AllocateBefore = SVEStackSize, AllocateAfter = {};
+  StackOffset SVECalleeSavedSize = {}, SVELocalsSize = SVEStackSize;
   MachineBasicBlock::iterator CalleeSavesBegin = MBBI, CalleeSavesEnd = MBBI;
 
   // Process the SVE callee-saves to determine what space needs to be
   // allocated.
   if (int64_t CalleeSavedSize = AFI->getSVECalleeSavedStackSize()) {
+LLVM_DEBUG(dbgs() << "SVECalleeSavedStackSize = " << CalleeSavedSize
+  << "\n");
 // Find callee save instructions in frame.
 CalleeSavesBegin = MBBI;
 assert(IsSVECalleeSave(CalleeSavesBegin) && "Unexpected instruction");
 while (IsSVECalleeSave(MBBI) && MBBI != MBB.getFirstTerminator())
   ++MBBI;
 CalleeSavesEnd = MBBI;
 
-AllocateBefore = StackOffset::getScalable(CalleeSavedSize);
-AllocateAfter = SVEStackSize - AllocateBefore;
+SVECalleeSavedSize = StackOffset::getScalable(CalleeSavedSize);
+SVELocalsSize = SVEStackSize - SVECalleeSavedSize;
+
+// Allocate space for the SVE callee saves.
+if (SVECalleeSavedSize) {
+  allocateSVEStackSpace(
+  MBB, CalleeSavesBegin, SVECalleeSavedSize,
+  StackOffset::getFixed((int64_t)MFI.getStackSize() - NumBytes),
+  EmitAsyncCFI && !HasFP);
+  if (EmitAsyncCFI)
+emitCalleeSavedSVELocations(MBB, CalleeSavesEnd);
+}
   }
 
-  // Allocate space for the callee saves (if any).
-  emitFrameOffset(
-  MBB, CalleeSavesBegin, DL, AArch64::SP, AArch64::SP, -AllocateBefore, 
TII,
-  MachineInstr::FrameSetup, false, false, nullptr,
-  EmitAsyncCFI && !HasFP && AllocateBefore,
-  StackOffset::getFixed((int64_t)MFI.getStackSize() - NumBytes));
-
-  if (EmitAsyncCFI)
-emitCalleeSavedSVELocations(MBB, CalleeSavesEnd);
-
-  // Finally allocate remaining SVE stack space.
-  emitFrameOffset(MBB, CalleeSavesEnd, DL, AArch64::SP, AArch64::SP,
-  -AllocateAfter, TII, MachineInstr::FrameSetup, false, false,
-  nullptr, EmitAsyncCFI && !HasFP && AllocateAfter,
-  AllocateBefore + StackOffset::getFixed(
-   (int64_t)MFI.getStackSize() - 
NumBytes));
+  // Allocate stack space for the local SVE objects.
+  if (SVELocalsSize)
+allocateSVEStackSpace(

momchil-velikov wrote:

Done (not the windows part)

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


[clang] [llvm] [AArch64] Stack probing for function prologues (PR #66524)

2023-11-23 Thread Momchil Velikov via cfe-commits


@@ -0,0 +1,722 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
+; RUN: llc -mtriple aarch64-none-eabi < %s -verify-machineinstrs | FileCheck %s
+; RUN: llc -mtriple aarch64-none-eabi < %s -verify-machineinstrs -global-isel 
-global-isel-abort=2 | FileCheck %s
+
+; Test prolog sequences for stack probing when SVE objects are involved.
+
+; The space for SVE objects needs probing in the general case, because
+; the stack adjustment may happen to be too big (i.e. greater than the
+; probe size) to allocate with a single `addvl`.
+; When we do know that the stack adjustment cannot exceed the probe size
+; we can avoid emitting a probe loop and emit a simple `addvl; str`
+; sequence instead.
+
+define void @sve_1_vector(ptr %out) #0 {
+; CHECK-LABEL: sve_1_vector:
+; CHECK:   // %bb.0: // %entry
+; CHECK-NEXT:str x29, [sp, #-16]! // 8-byte Folded Spill
+; CHECK-NEXT:.cfi_def_cfa_offset 16
+; CHECK-NEXT:.cfi_offset w29, -16
+; CHECK-NEXT:addvl sp, sp, #-1
+; CHECK-NEXT:.cfi_escape 0x0f, 0x0c, 0x8f, 0x00, 0x11, 0x10, 0x22, 0x11, 
0x08, 0x92, 0x2e, 0x00, 0x1e, 0x22 // sp + 16 + 8 * VG
+; CHECK-NEXT:addvl sp, sp, #1
+; CHECK-NEXT:.cfi_def_cfa wsp, 16
+; CHECK-NEXT:ldr x29, [sp], #16 // 8-byte Folded Reload
+; CHECK-NEXT:.cfi_def_cfa_offset 0
+; CHECK-NEXT:.cfi_restore w29
+; CHECK-NEXT:ret
+entry:
+  %vec = alloca , align 16
+  ret void
+}
+
+; As above, but with 4 SVE vectors of stack space.
+define void @sve_4_vector(ptr %out) #0 {
+; CHECK-LABEL: sve_4_vector:
+; CHECK:   // %bb.0: // %entry
+; CHECK-NEXT:str x29, [sp, #-16]! // 8-byte Folded Spill
+; CHECK-NEXT:.cfi_def_cfa_offset 16
+; CHECK-NEXT:.cfi_offset w29, -16
+; CHECK-NEXT:addvl sp, sp, #-4
+; CHECK-NEXT:.cfi_escape 0x0f, 0x0c, 0x8f, 0x00, 0x11, 0x10, 0x22, 0x11, 
0x20, 0x92, 0x2e, 0x00, 0x1e, 0x22 // sp + 16 + 32 * VG
+; CHECK-NEXT:addvl sp, sp, #4
+; CHECK-NEXT:.cfi_def_cfa wsp, 16
+; CHECK-NEXT:ldr x29, [sp], #16 // 8-byte Folded Reload
+; CHECK-NEXT:.cfi_def_cfa_offset 0
+; CHECK-NEXT:.cfi_restore w29
+; CHECK-NEXT:ret
+entry:
+  %vec1 = alloca , align 16
+  %vec2 = alloca , align 16
+  %vec3 = alloca , align 16
+  %vec4 = alloca , align 16
+  ret void
+}
+
+; As above, but with 16 SVE vectors of stack space.
+; The stack adjustment is less than or equal to 16 x 256 = 4096, so
+; we can allocate the locals at once.
+define void @sve_16_vector(ptr %out) #0 {
+; CHECK-LABEL: sve_16_vector:
+; CHECK:   // %bb.0: // %entry
+; CHECK-NEXT:str x29, [sp, #-16]! // 8-byte Folded Spill
+; CHECK-NEXT:.cfi_def_cfa_offset 16
+; CHECK-NEXT:.cfi_offset w29, -16
+; CHECK-NEXT:addvl sp, sp, #-16
+; CHECK-NEXT:.cfi_escape 0x0f, 0x0d, 0x8f, 0x00, 0x11, 0x10, 0x22, 0x11, 
0x80, 0x01, 0x92, 0x2e, 0x00, 0x1e, 0x22 // sp + 16 + 128 * VG
+; CHECK-NEXT:str xzr, [sp]
+; CHECK-NEXT:addvl sp, sp, #16
+; CHECK-NEXT:.cfi_def_cfa wsp, 16
+; CHECK-NEXT:ldr x29, [sp], #16 // 8-byte Folded Reload
+; CHECK-NEXT:.cfi_def_cfa_offset 0
+; CHECK-NEXT:.cfi_restore w29
+; CHECK-NEXT:ret
+entry:
+  %vec1 = alloca , align 16
+  %vec2 = alloca , align 16
+  %vec3 = alloca , align 16
+  %vec4 = alloca , align 16
+  %vec5 = alloca , align 16
+  %vec6 = alloca , align 16
+  %vec7 = alloca , align 16
+  %vec8 = alloca , align 16
+  %vec9 = alloca , align 16
+  %vec10 = alloca , align 16
+  %vec11 = alloca , align 16
+  %vec12 = alloca , align 16
+  %vec13 = alloca , align 16
+  %vec14 = alloca , align 16
+  %vec15 = alloca , align 16
+  %vec16 = alloca , align 16
+  ret void
+}
+
+; As above, but with 17 SVE vectors of stack space. Now we need
+; a probing loops since stack adjustment may be greater than
+; the probe size (17 x 256 = 4354 bytes)

momchil-velikov wrote:

Done

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


[clang] [llvm] [AArch64] Stack probing for dynamic allocas in SelectionDAG (PR #66525)

2023-11-23 Thread Momchil Velikov via cfe-commits


@@ -9461,6 +9462,94 @@ bool AArch64InstrInfo::isReallyTriviallyReMaterializable(
   return TargetInstrInfo::isReallyTriviallyReMaterializable(MI);
 }
 
+MachineBasicBlock::iterator
+AArch64InstrInfo::probedStackAlloc(MachineBasicBlock::iterator MBBI,

momchil-velikov wrote:

I've left a comment at the declaration in `AArch64InstrInfo.h`

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


[libunwind] [libunwind][WebAssembly] Don't build libunwind.cpp (PR #73196)

2023-11-23 Thread Louis Dionne via cfe-commits

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


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


[llvm] [clang] [AArch64] Stack probing for dynamic allocas in SelectionDAG (PR #66525)

2023-11-23 Thread Momchil Velikov via cfe-commits


@@ -861,6 +861,12 @@ def AArch64stilp : SDNode<"AArch64ISD::STILP", 
SDT_AArch64stilp, [SDNPHasChain,
 def AArch64stnp : SDNode<"AArch64ISD::STNP", SDT_AArch64stnp, [SDNPHasChain, 
SDNPMayStore, SDNPMemOperand]>;
 
 def AArch64tbl : SDNode<"AArch64ISD::TBL", SDT_AArch64TBL>;
+
+def AArch64probedalloca
+: SDNode<"AArch64ISD::PROBED_ALLOCA",
+ SDTypeProfile<0, 1, [SDTCisPtrTy<0>]>,
+ [SDNPHasChain]>;

momchil-velikov wrote:

Done

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


[llvm] [clang] [AArch64] Stack probing for dynamic allocas in SelectionDAG (PR #66525)

2023-11-23 Thread Momchil Velikov via cfe-commits


@@ -0,0 +1,363 @@
+; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
+; RUN: llc -mtriple aarch64-none-eabi < %s -verify-machineinstrs | FileCheck %s
+
+; Dynamically-sized allocation, needs a loop which can handle any size at
+; runtime. The final iteration of the loop will temporarily put SP below the
+; target address, but this doesn't break any of the ABI constraints on the
+; stack, and also doesn't probe below the target SP value.
+define void @dynamic(i64 %size, ptr %out) #0 {
+; CHECK-LABEL: dynamic:
+; CHECK:   // %bb.0:
+; CHECK-NEXT:stp x29, x30, [sp, #-16]! // 16-byte Folded Spill
+; CHECK-NEXT:.cfi_def_cfa_offset 16
+; CHECK-NEXT:mov x29, sp
+; CHECK-NEXT:.cfi_def_cfa w29, 16
+; CHECK-NEXT:.cfi_offset w30, -8
+; CHECK-NEXT:.cfi_offset w29, -16
+; CHECK-NEXT:add x9, x0, #15
+; CHECK-NEXT:mov x8, sp
+; CHECK-NEXT:and x9, x9, #0xfff0
+; CHECK-NEXT:sub x8, x8, x9
+; CHECK-NEXT:  .LBB0_1: // =>This Inner Loop Header: Depth=1
+; CHECK-NEXT:sub sp, sp, #1, lsl #12 // =4096
+; CHECK-NEXT:cmp sp, x8
+; CHECK-NEXT:b.le .LBB0_3
+; CHECK-NEXT:  // %bb.2: // in Loop: Header=BB0_1 Depth=1
+; CHECK-NEXT:str xzr, [sp]
+; CHECK-NEXT:b .LBB0_1
+; CHECK-NEXT:  .LBB0_3:
+; CHECK-NEXT:mov sp, x8
+; CHECK-NEXT:str xzr, [sp]
+; CHECK-NEXT:str x8, [x1]
+; CHECK-NEXT:mov sp, x29
+; CHECK-NEXT:.cfi_def_cfa wsp, 16
+; CHECK-NEXT:ldp x29, x30, [sp], #16 // 16-byte Folded Reload
+; CHECK-NEXT:.cfi_def_cfa_offset 0
+; CHECK-NEXT:.cfi_restore w30
+; CHECK-NEXT:.cfi_restore w29
+; CHECK-NEXT:ret
+  %v = alloca i8, i64 %size, align 1
+  store ptr %v, ptr %out, align 8
+  ret void
+}
+
+; This function has a fixed-size stack slot and a dynamic one. The fixed size
+; slot isn't large enough that we would normally probe it, but we need to do so
+; here otherwise the gap between the CSR save and the first probe of the
+; dynamic allocation could be too far apart when the size of the dynamic
+; allocation is close to the guard size.
+define void @dynamic_fixed(i64 %size, ptr %out1, ptr %out2) #0 {
+; CHECK-LABEL: dynamic_fixed:
+; CHECK:   // %bb.0:
+; CHECK-NEXT:stp x29, x30, [sp, #-16]! // 16-byte Folded Spill
+; CHECK-NEXT:.cfi_def_cfa_offset 16
+; CHECK-NEXT:mov x29, sp
+; CHECK-NEXT:.cfi_def_cfa w29, 16
+; CHECK-NEXT:.cfi_offset w30, -8
+; CHECK-NEXT:.cfi_offset w29, -16
+; CHECK-NEXT:str xzr, [sp, #-64]!
+; CHECK-NEXT:add x9, x0, #15
+; CHECK-NEXT:mov x8, sp
+; CHECK-NEXT:sub x10, x29, #64
+; CHECK-NEXT:and x9, x9, #0xfff0
+; CHECK-NEXT:str x10, [x1]
+; CHECK-NEXT:sub x8, x8, x9
+; CHECK-NEXT:  .LBB1_1: // =>This Inner Loop Header: Depth=1
+; CHECK-NEXT:sub sp, sp, #1, lsl #12 // =4096
+; CHECK-NEXT:cmp sp, x8
+; CHECK-NEXT:b.le .LBB1_3
+; CHECK-NEXT:  // %bb.2: // in Loop: Header=BB1_1 Depth=1
+; CHECK-NEXT:str xzr, [sp]
+; CHECK-NEXT:b .LBB1_1
+; CHECK-NEXT:  .LBB1_3:
+; CHECK-NEXT:mov sp, x8
+; CHECK-NEXT:str xzr, [sp]
+; CHECK-NEXT:str x8, [x2]
+; CHECK-NEXT:mov sp, x29
+; CHECK-NEXT:.cfi_def_cfa wsp, 16
+; CHECK-NEXT:ldp x29, x30, [sp], #16 // 16-byte Folded Reload
+; CHECK-NEXT:.cfi_def_cfa_offset 0
+; CHECK-NEXT:.cfi_restore w30
+; CHECK-NEXT:.cfi_restore w29
+; CHECK-NEXT:ret
+  %v1 = alloca i8, i64 64, align 1
+  store ptr %v1, ptr %out1, align 8
+  %v2 = alloca i8, i64 %size, align 1
+  store ptr %v2, ptr %out2, align 8
+  ret void
+}
+
+; Dynamic allocation, with an alignment requirement greater than the alignment
+; of SP. Done by ANDing the target SP with a constant to align it down, then
+; doing the loop as normal. Note that we also re-align the stack in the prolog,
+; which isn't actually needed because the only aligned allocations are dynamic,
+; this is done even without stack probing.
+define void @dynamic_align_64(i64 %size, ptr %out) #0 {
+; CHECK-LABEL: dynamic_align_64:
+; CHECK:   // %bb.0:
+; CHECK-NEXT:stp x29, x30, [sp, #-32]! // 16-byte Folded Spill
+; CHECK-NEXT:.cfi_def_cfa_offset 32
+; CHECK-NEXT:str x19, [sp, #16] // 8-byte Folded Spill
+; CHECK-NEXT:mov x29, sp
+; CHECK-NEXT:.cfi_def_cfa w29, 32
+; CHECK-NEXT:.cfi_offset w19, -16
+; CHECK-NEXT:.cfi_offset w30, -24
+; CHECK-NEXT:.cfi_offset w29, -32
+; CHECK-NEXT:sub x9, sp, #32
+; CHECK-NEXT:and sp, x9, #0xffc0
+; CHECK-NEXT:add x9, x0, #15
+; CHECK-NEXT:mov x8, sp
+; CHECK-NEXT:str xzr, [sp]
+; CHECK-NEXT:and x9, x9, #0xfff0
+; CHECK-NEXT:mov x19, sp
+; CHECK-NEXT:sub x8, x8, x9
+; CHECK-NEXT:and x8, x8, #0xffc0
+; CHECK-NEXT:  .LBB2_1: // =>This Inner Loop Header: Depth=1
+; CHECK-NEXT:sub sp, sp, #1, lsl #12 // =4096
+; CHECK-NEXT:cmp sp, x8
+; CHECK-NEXT:b.le .LBB2_3
+; CHECK-NEXT:  // %bb.2: // in Loop: Header=BB2_1 Depth=1
+; CHECK-NE

[clang] [clang][analyzer] Support `fgetc` in StreamChecker (PR #72627)

2023-11-23 Thread Balázs Kéri via cfe-commits

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


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


[lldb] [clang-tools-extra] [compiler-rt] [flang] [libcxx] [libc] [llvm] [clang] [flang] FDATE extension implementation: get date and time in ctime format (PR #71222)

2023-11-23 Thread Yi Wu via cfe-commits

https://github.com/yi-wu-arm updated 
https://github.com/llvm/llvm-project/pull/71222

>From e0d99fb5baa4231ab351f7fd5abf0a1ffe589547 Mon Sep 17 00:00:00 2001
From: Yi Wu 
Date: Mon, 6 Nov 2023 19:55:06 +
Subject: [PATCH 1/8] FDATE extension implementation: get date and time in
 ctime format

reference to gfortran fdate https://gcc.gnu.org/onlinedocs/gfortran/FDATE.html
usage:
CHARACTER(32) :: time
CALL fdate(time)
WRITE(*,*) time
---
 flang/docs/Intrinsics.md |  2 +-
 flang/include/flang/Runtime/command.h|  5 +
 flang/include/flang/Runtime/extensions.h |  2 ++
 flang/runtime/command.cpp| 28 
 flang/runtime/extensions.cpp |  5 +
 flang/unittests/Runtime/CommandTest.cpp  | 14 
 6 files changed, 55 insertions(+), 1 deletion(-)

diff --git a/flang/docs/Intrinsics.md b/flang/docs/Intrinsics.md
index ab0a940e53e5538..982be8208164296 100644
--- a/flang/docs/Intrinsics.md
+++ b/flang/docs/Intrinsics.md
@@ -751,7 +751,7 @@ This phase currently supports all the intrinsic procedures 
listed above but the
 | Object characteristic inquiry functions | ALLOCATED, ASSOCIATED, 
EXTENDS_TYPE_OF, IS_CONTIGUOUS, PRESENT, RANK, SAME_TYPE, STORAGE_SIZE |
 | Type inquiry intrinsic functions | BIT_SIZE, DIGITS, EPSILON, HUGE, KIND, 
MAXEXPONENT, MINEXPONENT, NEW_LINE, PRECISION, RADIX, RANGE, TINY|
 | Non-standard intrinsic functions | AND, OR, XOR, SHIFT, ZEXT, IZEXT, COSD, 
SIND, TAND, ACOSD, ASIND, ATAND, ATAN2D, COMPL, EQV, NEQV, INT8, JINT, JNINT, 
KNINT, QCMPLX, DREAL, DFLOAT, QEXT, QFLOAT, QREAL, DNUM, NUM, JNUM, KNUM, QNUM, 
RNUM, RAN, RANF, ILEN, SIZEOF, MCLOCK, SECNDS, COTAN, IBCHNG, ISHA, ISHC, ISHL, 
IXOR, IARG, IARGC, NARGS, NUMARG, BADDRESS, IADDR, CACHESIZE, EOF, FP_CLASS, 
INT_PTR_KIND, ISNAN, MALLOC |
-| Intrinsic subroutines |MVBITS (elemental), CPU_TIME, DATE_AND_TIME, 
EVENT_QUERY, EXECUTE_COMMAND_LINE, GET_COMMAND, GET_COMMAND_ARGUMENT, 
GET_ENVIRONMENT_VARIABLE, MOVE_ALLOC, RANDOM_INIT, RANDOM_NUMBER, RANDOM_SEED, 
SYSTEM_CLOCK |
+| Intrinsic subroutines |MVBITS (elemental), CPU_TIME, DATE_AND_TIME, 
EVENT_QUERY, EXECUTE_COMMAND_LINE, FDATE, GET_COMMAND, GET_COMMAND_ARGUMENT, 
GET_ENVIRONMENT_VARIABLE, MOVE_ALLOC, RANDOM_INIT, RANDOM_NUMBER, RANDOM_SEED, 
SYSTEM_CLOCK |
 | Atomic intrinsic subroutines | ATOMIC_ADD |
 | Collective intrinsic subroutines | CO_REDUCE |
 
diff --git a/flang/include/flang/Runtime/command.h 
b/flang/include/flang/Runtime/command.h
index ec6289390545479..07f6d8e169ead6c 100644
--- a/flang/include/flang/Runtime/command.h
+++ b/flang/include/flang/Runtime/command.h
@@ -23,6 +23,11 @@ extern "C" {
 // integer kind.
 std::int32_t RTNAME(ArgumentCount)();
 
+// Try to get the the current date (same format as CTIME: convert to a string)
+// Return a STATUS as described in the standard.
+std::int32_t RTNAME(FDate)(
+const Descriptor *argument = nullptr, const Descriptor *errmsg = nullptr);
+
 // 16.9.82 GET_COMMAND
 // Try to get the value of the whole command. All of the parameters are
 // optional.
diff --git a/flang/include/flang/Runtime/extensions.h 
b/flang/include/flang/Runtime/extensions.h
index ad592814e5acb79..92b9907860121aa 100644
--- a/flang/include/flang/Runtime/extensions.h
+++ b/flang/include/flang/Runtime/extensions.h
@@ -24,6 +24,8 @@ void FORTRAN_PROCEDURE_NAME(flush)(const int &unit);
 // GNU Fortran 77 compatibility function IARGC.
 std::int32_t FORTRAN_PROCEDURE_NAME(iargc)();
 
+void FORTRAN_PROCEDURE_NAME(fdate)(std::int8_t *string, std::int64_t length);
+
 // GNU Fortran 77 compatibility subroutine GETARG(N, ARG).
 void FORTRAN_PROCEDURE_NAME(getarg)(
 std::int32_t &n, std::int8_t *arg, std::int64_t length);
diff --git a/flang/runtime/command.cpp b/flang/runtime/command.cpp
index b81a0791c5e571b..da0803c39f49b6d 100644
--- a/flang/runtime/command.cpp
+++ b/flang/runtime/command.cpp
@@ -14,6 +14,7 @@
 #include "flang/Runtime/descriptor.h"
 #include 
 #include 
+#include 
 
 namespace Fortran::runtime {
 std::int32_t RTNAME(ArgumentCount)() {
@@ -125,6 +126,33 @@ static bool FitsInDescriptor(
   kind, terminator, value);
 }
 
+void removeNewLine(char *str) {
+  char *newlinePos = strchr(str, '\n');
+  if (newlinePos != NULL) {
+*newlinePos = '\0'; // Replace with null terminator
+  }
+}
+
+std::int32_t RTNAME(FDate)(const Descriptor *value, const Descriptor *errmsg) {
+  FillWithSpaces(*value);
+
+  time_t current_time;
+  time(¤t_time);
+
+  char *time_string = ctime(¤t_time);
+  removeNewLine(time_string);
+  std::int64_t stringLen{StringLength(time_string)};
+  if (stringLen <= 0) {
+return ToErrmsg(errmsg, StatMissingArgument);
+  }
+
+  if (value) {
+return CopyToDescriptor(*value, time_string, stringLen, errmsg);
+  }
+
+  return StatOk;
+}
+
 std::int32_t RTNAME(GetCommandArgument)(std::int32_t n, const Descriptor 
*value,
 const Descriptor *length, const Descriptor *errmsg, const char *sourceFile,
 int line) {
diff --git a/flang/run

[clang] [clang][AArch64] Pass down stack clash protection options to LLVM/Backend (PR #68993)

2023-11-23 Thread Momchil Velikov via cfe-commits


@@ -1076,6 +1076,16 @@ void CodeGenModule::Release() {
 "sign-return-address-with-bkey", 1);
   }
 
+  if (Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_be) {

momchil-velikov wrote:

Done, we now emit both

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


  1   2   3   >