[clang] [clang][analyzer] Fix argument invalidations in StreamChecker. (PR #79470)

2024-02-22 Thread Balázs Kéri via cfe-commits

https://github.com/balazske updated 
https://github.com/llvm/llvm-project/pull/79470

From 70eeae8170a782b93b546b81ac913e1b8eacd28e Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Bal=C3=A1zs=20K=C3=A9ri?= 
Date: Thu, 22 Feb 2024 10:18:06 +0100
Subject: [PATCH 1/2] [clang][analyzer] Fix argument invalidations in
 StreamChecker.

Specific arguments passed to stream handling functions are changed by the 
function,
this means these should be invalidated ("escaped") by the analyzer.
This change adds the argument invalidation (in specific cases) to the checker.
---
 .../StaticAnalyzer/Checkers/StreamChecker.cpp | 39 ++-
 1 file changed, 38 insertions(+), 1 deletion(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index a070f451694a3b..65bdc4cac30940 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -21,6 +21,7 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
+#include "llvm/ADT/Sequence.h"
 #include 
 #include 
 
@@ -629,6 +630,21 @@ const ExplodedNode 
*StreamChecker::getAcquisitionSite(const ExplodedNode *N,
   return nullptr;
 }
 
+static ProgramStateRef escapeArgs(ProgramStateRef State, CheckerContext ,
+  const CallEvent ,
+  ArrayRef EscapingArgs) {
+  const auto *CE = Call.getOriginExpr();
+
+  SmallVector EscapingVals;
+  EscapingVals.reserve(EscapingArgs.size());
+  for (auto EscArgIdx : EscapingArgs)
+EscapingVals.push_back(Call.getArgSVal(EscArgIdx));
+  State = State->invalidateRegions(EscapingVals, CE, C.blockCount(),
+   C.getLocationContext(),
+   /*CausesPointerEscape=*/false);
+  return State;
+}
+
 
//===--===//
 // Methods of StreamChecker.
 
//===--===//
@@ -819,6 +835,11 @@ void StreamChecker::evalFreadFwrite(const FnDescription 
*Desc,
 return;
   }
 
+  // At read, invalidate the buffer in any case of error or success,
+  // except if EOF was already present.
+  if (IsFread && !E.isStreamEof())
+State = escapeArgs(State, C, Call, {0});
+
   // Generate a transition for the success state.
   // If we know the state to be FEOF at fread, do not add a success state.
   if (!IsFread || !E.isStreamEof()) {
@@ -863,6 +884,9 @@ void StreamChecker::evalFgetx(const FnDescription *Desc, 
const CallEvent ,
 return;
 
   if (!E.isStreamEof()) {
+// If there was already EOF, assume that read buffer is not changed.
+// Otherwise it may change at success or failure.
+State = escapeArgs(State, C, Call, {0});
 if (SingleChar) {
   // Generate a transition for the success state of `fgetc`.
   NonLoc RetVal = makeRetVal(C, E.CE).castAs();
@@ -1011,6 +1035,14 @@ void StreamChecker::evalFscanf(const FnDescription 
*Desc, const CallEvent ,
 State->BindExpr(E.CE, C.getLocationContext(), RetVal);
 StateNotFailed =
 E.assumeBinOpNN(StateNotFailed, BO_GE, RetVal, E.getZeroVal(Call));
+if (!StateNotFailed)
+  return;
+
+SmallVector EscArgs;
+for (auto EscArg : llvm::seq(2u, Call.getNumArgs()))
+  EscArgs.push_back(EscArg);
+StateNotFailed = escapeArgs(StateNotFailed, C, Call, EscArgs);
+
 if (StateNotFailed)
   C.addTransition(StateNotFailed);
   }
@@ -1073,8 +1105,12 @@ void StreamChecker::evalGetdelim(const FnDescription 
*Desc,
   // return -1.
   // If an error occurs, the function shall return -1 and set 'errno'.
 
-  // Add transition for the successful state.
   if (!E.isStreamEof()) {
+// Escape buffer and size (may change by the call).
+// May happen even at error (partial read?).
+State = escapeArgs(State, C, Call, {0, 1});
+
+// Add transition for the successful state.
 NonLoc RetVal = makeRetVal(C, E.CE).castAs();
 ProgramStateRef StateNotFailed =
 State->BindExpr(E.CE, C.getLocationContext(), RetVal);
@@ -1161,6 +1197,7 @@ void StreamChecker::evalFgetpos(const FnDescription *Desc,
 
   ProgramStateRef StateNotFailed, StateFailed;
   std::tie(StateFailed, StateNotFailed) = E.makeRetValAndAssumeDual(State, C);
+  StateNotFailed = escapeArgs(StateNotFailed, C, Call, {1});
 
   // This function does not affect the stream state.
   // Still we add success and failure state with the appropriate return value.

From deb62b2e2694e8a45eca1c6001b8d90dfb1b1d7b Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Bal=C3=A1zs=20K=C3=A9ri?= 
Date: Fri, 23 Feb 2024 08:59:03 +0100
Subject: [PATCH 2/2] Add test file

---
 clang/test/Analysis/stream-invalidate.c | 147 
 1 file changed, 147 insertions(+)
 create 

[clang] [Clang][Sema] Print more static_assert exprs (PR #74852)

2024-02-22 Thread Timm Baeder via cfe-commits

tbaederr wrote:

Ping @cor3ntin @cjdb 

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


[clang] [compiler-rt] [llvm] [X86] Support APXF to enable __builtin_cpu_supports. (PR #80636)

2024-02-22 Thread Freddy Ye via cfe-commits

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


[clang] 1fe6be8 - [X86] Support APXF to enable __builtin_cpu_supports. (#80636)

2024-02-22 Thread via cfe-commits

Author: Freddy Ye
Date: 2024-02-23T15:18:42+08:00
New Revision: 1fe6be8794964c011aeba7a66bd2dcd891d21ab0

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

LOG: [X86] Support APXF to enable __builtin_cpu_supports. (#80636)

For referring, APX's spec:
https://cdrdv2.intel.com/v1/dl/getContent/784266
APX's index in libgcc:
https://github.com/gcc-mirror/gcc/blob/master/gcc/common/config/i386/i386-cpuinfo.h#L267

Added: 


Modified: 
clang/lib/Headers/cpuid.h
clang/test/CodeGen/target-builtin-noerror.c
compiler-rt/lib/builtins/cpu_model/x86.c
llvm/include/llvm/TargetParser/X86TargetParser.def
llvm/lib/TargetParser/Host.cpp

Removed: 




diff  --git a/clang/lib/Headers/cpuid.h b/clang/lib/Headers/cpuid.h
index c968d37fb8cd64..0bb9912b465ffe 100644
--- a/clang/lib/Headers/cpuid.h
+++ b/clang/lib/Headers/cpuid.h
@@ -219,6 +219,7 @@
 #define bit_PREFETCHI 0x4000
 #define bit_USERMSR   0x8000
 #define bit_AVX10 0x0008
+#define bit_APXF  0x0020
 
 /* Features in %eax for leaf 13 sub-leaf 1 */
 #define bit_XSAVEOPT0x0001

diff  --git a/clang/test/CodeGen/target-builtin-noerror.c 
b/clang/test/CodeGen/target-builtin-noerror.c
index 9608b5f37baaae..b438e50848a4b6 100644
--- a/clang/test/CodeGen/target-builtin-noerror.c
+++ b/clang/test/CodeGen/target-builtin-noerror.c
@@ -141,6 +141,7 @@ void verifyfeaturestrings(void) {
   (void)__builtin_cpu_supports("sm3");
   (void)__builtin_cpu_supports("sha512");
   (void)__builtin_cpu_supports("sm4");
+  (void)__builtin_cpu_supports("apxf");
   (void)__builtin_cpu_supports("usermsr");
   (void)__builtin_cpu_supports("avx10.1-256");
   (void)__builtin_cpu_supports("avx10.1-512");

diff  --git a/compiler-rt/lib/builtins/cpu_model/x86.c 
b/compiler-rt/lib/builtins/cpu_model/x86.c
index 1afa468c4ae8c1..7e8acb3e73eda9 100644
--- a/compiler-rt/lib/builtins/cpu_model/x86.c
+++ b/compiler-rt/lib/builtins/cpu_model/x86.c
@@ -217,8 +217,8 @@ enum ProcessorFeatures {
   FEATURE_SM3,
   FEATURE_SHA512,
   FEATURE_SM4,
-  // FEATURE_APXF,
-  FEATURE_USERMSR = 112,
+  FEATURE_APXF,
+  FEATURE_USERMSR,
   FEATURE_AVX10_1_256,
   FEATURE_AVX10_1_512,
   CPU_FEATURE_MAX
@@ -983,6 +983,8 @@ static void getAvailableFeatures(unsigned ECX, unsigned 
EDX, unsigned MaxLeaf,
 setFeature(FEATURE_USERMSR);
   if (HasLeaf7Subleaf1 && ((EDX >> 19) & 1))
 setFeature(FEATURE_AVX10_1_256);
+  if (HasLeaf7Subleaf1 && ((EDX >> 21) & 1))
+setFeature(FEATURE_APXF);
 
   unsigned MaxLevel;
   getX86CpuIDAndInfo(0, , , , );

diff  --git a/llvm/include/llvm/TargetParser/X86TargetParser.def 
b/llvm/include/llvm/TargetParser/X86TargetParser.def
index 4c630c1eb06e8c..a9ed56fcd4700e 100644
--- a/llvm/include/llvm/TargetParser/X86TargetParser.def
+++ b/llvm/include/llvm/TargetParser/X86TargetParser.def
@@ -265,6 +265,7 @@ X86_MICROARCH_LEVEL(X86_64_BASELINE,"x86-64",   
95)
 X86_MICROARCH_LEVEL(X86_64_V2,  "x86-64-v2",96)
 X86_MICROARCH_LEVEL(X86_64_V3,  "x86-64-v3",97)
 X86_MICROARCH_LEVEL(X86_64_V4,  "x86-64-v4",98)
+X86_MICROARCH_LEVEL(APXF,   "apxf",111)
 #undef X86_FEATURE_COMPAT
 #undef X86_FEATURE
 #undef X86_MICROARCH_LEVEL

diff  --git a/llvm/lib/TargetParser/Host.cpp b/llvm/lib/TargetParser/Host.cpp
index 4466d50458e198..a4cc757a9214ef 100644
--- a/llvm/lib/TargetParser/Host.cpp
+++ b/llvm/lib/TargetParser/Host.cpp
@@ -1846,6 +1846,13 @@ bool sys::getHostCPUFeatures(StringMap ) {
   Features["prefetchi"]  = HasLeaf7Subleaf1 && ((EDX >> 14) & 1);
   Features["usermsr"]  = HasLeaf7Subleaf1 && ((EDX >> 15) & 1);
   Features["avx10.1-256"] = HasLeaf7Subleaf1 && ((EDX >> 19) & 1);
+  bool HasAPXF = HasLeaf7Subleaf1 && ((EDX >> 21) & 1);
+  Features["egpr"] = HasAPXF;
+  Features["push2pop2"] = HasAPXF;
+  Features["ppx"] = HasAPXF;
+  Features["ndd"] = HasAPXF;
+  Features["ccmp"] = HasAPXF;
+  Features["cf"] = HasAPXF;
 
   bool HasLeafD = MaxLevel >= 0xd &&
   !getX86CpuIDAndInfoEx(0xd, 0x1, , , , );



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


[clang] [compiler-rt] [llvm] [X86] Support APXF to enable __builtin_cpu_supports. (PR #80636)

2024-02-22 Thread Freddy Ye via cfe-commits

FreddyLeaf wrote:

Thank you both for all of the review!

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


[clang] [compiler-rt] [llvm] [X86] Support APXF to enable __builtin_cpu_supports. (PR #80636)

2024-02-22 Thread Shengchen Kan via cfe-commits

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

LGTM

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


[clang] [clang][analyzer] Fix argument invalidations in StreamChecker. (PR #79470)

2024-02-22 Thread Alejandro Álvarez Ayllón via cfe-commits


@@ -763,6 +779,11 @@ void StreamChecker::evalFreadFwrite(const FnDescription 
*Desc,
 return;
   }
 
+  // At read, invalidate the buffer in any case of error or success,
+  // except if EOF was already present.
+  if (IsFread && (OldSS->ErrorState != ErrorFEof))
+State = escapeArgs(State, C, Call, {0});

alejandro-alvarez-sonarsource wrote:

Ok, let’s do that, and send this patch as a separate pr. @steakhal LGTM.

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


[clang] [compiler-rt] [llvm] [X86] Support APXF to enable __builtin_cpu_supports. (PR #80636)

2024-02-22 Thread Freddy Ye via cfe-commits

FreddyLeaf wrote:

ping

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


[clang] [clang-format] Limit how much work guessLanguage() can do (PR #78925)

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

owenca wrote:

> > If we add a `bool GuessObjC` parameter to `guessLanguage()`, would that 
> > solve the problem?
> 
> I assume you mean making it so that when clangd calls into `guessLanguage()`, 
> the ObjC guessing algorithm is skipped entirely.

I'm not familiar with clangd use cases, but I thought the `GuessObjC` flag 
would allow clangd to skip the guessing ObjC part for those "users who merely 
use these libraries (and so may open them in the editor to look at the header, 
but will not try to format it)". If it wouldn't work as you pointed out, then 
we probably need a new ObjC guesser that only relies on the lexer, similar to 
what's done in 
[IntegerLiteralSeparatorFixer::process()](https://github.com/llvm/llvm-project/blob/afd469023aad10786eaea3d444047a558ad8d5c1/clang/lib/Format/IntegerLiteralSeparatorFixer.cpp#L45).

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


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

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

https://github.com/farzonl ready_for_review 
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] [OpenMP][Clang] Enable inscan modifier for generic datatypes (PR #82220)

2024-02-22 Thread Animesh Kumar via cfe-commits

https://github.com/animeshk-amd updated 
https://github.com/llvm/llvm-project/pull/82220

>From b5de1dd29956ae99ce7990554c4886453b2988e7 Mon Sep 17 00:00:00 2001
From: Animesh Kumar 
Date: Mon, 19 Feb 2024 00:28:39 -0600
Subject: [PATCH] [OpenMP][Clang] Enable inscan modifier for generic datatypes

This patch fixes the #67002 ([OpenMP][Clang] Scan Directive not
supported for Generic types). It disables the Sema checks/analysis
that are run on the helper arrays which go into the implementation
of the `omp scan` directive until the template instantiation
happens.
---
 clang/lib/Sema/SemaOpenMP.cpp|  3 ++-
 clang/test/OpenMP/scan_ast_print.cpp | 18 ++
 2 files changed, 20 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Sema/SemaOpenMP.cpp b/clang/lib/Sema/SemaOpenMP.cpp
index 7f75cfc5b54f35..f4364a259ad57f 100644
--- a/clang/lib/Sema/SemaOpenMP.cpp
+++ b/clang/lib/Sema/SemaOpenMP.cpp
@@ -4962,7 +4962,8 @@ StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
   if (RC->getModifier() != OMPC_REDUCTION_inscan)
 continue;
   for (Expr *E : RC->copy_array_temps())
-MarkDeclarationsReferencedInExpr(E);
+if (E)
+  MarkDeclarationsReferencedInExpr(E);
 }
 if (auto *AC = dyn_cast(C)) {
   for (Expr *E : AC->varlists())
diff --git a/clang/test/OpenMP/scan_ast_print.cpp 
b/clang/test/OpenMP/scan_ast_print.cpp
index 3bbd3b60c3e8c4..82cb13eb6e70f7 100644
--- a/clang/test/OpenMP/scan_ast_print.cpp
+++ b/clang/test/OpenMP/scan_ast_print.cpp
@@ -17,6 +17,10 @@ T tmain(T argc) {
   static T a;
 #pragma omp for reduction(inscan, +: a)
   for (int i = 0; i < 10; ++i) {
+#pragma omp scan inclusive(a)
+  }
+#pragma omp parallel for reduction(inscan, +:a)
+  for (int i = 0; i < 10; ++i) {
 #pragma omp scan inclusive(a)
   }
   return a + argc;
@@ -25,15 +29,29 @@ T tmain(T argc) {
 // CHECK-NEXT: #pragma omp for reduction(inscan, +: a)
 // CHECK-NEXT: for (int i = 0; i < 10; ++i) {
 // CHECK-NEXT: #pragma omp scan inclusive(a){{$}}
+
+// CHECK: #pragma omp parallel for reduction(inscan, +: a)
+// CHECK-NEXT: for (int i = 0; i < 10; ++i) {
+// CHECK-NEXT: #pragma omp scan inclusive(a){{$}}
+
 // CHECK:  static int a;
 // CHECK-NEXT: #pragma omp for reduction(inscan, +: a)
 // CHECK-NEXT: for (int i = 0; i < 10; ++i) {
 // CHECK-NEXT: #pragma omp scan inclusive(a)
+
+// CHECK: #pragma omp parallel for reduction(inscan, +: a)
+// CHECK-NEXT: for (int i = 0; i < 10; ++i) {
+// CHECK-NEXT: #pragma omp scan inclusive(a)
+
 // CHECK:  static char a;
 // CHECK-NEXT: #pragma omp for reduction(inscan, +: a)
 // CHECK-NEXT: for (int i = 0; i < 10; ++i) {
 // CHECK-NEXT: #pragma omp scan inclusive(a)
 
+// CHECK: #pragma omp parallel for reduction(inscan, +: a)
+// CHECK-NEXT: for (int i = 0; i < 10; ++i) {
+// CHECK-NEXT: #pragma omp scan inclusive(a)
+
 int main(int argc, char **argv) {
   static int a;
 // CHECK: static int a;

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


[clang] [llvm] [PGO]Add `-fdiagnostics-show-profile-count` option to show real loop count from instr-profile (PR #75021)

2024-02-22 Thread Elvis Wang via cfe-commits

ElvisWang123 wrote:

Ping

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


[clang] [clang-format][NFC] Enable RemoveSemicolon for clang-format style (PR #82735)

2024-02-22 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-format

Author: Owen Pan (owenca)


Changes

Also insert separators for decimal integers longer than 4 digits.

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


4 Files Affected:

- (modified) clang/lib/Format/Format.cpp (+4-1) 
- (modified) clang/lib/Format/FormatToken.cpp (+1-1) 
- (modified) clang/lib/Format/UnwrappedLineFormatter.cpp (+2-2) 
- (modified) clang/unittests/Format/FormatTest.cpp (+1-1) 


``diff
diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 10ab406a15c6e1..2f6b52510099a7 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -1591,7 +1591,7 @@ FormatStyle getLLVMStyle(FormatStyle::LanguageKind 
Language) {
   LLVMStyle.PenaltyBreakScopeResolution = 500;
   LLVMStyle.PenaltyBreakString = 1000;
   LLVMStyle.PenaltyBreakTemplateDeclaration = prec::Relational;
-  LLVMStyle.PenaltyExcessCharacter = 100;
+  LLVMStyle.PenaltyExcessCharacter = 1'000'000;
   LLVMStyle.PenaltyIndentedWhitespace = 0;
   LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
 
@@ -1914,9 +1914,12 @@ FormatStyle getClangFormatStyle() {
   FormatStyle Style = getLLVMStyle();
   Style.InsertBraces = true;
   Style.InsertNewlineAtEOF = true;
+  Style.IntegerLiteralSeparator.Decimal = 3;
+  Style.IntegerLiteralSeparator.DecimalMinDigits = 5;
   Style.LineEnding = FormatStyle::LE_LF;
   Style.RemoveBracesLLVM = true;
   Style.RemoveParentheses = FormatStyle::RPS_ReturnStatement;
+  Style.RemoveSemicolon = true;
   return Style;
 }
 
diff --git a/clang/lib/Format/FormatToken.cpp b/clang/lib/Format/FormatToken.cpp
index b791c5a26bbe3a..56a7b2d6387765 100644
--- a/clang/lib/Format/FormatToken.cpp
+++ b/clang/lib/Format/FormatToken.cpp
@@ -137,7 +137,7 @@ unsigned CommaSeparatedList::formatAfterToken(LineState 
,
   // bin-packed. Add a severe penalty to this so that column layouts are
   // preferred if possible.
   if (!Format)
-return 1;
+return 10'000;
 
   // Format the entire list.
   unsigned Penalty = 0;
diff --git a/clang/lib/Format/UnwrappedLineFormatter.cpp 
b/clang/lib/Format/UnwrappedLineFormatter.cpp
index adeb072434873f..fb31980ab9f491 100644
--- a/clang/lib/Format/UnwrappedLineFormatter.cpp
+++ b/clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -1221,7 +1221,7 @@ class OptimizingLineFormatter : public LineFormatter {
 // While not empty, take first element and follow edges.
 while (!Queue.empty()) {
   // Quit if we still haven't found a solution by now.
-  if (Count > 2500)
+  if (Count > 25'000'000)
 return 0;
 
   Penalty = Queue.top().first.first;
@@ -1235,7 +1235,7 @@ class OptimizingLineFormatter : public LineFormatter {
 
   // Cut off the analysis of certain solutions if the analysis gets too
   // complex. See description of IgnoreStackForComparison.
-  if (Count > 5)
+  if (Count > 50'000)
 Node->State.IgnoreStackForComparison = true;
 
   if (!Seen.insert(>State).second) {
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index b8dc01f55b4faa..d9752c73e34e79 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -21669,7 +21669,7 @@ TEST_F(FormatTest, BreakPenaltyAfterCastLParen) {
"int));",
 
Style);
-  Style.PenaltyBreakOpenParenthesis = 10;
+  Style.PenaltyBreakOpenParenthesis = 100'000;
   verifyFormat("foo((int)\n"
");",
"foo((\n"

``




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


[clang] [clang-format][NFC] Enable RemoveSemicolon for clang-format style (PR #82735)

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

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

Also insert separators for decimal integers longer than 4 digits.

>From e0a9d61283276bddda8231b599697cf4d497ff0a Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Thu, 22 Feb 2024 20:56:47 -0800
Subject: [PATCH] [clang-format][NFC] Enable RemoveSemicolon for clang-format
 style

Also insert separators for decimal integers longer than 4 digits.

Reformat clang-format source with the new options.
---
 clang/lib/Format/Format.cpp | 5 -
 clang/lib/Format/FormatToken.cpp| 2 +-
 clang/lib/Format/UnwrappedLineFormatter.cpp | 4 ++--
 clang/unittests/Format/FormatTest.cpp   | 2 +-
 4 files changed, 8 insertions(+), 5 deletions(-)

diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 10ab406a15c6e1..2f6b52510099a7 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -1591,7 +1591,7 @@ FormatStyle getLLVMStyle(FormatStyle::LanguageKind 
Language) {
   LLVMStyle.PenaltyBreakScopeResolution = 500;
   LLVMStyle.PenaltyBreakString = 1000;
   LLVMStyle.PenaltyBreakTemplateDeclaration = prec::Relational;
-  LLVMStyle.PenaltyExcessCharacter = 100;
+  LLVMStyle.PenaltyExcessCharacter = 1'000'000;
   LLVMStyle.PenaltyIndentedWhitespace = 0;
   LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
 
@@ -1914,9 +1914,12 @@ FormatStyle getClangFormatStyle() {
   FormatStyle Style = getLLVMStyle();
   Style.InsertBraces = true;
   Style.InsertNewlineAtEOF = true;
+  Style.IntegerLiteralSeparator.Decimal = 3;
+  Style.IntegerLiteralSeparator.DecimalMinDigits = 5;
   Style.LineEnding = FormatStyle::LE_LF;
   Style.RemoveBracesLLVM = true;
   Style.RemoveParentheses = FormatStyle::RPS_ReturnStatement;
+  Style.RemoveSemicolon = true;
   return Style;
 }
 
diff --git a/clang/lib/Format/FormatToken.cpp b/clang/lib/Format/FormatToken.cpp
index b791c5a26bbe3a..56a7b2d6387765 100644
--- a/clang/lib/Format/FormatToken.cpp
+++ b/clang/lib/Format/FormatToken.cpp
@@ -137,7 +137,7 @@ unsigned CommaSeparatedList::formatAfterToken(LineState 
,
   // bin-packed. Add a severe penalty to this so that column layouts are
   // preferred if possible.
   if (!Format)
-return 1;
+return 10'000;
 
   // Format the entire list.
   unsigned Penalty = 0;
diff --git a/clang/lib/Format/UnwrappedLineFormatter.cpp 
b/clang/lib/Format/UnwrappedLineFormatter.cpp
index adeb072434873f..fb31980ab9f491 100644
--- a/clang/lib/Format/UnwrappedLineFormatter.cpp
+++ b/clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -1221,7 +1221,7 @@ class OptimizingLineFormatter : public LineFormatter {
 // While not empty, take first element and follow edges.
 while (!Queue.empty()) {
   // Quit if we still haven't found a solution by now.
-  if (Count > 2500)
+  if (Count > 25'000'000)
 return 0;
 
   Penalty = Queue.top().first.first;
@@ -1235,7 +1235,7 @@ class OptimizingLineFormatter : public LineFormatter {
 
   // Cut off the analysis of certain solutions if the analysis gets too
   // complex. See description of IgnoreStackForComparison.
-  if (Count > 5)
+  if (Count > 50'000)
 Node->State.IgnoreStackForComparison = true;
 
   if (!Seen.insert(>State).second) {
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index b8dc01f55b4faa..d9752c73e34e79 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -21669,7 +21669,7 @@ TEST_F(FormatTest, BreakPenaltyAfterCastLParen) {
"int));",
 
Style);
-  Style.PenaltyBreakOpenParenthesis = 10;
+  Style.PenaltyBreakOpenParenthesis = 100'000;
   verifyFormat("foo((int)\n"
");",
"foo((\n"

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


[libcxx] [libcxxabi] [libunwind] [libc++/libc++abi/libunwind] Add new test configs for Clang runtime library. NFC. (PR #82734)

2024-02-22 Thread Vladimir Vereschaka via cfe-commits

vvereschaka wrote:

Also it fixes the `llvm-libc++-static.cfg.in::mul_sat.pass.cpp` test for some 
of the cross target builds
https://lab.llvm.org/buildbot/#/builders/143/builds/631/steps/14/logs/FAIL__llvm-libc__-static_cfg_in__mul_sat_pass_cpp

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


[libcxx] [libcxxabi] [libunwind] [libc++/libc++abi/libunwind] Add new test configs for Clang runtime library. NFC. (PR #82734)

2024-02-22 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-libcxxabi

Author: Vladimir Vereschaka (vvereschaka)


Changes

These configurations use the target "just-built" Clang's runtime library 
(clang_rt.builtins) to link the tests.

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


3 Files Affected:

- (added) libcxx/test/configs/llvm-libc++-static-clang-rt.cfg.in (+32) 
- (added) libcxxabi/test/configs/llvm-libc++abi-static-clang-rt.cfg.in (+32) 
- (added) libunwind/test/configs/llvm-libunwind-static-clang-rt.cfg.in (+51) 


``diff
diff --git a/libcxx/test/configs/llvm-libc++-static-clang-rt.cfg.in 
b/libcxx/test/configs/llvm-libc++-static-clang-rt.cfg.in
new file mode 100644
index 00..ce6680ddc2908d
--- /dev/null
+++ b/libcxx/test/configs/llvm-libc++-static-clang-rt.cfg.in
@@ -0,0 +1,32 @@
+# This testing configuration handles running the test suite against LLVM's 
libc++
+# using a static library.
+#
+# This configuration uses a 'just-built' Clang runtime builtins library to 
link with
+# the tests instead of the target system library.
+#
+# Provided for testing of the LLVM/Clang toolchain builds.
+
+lit_config.load_config(config, '@CMAKE_CURRENT_BINARY_DIR@/cmake-bridge.cfg')
+
+config.substitutions.append(('%{flags}',
+'-pthread' + (' -isysroot {}'.format('@CMAKE_OSX_SYSROOT@') if 
'@CMAKE_OSX_SYSROOT@' else '')
+))
+config.substitutions.append(('%{compile_flags}',
+'-nostdinc++ -I %{include-dir} -I %{target-include-dir} -I 
%{libcxx-dir}/test/support'
+))
+config.substitutions.append(('%{link_flags}',
+'-nostdlib++ -L %{lib-dir} -lclang_rt.builtins -lc++ -lc++abi'
+))
+config.substitutions.append(('%{exec}',
+'%{executor} --execdir %T -- '
+))
+
+import os, site
+site.addsitedir(os.path.join('@LIBCXX_SOURCE_DIR@', 'utils'))
+import libcxx.test.params, libcxx.test.config
+libcxx.test.config.configure(
+libcxx.test.params.DEFAULT_PARAMETERS,
+libcxx.test.features.DEFAULT_FEATURES,
+config,
+lit_config
+)
diff --git a/libcxxabi/test/configs/llvm-libc++abi-static-clang-rt.cfg.in 
b/libcxxabi/test/configs/llvm-libc++abi-static-clang-rt.cfg.in
new file mode 100644
index 00..11b89e22fca9d6
--- /dev/null
+++ b/libcxxabi/test/configs/llvm-libc++abi-static-clang-rt.cfg.in
@@ -0,0 +1,32 @@
+# This testing configuration handles running the test suite against LLVM's 
libc++abi
+# using a static library.
+#
+# This configuration uses a 'just-built' Clang runtime builtins library to 
link with
+# the tests instead of the target system library.
+#
+# Provided for testing of the LLVM/Clang toolchain builds.
+
+lit_config.load_config(config, '@CMAKE_CURRENT_BINARY_DIR@/cmake-bridge.cfg')
+
+config.substitutions.append(('%{flags}',
+'-isysroot {}'.format('@CMAKE_OSX_SYSROOT@') if '@CMAKE_OSX_SYSROOT@' else 
''
+))
+config.substitutions.append(('%{compile_flags}',
+'-nostdinc++ -I %{include} -I %{cxx-include} -I %{cxx-target-include} 
%{maybe-include-libunwind} -I %{libcxx}/test/support -I %{libcxx}/src 
-D_LIBCPP_ENABLE_CXX17_REMOVED_UNEXPECTED_FUNCTIONS'
+))
+config.substitutions.append(('%{link_flags}',
+'-nostdlib++ -L %{lib} -lclang_rt.builtins -lc++ -lc++abi -pthread'
+))
+config.substitutions.append(('%{exec}',
+'%{executor} --execdir %T -- '
+))
+
+import os, site
+site.addsitedir(os.path.join('@LIBCXXABI_LIBCXX_PATH@', 'utils'))
+import libcxx.test.params, libcxx.test.config
+libcxx.test.config.configure(
+libcxx.test.params.DEFAULT_PARAMETERS,
+libcxx.test.features.DEFAULT_FEATURES,
+config,
+lit_config
+)
diff --git a/libunwind/test/configs/llvm-libunwind-static-clang-rt.cfg.in 
b/libunwind/test/configs/llvm-libunwind-static-clang-rt.cfg.in
new file mode 100644
index 00..d908a5d55c891c
--- /dev/null
+++ b/libunwind/test/configs/llvm-libunwind-static-clang-rt.cfg.in
@@ -0,0 +1,51 @@
+# Configuration file for running the libunwind tests against the static 
library.
+#
+# This configuration uses a 'just-built' Clang runtime builtins library to 
link with
+# the tests instead of the target system library.
+#
+# Provided for testing of the LLVM/Clang toolchain builds.
+
+lit_config.load_config(config, '@CMAKE_CURRENT_BINARY_DIR@/cmake-bridge.cfg')
+
+compile_flags = []
+link_flags = ['-lclang_rt.builtins']
+
+if @LIBUNWIND_ENABLE_THREADS@:
+link_flags.append('-lpthread')
+
+if @LIBUNWIND_ENABLE_CET@:
+compile_flags.append('-fcf-protection=full')
+
+# On ELF platforms, link tests with -Wl,--export-dynamic if supported by the 
linker.
+if len('@CMAKE_EXE_EXPORTS_CXX_FLAG@'):
+link_flags.append('@CMAKE_EXE_EXPORTS_CXX_FLAG@')
+
+if '@CMAKE_DL_LIBS@':
+link_flags.append('-l@CMAKE_DL_LIBS@')
+
+# Stack unwinding tests need unwinding tables and these are not generated by 
default on all targets.
+compile_flags.append('-funwind-tables')
+
+local_sysroot = '@CMAKE_OSX_SYSROOT@' or '@CMAKE_SYSROOT@'
+config.substitutions.append(('%{flags}',
+'-isysroot {}'.format(local_sysroot) if 

[libcxx] [libcxxabi] [libunwind] [libc++/libc++abi/libunwind] Add new test configs for Clang runtime library. NFC. (PR #82734)

2024-02-22 Thread Vladimir Vereschaka via cfe-commits

https://github.com/vvereschaka created 
https://github.com/llvm/llvm-project/pull/82734

These configurations use the target "just-built" Clang's runtime library 
(clang_rt.builtins) to link the tests.

>From 7c26b85f1d70ae25c7604aec1d7f3d316747dbdb Mon Sep 17 00:00:00 2001
From: Vladimir Vereschaka 
Date: Thu, 22 Feb 2024 14:31:00 -0800
Subject: [PATCH] [libc++/libc++abi/libunwind] Add new test configs for Clang
 runtime library. NFC.

These configurations use the target "just-built" Clang's runtime library
(clang_rt.builtins) to link the tests.
---
 .../llvm-libc++-static-clang-rt.cfg.in| 32 
 .../llvm-libc++abi-static-clang-rt.cfg.in | 32 
 .../llvm-libunwind-static-clang-rt.cfg.in | 51 +++
 3 files changed, 115 insertions(+)
 create mode 100644 libcxx/test/configs/llvm-libc++-static-clang-rt.cfg.in
 create mode 100644 libcxxabi/test/configs/llvm-libc++abi-static-clang-rt.cfg.in
 create mode 100644 libunwind/test/configs/llvm-libunwind-static-clang-rt.cfg.in

diff --git a/libcxx/test/configs/llvm-libc++-static-clang-rt.cfg.in 
b/libcxx/test/configs/llvm-libc++-static-clang-rt.cfg.in
new file mode 100644
index 00..ce6680ddc2908d
--- /dev/null
+++ b/libcxx/test/configs/llvm-libc++-static-clang-rt.cfg.in
@@ -0,0 +1,32 @@
+# This testing configuration handles running the test suite against LLVM's 
libc++
+# using a static library.
+#
+# This configuration uses a 'just-built' Clang runtime builtins library to 
link with
+# the tests instead of the target system library.
+#
+# Provided for testing of the LLVM/Clang toolchain builds.
+
+lit_config.load_config(config, '@CMAKE_CURRENT_BINARY_DIR@/cmake-bridge.cfg')
+
+config.substitutions.append(('%{flags}',
+'-pthread' + (' -isysroot {}'.format('@CMAKE_OSX_SYSROOT@') if 
'@CMAKE_OSX_SYSROOT@' else '')
+))
+config.substitutions.append(('%{compile_flags}',
+'-nostdinc++ -I %{include-dir} -I %{target-include-dir} -I 
%{libcxx-dir}/test/support'
+))
+config.substitutions.append(('%{link_flags}',
+'-nostdlib++ -L %{lib-dir} -lclang_rt.builtins -lc++ -lc++abi'
+))
+config.substitutions.append(('%{exec}',
+'%{executor} --execdir %T -- '
+))
+
+import os, site
+site.addsitedir(os.path.join('@LIBCXX_SOURCE_DIR@', 'utils'))
+import libcxx.test.params, libcxx.test.config
+libcxx.test.config.configure(
+libcxx.test.params.DEFAULT_PARAMETERS,
+libcxx.test.features.DEFAULT_FEATURES,
+config,
+lit_config
+)
diff --git a/libcxxabi/test/configs/llvm-libc++abi-static-clang-rt.cfg.in 
b/libcxxabi/test/configs/llvm-libc++abi-static-clang-rt.cfg.in
new file mode 100644
index 00..11b89e22fca9d6
--- /dev/null
+++ b/libcxxabi/test/configs/llvm-libc++abi-static-clang-rt.cfg.in
@@ -0,0 +1,32 @@
+# This testing configuration handles running the test suite against LLVM's 
libc++abi
+# using a static library.
+#
+# This configuration uses a 'just-built' Clang runtime builtins library to 
link with
+# the tests instead of the target system library.
+#
+# Provided for testing of the LLVM/Clang toolchain builds.
+
+lit_config.load_config(config, '@CMAKE_CURRENT_BINARY_DIR@/cmake-bridge.cfg')
+
+config.substitutions.append(('%{flags}',
+'-isysroot {}'.format('@CMAKE_OSX_SYSROOT@') if '@CMAKE_OSX_SYSROOT@' else 
''
+))
+config.substitutions.append(('%{compile_flags}',
+'-nostdinc++ -I %{include} -I %{cxx-include} -I %{cxx-target-include} 
%{maybe-include-libunwind} -I %{libcxx}/test/support -I %{libcxx}/src 
-D_LIBCPP_ENABLE_CXX17_REMOVED_UNEXPECTED_FUNCTIONS'
+))
+config.substitutions.append(('%{link_flags}',
+'-nostdlib++ -L %{lib} -lclang_rt.builtins -lc++ -lc++abi -pthread'
+))
+config.substitutions.append(('%{exec}',
+'%{executor} --execdir %T -- '
+))
+
+import os, site
+site.addsitedir(os.path.join('@LIBCXXABI_LIBCXX_PATH@', 'utils'))
+import libcxx.test.params, libcxx.test.config
+libcxx.test.config.configure(
+libcxx.test.params.DEFAULT_PARAMETERS,
+libcxx.test.features.DEFAULT_FEATURES,
+config,
+lit_config
+)
diff --git a/libunwind/test/configs/llvm-libunwind-static-clang-rt.cfg.in 
b/libunwind/test/configs/llvm-libunwind-static-clang-rt.cfg.in
new file mode 100644
index 00..d908a5d55c891c
--- /dev/null
+++ b/libunwind/test/configs/llvm-libunwind-static-clang-rt.cfg.in
@@ -0,0 +1,51 @@
+# Configuration file for running the libunwind tests against the static 
library.
+#
+# This configuration uses a 'just-built' Clang runtime builtins library to 
link with
+# the tests instead of the target system library.
+#
+# Provided for testing of the LLVM/Clang toolchain builds.
+
+lit_config.load_config(config, '@CMAKE_CURRENT_BINARY_DIR@/cmake-bridge.cfg')
+
+compile_flags = []
+link_flags = ['-lclang_rt.builtins']
+
+if @LIBUNWIND_ENABLE_THREADS@:
+link_flags.append('-lpthread')
+
+if @LIBUNWIND_ENABLE_CET@:
+compile_flags.append('-fcf-protection=full')
+
+# On ELF platforms, link tests with -Wl,--export-dynamic if supported by 

[clang] [libc] [llvm] [openmp] [libc] Rework the GPU build to be a regular target (PR #81921)

2024-02-22 Thread Vladimir Vereschaka via cfe-commits

vvereschaka wrote:

@jhuber6 ,
looks like these changes break the following builds
* https://lab.llvm.org/buildbot/#/builders/235/builds/5630
* https://lab.llvm.org/buildbot/#/builders/232/builds/19808

there are a lot of CMake error messages started with 
```
CMake Error at cmake/modules/AddLLVM.cmake:631 (set_target_properties):
  set_target_properties called with incorrect number of arguments.
Call Stack (most recent call first):
  cmake/modules/AddLLVM.cmake:854 (llvm_add_library)
  lib/Transforms/Hello/CMakeLists.txt:13 (add_llvm_library)
-- Targeting X86
-- Targeting NVPTX
CMake Error at CMakeLists.txt:1213 (add_subdirectory):
  add_subdirectory given source "/unittest" which is not an existing
  directory.
CMake Error at tools/llvm-config/CMakeLists.txt:54 (string):
  string sub-command REGEX, mode MATCH needs at least 5 arguments total to
  command.
...
```
would you take care of it?

https://github.com/llvm/llvm-project/pull/81921
___
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 layout can be statically known (PR #81335)

2024-02-22 Thread via cfe-commits

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

>From fb93a08f40800652ebe7065e8495511f9b751ec7 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| 96 +++
 1 file changed, 96 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..c4bb1ebc9a80be 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_$_SuperClass.superClassIvar" = hidden constant i64 20
+// CHECK: @"OBJC_IVAR_$_SuperClass._superClassProperty" = hidden constant i64 
24
+// CHECK: @"OBJC_IVAR_$_IntermediateClass.intermediateClassIvar" = global i64 
32
+// CHECK: @"OBJC_IVAR_$_IntermediateClass.intermediateClassIvar2" = global i64 
40
+// CHECK: @"OBJC_IVAR_$_IntermediateClass._intermediateProperty" = hidden 
global i64 48
+// CHECK: @"OBJC_IVAR_$_SubClass.subClassIvar" = global i64 56
+// CHECK: @"OBJC_IVAR_$_SubClass._subClassProperty" = hidden global i64 64
 // CHECK: @"OBJC_IVAR_$_NotStaticLayout.not_static_layout_ivar" = hidden 
global i64 12
 
 @interface NSObject {
@@ -20,6 +27,95 @@ -(void)meth {
 }
 @end
 
+// Ivars declared in the @interface
+@interface SuperClass : NSObject
+@property (nonatomic, assign) int superClassProperty;
+@end
+
+@implementation SuperClass {
+  int superClassIvar; // Declare an ivar
+}
+
+// CHECK-LABEL: define internal void @"\01-[SuperClass superClassMethod]"
+- (void)superClassMethod {
+_superClassProperty = 42;
+superClassIvar = 10;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SuperClass
+// CHECK: getelementptr inbounds i8, ptr %1, i64 20
+}
+
+// implicitly synthesized method here
+// CHECK-LABEL: define internal i32 @"\01-[SuperClass superClassProperty]"
+// CHECK: getelementptr inbounds i8, ptr %0, i64 24
+
+// CHECK-LABEL: define internal void @"\01-[SuperClass setSuperClassProperty:]"
+// CHECK: getelementptr inbounds i8, ptr %1, i64 24
+@end
+
+// Inheritance and Ivars
+@interface IntermediateClass : SuperClass
+{
+double intermediateClassIvar;
+
+@protected
+int intermediateClassIvar2;
+}
+@property (nonatomic, strong) SuperClass *intermediateProperty;
+@end
+
+@implementation IntermediateClass
+@synthesize intermediateProperty = _intermediateProperty;
+- (void)intermediateClassMethod {
+intermediateClassIvar = 3.14;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_IntermediateClass
+// CHECK: getelementptr inbounds i8, ptr %0, i64 %ivar
+}
+
+// CHECK-LABEL: define internal void @"\01-[IntermediateClass 
intermediateClassPropertyMethod]"
+- (void)intermediateClassPropertyMethod {
+self.intermediateProperty = 0;
+// CHECK: load ptr, ptr @OBJC_SELECTOR_REFERENCES_
+// CHECK: call void @objc_msgSend(ptr noundef %0, ptr noundef %1, ptr 
noundef null)
+}
+
+// CHECK-LABEL: define internal void @"\01-[IntermediateClass 
intermediateClassPropertyMethodDirect]"
+- (void)intermediateClassPropertyMethodDirect {
+_intermediateProperty = 0;
+// CHECK: load i64, ptr 
@"OBJC_IVAR_$_IntermediateClass._intermediateProperty"
+}
+@end
+
+@interface SubClass : IntermediateClass
+{
+double subClassIvar;
+}
+@property (nonatomic, assign) SubClass *subClassProperty;
+@end
+
+@implementation SubClass
+// CHECK-LABEL: define internal void @"\01-[SubClass subclassVar]"
+- (void)subclassVar {
+
+subClassIvar = 6.28;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SubClass
+// CHECK: getelementptr inbounds i8, ptr %0, i64 %ivar
+}
+
+// CHECK-LABEL: define internal void @"\01-[SubClass intermediateSubclassVar]"
+-(void)intermediateSubclassVar {
+intermediateClassIvar = 3.14;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_IntermediateClass
+// CHECK: getelementptr inbounds i8, ptr %0, i64 %ivar
+}
+
+// implicit synthesized method here:
+// CHECK-LABEL: define internal ptr @"\01-[SubClass subClassProperty]"
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SubClass._subClassProperty"
+
+// CHECK-LABEL: define internal void @"\01-[SubClass setSubClassProperty:]"
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SubClass._subClassProperty"
+@end
+
 @interface NotNSObject {
   int these, might, change;
 }

>From 7d5affc816da4f734c06862c82053f0d46435825 Mon Sep 17 00:00:00 2001
From: Rose <83477269+ataridre...@users.noreply.github.com>
Date: Tue, 13 Feb 2024 14:52:49 -0500
Subject: [PATCH 2/2] [ObjC] Check entire chain of superclasses to see if class
 layout can be statically known

As of now, we only check if a class directly inherits from NSObject to 

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

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

https://github.com/farzonl updated 
https://github.com/llvm/llvm-project/pull/81190

>From fad7e6eac6a1a65ce00ab3e4f64d5774b426c91d Mon Sep 17 00:00:00 2001
From: Farzon Lotfi 
Date: Thu, 8 Feb 2024 11:08:59 -0500
Subject: [PATCH 1/3] [HLSL] Implementation of dot intrinsic This change
 implements #70073

HLSL has a dot intrinsic defined here:
https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-dot

The intrinsic itself is defined as a HLSL_LANG LangBuiltin in Builtins.td.
This is used to associate all the dot product typdef defined hlsl_intrinsics.h
with a single intrinsic check in CGBuiltin.cpp & SemaChecking.cpp.

In IntrinsicsDirectX.td we define the llvmIR for the dot product.
A few goals were in mind for this IR. First it should operate on only
vectors. Second the return type should be the vector element type. Third
the second parameter vector should be of the same size as the first
parameter. Finally `a dot b` should be the same as `b dot a`.

In CGBuiltin.cpp hlsl has built on top of existing clang intrinsics via 
EmitBuiltinExpr. Dot
product though is language specific intrinsic and so is guarded behind 
getLangOpts().HLSL.
The call chain looks like this: EmitBuiltinExpr -> EmitHLSLBuiltinExp

EmitHLSLBuiltinExp dot product intrinsics makes a destinction
between vectors and scalars. This is because HLSL supports dot product on 
scalars which simplifies down to multiply.

Sema.h & SemaChecking.cpp saw the addition of CheckHLSLBuiltinFunctionCall, a 
language specific semantic validation that can be expanded for other hlsl 
specific intrinsics.
---
 clang/include/clang/Basic/Builtins.td |   6 +
 .../clang/Basic/DiagnosticSemaKinds.td|   2 +
 clang/include/clang/Sema/Sema.h   |   1 +
 clang/lib/CodeGen/CGBuiltin.cpp   |  49 
 clang/lib/CodeGen/CodeGenFunction.h   |   1 +
 clang/lib/Headers/hlsl/hlsl_intrinsics.h  |  92 
 clang/lib/Sema/SemaChecking.cpp   |  84 ++-
 clang/test/CodeGenHLSL/builtins/dot.hlsl  | 216 ++
 clang/test/SemaHLSL/BuiltIns/dot-errors.hlsl  |  46 
 llvm/include/llvm/IR/IntrinsicsDirectX.td |   5 +
 10 files changed, 497 insertions(+), 5 deletions(-)
 create mode 100644 clang/test/CodeGenHLSL/builtins/dot.hlsl
 create mode 100644 clang/test/SemaHLSL/BuiltIns/dot-errors.hlsl

diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index df74026c5d2d50..771c4f5d4121f4 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -4524,6 +4524,12 @@ def HLSLCreateHandle : LangBuiltin<"HLSL_LANG"> {
   let Prototype = "void*(unsigned char)";
 }
 
+def HLSLDotProduct : LangBuiltin<"HLSL_LANG"> {
+  let Spellings = ["__builtin_hlsl_dot"];
+  let Attributes = [NoThrow, Const, CustomTypeChecking];
+  let Prototype = "void(...)";
+}
+
 // Builtins for XRay.
 def XRayCustomEvent : Builtin {
   let Spellings = ["__xray_customevent"];
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index ebda201361fb07..5999b1ced36347 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -10270,6 +10270,8 @@ def err_vec_builtin_non_vector : Error<
  "first two arguments to %0 must be vectors">;
 def err_vec_builtin_incompatible_vector : Error<
   "first two arguments to %0 must have the same type">;
+def err_vec_builtin_incompatible_size : Error<
+  "first two arguments to %0 must have the same size">;
 def err_vsx_builtin_nonconstant_argument : Error<
   "argument %0 to %1 must be a 2-bit unsigned literal (i.e. 0, 1, 2 or 3)">;
 
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index fcccac10f4733a..c76c0df28334f8 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -14057,6 +14057,7 @@ class Sema final {
   bool CheckPPCBuiltinFunctionCall(const TargetInfo , unsigned BuiltinID,
CallExpr *TheCall);
   bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
+  bool CheckHLSLBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
   bool CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum);
   bool CheckRISCVBuiltinFunctionCall(const TargetInfo , unsigned BuiltinID,
  CallExpr *TheCall);
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 734eb5a035ca49..393ab497fb15c4 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -44,6 +44,7 @@
 #include "llvm/IR/IntrinsicsAMDGPU.h"
 #include "llvm/IR/IntrinsicsARM.h"
 #include "llvm/IR/IntrinsicsBPF.h"
+#include "llvm/IR/IntrinsicsDirectX.h"
 #include "llvm/IR/IntrinsicsHexagon.h"
 #include "llvm/IR/IntrinsicsNVPTX.h"
 #include "llvm/IR/IntrinsicsPowerPC.h"
@@ -5982,6 +5983,10 @@ RValue 

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

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

https://github.com/farzonl updated 
https://github.com/llvm/llvm-project/pull/81190

>From fad7e6eac6a1a65ce00ab3e4f64d5774b426c91d Mon Sep 17 00:00:00 2001
From: Farzon Lotfi 
Date: Thu, 8 Feb 2024 11:08:59 -0500
Subject: [PATCH 1/3] [HLSL] Implementation of dot intrinsic This change
 implements #70073

HLSL has a dot intrinsic defined here:
https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-dot

The intrinsic itself is defined as a HLSL_LANG LangBuiltin in Builtins.td.
This is used to associate all the dot product typdef defined hlsl_intrinsics.h
with a single intrinsic check in CGBuiltin.cpp & SemaChecking.cpp.

In IntrinsicsDirectX.td we define the llvmIR for the dot product.
A few goals were in mind for this IR. First it should operate on only
vectors. Second the return type should be the vector element type. Third
the second parameter vector should be of the same size as the first
parameter. Finally `a dot b` should be the same as `b dot a`.

In CGBuiltin.cpp hlsl has built on top of existing clang intrinsics via 
EmitBuiltinExpr. Dot
product though is language specific intrinsic and so is guarded behind 
getLangOpts().HLSL.
The call chain looks like this: EmitBuiltinExpr -> EmitHLSLBuiltinExp

EmitHLSLBuiltinExp dot product intrinsics makes a destinction
between vectors and scalars. This is because HLSL supports dot product on 
scalars which simplifies down to multiply.

Sema.h & SemaChecking.cpp saw the addition of CheckHLSLBuiltinFunctionCall, a 
language specific semantic validation that can be expanded for other hlsl 
specific intrinsics.
---
 clang/include/clang/Basic/Builtins.td |   6 +
 .../clang/Basic/DiagnosticSemaKinds.td|   2 +
 clang/include/clang/Sema/Sema.h   |   1 +
 clang/lib/CodeGen/CGBuiltin.cpp   |  49 
 clang/lib/CodeGen/CodeGenFunction.h   |   1 +
 clang/lib/Headers/hlsl/hlsl_intrinsics.h  |  92 
 clang/lib/Sema/SemaChecking.cpp   |  84 ++-
 clang/test/CodeGenHLSL/builtins/dot.hlsl  | 216 ++
 clang/test/SemaHLSL/BuiltIns/dot-errors.hlsl  |  46 
 llvm/include/llvm/IR/IntrinsicsDirectX.td |   5 +
 10 files changed, 497 insertions(+), 5 deletions(-)
 create mode 100644 clang/test/CodeGenHLSL/builtins/dot.hlsl
 create mode 100644 clang/test/SemaHLSL/BuiltIns/dot-errors.hlsl

diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index df74026c5d2d50..771c4f5d4121f4 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -4524,6 +4524,12 @@ def HLSLCreateHandle : LangBuiltin<"HLSL_LANG"> {
   let Prototype = "void*(unsigned char)";
 }
 
+def HLSLDotProduct : LangBuiltin<"HLSL_LANG"> {
+  let Spellings = ["__builtin_hlsl_dot"];
+  let Attributes = [NoThrow, Const, CustomTypeChecking];
+  let Prototype = "void(...)";
+}
+
 // Builtins for XRay.
 def XRayCustomEvent : Builtin {
   let Spellings = ["__xray_customevent"];
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index ebda201361fb07..5999b1ced36347 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -10270,6 +10270,8 @@ def err_vec_builtin_non_vector : Error<
  "first two arguments to %0 must be vectors">;
 def err_vec_builtin_incompatible_vector : Error<
   "first two arguments to %0 must have the same type">;
+def err_vec_builtin_incompatible_size : Error<
+  "first two arguments to %0 must have the same size">;
 def err_vsx_builtin_nonconstant_argument : Error<
   "argument %0 to %1 must be a 2-bit unsigned literal (i.e. 0, 1, 2 or 3)">;
 
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index fcccac10f4733a..c76c0df28334f8 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -14057,6 +14057,7 @@ class Sema final {
   bool CheckPPCBuiltinFunctionCall(const TargetInfo , unsigned BuiltinID,
CallExpr *TheCall);
   bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
+  bool CheckHLSLBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
   bool CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum);
   bool CheckRISCVBuiltinFunctionCall(const TargetInfo , unsigned BuiltinID,
  CallExpr *TheCall);
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 734eb5a035ca49..393ab497fb15c4 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -44,6 +44,7 @@
 #include "llvm/IR/IntrinsicsAMDGPU.h"
 #include "llvm/IR/IntrinsicsARM.h"
 #include "llvm/IR/IntrinsicsBPF.h"
+#include "llvm/IR/IntrinsicsDirectX.h"
 #include "llvm/IR/IntrinsicsHexagon.h"
 #include "llvm/IR/IntrinsicsNVPTX.h"
 #include "llvm/IR/IntrinsicsPowerPC.h"
@@ -5982,6 +5983,10 @@ RValue 

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

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

https://github.com/farzonl updated 
https://github.com/llvm/llvm-project/pull/81190

>From fad7e6eac6a1a65ce00ab3e4f64d5774b426c91d Mon Sep 17 00:00:00 2001
From: Farzon Lotfi 
Date: Thu, 8 Feb 2024 11:08:59 -0500
Subject: [PATCH 1/3] [HLSL] Implementation of dot intrinsic This change
 implements #70073

HLSL has a dot intrinsic defined here:
https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-dot

The intrinsic itself is defined as a HLSL_LANG LangBuiltin in Builtins.td.
This is used to associate all the dot product typdef defined hlsl_intrinsics.h
with a single intrinsic check in CGBuiltin.cpp & SemaChecking.cpp.

In IntrinsicsDirectX.td we define the llvmIR for the dot product.
A few goals were in mind for this IR. First it should operate on only
vectors. Second the return type should be the vector element type. Third
the second parameter vector should be of the same size as the first
parameter. Finally `a dot b` should be the same as `b dot a`.

In CGBuiltin.cpp hlsl has built on top of existing clang intrinsics via 
EmitBuiltinExpr. Dot
product though is language specific intrinsic and so is guarded behind 
getLangOpts().HLSL.
The call chain looks like this: EmitBuiltinExpr -> EmitHLSLBuiltinExp

EmitHLSLBuiltinExp dot product intrinsics makes a destinction
between vectors and scalars. This is because HLSL supports dot product on 
scalars which simplifies down to multiply.

Sema.h & SemaChecking.cpp saw the addition of CheckHLSLBuiltinFunctionCall, a 
language specific semantic validation that can be expanded for other hlsl 
specific intrinsics.
---
 clang/include/clang/Basic/Builtins.td |   6 +
 .../clang/Basic/DiagnosticSemaKinds.td|   2 +
 clang/include/clang/Sema/Sema.h   |   1 +
 clang/lib/CodeGen/CGBuiltin.cpp   |  49 
 clang/lib/CodeGen/CodeGenFunction.h   |   1 +
 clang/lib/Headers/hlsl/hlsl_intrinsics.h  |  92 
 clang/lib/Sema/SemaChecking.cpp   |  84 ++-
 clang/test/CodeGenHLSL/builtins/dot.hlsl  | 216 ++
 clang/test/SemaHLSL/BuiltIns/dot-errors.hlsl  |  46 
 llvm/include/llvm/IR/IntrinsicsDirectX.td |   5 +
 10 files changed, 497 insertions(+), 5 deletions(-)
 create mode 100644 clang/test/CodeGenHLSL/builtins/dot.hlsl
 create mode 100644 clang/test/SemaHLSL/BuiltIns/dot-errors.hlsl

diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index df74026c5d2d50..771c4f5d4121f4 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -4524,6 +4524,12 @@ def HLSLCreateHandle : LangBuiltin<"HLSL_LANG"> {
   let Prototype = "void*(unsigned char)";
 }
 
+def HLSLDotProduct : LangBuiltin<"HLSL_LANG"> {
+  let Spellings = ["__builtin_hlsl_dot"];
+  let Attributes = [NoThrow, Const, CustomTypeChecking];
+  let Prototype = "void(...)";
+}
+
 // Builtins for XRay.
 def XRayCustomEvent : Builtin {
   let Spellings = ["__xray_customevent"];
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index ebda201361fb07..5999b1ced36347 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -10270,6 +10270,8 @@ def err_vec_builtin_non_vector : Error<
  "first two arguments to %0 must be vectors">;
 def err_vec_builtin_incompatible_vector : Error<
   "first two arguments to %0 must have the same type">;
+def err_vec_builtin_incompatible_size : Error<
+  "first two arguments to %0 must have the same size">;
 def err_vsx_builtin_nonconstant_argument : Error<
   "argument %0 to %1 must be a 2-bit unsigned literal (i.e. 0, 1, 2 or 3)">;
 
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index fcccac10f4733a..c76c0df28334f8 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -14057,6 +14057,7 @@ class Sema final {
   bool CheckPPCBuiltinFunctionCall(const TargetInfo , unsigned BuiltinID,
CallExpr *TheCall);
   bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
+  bool CheckHLSLBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
   bool CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum);
   bool CheckRISCVBuiltinFunctionCall(const TargetInfo , unsigned BuiltinID,
  CallExpr *TheCall);
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 734eb5a035ca49..393ab497fb15c4 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -44,6 +44,7 @@
 #include "llvm/IR/IntrinsicsAMDGPU.h"
 #include "llvm/IR/IntrinsicsARM.h"
 #include "llvm/IR/IntrinsicsBPF.h"
+#include "llvm/IR/IntrinsicsDirectX.h"
 #include "llvm/IR/IntrinsicsHexagon.h"
 #include "llvm/IR/IntrinsicsNVPTX.h"
 #include "llvm/IR/IntrinsicsPowerPC.h"
@@ -5982,6 +5983,10 @@ RValue 

[clang] [InstallAPI] Hookup Input files & basic ASTVisitor (PR #82552)

2024-02-22 Thread Cyndy Ishida via cfe-commits

https://github.com/cyndyishida updated 
https://github.com/llvm/llvm-project/pull/82552

>From bb10dd04f1895b63d0183c1f1ee31d452233059b Mon Sep 17 00:00:00 2001
From: Cyndy Ishida 
Date: Wed, 21 Feb 2024 14:56:02 -0800
Subject: [PATCH] [InstallAPI] Hookup Input files & basic ASTVisitor

This patch takes in json files as input to determine that header files to 
process, and in which order, to pass along for CC1 invocations.
This patch also includes an ASTVisitor to collect simple global variables.
---
 clang/include/clang/InstallAPI/Context.h  |  22 +++-
 clang/include/clang/InstallAPI/Frontend.h |  48 +++
 clang/include/clang/InstallAPI/HeaderFile.h   |  23 
 clang/include/clang/InstallAPI/Visitor.h  |  51 
 clang/lib/InstallAPI/CMakeLists.txt   |   3 +
 clang/lib/InstallAPI/Frontend.cpp |  58 +
 clang/lib/InstallAPI/Visitor.cpp  |  94 +
 clang/test/InstallAPI/basic.test  |   5 +
 clang/test/InstallAPI/variables.test  |  63 +
 .../clang-installapi/ClangInstallAPI.cpp  | 123 +-
 clang/tools/clang-installapi/Options.cpp  |  29 +
 clang/tools/clang-installapi/Options.h|   8 ++
 12 files changed, 521 insertions(+), 6 deletions(-)
 create mode 100644 clang/include/clang/InstallAPI/Frontend.h
 create mode 100644 clang/include/clang/InstallAPI/Visitor.h
 create mode 100644 clang/lib/InstallAPI/Frontend.cpp
 create mode 100644 clang/lib/InstallAPI/Visitor.cpp
 create mode 100644 clang/test/InstallAPI/variables.test

diff --git a/clang/include/clang/InstallAPI/Context.h 
b/clang/include/clang/InstallAPI/Context.h
index 7d105920734fde..292992908aa129 100644
--- a/clang/include/clang/InstallAPI/Context.h
+++ b/clang/include/clang/InstallAPI/Context.h
@@ -9,6 +9,9 @@
 #ifndef LLVM_CLANG_INSTALLAPI_CONTEXT_H
 #define LLVM_CLANG_INSTALLAPI_CONTEXT_H
 
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/FileManager.h"
+#include "clang/InstallAPI/HeaderFile.h"
 #include "llvm/TextAPI/InterfaceFile.h"
 #include "llvm/TextAPI/RecordVisitor.h"
 #include "llvm/TextAPI/RecordsSlice.h"
@@ -24,8 +27,23 @@ struct InstallAPIContext {
   /// Library attributes that are typically passed as linker inputs.
   llvm::MachO::RecordsSlice::BinaryAttrs BA;
 
-  /// Active target triple to parse.
-  llvm::Triple TargetTriple{};
+  /// All headers that represent a library.
+  HeaderSeq InputHeaders;
+
+  /// Active language mode to parse in.
+  Language LangMode = Language::ObjC;
+
+  /// Active header access type.
+  HeaderType Type = HeaderType::Unknown;
+
+  /// Active TargetSlice for symbol record collection.
+  std::shared_ptr Records;
+
+  /// FileManager for all I/O operations.
+  FileManager *FM = nullptr;
+
+  /// DiagnosticsEngine for all error reporting.
+  DiagnosticsEngine *Diags = nullptr;
 
   /// File Path of output location.
   llvm::StringRef OutputLoc{};
diff --git a/clang/include/clang/InstallAPI/Frontend.h 
b/clang/include/clang/InstallAPI/Frontend.h
new file mode 100644
index 00..7ee87ae028d079
--- /dev/null
+++ b/clang/include/clang/InstallAPI/Frontend.h
@@ -0,0 +1,48 @@
+//===- InstallAPI/Frontend.h ---*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+///
+/// Top level wrappers for InstallAPI frontend operations.
+///
+//===--===//
+
+#ifndef LLVM_CLANG_INSTALLAPI_FRONTEND_H
+#define LLVM_CLANG_INSTALLAPI_FRONTEND_H
+
+#include "clang/AST/ASTConsumer.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Frontend/FrontendActions.h"
+#include "clang/InstallAPI/Context.h"
+#include "clang/InstallAPI/Visitor.h"
+#include "llvm/ADT/Twine.h"
+#include "llvm/Support/MemoryBuffer.h"
+
+namespace clang {
+namespace installapi {
+
+/// Create a buffer that contains all headers to scan
+/// for global symbols with.
+std::unique_ptr
+createInputBuffer(const InstallAPIContext );
+
+class InstallAPIAction : public ASTFrontendAction {
+public:
+  explicit InstallAPIAction(llvm::MachO::RecordsSlice )
+  : Records(Records) {}
+
+  std::unique_ptr CreateASTConsumer(CompilerInstance ,
+ StringRef InFile) override {
+return std::make_unique(CI.getASTContext(), Records);
+  }
+
+private:
+  llvm::MachO::RecordsSlice 
+};
+} // namespace installapi
+} // namespace clang
+
+#endif // LLVM_CLANG_INSTALLAPI_FRONTEND_H
diff --git a/clang/include/clang/InstallAPI/HeaderFile.h 
b/clang/include/clang/InstallAPI/HeaderFile.h
index fc64a43b3def5c..70e83bbb3e76f6 100644
--- a/clang/include/clang/InstallAPI/HeaderFile.h
+++ 

[clang] 2e5af56 - [C++20] [Modules] Allow to compile a pcm with and without -fPIC

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

Author: Chuanqi Xu
Date: 2024-02-23T11:05:15+08:00
New Revision: 2e5af56b05c2d39ab2c829bf4c13190523b67ddd

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

LOG: [C++20] [Modules] Allow to compile a pcm with and without -fPIC
seperately

We can compile a module unit in 2 phase compilaton:

```
clang++ -std=c++20 a.cppm --precompile -o a.pcm
clang++ -std=c++20 a.pcm -c -o a.o
```

And it is a general requirement that we need to compile a translation
unit with and without -fPIC for static and shared libraries.

But for C++20 modules with 2 phase compilation, it may be waste of time
to compile them 2 times completely. It may be fine to generate one BMI
and compile it with and without -fPIC seperately.

e.g.,

```
clang++ -std=c++20 a.cppm --precompile -o a.pcm
clang++ -std=c++20 a.pcm -c -o a.o
clang++ -std=c++20 a.pcm -c -fPIC -o a-PIC.o
```

Then we can save the time to parse a.cppm repeatedly.

Added: 
clang/test/Modules/compile-pcm-with-pic.cppm

Modified: 
clang/include/clang/Frontend/ASTUnit.h
clang/include/clang/Frontend/CompilerInstance.h
clang/include/clang/Frontend/CompilerInvocation.h
clang/lib/Frontend/ASTUnit.cpp
clang/lib/Frontend/FrontendAction.cpp
clang/tools/c-index-test/core_main.cpp
clang/tools/libclang/CIndex.cpp

Removed: 




diff  --git a/clang/include/clang/Frontend/ASTUnit.h 
b/clang/include/clang/Frontend/ASTUnit.h
index 6af712afdcb6d8..a2c1b25dd22476 100644
--- a/clang/include/clang/Frontend/ASTUnit.h
+++ b/clang/include/clang/Frontend/ASTUnit.h
@@ -691,16 +691,19 @@ class ASTUnit {
   /// lifetime is expected to extend past that of the returned ASTUnit.
   ///
   /// \returns - The initialized ASTUnit or null if the AST failed to load.
-  static std::unique_ptr LoadFromASTFile(
-  const std::string , const PCHContainerReader ,
-  WhatToLoad ToLoad, IntrusiveRefCntPtr Diags,
-  const FileSystemOptions ,
-  std::shared_ptr HSOpts, bool OnlyLocalDecls = false,
-  CaptureDiagsKind CaptureDiagnostics = CaptureDiagsKind::None,
-  bool AllowASTWithCompilerErrors = false,
-  bool UserFilesAreVolatile = false,
-  IntrusiveRefCntPtr VFS =
-  llvm::vfs::getRealFileSystem());
+  static std::unique_ptr
+  LoadFromASTFile(const std::string ,
+  const PCHContainerReader , WhatToLoad ToLoad,
+  IntrusiveRefCntPtr Diags,
+  const FileSystemOptions ,
+  std::shared_ptr HSOpts,
+  std::shared_ptr LangOpts = nullptr,
+  bool OnlyLocalDecls = false,
+  CaptureDiagsKind CaptureDiagnostics = CaptureDiagsKind::None,
+  bool AllowASTWithCompilerErrors = false,
+  bool UserFilesAreVolatile = false,
+  IntrusiveRefCntPtr VFS =
+  llvm::vfs::getRealFileSystem());
 
 private:
   /// Helper function for \c LoadFromCompilerInvocation() and

diff  --git a/clang/include/clang/Frontend/CompilerInstance.h 
b/clang/include/clang/Frontend/CompilerInstance.h
index ac2f940769fbe9..b97d0c636806a9 100644
--- a/clang/include/clang/Frontend/CompilerInstance.h
+++ b/clang/include/clang/Frontend/CompilerInstance.h
@@ -311,6 +311,9 @@ class CompilerInstance : public ModuleLoader {
 
   LangOptions () { return Invocation->getLangOpts(); }
   const LangOptions () const { return Invocation->getLangOpts(); }
+  std::shared_ptr getLangOptsPtr() const {
+return Invocation->getLangOptsPtr();
+  }
 
   PreprocessorOptions () {
 return Invocation->getPreprocessorOpts();

diff  --git a/clang/include/clang/Frontend/CompilerInvocation.h 
b/clang/include/clang/Frontend/CompilerInvocation.h
index c6528779bde7b2..8fc51e6ec03b64 100644
--- a/clang/include/clang/Frontend/CompilerInvocation.h
+++ b/clang/include/clang/Frontend/CompilerInvocation.h
@@ -271,6 +271,7 @@ class CompilerInvocation : public CompilerInvocationBase {
   std::shared_ptr getPreprocessorOptsPtr() {
 return PPOpts;
   }
+  std::shared_ptr getLangOptsPtr() { return LangOpts; }
   /// @}
 
   /// Create a compiler invocation from a list of input options.

diff  --git a/clang/lib/Frontend/ASTUnit.cpp b/clang/lib/Frontend/ASTUnit.cpp
index f09a01b5dd4aff..3610a08831e79a 100644
--- a/clang/lib/Frontend/ASTUnit.cpp
+++ b/clang/lib/Frontend/ASTUnit.cpp
@@ -540,7 +540,17 @@ class ASTInfoCollector : public ASTReaderListener {
 if (InitializedLanguage)
   return false;
 
+// FIXME: We did similar things in ReadHeaderSearchOptions too. But such
+// style is not scaling. Probably we need to invite some mechanism to
+// handle such patterns generally.
+auto PICLevel = LangOpt.PICLevel;
+auto PIE = LangOpt.PIE;
+
 LangOpt = LangOpts;
+
+LangOpt.PICLevel = PICLevel;
+

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

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

https://github.com/farzonl deleted 
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] [llvm] [HLSL] Implementation of dot intrinsic (PR #81190)

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

https://github.com/farzonl updated 
https://github.com/llvm/llvm-project/pull/81190

>From fad7e6eac6a1a65ce00ab3e4f64d5774b426c91d Mon Sep 17 00:00:00 2001
From: Farzon Lotfi 
Date: Thu, 8 Feb 2024 11:08:59 -0500
Subject: [PATCH 1/3] [HLSL] Implementation of dot intrinsic This change
 implements #70073

HLSL has a dot intrinsic defined here:
https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-dot

The intrinsic itself is defined as a HLSL_LANG LangBuiltin in Builtins.td.
This is used to associate all the dot product typdef defined hlsl_intrinsics.h
with a single intrinsic check in CGBuiltin.cpp & SemaChecking.cpp.

In IntrinsicsDirectX.td we define the llvmIR for the dot product.
A few goals were in mind for this IR. First it should operate on only
vectors. Second the return type should be the vector element type. Third
the second parameter vector should be of the same size as the first
parameter. Finally `a dot b` should be the same as `b dot a`.

In CGBuiltin.cpp hlsl has built on top of existing clang intrinsics via 
EmitBuiltinExpr. Dot
product though is language specific intrinsic and so is guarded behind 
getLangOpts().HLSL.
The call chain looks like this: EmitBuiltinExpr -> EmitHLSLBuiltinExp

EmitHLSLBuiltinExp dot product intrinsics makes a destinction
between vectors and scalars. This is because HLSL supports dot product on 
scalars which simplifies down to multiply.

Sema.h & SemaChecking.cpp saw the addition of CheckHLSLBuiltinFunctionCall, a 
language specific semantic validation that can be expanded for other hlsl 
specific intrinsics.
---
 clang/include/clang/Basic/Builtins.td |   6 +
 .../clang/Basic/DiagnosticSemaKinds.td|   2 +
 clang/include/clang/Sema/Sema.h   |   1 +
 clang/lib/CodeGen/CGBuiltin.cpp   |  49 
 clang/lib/CodeGen/CodeGenFunction.h   |   1 +
 clang/lib/Headers/hlsl/hlsl_intrinsics.h  |  92 
 clang/lib/Sema/SemaChecking.cpp   |  84 ++-
 clang/test/CodeGenHLSL/builtins/dot.hlsl  | 216 ++
 clang/test/SemaHLSL/BuiltIns/dot-errors.hlsl  |  46 
 llvm/include/llvm/IR/IntrinsicsDirectX.td |   5 +
 10 files changed, 497 insertions(+), 5 deletions(-)
 create mode 100644 clang/test/CodeGenHLSL/builtins/dot.hlsl
 create mode 100644 clang/test/SemaHLSL/BuiltIns/dot-errors.hlsl

diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index df74026c5d2d50..771c4f5d4121f4 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -4524,6 +4524,12 @@ def HLSLCreateHandle : LangBuiltin<"HLSL_LANG"> {
   let Prototype = "void*(unsigned char)";
 }
 
+def HLSLDotProduct : LangBuiltin<"HLSL_LANG"> {
+  let Spellings = ["__builtin_hlsl_dot"];
+  let Attributes = [NoThrow, Const, CustomTypeChecking];
+  let Prototype = "void(...)";
+}
+
 // Builtins for XRay.
 def XRayCustomEvent : Builtin {
   let Spellings = ["__xray_customevent"];
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index ebda201361fb07..5999b1ced36347 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -10270,6 +10270,8 @@ def err_vec_builtin_non_vector : Error<
  "first two arguments to %0 must be vectors">;
 def err_vec_builtin_incompatible_vector : Error<
   "first two arguments to %0 must have the same type">;
+def err_vec_builtin_incompatible_size : Error<
+  "first two arguments to %0 must have the same size">;
 def err_vsx_builtin_nonconstant_argument : Error<
   "argument %0 to %1 must be a 2-bit unsigned literal (i.e. 0, 1, 2 or 3)">;
 
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index fcccac10f4733a..c76c0df28334f8 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -14057,6 +14057,7 @@ class Sema final {
   bool CheckPPCBuiltinFunctionCall(const TargetInfo , unsigned BuiltinID,
CallExpr *TheCall);
   bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
+  bool CheckHLSLBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
   bool CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum);
   bool CheckRISCVBuiltinFunctionCall(const TargetInfo , unsigned BuiltinID,
  CallExpr *TheCall);
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 734eb5a035ca49..393ab497fb15c4 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -44,6 +44,7 @@
 #include "llvm/IR/IntrinsicsAMDGPU.h"
 #include "llvm/IR/IntrinsicsARM.h"
 #include "llvm/IR/IntrinsicsBPF.h"
+#include "llvm/IR/IntrinsicsDirectX.h"
 #include "llvm/IR/IntrinsicsHexagon.h"
 #include "llvm/IR/IntrinsicsNVPTX.h"
 #include "llvm/IR/IntrinsicsPowerPC.h"
@@ -5982,6 +5983,10 @@ RValue 

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

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

https://github.com/farzonl updated 
https://github.com/llvm/llvm-project/pull/81190

>From fad7e6eac6a1a65ce00ab3e4f64d5774b426c91d Mon Sep 17 00:00:00 2001
From: Farzon Lotfi 
Date: Thu, 8 Feb 2024 11:08:59 -0500
Subject: [PATCH 1/3] [HLSL] Implementation of dot intrinsic This change
 implements #70073

HLSL has a dot intrinsic defined here:
https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-dot

The intrinsic itself is defined as a HLSL_LANG LangBuiltin in Builtins.td.
This is used to associate all the dot product typdef defined hlsl_intrinsics.h
with a single intrinsic check in CGBuiltin.cpp & SemaChecking.cpp.

In IntrinsicsDirectX.td we define the llvmIR for the dot product.
A few goals were in mind for this IR. First it should operate on only
vectors. Second the return type should be the vector element type. Third
the second parameter vector should be of the same size as the first
parameter. Finally `a dot b` should be the same as `b dot a`.

In CGBuiltin.cpp hlsl has built on top of existing clang intrinsics via 
EmitBuiltinExpr. Dot
product though is language specific intrinsic and so is guarded behind 
getLangOpts().HLSL.
The call chain looks like this: EmitBuiltinExpr -> EmitHLSLBuiltinExp

EmitHLSLBuiltinExp dot product intrinsics makes a destinction
between vectors and scalars. This is because HLSL supports dot product on 
scalars which simplifies down to multiply.

Sema.h & SemaChecking.cpp saw the addition of CheckHLSLBuiltinFunctionCall, a 
language specific semantic validation that can be expanded for other hlsl 
specific intrinsics.
---
 clang/include/clang/Basic/Builtins.td |   6 +
 .../clang/Basic/DiagnosticSemaKinds.td|   2 +
 clang/include/clang/Sema/Sema.h   |   1 +
 clang/lib/CodeGen/CGBuiltin.cpp   |  49 
 clang/lib/CodeGen/CodeGenFunction.h   |   1 +
 clang/lib/Headers/hlsl/hlsl_intrinsics.h  |  92 
 clang/lib/Sema/SemaChecking.cpp   |  84 ++-
 clang/test/CodeGenHLSL/builtins/dot.hlsl  | 216 ++
 clang/test/SemaHLSL/BuiltIns/dot-errors.hlsl  |  46 
 llvm/include/llvm/IR/IntrinsicsDirectX.td |   5 +
 10 files changed, 497 insertions(+), 5 deletions(-)
 create mode 100644 clang/test/CodeGenHLSL/builtins/dot.hlsl
 create mode 100644 clang/test/SemaHLSL/BuiltIns/dot-errors.hlsl

diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index df74026c5d2d50..771c4f5d4121f4 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -4524,6 +4524,12 @@ def HLSLCreateHandle : LangBuiltin<"HLSL_LANG"> {
   let Prototype = "void*(unsigned char)";
 }
 
+def HLSLDotProduct : LangBuiltin<"HLSL_LANG"> {
+  let Spellings = ["__builtin_hlsl_dot"];
+  let Attributes = [NoThrow, Const, CustomTypeChecking];
+  let Prototype = "void(...)";
+}
+
 // Builtins for XRay.
 def XRayCustomEvent : Builtin {
   let Spellings = ["__xray_customevent"];
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index ebda201361fb07..5999b1ced36347 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -10270,6 +10270,8 @@ def err_vec_builtin_non_vector : Error<
  "first two arguments to %0 must be vectors">;
 def err_vec_builtin_incompatible_vector : Error<
   "first two arguments to %0 must have the same type">;
+def err_vec_builtin_incompatible_size : Error<
+  "first two arguments to %0 must have the same size">;
 def err_vsx_builtin_nonconstant_argument : Error<
   "argument %0 to %1 must be a 2-bit unsigned literal (i.e. 0, 1, 2 or 3)">;
 
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index fcccac10f4733a..c76c0df28334f8 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -14057,6 +14057,7 @@ class Sema final {
   bool CheckPPCBuiltinFunctionCall(const TargetInfo , unsigned BuiltinID,
CallExpr *TheCall);
   bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
+  bool CheckHLSLBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
   bool CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum);
   bool CheckRISCVBuiltinFunctionCall(const TargetInfo , unsigned BuiltinID,
  CallExpr *TheCall);
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 734eb5a035ca49..393ab497fb15c4 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -44,6 +44,7 @@
 #include "llvm/IR/IntrinsicsAMDGPU.h"
 #include "llvm/IR/IntrinsicsARM.h"
 #include "llvm/IR/IntrinsicsBPF.h"
+#include "llvm/IR/IntrinsicsDirectX.h"
 #include "llvm/IR/IntrinsicsHexagon.h"
 #include "llvm/IR/IntrinsicsNVPTX.h"
 #include "llvm/IR/IntrinsicsPowerPC.h"
@@ -5982,6 +5983,10 @@ RValue 

[clang] [clang-tools-extra] [clangd] Use `SymbolName` to represent Objective-C selectors (PR #82061)

2024-02-22 Thread Sam McCall via cfe-commits


@@ -27,19 +31,45 @@ namespace tooling {
 /// //   ^~ string 0 ~ ^~ string 1 ~
 /// \endcode
 class SymbolName {
+  llvm::SmallVector NamePieces;

sam-mccall wrote:

I'm a little wary of using this class as:

 - it seems like the design has only been informed by objective-C selectors. 
It's nice to abstract away difficulties of dealing with names, but this doesn't 
handle many (scope qualifiers, operator names, UDL-names) and it's not clear 
how/whether it should. If not, I think clangd is better off without the layer 
of indirection.
 - it's not really clear what you would *do* with this model (name chunks as 
strings) other than semi-textual rename. If it's a helper class as part of 
tooling/refactor/rename's API, it might be helpful if it were named/documented 
as such.

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


[clang] [clang-tools-extra] [clangd] Use `SymbolName` to represent Objective-C selectors (PR #82061)

2024-02-22 Thread Sam McCall via cfe-commits


@@ -27,19 +31,45 @@ namespace tooling {
 /// //   ^~ string 0 ~ ^~ string 1 ~
 /// \endcode
 class SymbolName {
+  llvm::SmallVector NamePieces;
+
 public:
-  explicit SymbolName(StringRef Name) {
-// While empty symbol names are valid (Objective-C selectors can have empty
-// name pieces), occurrences Objective-C selectors are created using an
-// array of strings instead of just one string.
-assert(!Name.empty() && "Invalid symbol name!");
-this->Name.push_back(Name.str());
-  }
+  SymbolName();
+
+  /// Create a new \c SymbolName with the specified pieces.
+  explicit SymbolName(ArrayRef NamePieces);
+  explicit SymbolName(ArrayRef NamePieces);
+
+  explicit SymbolName(const DeclarationName );
 
-  ArrayRef getNamePieces() const { return Name; }
+  /// Creates a \c SymbolName from the given string representation.
+  ///
+  /// For Objective-C symbol names, this splits a selector into multiple pieces
+  /// on `:`. For all other languages the name is used as the symbol name.

sam-mccall wrote:

This looks too much like guesswork. For example in an ObjC++ file (which is our 
default parse language for *.h), SymbolName(`operator std::string`) will be 
parsed as the ObjC selector `[" operator std", "", "string"].

If we want to clearly distinguish the different types of names (as clang AST 
does) then we should avoid implicit conversions like this where it's easy to 
confuse the encoded/decoded state.

If we're content to mostly use strings and heuristically interpret them as 
selector names at the edges, that seems OK too - but then this class could just 
be a "split" function or so.

(This is up to you - I don't mind much what this API looks like unless we end 
up depending on it)


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


[clang] [clang-tools-extra] [clangd] Use `SymbolName` to represent Objective-C selectors (PR #82061)

2024-02-22 Thread Sam McCall via cfe-commits

https://github.com/sam-mccall requested changes to this pull request.

As mentioned: unless there's a clear reason, I'd avoid not to add the 
dependency on Tooling/Refactoring as it doesn't seem to simplify the 
implementation much.

(My last comment should have been on the review - sorry, I'm still bad at 
github!)

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


[clang] [clang-tools-extra] [clangd] Use `SymbolName` to represent Objective-C selectors (PR #82061)

2024-02-22 Thread Sam McCall via cfe-commits

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


[clang] [llvm] [AMDGPU] Adding the amdgpu-num-work-groups function attribute (PR #79035)

2024-02-22 Thread Jun Wang via cfe-commits

jwanggit86 wrote:

Thanks for explaining the "dependent exp". At present, template arguments are 
not required for the attribute. In other words, only int constants are 
supported. Diagnostics and test cases have been updated.

https://github.com/llvm/llvm-project/pull/79035
___
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 layout can be statically known (PR #81335)

2024-02-22 Thread via cfe-commits

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

>From b88dcd912f3c9d4c600fa2132dfe84eb74264d10 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| 96 +++
 1 file changed, 96 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..c4bb1ebc9a80be 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_$_SuperClass.superClassIvar" = hidden constant i64 20
+// CHECK: @"OBJC_IVAR_$_SuperClass._superClassProperty" = hidden constant i64 
24
+// CHECK: @"OBJC_IVAR_$_IntermediateClass.intermediateClassIvar" = global i64 
32
+// CHECK: @"OBJC_IVAR_$_IntermediateClass.intermediateClassIvar2" = global i64 
40
+// CHECK: @"OBJC_IVAR_$_IntermediateClass._intermediateProperty" = hidden 
global i64 48
+// CHECK: @"OBJC_IVAR_$_SubClass.subClassIvar" = global i64 56
+// CHECK: @"OBJC_IVAR_$_SubClass._subClassProperty" = hidden global i64 64
 // CHECK: @"OBJC_IVAR_$_NotStaticLayout.not_static_layout_ivar" = hidden 
global i64 12
 
 @interface NSObject {
@@ -20,6 +27,95 @@ -(void)meth {
 }
 @end
 
+// Ivars declared in the @interface
+@interface SuperClass : NSObject
+@property (nonatomic, assign) int superClassProperty;
+@end
+
+@implementation SuperClass {
+  int superClassIvar; // Declare an ivar
+}
+
+// CHECK-LABEL: define internal void @"\01-[SuperClass superClassMethod]"
+- (void)superClassMethod {
+_superClassProperty = 42;
+superClassIvar = 10;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SuperClass
+// CHECK: getelementptr inbounds i8, ptr %1, i64 20
+}
+
+// implicitly synthesized method here
+// CHECK-LABEL: define internal i32 @"\01-[SuperClass superClassProperty]"
+// CHECK: getelementptr inbounds i8, ptr %0, i64 24
+
+// CHECK-LABEL: define internal void @"\01-[SuperClass setSuperClassProperty:]"
+// CHECK: getelementptr inbounds i8, ptr %1, i64 24
+@end
+
+// Inheritance and Ivars
+@interface IntermediateClass : SuperClass
+{
+double intermediateClassIvar;
+
+@protected
+int intermediateClassIvar2;
+}
+@property (nonatomic, strong) SuperClass *intermediateProperty;
+@end
+
+@implementation IntermediateClass
+@synthesize intermediateProperty = _intermediateProperty;
+- (void)intermediateClassMethod {
+intermediateClassIvar = 3.14;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_IntermediateClass
+// CHECK: getelementptr inbounds i8, ptr %0, i64 %ivar
+}
+
+// CHECK-LABEL: define internal void @"\01-[IntermediateClass 
intermediateClassPropertyMethod]"
+- (void)intermediateClassPropertyMethod {
+self.intermediateProperty = 0;
+// CHECK: load ptr, ptr @OBJC_SELECTOR_REFERENCES_
+// CHECK: call void @objc_msgSend(ptr noundef %0, ptr noundef %1, ptr 
noundef null)
+}
+
+// CHECK-LABEL: define internal void @"\01-[IntermediateClass 
intermediateClassPropertyMethodDirect]"
+- (void)intermediateClassPropertyMethodDirect {
+_intermediateProperty = 0;
+// CHECK: load i64, ptr 
@"OBJC_IVAR_$_IntermediateClass._intermediateProperty"
+}
+@end
+
+@interface SubClass : IntermediateClass
+{
+double subClassIvar;
+}
+@property (nonatomic, assign) SubClass *subClassProperty;
+@end
+
+@implementation SubClass
+// CHECK-LABEL: define internal void @"\01-[SubClass subclassVar]"
+- (void)subclassVar {
+
+subClassIvar = 6.28;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SubClass
+// CHECK: getelementptr inbounds i8, ptr %0, i64 %ivar
+}
+
+// CHECK-LABEL: define internal void @"\01-[SubClass intermediateSubclassVar]"
+-(void)intermediateSubclassVar {
+intermediateClassIvar = 3.14;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_IntermediateClass
+// CHECK: getelementptr inbounds i8, ptr %0, i64 %ivar
+}
+
+// implicit synthesized method here:
+// CHECK-LABEL: define internal ptr @"\01-[SubClass subClassProperty]"
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SubClass._subClassProperty"
+
+// CHECK-LABEL: define internal void @"\01-[SubClass setSubClassProperty:]"
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SubClass._subClassProperty"
+@end
+
 @interface NotNSObject {
   int these, might, change;
 }

>From 96abdb23e6b6d660c9b14dcb5cd19dd9b26a6c96 Mon Sep 17 00:00:00 2001
From: Rose <83477269+ataridre...@users.noreply.github.com>
Date: Tue, 13 Feb 2024 14:52:49 -0500
Subject: [PATCH 2/2] [ObjC] Check entire chain of superclasses to see if class
 layout can be statically known

As of now, we only check if a class directly inherits from NSObject to 

[clang] [clang-tools-extra] [clangd] Use `SymbolName` to represent Objective-C selectors (PR #82061)

2024-02-22 Thread Sam McCall via cfe-commits

sam-mccall wrote:

I don't know that this class brings enough value to warrant the dependency - we 
don't really seem to be simplifying the code, we're mostly just using it as a 
fancy `vector`.

(For some context: we went to some effort in the past to untangle this from 
tooling/Refactoring/Rename, and a lot of pieces of clangd make tradeoffs 
between keeping design simple and handling all the special cases of C, C++, 
ObjC precisely).

Is the underlying goal here to be able to use `adjustRenameRanges` from outside 
of clangd? (That's my reading of "finding the ranges to rename based on an 
index that’s not clangd’s built-in index" - if you were doing this inside 
clangd, ISTM you'd have a Selector regardless of the index used).
We don't use the selector for anything other than the text chunks it contains, 
so I think you could just replace `optional` with 
`optional>` there.

(I don't think there are any plans to make use of Selector in other ways, 
@kadircet @DavidGoldman would know)

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


[clang] [Headers][X86] Make brief descriptions briefer (PR #82422)

2024-02-22 Thread Phoebe Wang via cfe-commits

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

LGTM.

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


[clang] [Headers][X86] Make brief descriptions briefer (PR #82422)

2024-02-22 Thread Phoebe Wang via cfe-commits


@@ -2099,9 +2099,11 @@ static __inline__ __m128i __DEFAULT_FN_ATTRS 
_mm_add_epi64(__m128i __a,
 }
 
 /// Adds, with saturation, the corresponding elements of two 128-bit
-///signed [16 x i8] vectors, saving each sum in the corresponding element 
of
-///a 128-bit result vector of [16 x i8]. Positive sums greater than 0x7F 
are
-///saturated to 0x7F. Negative sums less than 0x80 are saturated to 0x80.
+///signed [16 x i8] vectors, saving each sum in the corresponding element
+///of a 128-bit result vector of [16 x i8].
+///

phoebewang wrote:

> Are you saying the detail about saturation belongs in the brief description?

Yes. I though otherwise the full description may turn into the second paragraph 
only. I'm not a doxygen user, so the explanation sounds good to me.

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


[clang] [NFC] Fix formatting so CI can continue (PR #82721)

2024-02-22 Thread via cfe-commits

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

>From 815f9333db0cec9a1db87fd4c3af90097520edc6 Mon Sep 17 00:00:00 2001
From: Rose <83477269+ataridre...@users.noreply.github.com>
Date: Thu, 22 Feb 2024 20:50:48 -0500
Subject: [PATCH] [NFC] Fix formatting so CI can continue

These keep tripping up the build bots for clang and preventing testing on libc 
to go forward.
---
 clang/docs/HLSL/ExpectedDifferences.rst | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/clang/docs/HLSL/ExpectedDifferences.rst 
b/clang/docs/HLSL/ExpectedDifferences.rst
index 60001b22dc7920..d1b6010f10f43a 100644
--- a/clang/docs/HLSL/ExpectedDifferences.rst
+++ b/clang/docs/HLSL/ExpectedDifferences.rst
@@ -93,7 +93,7 @@ behavior between Clang and DXC. Some examples include:
 fma(X, Y, Z); // DXC: Fails to resolve no known conversion from float to 
double.
   // Clang: Resolves to fma(double,double,double).
   #endif
-
+
 double D = dot(A, B); // DXC: Resolves to dot(double3, double3), fails 
DXIL Validation.
   // FXC: Expands to compute double dot product with 
fmul/fadd
   // Clang: Resolves to dot(float3, float3), emits 
conversion warnings.
@@ -102,7 +102,7 @@ behavior between Clang and DXC. Some examples include:
 
 .. note::
 
-  In Clang, a conscious decision was made to exclude the 
``dot(vector, vector)`` 
+  In Clang, a conscious decision was made to exclude the 
``dot(vector, vector)``
   overload and allow overload resolution to resolve the
   ``vector`` overload. This approach provides ``-Wconversion``
   diagnostic notifying the user of the conversion rather than silently altering

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


[clang] [NFC] Fix formatting so CI can continue (PR #82721)

2024-02-22 Thread via cfe-commits

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


[clang] [NFC] Fix clang format errors (PR #82721)

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


[clang] [NFC] Fix clang format errors (PR #82721)

2024-02-22 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang

@llvm/pr-subscribers-hlsl

Author: AtariDreams (AtariDreams)


Changes

These keep tripping up the build bots for clang and preventing testing on libc 
to go forward.

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


1 Files Affected:

- (modified) clang/docs/HLSL/ExpectedDifferences.rst (+2-2) 


``diff
diff --git a/clang/docs/HLSL/ExpectedDifferences.rst 
b/clang/docs/HLSL/ExpectedDifferences.rst
index 60001b22dc7920..d1b6010f10f43a 100644
--- a/clang/docs/HLSL/ExpectedDifferences.rst
+++ b/clang/docs/HLSL/ExpectedDifferences.rst
@@ -93,7 +93,7 @@ behavior between Clang and DXC. Some examples include:
 fma(X, Y, Z); // DXC: Fails to resolve no known conversion from float to 
double.
   // Clang: Resolves to fma(double,double,double).
   #endif
-
+
 double D = dot(A, B); // DXC: Resolves to dot(double3, double3), fails 
DXIL Validation.
   // FXC: Expands to compute double dot product with 
fmul/fadd
   // Clang: Resolves to dot(float3, float3), emits 
conversion warnings.
@@ -102,7 +102,7 @@ behavior between Clang and DXC. Some examples include:
 
 .. note::
 
-  In Clang, a conscious decision was made to exclude the 
``dot(vector, vector)`` 
+  In Clang, a conscious decision was made to exclude the 
``dot(vector, vector)``
   overload and allow overload resolution to resolve the
   ``vector`` overload. This approach provides ``-Wconversion``
   diagnostic notifying the user of the conversion rather than silently altering

``




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


[clang] [NFC] Fix clang format errors (PR #82721)

2024-02-22 Thread via cfe-commits

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

These keep tripping up the build bots for clang and preventing testing on libc 
to go forward.

>From c126098cb7fdd1e5c0d22b946732cd90a9671f96 Mon Sep 17 00:00:00 2001
From: Rose <83477269+ataridre...@users.noreply.github.com>
Date: Thu, 22 Feb 2024 20:50:48 -0500
Subject: [PATCH] [NFC] Fix clang format errors

These keep tripping up the build bots for clang and preventing testing on libc 
to go forward.
---
 clang/docs/HLSL/ExpectedDifferences.rst | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/clang/docs/HLSL/ExpectedDifferences.rst 
b/clang/docs/HLSL/ExpectedDifferences.rst
index 60001b22dc7920..d1b6010f10f43a 100644
--- a/clang/docs/HLSL/ExpectedDifferences.rst
+++ b/clang/docs/HLSL/ExpectedDifferences.rst
@@ -93,7 +93,7 @@ behavior between Clang and DXC. Some examples include:
 fma(X, Y, Z); // DXC: Fails to resolve no known conversion from float to 
double.
   // Clang: Resolves to fma(double,double,double).
   #endif
-
+
 double D = dot(A, B); // DXC: Resolves to dot(double3, double3), fails 
DXIL Validation.
   // FXC: Expands to compute double dot product with 
fmul/fadd
   // Clang: Resolves to dot(float3, float3), emits 
conversion warnings.
@@ -102,7 +102,7 @@ behavior between Clang and DXC. Some examples include:
 
 .. note::
 
-  In Clang, a conscious decision was made to exclude the 
``dot(vector, vector)`` 
+  In Clang, a conscious decision was made to exclude the 
``dot(vector, vector)``
   overload and allow overload resolution to resolve the
   ``vector`` overload. This approach provides ``-Wconversion``
   diagnostic notifying the user of the conversion rather than silently altering

___
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 layout can be statically known (PR #81335)

2024-02-22 Thread via cfe-commits

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

>From 40658e0af6d70dbc1d8cfee026aaa36ef6287276 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| 96 +++
 1 file changed, 96 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..c4bb1ebc9a80be 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_$_SuperClass.superClassIvar" = hidden constant i64 20
+// CHECK: @"OBJC_IVAR_$_SuperClass._superClassProperty" = hidden constant i64 
24
+// CHECK: @"OBJC_IVAR_$_IntermediateClass.intermediateClassIvar" = global i64 
32
+// CHECK: @"OBJC_IVAR_$_IntermediateClass.intermediateClassIvar2" = global i64 
40
+// CHECK: @"OBJC_IVAR_$_IntermediateClass._intermediateProperty" = hidden 
global i64 48
+// CHECK: @"OBJC_IVAR_$_SubClass.subClassIvar" = global i64 56
+// CHECK: @"OBJC_IVAR_$_SubClass._subClassProperty" = hidden global i64 64
 // CHECK: @"OBJC_IVAR_$_NotStaticLayout.not_static_layout_ivar" = hidden 
global i64 12
 
 @interface NSObject {
@@ -20,6 +27,95 @@ -(void)meth {
 }
 @end
 
+// Ivars declared in the @interface
+@interface SuperClass : NSObject
+@property (nonatomic, assign) int superClassProperty;
+@end
+
+@implementation SuperClass {
+  int superClassIvar; // Declare an ivar
+}
+
+// CHECK-LABEL: define internal void @"\01-[SuperClass superClassMethod]"
+- (void)superClassMethod {
+_superClassProperty = 42;
+superClassIvar = 10;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SuperClass
+// CHECK: getelementptr inbounds i8, ptr %1, i64 20
+}
+
+// implicitly synthesized method here
+// CHECK-LABEL: define internal i32 @"\01-[SuperClass superClassProperty]"
+// CHECK: getelementptr inbounds i8, ptr %0, i64 24
+
+// CHECK-LABEL: define internal void @"\01-[SuperClass setSuperClassProperty:]"
+// CHECK: getelementptr inbounds i8, ptr %1, i64 24
+@end
+
+// Inheritance and Ivars
+@interface IntermediateClass : SuperClass
+{
+double intermediateClassIvar;
+
+@protected
+int intermediateClassIvar2;
+}
+@property (nonatomic, strong) SuperClass *intermediateProperty;
+@end
+
+@implementation IntermediateClass
+@synthesize intermediateProperty = _intermediateProperty;
+- (void)intermediateClassMethod {
+intermediateClassIvar = 3.14;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_IntermediateClass
+// CHECK: getelementptr inbounds i8, ptr %0, i64 %ivar
+}
+
+// CHECK-LABEL: define internal void @"\01-[IntermediateClass 
intermediateClassPropertyMethod]"
+- (void)intermediateClassPropertyMethod {
+self.intermediateProperty = 0;
+// CHECK: load ptr, ptr @OBJC_SELECTOR_REFERENCES_
+// CHECK: call void @objc_msgSend(ptr noundef %0, ptr noundef %1, ptr 
noundef null)
+}
+
+// CHECK-LABEL: define internal void @"\01-[IntermediateClass 
intermediateClassPropertyMethodDirect]"
+- (void)intermediateClassPropertyMethodDirect {
+_intermediateProperty = 0;
+// CHECK: load i64, ptr 
@"OBJC_IVAR_$_IntermediateClass._intermediateProperty"
+}
+@end
+
+@interface SubClass : IntermediateClass
+{
+double subClassIvar;
+}
+@property (nonatomic, assign) SubClass *subClassProperty;
+@end
+
+@implementation SubClass
+// CHECK-LABEL: define internal void @"\01-[SubClass subclassVar]"
+- (void)subclassVar {
+
+subClassIvar = 6.28;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SubClass
+// CHECK: getelementptr inbounds i8, ptr %0, i64 %ivar
+}
+
+// CHECK-LABEL: define internal void @"\01-[SubClass intermediateSubclassVar]"
+-(void)intermediateSubclassVar {
+intermediateClassIvar = 3.14;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_IntermediateClass
+// CHECK: getelementptr inbounds i8, ptr %0, i64 %ivar
+}
+
+// implicit synthesized method here:
+// CHECK-LABEL: define internal ptr @"\01-[SubClass subClassProperty]"
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SubClass._subClassProperty"
+
+// CHECK-LABEL: define internal void @"\01-[SubClass setSubClassProperty:]"
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SubClass._subClassProperty"
+@end
+
 @interface NotNSObject {
   int these, might, change;
 }

>From a2c3250eaa74f7db388551da04184a1956f282f1 Mon Sep 17 00:00:00 2001
From: Rose <83477269+ataridre...@users.noreply.github.com>
Date: Tue, 13 Feb 2024 14:52:49 -0500
Subject: [PATCH 2/2] [ObjC] Check entire chain of superclasses to see if class
 layout can be statically known

As of now, we only check if a class directly inherits from NSObject to 

[clang-tools-extra] [clang-tidy] Unsafe CRTP check (PR #82403)

2024-02-22 Thread via cfe-commits


@@ -0,0 +1,171 @@
+//===--- UnsafeCrtpCheck.cpp - clang-tidy 
-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "UnsafeCrtpCheck.h"
+#include "../utils/LexerUtils.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+namespace {
+// Finds a node if it's already a bound node.
+AST_MATCHER_P(CXXRecordDecl, isBoundNode, std::string, ID) {
+  return Builder->removeBindings(
+  [&](const ast_matchers::internal::BoundNodesMap ) {
+const auto *BoundRecord = Nodes.getNodeAs(ID);
+return BoundRecord != 
+  });
+}
+
+bool hasPrivateConstructor(const CXXRecordDecl *RD) {
+  for (auto & : RD->ctors()) {
+if (Ctor->getAccess() == AS_private)
+  return true;
+  }
+
+  return false;
+}
+
+bool isDerivedParameterBefriended(const CXXRecordDecl *CRTP,
+  const NamedDecl *Param) {
+  for (auto & : CRTP->friends()) {
+const auto *TTPT =
+dyn_cast(Friend->getFriendType()->getType());
+
+if (TTPT && TTPT->getDecl() == Param)
+  return true;
+  }
+
+  return false;
+}
+
+bool isDerivedClassBefriended(const CXXRecordDecl *CRTP,
+  const CXXRecordDecl *Derived) {
+  for (auto & : CRTP->friends()) {
+if (Friend->getFriendType()->getType()->getAsCXXRecordDecl() == Derived)
+  return true;
+  }
+
+  return false;
+}
+
+std::optional
+getDerivedParameter(const ClassTemplateSpecializationDecl *CRTP,
+const CXXRecordDecl *Derived) {
+  size_t Idx = 0;
+  bool Found = false;
+  for (auto & : CRTP->getTemplateArgs().asArray()) {
+if (TemplateArg.getKind() == TemplateArgument::Type &&
+TemplateArg.getAsType()->getAsCXXRecordDecl() == Derived) {
+  Found = true;
+  break;
+}
+++Idx;
+  }
+
+  if (!Found)
+return std::nullopt;
+
+  return 
CRTP->getSpecializedTemplate()->getTemplateParameters()->getParam(Idx);
+}
+
+std::vector hintMakeCtorPrivate(const CXXConstructorDecl *Ctor,
+   const std::string ,
+   const SourceManager ,
+   const LangOptions ) {
+  std::vector Hints;
+
+  Hints.emplace_back(FixItHint::CreateInsertion(
+  Ctor->getBeginLoc().getLocWithOffset(-1), "private:\n"));
+
+  const SourceLocation CtorEndLoc =
+  Ctor->isExplicitlyDefaulted()
+  ? utils::lexer::findNextTerminator(Ctor->getEndLoc(), SM, LangOpts)
+  : Ctor->getEndLoc();
+  Hints.emplace_back(FixItHint::CreateInsertion(
+  CtorEndLoc.getLocWithOffset(1), '\n' + OriginalAccess + ':' + '\n'));
+
+  return Hints;
+}
+} // namespace
+
+void UnsafeCrtpCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  classTemplateSpecializationDecl(
+  decl().bind("crtp"),
+  hasAnyTemplateArgument(refersToType(recordType(hasDeclaration(
+  cxxRecordDecl(isDerivedFrom(cxxRecordDecl(isBoundNode("crtp"
+  .bind("derived")),
+  this);
+}
+
+void UnsafeCrtpCheck::check(const MatchFinder::MatchResult ) {
+  const auto *CRTPInstantiation =
+  Result.Nodes.getNodeAs("crtp");
+  const auto *DerivedRecord = Result.Nodes.getNodeAs("derived");
+  const CXXRecordDecl *CRTPDeclaration =
+  CRTPInstantiation->getSpecializedTemplate()->getTemplatedDecl();
+
+  if (!CRTPDeclaration->hasUserDeclaredConstructor()) {
+const bool IsStruct = CRTPDeclaration->isStruct();
+
+diag(CRTPDeclaration->getLocation(),
+ "the implicit default constructor of the CRTP is publicly accessible")
+<< CRTPDeclaration
+<< FixItHint::CreateInsertion(
+   CRTPDeclaration->getBraceRange().getBegin().getLocWithOffset(1),
+   (IsStruct ? "\nprivate:\n" : "\n") +
+   CRTPDeclaration->getNameAsString() + "() = default;\n" +
+   (IsStruct ? "public:\n" : ""));
+diag(CRTPDeclaration->getLocation(), "consider making it private",
+ DiagnosticIDs::Note);

isuckatcs wrote:

See the answer in [a previous 
discussion](https://github.com/llvm/llvm-project/pull/82403#discussion_r1496412033).

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


[clang-tools-extra] [clang-tidy] Unsafe CRTP check (PR #82403)

2024-02-22 Thread via cfe-commits


@@ -0,0 +1,232 @@
+// RUN: %check_clang_tidy %s bugprone-unsafe-crtp %t
+
+namespace class_implicit_ctor {
+template 
+class CRTP {};
+// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: the implicit default constructor 
of the CRTP is publicly accessible [bugprone-unsafe-crtp]
+// CHECK-MESSAGES: :[[@LINE-2]]:7: note: consider making it private

isuckatcs wrote:

This pattern comes from the automatically generated checker template by 
`add_new_checker.py`. Not sure why the example is presented like this if this 
is undesired.
```c++
diag(MatchedDecl->getLocation(), "function %%0 is insufficiently awesome")
  << MatchedDecl
  << FixItHint::CreateInsertion(MatchedDecl->getLocation(), "awesome_");
  diag(MatchedDecl->getLocation(), "insert 'awesome'", DiagnosticIDs::Note);
```

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


[clang] [Clang][Parser] Have the depth of the abbreviated generic lambdas inside a requires clause differ from the surrounding generic lambda (PR #80656)

2024-02-22 Thread Younan Zhang via cfe-commits

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


[clang] 19e518d - [Clang][Parser] Have the depth of the abbreviated generic lambdas inside a requires clause differ from the surrounding generic lambda (#80656)

2024-02-22 Thread via cfe-commits

Author: Younan Zhang
Date: 2024-02-23T09:36:32+08:00
New Revision: 19e518d2623c0e87a87ebf30405e74448bd1ee70

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

LOG: [Clang][Parser] Have the depth of the abbreviated generic lambdas inside a 
requires clause differ from the surrounding generic lambda (#80656)

A one-line fix, again : )

This fixes https://github.com/llvm/llvm-project/issues/78524 and the
similar example at
https://github.com/llvm/llvm-project/issues/78524#issuecomment-1899886951.

We previously increased the template depth by one after parsing the
attaching requires-clause on a lambda expression. This led to a problem
where the 'auto' parameters of nested abbreviated generic lambdas,
inside of a requires-expression, had the same depth as the template
parameters of the surrounding lambda. Consequently, during the
concept-checking stage, we ended up substituting these parameters with
the wrong template arguments because they were at different levels.

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Parse/ParseExprCXX.cpp
clang/test/Parser/cxx-concepts-requires-clause.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 19cc5b77564316..529dd783ab7382 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -277,6 +277,10 @@ Bug Fixes to C++ Support
   (`#82258 `_)
 - Correctly immediate-escalate lambda conversion functions.
   (`#82258 `_)
+- Fixed an issue where template parameters of a nested abbreviated generic 
lambda within
+  a requires-clause lie at the same depth as those of the surrounding lambda. 
This,
+  in turn, results in the wrong template argument substitution during 
constraint checking.
+  (`#78524 `_)
 
 Bug Fixes to AST Handling
 ^

diff  --git a/clang/lib/Parse/ParseExprCXX.cpp 
b/clang/lib/Parse/ParseExprCXX.cpp
index fd262ff31e661a..22ee60af4616d2 100644
--- a/clang/lib/Parse/ParseExprCXX.cpp
+++ b/clang/lib/Parse/ParseExprCXX.cpp
@@ -1385,6 +1385,16 @@ ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
   Diag(RAngleLoc,
diag::err_lambda_template_parameter_list_empty);
 } else {
+  // We increase the template depth before recursing into a 
requires-clause.
+  //
+  // This depth is used for setting up a LambdaScopeInfo (in
+  // Sema::RecordParsingTemplateParameterDepth), which is used later when
+  // inventing template parameters in InventTemplateParameter.
+  //
+  // This way, abbreviated generic lambdas could have 
diff erent template
+  // depths, avoiding substitution into the wrong template parameters 
during
+  // constraint satisfaction check.
+  ++CurTemplateDepthTracker;
   ExprResult RequiresClause;
   if (TryConsumeToken(tok::kw_requires)) {
 RequiresClause =
@@ -1396,7 +1406,6 @@ ExprResult Parser::ParseLambdaExpressionAfterIntroducer(
 
   Actions.ActOnLambdaExplicitTemplateParameterList(
   Intro, LAngleLoc, TemplateParams, RAngleLoc, RequiresClause);
-  ++CurTemplateDepthTracker;
 }
   }
 

diff  --git a/clang/test/Parser/cxx-concepts-requires-clause.cpp 
b/clang/test/Parser/cxx-concepts-requires-clause.cpp
index 1ec1eefa128653..5b5bc9ea978bf2 100644
--- a/clang/test/Parser/cxx-concepts-requires-clause.cpp
+++ b/clang/test/Parser/cxx-concepts-requires-clause.cpp
@@ -168,3 +168,30 @@ auto lambda4 = [] requires(sizeof(char) == 1){}; // 
expected-error {{expected bo
 #if __cplusplus <= 202002L
 // expected-warning@-2{{lambda without a parameter clause is a C++23 
extension}}
 #endif
+
+namespace GH78524 {
+
+template  T Foo;
+
+template  auto C(Foo);
+
+template  struct D {
+  decltype(T()(C)) Type;
+};
+
+template  D G(T, U) { return {}; }
+
+struct E {};
+
+void F() {
+  G([]
+// ~~ T: Depth: 0, Index: 0
+  requires requires { [](auto...) {}; }(T)
+//    auto: Depth: 1, Index: 0
+{ return T(); },
+E{});
+}
+
+int a = [] requires requires { [](auto){}; } { return 0; }();
+
+} // namespace GH78524



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


[clang] [clang-tools-extra] [clangd] Use `SymbolName` to represent Objective-C selectors (PR #82061)

2024-02-22 Thread Alex Hoppen via cfe-commits


@@ -13,6 +13,7 @@ add_clang_library(clangToolingRefactoring
   Rename/USRFinder.cpp
   Rename/USRFindingAction.cpp
   Rename/USRLocFinder.cpp
+  SymbolName.cpp

ahoppen wrote:

Goode suggestions  

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


[clang] [clang-tools-extra] [clangd] Use `SymbolName` to represent Objective-C selectors (PR #82061)

2024-02-22 Thread Alex Hoppen via cfe-commits

https://github.com/ahoppen updated 
https://github.com/llvm/llvm-project/pull/82061

>From fca2389759d73380312e284c05ddc1662209de2e Mon Sep 17 00:00:00 2001
From: Alex Hoppen 
Date: Fri, 16 Feb 2024 14:50:25 -0800
Subject: [PATCH] [clangd] Use `SymbolName` to represent Objective-C selectors
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

This is a cleaner design than using identifier and an optional `Selector`. It 
also allows rename of Objective-C method names if no declaration is at hand and 
thus no `Selector` instance can be formed. For example, when finding the ranges 
to rename based on an index that’s not clangd’s built-in index.
---
 clang-tools-extra/clangd/refactor/Rename.cpp  | 57 +++
 clang-tools-extra/clangd/refactor/Rename.h|  6 +-
 .../clangd/unittests/RenameTests.cpp  |  6 +-
 .../Tooling/Refactoring/Rename/SymbolName.h   | 50 ++---
 clang/lib/Tooling/Refactoring/CMakeLists.txt  |  2 +
 .../Refactoring/Rename/RenamingAction.cpp |  4 +-
 .../Tooling/Refactoring/Rename/SymbolName.cpp | 70 +++
 .../Refactoring/Rename/USRLocFinder.cpp   |  4 +-
 .../Tooling/RefactoringActionRulesTest.cpp|  6 +-
 9 files changed, 150 insertions(+), 55 deletions(-)
 create mode 100644 clang/lib/Tooling/Refactoring/Rename/SymbolName.cpp

diff --git a/clang-tools-extra/clangd/refactor/Rename.cpp 
b/clang-tools-extra/clangd/refactor/Rename.cpp
index 650862c99bcd12..bd2fcbb7ab1008 100644
--- a/clang-tools-extra/clangd/refactor/Rename.cpp
+++ b/clang-tools-extra/clangd/refactor/Rename.cpp
@@ -40,6 +40,8 @@ namespace clang {
 namespace clangd {
 namespace {
 
+using tooling::SymbolName;
+
 std::optional filePath(const SymbolLocation ,
 llvm::StringRef HintFilePath) {
   if (!Loc)
@@ -591,11 +593,11 @@ bool isMatchingSelectorName(const syntax::Token , 
const syntax::Token ,
 // The search will terminate upon seeing Terminator or a ; at the top level.
 std::optional
 findAllSelectorPieces(llvm::ArrayRef Tokens,
-  const SourceManager , Selector Sel,
+  const SourceManager , const SymbolName ,
   tok::TokenKind Terminator) {
   assert(!Tokens.empty());
 
-  unsigned NumArgs = Sel.getNumArgs();
+  unsigned NumArgs = Name.getNamePieces().size();
   llvm::SmallVector Closes;
   std::vector SelectorPieces;
   for (unsigned Index = 0, Last = Tokens.size(); Index < Last - 1; ++Index) {
@@ -605,12 +607,12 @@ findAllSelectorPieces(llvm::ArrayRef 
Tokens,
   auto PieceCount = SelectorPieces.size();
   if (PieceCount < NumArgs &&
   isMatchingSelectorName(Tok, Tokens[Index + 1], SM,
- Sel.getNameForSlot(PieceCount))) {
+ Name.getNamePieces()[PieceCount])) {
 // If 'foo:' instead of ':' (empty selector), we need to skip the ':'
 // token after the name. We don't currently properly support empty
 // selectors since we may lex them improperly due to ternary statements
 // as well as don't properly support storing their ranges for edits.
-if (!Sel.getNameForSlot(PieceCount).empty())
+if (!Name.getNamePieces()[PieceCount].empty())
   ++Index;
 SelectorPieces.push_back(
 halfOpenToRange(SM, Tok.range(SM).toCharRange(SM)));
@@ -662,16 +664,17 @@ findAllSelectorPieces(llvm::ArrayRef 
Tokens,
 
 /// Collects all ranges of the given identifier/selector in the source code.
 ///
-/// If a selector is given, this does a full lex of the given source code in
-/// order to identify all selector fragments (e.g. in method exprs/decls) since
-/// they are non-contiguous.
-std::vector collectRenameIdentifierRanges(
-llvm::StringRef Identifier, llvm::StringRef Content,
-const LangOptions , std::optional Selector) {
+/// If `Name` is an Objective-C symbol name, this does a full lex of the given
+/// source code in order to identify all selector fragments (e.g. in method
+/// exprs/decls) since they are non-contiguous.
+std::vector
+collectRenameIdentifierRanges(const tooling::SymbolName ,
+  llvm::StringRef Content,
+  const LangOptions ) {
   std::vector Ranges;
-  if (!Selector) {
+  if (auto SinglePiece = Name.getSinglePiece()) {
 auto IdentifierRanges =
-collectIdentifierRanges(Identifier, Content, LangOpts);
+collectIdentifierRanges(*SinglePiece, Content, LangOpts);
 for (const auto  : IdentifierRanges)
   Ranges.emplace_back(R);
 return Ranges;
@@ -685,7 +688,7 @@ std::vector collectRenameIdentifierRanges(
   // parsing a method declaration or definition which isn't at the top level or
   // similar looking expressions (e.g. an @selector() expression).
   llvm::SmallVector Closes;
-  llvm::StringRef FirstSelPiece = Selector->getNameForSlot(0);
+  llvm::StringRef FirstSelPiece = Name.getNamePieces()[0];
 

[clang-tools-extra] [clang-tidy] Unsafe CRTP check (PR #82403)

2024-02-22 Thread via cfe-commits

https://github.com/isuckatcs updated 
https://github.com/llvm/llvm-project/pull/82403

>From a11b863a62f3e27d90e5b337b47d7f20e260d98b Mon Sep 17 00:00:00 2001
From: isuckatcs <65320245+isucka...@users.noreply.github.com>
Date: Fri, 16 Feb 2024 00:25:29 +0100
Subject: [PATCH 01/19] added new checker

---
 .../bugprone/BugproneTidyModule.cpp   |  3 +
 .../clang-tidy/bugprone/CMakeLists.txt|  1 +
 .../clang-tidy/bugprone/UnsafeCrtpCheck.cpp   | 92 +++
 .../clang-tidy/bugprone/UnsafeCrtpCheck.h | 30 ++
 clang-tools-extra/docs/ReleaseNotes.rst   |  5 +
 .../checks/bugprone/unsafe-crtp.rst   |  6 ++
 .../docs/clang-tidy/checks/list.rst   |  1 +
 .../checkers/bugprone/unsafe-crtp.cpp | 14 +++
 8 files changed, 152 insertions(+)
 create mode 100644 clang-tools-extra/clang-tidy/bugprone/UnsafeCrtpCheck.cpp
 create mode 100644 clang-tools-extra/clang-tidy/bugprone/UnsafeCrtpCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/bugprone/unsafe-crtp.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/unsafe-crtp.cpp

diff --git a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp 
b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
index a8a23b045f80bb..b7b4d85a86cce2 100644
--- a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
@@ -83,6 +83,7 @@
 #include "UnhandledExceptionAtNewCheck.h"
 #include "UnhandledSelfAssignmentCheck.h"
 #include "UniquePtrArrayMismatchCheck.h"
+#include "UnsafeCrtpCheck.h"
 #include "UnsafeFunctionsCheck.h"
 #include "UnusedLocalNonTrivialVariableCheck.h"
 #include "UnusedRaiiCheck.h"
@@ -237,6 +238,8 @@ class BugproneModule : public ClangTidyModule {
 "bugprone-unhandled-exception-at-new");
 CheckFactories.registerCheck(
 "bugprone-unique-ptr-array-mismatch");
+CheckFactories.registerCheck(
+"bugprone-unsafe-crtp");
 CheckFactories.registerCheck(
 "bugprone-unsafe-functions");
 CheckFactories.registerCheck(
diff --git a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
index 1cd6fb207d7625..956b12ad1cdecd 100644
--- a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
@@ -79,6 +79,7 @@ add_clang_library(clangTidyBugproneModule
   UnhandledExceptionAtNewCheck.cpp
   UnhandledSelfAssignmentCheck.cpp
   UniquePtrArrayMismatchCheck.cpp
+  UnsafeCrtpCheck.cpp
   UnsafeFunctionsCheck.cpp
   UnusedLocalNonTrivialVariableCheck.cpp
   UnusedRaiiCheck.cpp
diff --git a/clang-tools-extra/clang-tidy/bugprone/UnsafeCrtpCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/UnsafeCrtpCheck.cpp
new file mode 100644
index 00..eb0f6187e58b2e
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/bugprone/UnsafeCrtpCheck.cpp
@@ -0,0 +1,92 @@
+//===--- UnsafeCrtpCheck.cpp - clang-tidy 
-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "UnsafeCrtpCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+namespace {
+// Finds a node if it's already a bound node.
+AST_MATCHER_P(CXXRecordDecl, isBoundNode, std::string, ID) {
+  return Builder->removeBindings(
+  [&](const ast_matchers::internal::BoundNodesMap ) {
+const auto *BoundRecord = Nodes.getNodeAs(ID);
+return BoundRecord != 
+  });
+}
+} // namespace
+
+void UnsafeCrtpCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  cxxRecordDecl(
+  decl().bind("record"),
+  hasAnyBase(hasType(
+  classTemplateSpecializationDecl(
+  hasAnyTemplateArgument(refersToType(recordType(
+  hasDeclaration(cxxRecordDecl(isBoundNode("record")))
+  .bind("crtp",
+  this);
+}
+
+void UnsafeCrtpCheck::check(const MatchFinder::MatchResult ) {
+  const auto *MatchedCRTP = Result.Nodes.getNodeAs("crtp");
+
+  MatchedCRTP->dump();
+
+  for (auto & : MatchedCRTP->ctors()) {
+if (ctor->getAccess() != AS_private) {
+  ctor->dump();
+};
+  }
+
+  return;
+
+  // if (!MatchedDecl->hasDefinition())
+  //   return;
+
+  // for (auto & : MatchedDecl->bases()) {
+  //   const auto *TemplateSpecDecl =
+  //   llvm::dyn_cast_if_present(
+  //   Base.getType()->getAsTagDecl());
+
+  //   if (!TemplateSpecDecl)
+  // continue;
+
+  //   TemplateSpecDecl->dump();
+
+  //   for (auto & : TemplateSpecDecl->getTemplateArgs().asArray())
+  //   {
+  // if 

[clang-tools-extra] [clang-tidy] Unsafe CRTP check (PR #82403)

2024-02-22 Thread via cfe-commits


@@ -0,0 +1,62 @@
+.. title:: clang-tidy - bugprone-unsafe-crtp
+
+bugprone-unsafe-crtp
+
+
+Finds CRTP used in an error-prone way.
+
+If the constructor of a class intended to be used in a CRTP is public, then
+it allows users to construct that class on its own.
+
+Example:

isuckatcs wrote:

This pattern is used by multiple other check documentations too. I'm just being 
consistent here.

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


[clang-tools-extra] [clang-tidy] Unsafe CRTP check (PR #82403)

2024-02-22 Thread via cfe-commits


@@ -0,0 +1,232 @@
+// RUN: %check_clang_tidy %s bugprone-unsafe-crtp %t
+
+namespace class_implicit_ctor {
+template 
+class CRTP {};
+// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: the implicit default constructor 
of the CRTP is publicly accessible [bugprone-unsafe-crtp]
+// CHECK-MESSAGES: :[[@LINE-2]]:7: note: consider making it private
+// CHECK-FIXES: CRTP() = default;
+
+class A : CRTP {};
+} // namespace class_implicit_ctor
+
+namespace class_uncostructible {
+template 
+class CRTP {
+// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: the CRTP cannot be constructed 
from the derived class [bugprone-unsafe-crtp]

isuckatcs wrote:

Some checker test files leave the name of the checker there, some don't, some 
mixes the two. I think it doesn't hurt to know that the message should be 
expected from this checker, though it might be obvious based on the name of the 
test.

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


[clang-tools-extra] [clang-tidy] Unsafe CRTP check (PR #82403)

2024-02-22 Thread via cfe-commits


@@ -0,0 +1,171 @@
+//===--- UnsafeCrtpCheck.cpp - clang-tidy 
-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "UnsafeCrtpCheck.h"
+#include "../utils/LexerUtils.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+namespace {
+// Finds a node if it's already a bound node.
+AST_MATCHER_P(CXXRecordDecl, isBoundNode, std::string, ID) {
+  return Builder->removeBindings(
+  [&](const ast_matchers::internal::BoundNodesMap ) {
+const auto *BoundRecord = Nodes.getNodeAs(ID);
+return BoundRecord != 
+  });
+}
+
+bool hasPrivateConstructor(const CXXRecordDecl *RD) {
+  for (auto & : RD->ctors()) {

isuckatcs wrote:

After taking a look at other similar helpers throughout the clang-tidy codebase 
(grep `static .*\(.*\*.*`), none of them actually check for `nullptr`, or 
assert the opposite. With `llvm::any_of()`, all of these are 1 liners, so I 
wouldn't pollute them with an additional check either.

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


[clang] [Driver] Remove duplicate -r flag usage when linking (PR #82715)

2024-02-22 Thread Brad Smith via cfe-commits

https://github.com/brad0 updated https://github.com/llvm/llvm-project/pull/82715

>From 339a9bc79325809dc58783ceb83cf949081a2c96 Mon Sep 17 00:00:00 2001
From: Brad Smith 
Date: Thu, 22 Feb 2024 19:44:56 -0500
Subject: [PATCH] [Driver] Remove duplicate -r flag usage when linking

Bug #82010
---
 clang/lib/Driver/ToolChains/Darwin.cpp| 5 ++---
 clang/lib/Driver/ToolChains/DragonFly.cpp | 2 +-
 clang/lib/Driver/ToolChains/FreeBSD.cpp   | 4 ++--
 clang/lib/Driver/ToolChains/Haiku.cpp | 2 +-
 clang/lib/Driver/ToolChains/NetBSD.cpp| 2 +-
 clang/lib/Driver/ToolChains/OpenBSD.cpp   | 4 ++--
 clang/lib/Driver/ToolChains/PS4CPU.cpp| 5 ++---
 clang/lib/Driver/ToolChains/Solaris.cpp   | 3 +--
 8 files changed, 12 insertions(+), 15 deletions(-)

diff --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index cc1219d69d9910..fff538d2e5d735 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -643,9 +643,8 @@ void darwin::Linker::ConstructJob(Compilation , const 
JobAction ,
 
   // It seems that the 'e' option is completely ignored for dynamic executables
   // (the default), and with static executables, the last one wins, as 
expected.
-  Args.addAllArgs(CmdArgs,
-  {options::OPT_d_Flag, options::OPT_s, options::OPT_t,
-   options::OPT_Z_Flag, options::OPT_u_Group, options::OPT_r});
+  Args.addAllArgs(CmdArgs, {options::OPT_d_Flag, options::OPT_s, 
options::OPT_t,
+options::OPT_Z_Flag, options::OPT_u_Group});
 
   // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
   // members of static archive libraries which implement Objective-C classes or
diff --git a/clang/lib/Driver/ToolChains/DragonFly.cpp 
b/clang/lib/Driver/ToolChains/DragonFly.cpp
index 9942fc632e0a91..89e0600277c44c 100644
--- a/clang/lib/Driver/ToolChains/DragonFly.cpp
+++ b/clang/lib/Driver/ToolChains/DragonFly.cpp
@@ -122,7 +122,7 @@ void dragonfly::Linker::ConstructJob(Compilation , const 
JobAction ,
   }
 
   Args.addAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
-options::OPT_s, options::OPT_t, options::OPT_r});
+options::OPT_s, options::OPT_t});
   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
 
   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
diff --git a/clang/lib/Driver/ToolChains/FreeBSD.cpp 
b/clang/lib/Driver/ToolChains/FreeBSD.cpp
index b7c9e0e51cdb66..9d698f77583950 100644
--- a/clang/lib/Driver/ToolChains/FreeBSD.cpp
+++ b/clang/lib/Driver/ToolChains/FreeBSD.cpp
@@ -261,8 +261,8 @@ void freebsd::Linker::ConstructJob(Compilation , const 
JobAction ,
 
   Args.AddAllArgs(CmdArgs, options::OPT_L);
   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
-  Args.addAllArgs(CmdArgs, {options::OPT_T_Group, options::OPT_s,
-options::OPT_t, options::OPT_r});
+  Args.addAllArgs(CmdArgs,
+  {options::OPT_T_Group, options::OPT_s, options::OPT_t});
 
   if (D.isUsingLTO()) {
 assert(!Inputs.empty() && "Must have at least one input.");
diff --git a/clang/lib/Driver/ToolChains/Haiku.cpp 
b/clang/lib/Driver/ToolChains/Haiku.cpp
index e0d94035823fd3..ca7faa68765abf 100644
--- a/clang/lib/Driver/ToolChains/Haiku.cpp
+++ b/clang/lib/Driver/ToolChains/Haiku.cpp
@@ -80,7 +80,7 @@ void haiku::Linker::ConstructJob(Compilation , const 
JobAction ,
   }
 
   Args.addAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
-options::OPT_s, options::OPT_t, options::OPT_r});
+options::OPT_s, options::OPT_t});
   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
 
   if (D.isUsingLTO()) {
diff --git a/clang/lib/Driver/ToolChains/NetBSD.cpp 
b/clang/lib/Driver/ToolChains/NetBSD.cpp
index 240bf5764b9cce..645d0311641f34 100644
--- a/clang/lib/Driver/ToolChains/NetBSD.cpp
+++ b/clang/lib/Driver/ToolChains/NetBSD.cpp
@@ -268,7 +268,7 @@ void netbsd::Linker::ConstructJob(Compilation , const 
JobAction ,
   }
 
   Args.addAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
-options::OPT_s, options::OPT_t, options::OPT_r});
+options::OPT_s, options::OPT_t});
   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
 
   bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
diff --git a/clang/lib/Driver/ToolChains/OpenBSD.cpp 
b/clang/lib/Driver/ToolChains/OpenBSD.cpp
index fd6aa4d7e68447..97f88b7b79dfbe 100644
--- a/clang/lib/Driver/ToolChains/OpenBSD.cpp
+++ b/clang/lib/Driver/ToolChains/OpenBSD.cpp
@@ -192,8 +192,8 @@ void openbsd::Linker::ConstructJob(Compilation , const 
JobAction ,
 
   Args.AddAllArgs(CmdArgs, options::OPT_L);
   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
-  Args.addAllArgs(CmdArgs, {options::OPT_T_Group, options::OPT_s,
-options::OPT_t, options::OPT_r});
+  Args.addAllArgs(CmdArgs,
+  

[clang] [Driver] Remove duplicate -r flag usage when linking (PR #82715)

2024-02-22 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 cd1d4d8dd31f527615de26f5b62d687c6b2982a6 
8049d576571703329d34f6a4d399665e07b22ee2 -- 
clang/lib/Driver/ToolChains/Darwin.cpp 
clang/lib/Driver/ToolChains/DragonFly.cpp 
clang/lib/Driver/ToolChains/FreeBSD.cpp clang/lib/Driver/ToolChains/Haiku.cpp 
clang/lib/Driver/ToolChains/NetBSD.cpp clang/lib/Driver/ToolChains/OpenBSD.cpp 
clang/lib/Driver/ToolChains/PS4CPU.cpp clang/lib/Driver/ToolChains/Solaris.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index 1922db77cb..fff538d2e5 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -643,9 +643,8 @@ void darwin::Linker::ConstructJob(Compilation , const 
JobAction ,
 
   // It seems that the 'e' option is completely ignored for dynamic executables
   // (the default), and with static executables, the last one wins, as 
expected.
-  Args.addAllArgs(CmdArgs,
-  {options::OPT_d_Flag, options::OPT_s, options::OPT_t,
-   options::OPT_Z_Flag, options::OPT_u_Group});
+  Args.addAllArgs(CmdArgs, {options::OPT_d_Flag, options::OPT_s, 
options::OPT_t,
+options::OPT_Z_Flag, options::OPT_u_Group});
 
   // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
   // members of static archive libraries which implement Objective-C classes or
diff --git a/clang/lib/Driver/ToolChains/FreeBSD.cpp 
b/clang/lib/Driver/ToolChains/FreeBSD.cpp
index f8025c8e99..9d698f7758 100644
--- a/clang/lib/Driver/ToolChains/FreeBSD.cpp
+++ b/clang/lib/Driver/ToolChains/FreeBSD.cpp
@@ -261,8 +261,8 @@ void freebsd::Linker::ConstructJob(Compilation , const 
JobAction ,
 
   Args.AddAllArgs(CmdArgs, options::OPT_L);
   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
-  Args.addAllArgs(CmdArgs, {options::OPT_T_Group, options::OPT_s,
-options::OPT_t});
+  Args.addAllArgs(CmdArgs,
+  {options::OPT_T_Group, options::OPT_s, options::OPT_t});
 
   if (D.isUsingLTO()) {
 assert(!Inputs.empty() && "Must have at least one input.");
diff --git a/clang/lib/Driver/ToolChains/OpenBSD.cpp 
b/clang/lib/Driver/ToolChains/OpenBSD.cpp
index ff4da31349..97f88b7b79 100644
--- a/clang/lib/Driver/ToolChains/OpenBSD.cpp
+++ b/clang/lib/Driver/ToolChains/OpenBSD.cpp
@@ -192,8 +192,8 @@ void openbsd::Linker::ConstructJob(Compilation , const 
JobAction ,
 
   Args.AddAllArgs(CmdArgs, options::OPT_L);
   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
-  Args.addAllArgs(CmdArgs, {options::OPT_T_Group, options::OPT_s,
-options::OPT_t});
+  Args.addAllArgs(CmdArgs,
+  {options::OPT_T_Group, options::OPT_s, options::OPT_t});
 
   if (D.isUsingLTO()) {
 assert(!Inputs.empty() && "Must have at least one input.");
diff --git a/clang/lib/Driver/ToolChains/PS4CPU.cpp 
b/clang/lib/Driver/ToolChains/PS4CPU.cpp
index e97f843bff..7bf9aa7938 100644
--- a/clang/lib/Driver/ToolChains/PS4CPU.cpp
+++ b/clang/lib/Driver/ToolChains/PS4CPU.cpp
@@ -208,9 +208,8 @@ void tools::PScpu::Linker::ConstructJob(Compilation , 
const JobAction ,
   CmdArgs.push_back("--lto=full");
   }
 
-  Args.addAllArgs(CmdArgs,
-  {options::OPT_L, options::OPT_T_Group, options::OPT_s,
-   options::OPT_t});
+  Args.addAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
+options::OPT_s, options::OPT_t});
 
   if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle))
 CmdArgs.push_back("--no-demangle");
diff --git a/clang/lib/Driver/ToolChains/Solaris.cpp 
b/clang/lib/Driver/ToolChains/Solaris.cpp
index 71eb16..5d7f0ae2a3 100644
--- a/clang/lib/Driver/ToolChains/Solaris.cpp
+++ b/clang/lib/Driver/ToolChains/Solaris.cpp
@@ -201,8 +201,7 @@ void solaris::Linker::ConstructJob(Compilation , const 
JobAction ,
 
   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
 
-  Args.addAllArgs(CmdArgs,
-  {options::OPT_L, options::OPT_T_Group});
+  Args.addAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group});
 
   bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);

``




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


[clang] [Driver] Remove duplicate -r flag usage when linking (PR #82715)

2024-02-22 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Brad Smith (brad0)


Changes

Bug #82010

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


8 Files Affected:

- (modified) clang/lib/Driver/ToolChains/Darwin.cpp (+1-1) 
- (modified) clang/lib/Driver/ToolChains/DragonFly.cpp (+1-1) 
- (modified) clang/lib/Driver/ToolChains/FreeBSD.cpp (+1-1) 
- (modified) clang/lib/Driver/ToolChains/Haiku.cpp (+1-1) 
- (modified) clang/lib/Driver/ToolChains/NetBSD.cpp (+1-1) 
- (modified) clang/lib/Driver/ToolChains/OpenBSD.cpp (+1-1) 
- (modified) clang/lib/Driver/ToolChains/PS4CPU.cpp (+1-1) 
- (modified) clang/lib/Driver/ToolChains/Solaris.cpp (+1-1) 


``diff
diff --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index cc1219d69d9910..1922db77cb09ae 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -645,7 +645,7 @@ void darwin::Linker::ConstructJob(Compilation , const 
JobAction ,
   // (the default), and with static executables, the last one wins, as 
expected.
   Args.addAllArgs(CmdArgs,
   {options::OPT_d_Flag, options::OPT_s, options::OPT_t,
-   options::OPT_Z_Flag, options::OPT_u_Group, options::OPT_r});
+   options::OPT_Z_Flag, options::OPT_u_Group});
 
   // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
   // members of static archive libraries which implement Objective-C classes or
diff --git a/clang/lib/Driver/ToolChains/DragonFly.cpp 
b/clang/lib/Driver/ToolChains/DragonFly.cpp
index 9942fc632e0a91..89e0600277c44c 100644
--- a/clang/lib/Driver/ToolChains/DragonFly.cpp
+++ b/clang/lib/Driver/ToolChains/DragonFly.cpp
@@ -122,7 +122,7 @@ void dragonfly::Linker::ConstructJob(Compilation , const 
JobAction ,
   }
 
   Args.addAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
-options::OPT_s, options::OPT_t, options::OPT_r});
+options::OPT_s, options::OPT_t});
   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
 
   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
diff --git a/clang/lib/Driver/ToolChains/FreeBSD.cpp 
b/clang/lib/Driver/ToolChains/FreeBSD.cpp
index b7c9e0e51cdb66..f8025c8e993be7 100644
--- a/clang/lib/Driver/ToolChains/FreeBSD.cpp
+++ b/clang/lib/Driver/ToolChains/FreeBSD.cpp
@@ -262,7 +262,7 @@ void freebsd::Linker::ConstructJob(Compilation , const 
JobAction ,
   Args.AddAllArgs(CmdArgs, options::OPT_L);
   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
   Args.addAllArgs(CmdArgs, {options::OPT_T_Group, options::OPT_s,
-options::OPT_t, options::OPT_r});
+options::OPT_t});
 
   if (D.isUsingLTO()) {
 assert(!Inputs.empty() && "Must have at least one input.");
diff --git a/clang/lib/Driver/ToolChains/Haiku.cpp 
b/clang/lib/Driver/ToolChains/Haiku.cpp
index e0d94035823fd3..ca7faa68765abf 100644
--- a/clang/lib/Driver/ToolChains/Haiku.cpp
+++ b/clang/lib/Driver/ToolChains/Haiku.cpp
@@ -80,7 +80,7 @@ void haiku::Linker::ConstructJob(Compilation , const 
JobAction ,
   }
 
   Args.addAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
-options::OPT_s, options::OPT_t, options::OPT_r});
+options::OPT_s, options::OPT_t});
   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
 
   if (D.isUsingLTO()) {
diff --git a/clang/lib/Driver/ToolChains/NetBSD.cpp 
b/clang/lib/Driver/ToolChains/NetBSD.cpp
index 240bf5764b9cce..645d0311641f34 100644
--- a/clang/lib/Driver/ToolChains/NetBSD.cpp
+++ b/clang/lib/Driver/ToolChains/NetBSD.cpp
@@ -268,7 +268,7 @@ void netbsd::Linker::ConstructJob(Compilation , const 
JobAction ,
   }
 
   Args.addAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
-options::OPT_s, options::OPT_t, options::OPT_r});
+options::OPT_s, options::OPT_t});
   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
 
   bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
diff --git a/clang/lib/Driver/ToolChains/OpenBSD.cpp 
b/clang/lib/Driver/ToolChains/OpenBSD.cpp
index fd6aa4d7e68447..ff4da313498298 100644
--- a/clang/lib/Driver/ToolChains/OpenBSD.cpp
+++ b/clang/lib/Driver/ToolChains/OpenBSD.cpp
@@ -193,7 +193,7 @@ void openbsd::Linker::ConstructJob(Compilation , const 
JobAction ,
   Args.AddAllArgs(CmdArgs, options::OPT_L);
   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
   Args.addAllArgs(CmdArgs, {options::OPT_T_Group, options::OPT_s,
-options::OPT_t, options::OPT_r});
+options::OPT_t});
 
   if (D.isUsingLTO()) {
 assert(!Inputs.empty() && "Must have at least one input.");
diff --git a/clang/lib/Driver/ToolChains/PS4CPU.cpp 
b/clang/lib/Driver/ToolChains/PS4CPU.cpp
index 8ba8b80cfec78e..e97f843bff7fdc 100644
--- a/clang/lib/Driver/ToolChains/PS4CPU.cpp
+++ b/clang/lib/Driver/ToolChains/PS4CPU.cpp
@@ 

[clang] [Driver] Remove duplicate -r flag usage when linking (PR #82715)

2024-02-22 Thread Brad Smith via cfe-commits

https://github.com/brad0 created https://github.com/llvm/llvm-project/pull/82715

Bug #82010

>From 8049d576571703329d34f6a4d399665e07b22ee2 Mon Sep 17 00:00:00 2001
From: Brad Smith 
Date: Thu, 22 Feb 2024 19:44:56 -0500
Subject: [PATCH] [Driver] Remove duplicate -r flag usage when linking

Bug #82010
---
 clang/lib/Driver/ToolChains/Darwin.cpp| 2 +-
 clang/lib/Driver/ToolChains/DragonFly.cpp | 2 +-
 clang/lib/Driver/ToolChains/FreeBSD.cpp   | 2 +-
 clang/lib/Driver/ToolChains/Haiku.cpp | 2 +-
 clang/lib/Driver/ToolChains/NetBSD.cpp| 2 +-
 clang/lib/Driver/ToolChains/OpenBSD.cpp   | 2 +-
 clang/lib/Driver/ToolChains/PS4CPU.cpp| 2 +-
 clang/lib/Driver/ToolChains/Solaris.cpp   | 2 +-
 8 files changed, 8 insertions(+), 8 deletions(-)

diff --git a/clang/lib/Driver/ToolChains/Darwin.cpp 
b/clang/lib/Driver/ToolChains/Darwin.cpp
index cc1219d69d9910..1922db77cb09ae 100644
--- a/clang/lib/Driver/ToolChains/Darwin.cpp
+++ b/clang/lib/Driver/ToolChains/Darwin.cpp
@@ -645,7 +645,7 @@ void darwin::Linker::ConstructJob(Compilation , const 
JobAction ,
   // (the default), and with static executables, the last one wins, as 
expected.
   Args.addAllArgs(CmdArgs,
   {options::OPT_d_Flag, options::OPT_s, options::OPT_t,
-   options::OPT_Z_Flag, options::OPT_u_Group, options::OPT_r});
+   options::OPT_Z_Flag, options::OPT_u_Group});
 
   // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading
   // members of static archive libraries which implement Objective-C classes or
diff --git a/clang/lib/Driver/ToolChains/DragonFly.cpp 
b/clang/lib/Driver/ToolChains/DragonFly.cpp
index 9942fc632e0a91..89e0600277c44c 100644
--- a/clang/lib/Driver/ToolChains/DragonFly.cpp
+++ b/clang/lib/Driver/ToolChains/DragonFly.cpp
@@ -122,7 +122,7 @@ void dragonfly::Linker::ConstructJob(Compilation , const 
JobAction ,
   }
 
   Args.addAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
-options::OPT_s, options::OPT_t, options::OPT_r});
+options::OPT_s, options::OPT_t});
   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
 
   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
diff --git a/clang/lib/Driver/ToolChains/FreeBSD.cpp 
b/clang/lib/Driver/ToolChains/FreeBSD.cpp
index b7c9e0e51cdb66..f8025c8e993be7 100644
--- a/clang/lib/Driver/ToolChains/FreeBSD.cpp
+++ b/clang/lib/Driver/ToolChains/FreeBSD.cpp
@@ -262,7 +262,7 @@ void freebsd::Linker::ConstructJob(Compilation , const 
JobAction ,
   Args.AddAllArgs(CmdArgs, options::OPT_L);
   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
   Args.addAllArgs(CmdArgs, {options::OPT_T_Group, options::OPT_s,
-options::OPT_t, options::OPT_r});
+options::OPT_t});
 
   if (D.isUsingLTO()) {
 assert(!Inputs.empty() && "Must have at least one input.");
diff --git a/clang/lib/Driver/ToolChains/Haiku.cpp 
b/clang/lib/Driver/ToolChains/Haiku.cpp
index e0d94035823fd3..ca7faa68765abf 100644
--- a/clang/lib/Driver/ToolChains/Haiku.cpp
+++ b/clang/lib/Driver/ToolChains/Haiku.cpp
@@ -80,7 +80,7 @@ void haiku::Linker::ConstructJob(Compilation , const 
JobAction ,
   }
 
   Args.addAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
-options::OPT_s, options::OPT_t, options::OPT_r});
+options::OPT_s, options::OPT_t});
   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
 
   if (D.isUsingLTO()) {
diff --git a/clang/lib/Driver/ToolChains/NetBSD.cpp 
b/clang/lib/Driver/ToolChains/NetBSD.cpp
index 240bf5764b9cce..645d0311641f34 100644
--- a/clang/lib/Driver/ToolChains/NetBSD.cpp
+++ b/clang/lib/Driver/ToolChains/NetBSD.cpp
@@ -268,7 +268,7 @@ void netbsd::Linker::ConstructJob(Compilation , const 
JobAction ,
   }
 
   Args.addAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group,
-options::OPT_s, options::OPT_t, options::OPT_r});
+options::OPT_s, options::OPT_t});
   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
 
   bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
diff --git a/clang/lib/Driver/ToolChains/OpenBSD.cpp 
b/clang/lib/Driver/ToolChains/OpenBSD.cpp
index fd6aa4d7e68447..ff4da313498298 100644
--- a/clang/lib/Driver/ToolChains/OpenBSD.cpp
+++ b/clang/lib/Driver/ToolChains/OpenBSD.cpp
@@ -193,7 +193,7 @@ void openbsd::Linker::ConstructJob(Compilation , const 
JobAction ,
   Args.AddAllArgs(CmdArgs, options::OPT_L);
   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
   Args.addAllArgs(CmdArgs, {options::OPT_T_Group, options::OPT_s,
-options::OPT_t, options::OPT_r});
+options::OPT_t});
 
   if (D.isUsingLTO()) {
 assert(!Inputs.empty() && "Must have at least one input.");
diff --git a/clang/lib/Driver/ToolChains/PS4CPU.cpp 
b/clang/lib/Driver/ToolChains/PS4CPU.cpp
index 8ba8b80cfec78e..e97f843bff7fdc 100644
--- 

[clang] reland: [clang][ScanDeps] Canonicalize -D and -U flags (PR #82568)

2024-02-22 Thread Michael Spencer via cfe-commits

Bigcheese wrote:

Try double quotes.

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


[clang] reland: [clang][ScanDeps] Canonicalize -D and -U flags (PR #82568)

2024-02-22 Thread Michael Spencer via cfe-commits

https://github.com/Bigcheese updated 
https://github.com/llvm/llvm-project/pull/82568

>From 9759145f34306f1832b1deff0ca1b5e41d2ad89d Mon Sep 17 00:00:00 2001
From: Michael Spencer 
Date: Fri, 16 Feb 2024 22:05:25 -0800
Subject: [PATCH] [clang][ScanDeps] Canonicalize -D and -U flags

Canonicalize `-D` and `-U` flags by sorting them and only keeping the
last instance of a given name.

This optimization will only fire if all `-D` and `-U` flags start with
a simple identifier that we can guarantee a simple analysis of can
determine if two flags refer to the same identifier or not. See the
comment on `getSimpleMacroName()` for details of what the issues are.
---
 .../DependencyScanningService.h   |  5 +-
 .../DependencyScanningWorker.cpp  | 74 
 .../optimize-canonicalize-macros.m| 87 +++
 clang/tools/clang-scan-deps/ClangScanDeps.cpp |  1 +
 4 files changed, 166 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/ClangScanDeps/optimize-canonicalize-macros.m

diff --git 
a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningService.h 
b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningService.h
index 4f9867262a275c..557f0e547ab4a8 100644
--- a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningService.h
+++ b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningService.h
@@ -60,7 +60,10 @@ enum class ScanningOptimizations {
   /// Remove unused -ivfsoverlay arguments.
   VFS = 4,
 
-  DSS_LAST_BITMASK_ENUM(VFS),
+  /// Canonicalize -D and -U options.
+  Macros = 8,
+
+  DSS_LAST_BITMASK_ENUM(Macros),
   Default = All
 };
 
diff --git a/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp 
b/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
index 3cf3ad8a4e4907..7477b930188b4f 100644
--- a/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
+++ b/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
@@ -179,6 +179,78 @@ static void sanitizeDiagOpts(DiagnosticOptions ) {
   DiagOpts.IgnoreWarnings = true;
 }
 
+// Clang implements -D and -U by splatting text into a predefines buffer. This
+// allows constructs such as `-DFඞ=3 "-D F\u{0D9E} 4 3 2”` to be accepted and
+// define the same macro, or adding C++ style comments before the macro name.
+//
+// This function checks that the first non-space characters in the macro
+// obviously form an identifier that can be uniqued on without lexing. Failing
+// to do this could lead to changing the final definition of a macro.
+//
+// We could set up a preprocessor and actually lex the name, but that's very
+// heavyweight for a situation that will almost never happen in practice.
+static std::optional getSimpleMacroName(StringRef Macro) {
+  StringRef Name = Macro.split("=").first.ltrim(" \t");
+  std::size_t I = 0;
+
+  auto FinishName = [&]() -> std::optional {
+StringRef SimpleName = Name.slice(0, I);
+if (SimpleName.empty())
+  return std::nullopt;
+return SimpleName;
+  };
+
+  for (; I != Name.size(); ++I) {
+switch (Name[I]) {
+case '(': // Start of macro parameter list
+case ' ': // End of macro name
+case '\t':
+  return FinishName();
+case '_':
+  continue;
+default:
+  if (llvm::isAlnum(Name[I]))
+continue;
+  return std::nullopt;
+}
+  }
+  return FinishName();
+}
+
+static void canonicalizeDefines(PreprocessorOptions ) {
+  using MacroOpt = std::pair;
+  std::vector SimpleNames;
+  SimpleNames.reserve(PPOpts.Macros.size());
+  std::size_t Index = 0;
+  for (const auto  : PPOpts.Macros) {
+auto SName = getSimpleMacroName(M.first);
+// Skip optimizing if we can't guarantee we can preserve relative order.
+if (!SName)
+  return;
+SimpleNames.emplace_back(*SName, Index);
+++Index;
+  }
+
+  llvm::stable_sort(SimpleNames, [](const MacroOpt , const MacroOpt ) {
+return A.first < B.first;
+  });
+  // Keep the last instance of each macro name by going in reverse
+  auto NewEnd = std::unique(
+  SimpleNames.rbegin(), SimpleNames.rend(),
+  [](const MacroOpt , const MacroOpt ) { return A.first == B.first; });
+  SimpleNames.erase(SimpleNames.begin(), NewEnd.base());
+
+  // Apply permutation.
+  decltype(PPOpts.Macros) NewMacros;
+  NewMacros.reserve(SimpleNames.size());
+  for (std::size_t I = 0, E = SimpleNames.size(); I != E; ++I) {
+std::size_t OriginalIndex = SimpleNames[I].second;
+// We still emit undefines here as they may be undefining a predefined 
macro
+NewMacros.push_back(std::move(PPOpts.Macros[OriginalIndex]));
+  }
+  std::swap(PPOpts.Macros, NewMacros);
+}
+
 /// A clang tool that runs the preprocessor in a mode that's optimized for
 /// dependency scanning for the given compiler invocation.
 class DependencyScanningAction : public tooling::ToolAction {
@@ -203,6 +275,8 @@ class DependencyScanningAction : public tooling::ToolAction 
{
 

[clang-tools-extra] [clang-tidy] Unsafe CRTP check (PR #82403)

2024-02-22 Thread via cfe-commits

https://github.com/isuckatcs updated 
https://github.com/llvm/llvm-project/pull/82403

>From a11b863a62f3e27d90e5b337b47d7f20e260d98b Mon Sep 17 00:00:00 2001
From: isuckatcs <65320245+isucka...@users.noreply.github.com>
Date: Fri, 16 Feb 2024 00:25:29 +0100
Subject: [PATCH 01/18] added new checker

---
 .../bugprone/BugproneTidyModule.cpp   |  3 +
 .../clang-tidy/bugprone/CMakeLists.txt|  1 +
 .../clang-tidy/bugprone/UnsafeCrtpCheck.cpp   | 92 +++
 .../clang-tidy/bugprone/UnsafeCrtpCheck.h | 30 ++
 clang-tools-extra/docs/ReleaseNotes.rst   |  5 +
 .../checks/bugprone/unsafe-crtp.rst   |  6 ++
 .../docs/clang-tidy/checks/list.rst   |  1 +
 .../checkers/bugprone/unsafe-crtp.cpp | 14 +++
 8 files changed, 152 insertions(+)
 create mode 100644 clang-tools-extra/clang-tidy/bugprone/UnsafeCrtpCheck.cpp
 create mode 100644 clang-tools-extra/clang-tidy/bugprone/UnsafeCrtpCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/bugprone/unsafe-crtp.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/unsafe-crtp.cpp

diff --git a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp 
b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
index a8a23b045f80bb..b7b4d85a86cce2 100644
--- a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
@@ -83,6 +83,7 @@
 #include "UnhandledExceptionAtNewCheck.h"
 #include "UnhandledSelfAssignmentCheck.h"
 #include "UniquePtrArrayMismatchCheck.h"
+#include "UnsafeCrtpCheck.h"
 #include "UnsafeFunctionsCheck.h"
 #include "UnusedLocalNonTrivialVariableCheck.h"
 #include "UnusedRaiiCheck.h"
@@ -237,6 +238,8 @@ class BugproneModule : public ClangTidyModule {
 "bugprone-unhandled-exception-at-new");
 CheckFactories.registerCheck(
 "bugprone-unique-ptr-array-mismatch");
+CheckFactories.registerCheck(
+"bugprone-unsafe-crtp");
 CheckFactories.registerCheck(
 "bugprone-unsafe-functions");
 CheckFactories.registerCheck(
diff --git a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
index 1cd6fb207d7625..956b12ad1cdecd 100644
--- a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
@@ -79,6 +79,7 @@ add_clang_library(clangTidyBugproneModule
   UnhandledExceptionAtNewCheck.cpp
   UnhandledSelfAssignmentCheck.cpp
   UniquePtrArrayMismatchCheck.cpp
+  UnsafeCrtpCheck.cpp
   UnsafeFunctionsCheck.cpp
   UnusedLocalNonTrivialVariableCheck.cpp
   UnusedRaiiCheck.cpp
diff --git a/clang-tools-extra/clang-tidy/bugprone/UnsafeCrtpCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/UnsafeCrtpCheck.cpp
new file mode 100644
index 00..eb0f6187e58b2e
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/bugprone/UnsafeCrtpCheck.cpp
@@ -0,0 +1,92 @@
+//===--- UnsafeCrtpCheck.cpp - clang-tidy 
-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "UnsafeCrtpCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+namespace {
+// Finds a node if it's already a bound node.
+AST_MATCHER_P(CXXRecordDecl, isBoundNode, std::string, ID) {
+  return Builder->removeBindings(
+  [&](const ast_matchers::internal::BoundNodesMap ) {
+const auto *BoundRecord = Nodes.getNodeAs(ID);
+return BoundRecord != 
+  });
+}
+} // namespace
+
+void UnsafeCrtpCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  cxxRecordDecl(
+  decl().bind("record"),
+  hasAnyBase(hasType(
+  classTemplateSpecializationDecl(
+  hasAnyTemplateArgument(refersToType(recordType(
+  hasDeclaration(cxxRecordDecl(isBoundNode("record")))
+  .bind("crtp",
+  this);
+}
+
+void UnsafeCrtpCheck::check(const MatchFinder::MatchResult ) {
+  const auto *MatchedCRTP = Result.Nodes.getNodeAs("crtp");
+
+  MatchedCRTP->dump();
+
+  for (auto & : MatchedCRTP->ctors()) {
+if (ctor->getAccess() != AS_private) {
+  ctor->dump();
+};
+  }
+
+  return;
+
+  // if (!MatchedDecl->hasDefinition())
+  //   return;
+
+  // for (auto & : MatchedDecl->bases()) {
+  //   const auto *TemplateSpecDecl =
+  //   llvm::dyn_cast_if_present(
+  //   Base.getType()->getAsTagDecl());
+
+  //   if (!TemplateSpecDecl)
+  // continue;
+
+  //   TemplateSpecDecl->dump();
+
+  //   for (auto & : TemplateSpecDecl->getTemplateArgs().asArray())
+  //   {
+  // if 

[clang] [WebAssembly] Add more features to generic CPU config (PR #80923)

2024-02-22 Thread Heejin Ahn via cfe-commits

https://github.com/aheejin updated 
https://github.com/llvm/llvm-project/pull/80923

>From d6fd48794112d6c140024d7cd55b5fe5e55e Mon Sep 17 00:00:00 2001
From: Heejin Ahn 
Date: Tue, 6 Feb 2024 00:31:59 +
Subject: [PATCH 1/2] [WebAssembly] Add more features to generic CPU config

This enables nontrapping-fptoint, multivlaue, reference-types, and
bulk-memory in `-mcpu=generic` configuration. These proposals have been
standardized and supported in all major browsers for several years at
this point: 
https://github.com/WebAssembly/proposals/blob/main/finished-proposals.md
---
 clang/docs/ReleaseNotes.rst|  4 
 clang/lib/Basic/Targets/WebAssembly.cpp| 18 --
 clang/test/Preprocessor/wasm-target-features.c |  8 
 3 files changed, 20 insertions(+), 10 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 802c44b6c86080..5a07dcca106876 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -259,6 +259,10 @@ AIX Support
 WebAssembly Support
 ^^^
 
+The -mcpu=generic configuration now enables nontrapping-fptoint, multivalue,
+reference-types, and bulk-memory.These proposals are standardized and available
+in all major engines.
+
 AVR Support
 ^^^
 
diff --git a/clang/lib/Basic/Targets/WebAssembly.cpp 
b/clang/lib/Basic/Targets/WebAssembly.cpp
index f1c925d90cb649..38fe4013090f40 100644
--- a/clang/lib/Basic/Targets/WebAssembly.cpp
+++ b/clang/lib/Basic/Targets/WebAssembly.cpp
@@ -147,19 +147,25 @@ void 
WebAssemblyTargetInfo::setFeatureEnabled(llvm::StringMap ,
 bool WebAssemblyTargetInfo::initFeatureMap(
 llvm::StringMap , DiagnosticsEngine , StringRef CPU,
 const std::vector ) const {
-  if (CPU == "bleeding-edge") {
-Features["nontrapping-fptoint"] = true;
+  auto addGenericFeatures = [&]() {
 Features["sign-ext"] = true;
+Features["mutable-globals"] = true;
+Features["nontrapping-fptoint"] = true;
 Features["bulk-memory"] = true;
+Features["reference-types"] = true;
+Features["multivalue"] = true;
+  };
+  auto addBleedingEdgeFeatures = [&]() {
 Features["atomics"] = true;
-Features["mutable-globals"] = true;
 Features["tail-call"] = true;
-Features["reference-types"] = true;
 Features["multimemory"] = true;
 setSIMDLevel(Features, SIMD128, true);
+  };
+  if (CPU == "bleeding-edge") {
+addGenericFeatures();
+addBleedingEdgeFeatures();
   } else if (CPU == "generic") {
-Features["sign-ext"] = true;
-Features["mutable-globals"] = true;
+addGenericFeatures();
   }
 
   return TargetInfo::initFeatureMap(Features, Diags, CPU, FeaturesVec);
diff --git a/clang/test/Preprocessor/wasm-target-features.c 
b/clang/test/Preprocessor/wasm-target-features.c
index eccd432aa8eee6..5834e6d183bc9c 100644
--- a/clang/test/Preprocessor/wasm-target-features.c
+++ b/clang/test/Preprocessor/wasm-target-features.c
@@ -155,15 +155,15 @@
 //
 // GENERIC-DAG:#define __wasm_sign_ext__ 1{{$}}
 // GENERIC-DAG:#define __wasm_mutable_globals__ 1{{$}}
-// GENERIC-NOT:#define __wasm_nontrapping_fptoint__ 1{{$}}
-// GENERIC-NOT:#define __wasm_bulk_memory__ 1{{$}}
+// GENERIC-DAG:#define __wasm_nontrapping_fptoint__ 1{{$}}
+// GENERIC-DAG:#define __wasm_bulk_memory__ 1{{$}}
+// GENERIC-DAG:#define __wasm_multivalue__ 1{{$}}
+// GENERIC-DAG:#define __wasm_reference_types__ 1{{$}}
 // GENERIC-NOT:#define __wasm_simd128__ 1{{$}}
 // GENERIC-NOT:#define __wasm_atomics__ 1{{$}}
 // GENERIC-NOT:#define __wasm_tail_call__ 1{{$}}
 // GENERIC-NOT:#define __wasm_multimemory__ 1{{$}}
 // GENERIC-NOT:#define __wasm_exception_handling__ 1{{$}}
-// GENERIC-NOT:#define __wasm_multivalue__ 1{{$}}
-// GENERIC-NOT:#define __wasm_reference_types__ 1{{$}}
 // GENERIC-NOT:#define __wasm_extended_const__ 1{{$}}
 
 // RUN: %clang -E -dM %s -o - 2>&1 \

>From 01ac8bd38aaa86e62b00709790a36e050528f853 Mon Sep 17 00:00:00 2001
From: Heejin Ahn 
Date: Fri, 23 Feb 2024 00:31:41 +
Subject: [PATCH 2/2] Mention that ABI is not turned on

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

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 5a07dcca106876..ec85d8882c1861 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -261,7 +261,8 @@ WebAssembly Support
 
 The -mcpu=generic configuration now enables nontrapping-fptoint, multivalue,
 reference-types, and bulk-memory.These proposals are standardized and available
-in all major engines.
+in all major engines. Enabling multivalue here only enables the language 
feature
+but does not turn on the multivalue ABI.
 
 AVR Support
 ^^^

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


[clang-tools-extra] [clang-tidy] Unsafe CRTP check (PR #82403)

2024-02-22 Thread via cfe-commits

https://github.com/isuckatcs edited 
https://github.com/llvm/llvm-project/pull/82403
___
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 layout can be statically known (PR #81335)

2024-02-22 Thread via cfe-commits

AtariDreams wrote:

@rjmccall Done!

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-tools-extra] [clang-tidy] Unsafe CRTP check (PR #82403)

2024-02-22 Thread via cfe-commits


@@ -0,0 +1,171 @@
+//===--- UnsafeCrtpCheck.cpp - clang-tidy 
-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "UnsafeCrtpCheck.h"
+#include "../utils/LexerUtils.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+namespace {
+// Finds a node if it's already a bound node.
+AST_MATCHER_P(CXXRecordDecl, isBoundNode, std::string, ID) {
+  return Builder->removeBindings(
+  [&](const ast_matchers::internal::BoundNodesMap ) {
+const auto *BoundRecord = Nodes.getNodeAs(ID);
+return BoundRecord != 
+  });
+}
+
+bool hasPrivateConstructor(const CXXRecordDecl *RD) {
+  for (auto & : RD->ctors()) {
+if (Ctor->getAccess() == AS_private)
+  return true;
+  }
+
+  return false;

isuckatcs wrote:

I once heard that usually range-based for is prefered over these methods, but I 
see that they are widely used in clang-tidy, so I guess there is no harm in 
switching to these helpers.

https://github.com/llvm/llvm-project/pull/82403
___
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 layout can be statically known (PR #81335)

2024-02-22 Thread via cfe-commits

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

>From 6c46f5be980dac3200058b694ab7fca3f6ad707e 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| 96 +++
 1 file changed, 96 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..c4bb1ebc9a80be 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_$_SuperClass.superClassIvar" = hidden constant i64 20
+// CHECK: @"OBJC_IVAR_$_SuperClass._superClassProperty" = hidden constant i64 
24
+// CHECK: @"OBJC_IVAR_$_IntermediateClass.intermediateClassIvar" = global i64 
32
+// CHECK: @"OBJC_IVAR_$_IntermediateClass.intermediateClassIvar2" = global i64 
40
+// CHECK: @"OBJC_IVAR_$_IntermediateClass._intermediateProperty" = hidden 
global i64 48
+// CHECK: @"OBJC_IVAR_$_SubClass.subClassIvar" = global i64 56
+// CHECK: @"OBJC_IVAR_$_SubClass._subClassProperty" = hidden global i64 64
 // CHECK: @"OBJC_IVAR_$_NotStaticLayout.not_static_layout_ivar" = hidden 
global i64 12
 
 @interface NSObject {
@@ -20,6 +27,95 @@ -(void)meth {
 }
 @end
 
+// Ivars declared in the @interface
+@interface SuperClass : NSObject
+@property (nonatomic, assign) int superClassProperty;
+@end
+
+@implementation SuperClass {
+  int superClassIvar; // Declare an ivar
+}
+
+// CHECK-LABEL: define internal void @"\01-[SuperClass superClassMethod]"
+- (void)superClassMethod {
+_superClassProperty = 42;
+superClassIvar = 10;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SuperClass
+// CHECK: getelementptr inbounds i8, ptr %1, i64 20
+}
+
+// implicitly synthesized method here
+// CHECK-LABEL: define internal i32 @"\01-[SuperClass superClassProperty]"
+// CHECK: getelementptr inbounds i8, ptr %0, i64 24
+
+// CHECK-LABEL: define internal void @"\01-[SuperClass setSuperClassProperty:]"
+// CHECK: getelementptr inbounds i8, ptr %1, i64 24
+@end
+
+// Inheritance and Ivars
+@interface IntermediateClass : SuperClass
+{
+double intermediateClassIvar;
+
+@protected
+int intermediateClassIvar2;
+}
+@property (nonatomic, strong) SuperClass *intermediateProperty;
+@end
+
+@implementation IntermediateClass
+@synthesize intermediateProperty = _intermediateProperty;
+- (void)intermediateClassMethod {
+intermediateClassIvar = 3.14;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_IntermediateClass
+// CHECK: getelementptr inbounds i8, ptr %0, i64 %ivar
+}
+
+// CHECK-LABEL: define internal void @"\01-[IntermediateClass 
intermediateClassPropertyMethod]"
+- (void)intermediateClassPropertyMethod {
+self.intermediateProperty = 0;
+// CHECK: load ptr, ptr @OBJC_SELECTOR_REFERENCES_
+// CHECK: call void @objc_msgSend(ptr noundef %0, ptr noundef %1, ptr 
noundef null)
+}
+
+// CHECK-LABEL: define internal void @"\01-[IntermediateClass 
intermediateClassPropertyMethodDirect]"
+- (void)intermediateClassPropertyMethodDirect {
+_intermediateProperty = 0;
+// CHECK: load i64, ptr 
@"OBJC_IVAR_$_IntermediateClass._intermediateProperty"
+}
+@end
+
+@interface SubClass : IntermediateClass
+{
+double subClassIvar;
+}
+@property (nonatomic, assign) SubClass *subClassProperty;
+@end
+
+@implementation SubClass
+// CHECK-LABEL: define internal void @"\01-[SubClass subclassVar]"
+- (void)subclassVar {
+
+subClassIvar = 6.28;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SubClass
+// CHECK: getelementptr inbounds i8, ptr %0, i64 %ivar
+}
+
+// CHECK-LABEL: define internal void @"\01-[SubClass intermediateSubclassVar]"
+-(void)intermediateSubclassVar {
+intermediateClassIvar = 3.14;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_IntermediateClass
+// CHECK: getelementptr inbounds i8, ptr %0, i64 %ivar
+}
+
+// implicit synthesized method here:
+// CHECK-LABEL: define internal ptr @"\01-[SubClass subClassProperty]"
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SubClass._subClassProperty"
+
+// CHECK-LABEL: define internal void @"\01-[SubClass setSubClassProperty:]"
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SubClass._subClassProperty"
+@end
+
 @interface NotNSObject {
   int these, might, change;
 }

>From 7907980a315c86e43b14d1fc137fc655bbfd2dc3 Mon Sep 17 00:00:00 2001
From: Rose <83477269+ataridre...@users.noreply.github.com>
Date: Tue, 13 Feb 2024 14:52:49 -0500
Subject: [PATCH 2/2] [ObjC] Check entire chain of superclasses to see if class
 layout can be statically known

As of now, we only check if a class directly inherits from NSObject to 

[clang] [WebAssembly] Add more features to generic CPU config (PR #80923)

2024-02-22 Thread Heejin Ahn via cfe-commits

https://github.com/aheejin updated 
https://github.com/llvm/llvm-project/pull/80923

>From d6fd48794112d6c140024d7cd55b5fe5e55e Mon Sep 17 00:00:00 2001
From: Heejin Ahn 
Date: Tue, 6 Feb 2024 00:31:59 +
Subject: [PATCH 1/2] [WebAssembly] Add more features to generic CPU config

This enables nontrapping-fptoint, multivlaue, reference-types, and
bulk-memory in `-mcpu=generic` configuration. These proposals have been
standardized and supported in all major browsers for several years at
this point: 
https://github.com/WebAssembly/proposals/blob/main/finished-proposals.md
---
 clang/docs/ReleaseNotes.rst|  4 
 clang/lib/Basic/Targets/WebAssembly.cpp| 18 --
 clang/test/Preprocessor/wasm-target-features.c |  8 
 3 files changed, 20 insertions(+), 10 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 802c44b6c86080..5a07dcca106876 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -259,6 +259,10 @@ AIX Support
 WebAssembly Support
 ^^^
 
+The -mcpu=generic configuration now enables nontrapping-fptoint, multivalue,
+reference-types, and bulk-memory.These proposals are standardized and available
+in all major engines.
+
 AVR Support
 ^^^
 
diff --git a/clang/lib/Basic/Targets/WebAssembly.cpp 
b/clang/lib/Basic/Targets/WebAssembly.cpp
index f1c925d90cb649..38fe4013090f40 100644
--- a/clang/lib/Basic/Targets/WebAssembly.cpp
+++ b/clang/lib/Basic/Targets/WebAssembly.cpp
@@ -147,19 +147,25 @@ void 
WebAssemblyTargetInfo::setFeatureEnabled(llvm::StringMap ,
 bool WebAssemblyTargetInfo::initFeatureMap(
 llvm::StringMap , DiagnosticsEngine , StringRef CPU,
 const std::vector ) const {
-  if (CPU == "bleeding-edge") {
-Features["nontrapping-fptoint"] = true;
+  auto addGenericFeatures = [&]() {
 Features["sign-ext"] = true;
+Features["mutable-globals"] = true;
+Features["nontrapping-fptoint"] = true;
 Features["bulk-memory"] = true;
+Features["reference-types"] = true;
+Features["multivalue"] = true;
+  };
+  auto addBleedingEdgeFeatures = [&]() {
 Features["atomics"] = true;
-Features["mutable-globals"] = true;
 Features["tail-call"] = true;
-Features["reference-types"] = true;
 Features["multimemory"] = true;
 setSIMDLevel(Features, SIMD128, true);
+  };
+  if (CPU == "bleeding-edge") {
+addGenericFeatures();
+addBleedingEdgeFeatures();
   } else if (CPU == "generic") {
-Features["sign-ext"] = true;
-Features["mutable-globals"] = true;
+addGenericFeatures();
   }
 
   return TargetInfo::initFeatureMap(Features, Diags, CPU, FeaturesVec);
diff --git a/clang/test/Preprocessor/wasm-target-features.c 
b/clang/test/Preprocessor/wasm-target-features.c
index eccd432aa8eee6..5834e6d183bc9c 100644
--- a/clang/test/Preprocessor/wasm-target-features.c
+++ b/clang/test/Preprocessor/wasm-target-features.c
@@ -155,15 +155,15 @@
 //
 // GENERIC-DAG:#define __wasm_sign_ext__ 1{{$}}
 // GENERIC-DAG:#define __wasm_mutable_globals__ 1{{$}}
-// GENERIC-NOT:#define __wasm_nontrapping_fptoint__ 1{{$}}
-// GENERIC-NOT:#define __wasm_bulk_memory__ 1{{$}}
+// GENERIC-DAG:#define __wasm_nontrapping_fptoint__ 1{{$}}
+// GENERIC-DAG:#define __wasm_bulk_memory__ 1{{$}}
+// GENERIC-DAG:#define __wasm_multivalue__ 1{{$}}
+// GENERIC-DAG:#define __wasm_reference_types__ 1{{$}}
 // GENERIC-NOT:#define __wasm_simd128__ 1{{$}}
 // GENERIC-NOT:#define __wasm_atomics__ 1{{$}}
 // GENERIC-NOT:#define __wasm_tail_call__ 1{{$}}
 // GENERIC-NOT:#define __wasm_multimemory__ 1{{$}}
 // GENERIC-NOT:#define __wasm_exception_handling__ 1{{$}}
-// GENERIC-NOT:#define __wasm_multivalue__ 1{{$}}
-// GENERIC-NOT:#define __wasm_reference_types__ 1{{$}}
 // GENERIC-NOT:#define __wasm_extended_const__ 1{{$}}
 
 // RUN: %clang -E -dM %s -o - 2>&1 \

>From 01ac8bd38aaa86e62b00709790a36e050528f853 Mon Sep 17 00:00:00 2001
From: Heejin Ahn 
Date: Fri, 23 Feb 2024 00:31:41 +
Subject: [PATCH 2/2] Mention that ABI is not turned on

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

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 5a07dcca106876..ec85d8882c1861 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -261,7 +261,8 @@ WebAssembly Support
 
 The -mcpu=generic configuration now enables nontrapping-fptoint, multivalue,
 reference-types, and bulk-memory.These proposals are standardized and available
-in all major engines.
+in all major engines. Enabling multivalue here only enables the language 
feature
+but does not turn on the multivalue ABI.
 
 AVR Support
 ^^^

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


[clang-tools-extra] [clang-tidy] Unsafe CRTP check (PR #82403)

2024-02-22 Thread via cfe-commits


@@ -0,0 +1,167 @@
+//===--- UnsafeCrtpCheck.cpp - clang-tidy 
-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "UnsafeCrtpCheck.h"
+#include "../utils/LexerUtils.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+namespace {
+// Finds a node if it's already a bound node.
+AST_MATCHER_P(CXXRecordDecl, isBoundNode, std::string, ID) {
+  return Builder->removeBindings(
+  [&](const ast_matchers::internal::BoundNodesMap ) {
+const auto *BoundRecord = Nodes.getNodeAs(ID);
+return BoundRecord != 
+  });
+}
+
+bool hasPrivateConstructor(const CXXRecordDecl *RD) {
+  for (auto & : RD->ctors()) {
+if (Ctor->getAccess() == AS_private)
+  return true;
+  }
+
+  return false;
+}
+
+bool isDerivedParameterBefriended(const CXXRecordDecl *CRTP,
+  const NamedDecl *Param) {
+  for (auto & : CRTP->friends()) {
+const auto *TTPT =
+dyn_cast(Friend->getFriendType()->getType());
+
+if (TTPT && TTPT->getDecl() == Param)
+  return true;
+  }
+
+  return false;
+}
+
+bool isDerivedClassBefriended(const CXXRecordDecl *CRTP,
+  const CXXRecordDecl *Derived) {
+  for (auto & : CRTP->friends()) {
+if (Friend->getFriendType()->getType()->getAsCXXRecordDecl() == Derived)
+  return true;
+  }
+
+  return false;
+}
+
+std::optional
+getDerivedParameter(const ClassTemplateSpecializationDecl *CRTP,

isuckatcs wrote:

`getAsTemplate()` would be valid in the following example from the AST Matcher 
reference:
```c++
template class S> class X {};
template class Y {};
X xi;
```

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


[clang] [WebAssembly] Add more features to generic CPU config (PR #80923)

2024-02-22 Thread Heejin Ahn via cfe-commits


@@ -259,6 +259,10 @@ AIX Support
 WebAssembly Support
 ^^^
 
+The -mcpu=generic configuration now enables nontrapping-fptoint, multivalue,
+reference-types, and bulk-memory.These proposals are standardized and available
+in all major engines.

aheejin wrote:

Done

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


[clang] [WebAssembly] Add more features to generic CPU config (PR #80923)

2024-02-22 Thread Heejin Ahn via cfe-commits

https://github.com/aheejin updated 
https://github.com/llvm/llvm-project/pull/80923

>From d6fd48794112d6c140024d7cd55b5fe5e55e Mon Sep 17 00:00:00 2001
From: Heejin Ahn 
Date: Tue, 6 Feb 2024 00:31:59 +
Subject: [PATCH 1/2] [WebAssembly] Add more features to generic CPU config

This enables nontrapping-fptoint, multivlaue, reference-types, and
bulk-memory in `-mcpu=generic` configuration. These proposals have been
standardized and supported in all major browsers for several years at
this point: 
https://github.com/WebAssembly/proposals/blob/main/finished-proposals.md
---
 clang/docs/ReleaseNotes.rst|  4 
 clang/lib/Basic/Targets/WebAssembly.cpp| 18 --
 clang/test/Preprocessor/wasm-target-features.c |  8 
 3 files changed, 20 insertions(+), 10 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 802c44b6c86080..5a07dcca106876 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -259,6 +259,10 @@ AIX Support
 WebAssembly Support
 ^^^
 
+The -mcpu=generic configuration now enables nontrapping-fptoint, multivalue,
+reference-types, and bulk-memory.These proposals are standardized and available
+in all major engines.
+
 AVR Support
 ^^^
 
diff --git a/clang/lib/Basic/Targets/WebAssembly.cpp 
b/clang/lib/Basic/Targets/WebAssembly.cpp
index f1c925d90cb649..38fe4013090f40 100644
--- a/clang/lib/Basic/Targets/WebAssembly.cpp
+++ b/clang/lib/Basic/Targets/WebAssembly.cpp
@@ -147,19 +147,25 @@ void 
WebAssemblyTargetInfo::setFeatureEnabled(llvm::StringMap ,
 bool WebAssemblyTargetInfo::initFeatureMap(
 llvm::StringMap , DiagnosticsEngine , StringRef CPU,
 const std::vector ) const {
-  if (CPU == "bleeding-edge") {
-Features["nontrapping-fptoint"] = true;
+  auto addGenericFeatures = [&]() {
 Features["sign-ext"] = true;
+Features["mutable-globals"] = true;
+Features["nontrapping-fptoint"] = true;
 Features["bulk-memory"] = true;
+Features["reference-types"] = true;
+Features["multivalue"] = true;
+  };
+  auto addBleedingEdgeFeatures = [&]() {
 Features["atomics"] = true;
-Features["mutable-globals"] = true;
 Features["tail-call"] = true;
-Features["reference-types"] = true;
 Features["multimemory"] = true;
 setSIMDLevel(Features, SIMD128, true);
+  };
+  if (CPU == "bleeding-edge") {
+addGenericFeatures();
+addBleedingEdgeFeatures();
   } else if (CPU == "generic") {
-Features["sign-ext"] = true;
-Features["mutable-globals"] = true;
+addGenericFeatures();
   }
 
   return TargetInfo::initFeatureMap(Features, Diags, CPU, FeaturesVec);
diff --git a/clang/test/Preprocessor/wasm-target-features.c 
b/clang/test/Preprocessor/wasm-target-features.c
index eccd432aa8eee6..5834e6d183bc9c 100644
--- a/clang/test/Preprocessor/wasm-target-features.c
+++ b/clang/test/Preprocessor/wasm-target-features.c
@@ -155,15 +155,15 @@
 //
 // GENERIC-DAG:#define __wasm_sign_ext__ 1{{$}}
 // GENERIC-DAG:#define __wasm_mutable_globals__ 1{{$}}
-// GENERIC-NOT:#define __wasm_nontrapping_fptoint__ 1{{$}}
-// GENERIC-NOT:#define __wasm_bulk_memory__ 1{{$}}
+// GENERIC-DAG:#define __wasm_nontrapping_fptoint__ 1{{$}}
+// GENERIC-DAG:#define __wasm_bulk_memory__ 1{{$}}
+// GENERIC-DAG:#define __wasm_multivalue__ 1{{$}}
+// GENERIC-DAG:#define __wasm_reference_types__ 1{{$}}
 // GENERIC-NOT:#define __wasm_simd128__ 1{{$}}
 // GENERIC-NOT:#define __wasm_atomics__ 1{{$}}
 // GENERIC-NOT:#define __wasm_tail_call__ 1{{$}}
 // GENERIC-NOT:#define __wasm_multimemory__ 1{{$}}
 // GENERIC-NOT:#define __wasm_exception_handling__ 1{{$}}
-// GENERIC-NOT:#define __wasm_multivalue__ 1{{$}}
-// GENERIC-NOT:#define __wasm_reference_types__ 1{{$}}
 // GENERIC-NOT:#define __wasm_extended_const__ 1{{$}}
 
 // RUN: %clang -E -dM %s -o - 2>&1 \

>From 01ac8bd38aaa86e62b00709790a36e050528f853 Mon Sep 17 00:00:00 2001
From: Heejin Ahn 
Date: Fri, 23 Feb 2024 00:31:41 +
Subject: [PATCH 2/2] Mention that ABI is not turned on

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

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 5a07dcca106876..ec85d8882c1861 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -261,7 +261,8 @@ WebAssembly Support
 
 The -mcpu=generic configuration now enables nontrapping-fptoint, multivalue,
 reference-types, and bulk-memory.These proposals are standardized and available
-in all major engines.
+in all major engines. Enabling multivalue here only enables the language 
feature
+but does not turn on the multivalue ABI.
 
 AVR Support
 ^^^

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


[clang-tools-extra] [clang-tidy] Unsafe CRTP check (PR #82403)

2024-02-22 Thread via cfe-commits


@@ -0,0 +1,167 @@
+//===--- UnsafeCrtpCheck.cpp - clang-tidy 
-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "UnsafeCrtpCheck.h"
+#include "../utils/LexerUtils.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+namespace {
+// Finds a node if it's already a bound node.
+AST_MATCHER_P(CXXRecordDecl, isBoundNode, std::string, ID) {
+  return Builder->removeBindings(
+  [&](const ast_matchers::internal::BoundNodesMap ) {
+const auto *BoundRecord = Nodes.getNodeAs(ID);
+return BoundRecord != 
+  });
+}
+
+bool hasPrivateConstructor(const CXXRecordDecl *RD) {
+  for (auto & : RD->ctors()) {
+if (Ctor->getAccess() == AS_private)
+  return true;
+  }
+
+  return false;
+}
+
+bool isDerivedParameterBefriended(const CXXRecordDecl *CRTP,
+  const NamedDecl *Param) {
+  for (auto & : CRTP->friends()) {
+const auto *TTPT =
+dyn_cast(Friend->getFriendType()->getType());
+
+if (TTPT && TTPT->getDecl() == Param)
+  return true;
+  }
+
+  return false;
+}
+
+bool isDerivedClassBefriended(const CXXRecordDecl *CRTP,
+  const CXXRecordDecl *Derived) {
+  for (auto & : CRTP->friends()) {
+if (Friend->getFriendType()->getType()->getAsCXXRecordDecl() == Derived)
+  return true;
+  }
+
+  return false;
+}
+
+std::optional
+getDerivedParameter(const ClassTemplateSpecializationDecl *CRTP,

isuckatcs wrote:

`getAsTemplate()` returns the argument as a template if it is one.

```c++
  /// Retrieve the template name for a template name argument.
  TemplateName getAsTemplate() const {
assert(getKind() == Template && "Unexpected kind");
return TemplateName::getFromVoidPointer(TemplateArg.Name);
  }
```
In this case the kind is `Type`.

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


[clang-tools-extra] [clang-tidy] Unsafe CRTP check (PR #82403)

2024-02-22 Thread via cfe-commits

https://github.com/isuckatcs updated 
https://github.com/llvm/llvm-project/pull/82403

>From a11b863a62f3e27d90e5b337b47d7f20e260d98b Mon Sep 17 00:00:00 2001
From: isuckatcs <65320245+isucka...@users.noreply.github.com>
Date: Fri, 16 Feb 2024 00:25:29 +0100
Subject: [PATCH 01/17] added new checker

---
 .../bugprone/BugproneTidyModule.cpp   |  3 +
 .../clang-tidy/bugprone/CMakeLists.txt|  1 +
 .../clang-tidy/bugprone/UnsafeCrtpCheck.cpp   | 92 +++
 .../clang-tidy/bugprone/UnsafeCrtpCheck.h | 30 ++
 clang-tools-extra/docs/ReleaseNotes.rst   |  5 +
 .../checks/bugprone/unsafe-crtp.rst   |  6 ++
 .../docs/clang-tidy/checks/list.rst   |  1 +
 .../checkers/bugprone/unsafe-crtp.cpp | 14 +++
 8 files changed, 152 insertions(+)
 create mode 100644 clang-tools-extra/clang-tidy/bugprone/UnsafeCrtpCheck.cpp
 create mode 100644 clang-tools-extra/clang-tidy/bugprone/UnsafeCrtpCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/bugprone/unsafe-crtp.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/unsafe-crtp.cpp

diff --git a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp 
b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
index a8a23b045f80bb..b7b4d85a86cce2 100644
--- a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
@@ -83,6 +83,7 @@
 #include "UnhandledExceptionAtNewCheck.h"
 #include "UnhandledSelfAssignmentCheck.h"
 #include "UniquePtrArrayMismatchCheck.h"
+#include "UnsafeCrtpCheck.h"
 #include "UnsafeFunctionsCheck.h"
 #include "UnusedLocalNonTrivialVariableCheck.h"
 #include "UnusedRaiiCheck.h"
@@ -237,6 +238,8 @@ class BugproneModule : public ClangTidyModule {
 "bugprone-unhandled-exception-at-new");
 CheckFactories.registerCheck(
 "bugprone-unique-ptr-array-mismatch");
+CheckFactories.registerCheck(
+"bugprone-unsafe-crtp");
 CheckFactories.registerCheck(
 "bugprone-unsafe-functions");
 CheckFactories.registerCheck(
diff --git a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
index 1cd6fb207d7625..956b12ad1cdecd 100644
--- a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
@@ -79,6 +79,7 @@ add_clang_library(clangTidyBugproneModule
   UnhandledExceptionAtNewCheck.cpp
   UnhandledSelfAssignmentCheck.cpp
   UniquePtrArrayMismatchCheck.cpp
+  UnsafeCrtpCheck.cpp
   UnsafeFunctionsCheck.cpp
   UnusedLocalNonTrivialVariableCheck.cpp
   UnusedRaiiCheck.cpp
diff --git a/clang-tools-extra/clang-tidy/bugprone/UnsafeCrtpCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/UnsafeCrtpCheck.cpp
new file mode 100644
index 00..eb0f6187e58b2e
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/bugprone/UnsafeCrtpCheck.cpp
@@ -0,0 +1,92 @@
+//===--- UnsafeCrtpCheck.cpp - clang-tidy 
-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "UnsafeCrtpCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+namespace {
+// Finds a node if it's already a bound node.
+AST_MATCHER_P(CXXRecordDecl, isBoundNode, std::string, ID) {
+  return Builder->removeBindings(
+  [&](const ast_matchers::internal::BoundNodesMap ) {
+const auto *BoundRecord = Nodes.getNodeAs(ID);
+return BoundRecord != 
+  });
+}
+} // namespace
+
+void UnsafeCrtpCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  cxxRecordDecl(
+  decl().bind("record"),
+  hasAnyBase(hasType(
+  classTemplateSpecializationDecl(
+  hasAnyTemplateArgument(refersToType(recordType(
+  hasDeclaration(cxxRecordDecl(isBoundNode("record")))
+  .bind("crtp",
+  this);
+}
+
+void UnsafeCrtpCheck::check(const MatchFinder::MatchResult ) {
+  const auto *MatchedCRTP = Result.Nodes.getNodeAs("crtp");
+
+  MatchedCRTP->dump();
+
+  for (auto & : MatchedCRTP->ctors()) {
+if (ctor->getAccess() != AS_private) {
+  ctor->dump();
+};
+  }
+
+  return;
+
+  // if (!MatchedDecl->hasDefinition())
+  //   return;
+
+  // for (auto & : MatchedDecl->bases()) {
+  //   const auto *TemplateSpecDecl =
+  //   llvm::dyn_cast_if_present(
+  //   Base.getType()->getAsTagDecl());
+
+  //   if (!TemplateSpecDecl)
+  // continue;
+
+  //   TemplateSpecDecl->dump();
+
+  //   for (auto & : TemplateSpecDecl->getTemplateArgs().asArray())
+  //   {
+  // if 

[clang-tools-extra] [clang-tidy] Unsafe CRTP check (PR #82403)

2024-02-22 Thread via cfe-commits


@@ -0,0 +1,167 @@
+//===--- UnsafeCrtpCheck.cpp - clang-tidy 
-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "UnsafeCrtpCheck.h"
+#include "../utils/LexerUtils.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+namespace {
+// Finds a node if it's already a bound node.
+AST_MATCHER_P(CXXRecordDecl, isBoundNode, std::string, ID) {
+  return Builder->removeBindings(
+  [&](const ast_matchers::internal::BoundNodesMap ) {
+const auto *BoundRecord = Nodes.getNodeAs(ID);
+return BoundRecord != 
+  });
+}
+
+bool hasPrivateConstructor(const CXXRecordDecl *RD) {
+  for (auto & : RD->ctors()) {
+if (Ctor->getAccess() == AS_private)
+  return true;
+  }
+
+  return false;
+}
+
+bool isDerivedParameterBefriended(const CXXRecordDecl *CRTP,
+  const NamedDecl *Param) {
+  for (auto & : CRTP->friends()) {
+const auto *TTPT =
+dyn_cast(Friend->getFriendType()->getType());
+
+if (TTPT && TTPT->getDecl() == Param)
+  return true;
+  }
+
+  return false;
+}
+
+bool isDerivedClassBefriended(const CXXRecordDecl *CRTP,
+  const CXXRecordDecl *Derived) {
+  for (auto & : CRTP->friends()) {
+if (Friend->getFriendType()->getType()->getAsCXXRecordDecl() == Derived)
+  return true;
+  }
+
+  return false;
+}
+
+std::optional
+getDerivedParameter(const ClassTemplateSpecializationDecl *CRTP,
+const CXXRecordDecl *Derived) {
+  size_t Idx = 0;
+  bool Found = false;
+  for (auto & : CRTP->getTemplateArgs().asArray()) {
+if (TemplateArg.getKind() == TemplateArgument::Type &&
+TemplateArg.getAsType()->getAsCXXRecordDecl() == Derived) {
+  Found = true;
+  break;
+}
+++Idx;
+  }
+
+  if (!Found)
+return std::nullopt;
+
+  return 
CRTP->getSpecializedTemplate()->getTemplateParameters()->getParam(Idx);
+}
+
+std::vector hintMakeCtorPrivate(const CXXConstructorDecl *Ctor,
+   const std::string ,
+   const SourceManager ,
+   const LangOptions ) {
+  std::vector Hints;
+
+  Hints.emplace_back(FixItHint::CreateInsertion(
+  Ctor->getBeginLoc().getLocWithOffset(-1), "private:\n"));
+
+  SourceLocation CtorEndLoc =
+  Ctor->isExplicitlyDefaulted()
+  ? utils::lexer::findNextTerminator(Ctor->getEndLoc(), SM, LangOpts)
+  : Ctor->getEndLoc();
+  Hints.emplace_back(FixItHint::CreateInsertion(
+  CtorEndLoc.getLocWithOffset(1), '\n' + OriginalAccess + ':' + '\n'));
+
+  return Hints;
+}
+} // namespace
+
+void UnsafeCrtpCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  classTemplateSpecializationDecl(
+  decl().bind("crtp"),
+  hasAnyTemplateArgument(refersToType(recordType(hasDeclaration(
+  cxxRecordDecl(isDerivedFrom(cxxRecordDecl(isBoundNode("crtp"
+  .bind("derived")),
+  this);
+}
+
+void UnsafeCrtpCheck::check(const MatchFinder::MatchResult ) {
+  const auto *CRTPInstantiation =
+  Result.Nodes.getNodeAs("crtp");
+  const auto *DerivedRecord = Result.Nodes.getNodeAs("derived");
+  const CXXRecordDecl *CRTPDeclaration =
+  CRTPInstantiation->getSpecializedTemplate()->getTemplatedDecl();
+
+  if (!CRTPDeclaration->hasUserDeclaredConstructor()) {
+bool IsStruct = CRTPDeclaration->isStruct();
+
+diag(CRTPDeclaration->getLocation(),
+ "the implicit default constructor of the CRTP is publicly accessible")
+<< CRTPDeclaration
+<< FixItHint::CreateInsertion(
+   CRTPDeclaration->getBraceRange().getBegin().getLocWithOffset(1),
+   (IsStruct ? "\nprivate:\n" : "\n") +
+   CRTPDeclaration->getNameAsString() + "() = default;\n" +
+   (IsStruct ? "public:\n" : ""));
+diag(CRTPDeclaration->getLocation(), "consider making it private",
+ DiagnosticIDs::Note);
+  }
+
+  const auto *DerivedTemplateParameter =
+  *getDerivedParameter(CRTPInstantiation, DerivedRecord);
+
+  if (hasPrivateConstructor(CRTPDeclaration) &&
+  !isDerivedParameterBefriended(CRTPDeclaration,
+DerivedTemplateParameter) &&
+  !isDerivedClassBefriended(CRTPDeclaration, DerivedRecord)) {
+diag(CRTPDeclaration->getLocation(),
+ "the CRTP cannot be constructed from the derived class")
+<< CRTPDeclaration
+<< FixItHint::CreateInsertion(
+   CRTPDeclaration->getBraceRange().getEnd(),
+   "friend " + 

[clang] Thread safety analysis: provide printSCFG definition. (PR #80277)

2024-02-22 Thread Aaron Puchert via cfe-commits

aaronpuchert wrote:

This sounds like a good idea!

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


[clang] [clang][nullability] allow _Nonnull etc on gsl::Pointer types (PR #82705)

2024-02-22 Thread Sam McCall via cfe-commits

https://github.com/sam-mccall updated 
https://github.com/llvm/llvm-project/pull/82705

>From 77ba6fd11bd7ae58a2d95ec002414d6e6e9b Mon Sep 17 00:00:00 2001
From: Sam McCall 
Date: Thu, 22 Feb 2024 16:00:44 +0100
Subject: [PATCH] [clang][nullability] allow _Nonnull etc on gsl::Pointer types

This enables external nullability checkers to make use of these
annotations on smart pointer types.

Existing static warnings for raw pointers are extended to smart pointers:

- nullptr used as return value or argument for non-null functions
  (`-Wnonnull`)
- assigning or initializing nonnull variables with nullable values
  (`-Wnullable-to-nonnull-conversion`)

It doesn't implicitly add these attributes based on the assume_nonnull
pragma, nor warn on missing attributes where the pragma would apply them.
I'm not confident that the pragma's current behavior will work well for
C++ (where type-based metaprogramming is much more common than C/ObjC).
We'd like to revisit this once we have more implementation experience.

Support can be detected as `__has_feature(nullability_on_gsl_pointer)`.
This is needed for back-compatibility, as previously clang would issue a
hard error when _Nullable appears on a smart pointer.

UBSan's `-fsanitize=nullability` will not check smart-pointer types.
It can be made to do so by synthesizing calls to `operator bool`, but
that's left for future work.
---
 clang/include/clang/Basic/AttrDocs.td  |  4 ++
 clang/include/clang/Basic/Features.def |  1 +
 clang/lib/AST/Type.cpp | 43 -
 clang/lib/CodeGen/CGCall.cpp   |  3 +-
 clang/lib/CodeGen/CodeGenFunction.cpp  |  3 +-
 clang/lib/Sema/SemaChecking.cpp|  9 +
 clang/lib/Sema/SemaInit.cpp|  5 +++
 clang/lib/Sema/SemaOverload.cpp|  7 
 clang/lib/Sema/SemaType.cpp| 18 +++--
 clang/test/SemaCXX/nullability.cpp | 52 +-
 10 files changed, 127 insertions(+), 18 deletions(-)

diff --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index b96fbddd51154c..28f201830fe56f 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -4096,6 +4096,10 @@ non-underscored keywords. For example:
   @property (assign, nullable) NSView *superview;
   @property (readonly, nonnull) NSArray *subviews;
 @end
+
+As well as built-in pointer types, ithe nullability attributes can be attached
+to the standard C++ pointer types ``std::unique_ptr`` and ``std::shared_ptr``,
+as well as C++ classes marked with the ``gsl::Pointer`` attribute.
   }];
 }
 
diff --git a/clang/include/clang/Basic/Features.def 
b/clang/include/clang/Basic/Features.def
index 5fad5fc3623cb6..8f1880ea53e485 100644
--- a/clang/include/clang/Basic/Features.def
+++ b/clang/include/clang/Basic/Features.def
@@ -94,6 +94,7 @@ EXTENSION(define_target_os_macros,
 FEATURE(enumerator_attributes, true)
 FEATURE(nullability, true)
 FEATURE(nullability_on_arrays, true)
+FEATURE(nullability_on_gsl_pointer, true)
 FEATURE(nullability_nullable_result, true)
 FEATURE(memory_sanitizer,
 LangOpts.Sanitize.hasOneOf(SanitizerKind::Memory |
diff --git a/clang/lib/AST/Type.cpp b/clang/lib/AST/Type.cpp
index 78dcd3f4007a5a..b8a8ccfe9b0673 100644
--- a/clang/lib/AST/Type.cpp
+++ b/clang/lib/AST/Type.cpp
@@ -44,6 +44,7 @@
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/FoldingSet.h"
 #include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringSwitch.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/MathExtras.h"
@@ -4524,6 +4525,26 @@ std::optional Type::getNullability() 
const {
   return std::nullopt;
 }
 
+// Smart pointers are well-known stdlib types or marked with [[gsl::Pointer]].
+static bool classCanHaveNullability(CXXRecordDecl *CRD) {
+  if (!CRD)
+return false;
+  if (CRD->hasAttr())
+return true;
+  if (auto *CTSD = llvm::dyn_cast(CRD))
+if (CTSD->getSpecializedTemplate()
+->getTemplatedDecl()
+->hasAttr())
+  return true;
+  if (CRD->isInStdNamespace())
+if (auto *II = CRD->getIdentifier())
+  return llvm::StringSwitch(II->getName())
+  .Cases("auto_ptr", "inout_ptr_t", "out_ptr_t", "shared_ptr",
+ "unique_ptr", true)
+  .Default(false);
+  return false;
+}
+
 bool Type::canHaveNullability(bool ResultIfUnknown) const {
   QualType type = getCanonicalTypeInternal();
 
@@ -4556,16 +4577,15 @@ bool Type::canHaveNullability(bool ResultIfUnknown) 
const {
   case Type::Auto:
 return ResultIfUnknown;
 
-  // Dependent template specializations can instantiate to pointer
-  // types unless they're known to be specializations of a class
-  // template.
+  // Dependent template specializations could instantiate to pointer types.
   case Type::TemplateSpecialization:
-if (TemplateDecl *templateDecl
-  = cast(type.getTypePtr())
-  

[clang-tools-extra] [clang-tidy] Unsafe CRTP check (PR #82403)

2024-02-22 Thread via cfe-commits

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


[clang-tools-extra] [clang-tidy] Unsafe CRTP check (PR #82403)

2024-02-22 Thread via cfe-commits


@@ -0,0 +1,62 @@
+.. title:: clang-tidy - bugprone-unsafe-crtp
+
+bugprone-unsafe-crtp
+
+
+Finds CRTP used in an error-prone way.
+
+If the constructor of a class intended to be used in a CRTP is public, then
+it allows users to construct that class on its own.
+
+Example:
+
+.. code-block:: c++
+
+  template  class CRTP {
+  public:
+CRTP() = default;
+  };
+
+  class Good : CRTP {};
+  Good GoodInstance;
+
+  CRTP BadInstance;
+
+If the constructor is protected, the possibility of an accidental instantiation
+is prevented, however it can fade an error, when a different class is used as
+the template parameter instead of the derived one.
+
+Example:
+
+.. code-block:: c++
+
+  template  class CRTP {
+  protected:
+CRTP() = default;
+  };
+
+  class Good : CRTP {};
+  Good GoodInstance;
+
+  class Bad : CRTP {};
+  Bad BadInstance;
+
+To ensure that no accidental instantiation happens, the best practice is to 
make
+the constructor private and declare the derived class as friend.
+
+Example:
+
+.. code-block:: c++
+
+  template  class CRTP {
+CRTP() = default;
+friend T;
+  };
+
+  class Good : CRTP {};
+  Good GoodInstance;
+
+  class Bad : CRTP {};
+  Bad CompileTimeError;
+
+  CRTP AlsoCompileTimeError;

isuckatcs wrote:

If the constructor is protected as in your example, the following will also 
compile, which is not desired.
```c++
struct Decl {};

struct Stmt : ASTNode {
  protected:
Stmt() : ASTNode() {  }
};
```
This is exactly the kind of usage, this check wants to catch. 

Also note that with the suggested fix, your example still compiles.
```c++
template 
struct ASTNode {
  private:
ASTNode() {  }
friend NodeFamily;
};

struct Stmt : ASTNode {
  protected:
Stmt() : ASTNode() {  }
};

struct IfStmt : Stmt {
  IfStmt() : Stmt() {  }
};
```

`IfStmt` calls the constructor of `Stmt`, and not the constructor of 
`ASTNode<>`. The latter constructor is called by `Stmt`, which has access to it 
either way.

For the record, AFAIK the CRTP is supposed to describe `has a` relationships 
and not `is a` relationships, so making ASTNode a CRTP might not be an ideal 
design choice. 

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


[clang-tools-extra] [clang-tidy] Unsafe CRTP check (PR #82403)

2024-02-22 Thread via cfe-commits


@@ -0,0 +1,232 @@
+// RUN: %check_clang_tidy %s bugprone-unsafe-crtp %t
+
+namespace class_implicit_ctor {
+template 
+class CRTP {};
+// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: the implicit default constructor 
of the CRTP is publicly accessible [bugprone-unsafe-crtp]
+// CHECK-MESSAGES: :[[@LINE-2]]:7: note: consider making it private
+// CHECK-FIXES: CRTP() = default;
+
+class A : CRTP {};
+} // namespace class_implicit_ctor
+
+namespace class_uncostructible {
+template 
+class CRTP {
+// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: the CRTP cannot be constructed 
from the derived class [bugprone-unsafe-crtp]
+// CHECK-MESSAGES: :[[@LINE-2]]:7: note: consider declaring the derived class 
as friend
+// CHECK-FIXES: friend T;
+CRTP() = default;
+};
+
+class A : CRTP {};
+} // namespace class_uncostructible 
+
+namespace class_public_default_ctor {
+template 
+class CRTP {
+public:
+CRTP() = default;
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: public contructor allows the 
CRTP to be constructed as a regular template class [bugprone-unsafe-crtp]
+// CHECK-MESSAGES: :[[@LINE-2]]:5: note: consider making it private
+// CHECK-FIXES: private:{{[[:space:]]*}}CRTP() = 
default;{{[[:space:]]*}}public:
+};
+
+class A : CRTP {};
+} // namespace class_public_default_ctor
+
+namespace class_public_user_provided_ctor {
+template 
+class CRTP {
+public:
+CRTP(int) {}
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: public contructor allows the 
CRTP to be constructed as a regular template class [bugprone-unsafe-crtp]
+// CHECK-MESSAGES: :[[@LINE-2]]:5: note: consider making it private
+// CHECK-FIXES: private:{{[[:space:]]*}}CRTP(int) {}{{[[:space:]]*}}public:
+};
+
+class A : CRTP {};
+} // namespace class_public_user_provided_ctor
+
+namespace class_public_multiple_user_provided_ctors {
+template 
+class CRTP {
+public:
+CRTP(int) {}
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: public contructor allows the 
CRTP to be constructed as a regular template class [bugprone-unsafe-crtp]
+// CHECK-MESSAGES: :[[@LINE-2]]:5: note: consider making it private
+// CHECK-FIXES: private:{{[[:space:]]*}}CRTP(int) {}{{[[:space:]]*}}public:
+CRTP(float) {}
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: public contructor allows the 
CRTP to be constructed as a regular template class [bugprone-unsafe-crtp]
+// CHECK-MESSAGES: :[[@LINE-2]]:5: note: consider making it private
+// CHECK-FIXES: private:{{[[:space:]]*}}CRTP(float) 
{}{{[[:space:]]*}}public:
+};
+
+class A : CRTP {};
+} // namespace class_public_multiple_user_provided_ctors
+
+namespace class_protected_ctors {
+template 
+class CRTP {
+protected:
+CRTP(int) {}
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: protected contructor allows 
the CRTP to be inherited from as a regular template class [bugprone-unsafe-crtp]
+// CHECK-MESSAGES: :[[@LINE-2]]:5: note: consider making it private
+// CHECK-FIXES: private:{{[[:space:]]*}}CRTP(int) 
{}{{[[:space:]]*}}protected:
+CRTP() = default;
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: protected contructor allows 
the CRTP to be inherited from as a regular template class [bugprone-unsafe-crtp]
+// CHECK-MESSAGES: :[[@LINE-2]]:5: note: consider making it private
+// CHECK-FIXES: private:{{[[:space:]]*}}CRTP() = 
default;{{[[:space:]]*}}protected:
+CRTP(float) {}
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: protected contructor allows 
the CRTP to be inherited from as a regular template class [bugprone-unsafe-crtp]
+// CHECK-MESSAGES: :[[@LINE-2]]:5: note: consider making it private
+// CHECK-FIXES: private:{{[[:space:]]*}}CRTP(float) 
{}{{[[:space:]]*}}protected:
+};
+
+class A : CRTP {};
+} // namespace class_protected_ctors
+
+namespace struct_implicit_ctor {
+template 
+struct CRTP {};
+// CHECK-MESSAGES: :[[@LINE-1]]:8: warning: the implicit default constructor 
of the CRTP is publicly accessible [bugprone-unsafe-crtp]
+// CHECK-MESSAGES: :[[@LINE-2]]:8: note: consider making it private
+// CHECK-FIXES: private:{{[[:space:]]*}}CRTP() = 
default;{{[[:space:]]*}}public:
+
+class A : CRTP {};
+} // namespace struct_implicit_ctor
+
+namespace struct_default_ctor {
+template 
+struct CRTP {
+CRTP() = default;
+// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: public contructor allows the 
CRTP to be constructed as a regular template class [bugprone-unsafe-crtp]
+// CHECK-MESSAGES: :[[@LINE-2]]:5: note: consider making it private
+// CHECK-FIXES: private:{{[[:space:]]*}}CRTP() = 
default;{{[[:space:]]*}}public:
+};
+
+class A : CRTP {};
+} // namespace struct_default_ctor
+
+namespace same_class_multiple_crtps {
+template 
+struct CRTP {};
+// CHECK-MESSAGES: :[[@LINE-1]]:8: warning: the implicit default constructor 
of the CRTP is publicly accessible [bugprone-unsafe-crtp]
+// CHECK-MESSAGES: :[[@LINE-2]]:8: note: consider making it private
+// CHECK-FIXES: private:{{[[:space:]]*}}CRTP() = 

[clang] [clang][nullability] allow _Nonnull etc on gsl::Pointer types (PR #82705)

2024-02-22 Thread Sam McCall via cfe-commits

https://github.com/sam-mccall updated 
https://github.com/llvm/llvm-project/pull/82705

>From 090c0b01d1b02fd68c15971a1f3d9548aba24670 Mon Sep 17 00:00:00 2001
From: Sam McCall 
Date: Thu, 22 Feb 2024 16:00:44 +0100
Subject: [PATCH] [clang][nullability] allow _Nonnull etc on gsl::Pointer types

This enables external nullability checkers to make use of these
annotations on smart pointer types.

Existing static warnings for raw pointers are extended to smart pointers:

- nullptr used as return value or argument for non-null functions
  (`-Wnonnull`)
- assigning or initializing nonnull variables with nullable values
  (`-Wnullable-to-nonnull-conversion`)

It doesn't implicitly add these attributes based on the assume_nonnull
pragma, nor warn on missing attributes where the pragma would apply them.
I'm not confident that the pragma's current behavior will work well for
C++ (where type-based metaprogramming is much more common than C/ObjC).
We'd like to revisit this once we have more implementation experience.

UBSan's `-fsanitize=nullability` will not check smart-pointer types.
It can be made to do so by synthesizing calls to `operator bool`, but
that's left for future work.
---
 clang/include/clang/Basic/AttrDocs.td |  4 +++
 clang/lib/AST/Type.cpp| 43 ++--
 clang/lib/CodeGen/CGCall.cpp  |  3 +-
 clang/lib/CodeGen/CodeGenFunction.cpp |  3 +-
 clang/lib/Sema/SemaChecking.cpp   |  9 +
 clang/lib/Sema/SemaInit.cpp   |  5 +++
 clang/lib/Sema/SemaOverload.cpp   |  7 
 clang/lib/Sema/SemaType.cpp   | 18 +++---
 clang/test/SemaCXX/nullability.cpp| 48 +--
 9 files changed, 122 insertions(+), 18 deletions(-)

diff --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index b96fbddd51154c..28f201830fe56f 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -4096,6 +4096,10 @@ non-underscored keywords. For example:
   @property (assign, nullable) NSView *superview;
   @property (readonly, nonnull) NSArray *subviews;
 @end
+
+As well as built-in pointer types, ithe nullability attributes can be attached
+to the standard C++ pointer types ``std::unique_ptr`` and ``std::shared_ptr``,
+as well as C++ classes marked with the ``gsl::Pointer`` attribute.
   }];
 }
 
diff --git a/clang/lib/AST/Type.cpp b/clang/lib/AST/Type.cpp
index 78dcd3f4007a5a..b8a8ccfe9b0673 100644
--- a/clang/lib/AST/Type.cpp
+++ b/clang/lib/AST/Type.cpp
@@ -44,6 +44,7 @@
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/FoldingSet.h"
 #include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringSwitch.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/MathExtras.h"
@@ -4524,6 +4525,26 @@ std::optional Type::getNullability() 
const {
   return std::nullopt;
 }
 
+// Smart pointers are well-known stdlib types or marked with [[gsl::Pointer]].
+static bool classCanHaveNullability(CXXRecordDecl *CRD) {
+  if (!CRD)
+return false;
+  if (CRD->hasAttr())
+return true;
+  if (auto *CTSD = llvm::dyn_cast(CRD))
+if (CTSD->getSpecializedTemplate()
+->getTemplatedDecl()
+->hasAttr())
+  return true;
+  if (CRD->isInStdNamespace())
+if (auto *II = CRD->getIdentifier())
+  return llvm::StringSwitch(II->getName())
+  .Cases("auto_ptr", "inout_ptr_t", "out_ptr_t", "shared_ptr",
+ "unique_ptr", true)
+  .Default(false);
+  return false;
+}
+
 bool Type::canHaveNullability(bool ResultIfUnknown) const {
   QualType type = getCanonicalTypeInternal();
 
@@ -4556,16 +4577,15 @@ bool Type::canHaveNullability(bool ResultIfUnknown) 
const {
   case Type::Auto:
 return ResultIfUnknown;
 
-  // Dependent template specializations can instantiate to pointer
-  // types unless they're known to be specializations of a class
-  // template.
+  // Dependent template specializations could instantiate to pointer types.
   case Type::TemplateSpecialization:
-if (TemplateDecl *templateDecl
-  = cast(type.getTypePtr())
-  ->getTemplateName().getAsTemplateDecl()) {
-  if (isa(templateDecl))
-return false;
-}
+// If it's a known class template, we can already check if it's a pointer.
+if (TemplateDecl *templateDecl =
+cast(type.getTypePtr())
+->getTemplateName()
+.getAsTemplateDecl())
+  if (auto *CTD = dyn_cast(templateDecl))
+return classCanHaveNullability(CTD->getTemplatedDecl());
 return ResultIfUnknown;
 
   case Type::Builtin:
@@ -4622,6 +4642,10 @@ bool Type::canHaveNullability(bool ResultIfUnknown) 
const {
 }
 llvm_unreachable("unknown builtin type");
 
+  case Type::Record:
+return classCanHaveNullability(
+cast(type)->getAsCXXRecordDecl());
+
   // Non-pointer types.
   case Type::Complex:
   case Type::LValueReference:
@@ 

[clang] [clang][nullability] allow _Nonnull etc on gsl::Pointer types (PR #82705)

2024-02-22 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 770fd3856660fea6cbaa78d9cb1f03cc92611783 
1a56ae6f27778750b8c7761e2630476833a061b8 -- clang/lib/AST/Type.cpp 
clang/lib/CodeGen/CGCall.cpp clang/lib/CodeGen/CodeGenFunction.cpp 
clang/lib/Sema/SemaChecking.cpp clang/lib/Sema/SemaInit.cpp 
clang/lib/Sema/SemaOverload.cpp clang/lib/Sema/SemaType.cpp 
clang/test/SemaCXX/nullability.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index eea63c2e57..45278fd53e 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -7052,8 +7052,8 @@ PerformConstructorInitialization(Sema ,
 
   // A smart pointer constructed from a null pointer is almost certainly null.
   if (NumArgs == 1 && !Kind.isExplicitCast())
-S.diagnoseNullableToNonnullConversion(Entity.getType(), 
Args.front()->getType(),
-  Kind.getLocation());
+S.diagnoseNullableToNonnullConversion(
+Entity.getType(), Args.front()->getType(), Kind.getLocation());
 
   // Determine the arguments required to actually perform the constructor
   // call.

``




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


[clang] [compiler-rt] [AArch64] Implement __builtin_cpu_supports, compiler-rt tests. (PR #82378)

2024-02-22 Thread Pavel Iliin via cfe-commits

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


[clang] 568baba - [AArch64] Implement __builtin_cpu_supports, compiler-rt tests. (#82378)

2024-02-22 Thread via cfe-commits

Author: Pavel Iliin
Date: 2024-02-22T23:33:54Z
New Revision: 568babab7e769a7793c28aee4f889898bf0bd8ba

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

LOG: [AArch64] Implement __builtin_cpu_supports, compiler-rt tests. (#82378)

The patch complements https://github.com/llvm/llvm-project/pull/68919
and adds AArch64 support for builtin
`__builtin_cpu_supports("feature1+...+featureN")`
which return true if all specified CPU features in argument are
detected. Also compiler-rt aarch64 native run tests for features
detection mechanism were added and 'cpu_model' check was fixed after its
refactor merged https://github.com/llvm/llvm-project/pull/75635 Original
RFC was https://reviews.llvm.org/D153153

Added: 
clang/test/CodeGen/aarch64-cpu-supports-target.c
clang/test/CodeGen/aarch64-cpu-supports.c
clang/test/Sema/aarch64-cpu-supports.c
compiler-rt/test/builtins/Unit/aarch64_cpu_features_test.c

Modified: 
clang/lib/Basic/Targets/AArch64.cpp
clang/lib/Basic/Targets/AArch64.h
clang/lib/CodeGen/CGBuiltin.cpp
clang/lib/CodeGen/CodeGenFunction.h
clang/test/Preprocessor/has_builtin_cpuid.c
clang/test/Sema/builtin-cpu-supports.c
compiler-rt/test/builtins/Unit/cpu_model_test.c

Removed: 




diff  --git a/clang/lib/Basic/Targets/AArch64.cpp 
b/clang/lib/Basic/Targets/AArch64.cpp
index 68032961451d90..5abb060073c517 100644
--- a/clang/lib/Basic/Targets/AArch64.cpp
+++ b/clang/lib/Basic/Targets/AArch64.cpp
@@ -667,7 +667,13 @@ StringRef 
AArch64TargetInfo::getFeatureDependencies(StringRef Name) const {
 }
 
 bool AArch64TargetInfo::validateCpuSupports(StringRef FeatureStr) const {
-  return llvm::AArch64::parseArchExtension(FeatureStr).has_value();
+  // CPU features might be separated by '+', extract them and check
+  llvm::SmallVector Features;
+  FeatureStr.split(Features, "+");
+  for (auto  : Features)
+if (!llvm::AArch64::parseArchExtension(Feature.trim()).has_value())
+  return false;
+  return true;
 }
 
 bool AArch64TargetInfo::hasFeature(StringRef Feature) const {

diff  --git a/clang/lib/Basic/Targets/AArch64.h 
b/clang/lib/Basic/Targets/AArch64.h
index 26ee7fa1978256..c1ba156860a122 100644
--- a/clang/lib/Basic/Targets/AArch64.h
+++ b/clang/lib/Basic/Targets/AArch64.h
@@ -165,7 +165,7 @@ class LLVM_LIBRARY_VISIBILITY AArch64TargetInfo : public 
TargetInfo {
 DiagnosticsEngine ) override;
   ParsedTargetAttr parseTargetAttr(StringRef Str) const override;
   bool supportsTargetAttributeTune() const override { return true; }
-
+  bool supportsCpuSupports() const override { return true; }
   bool checkArithmeticFenceSupported() const override { return true; }
 
   bool hasBFloat16Type() const override;

diff  --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index d8b2115f1e5e3c..734eb5a035ca49 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -10638,6 +10638,9 @@ Value *CodeGenFunction::EmitAArch64BuiltinExpr(unsigned 
BuiltinID,
   BuiltinID <= clang::AArch64::LastSMEBuiltin)
 return EmitAArch64SMEBuiltinExpr(BuiltinID, E);
 
+  if (BuiltinID == Builtin::BI__builtin_cpu_supports)
+return EmitAArch64CpuSupports(E);
+
   unsigned HintID = static_cast(-1);
   switch (BuiltinID) {
   default: break;
@@ -14025,6 +14028,19 @@ Value *CodeGenFunction::EmitX86CpuInit() {
   return Builder.CreateCall(Func);
 }
 
+Value *CodeGenFunction::EmitAArch64CpuSupports(const CallExpr *E) {
+  const Expr *ArgExpr = E->getArg(0)->IgnoreParenCasts();
+  StringRef ArgStr = cast(ArgExpr)->getString();
+  llvm::SmallVector Features;
+  ArgStr.split(Features, "+");
+  for (auto  : Features) {
+Feature = Feature.trim();
+if (Feature != "default")
+  Features.push_back(Feature);
+  }
+  return EmitAArch64CpuSupports(Features);
+}
+
 llvm::Value *
 CodeGenFunction::EmitAArch64CpuSupports(ArrayRef FeaturesStrs) {
   uint64_t FeaturesMask = llvm::AArch64::getCpuSupportsMask(FeaturesStrs);

diff  --git a/clang/lib/CodeGen/CodeGenFunction.h 
b/clang/lib/CodeGen/CodeGenFunction.h
index caa6a327550baa..92ce0edeaf9e9c 100644
--- a/clang/lib/CodeGen/CodeGenFunction.h
+++ b/clang/lib/CodeGen/CodeGenFunction.h
@@ -5013,10 +5013,10 @@ class CodeGenFunction : public CodeGenTypeCache {
   llvm::Value *EmitAArch64CpuInit();
   llvm::Value *
   FormAArch64ResolverCondition(const MultiVersionResolverOption );
+  llvm::Value *EmitAArch64CpuSupports(const CallExpr *E);
   llvm::Value *EmitAArch64CpuSupports(ArrayRef FeatureStrs);
 };
 
-
 inline DominatingLLVMValue::saved_type
 DominatingLLVMValue::save(CodeGenFunction , llvm::Value *value) {
   if (!needsSaving(value)) return saved_type(value, false);

diff  --git a/clang/test/CodeGen/aarch64-cpu-supports-target.c 

[clang] [clang][nullability] allow _Nonnull etc on gsl::Pointer types (PR #82705)

2024-02-22 Thread Sam McCall via cfe-commits

https://github.com/sam-mccall created 
https://github.com/llvm/llvm-project/pull/82705

This enables external nullability checkers to make use of these
annotations on smart pointer types.

Existing static warnings for raw pointers are extended to smart pointers:

- nullptr used as return value or argument for non-null functions
  (`-Wnonnull`)
- assigning or initializing nonnull variables with nullable values
  (`-Wnullable-to-nonnull-conversion`)

It doesn't implicitly add these attributes based on the assume_nonnull
pragma, nor warn on missing attributes where the pragma would apply them.
I'm not confident that the pragma's current behavior will work well for
C++ (where type-based metaprogramming is much more common than C/ObjC).
We'd like to revisit this once we have more implementation experience.

UBSan's `-fsanitize=nullability` will not check smart-pointer types.
It can be made to do so by synthesizing calls to `operator bool`, but
that's left for future work.


>From 1a56ae6f27778750b8c7761e2630476833a061b8 Mon Sep 17 00:00:00 2001
From: Sam McCall 
Date: Thu, 22 Feb 2024 16:00:44 +0100
Subject: [PATCH] [clang][nullability] allow _Nonnull etc on gsl::Pointer types

This enables external nullability checkers to make use of these
annotations on smart pointer types.

Existing static warnings for raw pointers are extended to smart pointers:

- nullptr used as return value or argument for non-null functions
  (`-Wnonnull`)
- assigning or initializing nonnull variables with nullable values
  (`-Wnullable-to-nonnull-conversion`)

It doesn't implicitly add these attributes based on the assume_nonnull
pragma, nor warn on missing attributes where the pragma would apply them.
I'm not confident that the pragma's current behavior will work well for
C++ (where type-based metaprogramming is much more common than C/ObjC).
We'd like to revisit this once we have more implementation experience.

UBSan's `-fsanitize=nullability` will not check smart-pointer types.
It can be made to do so by synthesizing calls to `operator bool`, but
that's left for future work.
---
 clang/include/clang/Basic/AttrDocs.td |  4 +++
 clang/lib/AST/Type.cpp| 44 ++--
 clang/lib/CodeGen/CGCall.cpp  |  3 +-
 clang/lib/CodeGen/CodeGenFunction.cpp |  3 +-
 clang/lib/Sema/SemaChecking.cpp   |  9 +
 clang/lib/Sema/SemaInit.cpp   |  5 +++
 clang/lib/Sema/SemaOverload.cpp   |  7 
 clang/lib/Sema/SemaType.cpp   | 18 +++---
 clang/test/SemaCXX/nullability.cpp| 48 +--
 9 files changed, 123 insertions(+), 18 deletions(-)

diff --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index b96fbddd51154c..28f201830fe56f 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -4096,6 +4096,10 @@ non-underscored keywords. For example:
   @property (assign, nullable) NSView *superview;
   @property (readonly, nonnull) NSArray *subviews;
 @end
+
+As well as built-in pointer types, ithe nullability attributes can be attached
+to the standard C++ pointer types ``std::unique_ptr`` and ``std::shared_ptr``,
+as well as C++ classes marked with the ``gsl::Pointer`` attribute.
   }];
 }
 
diff --git a/clang/lib/AST/Type.cpp b/clang/lib/AST/Type.cpp
index 78dcd3f4007a5a..f65529e5c917f3 100644
--- a/clang/lib/AST/Type.cpp
+++ b/clang/lib/AST/Type.cpp
@@ -44,6 +44,7 @@
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/FoldingSet.h"
 #include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringSwitch.h"
 #include "llvm/Support/Casting.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/MathExtras.h"
@@ -4524,6 +4525,26 @@ std::optional Type::getNullability() 
const {
   return std::nullopt;
 }
 
+// Smart pointers are well-known stdlib types or marked with [[gsl::Pointer]].
+static bool classCanHaveNullability(CXXRecordDecl *CRD) {
+  if (!CRD)
+return false;
+  if (CRD->hasAttr())
+return true;
+  if (auto *CTSD = llvm::dyn_cast(CRD))
+if (CTSD->getSpecializedTemplate()
+->getTemplatedDecl()
+->hasAttr())
+  return true;
+  if (CRD->isInStdNamespace())
+if (auto *II = CRD->getIdentifier())
+  return llvm::StringSwitch(II->getName())
+  .Cases("auto_ptr", "inout_ptr_t", "out_ptr_t", "shared_ptr",
+ "unique_ptr", true)
+  .Default(false);
+  return false;
+}
+
 bool Type::canHaveNullability(bool ResultIfUnknown) const {
   QualType type = getCanonicalTypeInternal();
 
@@ -4556,16 +4577,16 @@ bool Type::canHaveNullability(bool ResultIfUnknown) 
const {
   case Type::Auto:
 return ResultIfUnknown;
 
-  // Dependent template specializations can instantiate to pointer
-  // types unless they're known to be specializations of a class
-  // template.
+  // Dependent template specializations could instantiate to pointer types.
   case Type::TemplateSpecialization:
-if (TemplateDecl 

[clang-tools-extra] [clang-tidy] Unsafe CRTP check (PR #82403)

2024-02-22 Thread via cfe-commits

https://github.com/isuckatcs updated 
https://github.com/llvm/llvm-project/pull/82403

>From a11b863a62f3e27d90e5b337b47d7f20e260d98b Mon Sep 17 00:00:00 2001
From: isuckatcs <65320245+isucka...@users.noreply.github.com>
Date: Fri, 16 Feb 2024 00:25:29 +0100
Subject: [PATCH 01/16] added new checker

---
 .../bugprone/BugproneTidyModule.cpp   |  3 +
 .../clang-tidy/bugprone/CMakeLists.txt|  1 +
 .../clang-tidy/bugprone/UnsafeCrtpCheck.cpp   | 92 +++
 .../clang-tidy/bugprone/UnsafeCrtpCheck.h | 30 ++
 clang-tools-extra/docs/ReleaseNotes.rst   |  5 +
 .../checks/bugprone/unsafe-crtp.rst   |  6 ++
 .../docs/clang-tidy/checks/list.rst   |  1 +
 .../checkers/bugprone/unsafe-crtp.cpp | 14 +++
 8 files changed, 152 insertions(+)
 create mode 100644 clang-tools-extra/clang-tidy/bugprone/UnsafeCrtpCheck.cpp
 create mode 100644 clang-tools-extra/clang-tidy/bugprone/UnsafeCrtpCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/bugprone/unsafe-crtp.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/unsafe-crtp.cpp

diff --git a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp 
b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
index a8a23b045f80bb..b7b4d85a86cce2 100644
--- a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
@@ -83,6 +83,7 @@
 #include "UnhandledExceptionAtNewCheck.h"
 #include "UnhandledSelfAssignmentCheck.h"
 #include "UniquePtrArrayMismatchCheck.h"
+#include "UnsafeCrtpCheck.h"
 #include "UnsafeFunctionsCheck.h"
 #include "UnusedLocalNonTrivialVariableCheck.h"
 #include "UnusedRaiiCheck.h"
@@ -237,6 +238,8 @@ class BugproneModule : public ClangTidyModule {
 "bugprone-unhandled-exception-at-new");
 CheckFactories.registerCheck(
 "bugprone-unique-ptr-array-mismatch");
+CheckFactories.registerCheck(
+"bugprone-unsafe-crtp");
 CheckFactories.registerCheck(
 "bugprone-unsafe-functions");
 CheckFactories.registerCheck(
diff --git a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
index 1cd6fb207d7625..956b12ad1cdecd 100644
--- a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
@@ -79,6 +79,7 @@ add_clang_library(clangTidyBugproneModule
   UnhandledExceptionAtNewCheck.cpp
   UnhandledSelfAssignmentCheck.cpp
   UniquePtrArrayMismatchCheck.cpp
+  UnsafeCrtpCheck.cpp
   UnsafeFunctionsCheck.cpp
   UnusedLocalNonTrivialVariableCheck.cpp
   UnusedRaiiCheck.cpp
diff --git a/clang-tools-extra/clang-tidy/bugprone/UnsafeCrtpCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/UnsafeCrtpCheck.cpp
new file mode 100644
index 00..eb0f6187e58b2e
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/bugprone/UnsafeCrtpCheck.cpp
@@ -0,0 +1,92 @@
+//===--- UnsafeCrtpCheck.cpp - clang-tidy 
-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "UnsafeCrtpCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+namespace {
+// Finds a node if it's already a bound node.
+AST_MATCHER_P(CXXRecordDecl, isBoundNode, std::string, ID) {
+  return Builder->removeBindings(
+  [&](const ast_matchers::internal::BoundNodesMap ) {
+const auto *BoundRecord = Nodes.getNodeAs(ID);
+return BoundRecord != 
+  });
+}
+} // namespace
+
+void UnsafeCrtpCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  cxxRecordDecl(
+  decl().bind("record"),
+  hasAnyBase(hasType(
+  classTemplateSpecializationDecl(
+  hasAnyTemplateArgument(refersToType(recordType(
+  hasDeclaration(cxxRecordDecl(isBoundNode("record")))
+  .bind("crtp",
+  this);
+}
+
+void UnsafeCrtpCheck::check(const MatchFinder::MatchResult ) {
+  const auto *MatchedCRTP = Result.Nodes.getNodeAs("crtp");
+
+  MatchedCRTP->dump();
+
+  for (auto & : MatchedCRTP->ctors()) {
+if (ctor->getAccess() != AS_private) {
+  ctor->dump();
+};
+  }
+
+  return;
+
+  // if (!MatchedDecl->hasDefinition())
+  //   return;
+
+  // for (auto & : MatchedDecl->bases()) {
+  //   const auto *TemplateSpecDecl =
+  //   llvm::dyn_cast_if_present(
+  //   Base.getType()->getAsTagDecl());
+
+  //   if (!TemplateSpecDecl)
+  // continue;
+
+  //   TemplateSpecDecl->dump();
+
+  //   for (auto & : TemplateSpecDecl->getTemplateArgs().asArray())
+  //   {
+  // if 

[clang] [compiler-rt] [asan][windows] Eliminate the static asan runtime on windows (PR #81677)

2024-02-22 Thread Charlie Barto via cfe-commits

barcharcraz wrote:

The buildkite failure is just windows defender freaking out about one of 
cmake's test exes. Presumably it'll get sorted out next time it runs.

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


[clang] e8740d4 - [Clang] Fix missing architecture on CUDA test

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

Author: Joseph Huber
Date: 2024-02-22T16:59:56-06:00
New Revision: e8740d4eb1c88e968b155f73ac745f80b4681589

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

LOG: [Clang] Fix missing architecture on CUDA test

Summary:
Sorry about the churn here, my local git tree got corrupted so a few
broken tests slipped by while trying to fix it.

Added: 


Modified: 
clang/test/Driver/cuda-cross-compiling.c

Removed: 




diff  --git a/clang/test/Driver/cuda-cross-compiling.c 
b/clang/test/Driver/cuda-cross-compiling.c
index 25058358b63a80..086840accebe7f 100644
--- a/clang/test/Driver/cuda-cross-compiling.c
+++ b/clang/test/Driver/cuda-cross-compiling.c
@@ -71,7 +71,7 @@
 //
 // Test passing arguments directly to nvlink.
 //
-// RUN: %clang -target nvptx64-nvidia-cuda -Wl,-v -Wl,a,b -### %s 2>&1 \
+// RUN: %clang -target nvptx64-nvidia-cuda -Wl,-v -Wl,a,b -march=sm_52 -### %s 
2>&1 \
 // RUN:   | FileCheck -check-prefix=LINKER-ARGS %s
 
 // LINKER-ARGS: nvlink{{.*}}"-v"{{.*}}"a" "b"
@@ -87,4 +87,4 @@
 // RUN: %clang -target nvptx64-nvidia-cuda -flto -c %s -### 2>&1 \
 // RUN:   | FileCheck -check-prefix=GENERIC %s
 
-// GENERIC-NOT: -cc1" "-triple" "nvptx64-nvidia-cuda" {{.*}} "-target-cpu"
\ No newline at end of file
+// GENERIC-NOT: -cc1" "-triple" "nvptx64-nvidia-cuda" {{.*}} "-target-cpu"



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


[clang] e3cab8f - [LinkerWrapper] Fix test after permitting NVPTX linker arguments

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

Author: Joseph Huber
Date: 2024-02-22T16:54:03-06:00
New Revision: e3cab8fe82eb71fadb251d11fec7df9fa0dbdd27

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

LOG: [LinkerWrapper] Fix test after permitting NVPTX linker arguments

Summary:
Forgot to change this after a previous patch altered its behaviour.

Added: 


Modified: 
clang/test/Driver/linker-wrapper.c

Removed: 




diff  --git a/clang/test/Driver/linker-wrapper.c 
b/clang/test/Driver/linker-wrapper.c
index 7fd46778ac9102..83df2b84adefed 100644
--- a/clang/test/Driver/linker-wrapper.c
+++ b/clang/test/Driver/linker-wrapper.c
@@ -21,7 +21,7 @@ __attribute__((visibility("protected"), used)) int x;
 // RUN: clang-linker-wrapper --host-triple=x86_64-unknown-linux-gnu --dry-run \
 // RUN:   --linker-path=/usr/bin/ld -- %t.o -o a.out 2>&1 | FileCheck %s 
--check-prefix=NVPTX-LINK
 
-// NVPTX-LINK: clang{{.*}} -o {{.*}}.img --target=nvptx64-nvidia-cuda 
-march=sm_70 -O2 -Wl,--no-undefined {{.*}}.o {{.*}}.o
+// NVPTX-LINK: clang{{.*}} -o {{.*}}.img --target=nvptx64-nvidia-cuda 
-march=sm_70 -O2 {{.*}}.o {{.*}}.o
 
 // RUN: clang-offload-packager -o %t.out \
 // RUN:   
--image=file=%t.elf.o,kind=openmp,triple=nvptx64-nvidia-cuda,arch=sm_70 \
@@ -30,7 +30,7 @@ __attribute__((visibility("protected"), used)) int x;
 // RUN: clang-linker-wrapper --host-triple=x86_64-unknown-linux-gnu --dry-run 
--device-debug -O0 \
 // RUN:   --linker-path=/usr/bin/ld -- %t.o -o a.out 2>&1 | FileCheck %s 
--check-prefix=NVPTX-LINK-DEBUG
 
-// NVPTX-LINK-DEBUG: clang{{.*}} -o {{.*}}.img --target=nvptx64-nvidia-cuda 
-march=sm_70 -O2 -Wl,--no-undefined {{.*}}.o {{.*}}.o -g 
+// NVPTX-LINK-DEBUG: clang{{.*}} -o {{.*}}.img --target=nvptx64-nvidia-cuda 
-march=sm_70 -O2 {{.*}}.o {{.*}}.o -g 
 
 // RUN: clang-offload-packager -o %t.out \
 // RUN:   
--image=file=%t.elf.o,kind=openmp,triple=amdgcn-amd-amdhsa,arch=gfx908 \



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


[clang] [Clang][NVPTX] Allow passing arguments to the linker while standalone (PR #73030)

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

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


[clang] d5a15f3 - [Clang][NVPTX] Allow passing arguments to the linker while standalone (#73030)

2024-02-22 Thread via cfe-commits

Author: Joseph Huber
Date: 2024-02-22T16:27:53-06:00
New Revision: d5a15f3116f8c3ec32df1f13a2fc521a98b03d96

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

LOG: [Clang][NVPTX] Allow passing arguments to the linker while standalone 
(#73030)

Summary:
We support standalone compilation for the NVPTX architecture using
'nvlink' as our linker. Because of the special handling required to
transform input files to cubins, as nvlink expects for some reason, we
didn't use the standard AddLinkerInput method. However, this also meant
that we weren't forwarding options passed with -Wl to the linker. Add
this support in for the standalone toolchain path.

Revived from https://reviews.llvm.org/D149978

Added: 


Modified: 
clang/lib/Driver/ToolChains/Cuda.cpp
clang/test/Driver/cuda-cross-compiling.c
clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Cuda.cpp 
b/clang/lib/Driver/ToolChains/Cuda.cpp
index ed5924c3b73b55..94d4982d102bbd 100644
--- a/clang/lib/Driver/ToolChains/Cuda.cpp
+++ b/clang/lib/Driver/ToolChains/Cuda.cpp
@@ -623,35 +623,34 @@ void NVPTX::Linker::ConstructJob(Compilation , const 
JobAction ,
   continue;
 }
 
-// Currently, we only pass the input files to the linker, we do not pass
-// any libraries that may be valid only for the host.
-if (!II.isFilename())
-  continue;
-
 // The 'nvlink' application performs RDC-mode linking when given a '.o'
 // file and device linking when given a '.cubin' file. We always want to
 // perform device linking, so just rename any '.o' files.
 // FIXME: This should hopefully be removed if NVIDIA updates their tooling.
-auto InputFile = getToolChain().getInputFilename(II);
-if (llvm::sys::path::extension(InputFile) != ".cubin") {
-  // If there are no actions above this one then this is direct input and 
we
-  // can copy it. Otherwise the input is internal so a `.cubin` file should
-  // exist.
-  if (II.getAction() && II.getAction()->getInputs().size() == 0) {
-const char *CubinF =
-Args.MakeArgString(getToolChain().getDriver().GetTemporaryPath(
-llvm::sys::path::stem(InputFile), "cubin"));
-if (llvm::sys::fs::copy_file(InputFile, C.addTempFile(CubinF)))
-  continue;
+if (II.isFilename()) {
+  auto InputFile = getToolChain().getInputFilename(II);
+  if (llvm::sys::path::extension(InputFile) != ".cubin") {
+// If there are no actions above this one then this is direct input and
+// we can copy it. Otherwise the input is internal so a `.cubin` file
+// should exist.
+if (II.getAction() && II.getAction()->getInputs().size() == 0) {
+  const char *CubinF =
+  Args.MakeArgString(getToolChain().getDriver().GetTemporaryPath(
+  llvm::sys::path::stem(InputFile), "cubin"));
+  if (llvm::sys::fs::copy_file(InputFile, C.addTempFile(CubinF)))
+continue;
 
-CmdArgs.push_back(CubinF);
+  CmdArgs.push_back(CubinF);
+} else {
+  SmallString<256> Filename(InputFile);
+  llvm::sys::path::replace_extension(Filename, "cubin");
+  CmdArgs.push_back(Args.MakeArgString(Filename));
+}
   } else {
-SmallString<256> Filename(InputFile);
-llvm::sys::path::replace_extension(Filename, "cubin");
-CmdArgs.push_back(Args.MakeArgString(Filename));
+CmdArgs.push_back(Args.MakeArgString(InputFile));
   }
-} else {
-  CmdArgs.push_back(Args.MakeArgString(InputFile));
+} else if (!II.isNothing()) {
+  II.getInputArg().renderAsInput(Args, CmdArgs);
 }
   }
 

diff  --git a/clang/test/Driver/cuda-cross-compiling.c 
b/clang/test/Driver/cuda-cross-compiling.c
index 6c9e2cac736b79..25058358b63a80 100644
--- a/clang/test/Driver/cuda-cross-compiling.c
+++ b/clang/test/Driver/cuda-cross-compiling.c
@@ -69,6 +69,13 @@
 // LOWERING: -cc1" "-triple" "nvptx64-nvidia-cuda" {{.*}} "-mllvm" 
"--nvptx-lower-global-ctor-dtor"
 
 //
+// Test passing arguments directly to nvlink.
+//
+// RUN: %clang -target nvptx64-nvidia-cuda -Wl,-v -Wl,a,b -### %s 2>&1 \
+// RUN:   | FileCheck -check-prefix=LINKER-ARGS %s
+
+// LINKER-ARGS: nvlink{{.*}}"-v"{{.*}}"a" "b"
+
 // Tests for handling a missing architecture.
 //
 // RUN: not %clang -target nvptx64-nvidia-cuda %s -### 2>&1 \
@@ -80,4 +87,4 @@
 // RUN: %clang -target nvptx64-nvidia-cuda -flto -c %s -### 2>&1 \
 // RUN:   | FileCheck -check-prefix=GENERIC %s
 
-// GENERIC-NOT: -cc1" "-triple" "nvptx64-nvidia-cuda" {{.*}} "-target-cpu"
+// GENERIC-NOT: -cc1" "-triple" "nvptx64-nvidia-cuda" {{.*}} "-target-cpu"
\ No newline at end of file

diff  --git 

[clang] [clang][driver] Allow unaligned access on ARMv7 and higher by default (PR #82400)

2024-02-22 Thread Paul Kirth via cfe-commits

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


[clang] e314622 - [clang][driver] Allow unaligned access on ARMv7 and higher by default (#82400)

2024-02-22 Thread via cfe-commits

Author: Paul Kirth
Date: 2024-02-22T14:26:11-08:00
New Revision: e314622f204a01ffeda59cbe046dd403b01f8b74

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

LOG: [clang][driver] Allow unaligned access on ARMv7 and higher by default 
(#82400)

ARM's Clang and GCC embedded compilers default to allowing unaligned
access for ARMv7+. This patch changes the Clang driver default to match.
Users can opt out with `-mno-unaligned-access`.

Fixes #59560

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Driver/ToolChains/Arch/ARM.cpp
clang/test/Driver/arm-alignment.c

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 74bb9a07f0b13f..19cc5b77564316 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -302,6 +302,17 @@ X86 Support
 Arm and AArch64 Support
 ^^^
 
+- ARMv7+ targets now default to allowing unaligned access, except Armv6-M, and
+  Armv8-M without the Main Extension. Baremetal targets should check that the
+  new default will work with their system configurations, since it requires
+  that SCTLR.A is 0, SCTLR.U is 1, and that the memory in question is
+  configured as "normal" memory. This brings Clang in-line with the default
+  settings for GCC and Arm Compiler. Aside from making Clang align with other
+  compilers, changing the default brings major performance and code size
+  improvements for most targets. We have not changed the default behavior for
+  ARMv6, but may revisit that decision in the future. Users can restore the old
+  behavior with -m[no-]unaligned-access.
+
 Android Support
 ^^^
 

diff  --git a/clang/lib/Driver/ToolChains/Arch/ARM.cpp 
b/clang/lib/Driver/ToolChains/Arch/ARM.cpp
index e6ee2f88a84edf..ba158b92bb44ba 100644
--- a/clang/lib/Driver/ToolChains/Arch/ARM.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/ARM.cpp
@@ -890,25 +890,25 @@ llvm::ARM::FPUKind arm::getARMTargetFeatures(const Driver 
,
 // SCTLR.U bit, which is architecture-specific. We assume ARMv6
 // Darwin and NetBSD targets support unaligned accesses, and others don't.
 //
-// ARMv7 always has SCTLR.U set to 1, but it has a new SCTLR.A bit
-// which raises an alignment fault on unaligned accesses. Linux
-// defaults this bit to 0 and handles it as a system-wide (not
-// per-process) setting. It is therefore safe to assume that ARMv7+
-// Linux targets support unaligned accesses. The same goes for NaCl
-// and Windows.
+// ARMv7 always has SCTLR.U set to 1, but it has a new SCTLR.A bit which
+// raises an alignment fault on unaligned accesses. Assume ARMv7+ supports
+// unaligned accesses, except ARMv6-M, and ARMv8-M without the Main
+// Extension. This aligns with the default behavior of ARM's downstream
+// versions of GCC and Clang.
 //
-// The above behavior is consistent with GCC.
+// Users can change the default behavior via -m[no-]unaliged-access.
 int VersionNum = getARMSubArchVersionNumber(Triple);
 if (Triple.isOSDarwin() || Triple.isOSNetBSD()) {
   if (VersionNum < 6 ||
   Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
 Features.push_back("+strict-align");
-} else if (Triple.isOSLinux() || Triple.isOSNaCl() ||
-   Triple.isOSWindows()) {
-  if (VersionNum < 7)
-Features.push_back("+strict-align");
-} else
+} else if (VersionNum < 7 ||
+   Triple.getSubArch() ==
+   llvm::Triple::SubArchType::ARMSubArch_v6m ||
+   Triple.getSubArch() ==
+   llvm::Triple::SubArchType::ARMSubArch_v8m_baseline) {
   Features.push_back("+strict-align");
+}
   }
 
   // llvm does not support reserving registers in general. There is support

diff  --git a/clang/test/Driver/arm-alignment.c 
b/clang/test/Driver/arm-alignment.c
index 9177b625729b85..8c915477af9aff 100644
--- a/clang/test/Driver/arm-alignment.c
+++ b/clang/test/Driver/arm-alignment.c
@@ -22,6 +22,21 @@
 // RUN: %clang -target armv7-windows -### %s 2> %t
 // RUN: FileCheck --check-prefix=CHECK-UNALIGNED-ARM < %t %s
 
+// RUN: %clang --target=armv6 -### %s 2> %t
+// RUN: FileCheck --check-prefix=CHECK-ALIGNED-ARM < %t %s
+
+// RUN: %clang --target=armv7 -### %s 2> %t
+// RUN: FileCheck --check-prefix=CHECK-UNALIGNED-ARM < %t %s
+
+// RUN: %clang -target thumbv6m-none-gnueabi -mcpu=cortex-m0 -### %s 2> %t
+// RUN: FileCheck --check-prefix CHECK-ALIGNED-ARM <%t %s
+
+// RUN: %clang -target thumb-none-gnueabi -mcpu=cortex-m0 -### %s 2> %t
+// RUN: FileCheck --check-prefix CHECK-ALIGNED-ARM <%t %s
+
+// RUN: %clang -target thumbv8m.base-none-gnueabi -### %s 2> %t
+// RUN: FileCheck --check-prefix CHECK-ALIGNED-ARM <%t %s
+
 

[clang] [Clang][NVPTX] Allow passing arguments to the linker while standalone (PR #73030)

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

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

>From ee43e8f9ae90bcd70d46b17cfecb854711a4b1ce Mon Sep 17 00:00:00 2001
From: Joseph Huber 
Date: Tue, 21 Nov 2023 13:45:10 -0600
Subject: [PATCH] [Clang][NVPTX] Allow passing arguments to the linker while
 standalone

Summary:
We support standalone compilation for the NVPTX architecture using
'nvlink' as our linker. Because of the special handling required to
transform input files to cubins, as nvlink expects for some reason, we
didn't use the standard AddLinkerInput method. However, this also meant
that we weren't forwarding options passed with -Wl to the linker. Add
this support in for the standalone toolchain path.

Revived from https://reviews.llvm.org/D149978
---
 clang/lib/Driver/ToolChains/Cuda.cpp  | 43 +--
 clang/test/Driver/cuda-cross-compiling.c  |  8 
 .../ClangLinkerWrapper.cpp|  4 +-
 3 files changed, 32 insertions(+), 23 deletions(-)

diff --git a/clang/lib/Driver/ToolChains/Cuda.cpp 
b/clang/lib/Driver/ToolChains/Cuda.cpp
index e95ff98e6c940f..5ef8b4455c23f1 100644
--- a/clang/lib/Driver/ToolChains/Cuda.cpp
+++ b/clang/lib/Driver/ToolChains/Cuda.cpp
@@ -611,35 +611,34 @@ void NVPTX::Linker::ConstructJob(Compilation , const 
JobAction ,
   continue;
 }
 
-// Currently, we only pass the input files to the linker, we do not pass
-// any libraries that may be valid only for the host.
-if (!II.isFilename())
-  continue;
-
 // The 'nvlink' application performs RDC-mode linking when given a '.o'
 // file and device linking when given a '.cubin' file. We always want to
 // perform device linking, so just rename any '.o' files.
 // FIXME: This should hopefully be removed if NVIDIA updates their tooling.
-auto InputFile = getToolChain().getInputFilename(II);
-if (llvm::sys::path::extension(InputFile) != ".cubin") {
-  // If there are no actions above this one then this is direct input and 
we
-  // can copy it. Otherwise the input is internal so a `.cubin` file should
-  // exist.
-  if (II.getAction() && II.getAction()->getInputs().size() == 0) {
-const char *CubinF =
-Args.MakeArgString(getToolChain().getDriver().GetTemporaryPath(
-llvm::sys::path::stem(InputFile), "cubin"));
-if (llvm::sys::fs::copy_file(InputFile, C.addTempFile(CubinF)))
-  continue;
+if (II.isFilename()) {
+  auto InputFile = getToolChain().getInputFilename(II);
+  if (llvm::sys::path::extension(InputFile) != ".cubin") {
+// If there are no actions above this one then this is direct input and
+// we can copy it. Otherwise the input is internal so a `.cubin` file
+// should exist.
+if (II.getAction() && II.getAction()->getInputs().size() == 0) {
+  const char *CubinF =
+  Args.MakeArgString(getToolChain().getDriver().GetTemporaryPath(
+  llvm::sys::path::stem(InputFile), "cubin"));
+  if (llvm::sys::fs::copy_file(InputFile, C.addTempFile(CubinF)))
+continue;
 
-CmdArgs.push_back(CubinF);
+  CmdArgs.push_back(CubinF);
+} else {
+  SmallString<256> Filename(InputFile);
+  llvm::sys::path::replace_extension(Filename, "cubin");
+  CmdArgs.push_back(Args.MakeArgString(Filename));
+}
   } else {
-SmallString<256> Filename(InputFile);
-llvm::sys::path::replace_extension(Filename, "cubin");
-CmdArgs.push_back(Args.MakeArgString(Filename));
+CmdArgs.push_back(Args.MakeArgString(InputFile));
   }
-} else {
-  CmdArgs.push_back(Args.MakeArgString(InputFile));
+} else if (!II.isNothing()) {
+  II.getInputArg().renderAsInput(Args, CmdArgs);
 }
   }
 
diff --git a/clang/test/Driver/cuda-cross-compiling.c 
b/clang/test/Driver/cuda-cross-compiling.c
index 12d0af3b45f32f..5a52496838813e 100644
--- a/clang/test/Driver/cuda-cross-compiling.c
+++ b/clang/test/Driver/cuda-cross-compiling.c
@@ -77,3 +77,11 @@
 // RUN:   | FileCheck -check-prefix=LOWERING %s
 
 // LOWERING: -cc1" "-triple" "nvptx64-nvidia-cuda" {{.*}} "-mllvm" 
"--nvptx-lower-global-ctor-dtor"
+
+//
+// Test passing arguments directly to nvlink.
+//
+// RUN: %clang -target nvptx64-nvidia-cuda -Wl,-v -Wl,a,b -### %s 2>&1 \
+// RUN:   | FileCheck -check-prefix=LINKER-ARGS %s
+
+// LINKER-ARGS: nvlink{{.*}}"-v"{{.*}}"a" "b"
diff --git a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp 
b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
index bafe8ace60d1ce..03fb0a7d64552e 100644
--- a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -385,9 +385,11 @@ Expected clang(ArrayRef InputFiles, 
const ArgList ) {
   Triple.isAMDGPU() ? Args.MakeArgString("-mcpu=" + Arch)
 : Args.MakeArgString("-march=" + Arch),
   

[clang] [clang][test] Add test for incompatible cv-qualified reference types in conversion function template (PR #81950)

2024-02-22 Thread Duo Wang via cfe-commits

wdunicornpro wrote:

Ping: This helps to improve test coverage.

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


[clang] [compiler-rt] [AArch64] Implement __builtin_cpu_supports, compiler-rt tests. (PR #82378)

2024-02-22 Thread Pavel Iliin via cfe-commits

https://github.com/ilinpv updated 
https://github.com/llvm/llvm-project/pull/82378

>From 7283a6f34de8ca26aa36fcf83356f71f6f59a82f Mon Sep 17 00:00:00 2001
From: Pavel Iliin 
Date: Tue, 20 Feb 2024 02:01:04 +
Subject: [PATCH 1/2] [AArch64] Implement __builtin_cpu_supports, compiler-rt
 tests.

The patch complements https://github.com/llvm/llvm-project/pull/68919
and adds AArch64 support for builtin
__builtin_cpu_supports("feature1+...+featureN")
which return true if all specified CPU features in argument are
detected. Also compiler-rt aarch64 native run tests for features
detection mechanism were added and 'cpu_model' check was fixed after its
refactor merged https://github.com/llvm/llvm-project/pull/75635
Original RFC was https://reviews.llvm.org/D153153
---
 clang/lib/Basic/Targets/AArch64.cpp   |  8 ++-
 clang/lib/Basic/Targets/AArch64.h |  2 +-
 clang/lib/CodeGen/CGBuiltin.cpp   | 16 ++
 clang/lib/CodeGen/CodeGenFunction.h   |  2 +-
 .../CodeGen/aarch64-cpu-supports-target.c | 52 ++
 clang/test/CodeGen/aarch64-cpu-supports.c | 54 +++
 clang/test/Preprocessor/has_builtin_cpuid.c   |  7 +--
 clang/test/Sema/aarch64-cpu-supports.c| 26 +
 clang/test/Sema/builtin-cpu-supports.c|  2 +-
 .../builtins/Unit/aarch64_cpu_features_test.c | 17 ++
 .../test/builtins/Unit/cpu_model_test.c   |  2 +-
 11 files changed, 177 insertions(+), 11 deletions(-)
 create mode 100644 clang/test/CodeGen/aarch64-cpu-supports-target.c
 create mode 100644 clang/test/CodeGen/aarch64-cpu-supports.c
 create mode 100644 clang/test/Sema/aarch64-cpu-supports.c
 create mode 100644 compiler-rt/test/builtins/Unit/aarch64_cpu_features_test.c

diff --git a/clang/lib/Basic/Targets/AArch64.cpp 
b/clang/lib/Basic/Targets/AArch64.cpp
index 68032961451d90..5abb060073c517 100644
--- a/clang/lib/Basic/Targets/AArch64.cpp
+++ b/clang/lib/Basic/Targets/AArch64.cpp
@@ -667,7 +667,13 @@ StringRef 
AArch64TargetInfo::getFeatureDependencies(StringRef Name) const {
 }
 
 bool AArch64TargetInfo::validateCpuSupports(StringRef FeatureStr) const {
-  return llvm::AArch64::parseArchExtension(FeatureStr).has_value();
+  // CPU features might be separated by '+', extract them and check
+  llvm::SmallVector Features;
+  FeatureStr.split(Features, "+");
+  for (auto  : Features)
+if (!llvm::AArch64::parseArchExtension(Feature.trim()).has_value())
+  return false;
+  return true;
 }
 
 bool AArch64TargetInfo::hasFeature(StringRef Feature) const {
diff --git a/clang/lib/Basic/Targets/AArch64.h 
b/clang/lib/Basic/Targets/AArch64.h
index 26ee7fa1978256..c1ba156860a122 100644
--- a/clang/lib/Basic/Targets/AArch64.h
+++ b/clang/lib/Basic/Targets/AArch64.h
@@ -165,7 +165,7 @@ class LLVM_LIBRARY_VISIBILITY AArch64TargetInfo : public 
TargetInfo {
 DiagnosticsEngine ) override;
   ParsedTargetAttr parseTargetAttr(StringRef Str) const override;
   bool supportsTargetAttributeTune() const override { return true; }
-
+  bool supportsCpuSupports() const override { return true; }
   bool checkArithmeticFenceSupported() const override { return true; }
 
   bool hasBFloat16Type() const override;
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index d8b2115f1e5e3c..734eb5a035ca49 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -10638,6 +10638,9 @@ Value *CodeGenFunction::EmitAArch64BuiltinExpr(unsigned 
BuiltinID,
   BuiltinID <= clang::AArch64::LastSMEBuiltin)
 return EmitAArch64SMEBuiltinExpr(BuiltinID, E);
 
+  if (BuiltinID == Builtin::BI__builtin_cpu_supports)
+return EmitAArch64CpuSupports(E);
+
   unsigned HintID = static_cast(-1);
   switch (BuiltinID) {
   default: break;
@@ -14025,6 +14028,19 @@ Value *CodeGenFunction::EmitX86CpuInit() {
   return Builder.CreateCall(Func);
 }
 
+Value *CodeGenFunction::EmitAArch64CpuSupports(const CallExpr *E) {
+  const Expr *ArgExpr = E->getArg(0)->IgnoreParenCasts();
+  StringRef ArgStr = cast(ArgExpr)->getString();
+  llvm::SmallVector Features;
+  ArgStr.split(Features, "+");
+  for (auto  : Features) {
+Feature = Feature.trim();
+if (Feature != "default")
+  Features.push_back(Feature);
+  }
+  return EmitAArch64CpuSupports(Features);
+}
+
 llvm::Value *
 CodeGenFunction::EmitAArch64CpuSupports(ArrayRef FeaturesStrs) {
   uint64_t FeaturesMask = llvm::AArch64::getCpuSupportsMask(FeaturesStrs);
diff --git a/clang/lib/CodeGen/CodeGenFunction.h 
b/clang/lib/CodeGen/CodeGenFunction.h
index caa6a327550baa..92ce0edeaf9e9c 100644
--- a/clang/lib/CodeGen/CodeGenFunction.h
+++ b/clang/lib/CodeGen/CodeGenFunction.h
@@ -5013,10 +5013,10 @@ class CodeGenFunction : public CodeGenTypeCache {
   llvm::Value *EmitAArch64CpuInit();
   llvm::Value *
   FormAArch64ResolverCondition(const MultiVersionResolverOption );
+  llvm::Value *EmitAArch64CpuSupports(const CallExpr *E);
   llvm::Value 

[clang] [Clang] Append target search paths for direct offloading compilation (PR #82699)

2024-02-22 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang-driver
@llvm/pr-subscribers-backend-amdgpu

@llvm/pr-subscribers-clang

Author: Joseph Huber (jhuber6)


Changes

Summary:
Recent changes to the `libc` project caused the headers to be installed
to `include/triple` for the GPU and the libraries to be in
`lib/triple`. This means we should automatically append these search
paths so they can be found by default. This allows the following to work
targeting AMDGPU.

```shell
$ clang foo.c -flto -mcpu=native --target=amdgcn-amd-amdhsa -lc 
install/lib/amdgcn-amd-amdhsa/crt1.o
$ amdhsa-loader a.out
```


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


4 Files Affected:

- (modified) clang/lib/Driver/ToolChains/AMDGPU.cpp (+1) 
- (modified) clang/lib/Driver/ToolChains/Clang.cpp (+2-2) 
- (modified) clang/lib/Driver/ToolChains/Cuda.cpp (+4) 
- (modified) clang/test/Driver/gpu-libc-headers.c (+8-1) 


``diff
diff --git a/clang/lib/Driver/ToolChains/AMDGPU.cpp 
b/clang/lib/Driver/ToolChains/AMDGPU.cpp
index 60e8c123c591d2..6fcbcffd6f0d67 100644
--- a/clang/lib/Driver/ToolChains/AMDGPU.cpp
+++ b/clang/lib/Driver/ToolChains/AMDGPU.cpp
@@ -625,6 +625,7 @@ void amdgpu::Linker::ConstructJob(Compilation , const 
JobAction ,
 
   addLinkerCompressDebugSectionsOption(getToolChain(), Args, CmdArgs);
   Args.AddAllArgs(CmdArgs, options::OPT_L);
+  getToolChain().AddFilePathLibArgs(Args, CmdArgs);
   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
   if (C.getDriver().isUsingLTO())
 addLTOOptions(getToolChain(), Args, CmdArgs, Output, Inputs[0],
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 7c0409f0c3097a..6e1b7e8657d0dc 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -,8 +,8 @@ void Clang::AddPreprocessingOptions(Compilation , const 
JobAction ,
 C.getActiveOffloadKinds() == Action::OFK_None) {
   SmallString<128> P(llvm::sys::path::parent_path(D.InstalledDir));
   llvm::sys::path::append(P, "include");
-  llvm::sys::path::append(P, "gpu-none-llvm");
-  CmdArgs.push_back("-c-isystem");
+  llvm::sys::path::append(P, getToolChain().getTripleString());
+  CmdArgs.push_back("-internal-isystem");
   CmdArgs.push_back(Args.MakeArgString(P));
 } else if (C.getActiveOffloadKinds() == Action::OFK_OpenMP) {
   // TODO: CUDA / HIP include their own headers for some common functions
diff --git a/clang/lib/Driver/ToolChains/Cuda.cpp 
b/clang/lib/Driver/ToolChains/Cuda.cpp
index ed5924c3b73b55..8c7a96289559c1 100644
--- a/clang/lib/Driver/ToolChains/Cuda.cpp
+++ b/clang/lib/Driver/ToolChains/Cuda.cpp
@@ -609,6 +609,10 @@ void NVPTX::Linker::ConstructJob(Compilation , const 
JobAction ,
   // Add paths specified in LIBRARY_PATH environment variable as -L options.
   addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
 
+  // Add standard library search paths passed on the command line.
+  Args.AddAllArgs(CmdArgs, options::OPT_L);
+  getToolChain().AddFilePathLibArgs(Args, CmdArgs);
+
   // Add paths for the default clang library path.
   SmallString<256> DefaultLibPath =
   llvm::sys::path::parent_path(TC.getDriver().Dir);
diff --git a/clang/test/Driver/gpu-libc-headers.c 
b/clang/test/Driver/gpu-libc-headers.c
index 74e9a764dfcb35..356a401550399d 100644
--- a/clang/test/Driver/gpu-libc-headers.c
+++ b/clang/test/Driver/gpu-libc-headers.c
@@ -10,10 +10,17 @@
 // CHECK-HEADERS: "-cc1"{{.*}}"-internal-isystem" 
"{{.*}}include{{.*}}llvm_libc_wrappers"{{.*}}"-isysroot" "./"
 // CHECK-HEADERS: "-cc1"{{.*}}"-internal-isystem" 
"{{.*}}include{{.*}}llvm_libc_wrappers"{{.*}}"-isysroot" "./"
 
+// RUN:   %clang -### --target=amdgcn-amd-amdhsa -mcpu=gfx90a --sysroot=./ \
+// RUN: -nogpulib %s 2>&1 | FileCheck %s 
--check-prefix=CHECK-HEADERS-AMDGPU
+// RUN:   %clang -### --target=nvptx64-nvidia-cuda -march=sm_89 --sysroot=./ \
+// RUN: -nogpulib %s 2>&1 | FileCheck %s --check-prefix=CHECK-HEADERS-NVPTX
+// CHECK-HEADERS-AMDGPU: "-cc1"{{.*}}"-internal-isystem" 
"{{.*}}include{{.*}}amdgcn-amd-amdhsa"{{.*}}"-isysroot" "./"
+// CHECK-HEADERS-NVPTX: "-cc1"{{.*}}"-internal-isystem" 
"{{.*}}include{{.*}}nvptx64-nvidia-cuda"{{.*}}"-isysroot" "./"
+
 // RUN:   %clang -### --target=amdgcn-amd-amdhsa -mcpu=gfx1030 -nogpulib \
 // RUN: -nogpuinc %s 2>&1 | FileCheck %s 
--check-prefix=CHECK-HEADERS-DISABLED
 // RUN:   %clang -### --target=amdgcn-amd-amdhsa -mcpu=gfx1030 -nogpulib \
 // RUN: -nostdinc %s 2>&1 | FileCheck %s 
--check-prefix=CHECK-HEADERS-DISABLED
 // RUN:   %clang -### --target=amdgcn-amd-amdhsa -mcpu=gfx1030 -nogpulib \
 // RUN: -nobuiltininc %s 2>&1 | FileCheck %s 
--check-prefix=CHECK-HEADERS-DISABLED
-// CHECK-HEADERS-DISABLED-NOT: "-cc1"{{.*}}"-c-isystem" 
"{{.*}}include{{.*}}gpu-none-llvm"
+// CHECK-HEADERS-DISABLED-NOT: "-cc1"{{.*}}"-internal-isystem" 
"{{.*}}include{{.*}}gpu-none-llvm"

``





[clang] [Clang] Append target search paths for direct offloading compilation (PR #82699)

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

https://github.com/jhuber6 created 
https://github.com/llvm/llvm-project/pull/82699

Summary:
Recent changes to the `libc` project caused the headers to be installed
to `include/` for the GPU and the libraries to be in
`lib/`. This means we should automatically append these search
paths so they can be found by default. This allows the following to work
targeting AMDGPU.

```shell
$ clang foo.c -flto -mcpu=native --target=amdgcn-amd-amdhsa -lc 
/lib/amdgcn-amd-amdhsa/crt1.o
$ amdhsa-loader a.out
```


>From 8f0ac133bcea8181e59f82de5767bb9c34e6d346 Mon Sep 17 00:00:00 2001
From: Joseph Huber 
Date: Thu, 22 Feb 2024 16:13:35 -0600
Subject: [PATCH] [Clang] Append target search paths for direct offloading
 compilation

Summary:
Recent changes to the `libc` project caused the headers to be installed
to `include/` for the GPU and the libraries to be in
`lib/`. This means we should automatically append these search
paths so they can be found by default. This allows the following to work
targeting AMDGPU.

```shell
$ clang foo.c -flto -mcpu=native --target=amdgcn-amd-amdhsa -lc 
/lib/amdgcn-amd-amdhsa/crt1.o
$ amdhsa-loader a.out
```
---
 clang/lib/Driver/ToolChains/AMDGPU.cpp | 1 +
 clang/lib/Driver/ToolChains/Clang.cpp  | 4 ++--
 clang/lib/Driver/ToolChains/Cuda.cpp   | 4 
 clang/test/Driver/gpu-libc-headers.c   | 9 -
 4 files changed, 15 insertions(+), 3 deletions(-)

diff --git a/clang/lib/Driver/ToolChains/AMDGPU.cpp 
b/clang/lib/Driver/ToolChains/AMDGPU.cpp
index 60e8c123c591d2..6fcbcffd6f0d67 100644
--- a/clang/lib/Driver/ToolChains/AMDGPU.cpp
+++ b/clang/lib/Driver/ToolChains/AMDGPU.cpp
@@ -625,6 +625,7 @@ void amdgpu::Linker::ConstructJob(Compilation , const 
JobAction ,
 
   addLinkerCompressDebugSectionsOption(getToolChain(), Args, CmdArgs);
   Args.AddAllArgs(CmdArgs, options::OPT_L);
+  getToolChain().AddFilePathLibArgs(Args, CmdArgs);
   AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs, JA);
   if (C.getDriver().isUsingLTO())
 addLTOOptions(getToolChain(), Args, CmdArgs, Output, Inputs[0],
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 7c0409f0c3097a..6e1b7e8657d0dc 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -,8 +,8 @@ void Clang::AddPreprocessingOptions(Compilation , const 
JobAction ,
 C.getActiveOffloadKinds() == Action::OFK_None) {
   SmallString<128> P(llvm::sys::path::parent_path(D.InstalledDir));
   llvm::sys::path::append(P, "include");
-  llvm::sys::path::append(P, "gpu-none-llvm");
-  CmdArgs.push_back("-c-isystem");
+  llvm::sys::path::append(P, getToolChain().getTripleString());
+  CmdArgs.push_back("-internal-isystem");
   CmdArgs.push_back(Args.MakeArgString(P));
 } else if (C.getActiveOffloadKinds() == Action::OFK_OpenMP) {
   // TODO: CUDA / HIP include their own headers for some common functions
diff --git a/clang/lib/Driver/ToolChains/Cuda.cpp 
b/clang/lib/Driver/ToolChains/Cuda.cpp
index ed5924c3b73b55..8c7a96289559c1 100644
--- a/clang/lib/Driver/ToolChains/Cuda.cpp
+++ b/clang/lib/Driver/ToolChains/Cuda.cpp
@@ -609,6 +609,10 @@ void NVPTX::Linker::ConstructJob(Compilation , const 
JobAction ,
   // Add paths specified in LIBRARY_PATH environment variable as -L options.
   addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH");
 
+  // Add standard library search paths passed on the command line.
+  Args.AddAllArgs(CmdArgs, options::OPT_L);
+  getToolChain().AddFilePathLibArgs(Args, CmdArgs);
+
   // Add paths for the default clang library path.
   SmallString<256> DefaultLibPath =
   llvm::sys::path::parent_path(TC.getDriver().Dir);
diff --git a/clang/test/Driver/gpu-libc-headers.c 
b/clang/test/Driver/gpu-libc-headers.c
index 74e9a764dfcb35..356a401550399d 100644
--- a/clang/test/Driver/gpu-libc-headers.c
+++ b/clang/test/Driver/gpu-libc-headers.c
@@ -10,10 +10,17 @@
 // CHECK-HEADERS: "-cc1"{{.*}}"-internal-isystem" 
"{{.*}}include{{.*}}llvm_libc_wrappers"{{.*}}"-isysroot" "./"
 // CHECK-HEADERS: "-cc1"{{.*}}"-internal-isystem" 
"{{.*}}include{{.*}}llvm_libc_wrappers"{{.*}}"-isysroot" "./"
 
+// RUN:   %clang -### --target=amdgcn-amd-amdhsa -mcpu=gfx90a --sysroot=./ \
+// RUN: -nogpulib %s 2>&1 | FileCheck %s 
--check-prefix=CHECK-HEADERS-AMDGPU
+// RUN:   %clang -### --target=nvptx64-nvidia-cuda -march=sm_89 --sysroot=./ \
+// RUN: -nogpulib %s 2>&1 | FileCheck %s --check-prefix=CHECK-HEADERS-NVPTX
+// CHECK-HEADERS-AMDGPU: "-cc1"{{.*}}"-internal-isystem" 
"{{.*}}include{{.*}}amdgcn-amd-amdhsa"{{.*}}"-isysroot" "./"
+// CHECK-HEADERS-NVPTX: "-cc1"{{.*}}"-internal-isystem" 
"{{.*}}include{{.*}}nvptx64-nvidia-cuda"{{.*}}"-isysroot" "./"
+
 // RUN:   %clang -### --target=amdgcn-amd-amdhsa -mcpu=gfx1030 -nogpulib \
 // RUN: -nogpuinc %s 2>&1 | FileCheck %s 
--check-prefix=CHECK-HEADERS-DISABLED
 // RUN:   %clang -### --target=amdgcn-amd-amdhsa -mcpu=gfx1030 -nogpulib \
 // RUN: 

[clang] [clang] Implement __builtin_popcountg (PR #82359)

2024-02-22 Thread via cfe-commits

overmighty wrote:

Rebased.

@nickdesaulniers I am interested in implementing more builtins like this one. :)

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


[clang] [clang] Implement __builtin_popcountg (PR #82359)

2024-02-22 Thread via cfe-commits

https://github.com/overmighty updated 
https://github.com/llvm/llvm-project/pull/82359

>From e41f7bec8aa663d1f9d924e71e8471d40e30f495 Mon Sep 17 00:00:00 2001
From: OverMighty 
Date: Tue, 20 Feb 2024 13:45:13 +
Subject: [PATCH 1/5] [clang] Implement __builtin_popcountg

Fixes #82058.
---
 clang/include/clang/Basic/Builtins.td |  6 
 clang/lib/CodeGen/CGBuiltin.cpp   |  7 -
 clang/test/CodeGen/builtins.c | 43 +++
 3 files changed, 55 insertions(+), 1 deletion(-)

diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index df74026c5d2d50..3134450250edd5 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -688,6 +688,12 @@ def Popcount : Builtin, BitInt_Long_LongLongTemplate {
   let Prototype = "int(unsigned T)";
 }
 
+def Popcountg : Builtin {
+  let Spellings = ["__builtin_popcountg"];
+  let Attributes = [NoThrow, Const, Constexpr];
+  let Prototype = "int(...)";
+}
+
 def Clrsb : Builtin, BitInt_Long_LongLongTemplate {
   let Spellings = ["__builtin_clrsb"];
   let Attributes = [NoThrow, Const, Constexpr];
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index d8b2115f1e5e3c..c273cefdf9cac2 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -3216,7 +3216,12 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
   case Builtin::BI__popcnt64:
   case Builtin::BI__builtin_popcount:
   case Builtin::BI__builtin_popcountl:
-  case Builtin::BI__builtin_popcountll: {
+  case Builtin::BI__builtin_popcountll:
+  case Builtin::BI__builtin_popcountg: {
+if (BuiltinIDIfNoAsmLabel == Builtin::BI__builtin_popcountg) {
+  assert(E->getNumArgs() == 1 && "__builtin_popcountg takes 1 argument");
+}
+
 Value *ArgValue = EmitScalarExpr(E->getArg(0));
 
 llvm::Type *ArgType = ArgValue->getType();
diff --git a/clang/test/CodeGen/builtins.c b/clang/test/CodeGen/builtins.c
index 88282120283b8a..73866116e07e72 100644
--- a/clang/test/CodeGen/builtins.c
+++ b/clang/test/CodeGen/builtins.c
@@ -940,4 +940,47 @@ void test_builtin_os_log_long_double(void *buf, long 
double ld) {
 // CHECK: %[[V3:.*]] = load i128, ptr %[[ARG0_ADDR]], align 16
 // CHECK: store i128 %[[V3]], ptr %[[ARGDATA]], align 1
 
+// CHECK-LABEL: define{{.*}} void @test_builtin_popcountg
+void test_builtin_popcountg(unsigned char uc, unsigned short us,
+unsigned int ui, unsigned long ul,
+unsigned long long ull, unsigned __int128 ui128,
+unsigned _BitInt(128) ubi128) {
+  volatile int pop;
+  pop = __builtin_popcountg(uc);
+  // CHECK: %1 = load i8, ptr %uc.addr, align 1
+  // CHECK-NEXT: %conv = zext i8 %1 to i32
+  // CHECK-NEXT: %2 = call i32 @llvm.ctpop.i32(i32 %conv)
+  // CHECK-NEXT: store volatile i32 %2, ptr %pop, align 4
+  pop = __builtin_popcountg(us);
+  // CHECK-NEXT: %3 = load i16, ptr %us.addr, align 2
+  // CHECK-NEXT: %conv1 = zext i16 %3 to i32
+  // CHECK-NEXT: %4 = call i32 @llvm.ctpop.i32(i32 %conv1)
+  // CHECK-NEXT: store volatile i32 %4, ptr %pop, align 4
+  pop = __builtin_popcountg(ui);
+  // CHECK-NEXT: %5 = load i32, ptr %ui.addr, align 4
+  // CHECK-NEXT: %6 = call i32 @llvm.ctpop.i32(i32 %5)
+  // CHECK-NEXT: store volatile i32 %6, ptr %pop, align 4
+  pop = __builtin_popcountg(ul);
+  // CHECK-NEXT: %7 = load i64, ptr %ul.addr, align 8
+  // CHECK-NEXT: %8 = call i64 @llvm.ctpop.i64(i64 %7)
+  // CHECK-NEXT: %cast = trunc i64 %8 to i32
+  // CHECK-NEXT: store volatile i32 %cast, ptr %pop, align 4
+  pop = __builtin_popcountg(ull);
+  // CHECK-NEXT: %9 = load i64, ptr %ull.addr, align 8
+  // CHECK-NEXT: %10 = call i64 @llvm.ctpop.i64(i64 %9)
+  // CHECK-NEXT: %cast2 = trunc i64 %10 to i32
+  // CHECK-NEXT: store volatile i32 %cast2, ptr %pop, align 4
+  pop = __builtin_popcountg(ui128);
+  // CHECK-NEXT: %11 = load i128, ptr %ui128.addr, align 16
+  // CHECK-NEXT: %12 = call i128 @llvm.ctpop.i128(i128 %11)
+  // CHECK-NEXT: %cast3 = trunc i128 %12 to i32
+  // CHECK-NEXT: store volatile i32 %cast3, ptr %pop, align 4
+  pop = __builtin_popcountg(ubi128);
+  // CHECK-NEXT: %13 = load i128, ptr %ubi128.addr, align 8
+  // CHECK-NEXT: %14 = call i128 @llvm.ctpop.i128(i128 %13)
+  // CHECK-NEXT: %cast4 = trunc i128 %14 to i32
+  // CHECK-NEXT: store volatile i32 %cast4, ptr %pop, align 4
+  // CHECK-NEXT: ret void
+}
+
 #endif

>From 62d3883a89f01116e25f07b6897e58234fcae615 Mon Sep 17 00:00:00 2001
From: OverMighty 
Date: Tue, 20 Feb 2024 21:54:14 +
Subject: [PATCH 2/5] fixup! [clang] Implement __builtin_popcountg

---
 .../clang/Basic/DiagnosticSemaKinds.td|  3 ++-
 clang/lib/Sema/SemaChecking.cpp   | 22 +++
 clang/test/Sema/builtin-popcountg.c   | 14 
 3 files changed, 38 insertions(+), 1 deletion(-)
 create mode 100644 

[clang] [clang][CodeGen] Keep processing the rest of AST after encountering unsupported MC/DC expressions (PR #82464)

2024-02-22 Thread Wentao Zhang via cfe-commits

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


[clang] d4bfca3 - [clang][CodeGen] Keep processing the rest of AST after encountering unsupported MC/DC expressions (#82464)

2024-02-22 Thread via cfe-commits

Author: Wentao Zhang
Date: 2024-02-22T16:04:25-06:00
New Revision: d4bfca3b2e673789f7c278d46a199ae8910ddd37

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

LOG: [clang][CodeGen] Keep processing the rest of AST after encountering 
unsupported MC/DC expressions (#82464)

Currently, upon seeing unsupported decisions (more than 6 conditions, or
split nesting), the post-visitor hook dataTraverseStmtPost() returns a
false. As a result, in the rest of tree even supported decisions will
be skipped as well. Like in the below code:

{ // CompoundStmt
  a && b;   // 1: BinaryOperator (supported)
  a && foo(b && c); // 2: BinaryOperator (not yet supported due to split
//nesting)
  a && b;   // 3: BinaryOperator (supported)
}

Decision 3 will not be processed at all. And only one "Decision" region
will be emitted. Compiler explorer example:
https://godbolt.org/z/Px61sesoo

We hope to process such cases and emit two "Decision" regions (1 and 3)
in the above example.

Added: 


Modified: 
clang/lib/CodeGen/CodeGenPGO.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CodeGenPGO.cpp 
b/clang/lib/CodeGen/CodeGenPGO.cpp
index 48c5e68a3b7ba4..1ef7be3c72593d 100644
--- a/clang/lib/CodeGen/CodeGenPGO.cpp
+++ b/clang/lib/CodeGen/CodeGenPGO.cpp
@@ -239,9 +239,12 @@ struct MapRegionCounters : public 
RecursiveASTVisitor {
 if (MCDCMaxCond == 0)
   return true;
 
-/// At the top of the logical operator nest, reset the number of 
conditions.
-if (LogOpStack.empty())
+/// At the top of the logical operator nest, reset the number of 
conditions,
+/// also forget previously seen split nesting cases.
+if (LogOpStack.empty()) {
   NumCond = 0;
+  SplitNestedLogicalOp = false;
+}
 
 if (const Expr *E = dyn_cast(S)) {
   const BinaryOperator *BinOp = 
dyn_cast(E->IgnoreParens());
@@ -292,7 +295,7 @@ struct MapRegionCounters : public 
RecursiveASTVisitor {
 "contains an operation with a nested boolean expression. "
 "Expression will not be covered");
 Diag.Report(S->getBeginLoc(), DiagID);
-return false;
+return true;
   }
 
   /// Was the maximum number of conditions encountered?
@@ -303,7 +306,7 @@ struct MapRegionCounters : public 
RecursiveASTVisitor {
 "number of conditions (%0) exceeds max (%1). "
 "Expression will not be covered");
 Diag.Report(S->getBeginLoc(), DiagID) << NumCond << MCDCMaxCond;
-return false;
+return true;
   }
 
   // Otherwise, allocate the number of bytes required for the bitmap



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


[clang-tools-extra] [clang-tidy] Fix handling --driver-mode= (PR #66553)

2024-02-22 Thread Piotr Zegar via cfe-commits

PiotrZSL wrote:

@rsniezek If someone will review & approve it, then it will land.

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


[clang] [APINotes] Upstream Sema logic to apply API Notes to decls (PR #78445)

2024-02-22 Thread Egor Zhdan via cfe-commits

https://github.com/egorzhdan updated 
https://github.com/llvm/llvm-project/pull/78445

>From c1ad33ed549affb2bdabf49be4340a6f7580b191 Mon Sep 17 00:00:00 2001
From: Egor Zhdan 
Date: Wed, 17 Jan 2024 13:41:25 +
Subject: [PATCH] [APINotes] Upstream Sema logic to apply API Notes to decls

This upstreams more of the Clang API Notes functionality that is currently 
implemented in the Apple fork: 
https://github.com/apple/llvm-project/tree/next/clang/lib/APINotes
---
 .../clang/Basic/DiagnosticSemaKinds.td|   7 +
 clang/include/clang/Sema/Sema.h   |   6 +
 clang/lib/Sema/CMakeLists.txt |   1 +
 clang/lib/Sema/SemaAPINotes.cpp   | 995 ++
 clang/lib/Sema/SemaDecl.cpp   |   4 +
 clang/lib/Sema/SemaDeclAttr.cpp   |   3 +
 clang/lib/Sema/SemaDeclCXX.cpp|   6 +-
 clang/lib/Sema/SemaDeclObjC.cpp   |   4 +
 clang/lib/Sema/SemaObjCProperty.cpp   |   5 +
 clang/lib/Sema/SemaTemplate.cpp   |   7 +
 10 files changed, 1037 insertions(+), 1 deletion(-)
 create mode 100644 clang/lib/Sema/SemaAPINotes.cpp

diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index ebda201361fb07..887d6120f48d2c 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -10760,6 +10760,13 @@ def warn_imp_cast_drops_unaligned : Warning<
 
 } // end of sema category
 
+let CategoryName = "API Notes Issue" in {
+
+def err_incompatible_replacement_type : Error<
+  "API notes replacement type %0 has a different size from original type %1">;
+
+} // end of API Notes category
+
 let CategoryName = "OpenMP Issue" in {
 // OpenMP support.
 def err_omp_expected_var_arg : Error<
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index fcccac10f4733a..77749372b7fb65 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -4883,6 +4883,12 @@ class Sema final {
   bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr ,
 bool SkipArgCountCheck = false);
 
+  /// Map any API notes provided for this declaration to attributes on the
+  /// declaration.
+  ///
+  /// Triggered by declaration-attribute processing.
+  void ProcessAPINotes(Decl *D);
+
   /// Determine if type T is a valid subject for a nonnull and similar
   /// attributes. By default, we look through references (the behavior used by
   /// nonnull), but if the second parameter is true, then we treat a reference
diff --git a/clang/lib/Sema/CMakeLists.txt b/clang/lib/Sema/CMakeLists.txt
index 862f9d4ffb825d..e8bff07ced0cfa 100644
--- a/clang/lib/Sema/CMakeLists.txt
+++ b/clang/lib/Sema/CMakeLists.txt
@@ -27,6 +27,7 @@ add_clang_library(clangSema
   Sema.cpp
   SemaAccess.cpp
   SemaAttr.cpp
+  SemaAPINotes.cpp
   SemaAvailability.cpp
   SemaCXXScopeSpec.cpp
   SemaCast.cpp
diff --git a/clang/lib/Sema/SemaAPINotes.cpp b/clang/lib/Sema/SemaAPINotes.cpp
new file mode 100644
index 00..9b19d3a3eb9ef2
--- /dev/null
+++ b/clang/lib/Sema/SemaAPINotes.cpp
@@ -0,0 +1,995 @@
+//===--- SemaAPINotes.cpp - API Notes Handling 
===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file implements the mapping from API notes to declaration attributes.
+//
+//===--===//
+
+#include "clang/APINotes/APINotesReader.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/DeclObjC.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Lex/Lexer.h"
+#include "clang/Sema/SemaInternal.h"
+
+using namespace clang;
+
+namespace {
+enum class IsActive_t : bool { Inactive, Active };
+enum class IsReplacement_t : bool { Original, Replacement };
+
+struct VersionedInfoMetadata {
+  /// An empty version refers to unversioned metadata.
+  VersionTuple Version;
+  unsigned IsActive : 1;
+  unsigned IsReplacement : 1;
+
+  VersionedInfoMetadata(VersionTuple Version, IsActive_t Active,
+IsReplacement_t Replacement)
+  : Version(Version), IsActive(Active == IsActive_t::Active),
+IsReplacement(Replacement == IsReplacement_t::Replacement) {}
+};
+} // end anonymous namespace
+
+/// Determine whether this is a multi-level pointer type.
+static bool isIndirectPointerType(QualType Type) {
+  QualType Pointee = Type->getPointeeType();
+  if (Pointee.isNull())
+return false;
+
+  return Pointee->isAnyPointerType() || Pointee->isObjCObjectPointerType() ||
+ Pointee->isMemberPointerType();
+}
+
+/// Apply nullability to the given declaration.
+static void 

  1   2   3   4   5   >