[clang] [Clang] CGCoroutine: Skip moving parameters if the allocation decision is false (PR #81195)

2024-02-10 Thread Chuanqi Xu via cfe-commits

ChuanqiXu9 wrote:

yes if I remember correctly. I am away from the computer so I can't find the 
wording. 

But I don't think this is related to how the frame gets allocated. 

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


[clang] [clang-format] Add BreakAfterReturnType option to deprecate AlwaysBreakAfterReturnType. (PR #80827)

2024-02-10 Thread via cfe-commits

https://github.com/rmarker updated 
https://github.com/llvm/llvm-project/pull/80827

>From 3c3e167711dccfcc0a56c5b465b20c17854451a4 Mon Sep 17 00:00:00 2001
From: rmarker 
Date: Tue, 6 Feb 2024 21:53:20 +1030
Subject: [PATCH] [clang-format] Rename option AlwaysBreakAfterReturnType.

---
 clang/docs/ClangFormatStyleOptions.rst | 221 +++--
 clang/docs/ReleaseNotes.rst|   2 +
 clang/include/clang/Format/Format.h|   7 +-
 clang/lib/Format/Format.cpp|   5 +-
 clang/unittests/Format/ConfigParseTest.cpp |  17 ++
 5 files changed, 141 insertions(+), 111 deletions(-)

diff --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 5deeff0db239a8..fdf7bfaeaa4ec7 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -1531,114 +1531,8 @@ the configuration (without a prefix: ``Auto``).
 
 .. _AlwaysBreakAfterReturnType:
 
-**AlwaysBreakAfterReturnType** (``ReturnTypeBreakingStyle``) 
:versionbadge:`clang-format 3.8` :ref:`¶ `
-  The function declaration return type breaking style to use.
-
-  Possible values:
-
-  * ``RTBS_None`` (in configuration: ``None``)
-This is **deprecated**. See ``Automatic`` below.
-
-  * ``RTBS_Automatic`` (in configuration: ``Automatic``)
-Break after return type based on ``PenaltyReturnTypeOnItsOwnLine``.
-
-.. code-block:: c++
-
-  class A {
-int f() { return 0; };
-  };
-  int f();
-  int f() { return 1; }
-  int
-  LongName::AnotherLongName();
-
-  * ``RTBS_ExceptShortType`` (in configuration: ``ExceptShortType``)
-Same as ``Automatic`` above, except that there is no break after short
-return types.
-
-.. code-block:: c++
-
-  class A {
-int f() { return 0; };
-  };
-  int f();
-  int f() { return 1; }
-  int LongName::
-  AnotherLongName();
-
-  * ``RTBS_All`` (in configuration: ``All``)
-Always break after the return type.
-
-.. code-block:: c++
-
-  class A {
-int
-f() {
-  return 0;
-};
-  };
-  int
-  f();
-  int
-  f() {
-return 1;
-  }
-  int
-  LongName::AnotherLongName();
-
-  * ``RTBS_TopLevel`` (in configuration: ``TopLevel``)
-Always break after the return types of top-level functions.
-
-.. code-block:: c++
-
-  class A {
-int f() { return 0; };
-  };
-  int
-  f();
-  int
-  f() {
-return 1;
-  }
-  int
-  LongName::AnotherLongName();
-
-  * ``RTBS_AllDefinitions`` (in configuration: ``AllDefinitions``)
-Always break after the return type of function definitions.
-
-.. code-block:: c++
-
-  class A {
-int
-f() {
-  return 0;
-};
-  };
-  int f();
-  int
-  f() {
-return 1;
-  }
-  int
-  LongName::AnotherLongName();
-
-  * ``RTBS_TopLevelDefinitions`` (in configuration: ``TopLevelDefinitions``)
-Always break after the return type of top-level definitions.
-
-.. code-block:: c++
-
-  class A {
-int f() { return 0; };
-  };
-  int f();
-  int
-  f() {
-return 1;
-  }
-  int
-  LongName::AnotherLongName();
-
-
+**AlwaysBreakAfterReturnType** (``deprecated``) :versionbadge:`clang-format 
3.8` :ref:`¶ `
+  This option is renamed to ``BreakAfterReturnType``.
 
 .. _AlwaysBreakBeforeMultilineStrings:
 
@@ -2219,6 +2113,117 @@ the configuration (without a prefix: ``Auto``).
  @Mock
  DataLoad loader;
 
+.. _BreakAfterReturnType:
+
+**BreakAfterReturnType** (``ReturnTypeBreakingStyle``) 
:versionbadge:`clang-format 19` :ref:`¶ `
+  The function declaration return type breaking style to use.
+
+  Possible values:
+
+  * ``RTBS_None`` (in configuration: ``None``)
+This is **deprecated**. See ``Automatic`` below.
+
+  * ``RTBS_Automatic`` (in configuration: ``Automatic``)
+Break after return type based on ``PenaltyReturnTypeOnItsOwnLine``.
+
+.. code-block:: c++
+
+  class A {
+int f() { return 0; };
+  };
+  int f();
+  int f() { return 1; }
+  int
+  LongName::AnotherLongName();
+
+  * ``RTBS_ExceptShortType`` (in configuration: ``ExceptShortType``)
+Same as ``Automatic`` above, except that there is no break after short
+return types.
+
+.. code-block:: c++
+
+  class A {
+int f() { return 0; };
+  };
+  int f();
+  int f() { return 1; }
+  int LongName::
+  AnotherLongName();
+
+  * ``RTBS_All`` (in configuration: ``All``)
+Always break after the return type.
+
+.. code-block:: c++
+
+  class A {
+int
+f() {
+  return 0;
+};
+  };
+  int
+  f();
+  int
+  f() {
+return 1;
+  }
+  int
+  LongName::AnotherLongName();
+
+  * ``RTBS_TopLevel`` (in configuration: ``TopLevel``)
+Always break after t

[clang] [clang-format] Rename option AlwaysBreakAfterReturnType. (PR #80827)

2024-02-10 Thread via cfe-commits

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


[clang] [clang-format] Rename option AlwaysBreakAfterReturnType. (PR #80827)

2024-02-10 Thread via cfe-commits

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


[clang] [clang-format] Rename option AlwaysBreakAfterReturnType. (PR #80827)

2024-02-10 Thread via cfe-commits

rmarker wrote:

Right. I've updated the PR, following the pattern of #81093.

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


[clang] [clang-format] Rename option AlwaysBreakAfterReturnType. (PR #80827)

2024-02-10 Thread Owen Pan via cfe-commits

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


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


[clang] [clang] Fix crash when inheriting from a cv-qualified type (PR #70594)

2024-02-10 Thread Rajveer Singh Bharadwaj via cfe-commits

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


[clang] [llvm] [SPARC] Support reserving arbitrary general purpose registers (PR #74927)

2024-02-10 Thread via cfe-commits

https://github.com/koachan updated 
https://github.com/llvm/llvm-project/pull/74927

>From fd0bae41e2c3ed791a6a73affc9e1709e21ff880 Mon Sep 17 00:00:00 2001
From: Koakuma 
Date: Wed, 29 Nov 2023 08:08:29 +0700
Subject: [PATCH 1/7] [SPARC] Support reserving arbitrary general purpose
 registers

This adds support for marking arbitrary general purpose registers - except
for those with special purpose (G0, I6-I7, O6-O7) - as reserved, as needed
by some software like the Linux kernel.
---
 clang/include/clang/Driver/Options.td|  12 ++
 clang/lib/Driver/ToolChains/Arch/Sparc.cpp   |  81 +
 clang/test/Driver/sparc-fixed-register.c | 181 +++
 llvm/lib/Target/Sparc/Sparc.td   |  14 ++
 llvm/lib/Target/Sparc/SparcISelLowering.cpp  |  23 +++
 llvm/lib/Target/Sparc/SparcRegisterInfo.cpp  |  45 -
 llvm/lib/Target/Sparc/SparcRegisterInfo.h|   3 +
 llvm/lib/Target/Sparc/SparcRegisterInfo.td   |   4 +
 llvm/lib/Target/Sparc/SparcSubtarget.cpp |   4 +
 llvm/lib/Target/Sparc/SparcSubtarget.h   |  11 ++
 llvm/test/CodeGen/SPARC/reserved-arg-regs.ll |  25 +++
 llvm/test/CodeGen/SPARC/reserved-regs.ll |  17 ++
 12 files changed, 419 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/Driver/sparc-fixed-register.c
 create mode 100644 llvm/test/CodeGen/SPARC/reserved-arg-regs.ll

diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index f1687d823f6e0a..1bc21f24145688 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -5794,6 +5794,18 @@ def mvis3 : Flag<["-"], "mvis3">, 
Group;
 def mno_vis3 : Flag<["-"], "mno-vis3">, Group;
 def mhard_quad_float : Flag<["-"], "mhard-quad-float">, 
Group;
 def msoft_quad_float : Flag<["-"], "msoft-quad-float">, 
Group;
+foreach i = {1-7} in
+  def ffixed_g#i : Flag<["-"], "ffixed-g"#i>, Group,
+HelpText<"Reserve the G"#i#" register (SPARC only)">;
+foreach i = {0-5} in
+  def ffixed_o#i : Flag<["-"], "ffixed-o"#i>, Group,
+HelpText<"Reserve the O"#i#" register (SPARC only)">;
+foreach i = {0-7} in
+  def ffixed_l#i : Flag<["-"], "ffixed-l"#i>, Group,
+HelpText<"Reserve the L"#i#" register (SPARC only)">;
+foreach i = {0-5} in
+  def ffixed_i#i : Flag<["-"], "ffixed-i"#i>, Group,
+HelpText<"Reserve the I"#i#" register (SPARC only)">;
 } // let Flags = [TargetSpecific]
 
 // M68k features flags
diff --git a/clang/lib/Driver/ToolChains/Arch/Sparc.cpp 
b/clang/lib/Driver/ToolChains/Arch/Sparc.cpp
index 22e583021515e5..ae1a4ba7882627 100644
--- a/clang/lib/Driver/ToolChains/Arch/Sparc.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/Sparc.cpp
@@ -178,4 +178,85 @@ void sparc::getSparcTargetFeatures(const Driver &D, const 
ArgList &Args,
 else
   Features.push_back("-hard-quad-float");
   }
+
+  if (Args.hasArg(options::OPT_ffixed_g1))
+Features.push_back("+reserve-g1");
+
+  if (Args.hasArg(options::OPT_ffixed_g2))
+Features.push_back("+reserve-g2");
+
+  if (Args.hasArg(options::OPT_ffixed_g3))
+Features.push_back("+reserve-g3");
+
+  if (Args.hasArg(options::OPT_ffixed_g4))
+Features.push_back("+reserve-g4");
+
+  if (Args.hasArg(options::OPT_ffixed_g5))
+Features.push_back("+reserve-g5");
+
+  if (Args.hasArg(options::OPT_ffixed_g6))
+Features.push_back("+reserve-g6");
+
+  if (Args.hasArg(options::OPT_ffixed_g7))
+Features.push_back("+reserve-g7");
+
+  if (Args.hasArg(options::OPT_ffixed_o0))
+Features.push_back("+reserve-o0");
+
+  if (Args.hasArg(options::OPT_ffixed_o1))
+Features.push_back("+reserve-o1");
+
+  if (Args.hasArg(options::OPT_ffixed_o2))
+Features.push_back("+reserve-o2");
+
+  if (Args.hasArg(options::OPT_ffixed_o3))
+Features.push_back("+reserve-o3");
+
+  if (Args.hasArg(options::OPT_ffixed_o4))
+Features.push_back("+reserve-o4");
+
+  if (Args.hasArg(options::OPT_ffixed_o5))
+Features.push_back("+reserve-o5");
+
+  if (Args.hasArg(options::OPT_ffixed_l0))
+Features.push_back("+reserve-l0");
+
+  if (Args.hasArg(options::OPT_ffixed_l1))
+Features.push_back("+reserve-l1");
+
+  if (Args.hasArg(options::OPT_ffixed_l2))
+Features.push_back("+reserve-l2");
+
+  if (Args.hasArg(options::OPT_ffixed_l3))
+Features.push_back("+reserve-l3");
+
+  if (Args.hasArg(options::OPT_ffixed_l4))
+Features.push_back("+reserve-l4");
+
+  if (Args.hasArg(options::OPT_ffixed_l5))
+Features.push_back("+reserve-l5");
+
+  if (Args.hasArg(options::OPT_ffixed_l6))
+Features.push_back("+reserve-l6");
+
+  if (Args.hasArg(options::OPT_ffixed_l7))
+Features.push_back("+reserve-l7");
+
+  if (Args.hasArg(options::OPT_ffixed_i0))
+Features.push_back("+reserve-i0");
+
+  if (Args.hasArg(options::OPT_ffixed_i1))
+Features.push_back("+reserve-i1");
+
+  if (Args.hasArg(options::OPT_ffixed_i2))
+Features.push_back("+reserve-i2");
+
+  if (Args.hasArg(options::OPT_ffixed_i3))
+Features.push_back("+reserve-i3");
+
+  if (Args.hasArg(opti

[clang] [llvm] [LLVM] Add `__builtin_readfixedtimer` intrinsic and buiiltin for realtime clocks (PR #81331)

2024-02-10 Thread Joseph Huber via cfe-commits

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


[clang] [llvm] [LLVM] Add `__builtin_readfixedtimer` intrinsic and buiiltin for realtime clocks (PR #81331)

2024-02-10 Thread Joseph Huber via cfe-commits


@@ -312,6 +312,12 @@ void IntrinsicLowering::LowerIntrinsicCall(CallInst *CI) {
 CI->replaceAllUsesWith(ConstantInt::get(Type::getInt64Ty(Context), 0));
 break;
   }
+  case Intrinsic::readfixedtimer: {
+errs() << "WARNING: this target does not support the llvm.readfixedtimer"

jhuber6 wrote:

Not that I could tell, but I figured better safe than sorry.

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


[clang] [llvm] [LLVM] Add `__builtin_readfixedtimer` intrinsic and buiiltin for realtime clocks (PR #81331)

2024-02-10 Thread Joseph Huber via cfe-commits

https://github.com/jhuber6 updated 
https://github.com/llvm/llvm-project/pull/81331

>From 164d9775046d273fa45e9934cea1db07fdd2ca79 Mon Sep 17 00:00:00 2001
From: Joseph Huber 
Date: Fri, 9 Feb 2024 16:13:42 -0600
Subject: [PATCH] [WIP][LLVM] Add `__builtin_readsteadycounter` intrinsic and
 buiiltin

Summary:
This patch adds a new intrinsic and builtin function mirroring the
existing `__builtin_readcyclecounter`. The difference is that this
implementation targets a separate counter that some targets have which
returns a fixed frequency clock that can be used to determine elapsed
time, this is different compared to the cycle counter which often has
variable frequency. This is currently only valid for the NVPTX and
AMDGPU targets.
---
 clang/docs/LanguageExtensions.rst | 31 +++
 clang/include/clang/Basic/Builtins.td |  6 
 clang/lib/CodeGen/CGBuiltin.cpp   |  4 +++
 clang/test/CodeGen/builtins.c |  6 
 llvm/include/llvm/CodeGen/ISDOpcodes.h|  6 
 llvm/include/llvm/IR/Intrinsics.td|  2 ++
 llvm/include/llvm/Support/TargetOpcodes.def   |  3 ++
 llvm/include/llvm/Target/GenericOpcodes.td|  6 
 .../Target/GlobalISel/SelectionDAGCompat.td   |  1 +
 .../include/llvm/Target/TargetSelectionDAG.td |  3 ++
 llvm/lib/CodeGen/GlobalISel/IRTranslator.cpp  |  2 ++
 llvm/lib/CodeGen/IntrinsicLowering.cpp|  6 
 llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp |  6 ++--
 .../SelectionDAG/LegalizeIntegerTypes.cpp |  7 +++--
 llvm/lib/CodeGen/SelectionDAG/LegalizeTypes.h |  2 +-
 .../SelectionDAG/SelectionDAGBuilder.cpp  |  8 +
 .../SelectionDAG/SelectionDAGDumper.cpp   |  1 +
 llvm/lib/CodeGen/TargetLoweringBase.cpp   |  3 ++
 .../lib/Target/AMDGPU/AMDGPULegalizerInfo.cpp |  2 ++
 .../Target/AMDGPU/AMDGPURegisterBankInfo.cpp  |  1 +
 llvm/lib/Target/AMDGPU/SIISelLowering.cpp |  4 +++
 llvm/lib/Target/AMDGPU/SMInstructions.td  | 14 +
 llvm/lib/Target/NVPTX/NVPTXISelLowering.cpp   |  3 ++
 llvm/lib/Target/NVPTX/NVPTXInstrInfo.td   |  1 -
 llvm/lib/Target/NVPTX/NVPTXIntrinsics.td  |  4 +++
 llvm/test/CodeGen/AMDGPU/readsteadycounter.ll | 24 ++
 llvm/test/CodeGen/NVPTX/intrinsics.ll | 12 +++
 27 files changed, 161 insertions(+), 7 deletions(-)
 create mode 100644 llvm/test/CodeGen/AMDGPU/readsteadycounter.ll

diff --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index e91156837290f7..868c0d126d34a6 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -2764,6 +2764,37 @@ Query for this feature with 
``__has_builtin(__builtin_readcyclecounter)``. Note
 that even if present, its use may depend on run-time privilege or other OS
 controlled state.
 
+``__builtin_readsteadycounter``
+--
+
+``__builtin_readsteadycounter`` is used to access the fixed frequency counter 
+register (or a similar steady-rate clock) on those targets that support it.
+The function is similar to ``__builtin_readcyclecounter`` above except that 
the 
+frequency is fixed, making it suitable for measuring elapsed time.
+
+**Syntax**:
+
+.. code-block:: c++
+
+  __builtin_readsteadycounter()
+
+**Example of Use**:
+
+.. code-block:: c++
+
+  unsigned long long t0 = __builtin_readsteadycounter();
+  do_something();
+  unsigned long long t1 = __builtin_readsteadycounter();
+  unsigned long long secs_to_do_something = (t1 - t0) / tick_rate;
+
+**Description**:
+
+The ``__builtin_readsteadycounter()`` builtin returns the frequency counter 
value.
+When not supported by the target, the return value is always zero. This 
builtin 
+takes no arguments and produces an unsigned long long result.
+
+Query for this feature with ``__has_builtin(__builtin_readsteadycounter)``.
+
 ``__builtin_dump_struct``
 -
 
diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index 31a2bdeb2d3e5e..193d5851f9f29f 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -1110,6 +1110,12 @@ def ReadCycleCounter : Builtin {
   let Prototype = "unsigned long long int()";
 }
 
+def ReadSteadyCounter : Builtin {
+  let Spellings = ["__builtin_readsteadycounter"];
+  let Attributes = [NoThrow];
+  let Prototype = "unsigned long long int()";
+}
+
 def Trap : Builtin {
   let Spellings = ["__builtin_trap"];
   let Attributes = [NoThrow, NoReturn];
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index a7a410dab1a018..ee0b7504769622 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -3443,6 +3443,10 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
 Function *F = CGM.getIntrinsic(Intrinsic::readcyclecounter);
 return RValue::get(Builder.CreateCall(F));
   }
+  case Builtin::BI__builtin_readsteadycounter: {
+Function *F 

[clang] [llvm] [LLVM] Add `__builtin_readsteadycounter` intrinsic and buiiltin for realtime clocks (PR #81331)

2024-02-10 Thread Joseph Huber via cfe-commits

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


[clang] [llvm] [LLVM] Add `__builtin_readsteadycounter` intrinsic and buiiltin for realtime clocks (PR #81331)

2024-02-10 Thread Joseph Huber via cfe-commits

jhuber6 wrote:

Added clang test and renamed to `readsteadycounter` as I think it's more 
descriptive and matches the existing `readcyclecounter` better.

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


[clang] [llvm] [LLVM] Add `__builtin_readsteadycounter` intrinsic and buiiltin for realtime clocks (PR #81331)

2024-02-10 Thread Joseph Huber via cfe-commits

https://github.com/jhuber6 updated 
https://github.com/llvm/llvm-project/pull/81331

>From 109939223e7944472363134d72a223524e1e3f0a Mon Sep 17 00:00:00 2001
From: Joseph Huber 
Date: Fri, 9 Feb 2024 16:13:42 -0600
Subject: [PATCH] [WIP][LLVM] Add `__builtin_readsteadycounter` intrinsic and
 buiiltin

Summary:
This patch adds a new intrinsic and builtin function mirroring the
existing `__builtin_readcyclecounter`. The difference is that this
implementation targets a separate counter that some targets have which
returns a fixed frequency clock that can be used to determine elapsed
time, this is different compared to the cycle counter which often has
variable frequency. This is currently only valid for the NVPTX and
AMDGPU targets.
---
 clang/docs/LanguageExtensions.rst | 31 +++
 clang/include/clang/Basic/Builtins.td |  6 
 clang/lib/CodeGen/CGBuiltin.cpp   |  4 +++
 clang/test/CodeGen/builtins.c |  6 
 llvm/include/llvm/CodeGen/ISDOpcodes.h|  6 
 llvm/include/llvm/IR/Intrinsics.td|  2 ++
 llvm/include/llvm/Support/TargetOpcodes.def   |  3 ++
 llvm/include/llvm/Target/GenericOpcodes.td|  6 
 .../Target/GlobalISel/SelectionDAGCompat.td   |  1 +
 .../include/llvm/Target/TargetSelectionDAG.td |  3 ++
 llvm/lib/CodeGen/GlobalISel/IRTranslator.cpp  |  2 ++
 llvm/lib/CodeGen/IntrinsicLowering.cpp|  6 
 llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp |  6 ++--
 .../SelectionDAG/LegalizeIntegerTypes.cpp |  7 +++--
 llvm/lib/CodeGen/SelectionDAG/LegalizeTypes.h |  2 +-
 .../SelectionDAG/SelectionDAGBuilder.cpp  |  8 +
 .../SelectionDAG/SelectionDAGDumper.cpp   |  1 +
 llvm/lib/CodeGen/TargetLoweringBase.cpp   |  3 ++
 .../lib/Target/AMDGPU/AMDGPULegalizerInfo.cpp |  2 ++
 .../Target/AMDGPU/AMDGPURegisterBankInfo.cpp  |  1 +
 llvm/lib/Target/AMDGPU/SIISelLowering.cpp |  4 +++
 llvm/lib/Target/AMDGPU/SMInstructions.td  | 14 +
 llvm/lib/Target/NVPTX/NVPTXISelLowering.cpp   |  3 ++
 llvm/lib/Target/NVPTX/NVPTXInstrInfo.td   |  1 -
 llvm/lib/Target/NVPTX/NVPTXIntrinsics.td  |  4 +++
 llvm/test/CodeGen/AMDGPU/readsteadycounter.ll | 24 ++
 llvm/test/CodeGen/NVPTX/intrinsics.ll | 12 +++
 27 files changed, 161 insertions(+), 7 deletions(-)
 create mode 100644 llvm/test/CodeGen/AMDGPU/readsteadycounter.ll

diff --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index e91156837290f7..4cc73599f9bae0 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -2764,6 +2764,37 @@ Query for this feature with 
``__has_builtin(__builtin_readcyclecounter)``. Note
 that even if present, its use may depend on run-time privilege or other OS
 controlled state.
 
+``__builtin_readsteadycounter``
+--
+
+``__builtin_readsteadycounter`` is used to access the fixed frequency counter
+register (or a similar steady-rate clock) on those targets that support it.
+The function is similar to ``__builtin_readcyclecounter`` above except that the
+frequency is fixed, making it suitable for measuring elapsed time.
+
+**Syntax**:
+
+.. code-block:: c++
+
+  __builtin_readsteadycounter()
+
+**Example of Use**:
+
+.. code-block:: c++
+
+  unsigned long long t0 = __builtin_readsteadycounter();
+  do_something();
+  unsigned long long t1 = __builtin_readsteadycounter();
+  unsigned long long secs_to_do_something = (t1 - t0) / tick_rate;
+
+**Description**:
+
+The ``__builtin_readsteadycounter()`` builtin returns the frequency counter 
value.
+When not supported by the target, the return value is always zero. This builtin
+takes no arguments and produces an unsigned long long result.
+
+Query for this feature with ``__has_builtin(__builtin_readsteadycounter)``.
+
 ``__builtin_dump_struct``
 -
 
diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index 31a2bdeb2d3e5e..193d5851f9f29f 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -1110,6 +1110,12 @@ def ReadCycleCounter : Builtin {
   let Prototype = "unsigned long long int()";
 }
 
+def ReadSteadyCounter : Builtin {
+  let Spellings = ["__builtin_readsteadycounter"];
+  let Attributes = [NoThrow];
+  let Prototype = "unsigned long long int()";
+}
+
 def Trap : Builtin {
   let Spellings = ["__builtin_trap"];
   let Attributes = [NoThrow, NoReturn];
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index a7a410dab1a018..ee0b7504769622 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -3443,6 +3443,10 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
 Function *F = CGM.getIntrinsic(Intrinsic::readcyclecounter);
 return RValue::get(Builder.CreateCall(F));
   }
+  case Builtin::BI__builtin_readsteadycounter: {
+Function *F = CGM

[clang] [llvm] [MC/DC] Refactor: Let MCDCConditionID int16_t with zero-origin (PR #81257)

2024-02-10 Thread NAKAMURA Takumi via cfe-commits

https://github.com/chapuni updated 
https://github.com/llvm/llvm-project/pull/81257

>From b2e8b3eaa067844a5fa5643aca17dbb0f237182e Mon Sep 17 00:00:00 2001
From: NAKAMURA Takumi 
Date: Sat, 10 Feb 2024 00:08:36 +0900
Subject: [PATCH 1/2] [MC/DC] Refactor: Let MCDCConditionID int16_t with
 zero-origin

Also, Let NumConditions uint16_t
---
 clang/lib/CodeGen/CodeGenPGO.cpp  |  8 ++---
 clang/lib/CodeGen/CodeGenPGO.h|  2 +-
 clang/lib/CodeGen/CoverageMappingGen.cpp  | 30 +--
 clang/lib/CodeGen/CoverageMappingGen.h|  4 +--
 .../ProfileData/Coverage/CoverageMapping.h| 10 +++
 .../ProfileData/Coverage/CoverageMapping.cpp  | 25 
 .../Coverage/CoverageMappingReader.cpp| 17 ++-
 .../Coverage/CoverageMappingWriter.cpp|  6 ++--
 .../ProfileData/CoverageMappingTest.cpp   | 18 +--
 9 files changed, 61 insertions(+), 59 deletions(-)

diff --git a/clang/lib/CodeGen/CodeGenPGO.cpp b/clang/lib/CodeGen/CodeGenPGO.cpp
index 5d7c3847745762..9025889f443b88 100644
--- a/clang/lib/CodeGen/CodeGenPGO.cpp
+++ b/clang/lib/CodeGen/CodeGenPGO.cpp
@@ -1033,7 +1033,7 @@ void CodeGenPGO::emitCounterRegionMapping(const Decl *D) {
 
   std::string CoverageMapping;
   llvm::raw_string_ostream OS(CoverageMapping);
-  RegionCondIDMap.reset(new llvm::DenseMap);
+  RegionCondIDMap.reset(new llvm::DenseMap);
   CoverageMappingGen MappingGen(
   *CGM.getCoverageMapping(), CGM.getContext().getSourceManager(),
   CGM.getLangOpts(), RegionCounterMap.get(), RegionMCDCBitmapMap.get(),
@@ -1198,8 +1198,8 @@ void CodeGenPGO::emitMCDCCondBitmapUpdate(CGBuilderTy 
&Builder, const Expr *S,
 return;
 
   // Extract the ID of the condition we are setting in the bitmap.
-  unsigned CondID = ExprMCDCConditionIDMapIterator->second;
-  assert(CondID > 0 && "Condition has no ID!");
+  auto CondID = ExprMCDCConditionIDMapIterator->second;
+  assert(CondID >= 0 && "Condition has no ID!");
 
   auto *I8PtrTy = llvm::PointerType::getUnqual(CGM.getLLVMContext());
 
@@ -1208,7 +1208,7 @@ void CodeGenPGO::emitMCDCCondBitmapUpdate(CGBuilderTy 
&Builder, const Expr *S,
   // the resulting value is used to update the boolean expression's bitmap.
   llvm::Value *Args[5] = {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
   Builder.getInt64(FunctionHash),
-  Builder.getInt32(CondID - 1),
+  Builder.getInt32(CondID),
   MCDCCondBitmapAddr.getPointer(), Val};
   Builder.CreateCall(
   CGM.getIntrinsic(llvm::Intrinsic::instrprof_mcdc_condbitmap_update),
diff --git a/clang/lib/CodeGen/CodeGenPGO.h b/clang/lib/CodeGen/CodeGenPGO.h
index 6596b6c3527764..5f2941cfb2e95e 100644
--- a/clang/lib/CodeGen/CodeGenPGO.h
+++ b/clang/lib/CodeGen/CodeGenPGO.h
@@ -37,7 +37,7 @@ class CodeGenPGO {
   uint64_t FunctionHash;
   std::unique_ptr> RegionCounterMap;
   std::unique_ptr> RegionMCDCBitmapMap;
-  std::unique_ptr> RegionCondIDMap;
+  std::unique_ptr> RegionCondIDMap;
   std::unique_ptr> StmtCountMap;
   std::unique_ptr ProfRecord;
   std::vector RegionCounts;
diff --git a/clang/lib/CodeGen/CoverageMappingGen.cpp 
b/clang/lib/CodeGen/CoverageMappingGen.cpp
index 0c43317642bca4..d918acd951dd8c 100644
--- a/clang/lib/CodeGen/CoverageMappingGen.cpp
+++ b/clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -587,8 +587,8 @@ struct EmptyCoverageMappingBuilder : public 
CoverageMappingBuilder {
 struct MCDCCoverageBuilder {
 
   struct DecisionIDPair {
-MCDCConditionID TrueID = 0;
-MCDCConditionID FalseID = 0;
+MCDCConditionID TrueID = -1;
+MCDCConditionID FalseID = -1;
   };
 
   /// The AST walk recursively visits nested logical-AND or logical-OR binary
@@ -684,11 +684,11 @@ struct MCDCCoverageBuilder {
   llvm::SmallVector DecisionStack;
   llvm::DenseMap &CondIDs;
   llvm::DenseMap &MCDCBitmapMap;
-  MCDCConditionID NextID = 1;
+  MCDCConditionID NextID = 0;
   bool NotMapped = false;
 
   /// Represent a sentinel value of [0,0] for the bottom of DecisionStack.
-  static constexpr DecisionIDPair DecisionStackSentinel{0, 0};
+  static constexpr DecisionIDPair DecisionStackSentinel{-1, -1};
 
   /// Is this a logical-AND operation?
   bool isLAnd(const BinaryOperator *E) const {
@@ -705,12 +705,12 @@ struct MCDCCoverageBuilder {
   /// Return whether the build of the control flow map is at the top-level
   /// (root) of a logical operator nest in a boolean expression prior to the
   /// assignment of condition IDs.
-  bool isIdle() const { return (NextID == 1 && !NotMapped); }
+  bool isIdle() const { return (NextID == 0 && !NotMapped); }
 
   /// Return whether any IDs have been assigned in the build of the control
   /// flow map, indicating that the map is being generated for this boolean
   /// expression.
-  bool isBuilding() const { return (NextID > 1); }
+  bool isBuilding() const { return (NextID > 0); }
 
   /// Set the given condition's ID.
   

[clang] [llvm] [MC/DC] Refactor: Let MCDCConditionID int16_t with zero-origin (PR #81257)

2024-02-10 Thread NAKAMURA Takumi via cfe-commits

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


[clang] 59037c0 - [RISCV] Add Zicfiss support to the shadow call stack implementation. (#68075)

2024-02-10 Thread via cfe-commits

Author: Yeting Kuo
Date: 2024-02-10T22:18:46+08:00
New Revision: 59037c0975de51ae29a5f9bd4260131ba3b7c22a

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

LOG: [RISCV] Add Zicfiss support to the shadow call stack implementation. 
(#68075)

This patch enable hardware shadow stack with `Zicifss` and
`mno-forced-sw-shadow-stack`. New feature forced-sw-shadow-stack
disables hardware shadow stack even when `Zicfiss` enabled.

Added: 


Modified: 
clang/docs/ShadowCallStack.rst
clang/include/clang/Driver/Options.td
clang/test/Driver/riscv-features.c
llvm/lib/Target/RISCV/RISCVFeatures.td
llvm/lib/Target/RISCV/RISCVFrameLowering.cpp
llvm/test/CodeGen/RISCV/shadowcallstack.ll

Removed: 




diff  --git a/clang/docs/ShadowCallStack.rst b/clang/docs/ShadowCallStack.rst
index 6e5192fd672391..d7ece11b352606 100644
--- a/clang/docs/ShadowCallStack.rst
+++ b/clang/docs/ShadowCallStack.rst
@@ -57,19 +57,25 @@ compiled application or the operating system. Integrating 
the runtime into
 the operating system should be preferred since otherwise all thread creation
 and destruction would need to be intercepted by the application.
 
-The instrumentation makes use of the platform register ``x18`` on AArch64 and
-``x3`` (``gp``) on RISC-V. For simplicity we will refer to this as the
-``SCSReg``. On some platforms, ``SCSReg`` is reserved, and on others, it is
-designated as a scratch register.  This generally means that any code that may
-run on the same thread as code compiled with ShadowCallStack must either target
-one of the platforms whose ABI reserves ``SCSReg`` (currently Android, Darwin,
-Fuchsia and Windows) or be compiled with a flag to reserve that register (e.g.,
-``-ffixed-x18``). If absolutely necessary, code compiled without reserving the
-register may be run on the same thread as code that uses ShadowCallStack by
-saving the register value temporarily on the stack (`example in Android`_) but
-this should be done with care since it risks leaking the shadow call stack
-address.
-
+The instrumentation makes use of the platform register ``x18`` on AArch64,
+``x3`` (``gp``) on RISC-V with software shadow stack and ``ssp`` on RISC-V with
+hardware shadow stack, which needs `Zicfiss`_ and 
``-mno-forced-sw-shadow-stack``
+(default option). Note that with ``Zicfiss``_ the RISC-V backend will default 
to
+the hardware based shadow call stack. Users can force the RISC-V backend to
+generate the software shadow call stack with ``Zicfiss``_ by passing
+``-mforced-sw-shadow-stack``.
+For simplicity we will refer to this as the ``SCSReg``. On some platforms,
+``SCSReg`` is reserved, and on others, it is designated as a scratch register.
+This generally means that any code that may run on the same thread as code
+compiled with ShadowCallStack must either target one of the platforms whose ABI
+reserves ``SCSReg`` (currently Android, Darwin, Fuchsia and Windows) or be
+compiled with a flag to reserve that register (e.g., ``-ffixed-x18``). If
+absolutely necessary, code compiled without reserving the register may be run 
on
+the same thread as code that uses ShadowCallStack by saving the register value
+temporarily on the stack (`example in Android`_) but this should be done with
+care since it risks leaking the shadow call stack address.
+
+.. _`Zicfiss`: https://github.com/riscv/riscv-cfi/blob/main/cfi_backward.adoc
 .. _`example in Android`: 
https://android-review.googlesource.com/c/platform/frameworks/base/+/803717
 
 Because it requires a dedicated register, the ShadowCallStack feature is
@@ -151,9 +157,13 @@ Usage
 
 To enable ShadowCallStack, just pass the ``-fsanitize=shadow-call-stack`` flag
 to both compile and link command lines. On aarch64, you also need to pass
-``-ffixed-x18`` unless your target already reserves ``x18``. On RISC-V, ``x3``
-(``gp``) is always reserved. It is, however, important to disable GP relaxation
-in the linker. This can be done with the ``--no-relax-gp`` flag in GNU ld.
+``-ffixed-x18`` unless your target already reserves ``x18``. No additional 
flags
+need to be passed on RISC-V because the software based shadow stack uses
+``x3`` (``gp``), which is always reserved, and the hardware based shadow call
+stack uses a dedicated register, ``ssp``.
+However, it is important to disable GP relaxation in the linker when using the
+software based shadow call stack on RISC-V. This can be done with the
+``--no-relax-gp`` flag in GNU ld, and is off by default in LLD.
 
 Low-level API
 -

diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 31503fcfc99160..7f007320e2f908 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -4614,6 +4614,10 @@ def msave_rest

[clang] [llvm] [RISCV] Add Zicfiss support to the shadow call stack implementation. (PR #68075)

2024-02-10 Thread Yeting Kuo via cfe-commits

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


[clang] [llvm] [LLVM] Add `__builtin_readsteadycounter` intrinsic and buiiltin for realtime clocks (PR #81331)

2024-02-10 Thread Joseph Huber via cfe-commits

https://github.com/jhuber6 updated 
https://github.com/llvm/llvm-project/pull/81331

>From 30341079e795c2668588b791f2c97b44006e7a04 Mon Sep 17 00:00:00 2001
From: Joseph Huber 
Date: Fri, 9 Feb 2024 16:13:42 -0600
Subject: [PATCH] [WIP][LLVM] Add `__builtin_readsteadycounter` intrinsic and
 buiiltin

Summary:
This patch adds a new intrinsic and builtin function mirroring the
existing `__builtin_readcyclecounter`. The difference is that this
implementation targets a separate counter that some targets have which
returns a fixed frequency clock that can be used to determine elapsed
time, this is different compared to the cycle counter which often has
variable frequency. This is currently only valid for the NVPTX and
AMDGPU targets.
---
 clang/docs/LanguageExtensions.rst | 31 ++
 clang/include/clang/Basic/Builtins.td |  6 ++
 clang/lib/CodeGen/CGBuiltin.cpp   |  4 ++
 clang/test/CodeGen/builtins.c |  6 ++
 llvm/include/llvm/CodeGen/ISDOpcodes.h|  6 ++
 llvm/include/llvm/IR/Intrinsics.td|  2 +
 llvm/include/llvm/Support/TargetOpcodes.def   |  3 +
 llvm/include/llvm/Target/GenericOpcodes.td|  6 ++
 .../Target/GlobalISel/SelectionDAGCompat.td   |  1 +
 .../include/llvm/Target/TargetSelectionDAG.td |  3 +
 llvm/lib/CodeGen/GlobalISel/IRTranslator.cpp  |  2 +
 llvm/lib/CodeGen/IntrinsicLowering.cpp|  6 ++
 llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp |  6 +-
 .../SelectionDAG/LegalizeIntegerTypes.cpp |  7 ++-
 llvm/lib/CodeGen/SelectionDAG/LegalizeTypes.h |  2 +-
 .../SelectionDAG/SelectionDAGBuilder.cpp  |  8 +++
 .../SelectionDAG/SelectionDAGDumper.cpp   |  1 +
 llvm/lib/CodeGen/TargetLoweringBase.cpp   |  3 +
 .../lib/Target/AMDGPU/AMDGPULegalizerInfo.cpp |  2 +
 .../Target/AMDGPU/AMDGPURegisterBankInfo.cpp  |  1 +
 llvm/lib/Target/AMDGPU/SIISelLowering.cpp |  4 ++
 llvm/lib/Target/AMDGPU/SMInstructions.td  | 14 +
 llvm/lib/Target/NVPTX/NVPTXISelLowering.cpp   |  3 +
 llvm/lib/Target/NVPTX/NVPTXInstrInfo.td   |  1 -
 llvm/lib/Target/NVPTX/NVPTXIntrinsics.td  |  4 ++
 .../GlobalISel/legalizer-info-validation.mir  |  3 +
 llvm/test/CodeGen/AMDGPU/readsteadycounter.ll | 24 +++
 llvm/test/CodeGen/NVPTX/intrinsics.ll | 12 
 .../builtins/match-table-replacerreg.td   | 24 +++
 .../match-table-imms.td   | 32 +-
 .../match-table-intrinsics.td |  5 +-
 .../match-table-patfrag-root.td   |  4 +-
 .../GlobalISelCombinerEmitter/match-table.td  | 62 +--
 llvm/test/TableGen/GlobalISelEmitter.td   |  2 +-
 34 files changed, 228 insertions(+), 72 deletions(-)
 create mode 100644 llvm/test/CodeGen/AMDGPU/readsteadycounter.ll

diff --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index e91156837290f7..4cc73599f9bae0 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -2764,6 +2764,37 @@ Query for this feature with 
``__has_builtin(__builtin_readcyclecounter)``. Note
 that even if present, its use may depend on run-time privilege or other OS
 controlled state.
 
+``__builtin_readsteadycounter``
+--
+
+``__builtin_readsteadycounter`` is used to access the fixed frequency counter
+register (or a similar steady-rate clock) on those targets that support it.
+The function is similar to ``__builtin_readcyclecounter`` above except that the
+frequency is fixed, making it suitable for measuring elapsed time.
+
+**Syntax**:
+
+.. code-block:: c++
+
+  __builtin_readsteadycounter()
+
+**Example of Use**:
+
+.. code-block:: c++
+
+  unsigned long long t0 = __builtin_readsteadycounter();
+  do_something();
+  unsigned long long t1 = __builtin_readsteadycounter();
+  unsigned long long secs_to_do_something = (t1 - t0) / tick_rate;
+
+**Description**:
+
+The ``__builtin_readsteadycounter()`` builtin returns the frequency counter 
value.
+When not supported by the target, the return value is always zero. This builtin
+takes no arguments and produces an unsigned long long result.
+
+Query for this feature with ``__has_builtin(__builtin_readsteadycounter)``.
+
 ``__builtin_dump_struct``
 -
 
diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index 31a2bdeb2d3e5e..193d5851f9f29f 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -1110,6 +1110,12 @@ def ReadCycleCounter : Builtin {
   let Prototype = "unsigned long long int()";
 }
 
+def ReadSteadyCounter : Builtin {
+  let Spellings = ["__builtin_readsteadycounter"];
+  let Attributes = [NoThrow];
+  let Prototype = "unsigned long long int()";
+}
+
 def Trap : Builtin {
   let Spellings = ["__builtin_trap"];
   let Attributes = [NoThrow, NoReturn];
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index a7a410dab1a018..ee0b7504769622 100644
--- a/

[clang] [Clang][Sema]: Allow copy constructor side effects (PR #81127)

2024-02-10 Thread Vlad Serebrennikov via cfe-commits


@@ -183,7 +185,12 @@ void foo(int size) {
   NonTriviallyDestructible array[2];  // no warning
   NonTriviallyDestructible nestedArray[2][2]; // no warning
 
+  // Copy initialzation gives warning before C++17
+#if __cplusplus <= 201402L
   Foo fooScalar = 1; // expected-warning {{unused variable 'fooScalar'}}
+#else
+  Foo fooScalar = 1; // no warning

Endilll wrote:

Code around here can be replaced with a single line:
```
Foo fooScalar = 1; // cxx98-14-warning {{unused variable 'fooScalar'}}
```
Look at DR tests again how to make this happen (via `-verify=`):
https://github.com/llvm/llvm-project/blob/3902f9b6e2d925d50f9a4861d78e5aba07b6ef11/clang/test/CXX/drs/dr0xx.cpp#L1-L3

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


[clang] [clang-format] Support of TableGen value annotations. (PR #80299)

2024-02-10 Thread Hirofumi Nakamura via cfe-commits

https://github.com/hnakamura5 updated 
https://github.com/llvm/llvm-project/pull/80299

>From 36f83a124ea8ad27cfefa1d12ae5aa781f8e6e3e Mon Sep 17 00:00:00 2001
From: hnakamura5 
Date: Thu, 1 Feb 2024 23:07:42 +0900
Subject: [PATCH 1/3] [clang-format] Support of TableGen value annotations.

---
 clang/lib/Format/FormatToken.h|  10 +
 clang/lib/Format/FormatTokenLexer.cpp |   2 +-
 clang/lib/Format/TokenAnnotator.cpp   | 303 +-
 clang/lib/Format/UnwrappedLineParser.cpp  |  13 +-
 clang/unittests/Format/TokenAnnotatorTest.cpp |  45 +++
 5 files changed, 364 insertions(+), 9 deletions(-)

diff --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index bace91b5f99b4d..0c1dce7a294082 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -150,7 +150,17 @@ namespace format {
   TYPE(StructuredBindingLSquare)   
\
   TYPE(TableGenBangOperator)   
\
   TYPE(TableGenCondOperator)   
\
+  TYPE(TableGenCondOperatorColon)  
\
+  TYPE(TableGenCondOperatorComma)  
\
+  TYPE(TableGenDAGArgCloser)   
\
+  TYPE(TableGenDAGArgListColon)
\
+  TYPE(TableGenDAGArgListComma)
\
+  TYPE(TableGenDAGArgOpener)   
\
+  TYPE(TableGenListCloser) 
\
+  TYPE(TableGenListOpener) 
\
   TYPE(TableGenMultiLineString)
\
+  TYPE(TableGenTrailingPasteOperator)  
\
+  TYPE(TableGenValueSuffix)
\
   TYPE(TemplateCloser) 
\
   TYPE(TemplateOpener) 
\
   TYPE(TemplateString) 
\
diff --git a/clang/lib/Format/FormatTokenLexer.cpp 
b/clang/lib/Format/FormatTokenLexer.cpp
index d7de09ef0e12ab..27b2b1b619b1d3 100644
--- a/clang/lib/Format/FormatTokenLexer.cpp
+++ b/clang/lib/Format/FormatTokenLexer.cpp
@@ -816,7 +816,7 @@ void FormatTokenLexer::handleTableGenMultilineString() {
   auto CloseOffset = Lex->getBuffer().find("}]", OpenOffset);
   if (CloseOffset == StringRef::npos)
 return;
-  auto Text = Lex->getBuffer().substr(OpenOffset, CloseOffset + 2);
+  auto Text = Lex->getBuffer().substr(OpenOffset, CloseOffset - OpenOffset + 
2);
   MultiLineString->TokenText = Text;
   resetLexer(SourceMgr.getFileOffset(
   Lex->getSourceLocation(Lex->getBufferLocation() - 2 + Text.size(;
diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index df1c5bc19de1e8..afcf5f638ce4c8 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -256,6 +256,18 @@ class AnnotatingParser {
   }
 }
   }
+  if (Style.isTableGen()) {
+if (CurrentToken->isOneOf(tok::comma, tok::equal)) {
+  // They appears as a separator. Unless it is not in class definition.
+  next();
+  continue;
+}
+// In angle, there must be Value like tokens. Types are also able to be
+// parsed in the same way with Values.
+if (!parseTableGenValue())
+  return false;
+continue;
+  }
   if (!consumeToken())
 return false;
 }
@@ -388,6 +400,28 @@ class AnnotatingParser {
   Contexts.back().IsExpression = !IsForOrCatch;
 }
 
+if (Style.isTableGen()) {
+  if (FormatToken *Prev = OpeningParen.Previous) {
+if (Prev->is(TT_TableGenCondOperator)) {
+  Contexts.back().IsTableGenCondOpe = true;
+  Contexts.back().IsExpression = true;
+} else if (Contexts.size() > 1 &&
+   Contexts[Contexts.size() - 2].IsTableGenBangOpe) {
+  // Hack to handle bang operators. The parent context's flag
+  // was set by parseTableGenSimpleValue().
+  // We have to specify the context outside because the prev of "(" may
+  // be ">", not the bang operator in this case.
+  Contexts.back().IsTableGenBangOpe = true;
+  Contexts.back().IsExpression = true;
+} else {
+  // Otherwise, this paren seems DAGArg.
+  if (!parseTableGenDAGArg())
+return false;
+  return parseTableGenDAGArgAndList(&OpeningParen);
+}
+  }
+}
+
 // Infer the role of the l_paren based on the previous token if we haven't
 // detected one yet.
 if (PrevNonComment && Opening

[clang] [Clang][Sema]: Allow copy constructor side effects (PR #81127)

2024-02-10 Thread Vlad Serebrennikov via cfe-commits


@@ -183,7 +185,12 @@ void foo(int size) {
   NonTriviallyDestructible array[2];  // no warning
   NonTriviallyDestructible nestedArray[2][2]; // no warning
 
+  // Copy initialzation gives warning before C++17
+#if __cplusplus <= 201402L
   Foo fooScalar = 1; // expected-warning {{unused variable 'fooScalar'}}
+#else
+  Foo fooScalar = 1; // no warning

Endilll wrote:

Here is documentation for `-verify` if you feel you need it: 
https://clang.llvm.org/docs/InternalsManual.html#verifying-diagnostics

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


[clang] [clang-format] Support of TableGen value annotations. (PR #80299)

2024-02-10 Thread Hirofumi Nakamura via cfe-commits


@@ -833,13 +885,207 @@ class AnnotatingParser {
 Left->setType(TT_ArrayInitializerLSquare);
   }
   FormatToken *Tok = CurrentToken;
+  if (Style.isTableGen()) {
+if (CurrentToken->isOneOf(tok::comma, tok::minus, tok::ellipsis)) {
+  // '-' and '...' appears as a separator in slice.
+  next();
+} else {
+  // In TableGen there must be a list of Values in square brackets.
+  // It must be ValueList or SliceElements.
+  if (!parseTableGenValue())
+return false;
+}
+updateParameterCount(Left, Tok);
+continue;
+  }
   if (!consumeToken())
 return false;
   updateParameterCount(Left, Tok);
 }
 return false;
   }
 
+  void nextTableGenNonComment() {
+next();
+while (CurrentToken && CurrentToken->is(tok::comment))
+  next();
+  }
+
+  bool parseTableGenValue(bool ParseNameMode = false) {

hnakamura5 wrote:

I added some more comments, here and on tryToParseTableGenTokVar.
Actually the behavior of return value is same as other parse functions here 
such as parseAngle, parseBrace.
That is, returning false results in the total failure of parseLine itself. They 
do not backtrack on fail.

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


[clang] [llvm] [MC/DC] Refactor: Introduce `ConditionIDs` as `std::array<2>` (PR #81221)

2024-02-10 Thread NAKAMURA Takumi via cfe-commits

https://github.com/chapuni updated 
https://github.com/llvm/llvm-project/pull/81221

>From 66bb6cc3fd339360c16c6a98ce08f34978f665e0 Mon Sep 17 00:00:00 2001
From: NAKAMURA Takumi 
Date: Fri, 9 Feb 2024 07:56:51 +0900
Subject: [PATCH 1/3] [MC/DC] Refactor: Introduce `ConditionIDs` as
 `std::array<2>`

Its 0th element corresponds to `FalseID` and 1st to `TrueID`.

CoverageMappingGen.cpp: `DecisionIDPair` is replaced with `ConditionIDs`
---
 clang/lib/CodeGen/CoverageMappingGen.cpp  | 50 +++
 .../ProfileData/Coverage/CoverageMapping.h|  9 ++--
 .../ProfileData/Coverage/CoverageMapping.cpp  | 31 ++--
 .../Coverage/CoverageMappingReader.cpp|  7 +--
 .../Coverage/CoverageMappingWriter.cpp|  4 +-
 .../ProfileData/CoverageMappingTest.cpp   | 24 -
 6 files changed, 56 insertions(+), 69 deletions(-)

diff --git a/clang/lib/CodeGen/CoverageMappingGen.cpp 
b/clang/lib/CodeGen/CoverageMappingGen.cpp
index 0c43317642bca4..54559af47e63dc 100644
--- a/clang/lib/CodeGen/CoverageMappingGen.cpp
+++ b/clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -95,7 +95,6 @@ void CoverageSourceInfo::updateNextTokLoc(SourceLocation Loc) 
{
 }
 
 namespace {
-using MCDCConditionID = CounterMappingRegion::MCDCConditionID;
 using MCDCParameters = CounterMappingRegion::MCDCParameters;
 
 /// A region of source code that can be mapped to a counter.
@@ -586,11 +585,6 @@ struct EmptyCoverageMappingBuilder : public 
CoverageMappingBuilder {
 /// creation.
 struct MCDCCoverageBuilder {
 
-  struct DecisionIDPair {
-MCDCConditionID TrueID = 0;
-MCDCConditionID FalseID = 0;
-  };
-
   /// The AST walk recursively visits nested logical-AND or logical-OR binary
   /// operator nodes and then visits their LHS and RHS children nodes.  As this
   /// happens, the algorithm will assign IDs to each operator's LHS and RHS 
side
@@ -681,14 +675,14 @@ struct MCDCCoverageBuilder {
 private:
   CodeGenModule &CGM;
 
-  llvm::SmallVector DecisionStack;
+  llvm::SmallVector DecisionStack;
   llvm::DenseMap &CondIDs;
   llvm::DenseMap &MCDCBitmapMap;
   MCDCConditionID NextID = 1;
   bool NotMapped = false;
 
   /// Represent a sentinel value of [0,0] for the bottom of DecisionStack.
-  static constexpr DecisionIDPair DecisionStackSentinel{0, 0};
+  static constexpr MCDCConditionIDs DecisionStackSentinel{0, 0};
 
   /// Is this a logical-AND operation?
   bool isLAnd(const BinaryOperator *E) const {
@@ -727,7 +721,7 @@ struct MCDCCoverageBuilder {
   }
 
   /// Return the LHS Decision ([0,0] if not set).
-  const DecisionIDPair &back() const { return DecisionStack.back(); }
+  const MCDCConditionIDs &back() const { return DecisionStack.back(); }
 
   /// Push the binary operator statement to track the nest level and assign IDs
   /// to the operator's LHS and RHS.  The RHS may be a larger subtree that is
@@ -744,7 +738,7 @@ struct MCDCCoverageBuilder {
 if (NotMapped)
   return;
 
-const DecisionIDPair &ParentDecision = DecisionStack.back();
+const MCDCConditionIDs &ParentDecision = DecisionStack.back();
 
 // If the operator itself has an assigned ID, this means it represents a
 // larger subtree.  In this case, assign that ID to its LHS node.  Its RHS
@@ -760,18 +754,18 @@ struct MCDCCoverageBuilder {
 
 // Push the LHS decision IDs onto the DecisionStack.
 if (isLAnd(E))
-  DecisionStack.push_back({RHSid, ParentDecision.FalseID});
+  DecisionStack.push_back({ParentDecision[0], RHSid});
 else
-  DecisionStack.push_back({ParentDecision.TrueID, RHSid});
+  DecisionStack.push_back({RHSid, ParentDecision[1]});
   }
 
   /// Pop and return the LHS Decision ([0,0] if not set).
-  DecisionIDPair pop() {
+  MCDCConditionIDs pop() {
 if (!CGM.getCodeGenOpts().MCDCCoverage || NotMapped)
   return DecisionStack.front();
 
 assert(DecisionStack.size() > 1);
-DecisionIDPair D = DecisionStack.back();
+MCDCConditionIDs D = DecisionStack.back();
 DecisionStack.pop_back();
 return D;
   }
@@ -865,8 +859,7 @@ struct CounterCoverageMappingBuilder
 std::optional StartLoc = std::nullopt,
 std::optional EndLoc = std::nullopt,
 std::optional FalseCount = std::nullopt,
-MCDCConditionID ID = 0, MCDCConditionID TrueID = 0,
-MCDCConditionID FalseID = 0) {
+MCDCConditionID ID = 0, MCDCConditionIDs Conds = {}) {
 
 if (StartLoc && !FalseCount) {
   MostRecentLocation = *StartLoc;
@@ -885,8 +878,7 @@ struct CounterCoverageMappingBuilder
   StartLoc = std::nullopt;
 if (EndLoc && EndLoc->isInvalid())
   EndLoc = std::nullopt;
-RegionStack.emplace_back(Count, FalseCount,
- MCDCParameters{0, 0, ID, TrueID, FalseID},
+RegionStack.emplace_back(Count, FalseCount, MCDCParameters{0, 0, ID, 
Conds},
  StartLoc, EndLoc);
 
 return RegionStack.size() - 1;

[clang] [llvm] [MC/DC] Refactor: Introduce `ConditionIDs` as `std::array<2>` (PR #81221)

2024-02-10 Thread NAKAMURA Takumi via cfe-commits


@@ -217,6 +217,9 @@ class CounterExpressionBuilder {
 
 using LineColPair = std::pair;
 
+using MCDCConditionID = unsigned int;
+using MCDCConditionIDs = std::array;

chapuni wrote:

`first` and `second` didn't make sense to me.

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


[clang] [clang] Refactor `IdentifierInfo::ObjcOrBuiltinID` (PR #71709)

2024-02-10 Thread Vlad Serebrennikov via cfe-commits

https://github.com/Endilll updated 
https://github.com/llvm/llvm-project/pull/71709

>From 2823d38544d18213b5bf48c67e4eedd52acce850 Mon Sep 17 00:00:00 2001
From: Vlad Serebrennikov 
Date: Wed, 8 Nov 2023 20:30:37 +0300
Subject: [PATCH 1/3] [clang] Refactor `IdentifierInfo::ObjcOrBuiltinID`

This patch refactors how values are stored inside 
`IdentifierInfo::ObjcOrBuiltinID` bit-field, and annotates it with 
`preferred_type`. In order to make the value easier to interpret by debuggers, 
a new `ObjCKeywordOrInterestingOrBuiltin` is added. Previous "layout" of this 
fields couldn't be represented with this new enum, because it skipped over some 
arbitrary enumerators, so a new "layout" was invented based on 
`ObjCKeywordOrInterestingOrBuiltin` enum. I believe the new layout is simpler 
than the new one.
---
 clang/include/clang/Basic/IdentifierTable.h | 117 
 1 file changed, 73 insertions(+), 44 deletions(-)

diff --git a/clang/include/clang/Basic/IdentifierTable.h 
b/clang/include/clang/Basic/IdentifierTable.h
index 0898e7d39dd7de..fa76228da2b143 100644
--- a/clang/include/clang/Basic/IdentifierTable.h
+++ b/clang/include/clang/Basic/IdentifierTable.h
@@ -15,6 +15,7 @@
 #ifndef LLVM_CLANG_BASIC_IDENTIFIERTABLE_H
 #define LLVM_CLANG_BASIC_IDENTIFIERTABLE_H
 
+#include "clang/Basic/Builtins.h"
 #include "clang/Basic/DiagnosticIDs.h"
 #include "clang/Basic/LLVM.h"
 #include "clang/Basic/TokenKinds.h"
@@ -86,19 +87,26 @@ enum { IdentifierInfoAlignment = 8 };
 static constexpr int ObjCOrBuiltinIDBits = 16;
 
 /// The "layout" of ObjCOrBuiltinID is:
-///  - The first value (0) represents "not a special identifier".
-///  - The next (NUM_OBJC_KEYWORDS - 1) values represent ObjCKeywordKinds (not
-///including objc_not_keyword).
-///  - The next (NUM_INTERESTING_IDENTIFIERS - 1) values represent
-///InterestingIdentifierKinds (not including not_interesting).
-///  - The rest of the values represent builtin IDs (not including NotBuiltin).
-static constexpr int FirstObjCKeywordID = 1;
-static constexpr int LastObjCKeywordID =
-FirstObjCKeywordID + tok::NUM_OBJC_KEYWORDS - 2;
-static constexpr int FirstInterestingIdentifierID = LastObjCKeywordID + 1;
-static constexpr int LastInterestingIdentifierID =
-FirstInterestingIdentifierID + tok::NUM_INTERESTING_IDENTIFIERS - 2;
-static constexpr int FirstBuiltinID = LastInterestingIdentifierID + 1;
+///  - ObjCKeywordKind enumerators
+///  - InterestingIdentifierKind enumerators
+///  - Builtin::ID enumerators
+///  - NonSpecialIdentifier
+enum class ObjCKeywordOrInterestingOrBuiltin {
+#define OBJC_AT_KEYWORD(X) objc_##X,
+#include "clang/Basic/TokenKinds.def"
+  NUM_OBJC_KEYWORDS,
+
+#define INTERESTING_IDENTIFIER(X) X,
+#include "clang/Basic/TokenKinds.def"
+  NUM_OBJC_KEYWORDS_AND_INTERESTING_IDENTIFIERS,
+
+  NotBuiltin,
+#define BUILTIN(ID, TYPE, ATTRS) BI##ID,
+#include "clang/Basic/Builtins.def"
+  FirstTSBuiltin,
+
+  NonSpecialIdentifier = 65534
+};
 
 /// One of these records is kept for each identifier that
 /// is lexed.  This contains information about whether the token was 
\#define'd,
@@ -113,9 +121,7 @@ class alignas(IdentifierInfoAlignment) IdentifierInfo {
   LLVM_PREFERRED_TYPE(tok::TokenKind)
   unsigned TokenID : 9;
 
-  // ObjC keyword ('protocol' in '@protocol') or builtin (__builtin_inf).
-  // First NUM_OBJC_KEYWORDS values are for Objective-C,
-  // the remaining values are for builtins.
+  LLVM_PREFERRED_TYPE(ObjCKeywordOrInterestingOrBuiltin)
   unsigned ObjCOrBuiltinID : ObjCOrBuiltinIDBits;
 
   // True if there is a #define for this.
@@ -198,13 +204,16 @@ class alignas(IdentifierInfoAlignment) IdentifierInfo {
   llvm::StringMapEntry *Entry = nullptr;
 
   IdentifierInfo()
-  : TokenID(tok::identifier), ObjCOrBuiltinID(0), HasMacro(false),
-HadMacro(false), IsExtension(false), IsFutureCompatKeyword(false),
-IsPoisoned(false), IsCPPOperatorKeyword(false),
-NeedsHandleIdentifier(false), IsFromAST(false), 
ChangedAfterLoad(false),
-FEChangedAfterLoad(false), RevertedTokenID(false), OutOfDate(false),
-IsModulesImport(false), IsMangledOpenMPVariantName(false),
-IsDeprecatedMacro(false), IsRestrictExpansion(false), IsFinal(false) {}
+  : TokenID(tok::identifier),
+ObjCOrBuiltinID(llvm::to_underlying(
+ObjCKeywordOrInterestingOrBuiltin::NonSpecialIdentifier)),
+HasMacro(false), HadMacro(false), IsExtension(false),
+IsFutureCompatKeyword(false), IsPoisoned(false),
+IsCPPOperatorKeyword(false), NeedsHandleIdentifier(false),
+IsFromAST(false), ChangedAfterLoad(false), FEChangedAfterLoad(false),
+RevertedTokenID(false), OutOfDate(false), IsModulesImport(false),
+IsMangledOpenMPVariantName(false), IsDeprecatedMacro(false),
+IsRestrictExpansion(false), IsFinal(false) {}
 
 public:
   IdentifierInfo(const IdentifierInfo &) = delete;
@@ -332,42 +341,62 @@ class alignas(IdentifierInfoAlignment) 

[clang] [llvm] [MC/DC] Refactor: Introduce `ConditionIDs` as `std::array<2>` (PR #81221)

2024-02-10 Thread NAKAMURA Takumi via cfe-commits

chapuni wrote:

@evodius96 As an experiment, I've made subscripts as `bool`. It works 
semantically however I wonder they wouldn't be intuitive to us.

I can rewind it.

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


[clang] [Clang][Sema]: Allow copy constructor side effects (PR #81127)

2024-02-10 Thread Vinayak Dev via cfe-commits

https://github.com/vinayakdsci updated 
https://github.com/llvm/llvm-project/pull/81127

>From 335d2277881af6737ba899417121c321ce4d098f Mon Sep 17 00:00:00 2001
From: Vinayak Dev 
Date: Thu, 8 Feb 2024 17:29:44 +0530
Subject: [PATCH] [Clang][Sema]: Allow copy constructor side effects

---
 clang/docs/ReleaseNotes.rst  |  4 +++
 clang/lib/Sema/SemaDecl.cpp  |  3 +-
 clang/test/SemaCXX/warn-unused-variables.cpp | 33 ++--
 3 files changed, 37 insertions(+), 3 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index ece6013f672621..007791492cd1b6 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -173,6 +173,10 @@ Bug Fixes in This Version
   for logical operators in C23.
   Fixes (`#64356 `_).
 
+- Clang now doesn't produce false-positive warning `-Wunused-variable`
+  for variables created through copy initialization having side-effects in 
C++17 and later.
+  Fixes (`#79518 `_).
+
 Bug Fixes to Compiler Builtins
 ^^
 
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 2c526cd0d0e675..898d07e1c32ded 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -2044,7 +2044,8 @@ static bool ShouldDiagnoseUnusedDecl(const LangOptions 
&LangOpts,
   return false;
 
 if (Init) {
-  const auto *Construct = dyn_cast(Init);
+  const auto *Construct =
+  dyn_cast(Init->IgnoreImpCasts());
   if (Construct && !Construct->isElidable()) {
 const CXXConstructorDecl *CD = Construct->getConstructor();
 if (!CD->isTrivial() && !RD->hasAttr() &&
diff --git a/clang/test/SemaCXX/warn-unused-variables.cpp 
b/clang/test/SemaCXX/warn-unused-variables.cpp
index b649c7d8089355..29e8d08d37d8c6 100644
--- a/clang/test/SemaCXX/warn-unused-variables.cpp
+++ b/clang/test/SemaCXX/warn-unused-variables.cpp
@@ -1,5 +1,7 @@
 // RUN: %clang_cc1 -fsyntax-only -Wunused-variable -Wunused-label 
-Wno-c++1y-extensions -verify %s
-// RUN: %clang_cc1 -fsyntax-only -Wunused-variable -Wunused-label 
-Wno-c++1y-extensions -verify -std=gnu++11 %s
+// RUN: %clang_cc1 -fsyntax-only -Wunused-variable -Wunused-label 
-Wno-c++1y-extensions -verify=expected,cxx98-14 -std=gnu++11 %s
+// RUN: %clang_cc1 -fsyntax-only -Wunused-variable -Wunused-label 
-Wno-c++1y-extensions -verify=expected,cxx98-14 -std=gnu++14 %s
+// RUN: %clang_cc1 -fsyntax-only -Wunused-variable -Wunused-label 
-Wno-c++1y-extensions -verify -std=gnu++17 %s
 template void f() {
   T t;
   t = 17;
@@ -183,7 +185,8 @@ void foo(int size) {
   NonTriviallyDestructible array[2];  // no warning
   NonTriviallyDestructible nestedArray[2][2]; // no warning
 
-  Foo fooScalar = 1; // expected-warning {{unused variable 'fooScalar'}}
+  // Copy initialzation gives warning before C++17
+  Foo fooScalar = 1; // cxx98-14-warning {{unused variable 'fooScalar'}}
   Foo fooArray[] = {1,2}; // expected-warning {{unused variable 'fooArray'}}
   Foo fooNested[2][2] = { {1,2}, {3,4} }; // expected-warning {{unused 
variable 'fooNested'}}
 }
@@ -297,3 +300,29 @@ void RAIIWrapperTest() {
 }
 
 } // namespace gh54489
+
+// Ensure that -Wunused-variable does not emit warning
+// on copy constructors with side effects (C++17 and later)
+#if __cplusplus >= 201703L
+namespace gh79518 {
+
+struct S {
+S(int);
+};
+
+// With an initializer list
+struct A {
+  int x;
+  A(int x) : x(x) {}
+};
+
+void foo() {
+S s(0); // no warning
+S s2 = 0; // no warning
+S s3{0}; // no warning
+
+A a = 1; // no warning
+}
+
+} // namespace gh79518
+#endif

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


[clang] [Clang][Sema]: Allow copy constructor side effects (PR #81127)

2024-02-10 Thread Vinayak Dev via cfe-commits

vinayakdsci wrote:

I hope this does it!

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


[clang] [llvm] [MC/DC] Refactor: Make `MCDCParams` as `std::variant` (PR #81227)

2024-02-10 Thread NAKAMURA Takumi via cfe-commits


@@ -250,18 +251,27 @@ struct CounterMappingRegion {
   };
 
   using MCDCConditionID = unsigned int;
-  struct MCDCParameters {
+  struct MCDCDecisionParameters {
 /// Byte Index of Bitmap Coverage Object for a Decision Region.
-unsigned BitmapIdx = 0;
+unsigned BitmapIdx;
 
 /// Number of Conditions used for a Decision Region.
-unsigned NumConditions = 0;
+unsigned NumConditions;
 
+MCDCDecisionParameters() = delete;
+  };
+
+  struct MCDCBranchParameters {
 /// IDs used to represent a branch region and other branch regions
 /// evaluated based on True and False branches.
-MCDCConditionID ID = 0, TrueID = 0, FalseID = 0;
+MCDCConditionID ID, TrueID, FalseID;
+
+MCDCBranchParameters() = delete;
   };
 
+  using MCDCParameters = std::variant;

chapuni wrote:

FYI, the size of `MCDCParameters` will be `12` (gnu) or `8` (libc++) finally, 
with shrinking a few members to `int16_t`. (#81257)

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


[clang] [clang] Differentiate between identifier and string EnumArgument (PR #68550)

2024-02-10 Thread Sergei Barannikov via cfe-commits

https://github.com/s-barannikov updated 
https://github.com/llvm/llvm-project/pull/68550

>From 96dd0121b095f92cc66fcfc3ef08a19d0b2d6bec Mon Sep 17 00:00:00 2001
From: Sergei Barannikov 
Date: Mon, 9 Oct 2023 01:38:33 +0300
Subject: [PATCH 1/2] [clang] Differentiate between identifier and string
 EnumArgument

EnumArgument may be a string or an identifier. If it is a string, it
should be parsed as unevaluated string literal. Add IsString flag to
EnumArgument so that the parser can choose the correct parsing method.

Target-specific attributes that share spelling may have different
attribute "prototypes". For example, ARM's version of "interrupt"
attribute accepts a string enum, while MSP430's version accepts an
unsigned integer. Adjust ClangAttrEmitter so that the generated
`attributeStringLiteralListArg` returns the correct mask depending on
target triple.

It is worth noting that even after this change some string arguments are
still parsed as identifiers or, worse, as expressions. This is because
of some special logic in `ParseAttributeArgsCommon`. Fixing it is out of
scope of this patch.
---
 clang/include/clang/Basic/Attr.td| 82 +++-
 clang/lib/Parse/ParseDecl.cpp|  4 +-
 clang/test/Sema/attr-function-return.c   |  2 +-
 clang/test/Sema/callingconv-iamcu.c  |  2 +-
 clang/test/Sema/callingconv.c|  2 +-
 clang/test/Sema/zero_call_used_regs.c|  2 +-
 clang/test/SemaCXX/warn-consumed-parsing.cpp |  2 +-
 clang/test/SemaHLSL/shader_type_attr.hlsl|  4 +-
 clang/utils/TableGen/ClangAttrEmitter.cpp| 80 +++
 9 files changed, 119 insertions(+), 61 deletions(-)

diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index db17211747b17d..d9b55422d3a530 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -279,12 +279,15 @@ class DefaultIntArgument : 
IntArgument {
 
 // This argument is more complex, it includes the enumerator type
 // name, whether the enum type is externally defined, a list of
-// strings to accept, and a list of enumerators to map them to.
-class EnumArgument values,
+// possible values, and a list of enumerators to map them to.
+class EnumArgument 
values,
list enums, bit opt = 0, bit fake = 0,
bit isExternalType = 0>
 : Argument {
   string Type = type;
+  // When true, the argument will be parsed as an unevaluated string literal
+  // and otherwise as an identifier.
+  bit IsString = is_string;
   list Values = values;
   list Enums = enums;
   bit IsExternalType = isExternalType;
@@ -292,10 +295,14 @@ class EnumArgument 
values,
 
 // FIXME: There should be a VariadicArgument type that takes any other type
 //of argument and generates the appropriate type.
-class VariadicEnumArgument values,
-   list enums, bit isExternalType = 0>
+class VariadicEnumArgument values, list enums,
+   bit isExternalType = 0>
 : Argument  {
   string Type = type;
+  // When true, the argument will be parsed as an unevaluated string literal
+  // and otherwise as an identifier.
+  bit IsString = is_string;
   list Values = values;
   list Enums = enums;
   bit IsExternalType = isExternalType;
@@ -898,7 +905,7 @@ def ARMInterrupt : InheritableAttr, 
TargetSpecificAttr {
   // MSP430Interrupt's, MipsInterrupt's and AnyX86Interrupt's spellings
   // must match.
   let Spellings = [GCC<"interrupt">];
-  let Args = [EnumArgument<"Interrupt", "InterruptType",
+  let Args = [EnumArgument<"Interrupt", "InterruptType", /*is_string=*/true,
["IRQ", "FIQ", "SWI", "ABORT", "UNDEF", ""],
["IRQ", "FIQ", "SWI", "ABORT", "UNDEF", "Generic"],
1>];
@@ -1023,7 +1030,8 @@ def ExternalSourceSymbol : InheritableAttr {
 
 def Blocks : InheritableAttr {
   let Spellings = [Clang<"blocks">];
-  let Args = [EnumArgument<"Type", "BlockType", ["byref"], ["ByRef"]>];
+  let Args = [EnumArgument<"Type", "BlockType", /*is_string=*/true,
+   ["byref"], ["ByRef"]>];
   let Documentation = [Undocumented];
 }
 
@@ -1597,7 +1605,7 @@ def FlagEnum : InheritableAttr {
 def EnumExtensibility : InheritableAttr {
   let Spellings = [Clang<"enum_extensibility">];
   let Subjects = SubjectList<[Enum]>;
-  let Args = [EnumArgument<"Extensibility", "Kind",
+  let Args = [EnumArgument<"Extensibility", "Kind", /*is_string=*/false,
   ["closed", "open"], ["Closed", "Open"]>];
   let Documentation = [EnumExtensibilityDocs];
 }
@@ -1763,7 +1771,7 @@ def MipsInterrupt : InheritableAttr, 
TargetSpecificAttr {
   // must match.
   let Spellings = [GCC<"interrupt">];
   let Subjects = SubjectList<[Function]>;
-  let Args = [EnumArgument<"Interrupt", "InterruptType",
+  let Args = [EnumArgument<"Interrupt", "InterruptType", /*is_string=*/true,
["vec

[clang] [clang] Add -Wmissing-designated-field-initializers (PR #81364)

2024-02-10 Thread Vadim D. via cfe-commits

https://github.com/vvd170501 created 
https://github.com/llvm/llvm-project/pull/81364

Fixes  #68933.

>From aa48713c9bf23c24bbc0c22dd67f332ca970d2b8 Mon Sep 17 00:00:00 2001
From: Vadim Dudkin 
Date: Sat, 10 Feb 2024 02:29:48 +0300
Subject: [PATCH] Add -Wmissing-designated-field-initializers, decide whether
 to skip m-f-i check only when needed

---
 clang/include/clang/Basic/DiagnosticGroups.td | 10 +++-
 .../clang/Basic/DiagnosticSemaKinds.td|  4 ++
 clang/lib/Sema/SemaInit.cpp   | 50 ++-
 .../SemaCXX/cxx2a-initializer-aggregates.cpp  | 11 ++--
 4 files changed, 45 insertions(+), 30 deletions(-)

diff --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index 975eca0ad9b642..bda533f77cc56a 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -516,7 +516,15 @@ def MethodSignatures : DiagGroup<"method-signatures">;
 def MismatchedParameterTypes : DiagGroup<"mismatched-parameter-types">;
 def MismatchedReturnTypes : DiagGroup<"mismatched-return-types">;
 def MismatchedTags : DiagGroup<"mismatched-tags">;
-def MissingFieldInitializers : DiagGroup<"missing-field-initializers">;
+def MissingDesignatedFieldInitializers : 
DiagGroup<"missing-designated-field-initializers">{
+  code Documentation = [{
+Warn about designated initializers with some fields missing (only in C++).
+  }];
+}
+// Default -Wmissing-field-initializers matches gcc behavior,
+// but missing-designated-field-initializers can be turned off to match old 
clang behavior.
+def MissingFieldInitializers : DiagGroup<"missing-field-initializers",
+ [MissingDesignatedFieldInitializers]>;
 def ModuleLock : DiagGroup<"module-lock">;
 def ModuleBuild : DiagGroup<"module-build">;
 def ModuleImport : DiagGroup<"module-import">;
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index b4dc4feee8e63a..69e197e26b9b45 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -6165,6 +6165,10 @@ def ext_initializer_string_for_char_array_too_long : 
ExtWarn<
 def warn_missing_field_initializers : Warning<
   "missing field %0 initializer">,
   InGroup, DefaultIgnore;
+// The same warning, but another group is needed to disable it separately.
+def warn_missing_designated_field_initializers : Warning<
+  "missing field %0 initializer">,
+  InGroup, DefaultIgnore;
 def warn_braces_around_init : Warning<
   "braces around %select{scalar |}0initializer">,
   InGroup>;
diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index b6de06464cd6f3..08aa50ebad331f 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -2227,8 +2227,6 @@ void InitListChecker::CheckStructUnionTypes(
   size_t NumRecordDecls = llvm::count_if(RD->decls(), [&](const Decl *D) {
 return isa(D) || isa(D);
   });
-  bool CheckForMissingFields =
-!IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts());
   bool HasDesignatedInit = false;
 
   llvm::SmallPtrSet InitializedFields;
@@ -2269,11 +2267,6 @@ void InitListChecker::CheckStructUnionTypes(
   }
 
   InitializedSomething = true;
-
-  // Disable check for missing fields when designators are used.
-  // This matches gcc behaviour.
-  if (!SemaRef.getLangOpts().CPlusPlus)
-CheckForMissingFields = false;
   continue;
 }
 
@@ -2285,7 +2278,7 @@ void InitListChecker::CheckStructUnionTypes(
 // These are okay for randomized structures. [C99 6.7.8p19]
 //
 // Also, if there is only one element in the structure, we allow something
-// like this, because it's really not randomized in the tranditional sense.
+// like this, because it's really not randomized in the traditional sense.
 //
 //   struct foo h = {bar};
 auto IsZeroInitializer = [&](const Expr *I) {
@@ -2363,23 +2356,32 @@ void InitListChecker::CheckStructUnionTypes(
   }
 
   // Emit warnings for missing struct field initializers.
-  if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
-  !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;
+  if (!VerifyOnly && InitializedSomething && !RD->isUnion()) {
+// Disable missing fields check for:
+// - Zero initializers
+// - Designated initializers (only in C). This matches gcc behaviour.
+bool DisableCheck =
+IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts()) ||
+   

[clang] [clang] Add -Wmissing-designated-field-initializers (PR #81364)

2024-02-10 Thread via cfe-commits

github-actions[bot] wrote:



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

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

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

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

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

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

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

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


[clang] [Clang][Sema]: Allow copy constructor side effects (PR #81127)

2024-02-10 Thread Vlad Serebrennikov via cfe-commits

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

LGTM
Make sure @cor3ntin is happy, too.

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


[clang] [llvm] [TargetParser][AArch64] Add alias for FEAT_RDM. (PR #80540)

2024-02-10 Thread Alexandros Lamprineas via cfe-commits


@@ -673,7 +673,7 @@ int hoo(void) {
 //
 //
 // CHECK: Function Attrs: noinline nounwind optnone
-// CHECK-LABEL: define {{[^@]+}}@fmv_inline._MlseMrdm
+// CHECK-LABEL: define {{[^@]+}}@fmv_inline._MlseMrdma

labrinea wrote:

I raised this with the GCC team, I don't have an answer yet but I believe GCC 
only accepts "rdma" on the attribute (so I suppose that makes its way to the 
mangled name?). I remember you raised this matter again in a previous review, 
when we changed priorities and the mangling was affected. That is a good point 
but I think first we need to agree whether those functions are part of the ABI 
or not. Right now I don't see why they need to be. We could even make then have 
internal linkage, no? If I am mistaken a counter example would help, thanks!

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


[clang] [clang] Add -Wmissing-designated-field-initializers (PR #81364)

2024-02-10 Thread Vadim D. via cfe-commits

https://github.com/vvd170501 updated 
https://github.com/llvm/llvm-project/pull/81364

>From b7e3ffb25e1a50ac29e50ac8536ea93244f219a1 Mon Sep 17 00:00:00 2001
From: vvd170501 <36827317+vvd170...@users.noreply.github.com>
Date: Sat, 10 Feb 2024 19:19:52 +0300
Subject: [PATCH] Add -Wmissing-designated-field-initializers, decide whether
 to skip m-f-i check only when needed

---
 clang/include/clang/Basic/DiagnosticGroups.td | 10 +++-
 .../clang/Basic/DiagnosticSemaKinds.td|  4 ++
 clang/lib/Sema/SemaInit.cpp   | 50 ++-
 .../SemaCXX/cxx2a-initializer-aggregates.cpp  | 11 ++--
 4 files changed, 45 insertions(+), 30 deletions(-)

diff --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index 975eca0ad9b642..bda533f77cc56a 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -516,7 +516,15 @@ def MethodSignatures : DiagGroup<"method-signatures">;
 def MismatchedParameterTypes : DiagGroup<"mismatched-parameter-types">;
 def MismatchedReturnTypes : DiagGroup<"mismatched-return-types">;
 def MismatchedTags : DiagGroup<"mismatched-tags">;
-def MissingFieldInitializers : DiagGroup<"missing-field-initializers">;
+def MissingDesignatedFieldInitializers : 
DiagGroup<"missing-designated-field-initializers">{
+  code Documentation = [{
+Warn about designated initializers with some fields missing (only in C++).
+  }];
+}
+// Default -Wmissing-field-initializers matches gcc behavior,
+// but missing-designated-field-initializers can be turned off to match old 
clang behavior.
+def MissingFieldInitializers : DiagGroup<"missing-field-initializers",
+ [MissingDesignatedFieldInitializers]>;
 def ModuleLock : DiagGroup<"module-lock">;
 def ModuleBuild : DiagGroup<"module-build">;
 def ModuleImport : DiagGroup<"module-import">;
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index b4dc4feee8e63a..69e197e26b9b45 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -6165,6 +6165,10 @@ def ext_initializer_string_for_char_array_too_long : 
ExtWarn<
 def warn_missing_field_initializers : Warning<
   "missing field %0 initializer">,
   InGroup, DefaultIgnore;
+// The same warning, but another group is needed to disable it separately.
+def warn_missing_designated_field_initializers : Warning<
+  "missing field %0 initializer">,
+  InGroup, DefaultIgnore;
 def warn_braces_around_init : Warning<
   "braces around %select{scalar |}0initializer">,
   InGroup>;
diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index b6de06464cd6f3..08aa50ebad331f 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -2227,8 +2227,6 @@ void InitListChecker::CheckStructUnionTypes(
   size_t NumRecordDecls = llvm::count_if(RD->decls(), [&](const Decl *D) {
 return isa(D) || isa(D);
   });
-  bool CheckForMissingFields =
-!IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts());
   bool HasDesignatedInit = false;
 
   llvm::SmallPtrSet InitializedFields;
@@ -2269,11 +2267,6 @@ void InitListChecker::CheckStructUnionTypes(
   }
 
   InitializedSomething = true;
-
-  // Disable check for missing fields when designators are used.
-  // This matches gcc behaviour.
-  if (!SemaRef.getLangOpts().CPlusPlus)
-CheckForMissingFields = false;
   continue;
 }
 
@@ -2285,7 +2278,7 @@ void InitListChecker::CheckStructUnionTypes(
 // These are okay for randomized structures. [C99 6.7.8p19]
 //
 // Also, if there is only one element in the structure, we allow something
-// like this, because it's really not randomized in the tranditional sense.
+// like this, because it's really not randomized in the traditional sense.
 //
 //   struct foo h = {bar};
 auto IsZeroInitializer = [&](const Expr *I) {
@@ -2363,23 +2356,32 @@ void InitListChecker::CheckStructUnionTypes(
   }
 
   // Emit warnings for missing struct field initializers.
-  if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
-  !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;
+  if (!VerifyOnly && InitializedSomething && !RD->isUnion()) {
+// Disable missing fields check for:
+// - Zero initializers
+// - Designated initializers (only in C). This matches gcc behaviour.
+bool DisableCheck =
+IList->isIdiomaticZeroInitializer(Sema

[clang] [ObjC] Recursively check superclasses to see if any inherit from NSObject (PR #81335)

2024-02-10 Thread via cfe-commits

https://github.com/AtariDreams updated 
https://github.com/llvm/llvm-project/pull/81335

>From 18987af24d2f53d00e2ac42998a8f1580e35afdf Mon Sep 17 00:00:00 2001
From: Rose <83477269+ataridre...@users.noreply.github.com>
Date: Fri, 9 Feb 2024 17:51:15 -0500
Subject: [PATCH 1/2] [ObjC] Add pre-commit tests [NFC]

---
 .../CodeGenObjC/constant-non-fragile-ivar-offset.m  | 13 +
 1 file changed, 13 insertions(+)

diff --git a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m 
b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
index 788b3220af3067..40a97ba62ec6cf 100644
--- a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
+++ b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
@@ -1,6 +1,7 @@
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 -emit-llvm %s -o - | 
FileCheck %s
 
 // CHECK: @"OBJC_IVAR_$_StaticLayout.static_layout_ivar" = hidden constant i64 
20
+// CHECK: @"OBJC_IVAR_$_StaticLayoutSubClass.static_layout_ivar2" = hidden 
global i64 24
 // CHECK: @"OBJC_IVAR_$_NotStaticLayout.not_static_layout_ivar" = hidden 
global i64 12
 
 @interface NSObject {
@@ -20,6 +21,18 @@ -(void)meth {
 }
 @end
 
+@interface StaticLayoutSubClass : StaticLayout
+@end
+
+@implementation StaticLayoutSubClass {
+  int static_layout_ivar2;
+}
+-(void)meth2 {
+  static_layout_ivar2 = 0;
+  // CHECK: load i64, ptr @"OBJC_IVAR_$_StaticLayoutSubClass
+}
+@end
+
 @interface NotNSObject {
   int these, might, change;
 }

>From 193bec6224c2a04f486c24a7d262cbcb058cc1c3 Mon Sep 17 00:00:00 2001
From: Rose <83477269+ataridre...@users.noreply.github.com>
Date: Fri, 9 Feb 2024 17:47:59 -0500
Subject: [PATCH 2/2] [ObjC] Recursively check superclasses to see if any
 inherit from NSObject

If an NSObject subclass has fixed offsets, then so must the subclasses of that 
subclass!
---
 clang/lib/CodeGen/CGObjCMac.cpp   | 22 ++-
 .../constant-non-fragile-ivar-offset.m|  4 ++--
 2 files changed, 18 insertions(+), 8 deletions(-)

diff --git a/clang/lib/CodeGen/CGObjCMac.cpp b/clang/lib/CodeGen/CGObjCMac.cpp
index 27d77e9a8a5511..ceee70a5d79b3e 100644
--- a/clang/lib/CodeGen/CGObjCMac.cpp
+++ b/clang/lib/CodeGen/CGObjCMac.cpp
@@ -1593,12 +1593,22 @@ class CGObjCNonFragileABIMac : public CGObjCCommonMac {
   }
 
   bool isClassLayoutKnownStatically(const ObjCInterfaceDecl *ID) {
-// NSObject is a fixed size. If we can see the @implementation of a class
-// which inherits from NSObject then we know that all it's offsets also 
must
-// be fixed. FIXME: Can we do this if see a chain of super classes with
-// implementations leading to NSObject?
-return ID->getImplementation() && ID->getSuperClass() &&
-   ID->getSuperClass()->getName() == "NSObject";
+// Test a class by checking its superclasses up to its base class if it has
+// one
+while (ID) {
+  // The base class NSObject is a fixed size
+  if (ID->getName() == "NSObject")
+return true;
+
+  // If we cannot see the @implementation of a class, we cannot assume 
fixed
+  // offsets
+  if (!ID->getImplementation())
+return false;
+
+  // Test superclass
+  ID = ID->getSuperClass();
+}
+return false;
   }
 
 public:
diff --git a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m 
b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
index 40a97ba62ec6cf..c5bc2be0dfdb84 100644
--- a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
+++ b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
@@ -1,7 +1,7 @@
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 -emit-llvm %s -o - | 
FileCheck %s
 
 // CHECK: @"OBJC_IVAR_$_StaticLayout.static_layout_ivar" = hidden constant i64 
20
-// CHECK: @"OBJC_IVAR_$_StaticLayoutSubClass.static_layout_ivar2" = hidden 
global i64 24
+// CHECK: @"OBJC_IVAR_$_StaticLayoutSubClass.static_layout_ivar2" = hidden 
constant i64 24
 // CHECK: @"OBJC_IVAR_$_NotStaticLayout.not_static_layout_ivar" = hidden 
global i64 12
 
 @interface NSObject {
@@ -29,7 +29,7 @@ @implementation StaticLayoutSubClass {
 }
 -(void)meth2 {
   static_layout_ivar2 = 0;
-  // CHECK: load i64, ptr @"OBJC_IVAR_$_StaticLayoutSubClass
+  // CHECK-NOT: load i64, ptr @"OBJC_IVAR_$_StaticLayoutSubClass
 }
 @end
 

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


[clang] [Clang][Sema]: Allow copy constructor side effects (PR #81127)

2024-02-10 Thread Vinayak Dev via cfe-commits

vinayakdsci wrote:

> LGTM Make sure @cor3ntin is happy, too.

Thanks a lot! I have requested a review from @cor3ntin too. Thanks for your 
guidance!

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


[clang] [clang] Add -Wmissing-designated-field-initializers (PR #81364)

2024-02-10 Thread Vadim D. via cfe-commits

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


[clang] [ObjC] Recursively check superclasses to see if any inherit from NSObject (PR #81335)

2024-02-10 Thread via cfe-commits

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


[clang] [clang] Add -Wmissing-designated-field-initializers (PR #81364)

2024-02-10 Thread Vadim D. via cfe-commits

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


[clang] [ObjC] Check entire chain of superclasses to see if class has fixed offsets (PR #81335)

2024-02-10 Thread via cfe-commits

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


[clang] [clang] Add -Wmissing-designated-field-initializers (PR #81364)

2024-02-10 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Vadim D. (vvd170501)


Changes

Fixes  #68933.

#56628 changed the behavior of `-Wmissing-field-initializers`, which 
introduces many new warnings in C++ code that uses partial designated 
initializers. If such code is being built with `-Wextra -Werror`, this change 
will break the build.

This PR adds a new flag that allows to disable these new warnings, as was 
suggested by @AaronBallman in the original issue: 
https://github.com/llvm/llvm-project/issues/56628#issuecomment-1761510850

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


4 Files Affected:

- (modified) clang/include/clang/Basic/DiagnosticGroups.td (+9-1) 
- (modified) clang/include/clang/Basic/DiagnosticSemaKinds.td (+4) 
- (modified) clang/lib/Sema/SemaInit.cpp (+26-24) 
- (modified) clang/test/SemaCXX/cxx2a-initializer-aggregates.cpp (+6-5) 


``diff
diff --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index 975eca0ad9b642..bda533f77cc56a 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -516,7 +516,15 @@ def MethodSignatures : DiagGroup<"method-signatures">;
 def MismatchedParameterTypes : DiagGroup<"mismatched-parameter-types">;
 def MismatchedReturnTypes : DiagGroup<"mismatched-return-types">;
 def MismatchedTags : DiagGroup<"mismatched-tags">;
-def MissingFieldInitializers : DiagGroup<"missing-field-initializers">;
+def MissingDesignatedFieldInitializers : 
DiagGroup<"missing-designated-field-initializers">{
+  code Documentation = [{
+Warn about designated initializers with some fields missing (only in C++).
+  }];
+}
+// Default -Wmissing-field-initializers matches gcc behavior,
+// but missing-designated-field-initializers can be turned off to match old 
clang behavior.
+def MissingFieldInitializers : DiagGroup<"missing-field-initializers",
+ [MissingDesignatedFieldInitializers]>;
 def ModuleLock : DiagGroup<"module-lock">;
 def ModuleBuild : DiagGroup<"module-build">;
 def ModuleImport : DiagGroup<"module-import">;
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index b4dc4feee8e63a..69e197e26b9b45 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -6165,6 +6165,10 @@ def ext_initializer_string_for_char_array_too_long : 
ExtWarn<
 def warn_missing_field_initializers : Warning<
   "missing field %0 initializer">,
   InGroup, DefaultIgnore;
+// The same warning, but another group is needed to disable it separately.
+def warn_missing_designated_field_initializers : Warning<
+  "missing field %0 initializer">,
+  InGroup, DefaultIgnore;
 def warn_braces_around_init : Warning<
   "braces around %select{scalar |}0initializer">,
   InGroup>;
diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index b6de06464cd6f3..08aa50ebad331f 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -2227,8 +2227,6 @@ void InitListChecker::CheckStructUnionTypes(
   size_t NumRecordDecls = llvm::count_if(RD->decls(), [&](const Decl *D) {
 return isa(D) || isa(D);
   });
-  bool CheckForMissingFields =
-!IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts());
   bool HasDesignatedInit = false;
 
   llvm::SmallPtrSet InitializedFields;
@@ -2269,11 +2267,6 @@ void InitListChecker::CheckStructUnionTypes(
   }
 
   InitializedSomething = true;
-
-  // Disable check for missing fields when designators are used.
-  // This matches gcc behaviour.
-  if (!SemaRef.getLangOpts().CPlusPlus)
-CheckForMissingFields = false;
   continue;
 }
 
@@ -2285,7 +2278,7 @@ void InitListChecker::CheckStructUnionTypes(
 // These are okay for randomized structures. [C99 6.7.8p19]
 //
 // Also, if there is only one element in the structure, we allow something
-// like this, because it's really not randomized in the tranditional sense.
+// like this, because it's really not randomized in the traditional sense.
 //
 //   struct foo h = {bar};
 auto IsZeroInitializer = [&](const Expr *I) {
@@ -2363,23 +2356,32 @@ void InitListChecker::CheckStructUnionTypes(
   }
 
   // Emit warnings for missing struct field initializers.
-  if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
-  !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;
+  if (!VerifyOnly && InitializedSomething

[clang] [ObjC] Check entire chain of superclasses to see if class has fixed offsets (PR #81335)

2024-02-10 Thread via cfe-commits

https://github.com/AtariDreams updated 
https://github.com/llvm/llvm-project/pull/81335

>From 18987af24d2f53d00e2ac42998a8f1580e35afdf Mon Sep 17 00:00:00 2001
From: Rose <83477269+ataridre...@users.noreply.github.com>
Date: Fri, 9 Feb 2024 17:51:15 -0500
Subject: [PATCH 1/2] [ObjC] Add pre-commit tests [NFC]

---
 .../CodeGenObjC/constant-non-fragile-ivar-offset.m  | 13 +
 1 file changed, 13 insertions(+)

diff --git a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m 
b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
index 788b3220af3067..40a97ba62ec6cf 100644
--- a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
+++ b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
@@ -1,6 +1,7 @@
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 -emit-llvm %s -o - | 
FileCheck %s
 
 // CHECK: @"OBJC_IVAR_$_StaticLayout.static_layout_ivar" = hidden constant i64 
20
+// CHECK: @"OBJC_IVAR_$_StaticLayoutSubClass.static_layout_ivar2" = hidden 
global i64 24
 // CHECK: @"OBJC_IVAR_$_NotStaticLayout.not_static_layout_ivar" = hidden 
global i64 12
 
 @interface NSObject {
@@ -20,6 +21,18 @@ -(void)meth {
 }
 @end
 
+@interface StaticLayoutSubClass : StaticLayout
+@end
+
+@implementation StaticLayoutSubClass {
+  int static_layout_ivar2;
+}
+-(void)meth2 {
+  static_layout_ivar2 = 0;
+  // CHECK: load i64, ptr @"OBJC_IVAR_$_StaticLayoutSubClass
+}
+@end
+
 @interface NotNSObject {
   int these, might, change;
 }

>From 6f5944a577b45d6a9fb65e72c78cb55766c4f753 Mon Sep 17 00:00:00 2001
From: Rose <83477269+ataridre...@users.noreply.github.com>
Date: Fri, 9 Feb 2024 17:47:59 -0500
Subject: [PATCH 2/2] [ObjC] Check entire chain of superclasses to see if class
 has fixed offsets

As of now, we only check if a class directly inherits from NSObject to 
determine if said lass has fixed offsets and can therefore "opt-out" from the 
non-fragile ABI for ivars.

However, if an NSObject subclass has fixed offsets, then so must the subclasses 
of that subclass, so this allows us to optimize instances of subclasses of 
subclasses that inherit from NSObject and so on.
---
 clang/lib/CodeGen/CGObjCMac.cpp   | 22 ++-
 .../constant-non-fragile-ivar-offset.m|  4 ++--
 2 files changed, 18 insertions(+), 8 deletions(-)

diff --git a/clang/lib/CodeGen/CGObjCMac.cpp b/clang/lib/CodeGen/CGObjCMac.cpp
index 27d77e9a8a5511..ceee70a5d79b3e 100644
--- a/clang/lib/CodeGen/CGObjCMac.cpp
+++ b/clang/lib/CodeGen/CGObjCMac.cpp
@@ -1593,12 +1593,22 @@ class CGObjCNonFragileABIMac : public CGObjCCommonMac {
   }
 
   bool isClassLayoutKnownStatically(const ObjCInterfaceDecl *ID) {
-// NSObject is a fixed size. If we can see the @implementation of a class
-// which inherits from NSObject then we know that all it's offsets also 
must
-// be fixed. FIXME: Can we do this if see a chain of super classes with
-// implementations leading to NSObject?
-return ID->getImplementation() && ID->getSuperClass() &&
-   ID->getSuperClass()->getName() == "NSObject";
+// Test a class by checking its superclasses up to its base class if it has
+// one
+while (ID) {
+  // The base class NSObject is a fixed size
+  if (ID->getName() == "NSObject")
+return true;
+
+  // If we cannot see the @implementation of a class, we cannot assume 
fixed
+  // offsets
+  if (!ID->getImplementation())
+return false;
+
+  // Test superclass
+  ID = ID->getSuperClass();
+}
+return false;
   }
 
 public:
diff --git a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m 
b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
index 40a97ba62ec6cf..c5bc2be0dfdb84 100644
--- a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
+++ b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
@@ -1,7 +1,7 @@
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 -emit-llvm %s -o - | 
FileCheck %s
 
 // CHECK: @"OBJC_IVAR_$_StaticLayout.static_layout_ivar" = hidden constant i64 
20
-// CHECK: @"OBJC_IVAR_$_StaticLayoutSubClass.static_layout_ivar2" = hidden 
global i64 24
+// CHECK: @"OBJC_IVAR_$_StaticLayoutSubClass.static_layout_ivar2" = hidden 
constant i64 24
 // CHECK: @"OBJC_IVAR_$_NotStaticLayout.not_static_layout_ivar" = hidden 
global i64 12
 
 @interface NSObject {
@@ -29,7 +29,7 @@ @implementation StaticLayoutSubClass {
 }
 -(void)meth2 {
   static_layout_ivar2 = 0;
-  // CHECK: load i64, ptr @"OBJC_IVAR_$_StaticLayoutSubClass
+  // CHECK-NOT: load i64, ptr @"OBJC_IVAR_$_StaticLayoutSubClass
 }
 @end
 

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


[clang] [llvm] [MC/DC] Refactor: Make `MCDCParams` as `std::variant` (PR #81227)

2024-02-10 Thread NAKAMURA Takumi via cfe-commits

https://github.com/chapuni updated 
https://github.com/llvm/llvm-project/pull/81227

>From c2b49a5317bf5b8af419cba814f95cc9305bec21 Mon Sep 17 00:00:00 2001
From: NAKAMURA Takumi 
Date: Thu, 8 Feb 2024 23:12:54 +0900
Subject: [PATCH 1/2] [MC/DC] Refactor: Make `MCDCParams` as `std::variant`

Introduce `MCDCDecisionParameters` and `MCDCBranchParameters` and
make sure them not initialized as zero.

FIXME: Could we make `CoverageMappingRegion` as a smart tagged union?
---
 clang/lib/CodeGen/CoverageMappingGen.cpp  | 69 +
 .../ProfileData/Coverage/CoverageMapping.h| 77 ---
 .../ProfileData/Coverage/CoverageMapping.cpp  | 53 +++--
 .../Coverage/CoverageMappingReader.cpp| 17 ++--
 .../Coverage/CoverageMappingWriter.cpp| 23 --
 .../ProfileData/CoverageMappingTest.cpp   |  8 +-
 6 files changed, 149 insertions(+), 98 deletions(-)

diff --git a/clang/lib/CodeGen/CoverageMappingGen.cpp 
b/clang/lib/CodeGen/CoverageMappingGen.cpp
index 0c43317642bca4..da5d43cda91209 100644
--- a/clang/lib/CodeGen/CoverageMappingGen.cpp
+++ b/clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -97,6 +97,8 @@ void CoverageSourceInfo::updateNextTokLoc(SourceLocation Loc) 
{
 namespace {
 using MCDCConditionID = CounterMappingRegion::MCDCConditionID;
 using MCDCParameters = CounterMappingRegion::MCDCParameters;
+using MCDCBranchParameters = CounterMappingRegion::MCDCBranchParameters;
+using MCDCDecisionParameters = CounterMappingRegion::MCDCDecisionParameters;
 
 /// A region of source code that can be mapped to a counter.
 class SourceMappingRegion {
@@ -185,7 +187,17 @@ class SourceMappingRegion {
 
   bool isBranch() const { return FalseCount.has_value(); }
 
-  bool isMCDCDecision() const { return MCDCParams.NumConditions != 0; }
+  bool isMCDCDecision() const {
+const auto *DecisionParams =
+std::get_if(&MCDCParams);
+assert(!DecisionParams || DecisionParams->NumConditions > 0);
+return DecisionParams;
+  }
+
+  const auto &getMCDCDecisionParams() const {
+return CounterMappingRegion::getParams(
+MCDCParams);
+  }
 
   const MCDCParameters &getMCDCParams() const { return MCDCParams; }
 };
@@ -483,13 +495,13 @@ class CoverageMappingBuilder {
 SR.ColumnEnd));
   } else if (Region.isBranch()) {
 MappingRegions.push_back(CounterMappingRegion::makeBranchRegion(
-Region.getCounter(), Region.getFalseCounter(),
-Region.getMCDCParams(), *CovFileID, SR.LineStart, SR.ColumnStart,
-SR.LineEnd, SR.ColumnEnd));
+Region.getCounter(), Region.getFalseCounter(), *CovFileID,
+SR.LineStart, SR.ColumnStart, SR.LineEnd, SR.ColumnEnd,
+Region.getMCDCParams()));
   } else if (Region.isMCDCDecision()) {
 MappingRegions.push_back(CounterMappingRegion::makeDecisionRegion(
-Region.getMCDCParams(), *CovFileID, SR.LineStart, SR.ColumnStart,
-SR.LineEnd, SR.ColumnEnd));
+Region.getMCDCDecisionParams(), *CovFileID, SR.LineStart,
+SR.ColumnStart, SR.LineEnd, SR.ColumnEnd));
   } else {
 MappingRegions.push_back(CounterMappingRegion::makeRegion(
 Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
@@ -865,8 +877,7 @@ struct CounterCoverageMappingBuilder
 std::optional StartLoc = std::nullopt,
 std::optional EndLoc = std::nullopt,
 std::optional FalseCount = std::nullopt,
-MCDCConditionID ID = 0, MCDCConditionID TrueID = 0,
-MCDCConditionID FalseID = 0) {
+const MCDCParameters &BranchParams = std::monostate()) {
 
 if (StartLoc && !FalseCount) {
   MostRecentLocation = *StartLoc;
@@ -885,9 +896,7 @@ struct CounterCoverageMappingBuilder
   StartLoc = std::nullopt;
 if (EndLoc && EndLoc->isInvalid())
   EndLoc = std::nullopt;
-RegionStack.emplace_back(Count, FalseCount,
- MCDCParameters{0, 0, ID, TrueID, FalseID},
- StartLoc, EndLoc);
+RegionStack.emplace_back(Count, FalseCount, BranchParams, StartLoc, 
EndLoc);
 
 return RegionStack.size() - 1;
   }
@@ -896,8 +905,8 @@ struct CounterCoverageMappingBuilder
 std::optional StartLoc = std::nullopt,
 std::optional EndLoc = std::nullopt) {
 
-RegionStack.emplace_back(MCDCParameters{BitmapIdx, Conditions}, StartLoc,
- EndLoc);
+RegionStack.emplace_back(MCDCDecisionParameters{BitmapIdx, Conditions},
+ StartLoc, EndLoc);
 
 return RegionStack.size() - 1;
   }
@@ -1042,9 +1051,10 @@ struct CounterCoverageMappingBuilder
 // function's SourceRegions) because it doesn't apply to any other source
 // code other than the Condition.
 if (CodeGenFunction::isInstrumentedCondition(C)) {
+  MCDCParameters BranchParams;
   MCD

[clang] [clang] Add -Wmissing-designated-field-initializers (PR #81364)

2024-02-10 Thread Vadim D. via cfe-commits

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


[clang] [ObjC] Check entire chain of superclasses to see if class has fixed offsets (PR #81335)

2024-02-10 Thread via cfe-commits

AtariDreams wrote:

@rjmccall Do you think this is acceptable? 

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


[clang] b4c6ab6 - [clang][Interp][NFC] Don't use visitLocalInitializer in visitExpr

2024-02-10 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-02-10T18:01:30+01:00
New Revision: b4c6ab600f2ef6f3a842afee569dcf86bce7a43a

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

LOG: [clang][Interp][NFC] Don't use visitLocalInitializer in visitExpr

We were unnecessarily getting the pointer of the local variable twice.

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index aaa8ac834cf9fe..6993d751fe58f0 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -2555,10 +2555,13 @@ bool ByteCodeExprGen::visitExpr(const Expr *E) 
{
   // For us, that means everything we don't
   // have a PrimType for.
   if (std::optional LocalOffset = this->allocateLocal(E)) {
-if (!this->visitLocalInitializer(E, *LocalOffset))
+if (!this->emitGetPtrLocal(*LocalOffset, E))
   return false;
 
-if (!this->emitGetPtrLocal(*LocalOffset, E))
+if (!visitInitializer(E))
+  return false;
+
+if (!this->emitInitPtr(E))
   return false;
 return this->emitRetValue(E);
   }



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


[clang] [clang][modules] Print library module manifest path. (PR #76451)

2024-02-10 Thread Mark de Wever via cfe-commits

mordante wrote:

@kaz7 ping

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


[clang] d2e4a72 - [clang] Update Clang version from 18 to 19 in scan-build.1.

2024-02-10 Thread Frederic Cambus via cfe-commits

Author: Frederic Cambus
Date: 2024-02-10T18:16:08+01:00
New Revision: d2e4a725da5b4cbef8b5c1446f29fed1487aeab0

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

LOG: [clang] Update Clang version from 18 to 19 in scan-build.1.

Similar to D110763.

Added: 


Modified: 
clang/tools/scan-build/man/scan-build.1

Removed: 




diff  --git a/clang/tools/scan-build/man/scan-build.1 
b/clang/tools/scan-build/man/scan-build.1
index 29edbca1fc6388..e2b37f6062dbc0 100644
--- a/clang/tools/scan-build/man/scan-build.1
+++ b/clang/tools/scan-build/man/scan-build.1
@@ -2,9 +2,9 @@
 .\" See https://llvm.org/LICENSE.txt for license information.
 .\" SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
 .\" $Id$
-.Dd Sep 21, 2023
+.Dd Feb 10, 2024
 .Dt SCAN-BUILD 1
-.Os "clang" "18"
+.Os "clang" "19"
 .Sh NAME
 .Nm scan-build
 .Nd Clang static analyzer



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


[clang] [llvm] [TargetParser][AArch64] Add alias for FEAT_RDM. (PR #80540)

2024-02-10 Thread Jon Roelofs via cfe-commits


@@ -673,7 +673,7 @@ int hoo(void) {
 //
 //
 // CHECK: Function Attrs: noinline nounwind optnone
-// CHECK-LABEL: define {{[^@]+}}@fmv_inline._MlseMrdm
+// CHECK-LABEL: define {{[^@]+}}@fmv_inline._MlseMrdma

jroelofs wrote:

I think they are part of ABI, and giving them internal linkage is undesirable, 
IMO, as that would break an important use case: splitting the implementation 
across multiple TUs. https://godbolt.org/z/3zaM9MzPb

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


[clang] Resolve FIXME: Use HalfWidth and HalfAlign for shorts (PR #81367)

2024-02-10 Thread via cfe-commits

https://github.com/AtariDreams created 
https://github.com/llvm/llvm-project/pull/81367

Shorts are half an int, so HalfWidth and HalfAlign apply here.

>From b7c50bfa24abe51e73852667a6d972780dbf8cc2 Mon Sep 17 00:00:00 2001
From: Rose <83477269+ataridre...@users.noreply.github.com>
Date: Sat, 10 Feb 2024 12:35:20 -0500
Subject: [PATCH] Resolve FIXME: Use HalfWidth and HalfAlign for shorts

Shorts are half an int, so HalfWidth and HalfAlign apply here.
---
 clang/include/clang/Basic/TargetInfo.h | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/clang/include/clang/Basic/TargetInfo.h 
b/clang/include/clang/Basic/TargetInfo.h
index 48e9cec482755c..00851dc2fb0d07 100644
--- a/clang/include/clang/Basic/TargetInfo.h
+++ b/clang/include/clang/Basic/TargetInfo.h
@@ -489,11 +489,11 @@ class TargetInfo : public TransferrableTargetInfo,
 
   /// Return the size of 'signed short' and 'unsigned short' for this
   /// target, in bits.
-  unsigned getShortWidth() const { return 16; } // FIXME
+  unsigned getShortWidth() const { return HalfWidth; }
 
   /// Return the alignment of 'signed short' and 'unsigned short' for
   /// this target.
-  unsigned getShortAlign() const { return 16; } // FIXME
+  unsigned getShortAlign() const { return HalfAlign; }
 
   /// getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' 
for
   /// this target, in bits.

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


[clang] Resolve FIXME: Use HalfWidth and HalfAlign for shorts (PR #81367)

2024-02-10 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: AtariDreams (AtariDreams)


Changes

Shorts are half an int, so HalfWidth and HalfAlign apply here.

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


1 Files Affected:

- (modified) clang/include/clang/Basic/TargetInfo.h (+2-2) 


``diff
diff --git a/clang/include/clang/Basic/TargetInfo.h 
b/clang/include/clang/Basic/TargetInfo.h
index 48e9cec482755c..00851dc2fb0d07 100644
--- a/clang/include/clang/Basic/TargetInfo.h
+++ b/clang/include/clang/Basic/TargetInfo.h
@@ -489,11 +489,11 @@ class TargetInfo : public TransferrableTargetInfo,
 
   /// Return the size of 'signed short' and 'unsigned short' for this
   /// target, in bits.
-  unsigned getShortWidth() const { return 16; } // FIXME
+  unsigned getShortWidth() const { return HalfWidth; }
 
   /// Return the alignment of 'signed short' and 'unsigned short' for
   /// this target.
-  unsigned getShortAlign() const { return 16; } // FIXME
+  unsigned getShortAlign() const { return HalfAlign; }
 
   /// getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' 
for
   /// this target, in bits.

``




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


[clang] Resolve FIXME: Use HalfWidth and HalfAlign for shorts (PR #81367)

2024-02-10 Thread via cfe-commits

github-actions[bot] wrote:

⚠️ We detected that you are using a GitHub private e-mail address to contribute 
to the repo.
  Please turn off [Keep my email addresses 
private](https://github.com/settings/emails) setting in your account.
  See [LLVM 
Discourse](https://discourse.llvm.org/t/hidden-emails-on-github-should-we-do-something-about-it)
 for more information.


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


[clang] Resolve FIXME: Use HalfWidth and HalfAlign for shorts (PR #81367)

2024-02-10 Thread via cfe-commits

https://github.com/AtariDreams updated 
https://github.com/llvm/llvm-project/pull/81367

>From f12c08eb449781e782f84fc534d0bc6f8483e14f Mon Sep 17 00:00:00 2001
From: Rose <83477269+ataridre...@users.noreply.github.com>
Date: Sat, 10 Feb 2024 12:35:20 -0500
Subject: [PATCH] Resolve FIXME: Use HalfWidth and HalfAlign for shorts

Shorts are half an int, so HalfWidth and HalfAlign apply here.
---
 clang/include/clang/Basic/TargetInfo.h | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/clang/include/clang/Basic/TargetInfo.h 
b/clang/include/clang/Basic/TargetInfo.h
index 48e9cec482755c..00851dc2fb0d07 100644
--- a/clang/include/clang/Basic/TargetInfo.h
+++ b/clang/include/clang/Basic/TargetInfo.h
@@ -489,11 +489,11 @@ class TargetInfo : public TransferrableTargetInfo,
 
   /// Return the size of 'signed short' and 'unsigned short' for this
   /// target, in bits.
-  unsigned getShortWidth() const { return 16; } // FIXME
+  unsigned getShortWidth() const { return HalfWidth; }
 
   /// Return the alignment of 'signed short' and 'unsigned short' for
   /// this target.
-  unsigned getShortAlign() const { return 16; } // FIXME
+  unsigned getShortAlign() const { return HalfAlign; }
 
   /// getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' 
for
   /// this target, in bits.

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


[clang] [clang-tools-extra] In compilation databases, add support for relative directories (PR #69856)

2024-02-10 Thread via cfe-commits

https://github.com/Overhatted updated 
https://github.com/llvm/llvm-project/pull/69856

>From 071f8df3f82798255bcc0e2787fd7167b607d59f Mon Sep 17 00:00:00 2001
From: Overhatted <15021741+overhat...@users.noreply.github.com>
Date: Fri, 15 Dec 2023 15:53:56 +
Subject: [PATCH] In compilation databases, add support for relative
 directories

---
 .../clangd/GlobalCompilationDatabase.cpp  |  2 +-
 clang/docs/JSONCompilationDatabase.rst|  4 +++-
 .../clang/Tooling/JSONCompilationDatabase.h   | 10 
 clang/lib/Tooling/JSONCompilationDatabase.cpp | 24 ++-
 .../Tooling/CompilationDatabaseTest.cpp   | 10 
 5 files changed, 33 insertions(+), 17 deletions(-)

diff --git a/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp 
b/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
index 5bec7966a9c3a9..de017b78241ad3 100644
--- a/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
+++ b/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
@@ -245,7 +245,7 @@ 
DirectoryBasedGlobalCompilationDatabase::DirectoryCache::CachedFile::load(
 static std::unique_ptr
 parseJSON(PathRef Path, llvm::StringRef Data, std::string &Error) {
   if (auto CDB = tooling::JSONCompilationDatabase::loadFromBuffer(
-  Data, Error, tooling::JSONCommandLineSyntax::AutoDetect)) {
+  Path, Data, Error, tooling::JSONCommandLineSyntax::AutoDetect)) {
 // FS used for expanding response files.
 // FIXME: ExpandResponseFilesDatabase appears not to provide the usual
 // thread-safety guarantees, as the access to FS is not locked!
diff --git a/clang/docs/JSONCompilationDatabase.rst 
b/clang/docs/JSONCompilationDatabase.rst
index f5432278bd4d4e..41219a554dfdea 100644
--- a/clang/docs/JSONCompilationDatabase.rst
+++ b/clang/docs/JSONCompilationDatabase.rst
@@ -81,7 +81,9 @@ The contracts for each field in the command object are:
 
 -  **directory:** The working directory of the compilation. All paths
specified in the **command** or **file** fields must be either
-   absolute or relative to this directory.
+   absolute or relative to this directory. This field itself can be a
+   relative path in which case it is evaluated relative to the folder
+   containing the compilation database file.
 -  **file:** The main translation unit source processed by this
compilation step. This is used by tools as the key into the
compilation database. There can be multiple command objects for the
diff --git a/clang/include/clang/Tooling/JSONCompilationDatabase.h 
b/clang/include/clang/Tooling/JSONCompilationDatabase.h
index 96582457c63d58..3ec0e36c196d2e 100644
--- a/clang/include/clang/Tooling/JSONCompilationDatabase.h
+++ b/clang/include/clang/Tooling/JSONCompilationDatabase.h
@@ -72,8 +72,8 @@ class JSONCompilationDatabase : public CompilationDatabase {
   ///
   /// Returns NULL and sets ErrorMessage if the database could not be loaded.
   static std::unique_ptr
-  loadFromBuffer(StringRef DatabaseString, std::string &ErrorMessage,
- JSONCommandLineSyntax Syntax);
+  loadFromBuffer(StringRef FilePath, StringRef DatabaseString,
+ std::string &ErrorMessage, JSONCommandLineSyntax Syntax);
 
   /// Returns all compile commands in which the specified file was
   /// compiled.
@@ -94,9 +94,10 @@ class JSONCompilationDatabase : public CompilationDatabase {
 
 private:
   /// Constructs a JSON compilation database on a memory buffer.
-  JSONCompilationDatabase(std::unique_ptr Database,
+  JSONCompilationDatabase(SmallString<128> FolderPath,
+  std::unique_ptr Database,
   JSONCommandLineSyntax Syntax)
-  : Database(std::move(Database)), Syntax(Syntax),
+  : FolderPath(FolderPath), Database(std::move(Database)), Syntax(Syntax),
 YAMLStream(this->Database->getBuffer(), SM) {}
 
   /// Parses the database file and creates the index.
@@ -130,6 +131,7 @@ class JSONCompilationDatabase : public CompilationDatabase {
 
   FileMatchTrie MatchTrie;
 
+  SmallString<128> FolderPath;
   std::unique_ptr Database;
   JSONCommandLineSyntax Syntax;
   llvm::SourceMgr SM;
diff --git a/clang/lib/Tooling/JSONCompilationDatabase.cpp 
b/clang/lib/Tooling/JSONCompilationDatabase.cpp
index a77686996879f1..c8c7f46e1fb3e6 100644
--- a/clang/lib/Tooling/JSONCompilationDatabase.cpp
+++ b/clang/lib/Tooling/JSONCompilationDatabase.cpp
@@ -202,21 +202,26 @@ JSONCompilationDatabase::loadFromFile(StringRef FilePath,
 ErrorMessage = "Error while opening JSON database: " + Result.message();
 return nullptr;
   }
-  std::unique_ptr Database(
-  new JSONCompilationDatabase(std::move(*DatabaseBuffer), Syntax));
+  SmallString<128> FolderPath = FilePath;
+  llvm::sys::path::remove_filename(FolderPath);
+  std::unique_ptr Database(new 
JSONCompilationDatabase(
+  FolderPath, std::move(*DatabaseBuffer), Syntax));
   if (!Database->parse(ErrorMessage))
 return nullptr;
   return Database;
 }
 
 std::unique

[clang] [clang-tools-extra] In compilation databases, add support for relative directories (PR #69856)

2024-02-10 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-tools-extra

Author: None (Overhatted)


Changes

I haven't finished all of the tests and formatting so it's a bit in a POC stage 
but I would like to know if this change would be accepted.

The change is to support relative paths in the "directory" field in compilation 
databases. At the moment the specification doesn't seem to explicitly dissallow 
it but the implementation doesn't support it.

The use-case is I'm using Buck2 to generate the compilation databases which 
produces them with a "." for the directory field. Of course it could be changed 
on the Buck2 side but I think it would be useful to simply support relative 
paths on the clang side since it allows caching of the compilation database or 
maybe even commiting it to the repository.

Please let me know if this is an acceptable change or not.

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


5 Files Affected:

- (modified) clang-tools-extra/clangd/GlobalCompilationDatabase.cpp (+1-1) 
- (modified) clang/docs/JSONCompilationDatabase.rst (+3-1) 
- (modified) clang/include/clang/Tooling/JSONCompilationDatabase.h (+6-4) 
- (modified) clang/lib/Tooling/JSONCompilationDatabase.cpp (+18-6) 
- (modified) clang/unittests/Tooling/CompilationDatabaseTest.cpp (+5-5) 


``diff
diff --git a/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp 
b/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
index 5bec7966a9c3a9..de017b78241ad3 100644
--- a/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
+++ b/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
@@ -245,7 +245,7 @@ 
DirectoryBasedGlobalCompilationDatabase::DirectoryCache::CachedFile::load(
 static std::unique_ptr
 parseJSON(PathRef Path, llvm::StringRef Data, std::string &Error) {
   if (auto CDB = tooling::JSONCompilationDatabase::loadFromBuffer(
-  Data, Error, tooling::JSONCommandLineSyntax::AutoDetect)) {
+  Path, Data, Error, tooling::JSONCommandLineSyntax::AutoDetect)) {
 // FS used for expanding response files.
 // FIXME: ExpandResponseFilesDatabase appears not to provide the usual
 // thread-safety guarantees, as the access to FS is not locked!
diff --git a/clang/docs/JSONCompilationDatabase.rst 
b/clang/docs/JSONCompilationDatabase.rst
index f5432278bd4d4e..41219a554dfdea 100644
--- a/clang/docs/JSONCompilationDatabase.rst
+++ b/clang/docs/JSONCompilationDatabase.rst
@@ -81,7 +81,9 @@ The contracts for each field in the command object are:
 
 -  **directory:** The working directory of the compilation. All paths
specified in the **command** or **file** fields must be either
-   absolute or relative to this directory.
+   absolute or relative to this directory. This field itself can be a
+   relative path in which case it is evaluated relative to the folder
+   containing the compilation database file.
 -  **file:** The main translation unit source processed by this
compilation step. This is used by tools as the key into the
compilation database. There can be multiple command objects for the
diff --git a/clang/include/clang/Tooling/JSONCompilationDatabase.h 
b/clang/include/clang/Tooling/JSONCompilationDatabase.h
index 96582457c63d58..3ec0e36c196d2e 100644
--- a/clang/include/clang/Tooling/JSONCompilationDatabase.h
+++ b/clang/include/clang/Tooling/JSONCompilationDatabase.h
@@ -72,8 +72,8 @@ class JSONCompilationDatabase : public CompilationDatabase {
   ///
   /// Returns NULL and sets ErrorMessage if the database could not be loaded.
   static std::unique_ptr
-  loadFromBuffer(StringRef DatabaseString, std::string &ErrorMessage,
- JSONCommandLineSyntax Syntax);
+  loadFromBuffer(StringRef FilePath, StringRef DatabaseString,
+ std::string &ErrorMessage, JSONCommandLineSyntax Syntax);
 
   /// Returns all compile commands in which the specified file was
   /// compiled.
@@ -94,9 +94,10 @@ class JSONCompilationDatabase : public CompilationDatabase {
 
 private:
   /// Constructs a JSON compilation database on a memory buffer.
-  JSONCompilationDatabase(std::unique_ptr Database,
+  JSONCompilationDatabase(SmallString<128> FolderPath,
+  std::unique_ptr Database,
   JSONCommandLineSyntax Syntax)
-  : Database(std::move(Database)), Syntax(Syntax),
+  : FolderPath(FolderPath), Database(std::move(Database)), Syntax(Syntax),
 YAMLStream(this->Database->getBuffer(), SM) {}
 
   /// Parses the database file and creates the index.
@@ -130,6 +131,7 @@ class JSONCompilationDatabase : public CompilationDatabase {
 
   FileMatchTrie MatchTrie;
 
+  SmallString<128> FolderPath;
   std::unique_ptr Database;
   JSONCommandLineSyntax Syntax;
   llvm::SourceMgr SM;
diff --git a/clang/lib/Tooling/JSONCompilationDatabase.cpp 
b/clang/lib/Tooling/JSONCompilationDatabase.cpp
index a77686996879f1..c8c7f46e1fb3e6 100644
--- a/clang/lib/Tooling/JSONCompilationDatabase.cpp
+++ b/clang/lib/Tooling/JS

[clang] [clang-tools-extra] In compilation databases, add support for relative directories (PR #69856)

2024-02-10 Thread via cfe-commits

https://github.com/Overhatted updated 
https://github.com/llvm/llvm-project/pull/69856

>From 071f8df3f82798255bcc0e2787fd7167b607d59f Mon Sep 17 00:00:00 2001
From: Overhatted <15021741+overhat...@users.noreply.github.com>
Date: Fri, 15 Dec 2023 15:53:56 +
Subject: [PATCH] In compilation databases, add support for relative
 directories

---
 .../clangd/GlobalCompilationDatabase.cpp  |  2 +-
 clang/docs/JSONCompilationDatabase.rst|  4 +++-
 .../clang/Tooling/JSONCompilationDatabase.h   | 10 
 clang/lib/Tooling/JSONCompilationDatabase.cpp | 24 ++-
 .../Tooling/CompilationDatabaseTest.cpp   | 10 
 5 files changed, 33 insertions(+), 17 deletions(-)

diff --git a/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp 
b/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
index 5bec7966a9c3a9..de017b78241ad3 100644
--- a/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
+++ b/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
@@ -245,7 +245,7 @@ 
DirectoryBasedGlobalCompilationDatabase::DirectoryCache::CachedFile::load(
 static std::unique_ptr
 parseJSON(PathRef Path, llvm::StringRef Data, std::string &Error) {
   if (auto CDB = tooling::JSONCompilationDatabase::loadFromBuffer(
-  Data, Error, tooling::JSONCommandLineSyntax::AutoDetect)) {
+  Path, Data, Error, tooling::JSONCommandLineSyntax::AutoDetect)) {
 // FS used for expanding response files.
 // FIXME: ExpandResponseFilesDatabase appears not to provide the usual
 // thread-safety guarantees, as the access to FS is not locked!
diff --git a/clang/docs/JSONCompilationDatabase.rst 
b/clang/docs/JSONCompilationDatabase.rst
index f5432278bd4d4e..41219a554dfdea 100644
--- a/clang/docs/JSONCompilationDatabase.rst
+++ b/clang/docs/JSONCompilationDatabase.rst
@@ -81,7 +81,9 @@ The contracts for each field in the command object are:
 
 -  **directory:** The working directory of the compilation. All paths
specified in the **command** or **file** fields must be either
-   absolute or relative to this directory.
+   absolute or relative to this directory. This field itself can be a
+   relative path in which case it is evaluated relative to the folder
+   containing the compilation database file.
 -  **file:** The main translation unit source processed by this
compilation step. This is used by tools as the key into the
compilation database. There can be multiple command objects for the
diff --git a/clang/include/clang/Tooling/JSONCompilationDatabase.h 
b/clang/include/clang/Tooling/JSONCompilationDatabase.h
index 96582457c63d58..3ec0e36c196d2e 100644
--- a/clang/include/clang/Tooling/JSONCompilationDatabase.h
+++ b/clang/include/clang/Tooling/JSONCompilationDatabase.h
@@ -72,8 +72,8 @@ class JSONCompilationDatabase : public CompilationDatabase {
   ///
   /// Returns NULL and sets ErrorMessage if the database could not be loaded.
   static std::unique_ptr
-  loadFromBuffer(StringRef DatabaseString, std::string &ErrorMessage,
- JSONCommandLineSyntax Syntax);
+  loadFromBuffer(StringRef FilePath, StringRef DatabaseString,
+ std::string &ErrorMessage, JSONCommandLineSyntax Syntax);
 
   /// Returns all compile commands in which the specified file was
   /// compiled.
@@ -94,9 +94,10 @@ class JSONCompilationDatabase : public CompilationDatabase {
 
 private:
   /// Constructs a JSON compilation database on a memory buffer.
-  JSONCompilationDatabase(std::unique_ptr Database,
+  JSONCompilationDatabase(SmallString<128> FolderPath,
+  std::unique_ptr Database,
   JSONCommandLineSyntax Syntax)
-  : Database(std::move(Database)), Syntax(Syntax),
+  : FolderPath(FolderPath), Database(std::move(Database)), Syntax(Syntax),
 YAMLStream(this->Database->getBuffer(), SM) {}
 
   /// Parses the database file and creates the index.
@@ -130,6 +131,7 @@ class JSONCompilationDatabase : public CompilationDatabase {
 
   FileMatchTrie MatchTrie;
 
+  SmallString<128> FolderPath;
   std::unique_ptr Database;
   JSONCommandLineSyntax Syntax;
   llvm::SourceMgr SM;
diff --git a/clang/lib/Tooling/JSONCompilationDatabase.cpp 
b/clang/lib/Tooling/JSONCompilationDatabase.cpp
index a77686996879f1..c8c7f46e1fb3e6 100644
--- a/clang/lib/Tooling/JSONCompilationDatabase.cpp
+++ b/clang/lib/Tooling/JSONCompilationDatabase.cpp
@@ -202,21 +202,26 @@ JSONCompilationDatabase::loadFromFile(StringRef FilePath,
 ErrorMessage = "Error while opening JSON database: " + Result.message();
 return nullptr;
   }
-  std::unique_ptr Database(
-  new JSONCompilationDatabase(std::move(*DatabaseBuffer), Syntax));
+  SmallString<128> FolderPath = FilePath;
+  llvm::sys::path::remove_filename(FolderPath);
+  std::unique_ptr Database(new 
JSONCompilationDatabase(
+  FolderPath, std::move(*DatabaseBuffer), Syntax));
   if (!Database->parse(ErrorMessage))
 return nullptr;
   return Database;
 }
 
 std::unique

[clang] [clang-tools-extra] In compilation databases, add support for relative directories (PR #69856)

2024-02-10 Thread via cfe-commits

https://github.com/Overhatted updated 
https://github.com/llvm/llvm-project/pull/69856

>From cb57948468634e952d0c953fe0215fa15f030e28 Mon Sep 17 00:00:00 2001
From: Overhatted <15021741+overhat...@users.noreply.github.com>
Date: Fri, 15 Dec 2023 15:53:56 +
Subject: [PATCH] In compilation databases, add support for relative
 directories

---
 .../clangd/GlobalCompilationDatabase.cpp  |  2 +-
 clang/docs/JSONCompilationDatabase.rst|  4 +++-
 .../clang/Tooling/JSONCompilationDatabase.h   | 10 
 clang/lib/Tooling/JSONCompilationDatabase.cpp | 24 ++-
 .../Tooling/CompilationDatabaseTest.cpp   | 10 
 5 files changed, 33 insertions(+), 17 deletions(-)

diff --git a/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp 
b/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
index 5bec7966a9c3a9..de017b78241ad3 100644
--- a/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
+++ b/clang-tools-extra/clangd/GlobalCompilationDatabase.cpp
@@ -245,7 +245,7 @@ 
DirectoryBasedGlobalCompilationDatabase::DirectoryCache::CachedFile::load(
 static std::unique_ptr
 parseJSON(PathRef Path, llvm::StringRef Data, std::string &Error) {
   if (auto CDB = tooling::JSONCompilationDatabase::loadFromBuffer(
-  Data, Error, tooling::JSONCommandLineSyntax::AutoDetect)) {
+  Path, Data, Error, tooling::JSONCommandLineSyntax::AutoDetect)) {
 // FS used for expanding response files.
 // FIXME: ExpandResponseFilesDatabase appears not to provide the usual
 // thread-safety guarantees, as the access to FS is not locked!
diff --git a/clang/docs/JSONCompilationDatabase.rst 
b/clang/docs/JSONCompilationDatabase.rst
index f5432278bd4d4e..41219a554dfdea 100644
--- a/clang/docs/JSONCompilationDatabase.rst
+++ b/clang/docs/JSONCompilationDatabase.rst
@@ -81,7 +81,9 @@ The contracts for each field in the command object are:
 
 -  **directory:** The working directory of the compilation. All paths
specified in the **command** or **file** fields must be either
-   absolute or relative to this directory.
+   absolute or relative to this directory. This field itself can be a
+   relative path in which case it is evaluated relative to the folder
+   containing the compilation database file.
 -  **file:** The main translation unit source processed by this
compilation step. This is used by tools as the key into the
compilation database. There can be multiple command objects for the
diff --git a/clang/include/clang/Tooling/JSONCompilationDatabase.h 
b/clang/include/clang/Tooling/JSONCompilationDatabase.h
index 96582457c63d58..3ec0e36c196d2e 100644
--- a/clang/include/clang/Tooling/JSONCompilationDatabase.h
+++ b/clang/include/clang/Tooling/JSONCompilationDatabase.h
@@ -72,8 +72,8 @@ class JSONCompilationDatabase : public CompilationDatabase {
   ///
   /// Returns NULL and sets ErrorMessage if the database could not be loaded.
   static std::unique_ptr
-  loadFromBuffer(StringRef DatabaseString, std::string &ErrorMessage,
- JSONCommandLineSyntax Syntax);
+  loadFromBuffer(StringRef FilePath, StringRef DatabaseString,
+ std::string &ErrorMessage, JSONCommandLineSyntax Syntax);
 
   /// Returns all compile commands in which the specified file was
   /// compiled.
@@ -94,9 +94,10 @@ class JSONCompilationDatabase : public CompilationDatabase {
 
 private:
   /// Constructs a JSON compilation database on a memory buffer.
-  JSONCompilationDatabase(std::unique_ptr Database,
+  JSONCompilationDatabase(SmallString<128> FolderPath,
+  std::unique_ptr Database,
   JSONCommandLineSyntax Syntax)
-  : Database(std::move(Database)), Syntax(Syntax),
+  : FolderPath(FolderPath), Database(std::move(Database)), Syntax(Syntax),
 YAMLStream(this->Database->getBuffer(), SM) {}
 
   /// Parses the database file and creates the index.
@@ -130,6 +131,7 @@ class JSONCompilationDatabase : public CompilationDatabase {
 
   FileMatchTrie MatchTrie;
 
+  SmallString<128> FolderPath;
   std::unique_ptr Database;
   JSONCommandLineSyntax Syntax;
   llvm::SourceMgr SM;
diff --git a/clang/lib/Tooling/JSONCompilationDatabase.cpp 
b/clang/lib/Tooling/JSONCompilationDatabase.cpp
index a77686996879f1..c8c7f46e1fb3e6 100644
--- a/clang/lib/Tooling/JSONCompilationDatabase.cpp
+++ b/clang/lib/Tooling/JSONCompilationDatabase.cpp
@@ -202,21 +202,26 @@ JSONCompilationDatabase::loadFromFile(StringRef FilePath,
 ErrorMessage = "Error while opening JSON database: " + Result.message();
 return nullptr;
   }
-  std::unique_ptr Database(
-  new JSONCompilationDatabase(std::move(*DatabaseBuffer), Syntax));
+  SmallString<128> FolderPath = FilePath;
+  llvm::sys::path::remove_filename(FolderPath);
+  std::unique_ptr Database(new 
JSONCompilationDatabase(
+  FolderPath, std::move(*DatabaseBuffer), Syntax));
   if (!Database->parse(ErrorMessage))
 return nullptr;
   return Database;
 }
 
 std::unique

[clang] [clang] Resolve FIXME: Use HalfWidth and HalfAlign for shorts (PR #81367)

2024-02-10 Thread via cfe-commits

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


[clang] [clang] Resolve FIXME: Use HalfWidth and HalfAlign for shorts (PR #81367)

2024-02-10 Thread via cfe-commits

https://github.com/AtariDreams updated 
https://github.com/llvm/llvm-project/pull/81367

>From ebd724f537fe0f7c1ad468d15bb13245c7d56d9f Mon Sep 17 00:00:00 2001
From: Rose <83477269+ataridre...@users.noreply.github.com>
Date: Sat, 10 Feb 2024 12:35:20 -0500
Subject: [PATCH] [clang] Resolve FIXME: Use HalfWidth and HalfAlign for shorts

Shorts are half an int, so HalfWidth and HalfAlign apply here.
---
 clang/include/clang/Basic/TargetInfo.h | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/clang/include/clang/Basic/TargetInfo.h 
b/clang/include/clang/Basic/TargetInfo.h
index 48e9cec482755c..00851dc2fb0d07 100644
--- a/clang/include/clang/Basic/TargetInfo.h
+++ b/clang/include/clang/Basic/TargetInfo.h
@@ -489,11 +489,11 @@ class TargetInfo : public TransferrableTargetInfo,
 
   /// Return the size of 'signed short' and 'unsigned short' for this
   /// target, in bits.
-  unsigned getShortWidth() const { return 16; } // FIXME
+  unsigned getShortWidth() const { return HalfWidth; }
 
   /// Return the alignment of 'signed short' and 'unsigned short' for
   /// this target.
-  unsigned getShortAlign() const { return 16; } // FIXME
+  unsigned getShortAlign() const { return HalfAlign; }
 
   /// getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' 
for
   /// this target, in bits.

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


[clang] [ObjC] Check entire chain of superclasses to see if class has fixed offsets (PR #81335)

2024-02-10 Thread via cfe-commits

https://github.com/AtariDreams updated 
https://github.com/llvm/llvm-project/pull/81335

>From 70c646a54852f33306ff567b5cb125558e2b9529 Mon Sep 17 00:00:00 2001
From: Rose <83477269+ataridre...@users.noreply.github.com>
Date: Fri, 9 Feb 2024 17:51:15 -0500
Subject: [PATCH 1/2] [ObjC] Add pre-commit tests [NFC]

---
 .../CodeGenObjC/constant-non-fragile-ivar-offset.m  | 13 +
 1 file changed, 13 insertions(+)

diff --git a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m 
b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
index 788b3220af3067..40a97ba62ec6cf 100644
--- a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
+++ b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
@@ -1,6 +1,7 @@
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 -emit-llvm %s -o - | 
FileCheck %s
 
 // CHECK: @"OBJC_IVAR_$_StaticLayout.static_layout_ivar" = hidden constant i64 
20
+// CHECK: @"OBJC_IVAR_$_StaticLayoutSubClass.static_layout_ivar2" = hidden 
global i64 24
 // CHECK: @"OBJC_IVAR_$_NotStaticLayout.not_static_layout_ivar" = hidden 
global i64 12
 
 @interface NSObject {
@@ -20,6 +21,18 @@ -(void)meth {
 }
 @end
 
+@interface StaticLayoutSubClass : StaticLayout
+@end
+
+@implementation StaticLayoutSubClass {
+  int static_layout_ivar2;
+}
+-(void)meth2 {
+  static_layout_ivar2 = 0;
+  // CHECK: load i64, ptr @"OBJC_IVAR_$_StaticLayoutSubClass
+}
+@end
+
 @interface NotNSObject {
   int these, might, change;
 }

>From f196660a9cebcfefed3a0ba68b8024e30698ea15 Mon Sep 17 00:00:00 2001
From: Rose <83477269+ataridre...@users.noreply.github.com>
Date: Fri, 9 Feb 2024 17:47:59 -0500
Subject: [PATCH 2/2] [ObjC] Check entire chain of superclasses to see if class
 has fixed offsets

As of now, we only check if a class directly inherits from NSObject to 
determine if said lass has fixed offsets and can therefore "opt-out" from the 
non-fragile ABI for ivars.

However, if an NSObject subclass has fixed offsets, then so must the subclasses 
of that subclass, so this allows us to optimize instances of subclasses of 
subclasses that inherit from NSObject and so on.

Fixes: #81369
---
 clang/lib/CodeGen/CGObjCMac.cpp   | 22 ++-
 .../constant-non-fragile-ivar-offset.m|  4 ++--
 2 files changed, 18 insertions(+), 8 deletions(-)

diff --git a/clang/lib/CodeGen/CGObjCMac.cpp b/clang/lib/CodeGen/CGObjCMac.cpp
index 27d77e9a8a5511..ceee70a5d79b3e 100644
--- a/clang/lib/CodeGen/CGObjCMac.cpp
+++ b/clang/lib/CodeGen/CGObjCMac.cpp
@@ -1593,12 +1593,22 @@ class CGObjCNonFragileABIMac : public CGObjCCommonMac {
   }
 
   bool isClassLayoutKnownStatically(const ObjCInterfaceDecl *ID) {
-// NSObject is a fixed size. If we can see the @implementation of a class
-// which inherits from NSObject then we know that all it's offsets also 
must
-// be fixed. FIXME: Can we do this if see a chain of super classes with
-// implementations leading to NSObject?
-return ID->getImplementation() && ID->getSuperClass() &&
-   ID->getSuperClass()->getName() == "NSObject";
+// Test a class by checking its superclasses up to its base class if it has
+// one
+while (ID) {
+  // The base class NSObject is a fixed size
+  if (ID->getName() == "NSObject")
+return true;
+
+  // If we cannot see the @implementation of a class, we cannot assume 
fixed
+  // offsets
+  if (!ID->getImplementation())
+return false;
+
+  // Test superclass
+  ID = ID->getSuperClass();
+}
+return false;
   }
 
 public:
diff --git a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m 
b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
index 40a97ba62ec6cf..c5bc2be0dfdb84 100644
--- a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
+++ b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
@@ -1,7 +1,7 @@
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 -emit-llvm %s -o - | 
FileCheck %s
 
 // CHECK: @"OBJC_IVAR_$_StaticLayout.static_layout_ivar" = hidden constant i64 
20
-// CHECK: @"OBJC_IVAR_$_StaticLayoutSubClass.static_layout_ivar2" = hidden 
global i64 24
+// CHECK: @"OBJC_IVAR_$_StaticLayoutSubClass.static_layout_ivar2" = hidden 
constant i64 24
 // CHECK: @"OBJC_IVAR_$_NotStaticLayout.not_static_layout_ivar" = hidden 
global i64 12
 
 @interface NSObject {
@@ -29,7 +29,7 @@ @implementation StaticLayoutSubClass {
 }
 -(void)meth2 {
   static_layout_ivar2 = 0;
-  // CHECK: load i64, ptr @"OBJC_IVAR_$_StaticLayoutSubClass
+  // CHECK-NOT: load i64, ptr @"OBJC_IVAR_$_StaticLayoutSubClass
 }
 @end
 

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


[clang] [ObjC] Check entire chain of superclasses to see if class has fixed offsets (PR #81335)

2024-02-10 Thread via cfe-commits

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


[clang] Avoid printing overly large integer. (PR #75902)

2024-02-10 Thread Nhat Nguyen via cfe-commits
=?utf-8?q?“Nhat?= ,
=?utf-8?q?“Nhat?= ,
=?utf-8?q?“Nhat?= ,
=?utf-8?q?“Nhat?= ,
=?utf-8?q?“Nhat?= 
Message-ID:
In-Reply-To: 


https://github.com/changkhothuychung updated 
https://github.com/llvm/llvm-project/pull/75902

>From 4939edb1cb2b73f9c60c4cce0803fab4888beb6e Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E2=80=9CNhat?= 
Date: Mon, 1 Jan 2024 20:59:26 -0500
Subject: [PATCH 1/6] return false if the value is too large

---
 clang/lib/Sema/SemaDeclCXX.cpp | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index a3f68d4ffc0f6e..18631ec7dac152 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -17132,6 +17132,9 @@ static bool ConvertAPValueToString(const APValue &V, 
QualType T,
 case BuiltinType::WChar_U: {
   unsigned TyWidth = Context.getIntWidth(T);
   assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
+  if (V.getInt() >= (1 << 64)) {
+return false;
+  }
   uint32_t CodeUnit = static_cast(V.getInt().getZExtValue());
   WriteCharTypePrefix(BTy->getKind(), OS);
   OS << '\'';

>From 1932765f174e187a79144c4fd69657dc7bae480a Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E2=80=9CNhat?= 
Date: Mon, 1 Jan 2024 20:59:27 -0500
Subject: [PATCH 2/6] Update clang/lib/Sema/SemaDeclCXX.cpp

Co-authored-by: Yueh-Shun Li 
---
 clang/lib/Sema/SemaDeclCXX.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 18631ec7dac152..196e32a4a349f2 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -17132,7 +17132,7 @@ static bool ConvertAPValueToString(const APValue &V, 
QualType T,
 case BuiltinType::WChar_U: {
   unsigned TyWidth = Context.getIntWidth(T);
   assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
-  if (V.getInt() >= (1 << 64)) {
+  if (V.getInt() > std::numeric_limits::max() || V.getInt() 
< std::numeric_limits::min()) {
 return false;
   }
   uint32_t CodeUnit = static_cast(V.getInt().getZExtValue());

>From 69e21b2bf76b51914f835c74af9e2b3c685ffae0 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E2=80=9CNhat?= 
Date: Mon, 1 Jan 2024 20:59:28 -0500
Subject: [PATCH 3/6] clang format

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

diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 196e32a4a349f2..323890b38daeec 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -17132,7 +17132,8 @@ static bool ConvertAPValueToString(const APValue &V, 
QualType T,
 case BuiltinType::WChar_U: {
   unsigned TyWidth = Context.getIntWidth(T);
   assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
-  if (V.getInt() > std::numeric_limits::max() || V.getInt() 
< std::numeric_limits::min()) {
+  if (V.getInt() > std::numeric_limits::max() || 
+  V.getInt() < std::numeric_limits::min()) {
 return false;
   }
   uint32_t CodeUnit = static_cast(V.getInt().getZExtValue());

>From ac93beb74cbe6e0cb6383ece6b72b59b00aeca0d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E2=80=9CNhat?= 
Date: Mon, 1 Jan 2024 20:59:29 -0500
Subject: [PATCH 4/6] clang format

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

diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 323890b38daeec..80e6cd9ee07420 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -17132,7 +17132,7 @@ static bool ConvertAPValueToString(const APValue &V, 
QualType T,
 case BuiltinType::WChar_U: {
   unsigned TyWidth = Context.getIntWidth(T);
   assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
-  if (V.getInt() > std::numeric_limits::max() || 
+  if (V.getInt() > std::numeric_limits::max() ||
   V.getInt() < std::numeric_limits::min()) {
 return false;
   }

>From 35773add17d8b4e884daac0e3e7dc312f1947911 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E2=80=9CNhat?= 
Date: Mon, 1 Jan 2024 21:09:21 -0500
Subject: [PATCH 5/6] move the condition right under toString

---
 clang/lib/Sema/SemaDeclCXX.cpp | 8 
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 80e6cd9ee07420..d3b68c9aa95645 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -17132,10 +17132,6 @@ static bool ConvertAPValueToString(const APValue &V, 
QualType T,
 case BuiltinType::WChar_U: {
   unsigned TyWidth = Context.getIntWidth(T);
   assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
-  if 

[clang] ba451c8 - [clang][Interp][NFC] Only set result invalid if empty

2024-02-10 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-02-10T19:45:10+01:00
New Revision: ba451c80ba67ab6834305f35d47e36b6b446ce83

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

LOG: [clang][Interp][NFC] Only set result invalid if empty

This is currently NFC but required for later changes. A Ret op
might fail and set the result to invalid, causing another setInvalid()
call, which asserts that the result is still empty.

Added: 


Modified: 
clang/lib/AST/Interp/EvalEmitter.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/EvalEmitter.cpp 
b/clang/lib/AST/Interp/EvalEmitter.cpp
index a60f893de8bda7..945b78d7a609d7 100644
--- a/clang/lib/AST/Interp/EvalEmitter.cpp
+++ b/clang/lib/AST/Interp/EvalEmitter.cpp
@@ -36,7 +36,7 @@ EvalEmitter::~EvalEmitter() {
 EvaluationResult EvalEmitter::interpretExpr(const Expr *E) {
   EvalResult.setSource(E);
 
-  if (!this->visitExpr(E))
+  if (!this->visitExpr(E) && EvalResult.empty())
 EvalResult.setInvalid();
 
   return std::move(this->EvalResult);
@@ -45,7 +45,7 @@ EvaluationResult EvalEmitter::interpretExpr(const Expr *E) {
 EvaluationResult EvalEmitter::interpretDecl(const VarDecl *VD) {
   EvalResult.setSource(VD);
 
-  if (!this->visitDecl(VD))
+  if (!this->visitDecl(VD) && EvalResult.empty())
 EvalResult.setInvalid();
 
   return std::move(this->EvalResult);



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


[clang] [clang] Resolve FIXME: Use HalfWidth and HalfAlign for shorts (PR #81367)

2024-02-10 Thread Sergei Barannikov via cfe-commits

s-barannikov wrote:

> Shorts are half an int, so HalfWidth and HalfAlign apply here.

This is not true for our downstream target where `short` has the same width as 
`int` (note that the standard allows it).
It would be better to introduce `ShortWidth` / `ShortAlign` fields and 
initialize them to 16 by default.


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


[clang] bc034ba - [clang][Interp] Protect InitPtr from non-initializable pointers

2024-02-10 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-02-10T19:45:10+01:00
New Revision: bc034baaff1f6ce4e18b68c20df3be45bfb5104f

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

LOG: [clang][Interp] Protect InitPtr from non-initializable pointers

This can happen when an initializer returns a dummy pointer.

Added: 
clang/test/AST/Interp/complex.c

Modified: 
clang/lib/AST/Interp/Interp.h

Removed: 




diff  --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index 290edc07fdc87a..15c137098af355 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -1278,13 +1278,16 @@ inline bool GetPtrThisBase(InterpState &S, CodePtr 
OpPC, uint32_t Off) {
 
 inline bool InitPtrPop(InterpState &S, CodePtr OpPC) {
   const Pointer &Ptr = S.Stk.pop();
-  Ptr.initialize();
+  if (Ptr.canBeInitialized())
+Ptr.initialize();
   return true;
 }
 
 inline bool InitPtr(InterpState &S, CodePtr OpPC) {
   const Pointer &Ptr = S.Stk.peek();
-  Ptr.initialize();
+
+  if (Ptr.canBeInitialized())
+Ptr.initialize();
   return true;
 }
 

diff  --git a/clang/test/AST/Interp/complex.c b/clang/test/AST/Interp/complex.c
new file mode 100644
index 00..b07d0241da12d6
--- /dev/null
+++ b/clang/test/AST/Interp/complex.c
@@ -0,0 +1,14 @@
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter 
-verify=expected,both -Wno-unused-value %s
+// RUN: %clang_cc1 -verify=ref,both -Wno-unused-value %s
+
+// expected-no-diagnostics
+// ref-no-diagnostics
+
+void blah() {
+  __complex__ unsigned xx;
+  __complex__ signed yy;
+  __complex__ int result;
+
+  /// The following line calls into the constant interpreter.
+  result = xx * yy;
+}



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


[clang] [clang] Refactor `IdentifierInfo::ObjcOrBuiltinID` (PR #71709)

2024-02-10 Thread Vlad Serebrennikov via cfe-commits

https://github.com/Endilll updated 
https://github.com/llvm/llvm-project/pull/71709

>From 2823d38544d18213b5bf48c67e4eedd52acce850 Mon Sep 17 00:00:00 2001
From: Vlad Serebrennikov 
Date: Wed, 8 Nov 2023 20:30:37 +0300
Subject: [PATCH 1/4] [clang] Refactor `IdentifierInfo::ObjcOrBuiltinID`

This patch refactors how values are stored inside 
`IdentifierInfo::ObjcOrBuiltinID` bit-field, and annotates it with 
`preferred_type`. In order to make the value easier to interpret by debuggers, 
a new `ObjCKeywordOrInterestingOrBuiltin` is added. Previous "layout" of this 
fields couldn't be represented with this new enum, because it skipped over some 
arbitrary enumerators, so a new "layout" was invented based on 
`ObjCKeywordOrInterestingOrBuiltin` enum. I believe the new layout is simpler 
than the new one.
---
 clang/include/clang/Basic/IdentifierTable.h | 117 
 1 file changed, 73 insertions(+), 44 deletions(-)

diff --git a/clang/include/clang/Basic/IdentifierTable.h 
b/clang/include/clang/Basic/IdentifierTable.h
index 0898e7d39dd7de..fa76228da2b143 100644
--- a/clang/include/clang/Basic/IdentifierTable.h
+++ b/clang/include/clang/Basic/IdentifierTable.h
@@ -15,6 +15,7 @@
 #ifndef LLVM_CLANG_BASIC_IDENTIFIERTABLE_H
 #define LLVM_CLANG_BASIC_IDENTIFIERTABLE_H
 
+#include "clang/Basic/Builtins.h"
 #include "clang/Basic/DiagnosticIDs.h"
 #include "clang/Basic/LLVM.h"
 #include "clang/Basic/TokenKinds.h"
@@ -86,19 +87,26 @@ enum { IdentifierInfoAlignment = 8 };
 static constexpr int ObjCOrBuiltinIDBits = 16;
 
 /// The "layout" of ObjCOrBuiltinID is:
-///  - The first value (0) represents "not a special identifier".
-///  - The next (NUM_OBJC_KEYWORDS - 1) values represent ObjCKeywordKinds (not
-///including objc_not_keyword).
-///  - The next (NUM_INTERESTING_IDENTIFIERS - 1) values represent
-///InterestingIdentifierKinds (not including not_interesting).
-///  - The rest of the values represent builtin IDs (not including NotBuiltin).
-static constexpr int FirstObjCKeywordID = 1;
-static constexpr int LastObjCKeywordID =
-FirstObjCKeywordID + tok::NUM_OBJC_KEYWORDS - 2;
-static constexpr int FirstInterestingIdentifierID = LastObjCKeywordID + 1;
-static constexpr int LastInterestingIdentifierID =
-FirstInterestingIdentifierID + tok::NUM_INTERESTING_IDENTIFIERS - 2;
-static constexpr int FirstBuiltinID = LastInterestingIdentifierID + 1;
+///  - ObjCKeywordKind enumerators
+///  - InterestingIdentifierKind enumerators
+///  - Builtin::ID enumerators
+///  - NonSpecialIdentifier
+enum class ObjCKeywordOrInterestingOrBuiltin {
+#define OBJC_AT_KEYWORD(X) objc_##X,
+#include "clang/Basic/TokenKinds.def"
+  NUM_OBJC_KEYWORDS,
+
+#define INTERESTING_IDENTIFIER(X) X,
+#include "clang/Basic/TokenKinds.def"
+  NUM_OBJC_KEYWORDS_AND_INTERESTING_IDENTIFIERS,
+
+  NotBuiltin,
+#define BUILTIN(ID, TYPE, ATTRS) BI##ID,
+#include "clang/Basic/Builtins.def"
+  FirstTSBuiltin,
+
+  NonSpecialIdentifier = 65534
+};
 
 /// One of these records is kept for each identifier that
 /// is lexed.  This contains information about whether the token was 
\#define'd,
@@ -113,9 +121,7 @@ class alignas(IdentifierInfoAlignment) IdentifierInfo {
   LLVM_PREFERRED_TYPE(tok::TokenKind)
   unsigned TokenID : 9;
 
-  // ObjC keyword ('protocol' in '@protocol') or builtin (__builtin_inf).
-  // First NUM_OBJC_KEYWORDS values are for Objective-C,
-  // the remaining values are for builtins.
+  LLVM_PREFERRED_TYPE(ObjCKeywordOrInterestingOrBuiltin)
   unsigned ObjCOrBuiltinID : ObjCOrBuiltinIDBits;
 
   // True if there is a #define for this.
@@ -198,13 +204,16 @@ class alignas(IdentifierInfoAlignment) IdentifierInfo {
   llvm::StringMapEntry *Entry = nullptr;
 
   IdentifierInfo()
-  : TokenID(tok::identifier), ObjCOrBuiltinID(0), HasMacro(false),
-HadMacro(false), IsExtension(false), IsFutureCompatKeyword(false),
-IsPoisoned(false), IsCPPOperatorKeyword(false),
-NeedsHandleIdentifier(false), IsFromAST(false), 
ChangedAfterLoad(false),
-FEChangedAfterLoad(false), RevertedTokenID(false), OutOfDate(false),
-IsModulesImport(false), IsMangledOpenMPVariantName(false),
-IsDeprecatedMacro(false), IsRestrictExpansion(false), IsFinal(false) {}
+  : TokenID(tok::identifier),
+ObjCOrBuiltinID(llvm::to_underlying(
+ObjCKeywordOrInterestingOrBuiltin::NonSpecialIdentifier)),
+HasMacro(false), HadMacro(false), IsExtension(false),
+IsFutureCompatKeyword(false), IsPoisoned(false),
+IsCPPOperatorKeyword(false), NeedsHandleIdentifier(false),
+IsFromAST(false), ChangedAfterLoad(false), FEChangedAfterLoad(false),
+RevertedTokenID(false), OutOfDate(false), IsModulesImport(false),
+IsMangledOpenMPVariantName(false), IsDeprecatedMacro(false),
+IsRestrictExpansion(false), IsFinal(false) {}
 
 public:
   IdentifierInfo(const IdentifierInfo &) = delete;
@@ -332,42 +341,62 @@ class alignas(IdentifierInfoAlignment) 

[clang] [llvm] [HLSL] Implementation of dot intrinsic (PR #81190)

2024-02-10 Thread Farzon Lotfi via cfe-commits

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


[clang] [clang] Refactor `IdentifierInfo::ObjcOrBuiltinID` (PR #71709)

2024-02-10 Thread Vlad Serebrennikov via cfe-commits

https://github.com/Endilll updated 
https://github.com/llvm/llvm-project/pull/71709

>From 2823d38544d18213b5bf48c67e4eedd52acce850 Mon Sep 17 00:00:00 2001
From: Vlad Serebrennikov 
Date: Wed, 8 Nov 2023 20:30:37 +0300
Subject: [PATCH 1/4] [clang] Refactor `IdentifierInfo::ObjcOrBuiltinID`

This patch refactors how values are stored inside 
`IdentifierInfo::ObjcOrBuiltinID` bit-field, and annotates it with 
`preferred_type`. In order to make the value easier to interpret by debuggers, 
a new `ObjCKeywordOrInterestingOrBuiltin` is added. Previous "layout" of this 
fields couldn't be represented with this new enum, because it skipped over some 
arbitrary enumerators, so a new "layout" was invented based on 
`ObjCKeywordOrInterestingOrBuiltin` enum. I believe the new layout is simpler 
than the new one.
---
 clang/include/clang/Basic/IdentifierTable.h | 117 
 1 file changed, 73 insertions(+), 44 deletions(-)

diff --git a/clang/include/clang/Basic/IdentifierTable.h 
b/clang/include/clang/Basic/IdentifierTable.h
index 0898e7d39dd7de..fa76228da2b143 100644
--- a/clang/include/clang/Basic/IdentifierTable.h
+++ b/clang/include/clang/Basic/IdentifierTable.h
@@ -15,6 +15,7 @@
 #ifndef LLVM_CLANG_BASIC_IDENTIFIERTABLE_H
 #define LLVM_CLANG_BASIC_IDENTIFIERTABLE_H
 
+#include "clang/Basic/Builtins.h"
 #include "clang/Basic/DiagnosticIDs.h"
 #include "clang/Basic/LLVM.h"
 #include "clang/Basic/TokenKinds.h"
@@ -86,19 +87,26 @@ enum { IdentifierInfoAlignment = 8 };
 static constexpr int ObjCOrBuiltinIDBits = 16;
 
 /// The "layout" of ObjCOrBuiltinID is:
-///  - The first value (0) represents "not a special identifier".
-///  - The next (NUM_OBJC_KEYWORDS - 1) values represent ObjCKeywordKinds (not
-///including objc_not_keyword).
-///  - The next (NUM_INTERESTING_IDENTIFIERS - 1) values represent
-///InterestingIdentifierKinds (not including not_interesting).
-///  - The rest of the values represent builtin IDs (not including NotBuiltin).
-static constexpr int FirstObjCKeywordID = 1;
-static constexpr int LastObjCKeywordID =
-FirstObjCKeywordID + tok::NUM_OBJC_KEYWORDS - 2;
-static constexpr int FirstInterestingIdentifierID = LastObjCKeywordID + 1;
-static constexpr int LastInterestingIdentifierID =
-FirstInterestingIdentifierID + tok::NUM_INTERESTING_IDENTIFIERS - 2;
-static constexpr int FirstBuiltinID = LastInterestingIdentifierID + 1;
+///  - ObjCKeywordKind enumerators
+///  - InterestingIdentifierKind enumerators
+///  - Builtin::ID enumerators
+///  - NonSpecialIdentifier
+enum class ObjCKeywordOrInterestingOrBuiltin {
+#define OBJC_AT_KEYWORD(X) objc_##X,
+#include "clang/Basic/TokenKinds.def"
+  NUM_OBJC_KEYWORDS,
+
+#define INTERESTING_IDENTIFIER(X) X,
+#include "clang/Basic/TokenKinds.def"
+  NUM_OBJC_KEYWORDS_AND_INTERESTING_IDENTIFIERS,
+
+  NotBuiltin,
+#define BUILTIN(ID, TYPE, ATTRS) BI##ID,
+#include "clang/Basic/Builtins.def"
+  FirstTSBuiltin,
+
+  NonSpecialIdentifier = 65534
+};
 
 /// One of these records is kept for each identifier that
 /// is lexed.  This contains information about whether the token was 
\#define'd,
@@ -113,9 +121,7 @@ class alignas(IdentifierInfoAlignment) IdentifierInfo {
   LLVM_PREFERRED_TYPE(tok::TokenKind)
   unsigned TokenID : 9;
 
-  // ObjC keyword ('protocol' in '@protocol') or builtin (__builtin_inf).
-  // First NUM_OBJC_KEYWORDS values are for Objective-C,
-  // the remaining values are for builtins.
+  LLVM_PREFERRED_TYPE(ObjCKeywordOrInterestingOrBuiltin)
   unsigned ObjCOrBuiltinID : ObjCOrBuiltinIDBits;
 
   // True if there is a #define for this.
@@ -198,13 +204,16 @@ class alignas(IdentifierInfoAlignment) IdentifierInfo {
   llvm::StringMapEntry *Entry = nullptr;
 
   IdentifierInfo()
-  : TokenID(tok::identifier), ObjCOrBuiltinID(0), HasMacro(false),
-HadMacro(false), IsExtension(false), IsFutureCompatKeyword(false),
-IsPoisoned(false), IsCPPOperatorKeyword(false),
-NeedsHandleIdentifier(false), IsFromAST(false), 
ChangedAfterLoad(false),
-FEChangedAfterLoad(false), RevertedTokenID(false), OutOfDate(false),
-IsModulesImport(false), IsMangledOpenMPVariantName(false),
-IsDeprecatedMacro(false), IsRestrictExpansion(false), IsFinal(false) {}
+  : TokenID(tok::identifier),
+ObjCOrBuiltinID(llvm::to_underlying(
+ObjCKeywordOrInterestingOrBuiltin::NonSpecialIdentifier)),
+HasMacro(false), HadMacro(false), IsExtension(false),
+IsFutureCompatKeyword(false), IsPoisoned(false),
+IsCPPOperatorKeyword(false), NeedsHandleIdentifier(false),
+IsFromAST(false), ChangedAfterLoad(false), FEChangedAfterLoad(false),
+RevertedTokenID(false), OutOfDate(false), IsModulesImport(false),
+IsMangledOpenMPVariantName(false), IsDeprecatedMacro(false),
+IsRestrictExpansion(false), IsFinal(false) {}
 
 public:
   IdentifierInfo(const IdentifierInfo &) = delete;
@@ -332,42 +341,62 @@ class alignas(IdentifierInfoAlignment) 

[clang-tools-extra] [clangd] Prevent printing huge initializer lists in hover definitions (PR #79746)

2024-02-10 Thread Raoul Wols via cfe-commits

https://github.com/rwols updated https://github.com/llvm/llvm-project/pull/79746

>From 8c850241cedeaad1bcc91c68ad7558f485d212e8 Mon Sep 17 00:00:00 2001
From: Raoul Wols 
Date: Sat, 10 Feb 2024 20:52:03 +0100
Subject: [PATCH] [clangd] Do not render large initializer expressions from the
 preamble

---
 clang-tools-extra/clangd/Hover.cpp|  5 ++-
 .../clangd/unittests/HoverTests.cpp   | 34 +++
 2 files changed, 38 insertions(+), 1 deletion(-)

diff --git a/clang-tools-extra/clangd/Hover.cpp 
b/clang-tools-extra/clangd/Hover.cpp
index 06b949bc4a2b55..2ff2416c3d68a8 100644
--- a/clang-tools-extra/clangd/Hover.cpp
+++ b/clang-tools-extra/clangd/Hover.cpp
@@ -143,8 +143,11 @@ std::string printDefinition(const Decl *D, PrintingPolicy 
PP,
   // Initializers might be huge and result in lots of memory allocations in
   // some catostrophic cases. Such long lists are not useful in hover cards
   // anyway.
-  if (200 < TB.expandedTokens(IE->getSourceRange()).size())
+  const auto &SM = VD->getASTContext().getSourceManager();
+  if (!SM.isInMainFile(VD->getLocation()) ||
+  200 < TB.expandedTokens(IE->getSourceRange()).size()) {
 PP.SuppressInitializers = true;
+  }
 }
   }
   std::string Definition;
diff --git a/clang-tools-extra/clangd/unittests/HoverTests.cpp 
b/clang-tools-extra/clangd/unittests/HoverTests.cpp
index 35db757b9c15b5..e591f246457bc1 100644
--- a/clang-tools-extra/clangd/unittests/HoverTests.cpp
+++ b/clang-tools-extra/clangd/unittests/HoverTests.cpp
@@ -3956,6 +3956,40 @@ TEST(Hover, HideBigInitializers) {
   EXPECT_EQ(H->Definition, "int arr[]");
 }
 
+TEST(Hover, HideBigInitializersIncludedFromThePreamble) {
+  Annotations T(R"cpp(
+  #include "hugearray.h"
+  auto x = a^rr;
+  )cpp");
+  TestTU TU = TestTU::withCode(T.code());
+  TU.AdditionalFiles["hugearray.h"] = R"cpp(
+#define A(x) x, x, x, x
+#define B(x) A(A(A(A(x
+int arr[256] = {B(0)};
+  )cpp";
+  auto AST = TU.build();
+  auto H = getHover(AST, T.point(), format::getLLVMStyle(), nullptr);
+  ASSERT_TRUE(H);
+  EXPECT_EQ(H->Definition, "int arr[256]");
+}
+
+// FIXME(rwols): Enable this test.
+TEST(Hover, DISABLED_DoNotHideSmallInitializersIncludedFromThePreamble) {
+  Annotations T(R"cpp(
+  #include "smallarray.h"
+  auto x = a^rr;
+  )cpp");
+  TestTU TU = TestTU::withCode(T.code());
+  TU.AdditionalFiles["smallarray.h"] = R"cpp(
+#define A(x) x, x
+#define B(x) A(A(x))
+int arr[4] = {B(0)};
+  )cpp";
+  auto AST = TU.build();
+  auto H = getHover(AST, T.point(), format::getLLVMStyle(), nullptr);
+  ASSERT_TRUE(H);
+}
+
 #if defined(__aarch64__)
 // FIXME: AARCH64 sanitizer buildbots are broken after 72142fbac4.
 #define PREDEFINEMACROS_TEST(x) DISABLED_##x

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


[clang-tools-extra] [clangd] Prevent printing huge initializer lists in hover definitions (PR #79746)

2024-02-10 Thread Raoul Wols via cfe-commits

https://github.com/rwols updated https://github.com/llvm/llvm-project/pull/79746

>From 1739d0a4fd079d2201e63166fbaba60644c52297 Mon Sep 17 00:00:00 2001
From: Raoul Wols 
Date: Sat, 10 Feb 2024 20:52:03 +0100
Subject: [PATCH] [clangd] Do not render large initializer expressions from the
 preamble

---
 clang-tools-extra/clangd/Hover.cpp|  5 ++-
 .../clangd/unittests/HoverTests.cpp   | 35 +++
 2 files changed, 39 insertions(+), 1 deletion(-)

diff --git a/clang-tools-extra/clangd/Hover.cpp 
b/clang-tools-extra/clangd/Hover.cpp
index 06b949bc4a2b55..2ff2416c3d68a8 100644
--- a/clang-tools-extra/clangd/Hover.cpp
+++ b/clang-tools-extra/clangd/Hover.cpp
@@ -143,8 +143,11 @@ std::string printDefinition(const Decl *D, PrintingPolicy 
PP,
   // Initializers might be huge and result in lots of memory allocations in
   // some catostrophic cases. Such long lists are not useful in hover cards
   // anyway.
-  if (200 < TB.expandedTokens(IE->getSourceRange()).size())
+  const auto &SM = VD->getASTContext().getSourceManager();
+  if (!SM.isInMainFile(VD->getLocation()) ||
+  200 < TB.expandedTokens(IE->getSourceRange()).size()) {
 PP.SuppressInitializers = true;
+  }
 }
   }
   std::string Definition;
diff --git a/clang-tools-extra/clangd/unittests/HoverTests.cpp 
b/clang-tools-extra/clangd/unittests/HoverTests.cpp
index 35db757b9c15b5..c1c986d1db3769 100644
--- a/clang-tools-extra/clangd/unittests/HoverTests.cpp
+++ b/clang-tools-extra/clangd/unittests/HoverTests.cpp
@@ -3956,6 +3956,41 @@ TEST(Hover, HideBigInitializers) {
   EXPECT_EQ(H->Definition, "int arr[]");
 }
 
+TEST(Hover, HideBigInitializersIncludedFromThePreamble) {
+  Annotations T(R"cpp(
+  #include "hugearray.h"
+  auto x = a^rr;
+  )cpp");
+  TestTU TU = TestTU::withCode(T.code());
+  TU.AdditionalFiles["hugearray.h"] = R"cpp(
+#define A(x) x, x, x, x
+#define B(x) A(A(A(A(x
+int arr[256] = {B(0)};
+  )cpp";
+  auto AST = TU.build();
+  auto H = getHover(AST, T.point(), format::getLLVMStyle(), nullptr);
+  ASSERT_TRUE(H);
+  EXPECT_EQ(H->Definition, "int arr[256]");
+}
+
+// FIXME(rwols): Enable this test.
+TEST(Hover, DISABLED_DoNotHideSmallInitializersIncludedFromThePreamble) {
+  Annotations T(R"cpp(
+  #include "smallarray.h"
+  auto x = a^rr;
+  )cpp");
+  TestTU TU = TestTU::withCode(T.code());
+  TU.AdditionalFiles["smallarray.h"] = R"cpp(
+#define A(x) x, x
+#define B(x) A(A(x))
+int arr[4] = {B(0)};
+  )cpp";
+  auto AST = TU.build();
+  auto H = getHover(AST, T.point(), format::getLLVMStyle(), nullptr);
+  ASSERT_TRUE(H);
+  EXPECT_EQ(H->Definition, "int arr[4] = {0, 0, 0, 0}");
+}
+
 #if defined(__aarch64__)
 // FIXME: AARCH64 sanitizer buildbots are broken after 72142fbac4.
 #define PREDEFINEMACROS_TEST(x) DISABLED_##x

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


[clang-tools-extra] [clangd] Prevent printing huge initializer lists in hover definitions (PR #79746)

2024-02-10 Thread Raoul Wols via cfe-commits

https://github.com/rwols updated https://github.com/llvm/llvm-project/pull/79746

>From 3ad404a10c3def9f92f399774f9f1507442bca1b Mon Sep 17 00:00:00 2001
From: Raoul Wols 
Date: Sat, 10 Feb 2024 20:52:03 +0100
Subject: [PATCH] [clangd] Do not render large initializer expressions from the
 preamble

An attempt is made to estimate the size of the initializer expression.
If it has less than 100 direct AST child nodes we'll assume it should render
OK.
---
 clang-tools-extra/clangd/Hover.cpp| 10 +-
 .../clangd/unittests/HoverTests.cpp   | 34 +++
 2 files changed, 43 insertions(+), 1 deletion(-)

diff --git a/clang-tools-extra/clangd/Hover.cpp 
b/clang-tools-extra/clangd/Hover.cpp
index 06b949bc4a2b55..b39c2b40468cd1 100644
--- a/clang-tools-extra/clangd/Hover.cpp
+++ b/clang-tools-extra/clangd/Hover.cpp
@@ -143,8 +143,16 @@ std::string printDefinition(const Decl *D, PrintingPolicy 
PP,
   // Initializers might be huge and result in lots of memory allocations in
   // some catostrophic cases. Such long lists are not useful in hover cards
   // anyway.
-  if (200 < TB.expandedTokens(IE->getSourceRange()).size())
+  const auto &SM = VD->getASTContext().getSourceManager();
+  if (!SM.isInMainFile(VD->getLocation())) {
+const auto &Children = IE->children();
+const size_t Length = std::distance(Children.begin(), Children.end());
+if (100 < Length) {
+  PP.SuppressInitializers = true;
+}
+  } else if (200 < TB.expandedTokens(IE->getSourceRange()).size()) {
 PP.SuppressInitializers = true;
+  }
 }
   }
   std::string Definition;
diff --git a/clang-tools-extra/clangd/unittests/HoverTests.cpp 
b/clang-tools-extra/clangd/unittests/HoverTests.cpp
index 35db757b9c15b5..a77b2d66d9e7fa 100644
--- a/clang-tools-extra/clangd/unittests/HoverTests.cpp
+++ b/clang-tools-extra/clangd/unittests/HoverTests.cpp
@@ -3956,6 +3956,40 @@ TEST(Hover, HideBigInitializers) {
   EXPECT_EQ(H->Definition, "int arr[]");
 }
 
+TEST(Hover, HideBigInitializersIncludedFromThePreamble) {
+  Annotations T(R"cpp(
+  #include "hugearray.h"
+  auto x = a^rr;
+  )cpp");
+  TestTU TU = TestTU::withCode(T.code());
+  TU.AdditionalFiles["hugearray.h"] = R"cpp(
+#define A(x) x, x, x, x
+#define B(x) A(A(A(A(x
+int arr[256] = {B(0)};
+  )cpp";
+  auto AST = TU.build();
+  auto H = getHover(AST, T.point(), format::getLLVMStyle(), nullptr);
+  ASSERT_TRUE(H);
+  EXPECT_EQ(H->Definition, "int arr[256]");
+}
+
+TEST(Hover, DoNotHideSmallInitializersIncludedFromThePreamble) {
+  Annotations T(R"cpp(
+  #include "smallarray.h"
+  auto x = a^rr;
+  )cpp");
+  TestTU TU = TestTU::withCode(T.code());
+  TU.AdditionalFiles["smallarray.h"] = R"cpp(
+#define A(x) x, x
+#define B(x) A(A(x))
+int arr[4] = {B(0)};
+  )cpp";
+  auto AST = TU.build();
+  auto H = getHover(AST, T.point(), format::getLLVMStyle(), nullptr);
+  ASSERT_TRUE(H);
+  EXPECT_EQ(H->Definition, "int arr[4] = {0, 0, 0, 0}");
+}
+
 #if defined(__aarch64__)
 // FIXME: AARCH64 sanitizer buildbots are broken after 72142fbac4.
 #define PREDEFINEMACROS_TEST(x) DISABLED_##x

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


[clang-tools-extra] [clangd] Prevent printing huge initializer lists in hover definitions (PR #79746)

2024-02-10 Thread Raoul Wols via cfe-commits


@@ -138,15 +138,9 @@ std::string getNamespaceScope(const Decl *D) {
 
 std::string printDefinition(const Decl *D, PrintingPolicy PP,
 const syntax::TokenBuffer &TB) {
-  if (auto *VD = llvm::dyn_cast(D)) {
-if (auto *IE = VD->getInit()) {
-  // Initializers might be huge and result in lots of memory allocations in
-  // some catostrophic cases. Such long lists are not useful in hover cards
-  // anyway.
-  if (200 < TB.expandedTokens(IE->getSourceRange()).size())
-PP.SuppressInitializers = true;
-}
-  }
+  // Initializers might be huge and result in lots of memory allocations in 
some
+  // catostrophic cases. Such long lists are not useful in hover cards anyway.
+  PP.EntireContentsOfLargeArray = false;

rwols wrote:

OK, I check the size of the children() now when the initializer expression is 
not in the main file, and added two unit tests that verify that for a large 
initializer list from a header file it won't render, while a "small" 
initializer list will still render.

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


[clang-tools-extra] [clangd] Prevent printing huge initializer lists in hover definitions (PR #79746)

2024-02-10 Thread Raoul Wols via cfe-commits


@@ -1720,6 +1720,12 @@ void StmtPrinter::VisitInitListExpr(InitListExpr* Node) {
   OS << "{";
   for (unsigned i = 0, e = Node->getNumInits(); i != e; ++i) {
 if (i) OS << ", ";
+// TODO: There is duplicated functionality in APValue::printPretty.
+// Would be good to consolidate the two.
+if (!Policy.EntireContentsOfLargeArray && i == 10) {

rwols wrote:

I reverted these changes in the clang namespace.

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


[clang] 3a05e76 - [clang][NFC] Annotate `Sema/DeclSpec.h` with `preferred_type`

2024-02-10 Thread Vlad Serebrennikov via cfe-commits

Author: Vlad Serebrennikov
Date: 2024-02-10T23:37:00+03:00
New Revision: 3a05e7651bc71b3c71757bb406f211645c1c1a37

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

LOG: [clang][NFC] Annotate `Sema/DeclSpec.h` with `preferred_type`

This helps debuggers to display values in bit-fields in a more helpful way.

Added: 


Modified: 
clang/include/clang/Sema/DeclSpec.h

Removed: 




diff  --git a/clang/include/clang/Sema/DeclSpec.h 
b/clang/include/clang/Sema/DeclSpec.h
index 77638def60063d..d161147527dc34 100644
--- a/clang/include/clang/Sema/DeclSpec.h
+++ b/clang/include/clang/Sema/DeclSpec.h
@@ -353,36 +353,57 @@ class DeclSpec {
 
 private:
   // storage-class-specifier
-  /*SCS*/unsigned StorageClassSpec : 3;
-  /*TSCS*/unsigned ThreadStorageClassSpec : 2;
+  LLVM_PREFERRED_TYPE(SCS)
+  unsigned StorageClassSpec : 3;
+  LLVM_PREFERRED_TYPE(TSCS)
+  unsigned ThreadStorageClassSpec : 2;
+  LLVM_PREFERRED_TYPE(bool)
   unsigned SCS_extern_in_linkage_spec : 1;
 
   // type-specifier
-  /*TypeSpecifierWidth*/ unsigned TypeSpecWidth : 2;
-  /*TSC*/unsigned TypeSpecComplex : 2;
-  /*TSS*/unsigned TypeSpecSign : 2;
-  /*TST*/unsigned TypeSpecType : 7;
+  LLVM_PREFERRED_TYPE(TypeSpecifierWidth)
+  unsigned TypeSpecWidth : 2;
+  LLVM_PREFERRED_TYPE(TSC)
+  unsigned TypeSpecComplex : 2;
+  LLVM_PREFERRED_TYPE(TypeSpecifierSign)
+  unsigned TypeSpecSign : 2;
+  LLVM_PREFERRED_TYPE(TST)
+  unsigned TypeSpecType : 7;
+  LLVM_PREFERRED_TYPE(bool)
   unsigned TypeAltiVecVector : 1;
+  LLVM_PREFERRED_TYPE(bool)
   unsigned TypeAltiVecPixel : 1;
+  LLVM_PREFERRED_TYPE(bool)
   unsigned TypeAltiVecBool : 1;
+  LLVM_PREFERRED_TYPE(bool)
   unsigned TypeSpecOwned : 1;
+  LLVM_PREFERRED_TYPE(bool)
   unsigned TypeSpecPipe : 1;
+  LLVM_PREFERRED_TYPE(bool)
   unsigned TypeSpecSat : 1;
+  LLVM_PREFERRED_TYPE(bool)
   unsigned ConstrainedAuto : 1;
 
   // type-qualifiers
+  LLVM_PREFERRED_TYPE(TQ)
   unsigned TypeQualifiers : 5;  // Bitwise OR of TQ.
 
   // function-specifier
+  LLVM_PREFERRED_TYPE(bool)
   unsigned FS_inline_specified : 1;
+  LLVM_PREFERRED_TYPE(bool)
   unsigned FS_forceinline_specified: 1;
+  LLVM_PREFERRED_TYPE(bool)
   unsigned FS_virtual_specified : 1;
+  LLVM_PREFERRED_TYPE(bool)
   unsigned FS_noreturn_specified : 1;
 
   // friend-specifier
+  LLVM_PREFERRED_TYPE(bool)
   unsigned Friend_specified : 1;
 
   // constexpr-specifier
+  LLVM_PREFERRED_TYPE(ConstexprSpecKind)
   unsigned ConstexprSpecifier : 2;
 
   union {
@@ -1246,6 +1267,7 @@ struct DeclaratorChunk {
 
   struct PointerTypeInfo {
 /// The type qualifiers: const/volatile/restrict/unaligned/atomic.
+LLVM_PREFERRED_TYPE(DeclSpec::TQ)
 unsigned TypeQuals : 5;
 
 /// The location of the const-qualifier, if any.
@@ -1279,12 +1301,15 @@ struct DeclaratorChunk {
   struct ArrayTypeInfo {
 /// The type qualifiers for the array:
 /// const/volatile/restrict/__unaligned/_Atomic.
+LLVM_PREFERRED_TYPE(DeclSpec::TQ)
 unsigned TypeQuals : 5;
 
 /// True if this dimension included the 'static' keyword.
+LLVM_PREFERRED_TYPE(bool)
 unsigned hasStatic : 1;
 
 /// True if this dimension was [*].  In this case, NumElts is null.
+LLVM_PREFERRED_TYPE(bool)
 unsigned isStar : 1;
 
 /// This is the size of the array, or null if [] or [*] was specified.
@@ -1331,28 +1356,35 @@ struct DeclaratorChunk {
 /// hasPrototype - This is true if the function had at least one typed
 /// parameter.  If the function is () or (a,b,c), then it has no prototype,
 /// and is treated as a K&R-style function.
+LLVM_PREFERRED_TYPE(bool)
 unsigned hasPrototype : 1;
 
 /// isVariadic - If this function has a prototype, and if that
 /// proto ends with ',...)', this is true. When true, EllipsisLoc
 /// contains the location of the ellipsis.
+LLVM_PREFERRED_TYPE(bool)
 unsigned isVariadic : 1;
 
 /// Can this declaration be a constructor-style initializer?
+LLVM_PREFERRED_TYPE(bool)
 unsigned isAmbiguous : 1;
 
 /// Whether the ref-qualifier (if any) is an lvalue reference.
 /// Otherwise, it's an rvalue reference.
+LLVM_PREFERRED_TYPE(bool)
 unsigned RefQualifierIsLValueRef : 1;
 
 /// ExceptionSpecType - An ExceptionSpecificationType value.
+LLVM_PREFERRED_TYPE(ExceptionSpecificationType)
 unsigned ExceptionSpecType : 4;
 
 /// DeleteParams - If this is true, we need to delete[] Params.
+LLVM_PREFERRED_TYPE(bool)
 unsigned DeleteParams : 1;
 
 /// HasTrailingReturnType - If this is true, a trailing return type was
 /// specified.
+LLVM_PREFERRED_TYPE(bool)
 unsigned HasTrailingReturnType : 1;
 
 /// The location of the left parenthesis in the source.
@@ -1567,6 +1599,7 @@ struct Declarat

[clang] [lld] [llvm] [llvm-driver] Fix usage of `InitLLVM` on Windows (PR #76306)

2024-02-10 Thread Dimitry Andric via cfe-commits

DimitryAndric wrote:

Maybe I'm doing something wrong, but after this commit (and its merge to 18.x) 
I don't see to get stack traces from clang anymore after assertions?  How is 
this supposed to work?


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


[clang] [lld] [llvm] [llvm-driver] Fix usage of `InitLLVM` on Windows (PR #76306)

2024-02-10 Thread Jessica Clarke via cfe-commits

jrtc27 wrote:

llvm-driver-template.cpp.in is what should be generating the real main for 
Clang (and call clang_main), and that was patched in this commit.

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


[clang] [ObjC] Check entire chain of superclasses to see if class has fixed offsets (PR #81335)

2024-02-10 Thread John McCall via cfe-commits

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

Okay, your description of the change here is very misleading; it doesn't even 
mention that this is specific to having an `@implementation` for every 
intermediate class.

Your test seems completely inadequate — you need to test that we're doing the 
static layout properly, and you need to test with ivars coming from a variety 
of different places, including:
- ivars declared in the `@interface`
- ivars declared in the `@implementation`
- ivars synthesized explicitly in the `@implementation`
- vars synthesized implicitly in the `@implementation`

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


[clang] 4e16a75 - [clang][NFC] Annotate `Sema/ScopeInfo.h` with `preferred_type`

2024-02-10 Thread Vlad Serebrennikov via cfe-commits

Author: Vlad Serebrennikov
Date: 2024-02-10T23:58:26+03:00
New Revision: 4e16a75902d5718f4932fae9b2a07c410cd0ba34

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

LOG: [clang][NFC] Annotate `Sema/ScopeInfo.h` with `preferred_type`

This helps debuggers to display values in bit-fields in a more helpful way.

Added: 


Modified: 
clang/include/clang/Sema/ScopeInfo.h

Removed: 




diff  --git a/clang/include/clang/Sema/ScopeInfo.h 
b/clang/include/clang/Sema/ScopeInfo.h
index 6eaa74382685ba..076dcaaf223a34 100644
--- a/clang/include/clang/Sema/ScopeInfo.h
+++ b/clang/include/clang/Sema/ScopeInfo.h
@@ -97,6 +97,8 @@ class PossiblyUnreachableDiag {
   : PD(PD), Loc(Loc), Stmts(Stmts) {}
 };
 
+enum class FirstCoroutineStmtKind { co_return, co_await, co_yield };
+
 /// Retains information about a function, method, or block that is
 /// currently being parsed.
 class FunctionScopeInfo {
@@ -170,6 +172,7 @@ class FunctionScopeInfo {
 
   /// An enumeration representing the kind of the first coroutine statement
   /// in the function. One of co_return, co_await, or co_yield.
+  LLVM_PREFERRED_TYPE(FirstCoroutineStmtKind)
   unsigned char FirstCoroutineStmtKind : 2;
 
   /// Whether we found an immediate-escalating expression.
@@ -502,22 +505,30 @@ class FunctionScopeInfo {
 assert(FirstCoroutineStmtLoc.isInvalid() &&
"first coroutine statement location already set");
 FirstCoroutineStmtLoc = Loc;
-FirstCoroutineStmtKind = llvm::StringSwitch(Keyword)
-.Case("co_return", 0)
-.Case("co_await", 1)
-.Case("co_yield", 2);
+FirstCoroutineStmtKind =
+llvm::StringSwitch(Keyword)
+.Case("co_return",
+  llvm::to_underlying(FirstCoroutineStmtKind::co_return))
+.Case("co_await",
+  llvm::to_underlying(FirstCoroutineStmtKind::co_await))
+.Case("co_yield",
+  llvm::to_underlying(FirstCoroutineStmtKind::co_yield));
   }
 
   StringRef getFirstCoroutineStmtKeyword() const {
 assert(FirstCoroutineStmtLoc.isValid()
&& "no coroutine statement available");
-switch (FirstCoroutineStmtKind) {
-case 0: return "co_return";
-case 1: return "co_await";
-case 2: return "co_yield";
-default:
-  llvm_unreachable("FirstCoroutineStmtKind has an invalid value");
+auto Value =
+static_cast(FirstCoroutineStmtKind);
+switch (Value) {
+case FirstCoroutineStmtKind::co_return:
+  return "co_return";
+case FirstCoroutineStmtKind::co_await:
+  return "co_await";
+case FirstCoroutineStmtKind::co_yield:
+  return "co_yield";
 };
+llvm_unreachable("FirstCoroutineStmtKind has an invalid value");
   }
 
   void setNeedsCoroutineSuspends(bool value = true) {
@@ -582,25 +593,31 @@ class Capture {
   QualType CaptureType;
 
   /// The CaptureKind of this capture.
+  LLVM_PREFERRED_TYPE(CaptureKind)
   unsigned Kind : 2;
 
   /// Whether this is a nested capture (a capture of an enclosing capturing
   /// scope's capture).
+  LLVM_PREFERRED_TYPE(bool)
   unsigned Nested : 1;
 
   /// Whether this is a capture of '*this'.
+  LLVM_PREFERRED_TYPE(bool)
   unsigned CapturesThis : 1;
 
   /// Whether an explicit capture has been odr-used in the body of the
   /// lambda.
+  LLVM_PREFERRED_TYPE(bool)
   unsigned ODRUsed : 1;
 
   /// Whether an explicit capture has been non-odr-used in the body of
   /// the lambda.
+  LLVM_PREFERRED_TYPE(bool)
   unsigned NonODRUsed : 1;
 
   /// Whether the capture is invalid (a capture was required but the entity is
   /// non-capturable).
+  LLVM_PREFERRED_TYPE(bool)
   unsigned Invalid : 1;
 
 public:



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


[clang] [lld] [llvm] [llvm-driver] Fix usage of `InitLLVM` on Windows (PR #76306)

2024-02-10 Thread Dimitry Andric via cfe-commits

DimitryAndric wrote:

Ah that was my error, I hadn't used the regenerated `*-driver.cpp` files. These 
indeed should contain the `InitLLVM` call.

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


[clang] [clang][Sema] Fix for enums overflowing (#24667) (PR #78742)

2024-02-10 Thread via cfe-commits

wheatman wrote:

@AaronBallman I am a little confused about what is the correct behavior for one 
the the cases in the test file for c.
```cpp
enum PR4515 {PR4515a=1u,PR4515b=(PR4515a-2)/2};
int CheckPR4515[PR4515b==0?1:-1];
```
At present since everything is ints this works fine, but some things are not 
clear to me once the enum is allowed to be an unsigned type
https://godbolt.org/z/8bfr8s3n5

```cpp
enum PR4515 {PR4515a=1u,PR4515b=(PR4515a-2)/2};
 auto a = PR4515a;
 auto b = PR4515b;
 auto c = (1 - 2)/2;
 auto d = (1u - 2)/2;
 auto e = (PR4515a-2)/2;
```
values
```
a:
.long   1   # 0x1

b:
.long   0   # 0x0

c:
.long   0   # 0x0

d:
.long   2147483647  # 0x7fff

e:
.long   0   # 0x0
```


specifically around the value for `PR4515b=(PR4515a-2)/2` 
if `PR4515a` has type unsigned int, then the value of this expression is 
2147483647 see `d`, but if it has type int then it has value of 0 see `c` which 
is the expected value for the test.  However, with the new change the enum type 
would be unsigned since it was specified as unsigned, which I believe is the 
new behavior.  

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


[clang] d2812d2 - [clang][NFC] Annotate `Sema/Overload.h` with `preferred_type`

2024-02-10 Thread Vlad Serebrennikov via cfe-commits

Author: Vlad Serebrennikov
Date: 2024-02-11T00:11:13+03:00
New Revision: d2812d2d1a9b4edb64e95a9a86a2599a24bcb5ec

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

LOG: [clang][NFC] Annotate `Sema/Overload.h` with `preferred_type`

This helps debuggers to display values in bit-fields in a more helpful way.

Added: 


Modified: 
clang/include/clang/Sema/Overload.h

Removed: 




diff  --git a/clang/include/clang/Sema/Overload.h 
b/clang/include/clang/Sema/Overload.h
index 6ccabad3af544..9b342c0916844 100644
--- a/clang/include/clang/Sema/Overload.h
+++ b/clang/include/clang/Sema/Overload.h
@@ -278,40 +278,50 @@ class Sema;
 /// Whether this is the deprecated conversion of a
 /// string literal to a pointer to non-const character data
 /// (C++ 4.2p2).
+LLVM_PREFERRED_TYPE(bool)
 unsigned DeprecatedStringLiteralToCharPtr : 1;
 
 /// Whether the qualification conversion involves a change in the
 /// Objective-C lifetime (for automatic reference counting).
+LLVM_PREFERRED_TYPE(bool)
 unsigned QualificationIncludesObjCLifetime : 1;
 
 /// IncompatibleObjC - Whether this is an Objective-C conversion
 /// that we should warn about (if we actually use it).
+LLVM_PREFERRED_TYPE(bool)
 unsigned IncompatibleObjC : 1;
 
 /// ReferenceBinding - True when this is a reference binding
 /// (C++ [over.ics.ref]).
+LLVM_PREFERRED_TYPE(bool)
 unsigned ReferenceBinding : 1;
 
 /// DirectBinding - True when this is a reference binding that is a
 /// direct binding (C++ [dcl.init.ref]).
+LLVM_PREFERRED_TYPE(bool)
 unsigned DirectBinding : 1;
 
 /// Whether this is an lvalue reference binding (otherwise, it's
 /// an rvalue reference binding).
+LLVM_PREFERRED_TYPE(bool)
 unsigned IsLvalueReference : 1;
 
 /// Whether we're binding to a function lvalue.
+LLVM_PREFERRED_TYPE(bool)
 unsigned BindsToFunctionLvalue : 1;
 
 /// Whether we're binding to an rvalue.
+LLVM_PREFERRED_TYPE(bool)
 unsigned BindsToRvalue : 1;
 
 /// Whether this binds an implicit object argument to a
 /// non-static member function without a ref-qualifier.
+LLVM_PREFERRED_TYPE(bool)
 unsigned BindsImplicitObjectArgumentWithoutRefQualifier : 1;
 
 /// Whether this binds a reference to an object with a 
diff erent
 /// Objective-C lifetime qualifier.
+LLVM_PREFERRED_TYPE(bool)
 unsigned ObjCLifetimeConversionBinding : 1;
 
 /// FromType - The type that this conversion is converting
@@ -541,9 +551,11 @@ class Sema;
 };
 
 /// ConversionKind - The kind of implicit conversion sequence.
+LLVM_PREFERRED_TYPE(Kind)
 unsigned ConversionKind : 31;
 
 // Whether the initializer list was of an incomplete array.
+LLVM_PREFERRED_TYPE(bool)
 unsigned InitializerListOfIncompleteArray : 1;
 
 /// When initializing an array or std::initializer_list from an
@@ -878,6 +890,7 @@ class Sema;
 CallExpr::ADLCallKind IsADLCandidate : 1;
 
 /// Whether this is a rewritten candidate, and if so, of what kind?
+LLVM_PREFERRED_TYPE(OverloadCandidateRewriteKind)
 unsigned RewriteKind : 2;
 
 /// FailureKind - The reason why this candidate is not viable.



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


[clang] 425fd3e - [clang][NFC] Rename FirstCoroutineStmtKind enumerators

2024-02-10 Thread Vlad Serebrennikov via cfe-commits

Author: Vlad Serebrennikov
Date: 2024-02-11T00:15:25+03:00
New Revision: 425fd3eb10f29e73d722b4c2bc9cb50798de18e8

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

LOG: [clang][NFC] Rename FirstCoroutineStmtKind enumerators

So that they do not use coroutine keywords.
Fixed buildbot failure https://lab.llvm.org/buildbot/#/builders/86/builds/74100

Added: 


Modified: 
clang/include/clang/Sema/ScopeInfo.h

Removed: 




diff  --git a/clang/include/clang/Sema/ScopeInfo.h 
b/clang/include/clang/Sema/ScopeInfo.h
index 076dcaaf223a34..ca3d0a02ddb579 100644
--- a/clang/include/clang/Sema/ScopeInfo.h
+++ b/clang/include/clang/Sema/ScopeInfo.h
@@ -97,7 +97,7 @@ class PossiblyUnreachableDiag {
   : PD(PD), Loc(Loc), Stmts(Stmts) {}
 };
 
-enum class FirstCoroutineStmtKind { co_return, co_await, co_yield };
+enum class FirstCoroutineStmtKind { CoReturn, CoAwait, CoYield };
 
 /// Retains information about a function, method, or block that is
 /// currently being parsed.
@@ -508,11 +508,11 @@ class FunctionScopeInfo {
 FirstCoroutineStmtKind =
 llvm::StringSwitch(Keyword)
 .Case("co_return",
-  llvm::to_underlying(FirstCoroutineStmtKind::co_return))
+  llvm::to_underlying(FirstCoroutineStmtKind::CoReturn))
 .Case("co_await",
-  llvm::to_underlying(FirstCoroutineStmtKind::co_await))
+  llvm::to_underlying(FirstCoroutineStmtKind::CoAwait))
 .Case("co_yield",
-  llvm::to_underlying(FirstCoroutineStmtKind::co_yield));
+  llvm::to_underlying(FirstCoroutineStmtKind::CoYield));
   }
 
   StringRef getFirstCoroutineStmtKeyword() const {
@@ -521,11 +521,11 @@ class FunctionScopeInfo {
 auto Value =
 static_cast(FirstCoroutineStmtKind);
 switch (Value) {
-case FirstCoroutineStmtKind::co_return:
+case FirstCoroutineStmtKind::CoReturn:
   return "co_return";
-case FirstCoroutineStmtKind::co_await:
+case FirstCoroutineStmtKind::CoAwait:
   return "co_await";
-case FirstCoroutineStmtKind::co_yield:
+case FirstCoroutineStmtKind::CoYield:
   return "co_yield";
 };
 llvm_unreachable("FirstCoroutineStmtKind has an invalid value");



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


[clang] 6a7cf80 - [clang][NFC] Annotate `Sema/ParsedAttr.h` with `preferred_type`

2024-02-10 Thread Vlad Serebrennikov via cfe-commits

Author: Vlad Serebrennikov
Date: 2024-02-11T00:21:37+03:00
New Revision: 6a7cf806a66c67df01818fda01116a2dd2d90b0d

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

LOG: [clang][NFC] Annotate `Sema/ParsedAttr.h` with `preferred_type`

This helps debuggers to display values in bit-fields in a more helpful way.

Added: 


Modified: 
clang/include/clang/Sema/ParsedAttr.h

Removed: 




diff  --git a/clang/include/clang/Sema/ParsedAttr.h 
b/clang/include/clang/Sema/ParsedAttr.h
index 8c0edca1ebc5ee..8c3ba39031aad8 100644
--- a/clang/include/clang/Sema/ParsedAttr.h
+++ b/clang/include/clang/Sema/ParsedAttr.h
@@ -82,7 +82,9 @@ struct AvailabilityData {
 
 struct TypeTagForDatatypeData {
   ParsedType MatchingCType;
+  LLVM_PREFERRED_TYPE(bool)
   unsigned LayoutCompatible : 1;
+  LLVM_PREFERRED_TYPE(bool)
   unsigned MustBeNull : 1;
 };
 struct PropertyData {
@@ -149,33 +151,41 @@ class ParsedAttr final
   unsigned NumArgs : 16;
 
   /// True if already diagnosed as invalid.
+  LLVM_PREFERRED_TYPE(bool)
   mutable unsigned Invalid : 1;
 
   /// True if this attribute was used as a type attribute.
+  LLVM_PREFERRED_TYPE(bool)
   mutable unsigned UsedAsTypeAttr : 1;
 
   /// True if this has the extra information associated with an
   /// availability attribute.
+  LLVM_PREFERRED_TYPE(bool)
   unsigned IsAvailability : 1;
 
   /// True if this has extra information associated with a
   /// type_tag_for_datatype attribute.
+  LLVM_PREFERRED_TYPE(bool)
   unsigned IsTypeTagForDatatype : 1;
 
   /// True if this has extra information associated with a
   /// Microsoft __delcspec(property) attribute.
+  LLVM_PREFERRED_TYPE(bool)
   unsigned IsProperty : 1;
 
   /// True if this has a ParsedType
+  LLVM_PREFERRED_TYPE(bool)
   unsigned HasParsedType : 1;
 
   /// True if the processing cache is valid.
+  LLVM_PREFERRED_TYPE(bool)
   mutable unsigned HasProcessingCache : 1;
 
   /// A cached value.
   mutable unsigned ProcessingCache : 8;
 
   /// True if the attribute is specified using '#pragma clang attribute'.
+  LLVM_PREFERRED_TYPE(bool)
   mutable unsigned IsPragmaClangAttribute : 1;
 
   /// The location of the 'unavailable' keyword in an



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


[clang] [ObjC] Check entire chain of superclasses to see if class has fixed offsets (PR #81335)

2024-02-10 Thread via cfe-commits

AtariDreams wrote:

> Okay, your description of the change here is very misleading; it doesn't even 
> mention that this is specific to having an `@implementation` for every 
> intermediate class.
> 
> Your test seems completely inadequate — you need to test that we're doing the 
> static layout properly, and you need to test with ivars coming from a variety 
> of different places, including:
> 
> * ivars declared in the `@interface`
> * ivars declared in the `@implementation`
> * ivars synthesized explicitly in the `@implementation`
> * vars synthesized implicitly in the `@implementation`

So this is a way to check for static linked; if the compiler can see the 
@implementation, right?

Only then can we "opt-out" of the non-fragile ABI like NSObject and its 
subclasses do, right? 



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


[clang] [ObjC] Check entire chain of superclasses to see if class has fixed offsets (PR #81335)

2024-02-10 Thread via cfe-commits

AtariDreams wrote:

> test seems completely inadequate — you need to test that we're doing the 
> static layout properly, and you need to test with ivars coming from a variety 
> of different places, including:
> 
> * ivars declared in the `@interface`
> * ivars declared in the `@implementation`
> * ivars synthesized explicitly in the `@implementation`
> * vars synthesized implicitly in the `@implementation`

I think it is the only way, otherwise it would have to be done at link time. 
Can we do it at link time? probably another PR would have to deal with that.

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


[clang] [ObjC] Check entire chain of superclasses to see if class has fixed offsets (PR #81335)

2024-02-10 Thread via cfe-commits

https://github.com/AtariDreams updated 
https://github.com/llvm/llvm-project/pull/81335

>From 527e24ae4d6f662c2bee1a281914df028bcd01e1 Mon Sep 17 00:00:00 2001
From: Rose <83477269+ataridre...@users.noreply.github.com>
Date: Fri, 9 Feb 2024 17:51:15 -0500
Subject: [PATCH 1/2] [ObjC] Add pre-commit tests [NFC]

---
 .../constant-non-fragile-ivar-offset.m| 84 +++
 1 file changed, 84 insertions(+)

diff --git a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m 
b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
index 788b3220af3067..bed6497f8827ae 100644
--- a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
+++ b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
@@ -1,6 +1,13 @@
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 -emit-llvm %s -o - | 
FileCheck %s
 
 // CHECK: @"OBJC_IVAR_$_StaticLayout.static_layout_ivar" = hidden constant i64 
20
+// CHECK: @"OBJC_IVAR_$_StaticLayoutSubClass.static_layout_ivar2" = hidden 
constant i64 24
+// CHECK: @"OBJC_IVAR_$_MyClass.myIvar" = constant i64 20
+// CHECK: @"OBJC_IVAR_$_MyClass._myProperty" = hidden constant i64 24
+// CHECK: @"OBJC_IVAR_$_AnotherClass.privateId" = constant i64 24
+// CHECK: @"OBJC_IVAR_$_AnotherClass.anotherPrivateId" = hidden constant i64 32
+// CHECK: @"OBJC_IVAR_$_SuperClass.superClassIvar" = constant i64 20
+// CHECK: @"OBJC_IVAR_$_SubClass.subClassIvar" = global i64 24
 // CHECK: @"OBJC_IVAR_$_NotStaticLayout.not_static_layout_ivar" = hidden 
global i64 12
 
 @interface NSObject {
@@ -20,6 +27,83 @@ -(void)meth {
 }
 @end
 
+// Scenario 1: Ivars declared in the @interface
+@interface MyClass : NSObject
+{
+int myIvar; // Declare an ivar
+}
+
+@property (nonatomic, assign) int myProperty; // Synthesize a property
+
+@end
+
+@implementation MyClass 
+
+- (void)exampleMethod {
+self.myProperty = 42; // Access the property
+myIvar = 10; // Access the ivar directly
+}
+
+@end
+
+// Scenario 2: Ivars declared directly in the @implementation
+@interface AnotherClass : NSObject
+{
+  id privateId;
+}
+
+@end
+
+@implementation AnotherClass
+{
+id anotherPrivateId; // Declare an ivar directly in the implementation
+}
+
+- (void)doSomething {
+   privateId = anotherPrivateId;
+}
+
+@end
+
+// Scenario 3: Inheritance and Ivars
+@interface SuperClass : NSObject
+{
+int superClassIvar;
+}
+@end
+
+@implementation SuperClass
+@end
+
+@interface SubClass : SuperClass
+{
+double subClassIvar;
+}
+@end
+
+@implementation SubClass
+- (void)exampleMethod {
+// CHECK: load i64, ptr @"OBJC_IVAR_$SuperClass
+superClassIvar = 100; // Access superclass ivar
+subClassIvar = 3.14; // Access subclass ivar
+}
+@end
+
+// Scenario 4: Custom Getter/Setter Methods
+@interface CustomPropertyClass : NSObject
+@property (nonatomic, strong, getter=myCustomGetter, setter=myCustomSetter:) 
id customProperty;
+@end
+
+@implementation CustomPropertyClass
+- (id) myCustomGetter {
+return 0;
+}
+
+- (void)myCustomSetter:(id)newValue {
+// Custom setter logic
+}
+@end
+
 @interface NotNSObject {
   int these, might, change;
 }

>From f22d935cb80d79ea5354317bcd34049579ccf3ee Mon Sep 17 00:00:00 2001
From: Rose <83477269+ataridre...@users.noreply.github.com>
Date: Fri, 9 Feb 2024 17:47:59 -0500
Subject: [PATCH 2/2] [ObjC] Check entire chain of superclasses to see if class
 has fixed offsets

As of now, we only check if a class directly inherits from NSObject to 
determine if said lass has fixed offsets and can therefore "opt-out" from the 
non-fragile ABI for ivars.

However, if an NSObject subclass has fixed offsets, then so must the subclasses 
of that subclass, so this allows us to optimize instances of subclasses of 
subclasses that inherit from NSObject and so on.

Fixes: #81369
---
 clang/lib/CodeGen/CGObjCMac.cpp   | 22 ++-
 .../constant-non-fragile-ivar-offset.m|  6 ++---
 2 files changed, 19 insertions(+), 9 deletions(-)

diff --git a/clang/lib/CodeGen/CGObjCMac.cpp b/clang/lib/CodeGen/CGObjCMac.cpp
index 27d77e9a8a5511..ceee70a5d79b3e 100644
--- a/clang/lib/CodeGen/CGObjCMac.cpp
+++ b/clang/lib/CodeGen/CGObjCMac.cpp
@@ -1593,12 +1593,22 @@ class CGObjCNonFragileABIMac : public CGObjCCommonMac {
   }
 
   bool isClassLayoutKnownStatically(const ObjCInterfaceDecl *ID) {
-// NSObject is a fixed size. If we can see the @implementation of a class
-// which inherits from NSObject then we know that all it's offsets also 
must
-// be fixed. FIXME: Can we do this if see a chain of super classes with
-// implementations leading to NSObject?
-return ID->getImplementation() && ID->getSuperClass() &&
-   ID->getSuperClass()->getName() == "NSObject";
+// Test a class by checking its superclasses up to its base class if it has
+// one
+while (ID) {
+  // The base class NSObject is a fixed size
+  if (ID->getName() == "NSObject")
+return true;
+
+  // If we cannot see the @implementa

[clang] [Clang][Sema] Fix missing warning when comparing mismatched enums in … (PR #81389)

2024-02-10 Thread via cfe-commits

github-actions[bot] wrote:



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

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

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

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

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

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

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

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


[clang] [Clang][Sema] Fix missing warning when comparing mismatched enums in … (PR #81389)

2024-02-10 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: None (44-2-Kupa-Martin)


Changes

…C mode

Factored logic from `CheckImplicitConversion` into new methods 
`Expr::getEnumConstantDecl` and `Expr::getEnumCoercedType` for use in 
`checkEnumArithmeticConversions`.

Fix #29217

---

Patch is 650.51 KiB, truncated to 20.00 KiB below, full version: 
https://github.com/llvm/llvm-project/pull/81389.diff


9 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+3) 
- (modified) clang/include/clang/AST/Expr.h (+256-269) 
- (modified) clang/lib/AST/Expr.cpp (+585-463) 
- (modified) clang/lib/Sema/SemaChecking.cpp (+1428-1193) 
- (modified) clang/lib/Sema/SemaExpr.cpp (+1534-1453) 
- (modified) clang/test/Sema/builtins-elementwise-math.c (+4) 
- (added) clang/test/Sema/warn-compare-enum-types-mismatch.c (+42) 
- (renamed) clang/test/Sema/warn-conditional-enum-types-mismatch.c (+1-1) 
- (modified) clang/test/Sema/warn-overlap.c (+2-2) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index ece6013f672621..00ddf0b9656a31 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -161,6 +161,9 @@ Improvements to Clang's time-trace
 
 Bug Fixes in This Version
 -
+- Fixed missing warnings when comparing mismatched enumeration constants
+  in C (`#29217 `).
+
 - Clang now accepts elaborated-type-specifiers that explicitly specialize
   a member class template for an implicit instantiation of a class template.
 
diff --git a/clang/include/clang/AST/Expr.h b/clang/include/clang/AST/Expr.h
index 3fc481a62a78a9..4f11f3eb610564 100644
--- a/clang/include/clang/AST/Expr.h
+++ b/clang/include/clang/AST/Expr.h
@@ -40,26 +40,26 @@
 #include 
 
 namespace clang {
-  class APValue;
-  class ASTContext;
-  class BlockDecl;
-  class CXXBaseSpecifier;
-  class CXXMemberCallExpr;
-  class CXXOperatorCallExpr;
-  class CastExpr;
-  class Decl;
-  class IdentifierInfo;
-  class MaterializeTemporaryExpr;
-  class NamedDecl;
-  class ObjCPropertyRefExpr;
-  class OpaqueValueExpr;
-  class ParmVarDecl;
-  class StringLiteral;
-  class TargetInfo;
-  class ValueDecl;
+class APValue;
+class ASTContext;
+class BlockDecl;
+class CXXBaseSpecifier;
+class CXXMemberCallExpr;
+class CXXOperatorCallExpr;
+class CastExpr;
+class Decl;
+class IdentifierInfo;
+class MaterializeTemporaryExpr;
+class NamedDecl;
+class ObjCPropertyRefExpr;
+class OpaqueValueExpr;
+class ParmVarDecl;
+class StringLiteral;
+class TargetInfo;
+class ValueDecl;
 
 /// A simple array of base specifiers.
-typedef SmallVector CXXCastPath;
+typedef SmallVector CXXCastPath;
 
 /// An adjustment to be made to the temporary created when emitting a
 /// reference binding, which accesses a particular subobject of that temporary.
@@ -88,7 +88,7 @@ struct SubobjectAdjustment {
 
   SubobjectAdjustment(const CastExpr *BasePath,
   const CXXRecordDecl *DerivedClass)
-: Kind(DerivedToBaseAdjustment) {
+  : Kind(DerivedToBaseAdjustment) {
 DerivedToBase.BasePath = BasePath;
 DerivedToBase.DerivedClass = DerivedClass;
   }
@@ -98,7 +98,7 @@ struct SubobjectAdjustment {
   }
 
   SubobjectAdjustment(const MemberPointerType *MPT, Expr *RHS)
-: Kind(MemberPointerAdjustment) {
+  : Kind(MemberPointerAdjustment) {
 this->Ptr.MPT = MPT;
 this->Ptr.RHS = RHS;
   }
@@ -112,10 +112,10 @@ class Expr : public ValueStmt {
 
 public:
   Expr() = delete;
-  Expr(const Expr&) = delete;
+  Expr(const Expr &) = delete;
   Expr(Expr &&) = delete;
-  Expr &operator=(const Expr&) = delete;
-  Expr &operator=(Expr&&) = delete;
+  Expr &operator=(const Expr &) = delete;
+  Expr &operator=(Expr &&) = delete;
 
 protected:
   Expr(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK)
@@ -128,7 +128,7 @@ class Expr : public ValueStmt {
   }
 
   /// Construct an empty expression.
-  explicit Expr(StmtClass SC, EmptyShell) : ValueStmt(SC) { }
+  explicit Expr(StmtClass SC, EmptyShell) : ValueStmt(SC) {}
 
   /// Each concrete expr subclass is expected to compute its dependence and 
call
   /// this in the constructor.
@@ -153,6 +153,12 @@ class Expr : public ValueStmt {
 TR = t;
   }
 
+  /// If this expression is an enumeration constant, return the
+  /// enumeration type under which said constant was declared.
+  /// Otherwise return the expression's type.
+  /// Note this effectively circumvents the weak typing of C's enum constants
+  QualType getEnumCoercedType(const ASTContext &Ctx) const;
+
   ExprDependence getDependence() const {
 return static_cast(ExprBits.Dependent);
   }
@@ -294,7 +300,7 @@ class Expr : public ValueStmt {
 MLV_IncompleteVoidType,
 MLV_DuplicateVectorComponents,
 MLV_InvalidExpression,
-MLV_LValueCast,   // Specialized form of MLV_InvalidExpression.
+MLV_LValueCast, // Specialized form of MLV_InvalidExpression.
 MLV_IncompleteType,
 MLV_ConstQu

[clang] [ObjC] Check entire chain of superclasses to see if class has fixed offsets (PR #81335)

2024-02-10 Thread via cfe-commits

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


[clang] [ObjC] Check entire chain of superclasses to see if class has fixed offsets (PR #81335)

2024-02-10 Thread via cfe-commits

https://github.com/AtariDreams updated 
https://github.com/llvm/llvm-project/pull/81335

>From 527e24ae4d6f662c2bee1a281914df028bcd01e1 Mon Sep 17 00:00:00 2001
From: Rose <83477269+ataridre...@users.noreply.github.com>
Date: Fri, 9 Feb 2024 17:51:15 -0500
Subject: [PATCH 1/2] [ObjC] Add pre-commit tests [NFC]

---
 .../constant-non-fragile-ivar-offset.m| 84 +++
 1 file changed, 84 insertions(+)

diff --git a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m 
b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
index 788b3220af3067..bed6497f8827ae 100644
--- a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
+++ b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
@@ -1,6 +1,13 @@
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 -emit-llvm %s -o - | 
FileCheck %s
 
 // CHECK: @"OBJC_IVAR_$_StaticLayout.static_layout_ivar" = hidden constant i64 
20
+// CHECK: @"OBJC_IVAR_$_StaticLayoutSubClass.static_layout_ivar2" = hidden 
constant i64 24
+// CHECK: @"OBJC_IVAR_$_MyClass.myIvar" = constant i64 20
+// CHECK: @"OBJC_IVAR_$_MyClass._myProperty" = hidden constant i64 24
+// CHECK: @"OBJC_IVAR_$_AnotherClass.privateId" = constant i64 24
+// CHECK: @"OBJC_IVAR_$_AnotherClass.anotherPrivateId" = hidden constant i64 32
+// CHECK: @"OBJC_IVAR_$_SuperClass.superClassIvar" = constant i64 20
+// CHECK: @"OBJC_IVAR_$_SubClass.subClassIvar" = global i64 24
 // CHECK: @"OBJC_IVAR_$_NotStaticLayout.not_static_layout_ivar" = hidden 
global i64 12
 
 @interface NSObject {
@@ -20,6 +27,83 @@ -(void)meth {
 }
 @end
 
+// Scenario 1: Ivars declared in the @interface
+@interface MyClass : NSObject
+{
+int myIvar; // Declare an ivar
+}
+
+@property (nonatomic, assign) int myProperty; // Synthesize a property
+
+@end
+
+@implementation MyClass 
+
+- (void)exampleMethod {
+self.myProperty = 42; // Access the property
+myIvar = 10; // Access the ivar directly
+}
+
+@end
+
+// Scenario 2: Ivars declared directly in the @implementation
+@interface AnotherClass : NSObject
+{
+  id privateId;
+}
+
+@end
+
+@implementation AnotherClass
+{
+id anotherPrivateId; // Declare an ivar directly in the implementation
+}
+
+- (void)doSomething {
+   privateId = anotherPrivateId;
+}
+
+@end
+
+// Scenario 3: Inheritance and Ivars
+@interface SuperClass : NSObject
+{
+int superClassIvar;
+}
+@end
+
+@implementation SuperClass
+@end
+
+@interface SubClass : SuperClass
+{
+double subClassIvar;
+}
+@end
+
+@implementation SubClass
+- (void)exampleMethod {
+// CHECK: load i64, ptr @"OBJC_IVAR_$SuperClass
+superClassIvar = 100; // Access superclass ivar
+subClassIvar = 3.14; // Access subclass ivar
+}
+@end
+
+// Scenario 4: Custom Getter/Setter Methods
+@interface CustomPropertyClass : NSObject
+@property (nonatomic, strong, getter=myCustomGetter, setter=myCustomSetter:) 
id customProperty;
+@end
+
+@implementation CustomPropertyClass
+- (id) myCustomGetter {
+return 0;
+}
+
+- (void)myCustomSetter:(id)newValue {
+// Custom setter logic
+}
+@end
+
 @interface NotNSObject {
   int these, might, change;
 }

>From 467244d2c2fe6e0c526344360326e704616295d2 Mon Sep 17 00:00:00 2001
From: Rose <83477269+ataridre...@users.noreply.github.com>
Date: Fri, 9 Feb 2024 17:47:59 -0500
Subject: [PATCH 2/2] [ObjC] Check entire chain of superclasses to see if class
 has fixed offsets

As of now, we only check if a class directly inherits from NSObject to 
determine if said lass has fixed offsets and can therefore "opt-out" from the 
non-fragile ABI for ivars.

However, if an NSObject subclass has fixed offsets, then so must the subclasses 
of that subclass, so this allows us to optimize instances of subclasses of 
subclasses that inherit from NSObject and so on.

To determine this, we need to find that the compiler can see the implementation 
of each intermediate class, as that means it is statically linked.

Perhaps there is another way to figure this out at link time as well, but that 
is for another time and another PR.

Fixes: #81369
---
 clang/lib/CodeGen/CGObjCMac.cpp   | 22 ++-
 .../constant-non-fragile-ivar-offset.m|  6 ++---
 2 files changed, 19 insertions(+), 9 deletions(-)

diff --git a/clang/lib/CodeGen/CGObjCMac.cpp b/clang/lib/CodeGen/CGObjCMac.cpp
index 27d77e9a8a5511..ceee70a5d79b3e 100644
--- a/clang/lib/CodeGen/CGObjCMac.cpp
+++ b/clang/lib/CodeGen/CGObjCMac.cpp
@@ -1593,12 +1593,22 @@ class CGObjCNonFragileABIMac : public CGObjCCommonMac {
   }
 
   bool isClassLayoutKnownStatically(const ObjCInterfaceDecl *ID) {
-// NSObject is a fixed size. If we can see the @implementation of a class
-// which inherits from NSObject then we know that all it's offsets also 
must
-// be fixed. FIXME: Can we do this if see a chain of super classes with
-// implementations leading to NSObject?
-return ID->getImplementation() && ID->getSuperClass() &&
-   ID->getSuperClass()->getName() == "NSObject";
+

[clang] [Clang][Sema] Fix missing warning when comparing mismatched enums in … (PR #81389)

2024-02-10 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 b17348c3b541d7fc7ec441c98db75c18d8959910 
b256939140c99356f2ab41e2c69f3d218ffc81a6 -- 
clang/test/Sema/warn-compare-enum-types-mismatch.c 
clang/include/clang/AST/Expr.h clang/lib/AST/Expr.cpp 
clang/lib/Sema/SemaChecking.cpp clang/lib/Sema/SemaExpr.cpp 
clang/test/Sema/builtins-elementwise-math.c clang/test/Sema/warn-overlap.c 
clang/test/Sema/warn-conditional-enum-types-mismatch.c
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 2ccd8f5842..bfd8dbced1 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -9735,7 +9735,8 @@ ExprResult Sema::SemaConvertVectorExpr(Expr *E, 
TypeSourceInfo *TInfo,
  << E->getSourceRange());
   if (!DstTy->isVectorType() && !DstTy->isDependentType())
 return ExprError(Diag(BuiltinLoc, diag::err_builtin_non_vector_type)
- << "second" << "__builtin_convertvector");
+ << "second"
+ << "__builtin_convertvector");
 
   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
 unsigned SrcElts = SrcTy->castAs()->getNumElements();
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index dbcd1513ed..cf2131c2f4 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -4354,7 +4354,8 @@ static bool CheckVectorElementsTraitOperandType(Sema &S, 
QualType T,
   // builtin_vectorelements supports both fixed-sized and scalable vectors.
   if (!T->isVectorType() && !T->isSizelessVectorType())
 return S.Diag(Loc, diag::err_builtin_non_vector_type)
-   << "" << "__builtin_vectorelements" << T << ArgRange;
+   << ""
+   << "__builtin_vectorelements" << T << ArgRange;
 
   return false;
 }

``




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


[clang] [ObjC] Check entire chain of superclasses to see if class has fixed offsets (PR #81335)

2024-02-10 Thread via cfe-commits

https://github.com/AtariDreams updated 
https://github.com/llvm/llvm-project/pull/81335

>From 4bdf6f78a595e7e33387a1b4f1f80286b0163d47 Mon Sep 17 00:00:00 2001
From: Rose <83477269+ataridre...@users.noreply.github.com>
Date: Fri, 9 Feb 2024 17:51:15 -0500
Subject: [PATCH 1/2] [ObjC] Add pre-commit tests [NFC]

---
 .../constant-non-fragile-ivar-offset.m| 83 +++
 1 file changed, 83 insertions(+)

diff --git a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m 
b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
index 788b3220af3067..e9096f2449a859 100644
--- a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
+++ b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
@@ -1,6 +1,13 @@
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 -emit-llvm %s -o - | 
FileCheck %s
 
 // CHECK: @"OBJC_IVAR_$_StaticLayout.static_layout_ivar" = hidden constant i64 
20
+// CHECK: @"OBJC_IVAR_$_StaticLayoutSubClass.static_layout_ivar2" = hidden 
constant i64 24
+// CHECK: @"OBJC_IVAR_$_MyClass.myIvar" = constant i64 20
+// CHECK: @"OBJC_IVAR_$_MyClass._myProperty" = hidden constant i64 24
+// CHECK: @"OBJC_IVAR_$_AnotherClass.privateId" = constant i64 24
+// CHECK: @"OBJC_IVAR_$_AnotherClass.anotherPrivateId" = hidden constant i64 32
+// CHECK: @"OBJC_IVAR_$_SuperClass.superClassIvar" = constant i64 20
+// CHECK: @"OBJC_IVAR_$_SubClass.subClassIvar" = global i64 24
 // CHECK: @"OBJC_IVAR_$_NotStaticLayout.not_static_layout_ivar" = hidden 
global i64 12
 
 @interface NSObject {
@@ -20,6 +27,82 @@ -(void)meth {
 }
 @end
 
+// Scenario 1: Ivars declared in the @interface
+@interface MyClass : NSObject
+{
+int myIvar; // Declare an ivar
+}
+
+@property (nonatomic, assign) int myProperty; // Synthesize a property
+
+@end
+
+@implementation MyClass 
+
+- (void)exampleMethod {
+self.myProperty = 42; // Access the property
+myIvar = 10; // Access the ivar directly
+}
+
+@end
+
+// Scenario 2: Ivars declared directly in the @implementation
+@interface AnotherClass : NSObject
+{
+  id privateId;
+}
+
+@end
+
+@implementation AnotherClass
+{
+id anotherPrivateId; // Declare an ivar directly in the implementation
+}
+
+- (void)doSomething {
+   privateId = anotherPrivateId;
+}
+
+@end
+
+// Scenario 3: Inheritance and Ivars
+@interface SuperClass : NSObject
+{
+int superClassIvar;
+}
+@end
+
+@implementation SuperClass
+@end
+
+@interface SubClass : SuperClass
+{
+double subClassIvar;
+}
+@end
+
+@implementation SubClass
+- (void)exampleMethod {
+// CHECK: load i64, ptr @"OBJC_IVAR_$SuperClass
+superClassIvar = 100; // Access superclass ivar
+subClassIvar = 3.14; // Access subclass ivar
+}
+@end
+
+// Scenario 4: Custom Getter/Setter Methods
+@interface CustomPropertyClass : NSObject
+@property (nonatomic, strong, getter=myCustomGetter, setter=myCustomSetter:) 
id customProperty;
+@end
+
+@implementation CustomPropertyClass
+- (id) myCustomGetter {
+return 0;
+}
+
+- (void)myCustomSetter:(id)newValue {
+}
+@end
+
 @interface NotNSObject {
   int these, might, change;
 }

>From 1b8bbd58639e7519d74336e9a28c2f58e6aa3696 Mon Sep 17 00:00:00 2001
From: Rose <83477269+ataridre...@users.noreply.github.com>
Date: Fri, 9 Feb 2024 17:47:59 -0500
Subject: [PATCH 2/2] [ObjC] Check entire chain of superclasses to see if class
 has fixed offsets

As of now, we only check if a class directly inherits from NSObject to 
determine if said lass has fixed offsets and can therefore "opt-out" from the 
non-fragile ABI for ivars.

However, if an NSObject subclass has fixed offsets, then so must the subclasses 
of that subclass, so this allows us to optimize instances of subclasses of 
subclasses that inherit from NSObject and so on.

To determine this, we need to find that the compiler can see the implementation 
of each intermediate class, as that means it is statically linked.

Perhaps there is another way to figure this out at link time as well, but that 
is for another time and another PR.

Fixes: #81369
---
 clang/lib/CodeGen/CGObjCMac.cpp   | 22 ++-
 .../constant-non-fragile-ivar-offset.m|  6 ++---
 2 files changed, 19 insertions(+), 9 deletions(-)

diff --git a/clang/lib/CodeGen/CGObjCMac.cpp b/clang/lib/CodeGen/CGObjCMac.cpp
index 27d77e9a8a5511..ceee70a5d79b3e 100644
--- a/clang/lib/CodeGen/CGObjCMac.cpp
+++ b/clang/lib/CodeGen/CGObjCMac.cpp
@@ -1593,12 +1593,22 @@ class CGObjCNonFragileABIMac : public CGObjCCommonMac {
   }
 
   bool isClassLayoutKnownStatically(const ObjCInterfaceDecl *ID) {
-// NSObject is a fixed size. If we can see the @implementation of a class
-// which inherits from NSObject then we know that all it's offsets also 
must
-// be fixed. FIXME: Can we do this if see a chain of super classes with
-// implementations leading to NSObject?
-return ID->getImplementation() && ID->getSuperClass() &&
-   ID->getSuperClass()->getName() == "NSObject";
+// Test a class by check

[clang] [ObjC] Check entire chain of superclasses to see if class has fixed offsets (PR #81335)

2024-02-10 Thread via cfe-commits

https://github.com/AtariDreams updated 
https://github.com/llvm/llvm-project/pull/81335

>From 4bdf6f78a595e7e33387a1b4f1f80286b0163d47 Mon Sep 17 00:00:00 2001
From: Rose <83477269+ataridre...@users.noreply.github.com>
Date: Fri, 9 Feb 2024 17:51:15 -0500
Subject: [PATCH 1/2] [ObjC] Add pre-commit tests [NFC]

---
 .../constant-non-fragile-ivar-offset.m| 83 +++
 1 file changed, 83 insertions(+)

diff --git a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m 
b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
index 788b3220af3067..e9096f2449a859 100644
--- a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
+++ b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
@@ -1,6 +1,13 @@
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 -emit-llvm %s -o - | 
FileCheck %s
 
 // CHECK: @"OBJC_IVAR_$_StaticLayout.static_layout_ivar" = hidden constant i64 
20
+// CHECK: @"OBJC_IVAR_$_StaticLayoutSubClass.static_layout_ivar2" = hidden 
constant i64 24
+// CHECK: @"OBJC_IVAR_$_MyClass.myIvar" = constant i64 20
+// CHECK: @"OBJC_IVAR_$_MyClass._myProperty" = hidden constant i64 24
+// CHECK: @"OBJC_IVAR_$_AnotherClass.privateId" = constant i64 24
+// CHECK: @"OBJC_IVAR_$_AnotherClass.anotherPrivateId" = hidden constant i64 32
+// CHECK: @"OBJC_IVAR_$_SuperClass.superClassIvar" = constant i64 20
+// CHECK: @"OBJC_IVAR_$_SubClass.subClassIvar" = global i64 24
 // CHECK: @"OBJC_IVAR_$_NotStaticLayout.not_static_layout_ivar" = hidden 
global i64 12
 
 @interface NSObject {
@@ -20,6 +27,82 @@ -(void)meth {
 }
 @end
 
+// Scenario 1: Ivars declared in the @interface
+@interface MyClass : NSObject
+{
+int myIvar; // Declare an ivar
+}
+
+@property (nonatomic, assign) int myProperty; // Synthesize a property
+
+@end
+
+@implementation MyClass 
+
+- (void)exampleMethod {
+self.myProperty = 42; // Access the property
+myIvar = 10; // Access the ivar directly
+}
+
+@end
+
+// Scenario 2: Ivars declared directly in the @implementation
+@interface AnotherClass : NSObject
+{
+  id privateId;
+}
+
+@end
+
+@implementation AnotherClass
+{
+id anotherPrivateId; // Declare an ivar directly in the implementation
+}
+
+- (void)doSomething {
+   privateId = anotherPrivateId;
+}
+
+@end
+
+// Scenario 3: Inheritance and Ivars
+@interface SuperClass : NSObject
+{
+int superClassIvar;
+}
+@end
+
+@implementation SuperClass
+@end
+
+@interface SubClass : SuperClass
+{
+double subClassIvar;
+}
+@end
+
+@implementation SubClass
+- (void)exampleMethod {
+// CHECK: load i64, ptr @"OBJC_IVAR_$SuperClass
+superClassIvar = 100; // Access superclass ivar
+subClassIvar = 3.14; // Access subclass ivar
+}
+@end
+
+// Scenario 4: Custom Getter/Setter Methods
+@interface CustomPropertyClass : NSObject
+@property (nonatomic, strong, getter=myCustomGetter, setter=myCustomSetter:) 
id customProperty;
+@end
+
+@implementation CustomPropertyClass
+- (id) myCustomGetter {
+return 0;
+}
+
+- (void)myCustomSetter:(id)newValue {
+}
+@end
+
 @interface NotNSObject {
   int these, might, change;
 }

>From 3679a6b4b575e00433e6e2d2bff7df96df201d1c Mon Sep 17 00:00:00 2001
From: Rose <83477269+ataridre...@users.noreply.github.com>
Date: Fri, 9 Feb 2024 17:47:59 -0500
Subject: [PATCH 2/2] [ObjC] Check entire chain of superclasses to see if class
 has fixed offsets

As of now, we only check if a class directly inherits from NSObject to 
determine if said lass has fixed offsets and can therefore "opt-out" from the 
non-fragile ABI for ivars.

However, if an NSObject subclass has fixed offsets, then so must the subclasses 
of that subclass, so this allows us to optimize instances of subclasses of 
subclasses that inherit from NSObject and so on.

To determine this, we need to find that the compiler can see the implementation 
of each intermediate class, as that means it is statically linked.

Perhaps there is another way to figure this out at link time as well, but that 
is for another time and another PR.

Fixes: #81369
---
 clang/lib/CodeGen/CGObjCMac.cpp   | 22 ++-
 .../constant-non-fragile-ivar-offset.m|  4 ++--
 2 files changed, 18 insertions(+), 8 deletions(-)

diff --git a/clang/lib/CodeGen/CGObjCMac.cpp b/clang/lib/CodeGen/CGObjCMac.cpp
index 27d77e9a8a5511..ceee70a5d79b3e 100644
--- a/clang/lib/CodeGen/CGObjCMac.cpp
+++ b/clang/lib/CodeGen/CGObjCMac.cpp
@@ -1593,12 +1593,22 @@ class CGObjCNonFragileABIMac : public CGObjCCommonMac {
   }
 
   bool isClassLayoutKnownStatically(const ObjCInterfaceDecl *ID) {
-// NSObject is a fixed size. If we can see the @implementation of a class
-// which inherits from NSObject then we know that all it's offsets also 
must
-// be fixed. FIXME: Can we do this if see a chain of super classes with
-// implementations leading to NSObject?
-return ID->getImplementation() && ID->getSuperClass() &&
-   ID->getSuperClass()->getName() == "NSObject";
+// Test a class by checki

[clang] [Clang][Sema] Fix missing warning when comparing mismatched enums in … (PR #81389)

2024-02-10 Thread via cfe-commits

44-2-Kupa-Martin wrote:

Got the formatter wrong

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


[clang] [Clang][Sema] Fix missing warning when comparing mismatched enums in … (PR #81389)

2024-02-10 Thread via cfe-commits

https://github.com/44-2-Kupa-Martin closed 
https://github.com/llvm/llvm-project/pull/81389
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [ObjC] Check entire chain of superclasses to see if class has fixed offsets (PR #81335)

2024-02-10 Thread via cfe-commits

https://github.com/AtariDreams updated 
https://github.com/llvm/llvm-project/pull/81335

>From 3287e1ddb572f73ca774e50323b037d50b600e34 Mon Sep 17 00:00:00 2001
From: Rose <83477269+ataridre...@users.noreply.github.com>
Date: Fri, 9 Feb 2024 17:51:15 -0500
Subject: [PATCH 1/2] [ObjC] Add pre-commit tests [NFC]

---
 .../constant-non-fragile-ivar-offset.m| 82 +++
 1 file changed, 82 insertions(+)

diff --git a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m 
b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
index 788b3220af3067..6806fbf8f435aa 100644
--- a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
+++ b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
@@ -1,6 +1,12 @@
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 -emit-llvm %s -o - | 
FileCheck %s
 
 // CHECK: @"OBJC_IVAR_$_StaticLayout.static_layout_ivar" = hidden constant i64 
20
+// CHECK: @"OBJC_IVAR_$_MyClass.myIvar" = constant i64 20
+// CHECK: @"OBJC_IVAR_$_MyClass._myProperty" = hidden constant i64 24
+// CHECK: @"OBJC_IVAR_$_AnotherClass.privateId" = constant i64 24
+// CHECK: @"OBJC_IVAR_$_AnotherClass.anotherPrivateId" = hidden constant i64 32
+// CHECK: @"OBJC_IVAR_$_SuperClass.superClassIvar" = constant i64 20
+// CHECK: @"OBJC_IVAR_$_SubClass.subClassIvar" = global i64 24
 // CHECK: @"OBJC_IVAR_$_NotStaticLayout.not_static_layout_ivar" = hidden 
global i64 12
 
 @interface NSObject {
@@ -20,6 +26,82 @@ -(void)meth {
 }
 @end
 
+// Scenario 1: Ivars declared in the @interface
+@interface MyClass : NSObject
+{
+int myIvar; // Declare an ivar
+}
+
+@property (nonatomic, assign) int myProperty; // Synthesize a property
+
+@end
+
+@implementation MyClass 
+
+- (void)exampleMethod {
+self.myProperty = 42; // Access the property
+myIvar = 10; // Access the ivar directly
+}
+
+@end
+
+// Scenario 2: Ivars declared directly in the @implementation
+@interface AnotherClass : NSObject
+{
+  id privateId;
+}
+
+@end
+
+@implementation AnotherClass
+{
+id anotherPrivateId; // Declare an ivar directly in the implementation
+}
+
+- (void)doSomething {
+   privateId = anotherPrivateId;
+}
+
+@end
+
+// Scenario 3: Inheritance and Ivars
+@interface SuperClass : NSObject
+{
+int superClassIvar;
+}
+@end
+
+@implementation SuperClass
+@end
+
+@interface SubClass : SuperClass
+{
+double subClassIvar;
+}
+@end
+
+@implementation SubClass
+- (void)exampleMethod {
+// CHECK: load i64, ptr @"OBJC_IVAR_$SuperClass
+superClassIvar = 100; // Access superclass ivar
+subClassIvar = 3.14; // Access subclass ivar
+}
+@end
+
+// Scenario 4: Custom Getter/Setter Methods
+@interface CustomPropertyClass : NSObject
+@property (nonatomic, strong, getter=myCustomGetter, setter=myCustomSetter:) 
id customProperty;
+@end
+
+@implementation CustomPropertyClass
+- (id) myCustomGetter {
+return 0;
+}
+
+- (void)myCustomSetter:(id)newValue {
+}
+@end
+
 @interface NotNSObject {
   int these, might, change;
 }

>From 698bb848e711093fddae88b780f86e67be0306e9 Mon Sep 17 00:00:00 2001
From: Rose <83477269+ataridre...@users.noreply.github.com>
Date: Fri, 9 Feb 2024 17:47:59 -0500
Subject: [PATCH 2/2] [ObjC] Check entire chain of superclasses to see if class
 has fixed offsets

As of now, we only check if a class directly inherits from NSObject to 
determine if said lass has fixed offsets and can therefore "opt-out" from the 
non-fragile ABI for ivars.

However, if an NSObject subclass has fixed offsets, then so must the subclasses 
of that subclass, so this allows us to optimize instances of subclasses of 
subclasses that inherit from NSObject and so on.

To determine this, we need to find that the compiler can see the implementation 
of each intermediate class, as that means it is statically linked.

Perhaps there is another way to figure this out at link time as well, but that 
is for another time and another PR.

Fixes: #81369
---
 clang/lib/CodeGen/CGObjCMac.cpp   | 22 ++-
 .../constant-non-fragile-ivar-offset.m|  4 ++--
 2 files changed, 18 insertions(+), 8 deletions(-)

diff --git a/clang/lib/CodeGen/CGObjCMac.cpp b/clang/lib/CodeGen/CGObjCMac.cpp
index 27d77e9a8a5511..ceee70a5d79b3e 100644
--- a/clang/lib/CodeGen/CGObjCMac.cpp
+++ b/clang/lib/CodeGen/CGObjCMac.cpp
@@ -1593,12 +1593,22 @@ class CGObjCNonFragileABIMac : public CGObjCCommonMac {
   }
 
   bool isClassLayoutKnownStatically(const ObjCInterfaceDecl *ID) {
-// NSObject is a fixed size. If we can see the @implementation of a class
-// which inherits from NSObject then we know that all it's offsets also 
must
-// be fixed. FIXME: Can we do this if see a chain of super classes with
-// implementations leading to NSObject?
-return ID->getImplementation() && ID->getSuperClass() &&
-   ID->getSuperClass()->getName() == "NSObject";
+// Test a class by checking its superclasses up to its base class if it has
+// one
+while (ID) {
+  // Th

[clang] [ObjC] Check entire chain of superclasses to see if class has fixed offsets (PR #81335)

2024-02-10 Thread via cfe-commits

AtariDreams wrote:

Layout before and after my change:
https://github.com/llvm/llvm-project/assets/83477269/6e45ad11-16e8-4dcc-8d7b-f8e29a1a9cc0";>


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


[clang] [ObjC] Check entire chain of superclasses to see if class has fixed offsets (PR #81335)

2024-02-10 Thread via cfe-commits

AtariDreams wrote:

Sorry, that was codegen, I meant 
![image](https://github.com/llvm/llvm-project/assets/83477269/cd59af73-2f4a-48b6-b847-0994c8191ab2)


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


  1   2   >