[clang] e44600f - [X86][CFE] Support EGPR in GCCRegNames. (#91323)

2024-05-08 Thread via cfe-commits

Author: Freddy Ye
Date: 2024-05-08T15:07:18+08:00
New Revision: e44600f3ab58b0e93a2a80f18e17181c2bc007a4

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

LOG: [X86][CFE] Support EGPR in GCCRegNames. (#91323)

Added: 
clang/test/CodeGen/X86/inline-asm-gcc-regs.c

Modified: 
clang/lib/Basic/Targets/X86.cpp

Removed: 




diff  --git a/clang/lib/Basic/Targets/X86.cpp b/clang/lib/Basic/Targets/X86.cpp
index bf1767c87fe1c..67e2126cf766b 100644
--- a/clang/lib/Basic/Targets/X86.cpp
+++ b/clang/lib/Basic/Targets/X86.cpp
@@ -64,6 +64,8 @@ static const char *const GCCRegNames[] = {
 "dr0",   "dr1",   "dr2",   "dr3",   "dr6", "dr7",
 "bnd0",  "bnd1",  "bnd2",  "bnd3",
 "tmm0",  "tmm1",  "tmm2",  "tmm3",  "tmm4","tmm5",  "tmm6",  "tmm7",
+"r16",   "r17",   "r18",   "r19",   "r20", "r21",   "r22",   "r23",
+"r24",   "r25",   "r26",   "r27",   "r28", "r29",   "r30",   "r31",
 };
 
 const TargetInfo::AddlRegName AddlRegNames[] = {
@@ -83,8 +85,23 @@ const TargetInfo::AddlRegName AddlRegNames[] = {
 {{"r13d", "r13w", "r13b"}, 43},
 {{"r14d", "r14w", "r14b"}, 44},
 {{"r15d", "r15w", "r15b"}, 45},
+{{"r16d", "r16w", "r16b"}, 165},
+{{"r17d", "r17w", "r17b"}, 166},
+{{"r18d", "r18w", "r18b"}, 167},
+{{"r19d", "r19w", "r19b"}, 168},
+{{"r20d", "r20w", "r20b"}, 169},
+{{"r21d", "r21w", "r21b"}, 170},
+{{"r22d", "r22w", "r22b"}, 171},
+{{"r23d", "r23w", "r23b"}, 172},
+{{"r24d", "r24w", "r24b"}, 173},
+{{"r25d", "r25w", "r25b"}, 174},
+{{"r26d", "r26w", "r26b"}, 175},
+{{"r27d", "r27w", "r27b"}, 176},
+{{"r28d", "r28w", "r28b"}, 177},
+{{"r29d", "r29w", "r29b"}, 178},
+{{"r30d", "r30w", "r30b"}, 179},
+{{"r31d", "r31w", "r31b"}, 180},
 };
-
 } // namespace targets
 } // namespace clang
 

diff  --git a/clang/test/CodeGen/X86/inline-asm-gcc-regs.c 
b/clang/test/CodeGen/X86/inline-asm-gcc-regs.c
new file mode 100644
index 0..17adbdc20a406
--- /dev/null
+++ b/clang/test/CodeGen/X86/inline-asm-gcc-regs.c
@@ -0,0 +1,121 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -emit-llvm -O2 %s -o - | 
FileCheck %s
+
+// CHECK-LABEL: @test_r15
+// CHECK: call void asm sideeffect "", "{r15},~{dirflag},~{fpsr},~{flags}"(i32 
undef)
+void test_r15() {
+register int a asm ("r15");
+asm ("" :: "r" (a));
+}
+
+// CHECK-LABEL: @test_r16
+// CHECK: call void asm sideeffect "", "{r16},~{dirflag},~{fpsr},~{flags}"(i32 
undef)
+void test_r16() {
+register int a asm ("r16");
+asm ("" :: "r" (a));
+}
+
+// CHECK-LABEL: @test_r17
+// CHECK: call void asm sideeffect "", "{r17},~{dirflag},~{fpsr},~{flags}"(i32 
undef)
+void test_r17() {
+register int a asm ("r17");
+asm ("" :: "r" (a));
+}
+
+// CHECK-LABEL: @test_r18
+// CHECK: call void asm sideeffect "", "{r18},~{dirflag},~{fpsr},~{flags}"(i32 
undef)
+void test_r18() {
+register int a asm ("r18");
+asm ("" :: "r" (a));
+}
+
+// CHECK-LABEL: @test_r19
+// CHECK: call void asm sideeffect "", "{r19},~{dirflag},~{fpsr},~{flags}"(i32 
undef)
+void test_r19() {
+register int a asm ("r19");
+asm ("" :: "r" (a));
+}
+
+// CHECK-LABEL: @test_r20
+// CHECK: call void asm sideeffect "", "{r20},~{dirflag},~{fpsr},~{flags}"(i32 
undef)
+void test_r20() {
+register int a asm ("r20");
+asm ("" :: "r" (a));
+}
+
+// CHECK-LABEL: @test_r21
+// CHECK: call void asm sideeffect "", "{r21},~{dirflag},~{fpsr},~{flags}"(i32 
undef)
+void test_r21() {
+register int a asm ("r21");
+asm ("" :: "r" (a));
+}
+
+// CHECK-LABEL: @test_r22
+// CHECK: call void asm sideeffect "", "{r22},~{dirflag},~{fpsr},~{flags}"(i32 
undef)
+void test_r22() {
+register int a asm ("r22");
+asm ("" :: "r" (a));
+}
+
+// CHECK-LABEL: @test_r23
+// CHECK: call void asm sideeffect "", "{r23},~{dirflag},~{fpsr},~{flags}"(i32 
undef)
+void test_r23() {
+register int a asm ("r23");
+asm ("" :: "r" (a));
+}
+
+// CHECK-LABEL: @test_r24
+// CHECK: call void asm sideeffect "", "{r24},~{dirflag},~{fpsr},~{flags}"(i32 
undef)
+void test_r24() {
+register int a asm ("r24");
+asm ("" :: "r" (a));
+}
+
+// CHECK-LABEL: @test_r25
+// CHECK: call void asm sideeffect "", "{r25},~{dirflag},~{fpsr},~{flags}"(i32 
undef)
+void test_r25() {
+register int a asm ("r25");
+asm ("" :: "r" (a));
+}
+
+// CHECK-LABEL: @test_r26
+// CHECK: call void asm sideeffect "", "{r26},~{dirflag},~{fpsr},~{flags}"(i32 
undef)
+void test_r26() {
+register int a asm ("r26");
+asm ("" :: "r" (a));
+}
+
+// CHECK-LABEL: @test_r27
+// CHECK: call void asm sideeffect "", "{r27},~{dirflag},~{fpsr},~{flags}"(i32 
undef)
+void test_r27() {
+register int a asm ("r27");
+asm ("" :: "r" (a));
+}
+
+// CHECK-LABEL: @test_r28
+// CHECK: call v

[clang] [X86][CFE] Support EGPR in GCCRegNames. (PR #91323)

2024-05-08 Thread Freddy Ye via cfe-commits

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


[clang] Fix P2564 handling of variable initializers (PR #89565)

2024-05-08 Thread via cfe-commits

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

>From 218ffb6d5a03c96d46bfecdb4490277809f5b62e Mon Sep 17 00:00:00 2001
From: Dan Katz 
Date: Tue, 16 Apr 2024 17:14:50 -0400
Subject: [PATCH 1/8] Fix bug with constexpr initialization.

---
 clang/lib/Parse/ParseDecl.cpp | 12 ++-
 clang/test/CXX/expr/expr.const/p6-2a.cpp  |  7 +++
 clang/test/SemaCXX/builtin_vectorelements.cpp |  4 ++--
 clang/test/SemaCXX/cxx2a-consteval.cpp| 20 ---
 clang/unittests/Support/TimeProfilerTest.cpp  |  1 -
 5 files changed, 24 insertions(+), 20 deletions(-)

diff --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp
index 05ad5ecbfaa0c..d71dfaf20a793 100644
--- a/clang/lib/Parse/ParseDecl.cpp
+++ b/clang/lib/Parse/ParseDecl.cpp
@@ -2552,6 +2552,13 @@ Decl *Parser::ParseDeclarationAfterDeclarator(
   return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo);
 }
 
+static bool isConstexprVariable(const Decl *D) {
+  if (const VarDecl *Var = dyn_cast_or_null(D))
+return Var->isConstexpr();
+
+  return false;
+}
+
 Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes(
 Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) {
   // RAII type used to track whether we're inside an initializer.
@@ -2559,9 +2566,12 @@ Decl 
*Parser::ParseDeclarationAfterDeclaratorAndAttributes(
 Parser &P;
 Declarator &D;
 Decl *ThisDecl;
+llvm::SaveAndRestore ConstantContext;
 
 InitializerScopeRAII(Parser &P, Declarator &D, Decl *ThisDecl)
-: P(P), D(D), ThisDecl(ThisDecl) {
+: P(P), D(D), ThisDecl(ThisDecl),
+  ConstantContext(P.Actions.isConstantEvaluatedOverride,
+  isConstexprVariable(ThisDecl)) {
   if (ThisDecl && P.getLangOpts().CPlusPlus) {
 Scope *S = nullptr;
 if (D.getCXXScopeSpec().isSet()) {
diff --git a/clang/test/CXX/expr/expr.const/p6-2a.cpp 
b/clang/test/CXX/expr/expr.const/p6-2a.cpp
index a937474d53b22..8b940b2ee9fb2 100644
--- a/clang/test/CXX/expr/expr.const/p6-2a.cpp
+++ b/clang/test/CXX/expr/expr.const/p6-2a.cpp
@@ -43,12 +43,11 @@ struct Temporary {
 constexpr Temporary t = {3}; // expected-error {{must have constant 
destruction}} expected-note {{created here}} expected-note {{in call}}
 
 namespace P1073R3 {
-consteval int f() { return 42; } // expected-note 2 {{declared here}}
+consteval int f() { return 42; } // expected-note {{declared here}}
 consteval auto g() { return f; }
 consteval int h(int (*p)() = g()) { return p(); }
 constexpr int r = h();
-constexpr auto e = g();  // expected-error {{call to consteval function 
'P1073R3::g' is not a constant expression}} \
-expected-error {{constexpr variable 'e' must be 
initialized by a constant expression}} \
-expected-note 2 {{pointer to a consteval 
declaration is not a constant expression}}
+constexpr auto e = g();  // expected-error {{constexpr variable 'e' must be 
initialized by a constant expression}} \
+expected-note {{pointer to a consteval declaration 
is not a constant expression}}
 static_assert(r == 42);
 } // namespace P1073R3
diff --git a/clang/test/SemaCXX/builtin_vectorelements.cpp 
b/clang/test/SemaCXX/builtin_vectorelements.cpp
index 59ff09ac72e42..12f2cbe57bd47 100644
--- a/clang/test/SemaCXX/builtin_vectorelements.cpp
+++ b/clang/test/SemaCXX/builtin_vectorelements.cpp
@@ -42,11 +42,11 @@ void test_builtin_vectorelements() {
 #include 
 
 consteval int consteval_elements() { // expected-error {{consteval function 
never produces a constant expression}}
-  return __builtin_vectorelements(svuint64_t); // expected-note {{cannot 
determine number of elements for sizeless vectors in a constant expression}}  
// expected-note {{cannot determine number of elements for sizeless vectors in 
a constant expression}} // expected-note {{cannot determine number of elements 
for sizeless vectors in a constant expression}}
+  return __builtin_vectorelements(svuint64_t); // expected-note {{cannot 
determine number of elements for sizeless vectors in a constant expression}} // 
expected-note {{cannot determine number of elements for sizeless vectors in a 
constant expression}}
 }
 
 void test_bad_constexpr() {
-  constexpr int eval = consteval_elements(); // expected-error {{initialized 
by a constant expression}} // expected-error {{not a constant expression}} // 
expected-note {{in call}} // expected-note {{in call}}
+  constexpr int eval = consteval_elements(); // expected-error {{initialized 
by a constant expression}} // expected-note {{in call}}
   constexpr int i32 = __builtin_vectorelements(svuint32_t); // expected-error 
{{initialized by a constant expression}} // expected-note {{cannot determine 
number of elements for sizeless vectors in a constant expression}}
   constexpr int i16p8 = __builtin_vectorelements(svuint16_t) + 16; // 
expected-e

[clang] [Clang] Fix P2564 handling of variable initializers (PR #89565)

2024-05-08 Thread via cfe-commits

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


[clang] [Coro] Relax a debug-info test (PR #91401)

2024-05-08 Thread Haojian Wu via cfe-commits

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


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


[clang] [clang] CTAD: implement the missing IsDeducible constraint for alias templates (PR #89358)

2024-05-08 Thread via cfe-commits


@@ -18,6 +18,7 @@
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/AST/TemplateName.h"
+#include "clang/AST/Type.h"

cor3ntin wrote:

Probably not a needed change

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


[clang] [clang] CTAD: implement the missing IsDeducible constraint for alias templates (PR #89358)

2024-05-08 Thread via cfe-commits


@@ -3239,6 +3239,40 @@ static TemplateDeductionResult 
FinishTemplateArgumentDeduction(
 
   return TemplateDeductionResult::Success;
 }
+/// Complete template argument deduction for DeduceTemplateArgumentsFromType.
+/// FIXME: this is mostly duplicated with the above two versions. Deduplicate
+/// the three implementations.

cor3ntin wrote:

Is that something you would be willing to do in a follow up patch?

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


[clang] [clang] CTAD: implement the missing IsDeducible constraint for alias templates (PR #89358)

2024-05-08 Thread via cfe-commits


@@ -6116,6 +6116,17 @@ static bool EvaluateBinaryTypeTrait(Sema &Self, 
TypeTrait BTT, const TypeSourceI
   tok::kw___is_pointer_interconvertible_base_of);
 
 return Self.IsPointerInterconvertibleBaseOf(Lhs, Rhs);
+  }
+  case BTT_IsDeducible: {
+if (const auto *TSTToBeDeduced =
+LhsT->getAs()) {
+  sema::TemplateDeductionInfo Info(KeyLoc);
+  return Self.DeduceTemplateArgumentsFromType(
+ TSTToBeDeduced->getTemplateName().getAsTemplateDecl(), RhsT,
+ Info) == TemplateDeductionResult::Success;
+}
+assert("Expect to see DeducedTemplateSpecializationType!");

cor3ntin wrote:

that is always true (you probably mean `false && ""`).
But I would remove the `if`, use 
`cast(LhsT)` that will assert for you)

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


[clang] [clang] CTAD: implement the missing IsDeducible constraint for alias templates (PR #89358)

2024-05-08 Thread via cfe-commits


@@ -3307,6 +3341,58 @@ 
Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
   return ::DeduceTemplateArguments(*this, Partial, TemplateArgs, Info);
 }
 
+TemplateDeductionResult
+Sema::DeduceTemplateArgumentsFromType(TemplateDecl *TD, QualType FromType,

cor3ntin wrote:

We have a lot of `DeduceTemplateArguments` function so I think we want to add a 
comment here describing what that function does / when it is used.

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


[clang] [clang] CTAD: implement the missing IsDeducible constraint for alias templates (PR #89358)

2024-05-08 Thread via cfe-commits


@@ -190,13 +196,15 @@ template  struct Foo { Foo(T); };
 
 template using AFoo = Foo;
 template concept False = false;
-template using BFoo = AFoo;
+template
+using BFoo = AFoo; // expected-note {{candidate template ignored: 
constraints not satisfied [with V = int]}} \
+  // expected-note {{because '__is_deducible(BFoo, Foo)' evaluated to false}} \

cor3ntin wrote:

I think we want to add code in this PR to improve the diagnostic

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


[clang] [clang] CTAD: implement the missing IsDeducible constraint for alias templates (PR #89358)

2024-05-08 Thread via cfe-commits


@@ -2774,6 +2775,41 @@ Expr *transformRequireClause(Sema &SemaRef, 
FunctionTemplateDecl *FTD,
   return E.getAs();
 }
 
+// Build the associated constraints for the alias deduction guides.
+// C++ [over.match.class.deduct]p3.3:
+//   The associated constraints ([temp.constr.decl]) are the conjunction of the
+//   associated constraints of g and a constraint that is satisfied if and only
+//   if the arguments of A are deducible (see below) from the return type.
+Expr *
+buildAssociatedConstraints(Sema &SemaRef, TypeAliasTemplateDecl *AliasTemplate,
+   FunctionTemplateDecl *FTD,
+   llvm::ArrayRef TransformedArgs,
+   QualType ReturnType) {
+  auto &Context = SemaRef.Context;

cor3ntin wrote:

```suggestion
  (const?) ASTContext &Context = SemaRef.Context;
```

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


[clang] [clang] CTAD: implement the missing IsDeducible constraint for alias templates (PR #89358)

2024-05-08 Thread via cfe-commits


@@ -27,7 +27,8 @@ enum TypeTrait {
   ,
 #define TYPE_TRAIT_2(Spelling, Name, Key) BTT_##Name,
 #include "clang/Basic/TokenKinds.def"
-  BTT_Last = UTT_Last // BTT_Last == last BTT_XX in the enum.
+  BTT_Last = UTT_Last

cor3ntin wrote:

Why remove the comment?

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


[clang] [clang][analyzer] Add checker 'Security.SetgidSetuidOrder'. (PR #91445)

2024-05-08 Thread Balázs Kéri via cfe-commits

https://github.com/balazske created 
https://github.com/llvm/llvm-project/pull/91445

None

From d839faf7a30851a172d812137b30635c741870f0 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Bal=C3=A1zs=20K=C3=A9ri?= 
Date: Wed, 8 May 2024 10:10:24 +0200
Subject: [PATCH] [clang][analyzer] Add checker 'Security.SetgidSetuidOrder'.

---
 clang/docs/analyzer/checkers.rst  |  28 +++
 .../clang/StaticAnalyzer/Checkers/Checkers.td |   5 +
 .../StaticAnalyzer/Checkers/CMakeLists.txt|   1 +
 .../Checkers/SetgidSetuidOrderChecker.cpp | 196 ++
 .../system-header-simulator-setgid-setuid.h   |  15 ++
 clang/test/Analysis/setgid-setuid-order.c | 170 +++
 6 files changed, 415 insertions(+)
 create mode 100644 
clang/lib/StaticAnalyzer/Checkers/SetgidSetuidOrderChecker.cpp
 create mode 100644 
clang/test/Analysis/Inputs/system-header-simulator-setgid-setuid.h
 create mode 100644 clang/test/Analysis/setgid-setuid-order.c

diff --git a/clang/docs/analyzer/checkers.rst b/clang/docs/analyzer/checkers.rst
index 0d87df36ced0e..d0c0c7a535c62 100644
--- a/clang/docs/analyzer/checkers.rst
+++ b/clang/docs/analyzer/checkers.rst
@@ -1179,6 +1179,34 @@ security.insecureAPI.DeprecatedOrUnsafeBufferHandling (C)
strncpy(buf, "a", 1); // warn
  }
 
+security.SetgidSetuidOrder (C)
+""
+When dropping user-level and group-level privileges in a program by using
+``setuid`` and ``setgid`` calls, it is important to reset the group-level
+privileges (with ``setgid``) first. Function ``setgid`` will likely fail if
+the superuser privileges are already dropped.
+
+The checker checks for sequences of ``setuid(getuid())`` and
+``setgid(getgid())`` calls (in this order). If such a sequence is found and
+there is no other privilege-changing function call (``seteuid``, ``setreuid``,
+``setresuid`` and the GID versions of these) in between, a warning is
+generated. The checker finds only exactly ``setuid(getuid())`` calls (and the
+GID versions), not for example if the result of ``getuid()`` is stored in a
+variable.
+
+This check corresponds to SEI CERT Rule `POS36-C 
`_.
+
+.. code-block:: c
+
+ void test1() {
+   if (setuid(getuid()) == -1) {
+ /* handle error condition */
+   }
+   if (setgid(getgid()) == -1) { // warn
+ /* handle error condition */
+   }
+ }
+
 .. _unix-checkers:
 
 unix
diff --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td 
b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
index 520286b57c9fd..cc954828901af 100644
--- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -1011,6 +1011,11 @@ def FloatLoopCounter : Checker<"FloatLoopCounter">,
   Dependencies<[SecuritySyntaxChecker]>,
   Documentation;
 
+def SetgidSetuidOrderChecker : Checker<"SetgidSetuidOrder">,
+  HelpText<"Warn on possible reversed order of 'setgid(getgid()))' and 
'setuid(getuid())' (CERT: "
+   "POS36-C)">,
+  Documentation;
+
 } // end "security"
 
 let ParentPackage = ENV in {
diff --git a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt 
b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
index 4443ffd092938..45d3788f105dc 100644
--- a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
+++ b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
@@ -103,6 +103,7 @@ add_clang_library(clangStaticAnalyzerCheckers
   ReturnUndefChecker.cpp
   ReturnValueChecker.cpp
   RunLoopAutoreleaseLeakChecker.cpp
+  SetgidSetuidOrderChecker.cpp
   SimpleStreamChecker.cpp
   SmartPtrChecker.cpp
   SmartPtrModeling.cpp
diff --git a/clang/lib/StaticAnalyzer/Checkers/SetgidSetuidOrderChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/SetgidSetuidOrderChecker.cpp
new file mode 100644
index 0..11cc748cb40b1
--- /dev/null
+++ b/clang/lib/StaticAnalyzer/Checkers/SetgidSetuidOrderChecker.cpp
@@ -0,0 +1,196 @@
+//===-- ChrootChecker.cpp - chroot usage checks 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines chroot checker, which checks improper use of chroot.
+//
+//===--===//
+
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include

[clang] [clang][analyzer] Add checker 'Security.SetgidSetuidOrder'. (PR #91445)

2024-05-08 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang-static-analyzer-1

@llvm/pr-subscribers-clang

Author: Balázs Kéri (balazske)


Changes



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


6 Files Affected:

- (modified) clang/docs/analyzer/checkers.rst (+28) 
- (modified) clang/include/clang/StaticAnalyzer/Checkers/Checkers.td (+5) 
- (modified) clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt (+1) 
- (added) clang/lib/StaticAnalyzer/Checkers/SetgidSetuidOrderChecker.cpp (+196) 
- (added) clang/test/Analysis/Inputs/system-header-simulator-setgid-setuid.h 
(+15) 
- (added) clang/test/Analysis/setgid-setuid-order.c (+170) 


``diff
diff --git a/clang/docs/analyzer/checkers.rst b/clang/docs/analyzer/checkers.rst
index 0d87df36ced0e..d0c0c7a535c62 100644
--- a/clang/docs/analyzer/checkers.rst
+++ b/clang/docs/analyzer/checkers.rst
@@ -1179,6 +1179,34 @@ security.insecureAPI.DeprecatedOrUnsafeBufferHandling (C)
strncpy(buf, "a", 1); // warn
  }
 
+security.SetgidSetuidOrder (C)
+""
+When dropping user-level and group-level privileges in a program by using
+``setuid`` and ``setgid`` calls, it is important to reset the group-level
+privileges (with ``setgid``) first. Function ``setgid`` will likely fail if
+the superuser privileges are already dropped.
+
+The checker checks for sequences of ``setuid(getuid())`` and
+``setgid(getgid())`` calls (in this order). If such a sequence is found and
+there is no other privilege-changing function call (``seteuid``, ``setreuid``,
+``setresuid`` and the GID versions of these) in between, a warning is
+generated. The checker finds only exactly ``setuid(getuid())`` calls (and the
+GID versions), not for example if the result of ``getuid()`` is stored in a
+variable.
+
+This check corresponds to SEI CERT Rule `POS36-C 
`_.
+
+.. code-block:: c
+
+ void test1() {
+   if (setuid(getuid()) == -1) {
+ /* handle error condition */
+   }
+   if (setgid(getgid()) == -1) { // warn
+ /* handle error condition */
+   }
+ }
+
 .. _unix-checkers:
 
 unix
diff --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td 
b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
index 520286b57c9fd..cc954828901af 100644
--- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -1011,6 +1011,11 @@ def FloatLoopCounter : Checker<"FloatLoopCounter">,
   Dependencies<[SecuritySyntaxChecker]>,
   Documentation;
 
+def SetgidSetuidOrderChecker : Checker<"SetgidSetuidOrder">,
+  HelpText<"Warn on possible reversed order of 'setgid(getgid()))' and 
'setuid(getuid())' (CERT: "
+   "POS36-C)">,
+  Documentation;
+
 } // end "security"
 
 let ParentPackage = ENV in {
diff --git a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt 
b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
index 4443ffd092938..45d3788f105dc 100644
--- a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
+++ b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
@@ -103,6 +103,7 @@ add_clang_library(clangStaticAnalyzerCheckers
   ReturnUndefChecker.cpp
   ReturnValueChecker.cpp
   RunLoopAutoreleaseLeakChecker.cpp
+  SetgidSetuidOrderChecker.cpp
   SimpleStreamChecker.cpp
   SmartPtrChecker.cpp
   SmartPtrModeling.cpp
diff --git a/clang/lib/StaticAnalyzer/Checkers/SetgidSetuidOrderChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/SetgidSetuidOrderChecker.cpp
new file mode 100644
index 0..11cc748cb40b1
--- /dev/null
+++ b/clang/lib/StaticAnalyzer/Checkers/SetgidSetuidOrderChecker.cpp
@@ -0,0 +1,196 @@
+//===-- ChrootChecker.cpp - chroot usage checks 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines chroot checker, which checks improper use of chroot.
+//
+//===--===//
+
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
+
+using namespace clang;
+using namespace ento;
+
+namespace {
+
+class SetgidSetuidOrderChecker
+: public Checker {
+  const BugType BT_WrongRevocationOrder{
+ 

[clang] [Coverage] Rework !SystemHeadersCoverage (PR #91446)

2024-05-08 Thread NAKAMURA Takumi via cfe-commits

https://github.com/chapuni created 
https://github.com/llvm/llvm-project/pull/91446

- Introduce `LeafExprSet`,
  - Suppress traversing LAnd and LOr expr under system headers.
  - Handle LAnd and LOr as instrumented leaves to override 
`!isInstrumentedCondition(C)`.
- Replace Loc with FileLoc if it is expanded with system headers.

Fixes #78920

>From d3ee2d086d07ce0803117ec9fa16ac72801619c7 Mon Sep 17 00:00:00 2001
From: NAKAMURA Takumi 
Date: Thu, 2 May 2024 09:36:39 +0900
Subject: [PATCH] [Coverage] Rework !SystemHeadersCoverage

- Introduce `LeafExprSet`,
  - Suppress traversing LAnd and LOr expr under system headers.
  - Handle LAnd and LOr as instrumented leaves to override
`!isInstrumentedCondition(C)`.
- Replace Loc with FileLoc if it is expanded with system headers.

Fixes #78920
---
 clang/lib/CodeGen/CoverageMappingGen.cpp  | 48 +++---
 .../CoverageMapping/mcdc-system-headers.cpp   | 50 +++
 2 files changed, 92 insertions(+), 6 deletions(-)
 create mode 100644 clang/test/CoverageMapping/mcdc-system-headers.cpp

diff --git a/clang/lib/CodeGen/CoverageMappingGen.cpp 
b/clang/lib/CodeGen/CoverageMappingGen.cpp
index 71215da362d3d..15d7199e95b0f 100644
--- a/clang/lib/CodeGen/CoverageMappingGen.cpp
+++ b/clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -17,6 +17,7 @@
 #include "clang/Basic/FileManager.h"
 #include "clang/Frontend/FrontendDiagnostic.h"
 #include "clang/Lex/Lexer.h"
+#include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/SmallSet.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ProfileData/Coverage/CoverageMapping.h"
@@ -339,16 +340,26 @@ class CoverageMappingBuilder {
 
 llvm::SmallSet Visited;
 SmallVector, 8> FileLocs;
-for (const auto &Region : SourceRegions) {
+for (auto &Region : SourceRegions) {
   SourceLocation Loc = Region.getBeginLoc();
+
+  // Replace Loc with FileLoc if it is expanded with system headers.
+  if (!SystemHeadersCoverage && SM.isInSystemMacro(Loc)) {
+auto BeginLoc = SM.getSpellingLoc(Loc);
+auto EndLoc = SM.getSpellingLoc(Region.getEndLoc());
+if (SM.isWrittenInSameFile(BeginLoc, EndLoc)) {
+  Loc = SM.getFileLoc(Loc);
+  Region.setStartLoc(Loc);
+  Region.setEndLoc(SM.getFileLoc(Region.getEndLoc()));
+}
+  }
+
   FileID File = SM.getFileID(Loc);
   if (!Visited.insert(File).second)
 continue;
 
-  // Do not map FileID's associated with system headers unless collecting
-  // coverage from system headers is explicitly enabled.
-  if (!SystemHeadersCoverage && 
SM.isInSystemHeader(SM.getSpellingLoc(Loc)))
-continue;
+  assert(SystemHeadersCoverage ||
+ !SM.isInSystemHeader(SM.getSpellingLoc(Loc)));
 
   unsigned Depth = 0;
   for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
@@ -821,6 +832,10 @@ struct CounterCoverageMappingBuilder
   /// A stack of currently live regions.
   llvm::SmallVector RegionStack;
 
+  /// Set if the Expr should be handled as a leaf even if it is kind of binary
+  /// logical ops (&&, ||).
+  llvm::DenseSet LeafExprSet;
+
   /// An object to manage MCDC regions.
   MCDCCoverageBuilder MCDCBuilder;
 
@@ -1043,7 +1058,10 @@ struct CounterCoverageMappingBuilder
 // region onto RegionStack but immediately pop it (which adds it to the
 // function's SourceRegions) because it doesn't apply to any other source
 // code other than the Condition.
-if (CodeGenFunction::isInstrumentedCondition(C)) {
+// With !SystemHeadersCoverage, binary logical ops in system headers may be
+// treated as instrumentable conditions.
+if (CodeGenFunction::isInstrumentedCondition(C) ||
+LeafExprSet.count(CodeGenFunction::stripCond(C))) {
   mcdc::Parameters BranchParams;
   mcdc::ConditionID ID = MCDCBuilder.getCondID(C);
   if (ID >= 0)
@@ -2064,7 +2082,20 @@ struct CounterCoverageMappingBuilder
 createDecisionRegion(E, DecisionParams);
   }
 
+  /// Check if E belongs to system headers.
+  bool isExprInSystemHeader(const BinaryOperator *E) const {
+return (!SystemHeadersCoverage &&
+SM.isInSystemHeader(SM.getSpellingLoc(E->getOperatorLoc())) &&
+SM.isInSystemHeader(SM.getSpellingLoc(E->getBeginLoc())) &&
+SM.isInSystemHeader(SM.getSpellingLoc(E->getEndLoc(;
+  }
+
   void VisitBinLAnd(const BinaryOperator *E) {
+if (isExprInSystemHeader(E)) {
+  LeafExprSet.insert(E);
+  return;
+}
+
 bool IsRootNode = MCDCBuilder.isIdle();
 
 // Keep track of Binary Operator and assign MCDC condition IDs.
@@ -2119,6 +2150,11 @@ struct CounterCoverageMappingBuilder
   }
 
   void VisitBinLOr(const BinaryOperator *E) {
+if (isExprInSystemHeader(E)) {
+  LeafExprSet.insert(E);
+  return;
+}
+
 bool IsRootNode = MCDCBuilder.isIdle();
 
 // Keep track of Binary Operator and assign MCDC condition IDs.
diff --git a/clang/test/CoverageMapping/mcdc-system-

[clang] [Coverage] Rework !SystemHeadersCoverage (PR #91446)

2024-05-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-codegen

Author: NAKAMURA Takumi (chapuni)


Changes

- Introduce `LeafExprSet`,
  - Suppress traversing LAnd and LOr expr under system headers.
  - Handle LAnd and LOr as instrumented leaves to override 
`!isInstrumentedCondition(C)`.
- Replace Loc with FileLoc if it is expanded with system headers.

Fixes #78920

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


2 Files Affected:

- (modified) clang/lib/CodeGen/CoverageMappingGen.cpp (+42-6) 
- (added) clang/test/CoverageMapping/mcdc-system-headers.cpp (+50) 


``diff
diff --git a/clang/lib/CodeGen/CoverageMappingGen.cpp 
b/clang/lib/CodeGen/CoverageMappingGen.cpp
index 71215da362d3d..15d7199e95b0f 100644
--- a/clang/lib/CodeGen/CoverageMappingGen.cpp
+++ b/clang/lib/CodeGen/CoverageMappingGen.cpp
@@ -17,6 +17,7 @@
 #include "clang/Basic/FileManager.h"
 #include "clang/Frontend/FrontendDiagnostic.h"
 #include "clang/Lex/Lexer.h"
+#include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/SmallSet.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ProfileData/Coverage/CoverageMapping.h"
@@ -339,16 +340,26 @@ class CoverageMappingBuilder {
 
 llvm::SmallSet Visited;
 SmallVector, 8> FileLocs;
-for (const auto &Region : SourceRegions) {
+for (auto &Region : SourceRegions) {
   SourceLocation Loc = Region.getBeginLoc();
+
+  // Replace Loc with FileLoc if it is expanded with system headers.
+  if (!SystemHeadersCoverage && SM.isInSystemMacro(Loc)) {
+auto BeginLoc = SM.getSpellingLoc(Loc);
+auto EndLoc = SM.getSpellingLoc(Region.getEndLoc());
+if (SM.isWrittenInSameFile(BeginLoc, EndLoc)) {
+  Loc = SM.getFileLoc(Loc);
+  Region.setStartLoc(Loc);
+  Region.setEndLoc(SM.getFileLoc(Region.getEndLoc()));
+}
+  }
+
   FileID File = SM.getFileID(Loc);
   if (!Visited.insert(File).second)
 continue;
 
-  // Do not map FileID's associated with system headers unless collecting
-  // coverage from system headers is explicitly enabled.
-  if (!SystemHeadersCoverage && 
SM.isInSystemHeader(SM.getSpellingLoc(Loc)))
-continue;
+  assert(SystemHeadersCoverage ||
+ !SM.isInSystemHeader(SM.getSpellingLoc(Loc)));
 
   unsigned Depth = 0;
   for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
@@ -821,6 +832,10 @@ struct CounterCoverageMappingBuilder
   /// A stack of currently live regions.
   llvm::SmallVector RegionStack;
 
+  /// Set if the Expr should be handled as a leaf even if it is kind of binary
+  /// logical ops (&&, ||).
+  llvm::DenseSet LeafExprSet;
+
   /// An object to manage MCDC regions.
   MCDCCoverageBuilder MCDCBuilder;
 
@@ -1043,7 +1058,10 @@ struct CounterCoverageMappingBuilder
 // region onto RegionStack but immediately pop it (which adds it to the
 // function's SourceRegions) because it doesn't apply to any other source
 // code other than the Condition.
-if (CodeGenFunction::isInstrumentedCondition(C)) {
+// With !SystemHeadersCoverage, binary logical ops in system headers may be
+// treated as instrumentable conditions.
+if (CodeGenFunction::isInstrumentedCondition(C) ||
+LeafExprSet.count(CodeGenFunction::stripCond(C))) {
   mcdc::Parameters BranchParams;
   mcdc::ConditionID ID = MCDCBuilder.getCondID(C);
   if (ID >= 0)
@@ -2064,7 +2082,20 @@ struct CounterCoverageMappingBuilder
 createDecisionRegion(E, DecisionParams);
   }
 
+  /// Check if E belongs to system headers.
+  bool isExprInSystemHeader(const BinaryOperator *E) const {
+return (!SystemHeadersCoverage &&
+SM.isInSystemHeader(SM.getSpellingLoc(E->getOperatorLoc())) &&
+SM.isInSystemHeader(SM.getSpellingLoc(E->getBeginLoc())) &&
+SM.isInSystemHeader(SM.getSpellingLoc(E->getEndLoc(;
+  }
+
   void VisitBinLAnd(const BinaryOperator *E) {
+if (isExprInSystemHeader(E)) {
+  LeafExprSet.insert(E);
+  return;
+}
+
 bool IsRootNode = MCDCBuilder.isIdle();
 
 // Keep track of Binary Operator and assign MCDC condition IDs.
@@ -2119,6 +2150,11 @@ struct CounterCoverageMappingBuilder
   }
 
   void VisitBinLOr(const BinaryOperator *E) {
+if (isExprInSystemHeader(E)) {
+  LeafExprSet.insert(E);
+  return;
+}
+
 bool IsRootNode = MCDCBuilder.isIdle();
 
 // Keep track of Binary Operator and assign MCDC condition IDs.
diff --git a/clang/test/CoverageMapping/mcdc-system-headers.cpp 
b/clang/test/CoverageMapping/mcdc-system-headers.cpp
new file mode 100644
index 0..829b8170fc62a
--- /dev/null
+++ b/clang/test/CoverageMapping/mcdc-system-headers.cpp
@@ -0,0 +1,50 @@
+// RUN: %clang_cc1 -std=c++11 -fprofile-instrument=clang -fcoverage-mapping 
-dump-coverage-mapping  -fcoverage-mcdc -mllvm -system-headers-coverage 
-emit-llvm-only -o - %s | FileCheck %s --check-prefixes=CHECK,W_SYS
+// RUN: %clang_cc1 -std=c++11 -fprofile-inst

[clang] [clang][analyzer] Add checker 'Security.SetgidSetuidOrder'. (PR #91445)

2024-05-08 Thread Balázs Kéri via cfe-commits

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

From d839faf7a30851a172d812137b30635c741870f0 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Bal=C3=A1zs=20K=C3=A9ri?= 
Date: Wed, 8 May 2024 10:10:24 +0200
Subject: [PATCH 1/2] [clang][analyzer] Add checker
 'Security.SetgidSetuidOrder'.

---
 clang/docs/analyzer/checkers.rst  |  28 +++
 .../clang/StaticAnalyzer/Checkers/Checkers.td |   5 +
 .../StaticAnalyzer/Checkers/CMakeLists.txt|   1 +
 .../Checkers/SetgidSetuidOrderChecker.cpp | 196 ++
 .../system-header-simulator-setgid-setuid.h   |  15 ++
 clang/test/Analysis/setgid-setuid-order.c | 170 +++
 6 files changed, 415 insertions(+)
 create mode 100644 
clang/lib/StaticAnalyzer/Checkers/SetgidSetuidOrderChecker.cpp
 create mode 100644 
clang/test/Analysis/Inputs/system-header-simulator-setgid-setuid.h
 create mode 100644 clang/test/Analysis/setgid-setuid-order.c

diff --git a/clang/docs/analyzer/checkers.rst b/clang/docs/analyzer/checkers.rst
index 0d87df36ced0e..d0c0c7a535c62 100644
--- a/clang/docs/analyzer/checkers.rst
+++ b/clang/docs/analyzer/checkers.rst
@@ -1179,6 +1179,34 @@ security.insecureAPI.DeprecatedOrUnsafeBufferHandling (C)
strncpy(buf, "a", 1); // warn
  }
 
+security.SetgidSetuidOrder (C)
+""
+When dropping user-level and group-level privileges in a program by using
+``setuid`` and ``setgid`` calls, it is important to reset the group-level
+privileges (with ``setgid``) first. Function ``setgid`` will likely fail if
+the superuser privileges are already dropped.
+
+The checker checks for sequences of ``setuid(getuid())`` and
+``setgid(getgid())`` calls (in this order). If such a sequence is found and
+there is no other privilege-changing function call (``seteuid``, ``setreuid``,
+``setresuid`` and the GID versions of these) in between, a warning is
+generated. The checker finds only exactly ``setuid(getuid())`` calls (and the
+GID versions), not for example if the result of ``getuid()`` is stored in a
+variable.
+
+This check corresponds to SEI CERT Rule `POS36-C 
`_.
+
+.. code-block:: c
+
+ void test1() {
+   if (setuid(getuid()) == -1) {
+ /* handle error condition */
+   }
+   if (setgid(getgid()) == -1) { // warn
+ /* handle error condition */
+   }
+ }
+
 .. _unix-checkers:
 
 unix
diff --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td 
b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
index 520286b57c9fd..cc954828901af 100644
--- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -1011,6 +1011,11 @@ def FloatLoopCounter : Checker<"FloatLoopCounter">,
   Dependencies<[SecuritySyntaxChecker]>,
   Documentation;
 
+def SetgidSetuidOrderChecker : Checker<"SetgidSetuidOrder">,
+  HelpText<"Warn on possible reversed order of 'setgid(getgid()))' and 
'setuid(getuid())' (CERT: "
+   "POS36-C)">,
+  Documentation;
+
 } // end "security"
 
 let ParentPackage = ENV in {
diff --git a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt 
b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
index 4443ffd092938..45d3788f105dc 100644
--- a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
+++ b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
@@ -103,6 +103,7 @@ add_clang_library(clangStaticAnalyzerCheckers
   ReturnUndefChecker.cpp
   ReturnValueChecker.cpp
   RunLoopAutoreleaseLeakChecker.cpp
+  SetgidSetuidOrderChecker.cpp
   SimpleStreamChecker.cpp
   SmartPtrChecker.cpp
   SmartPtrModeling.cpp
diff --git a/clang/lib/StaticAnalyzer/Checkers/SetgidSetuidOrderChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/SetgidSetuidOrderChecker.cpp
new file mode 100644
index 0..11cc748cb40b1
--- /dev/null
+++ b/clang/lib/StaticAnalyzer/Checkers/SetgidSetuidOrderChecker.cpp
@@ -0,0 +1,196 @@
+//===-- ChrootChecker.cpp - chroot usage checks 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines chroot checker, which checks improper use of chroot.
+//
+//===--===//
+
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include 

[clang] [llvm] [AArch64] Add support for Qualcomm Oryon processor (PR #91022)

2024-05-08 Thread Jonathan Thackray via cfe-commits

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


[clang] [Clang][Sema] access checking of friend declaration should not be delayed (PR #91430)

2024-05-08 Thread via cfe-commits


@@ -1477,8 +1477,16 @@ static Sema::AccessResult CheckAccess(Sema &S, 
SourceLocation Loc,
   //   void foo(A::private_type);

cor3ntin wrote:

The comment above needs tweaking

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


[clang] [Clang][Sema] access checking of friend declaration should not be delayed (PR #91430)

2024-05-08 Thread via cfe-commits


@@ -229,6 +229,8 @@ void Scope::dumpImpl(raw_ostream &OS) const {
   {ClassInheritanceScope, "ClassInheritanceScope"},
   {CatchScope, "CatchScope"},
   {OpenACCComputeConstructScope, "OpenACCComputeConstructScope"},
+  {TypeAliasScope, "TypeAliasScope"},

cor3ntin wrote:

Note: Drive by fix

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


[clang] [Clang][Sema] access checking of friend declaration should not be delayed (PR #91430)

2024-05-08 Thread via cfe-commits


@@ -1477,8 +1477,16 @@ static Sema::AccessResult CheckAccess(Sema &S, 
SourceLocation Loc,
   //   void foo(A::private_type);
   //   void B::foo(A::private_type);
   if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
-S.DelayedDiagnostics.add(DelayedDiagnostic::makeAccess(Loc, Entity));
-return Sema::AR_delayed;
+Scope *TS = S.getCurScope();
+bool IsFriendDeclaration = false;
+while (TS && !IsFriendDeclaration) {
+  IsFriendDeclaration = TS->isFriendScope();
+  TS = TS->getParent();
+}
+if (!IsFriendDeclaration) {
+  S.DelayedDiagnostics.add(DelayedDiagnostic::makeAccess(Loc, Entity));
+  return Sema::AR_delayed;
+}

cor3ntin wrote:

We might want to quote the standard
https://eel.is/c++draft/class.friend#9

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


[clang] [Clang][Sema] access checking of friend declaration should not be delayed (PR #91430)

2024-05-08 Thread via cfe-commits

cor3ntin wrote:

Can you add a changelog entry?

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


[clang] [clang] Add examples from [dcl.init.aggr] to C++ conformance tests (PR #91435)

2024-05-08 Thread via cfe-commits


@@ -0,0 +1,294 @@
+// RUN:  %clang_cc1 -std=c++2c -verify %s
+

cor3ntin wrote:

For future reference, can you say this is testing c++2c and maybe quote a paper 
number (latest working draft?)

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


[clang] [clang] Add examples from [dcl.init.aggr] to C++ conformance tests (PR #91435)

2024-05-08 Thread via cfe-commits

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


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


[clang] [clang][NFC] Add examples from [dcl.init.aggr] to C++ conformance tests (PR #91435)

2024-05-08 Thread via cfe-commits

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


[clang] [clang][NFC] Add examples from [dcl.init.aggr] to C++ conformance tests (PR #91435)

2024-05-08 Thread Vlad Serebrennikov via cfe-commits

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


[clang] [clang][NFC] Add examples from [dcl.init.aggr] to C++ conformance tests (PR #91435)

2024-05-08 Thread Vlad Serebrennikov via cfe-commits


@@ -0,0 +1,294 @@
+// RUN:  %clang_cc1 -std=c++2c -verify %s
+

Endilll wrote:

Any reference would become outdated the moment this file is touched next time, 
so I added one to the PR description, so it makes it into the commit message.

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


[clang] 602df27 - [Flang] RFC: Add support for -w option 1/n (#90420)

2024-05-08 Thread via cfe-commits

Author: Kiran Chandramohan
Date: 2024-05-08T10:00:48+01:00
New Revision: 602df270a9bfcb52980a93c85eb615c0d91eba0c

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

LOG: [Flang] RFC: Add support for -w option 1/n (#90420)

Add support for the -w option to switch OFF all Flang
warnings. This patch only supports switching OFF the
frontend warnings.

TODO : Support for MLIR, LLVM and Driver warnings.
TODO : Support interactions between -w, -pedantic, -Wall

Added: 
flang/test/Driver/w-option.f90

Modified: 
clang/include/clang/Driver/Options.td
clang/lib/Driver/ToolChains/Flang.cpp
flang/include/flang/Frontend/CompilerInvocation.h
flang/lib/Frontend/CompilerInvocation.cpp

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 2c319ba38a298..734ae7833f5c3 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -5703,7 +5703,7 @@ def whatsloaded : Flag<["-"], "whatsloaded">;
 def why_load : Flag<["-"], "why_load">;
 def whyload : Flag<["-"], "whyload">, Alias;
 def w : Flag<["-"], "w">, HelpText<"Suppress all warnings">,
-  Visibility<[ClangOption, CC1Option]>,
+  Visibility<[ClangOption, CC1Option, FlangOption, FC1Option]>,
   MarshallingInfoFlag>;
 def x : JoinedOrSeparate<["-"], "x">,
 Flags<[NoXarchOption]>,

diff  --git a/clang/lib/Driver/ToolChains/Flang.cpp 
b/clang/lib/Driver/ToolChains/Flang.cpp
index 8955b9fb653c2..436a9c418a5f9 100644
--- a/clang/lib/Driver/ToolChains/Flang.cpp
+++ b/clang/lib/Driver/ToolChains/Flang.cpp
@@ -748,6 +748,10 @@ void Flang::ConstructJob(Compilation &C, const JobAction 
&JA,
   // Add other compile options
   addOtherOptions(Args, CmdArgs);
 
+  // Disable all warnings
+  // TODO: Handle interactions between -w, -pedantic, -Wall, -WOption
+  Args.AddLastArg(CmdArgs, options::OPT_w);
+
   // Forward flags for OpenMP. We don't do this if the current action is an
   // device offloading action other than OpenMP.
   if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,

diff  --git a/flang/include/flang/Frontend/CompilerInvocation.h 
b/flang/include/flang/Frontend/CompilerInvocation.h
index 4924d090eaf9c..0fefaecfe4f06 100644
--- a/flang/include/flang/Frontend/CompilerInvocation.h
+++ b/flang/include/flang/Frontend/CompilerInvocation.h
@@ -114,8 +114,10 @@ class CompilerInvocation : public CompilerInvocationBase {
   // Fortran Dialect options
   Fortran::common::IntrinsicTypeDefaultKinds defaultKinds;
 
+  // Fortran Warning options
   bool enableConformanceChecks = false;
   bool enableUsageChecks = false;
+  bool disableWarnings = false;
 
   /// Used in e.g. unparsing to dump the analyzed rather than the original
   /// parse-tree objects.
@@ -197,6 +199,9 @@ class CompilerInvocation : public CompilerInvocationBase {
   bool &getEnableUsageChecks() { return enableUsageChecks; }
   const bool &getEnableUsageChecks() const { return enableUsageChecks; }
 
+  bool &getDisableWarnings() { return disableWarnings; }
+  const bool &getDisableWarnings() const { return disableWarnings; }
+
   Fortran::parser::AnalyzedObjectsAsFortran &getAsFortran() {
 return asFortran;
   }
@@ -226,6 +231,9 @@ class CompilerInvocation : public CompilerInvocationBase {
   // Enables the usage checks
   void setEnableUsageChecks() { enableUsageChecks = true; }
 
+  // Disables all Warnings
+  void setDisableWarnings() { disableWarnings = true; }
+
   /// Useful setters
   void setArgv0(const char *dir) { argv0 = dir; }
 

diff  --git a/flang/lib/Frontend/CompilerInvocation.cpp 
b/flang/lib/Frontend/CompilerInvocation.cpp
index f1b7b53975398..4318286e74152 100644
--- a/flang/lib/Frontend/CompilerInvocation.cpp
+++ b/flang/lib/Frontend/CompilerInvocation.cpp
@@ -975,6 +975,11 @@ static bool parseDialectArgs(CompilerInvocation &res, 
llvm::opt::ArgList &args,
 res.setEnableConformanceChecks();
 res.setEnableUsageChecks();
   }
+
+  // -w
+  if (args.hasArg(clang::driver::options::OPT_w))
+res.setDisableWarnings();
+
   // -std=f2018
   // TODO: Set proper options when more fortran standards
   // are supported.
@@ -1403,6 +1408,11 @@ void CompilerInvocation::setFortranOpts() {
 
   if (getEnableUsageChecks())
 fortranOptions.features.WarnOnAllUsage();
+
+  if (getDisableWarnings()) {
+fortranOptions.features.DisableAllNonstandardWarnings();
+fortranOptions.features.DisableAllUsageWarnings();
+  }
 }
 
 std::unique_ptr

diff  --git a/flang/test/Driver/w-option.f90 b/flang/test/Driver/w-option.f90
new file mode 100644
index 0..e34cddaab373a
--- /dev/null
+++ b/flang/test/Driver/w-option.f90
@@ -0,0 +1,31 @@
+! Test the default setting. Emit warnings only.
+! RUN: %flang -c %s 2>&1 | FileCheck %s -check-prefix=DEFAULT

[clang] [flang] [Flang] RFC: Add support for -w option 1/n (PR #90420)

2024-05-08 Thread Kiran Chandramohan via cfe-commits

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


[clang] [Clang][Sema] access checking of friend declaration should not be delayed (PR #91430)

2024-05-08 Thread Qizhi Hu via cfe-commits

jcsxky wrote:

> Can you add a changelog entry?

Ah, I forgot that! will be added when applying other reviews.

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


[clang] [llvm] [MC,clang,llvm-readobj,yaml2obj] Support CREL relocation format (PR #91280)

2024-05-08 Thread Peter Smith via cfe-commits

smithp35 wrote:

I will take a look, but may take me a while to go through it. Some very quick 
comments:
* Would `--enable-experimental-crel` be a better name than 
`--experimental-crel` that makes it clear that the option is just an unlock of 
another flag, and not a flag in of itself?
* I agree that the section type should be in the generic range. While it is in 
the experimental stage it could be possible to put it in  SHT_LOOS SHT_HIOS 
range temporarily. When there is an official ELF code in the generic range it 
could be changed (forcing a recompile, or a migration script), or just have the 
LLVM tools implicitly convert from the old code to the new. For the 
experimental range.
* While I can give a personal opinion. This will touch multiple components of 
LLVM each with their own code-owners. Will probably need a signal, either on 
the review or via discourse threads that the community is happy to go ahead 
with the addition of CREL. 

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


[clang] [llvm] [BPF] Fix linking issues in static map initializers (PR #91310)

2024-05-08 Thread Nick Zavaritsky via cfe-commits


@@ -1950,8 +1950,22 @@ ConstantLValueEmitter::tryEmitBase(const 
APValue::LValueBase &base) {
 if (D->hasAttr())
   return CGM.GetWeakRefReference(D).getPointer();
 
-if (auto FD = dyn_cast(D))
-  return CGM.GetAddrOfFunction(FD);
+if (auto FD = dyn_cast(D)) {
+  auto *C = CGM.GetAddrOfFunction(FD);
+
+  // we don't normally emit debug info for extern fns referenced via
+  // variable initialisers; BPF needs it since it generates BTF from
+  // debug info and bpftool demands BTF for every symbol linked
+  if (CGM.getTarget().getTriple().isBPF() && FD->getStorageClass() == 
SC_Extern) {

mejedi wrote:

@efriedma-quic Thank you for insightful comments! As a newbie, I need more 
guidance.

It is pretty much clear that `allowDebugInfoForExternalRef` is a preferred way 
to check whether we should emit additional debug info. It is currently only 
overriden by BPF target and is being used for exact same purpose we have here.

I need help getting up to speed irt. `CompleteExternalDeclaration` proposal. 
Having grepped through the code, I can see that BPF faced the same challenge 
with `extern` variables. At the moment, there's a vector of `VariableDecl`s 
populated in `SemaDecl.cpp` and later used to attach debug info to variables.

A different mechanism is applied to discovering `extern` functions in need for 
debug info (prior to my patch, `extern` functions referenced through code were 
handled). This is accomplished by code in `CGExpr.cpp`. I am proposing a 
similar extension in `CGExprConstant.cpp`.

Would you like to have functions on `ExternalDeclarations` list instead?

What would be a good spot to get ahold of `FunctionDecl` to put it on 
`ExternalDeclarations` list?

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


[clang] Revert "Revert "[OpenMP][TR12] change property of map-type modifier."… (PR #91141)

2024-05-08 Thread Tom Weaver via cfe-commits

TomWeaver18 wrote:

Greetings and hello from the UK!

 it looks as though this commit caused a test failure on the following build 
bot, is anyone able to take a look see?

https://lab.llvm.org/buildbot/#/builders/139/builds/65066

Will give it an hour for a reply before looking at a revert.

Have a great day all.



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


[clang] [clang] Implement provisional wording for CWG2398 regarding packs (PR #90820)

2024-05-08 Thread via cfe-commits


@@ -2552,7 +2553,7 @@ DeduceTemplateArguments(Sema &S, TemplateParameterList 
*TemplateParams,
 ArrayRef As,
 TemplateDeductionInfo &Info,
 SmallVectorImpl &Deduced,
-bool NumberOfArgumentsMustMatch) {
+bool NumberOfArgumentsMustMatch, bool Swapped) {

cor3ntin wrote:

I think this needs a comment.
`Swapped` should be defaulted and have a better name.
Maybe `ForPartialOrderingOfDeducedTemplateTemplateArgument`

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


[clang] [clang] Implement provisional wording for CWG2398 regarding packs (PR #90820)

2024-05-08 Thread via cfe-commits


@@ -2583,8 +2584,11 @@ DeduceTemplateArguments(Sema &S, TemplateParameterList 
*TemplateParams,
 return TemplateDeductionResult::MiscellaneousDeductionFailure;
 
   // Perform deduction for this Pi/Ai pair.
-  if (auto Result = DeduceTemplateArguments(S, TemplateParams, P,
-As[ArgIdx], Info, Deduced);
+  TemplateArgument Pi = P, Ai = As[ArgIdx];
+  if (Swapped)
+std::swap(Pi, Ai);

cor3ntin wrote:

We might want a comment here too

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


[clang] [Clang] Fall back to DW_TAG_typedef for instantiation dependent template aliases (PR #90032)

2024-05-08 Thread Orlando Cazalet-Hyams via cfe-commits

OCHyams wrote:

Here's that issue - #91451.

Carlos pointed me to [bz44884](https://bugs.llvm.org/show_bug.cgi?id=44884) 
(#44229) which may be related

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


[clang] [clang] Enable C++17 relaxed template template argument matching by default (PR #89807)

2024-05-08 Thread Sam McCall via cfe-commits

sam-mccall wrote:

This patch introduced a crash on code that clang previously accepted (I'm not 
sure whether the code is correct).

The code is 
https://github.com/nvidia/stdexec/tree/467f4a68ee04f3bb4c35e7a5dd13a3419da160cb,
 building `test/stdexec/algos/adaptors/test_stopped_as_optional.cpp` crashes.


Errors prior to crash

```
third_party/stdexec/test/stdexec/algos/adaptors/test_stopped_as_optional.cpp:38:19:
 error: static assertion failed
   38 | static_assert(ex::sender_in);
  |   ^~~
third_party/stdexec/test/stdexec/algos/adaptors/test_stopped_as_optional.cpp:38:19:
 note: because 'ex::sender_in' evaluated to false
./third_party/stdexec/include/stdexec/execution.hpp:824:9: note: because 
'decltype(__impl, 
stdexec::__env::empty_env>()())' (aka 
'stdexec::_ERROR_, 
stdexec::_WITH_META_FUNCTION_T_, 
stdexec::_WITH_TYPES_, 
stdexec::__env::empty_env, 
stdexec::__q,
 stdexec::__q>>') does not satisfy 
'__valid_completion_signatures':
  824 | get_completion_signatures((_Sender&&) __sndr, (_Env&&) __env)
  | ^
./third_party/stdexec/include/stdexec/execution.hpp:273:5: note: because 
'stdexec::_ERROR_, 
stdexec::_WITH_META_FUNCTION_T_, 
stdexec::_WITH_TYPES_, 
stdexec::__env::empty_env, 
stdexec::__q,
 stdexec::__q>>' does not satisfy '__ok'
  273 | __ok<_Completions> && __is_instance_of<_Completions, 
completion_signatures>;
  | ^
./third_party/stdexec/include/stdexec/__detail/__meta.hpp:243:18: note: because 
'__same_as<__ok_t<_ERROR_<_BAD_SUBSTITUTION_<__mstring<76UL>{"The specified 
meta-function could not be evaluated with the types provided."}>, 
_WITH_META_FUNCTION_T_, 
_WITH_TYPES_<__sexpr<(lambda at 
./third_party/stdexec/include/stdexec/__detail/__basic_sender.hpp:594:18)>, 
empty_env, 
__q, 
__q > > >, __msuccess>' evaluated to 
false
  243 |   concept __ok = __same_as<__ok_t<_Arg>, __msuccess>;
  |  ^
./third_party/stdexec/include/stdexec/__detail/__concepts.hpp:51:23: note: 
because '__is_same(stdexec::_ERROR_, 
stdexec::_WITH_META_FUNCTION_T_, 
stdexec::_WITH_TYPES_, 
stdexec::__env::empty_env, 
stdexec::__q,
 stdexec::__q > >, int)' evaluated to 
false
   51 |   concept __same_as = __is_same(_Ap, _Bp);
  |   ^
third_party/stdexec/test/stdexec/algos/adaptors/test_stopped_as_optional.cpp:45:15:
 error: no matching function for call to object of type 'const 
__connect::connect_t'
   45 | auto op = ex::connect(std::move(snd), 
expect_value_receiver{std::optional{}});
  |   ^~~
./third_party/stdexec/include/stdexec/execution.hpp:1471:12: note: candidate 
template ignored: constraints not satisfied [with _Sender = 
__libcpp_remove_reference_t<__sexpr<(lambda at 
./third_party/stdexec/include/stdexec/__detail/__basic_sender.hpp:594:18)> &>, 
_Receiver = expect_value_receiver>]
 1471 |   auto operator()(_Sender&& __sndr, _Receiver&& __rcvr) const
  |^
./third_party/stdexec/include/stdexec/execution.hpp:1468:18: note: because 
'__connectable_with_tag_invoke, 
(anonymous namespace)::expect_value_receiver > >' evaluated to false
 1468 | requires __connectable_with_tag_invoke<_Sender, _Receiver>
  |  ^
./third_party/stdexec/include/stdexec/execution.hpp:1415:7: note: because 
'__connectable_with_tag_invoke_<__tfx_sender<__sexpr<(lambda at 
./third_party/stdexec/include/stdexec/__detail/__basic_sender.hpp:594:18)>, 
expect_value_receiver > >, (anonymous 
namespace)::expect_value_receiver 
> >' evaluated to false
 1415 |   __connectable_with_tag_invoke_<__tfx_sender<_Sender, _Receiver>, 
_Receiver>;
  |   ^
./third_party/stdexec/include/stdexec/execution.hpp:1409:7: note: because 
'sender_in, 
env_of_t > > >' evaluated to 
false
 1409 |   sender_in<_Sender, env_of_t<_Receiver>> && //
  |   ^
./third_party/stdexec/include/stdexec/execution.hpp:824:9: note: because 
'decltype(__impl, 
stdexec::__env::empty_env>()())' (aka 
'_ERROR_{"The 
given type cannot be used as a[...]"}>, 
stdexec::__error__::_WITH_SENDER_>>>, 
stdexec::__error__::_WITH_ENVIRONMENT_>') does not 
satisfy '__valid_completion_signatures':
  824 | get_completion_signatures((_Sender&&) __sndr, (_Env&&) __env)
  | ^
./third_party/stdexec/include/stdexec/execution.hpp:273:5: note: because 
'stdexec::_ERROR_, 
stdexec::__error__::_WITH_SENDER_>>>, 
stdexec::__error__::_WITH_ENVIRONMENT_>' does not 
satisfy '__ok'
  273 | __ok<_Completions> && __is_instance_of<_Completions, 
completion_signatures>;
  | ^
./third_party/stdexec/include/stdexec/__detail/__meta.hpp:243:18: note: because 
'__same_as<__ok_t<_ERROR_<_UNRECOGNIZED_SENDER_TYPE_<__mstring<134UL>{"The 
given type cannot be used as a sender with the given environment because the 
attempt to compute the completion signatures failed."}>, 
_WITH_SENDER_<__sexpr > > >, _WITH_ENVIRONMENT_ > >, 
__msuccess>' evaluated to false
 

[clang-tools-extra] aefad85 - [clangd] Fix data race surfaced in clangd-tsan buildbot

2024-05-08 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2024-05-08T12:00:54+02:00
New Revision: aefad851672e6dd17592895066a39aa5b388e5db

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

LOG: [clangd] Fix data race surfaced in clangd-tsan buildbot

We can have concurrent accesses to same PreambleData (e.g.
code-completion and ast-builds). Hence we need to
deep copy TargetOpts.

Added: 


Modified: 
clang-tools-extra/clangd/Preamble.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/Preamble.cpp 
b/clang-tools-extra/clangd/Preamble.cpp
index d5818e0ca309b..ecd490145dd3c 100644
--- a/clang-tools-extra/clangd/Preamble.cpp
+++ b/clang-tools-extra/clangd/Preamble.cpp
@@ -918,7 +918,9 @@ void PreamblePatch::apply(CompilerInvocation &CI) const {
   // no guarantees around using arbitrary options when reusing PCHs, and
   // 
diff erent target opts can result in crashes, see
   // ParsedASTTest.PreambleWithDifferentTarget.
-  CI.TargetOpts = Baseline->TargetOpts;
+  // Make sure this is a deep copy, as the same Baseline might be used
+  // concurrently.
+  *CI.TargetOpts = *Baseline->TargetOpts;
 
   // No need to map an empty file.
   if (PatchContents.empty())



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


[clang] Revert "Revert "[OpenMP][TR12] change property of map-type modifier."… (PR #91141)

2024-05-08 Thread Vitaly Buka via cfe-commits

vitalybuka wrote:

> Greetings and hello from the UK!
> 
> it looks as though this commit caused a test failure on the following build 
> bot, is anyone able to take a look see?
> 
> https://lab.llvm.org/buildbot/#/builders/139/builds/65066
> 
> Will give it an hour for a reply before looking at a revert.
> 
> Have a great day all.

I am not looking into this, and not sure if @jyu2-git 
revert is LGTM 

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


[clang] [Clang][Sema] Earlier type checking for builtin unary operators (PR #90500)

2024-05-08 Thread Krystian Stasiowski via cfe-commits

sdkrystian wrote:

Ping @shafik 

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


[clang] [clang] Enable C++17 relaxed template template argument matching by default (PR #89807)

2024-05-08 Thread via cfe-commits

cor3ntin wrote:

@sam-mccall Thanks! do you have a reduction? or at least a preprocessed source 
file we could reduce?

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


[clang] 341aecc - Revert "Revert "Revert "[OpenMP][TR12] change property of map-type modifier."… (#91141)"

2024-05-08 Thread via cfe-commits

Author: Weaver
Date: 2024-05-08T11:12:14+01:00
New Revision: 341aecc2dd0f6debcbe9f251a6d2e8a60d327eea

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

LOG: Revert "Revert "Revert "[OpenMP][TR12] change property of map-type 
modifier."… (#91141)"

This reverts commit a99ce615f19fec6fbb835490b89f53cba3cf9eff.

Caused test failure on following buildbot:
https://lab.llvm.org/buildbot/#/builders/139/builds/65066

Added: 


Modified: 
clang/include/clang/Basic/DiagnosticParseKinds.td
clang/lib/Parse/ParseOpenMP.cpp
clang/test/OpenMP/target_ast_print.cpp
clang/test/OpenMP/target_map_messages.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticParseKinds.td 
b/clang/include/clang/Basic/DiagnosticParseKinds.td
index 44bc4e0e130de..fdffb35ea0d95 100644
--- a/clang/include/clang/Basic/DiagnosticParseKinds.td
+++ b/clang/include/clang/Basic/DiagnosticParseKinds.td
@@ -1438,9 +1438,6 @@ def err_omp_decl_in_declare_simd_variant : Error<
 def err_omp_sink_and_source_iteration_not_allowd: Error<" '%0 
%select{sink:|source:}1' must be with '%select{omp_cur_iteration - 
1|omp_cur_iteration}1'">;
 def err_omp_unknown_map_type : Error<
   "incorrect map type, expected one of 'to', 'from', 'tofrom', 'alloc', 
'release', or 'delete'">;
-def err_omp_more_one_map_type : Error<"map type is already specified">;
-def note_previous_map_type_specified_here
-: Note<"map type '%0' is previous specified here">;
 def err_omp_unknown_map_type_modifier : Error<
   "incorrect map type modifier, expected one of: 'always', 'close', 'mapper'"
   "%select{|, 'present'|, 'present', 'iterator'}0%select{|, 'ompx_hold'}1">;
@@ -1448,8 +1445,6 @@ def err_omp_map_type_missing : Error<
   "missing map type">;
 def err_omp_map_type_modifier_missing : Error<
   "missing map type modifier">;
-def err_omp_map_modifier_specification_list : Error<
-  "empty modifier-specification-list is not allowed">;
 def err_omp_declare_simd_inbranch_notinbranch : Error<
   "unexpected '%0' clause, '%1' is specified already">;
 def err_omp_expected_clause_argument

diff  --git a/clang/lib/Parse/ParseOpenMP.cpp b/clang/lib/Parse/ParseOpenMP.cpp
index 5265d8f1922c3..18ba1185ee8de 100644
--- a/clang/lib/Parse/ParseOpenMP.cpp
+++ b/clang/lib/Parse/ParseOpenMP.cpp
@@ -4228,20 +4228,13 @@ bool 
Parser::parseMapperModifier(SemaOpenMP::OpenMPVarListDataTy &Data) {
   return T.consumeClose();
 }
 
-static OpenMPMapClauseKind isMapType(Parser &P);
-
 /// Parse map-type-modifiers in map clause.
-/// map([ [map-type-modifier[,] [map-type-modifier[,] ...] [map-type] : ] list)
+/// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list)
 /// where, map-type-modifier ::= always | close | mapper(mapper-identifier) |
 /// present
-/// where, map-type ::= alloc | delete | from | release | to | tofrom
 bool Parser::parseMapTypeModifiers(SemaOpenMP::OpenMPVarListDataTy &Data) {
-  bool HasMapType = false;
-  SourceLocation PreMapLoc = Tok.getLocation();
-  StringRef PreMapName = "";
   while (getCurToken().isNot(tok::colon)) {
 OpenMPMapModifierKind TypeModifier = isMapModifier(*this);
-OpenMPMapClauseKind MapKind = isMapType(*this);
 if (TypeModifier == OMPC_MAP_MODIFIER_always ||
 TypeModifier == OMPC_MAP_MODIFIER_close ||
 TypeModifier == OMPC_MAP_MODIFIER_present ||
@@ -4264,19 +4257,6 @@ bool 
Parser::parseMapTypeModifiers(SemaOpenMP::OpenMPVarListDataTy &Data) {
 Diag(Data.MapTypeModifiersLoc.back(), diag::err_omp_missing_comma)
 << "map type modifier";
 
-} else if (getLangOpts().OpenMP >= 60 && MapKind != OMPC_MAP_unknown) {
-  if (!HasMapType) {
-HasMapType = true;
-Data.ExtraModifier = MapKind;
-MapKind = OMPC_MAP_unknown;
-PreMapLoc = Tok.getLocation();
-PreMapName = Tok.getIdentifierInfo()->getName();
-  } else {
-Diag(Tok, diag::err_omp_more_one_map_type);
-Diag(PreMapLoc, diag::note_previous_map_type_specified_here)
-<< PreMapName;
-  }
-  ConsumeToken();
 } else {
   // For the case of unknown map-type-modifier or a map-type.
   // Map-type is followed by a colon; the function returns when it
@@ -4287,14 +4267,8 @@ bool 
Parser::parseMapTypeModifiers(SemaOpenMP::OpenMPVarListDataTy &Data) {
 continue;
   }
   // Potential map-type token as it is followed by a colon.
-  if (PP.LookAhead(0).is(tok::colon)) {
-if (getLangOpts().OpenMP >= 60) {
-  break;
-} else {
-  return false;
-}
-  }
-
+  if (PP.LookAhead(0).is(tok::colon))
+return false;
   Diag(Tok, diag::err_omp_unknown_map_type_modifier)
   << (getLangOpts().OpenMP >= 51 ? (getLangOpts().OpenMP >= 52 ? 2 : 1)
 

[clang] Revert "Revert "[OpenMP][TR12] change property of map-type modifier."… (PR #91141)

2024-05-08 Thread Tom Weaver via cfe-commits

TomWeaver18 wrote:

Reverted in 
https://github.com/llvm/llvm-project/commit/341aecc2dd0f6debcbe9f251a6d2e8a60d327eea

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


[clang] [Serialization] Check for stack exhaustion when reading declarations (PR #79875)

2024-05-08 Thread Ilya Biryukov via cfe-commits

ilya-biryukov wrote:

Sorry for loosing track of this change. I will go through the comments and try 
to land this some time next week.

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


[clang] [AST] RecursiveASTVisitor: Don't traverse the alias deduction guides in the default mode. (PR #91454)

2024-05-08 Thread Haojian Wu via cfe-commits

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

By default (`shouldVisitImplicitCode()` returns `false`), RAV should not 
traverse AST nodes that are not spelled in the source code. Deduction guides 
for alias templates are always synthesized, so they should not be traversed.

This is usually done by checking the implicit bit of the Decl. However, this 
doesn't work deduction guides that are synthesized from explicit user-defined 
deduction guides, as we must maintain the explicit bit to ensure correct 
overload resolution.

>From e560fe2bf2d4bdc07a71682aa4d3a4bee8730b80 Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Wed, 8 May 2024 12:11:10 +0200
Subject: [PATCH] [AST] RecursiveASTVisitor: Don't traverse the alias deduction
 guides in default mode.

---
 clang/include/clang/AST/RecursiveASTVisitor.h | 28 --
 .../DeductionGuide.cpp| 89 +++
 2 files changed, 110 insertions(+), 7 deletions(-)
 create mode 100644 
clang/unittests/Tooling/RecursiveASTVisitorTests/DeductionGuide.cpp

diff --git a/clang/include/clang/AST/RecursiveASTVisitor.h 
b/clang/include/clang/AST/RecursiveASTVisitor.h
index f9b145b4e86a5..2517189c95300 100644
--- a/clang/include/clang/AST/RecursiveASTVisitor.h
+++ b/clang/include/clang/AST/RecursiveASTVisitor.h
@@ -736,13 +736,27 @@ bool RecursiveASTVisitor::TraverseDecl(Decl *D) {
 
   // As a syntax visitor, by default we want to ignore declarations for
   // implicit declarations (ones not typed explicitly by the user).
-  if (!getDerived().shouldVisitImplicitCode() && D->isImplicit()) {
-// For an implicit template type parameter, its type constraints are not
-// implicit and are not represented anywhere else. We still need to visit
-// them.
-if (auto *TTPD = dyn_cast(D))
-  return TraverseTemplateTypeParamDeclConstraints(TTPD);
-return true;
+  if (!getDerived().shouldVisitImplicitCode()) {
+if (D->isImplicit()) {
+  // For an implicit template type parameter, its type constraints are not
+  // implicit and are not represented anywhere else. We still need to visit
+  // them.
+  if (auto *TTPD = dyn_cast(D))
+return TraverseTemplateTypeParamDeclConstraints(TTPD);
+  return true;
+}
+
+// Deduction guides for alias templates are always synthesized, so they
+// should not be traversed unless shouldVisitImplicitCode() returns true.
+//
+// It's important to note that checking the implicit bit is not efficient
+// for the alias case. For deduction guides synthesized from explicit
+// user-defined deduction guides, we must maintain the explicit bit to
+// ensure correct overload resolution.
+if (auto *FTD = dyn_cast(D))
+  if (llvm::isa_and_present(
+  FTD->getDeclName().getCXXDeductionGuideTemplate()))
+return true;
   }
 
   switch (D->getKind()) {
diff --git 
a/clang/unittests/Tooling/RecursiveASTVisitorTests/DeductionGuide.cpp 
b/clang/unittests/Tooling/RecursiveASTVisitorTests/DeductionGuide.cpp
new file mode 100644
index 0..abfdbaea4a615
--- /dev/null
+++ b/clang/unittests/Tooling/RecursiveASTVisitorTests/DeductionGuide.cpp
@@ -0,0 +1,89 @@
+//===- unittest/Tooling/RecursiveASTVisitorTests/DeductionGuide.cpp 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "TestVisitor.h"
+#include 
+
+using namespace clang;
+
+namespace {
+
+class DeductionGuideVisitor
+: public ExpectedLocationVisitor {
+public:
+  DeductionGuideVisitor(bool ShouldVisitImplicitCode)
+  : ShouldVisitImplicitCode(ShouldVisitImplicitCode) {}
+  bool VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
+std::string Storage;
+llvm::raw_string_ostream Stream(Storage);
+D->print(Stream);
+Match(Stream.str(),D->getLocation());
+return true;
+  }
+
+  bool shouldVisitTemplateInstantiations() const {
+return false;
+  }
+
+  bool shouldVisitImplicitCode() const {
+return ShouldVisitImplicitCode;
+  }
+  bool ShouldVisitImplicitCode;
+};
+
+TEST(RecursiveASTVisitor, DeductionGuideNonImplicitMode) {
+  DeductionGuideVisitor Visitor(/*ShouldVisitImplicitCode*/ false);
+  // Verify that the synthezied deduction guide for alias is not visited in
+  // RAV's implicit mode.
+  Visitor.ExpectMatch("Foo(T) -> Foo", 11, 1);
+  Visitor.DisallowMatch("Bar(type-parameter-0-0) -> Foo", 14, 1);
+  EXPECT_TRUE(Visitor.runOver(
+R"cpp(
+template 
+concept False = true;
+
+template  
+struct Foo { 
+  Foo(T);
+};
+
+template requires False
+Foo(T) -> Foo;
+
+template 
+using Bar = Foo;
+Bar s(1); 
+   )cpp"
+  , DeductionGuideVisitor::Lang_CXX2a));
+}
+
+TEST(RecursiveASTVisitor, DeductionGuideImplicitMode) {
+  DeductionGuide

[clang] [AST] RecursiveASTVisitor: Don't traverse the alias deduction guides in the default mode. (PR #91454)

2024-05-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Haojian Wu (hokein)


Changes

By default (`shouldVisitImplicitCode()` returns `false`), RAV should not 
traverse AST nodes that are not spelled in the source code. Deduction guides 
for alias templates are always synthesized, so they should not be traversed.

This is usually done by checking the implicit bit of the Decl. However, this 
doesn't work deduction guides that are synthesized from explicit user-defined 
deduction guides, as we must maintain the explicit bit to ensure correct 
overload resolution.

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


2 Files Affected:

- (modified) clang/include/clang/AST/RecursiveASTVisitor.h (+21-7) 
- (added) clang/unittests/Tooling/RecursiveASTVisitorTests/DeductionGuide.cpp 
(+89) 


``diff
diff --git a/clang/include/clang/AST/RecursiveASTVisitor.h 
b/clang/include/clang/AST/RecursiveASTVisitor.h
index f9b145b4e86a5..2517189c95300 100644
--- a/clang/include/clang/AST/RecursiveASTVisitor.h
+++ b/clang/include/clang/AST/RecursiveASTVisitor.h
@@ -736,13 +736,27 @@ bool RecursiveASTVisitor::TraverseDecl(Decl *D) {
 
   // As a syntax visitor, by default we want to ignore declarations for
   // implicit declarations (ones not typed explicitly by the user).
-  if (!getDerived().shouldVisitImplicitCode() && D->isImplicit()) {
-// For an implicit template type parameter, its type constraints are not
-// implicit and are not represented anywhere else. We still need to visit
-// them.
-if (auto *TTPD = dyn_cast(D))
-  return TraverseTemplateTypeParamDeclConstraints(TTPD);
-return true;
+  if (!getDerived().shouldVisitImplicitCode()) {
+if (D->isImplicit()) {
+  // For an implicit template type parameter, its type constraints are not
+  // implicit and are not represented anywhere else. We still need to visit
+  // them.
+  if (auto *TTPD = dyn_cast(D))
+return TraverseTemplateTypeParamDeclConstraints(TTPD);
+  return true;
+}
+
+// Deduction guides for alias templates are always synthesized, so they
+// should not be traversed unless shouldVisitImplicitCode() returns true.
+//
+// It's important to note that checking the implicit bit is not efficient
+// for the alias case. For deduction guides synthesized from explicit
+// user-defined deduction guides, we must maintain the explicit bit to
+// ensure correct overload resolution.
+if (auto *FTD = dyn_cast(D))
+  if (llvm::isa_and_present(
+  FTD->getDeclName().getCXXDeductionGuideTemplate()))
+return true;
   }
 
   switch (D->getKind()) {
diff --git 
a/clang/unittests/Tooling/RecursiveASTVisitorTests/DeductionGuide.cpp 
b/clang/unittests/Tooling/RecursiveASTVisitorTests/DeductionGuide.cpp
new file mode 100644
index 0..abfdbaea4a615
--- /dev/null
+++ b/clang/unittests/Tooling/RecursiveASTVisitorTests/DeductionGuide.cpp
@@ -0,0 +1,89 @@
+//===- unittest/Tooling/RecursiveASTVisitorTests/DeductionGuide.cpp 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "TestVisitor.h"
+#include 
+
+using namespace clang;
+
+namespace {
+
+class DeductionGuideVisitor
+: public ExpectedLocationVisitor {
+public:
+  DeductionGuideVisitor(bool ShouldVisitImplicitCode)
+  : ShouldVisitImplicitCode(ShouldVisitImplicitCode) {}
+  bool VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
+std::string Storage;
+llvm::raw_string_ostream Stream(Storage);
+D->print(Stream);
+Match(Stream.str(),D->getLocation());
+return true;
+  }
+
+  bool shouldVisitTemplateInstantiations() const {
+return false;
+  }
+
+  bool shouldVisitImplicitCode() const {
+return ShouldVisitImplicitCode;
+  }
+  bool ShouldVisitImplicitCode;
+};
+
+TEST(RecursiveASTVisitor, DeductionGuideNonImplicitMode) {
+  DeductionGuideVisitor Visitor(/*ShouldVisitImplicitCode*/ false);
+  // Verify that the synthezied deduction guide for alias is not visited in
+  // RAV's implicit mode.
+  Visitor.ExpectMatch("Foo(T) -> Foo", 11, 1);
+  Visitor.DisallowMatch("Bar(type-parameter-0-0) -> Foo", 14, 1);
+  EXPECT_TRUE(Visitor.runOver(
+R"cpp(
+template 
+concept False = true;
+
+template  
+struct Foo { 
+  Foo(T);
+};
+
+template requires False
+Foo(T) -> Foo;
+
+template 
+using Bar = Foo;
+Bar s(1); 
+   )cpp"
+  , DeductionGuideVisitor::Lang_CXX2a));
+}
+
+TEST(RecursiveASTVisitor, DeductionGuideImplicitMode) {
+  DeductionGuideVisitor Visitor(/*ShouldVisitImplicitCode*/ true);
+  Visitor.ExpectMatch("Foo(T) -> Foo", 11, 1);
+  Visitor.ExpectMatch("Bar(type-parameter-0-0) -> Foo", 14, 1);
+  EXPECT_TRUE(Visitor.runOver(
+R"cpp(
+template 
+concept False = true;
+
+te

[clang] [llvm] [clang][dataflow] Make `SolverTest` a type-parameterized test. (PR #91455)

2024-05-08 Thread via cfe-commits

https://github.com/martinboehme created 
https://github.com/llvm/llvm-project/pull/91455

This allows the tests to be run against any implementation of `Solver` instead
of begin specific to `WatchedLiteralsSolver` as they currently are.


>From 84a60b093952ee397b33ddbac21febae6258a006 Mon Sep 17 00:00:00 2001
From: Martin Braenne 
Date: Wed, 8 May 2024 10:29:06 +
Subject: [PATCH] [clang][dataflow] Make `SolverTest` a type-parameterized
 test.

This allows the tests to be run against any implementation of `Solver` instead
of begin specific to `WatchedLiteralsSolver` as they currently are.
---
 clang/docs/tools/clang-formatted-files.txt|   3 +-
 .../Analysis/FlowSensitive/CMakeLists.txt |   2 +-
 .../{SolverTest.cpp => SolverTest.h}  | 166 ++
 .../WatchedLiteralsSolverTest.cpp |  26 +++
 .../unittests/Analysis/FlowSensitive/BUILD.gn |   2 +-
 5 files changed, 124 insertions(+), 75 deletions(-)
 rename clang/unittests/Analysis/FlowSensitive/{SolverTest.cpp => SolverTest.h} 
(62%)
 create mode 100644 
clang/unittests/Analysis/FlowSensitive/WatchedLiteralsSolverTest.cpp

diff --git a/clang/docs/tools/clang-formatted-files.txt 
b/clang/docs/tools/clang-formatted-files.txt
index 2252d0ccde96d..eaeadf2656b0b 100644
--- a/clang/docs/tools/clang-formatted-files.txt
+++ b/clang/docs/tools/clang-formatted-files.txt
@@ -632,11 +632,12 @@ clang/unittests/Analysis/FlowSensitive/MapLatticeTest.cpp
 clang/unittests/Analysis/FlowSensitive/MatchSwitchTest.cpp
 clang/unittests/Analysis/FlowSensitive/MultiVarConstantPropagationTest.cpp
 clang/unittests/Analysis/FlowSensitive/SingleVarConstantPropagationTest.cpp
-clang/unittests/Analysis/FlowSensitive/SolverTest.cpp
+clang/unittests/Analysis/FlowSensitive/SolverTest.h
 clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp
 clang/unittests/Analysis/FlowSensitive/TestingSupport.h
 clang/unittests/Analysis/FlowSensitive/TestingSupportTest.cpp
 clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
+clang/unittests/Analysis/FlowSensitive/WatchedLiteralsSolverTest.cpp
 clang/unittests/AST/ASTImporterFixtures.cpp
 clang/unittests/AST/ASTImporterFixtures.h
 clang/unittests/AST/ASTImporterObjCTest.cpp
diff --git a/clang/unittests/Analysis/FlowSensitive/CMakeLists.txt 
b/clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
index 94160d949637c..cfabb80576bc1 100644
--- a/clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
+++ b/clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
@@ -19,7 +19,6 @@ add_clang_unittest(ClangAnalysisFlowSensitiveTests
   SignAnalysisTest.cpp
   SimplifyConstraintsTest.cpp
   SingleVarConstantPropagationTest.cpp
-  SolverTest.cpp
   TestingSupport.cpp
   TestingSupportTest.cpp
   TransferBranchTest.cpp
@@ -27,6 +26,7 @@ add_clang_unittest(ClangAnalysisFlowSensitiveTests
   TypeErasedDataflowAnalysisTest.cpp
   UncheckedOptionalAccessModelTest.cpp
   ValueTest.cpp
+  WatchedLiteralsSolverTest.cpp
   )
 
 clang_target_link_libraries(ClangAnalysisFlowSensitiveTests
diff --git a/clang/unittests/Analysis/FlowSensitive/SolverTest.cpp 
b/clang/unittests/Analysis/FlowSensitive/SolverTest.h
similarity index 62%
rename from clang/unittests/Analysis/FlowSensitive/SolverTest.cpp
rename to clang/unittests/Analysis/FlowSensitive/SolverTest.h
index 71f6da93594e3..b375344381213 100644
--- a/clang/unittests/Analysis/FlowSensitive/SolverTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/SolverTest.h
@@ -1,4 +1,4 @@
-//===- unittests/Analysis/FlowSensitive/SolverTest.cpp 
===//
+//===--- SolverTest.h - Type-parameterized test for solvers 
---===//
 //
 // Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
 // See https://llvm.org/LICENSE.txt for license information.
@@ -6,43 +6,53 @@
 //
 
//===--===//
 
-#include 
+#ifndef LLVM_CLANG_ANALYSIS_FLOW_SENSITIVE_SOLVER_TEST_H_
+#define LLVM_CLANG_ANALYSIS_FLOW_SENSITIVE_SOLVER_TEST_H_
 
 #include "TestingSupport.h"
-#include "clang/Analysis/FlowSensitive/Arena.h"
-#include "clang/Analysis/FlowSensitive/Formula.h"
 #include "clang/Analysis/FlowSensitive/Solver.h"
-#include "clang/Analysis/FlowSensitive/WatchedLiteralsSolver.h"
-#include "clang/Basic/LLVM.h"
-#include "llvm/ADT/ArrayRef.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
-#include 
+
+namespace clang::dataflow::test {
 
 namespace {
 
-using namespace clang;
-using namespace dataflow;
+constexpr auto AssignedTrue = Solver::Result::Assignment::AssignedTrue;
+constexpr auto AssignedFalse = Solver::Result::Assignment::AssignedFalse;
 
-using test::ConstraintContext;
-using test::parseFormulas;
 using testing::_;
 using testing::AnyOf;
 using testing::Pair;
 using testing::UnorderedElementsAre;
 
-constexpr auto AssignedTrue = Solver::Result::Assignment::AssignedTrue;
-constexpr auto AssignedFalse = Solver::Result::Assignment::AssignedFalse;
+} // namespace
 
-// C

[clang] [llvm] [clang][dataflow] Make `SolverTest` a type-parameterized test. (PR #91455)

2024-05-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: None (martinboehme)


Changes

This allows the tests to be run against any implementation of `Solver` instead
of begin specific to `WatchedLiteralsSolver` as they currently are.


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


5 Files Affected:

- (modified) clang/docs/tools/clang-formatted-files.txt (+2-1) 
- (modified) clang/unittests/Analysis/FlowSensitive/CMakeLists.txt (+1-1) 
- (renamed) clang/unittests/Analysis/FlowSensitive/SolverTest.h (+94-72) 
- (added) clang/unittests/Analysis/FlowSensitive/WatchedLiteralsSolverTest.cpp 
(+26) 
- (modified) 
llvm/utils/gn/secondary/clang/unittests/Analysis/FlowSensitive/BUILD.gn (+1-1) 


``diff
diff --git a/clang/docs/tools/clang-formatted-files.txt 
b/clang/docs/tools/clang-formatted-files.txt
index 2252d0ccde96d..eaeadf2656b0b 100644
--- a/clang/docs/tools/clang-formatted-files.txt
+++ b/clang/docs/tools/clang-formatted-files.txt
@@ -632,11 +632,12 @@ clang/unittests/Analysis/FlowSensitive/MapLatticeTest.cpp
 clang/unittests/Analysis/FlowSensitive/MatchSwitchTest.cpp
 clang/unittests/Analysis/FlowSensitive/MultiVarConstantPropagationTest.cpp
 clang/unittests/Analysis/FlowSensitive/SingleVarConstantPropagationTest.cpp
-clang/unittests/Analysis/FlowSensitive/SolverTest.cpp
+clang/unittests/Analysis/FlowSensitive/SolverTest.h
 clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp
 clang/unittests/Analysis/FlowSensitive/TestingSupport.h
 clang/unittests/Analysis/FlowSensitive/TestingSupportTest.cpp
 clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
+clang/unittests/Analysis/FlowSensitive/WatchedLiteralsSolverTest.cpp
 clang/unittests/AST/ASTImporterFixtures.cpp
 clang/unittests/AST/ASTImporterFixtures.h
 clang/unittests/AST/ASTImporterObjCTest.cpp
diff --git a/clang/unittests/Analysis/FlowSensitive/CMakeLists.txt 
b/clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
index 94160d949637c..cfabb80576bc1 100644
--- a/clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
+++ b/clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
@@ -19,7 +19,6 @@ add_clang_unittest(ClangAnalysisFlowSensitiveTests
   SignAnalysisTest.cpp
   SimplifyConstraintsTest.cpp
   SingleVarConstantPropagationTest.cpp
-  SolverTest.cpp
   TestingSupport.cpp
   TestingSupportTest.cpp
   TransferBranchTest.cpp
@@ -27,6 +26,7 @@ add_clang_unittest(ClangAnalysisFlowSensitiveTests
   TypeErasedDataflowAnalysisTest.cpp
   UncheckedOptionalAccessModelTest.cpp
   ValueTest.cpp
+  WatchedLiteralsSolverTest.cpp
   )
 
 clang_target_link_libraries(ClangAnalysisFlowSensitiveTests
diff --git a/clang/unittests/Analysis/FlowSensitive/SolverTest.cpp 
b/clang/unittests/Analysis/FlowSensitive/SolverTest.h
similarity index 62%
rename from clang/unittests/Analysis/FlowSensitive/SolverTest.cpp
rename to clang/unittests/Analysis/FlowSensitive/SolverTest.h
index 71f6da93594e3..b375344381213 100644
--- a/clang/unittests/Analysis/FlowSensitive/SolverTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/SolverTest.h
@@ -1,4 +1,4 @@
-//===- unittests/Analysis/FlowSensitive/SolverTest.cpp 
===//
+//===--- SolverTest.h - Type-parameterized test for solvers 
---===//
 //
 // Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
 // See https://llvm.org/LICENSE.txt for license information.
@@ -6,43 +6,53 @@
 //
 
//===--===//
 
-#include 
+#ifndef LLVM_CLANG_ANALYSIS_FLOW_SENSITIVE_SOLVER_TEST_H_
+#define LLVM_CLANG_ANALYSIS_FLOW_SENSITIVE_SOLVER_TEST_H_
 
 #include "TestingSupport.h"
-#include "clang/Analysis/FlowSensitive/Arena.h"
-#include "clang/Analysis/FlowSensitive/Formula.h"
 #include "clang/Analysis/FlowSensitive/Solver.h"
-#include "clang/Analysis/FlowSensitive/WatchedLiteralsSolver.h"
-#include "clang/Basic/LLVM.h"
-#include "llvm/ADT/ArrayRef.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
-#include 
+
+namespace clang::dataflow::test {
 
 namespace {
 
-using namespace clang;
-using namespace dataflow;
+constexpr auto AssignedTrue = Solver::Result::Assignment::AssignedTrue;
+constexpr auto AssignedFalse = Solver::Result::Assignment::AssignedFalse;
 
-using test::ConstraintContext;
-using test::parseFormulas;
 using testing::_;
 using testing::AnyOf;
 using testing::Pair;
 using testing::UnorderedElementsAre;
 
-constexpr auto AssignedTrue = Solver::Result::Assignment::AssignedTrue;
-constexpr auto AssignedFalse = Solver::Result::Assignment::AssignedFalse;
+} // namespace
 
-// Checks if the conjunction of `Vals` is satisfiable and returns the
-// corresponding result.
-Solver::Result solve(llvm::ArrayRef Vals) {
-  return WatchedLiteralsSolver().solve(Vals);
-}
+/// Type-parameterized test for implementations of the `Solver` interface.
+/// To use:
+/// 1.  Implement a specialization of `createSolverWithLowTimeout()` for the
+/// solver you want to test.
+/// 2. 

[clang] [AST] RecursiveASTVisitor: Don't traverse the alias deduction guides in the default mode. (PR #91454)

2024-05-08 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 2d4acb086541577ac6ab3a140b9ceb9659ce7094 
e560fe2bf2d4bdc07a71682aa4d3a4bee8730b80 -- 
clang/unittests/Tooling/RecursiveASTVisitorTests/DeductionGuide.cpp 
clang/include/clang/AST/RecursiveASTVisitor.h
``





View the diff from clang-format here.


``diff
diff --git 
a/clang/unittests/Tooling/RecursiveASTVisitorTests/DeductionGuide.cpp 
b/clang/unittests/Tooling/RecursiveASTVisitorTests/DeductionGuide.cpp
index abfdbaea4a..274f275ea6 100644
--- a/clang/unittests/Tooling/RecursiveASTVisitorTests/DeductionGuide.cpp
+++ b/clang/unittests/Tooling/RecursiveASTVisitorTests/DeductionGuide.cpp
@@ -22,17 +22,13 @@ public:
 std::string Storage;
 llvm::raw_string_ostream Stream(Storage);
 D->print(Stream);
-Match(Stream.str(),D->getLocation());
+Match(Stream.str(), D->getLocation());
 return true;
   }
 
-  bool shouldVisitTemplateInstantiations() const {
-return false;
-  }
+  bool shouldVisitTemplateInstantiations() const { return false; }
 
-  bool shouldVisitImplicitCode() const {
-return ShouldVisitImplicitCode;
-  }
+  bool shouldVisitImplicitCode() const { return ShouldVisitImplicitCode; }
   bool ShouldVisitImplicitCode;
 };
 
@@ -43,7 +39,7 @@ TEST(RecursiveASTVisitor, DeductionGuideNonImplicitMode) {
   Visitor.ExpectMatch("Foo(T) -> Foo", 11, 1);
   Visitor.DisallowMatch("Bar(type-parameter-0-0) -> Foo", 14, 1);
   EXPECT_TRUE(Visitor.runOver(
-R"cpp(
+  R"cpp(
 template 
 concept False = true;
 
@@ -58,8 +54,8 @@ Foo(T) -> Foo;
 template 
 using Bar = Foo;
 Bar s(1); 
-   )cpp"
-  , DeductionGuideVisitor::Lang_CXX2a));
+   )cpp",
+  DeductionGuideVisitor::Lang_CXX2a));
 }
 
 TEST(RecursiveASTVisitor, DeductionGuideImplicitMode) {
@@ -67,7 +63,7 @@ TEST(RecursiveASTVisitor, DeductionGuideImplicitMode) {
   Visitor.ExpectMatch("Foo(T) -> Foo", 11, 1);
   Visitor.ExpectMatch("Bar(type-parameter-0-0) -> Foo", 14, 1);
   EXPECT_TRUE(Visitor.runOver(
-R"cpp(
+  R"cpp(
 template 
 concept False = true;
 
@@ -82,8 +78,8 @@ Foo(T) -> Foo;
 template 
 using Bar = Foo;
 Bar s(1); 
-   )cpp"
-  , DeductionGuideVisitor::Lang_CXX2a));
+   )cpp",
+  DeductionGuideVisitor::Lang_CXX2a));
 }
 
 } // end anonymous namespace

``




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


[clang] [llvm] [clang][dataflow] Make `SolverTest` a type-parameterized test. (PR #91455)

2024-05-08 Thread via cfe-commits

https://github.com/martinboehme updated 
https://github.com/llvm/llvm-project/pull/91455

>From 84a60b093952ee397b33ddbac21febae6258a006 Mon Sep 17 00:00:00 2001
From: Martin Braenne 
Date: Wed, 8 May 2024 10:29:06 +
Subject: [PATCH 1/2] [clang][dataflow] Make `SolverTest` a type-parameterized
 test.

This allows the tests to be run against any implementation of `Solver` instead
of begin specific to `WatchedLiteralsSolver` as they currently are.
---
 clang/docs/tools/clang-formatted-files.txt|   3 +-
 .../Analysis/FlowSensitive/CMakeLists.txt |   2 +-
 .../{SolverTest.cpp => SolverTest.h}  | 166 ++
 .../WatchedLiteralsSolverTest.cpp |  26 +++
 .../unittests/Analysis/FlowSensitive/BUILD.gn |   2 +-
 5 files changed, 124 insertions(+), 75 deletions(-)
 rename clang/unittests/Analysis/FlowSensitive/{SolverTest.cpp => SolverTest.h} 
(62%)
 create mode 100644 
clang/unittests/Analysis/FlowSensitive/WatchedLiteralsSolverTest.cpp

diff --git a/clang/docs/tools/clang-formatted-files.txt 
b/clang/docs/tools/clang-formatted-files.txt
index 2252d0ccde96d..eaeadf2656b0b 100644
--- a/clang/docs/tools/clang-formatted-files.txt
+++ b/clang/docs/tools/clang-formatted-files.txt
@@ -632,11 +632,12 @@ clang/unittests/Analysis/FlowSensitive/MapLatticeTest.cpp
 clang/unittests/Analysis/FlowSensitive/MatchSwitchTest.cpp
 clang/unittests/Analysis/FlowSensitive/MultiVarConstantPropagationTest.cpp
 clang/unittests/Analysis/FlowSensitive/SingleVarConstantPropagationTest.cpp
-clang/unittests/Analysis/FlowSensitive/SolverTest.cpp
+clang/unittests/Analysis/FlowSensitive/SolverTest.h
 clang/unittests/Analysis/FlowSensitive/TestingSupport.cpp
 clang/unittests/Analysis/FlowSensitive/TestingSupport.h
 clang/unittests/Analysis/FlowSensitive/TestingSupportTest.cpp
 clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
+clang/unittests/Analysis/FlowSensitive/WatchedLiteralsSolverTest.cpp
 clang/unittests/AST/ASTImporterFixtures.cpp
 clang/unittests/AST/ASTImporterFixtures.h
 clang/unittests/AST/ASTImporterObjCTest.cpp
diff --git a/clang/unittests/Analysis/FlowSensitive/CMakeLists.txt 
b/clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
index 94160d949637c..cfabb80576bc1 100644
--- a/clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
+++ b/clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
@@ -19,7 +19,6 @@ add_clang_unittest(ClangAnalysisFlowSensitiveTests
   SignAnalysisTest.cpp
   SimplifyConstraintsTest.cpp
   SingleVarConstantPropagationTest.cpp
-  SolverTest.cpp
   TestingSupport.cpp
   TestingSupportTest.cpp
   TransferBranchTest.cpp
@@ -27,6 +26,7 @@ add_clang_unittest(ClangAnalysisFlowSensitiveTests
   TypeErasedDataflowAnalysisTest.cpp
   UncheckedOptionalAccessModelTest.cpp
   ValueTest.cpp
+  WatchedLiteralsSolverTest.cpp
   )
 
 clang_target_link_libraries(ClangAnalysisFlowSensitiveTests
diff --git a/clang/unittests/Analysis/FlowSensitive/SolverTest.cpp 
b/clang/unittests/Analysis/FlowSensitive/SolverTest.h
similarity index 62%
rename from clang/unittests/Analysis/FlowSensitive/SolverTest.cpp
rename to clang/unittests/Analysis/FlowSensitive/SolverTest.h
index 71f6da93594e3..b375344381213 100644
--- a/clang/unittests/Analysis/FlowSensitive/SolverTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/SolverTest.h
@@ -1,4 +1,4 @@
-//===- unittests/Analysis/FlowSensitive/SolverTest.cpp 
===//
+//===--- SolverTest.h - Type-parameterized test for solvers 
---===//
 //
 // Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
 // See https://llvm.org/LICENSE.txt for license information.
@@ -6,43 +6,53 @@
 //
 
//===--===//
 
-#include 
+#ifndef LLVM_CLANG_ANALYSIS_FLOW_SENSITIVE_SOLVER_TEST_H_
+#define LLVM_CLANG_ANALYSIS_FLOW_SENSITIVE_SOLVER_TEST_H_
 
 #include "TestingSupport.h"
-#include "clang/Analysis/FlowSensitive/Arena.h"
-#include "clang/Analysis/FlowSensitive/Formula.h"
 #include "clang/Analysis/FlowSensitive/Solver.h"
-#include "clang/Analysis/FlowSensitive/WatchedLiteralsSolver.h"
-#include "clang/Basic/LLVM.h"
-#include "llvm/ADT/ArrayRef.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
-#include 
+
+namespace clang::dataflow::test {
 
 namespace {
 
-using namespace clang;
-using namespace dataflow;
+constexpr auto AssignedTrue = Solver::Result::Assignment::AssignedTrue;
+constexpr auto AssignedFalse = Solver::Result::Assignment::AssignedFalse;
 
-using test::ConstraintContext;
-using test::parseFormulas;
 using testing::_;
 using testing::AnyOf;
 using testing::Pair;
 using testing::UnorderedElementsAre;
 
-constexpr auto AssignedTrue = Solver::Result::Assignment::AssignedTrue;
-constexpr auto AssignedFalse = Solver::Result::Assignment::AssignedFalse;
+} // namespace
 
-// Checks if the conjunction of `Vals` is satisfiable and returns the
-// corresponding result.
-Solver::Result solve(llvm::ArrayRef Vals) {
-  retur

[clang] [clang][analyzer] Add checker 'Security.SetgidSetuidOrder'. (PR #91445)

2024-05-08 Thread Donát Nagy via cfe-commits

https://github.com/NagyDonat commented:

It's good to see that this checker is finished. I added several inline 
comments, but they are not serious issues -- most are connected to 
`CallDescription`s where I'm now very familiar with the available options (and 
I refactored the code, so others are not so familiar with it...).

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


[clang] [clang][analyzer] Add checker 'Security.SetgidSetuidOrder'. (PR #91445)

2024-05-08 Thread Donát Nagy via cfe-commits


@@ -0,0 +1,197 @@
+//===-- SetgidSetuidOrderChecker.cpp - check privilege revocation calls 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines a checker to detect possible reversed order of privilege
+//  revocations when 'setgid' and 'setuid' is used.
+//
+//===--===//
+
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
+
+using namespace clang;
+using namespace ento;
+
+namespace {
+
+class SetgidSetuidOrderChecker
+: public Checker {
+  const BugType BT_WrongRevocationOrder{
+  this, "Possible wrong order of privilege revocation"};
+
+  const CallDescription SetuidDesc{{"setuid"}, 1};
+  const CallDescription SetgidDesc{{"setgid"}, 1};
+  const CallDescription SeteuidDesc{{"seteuid"}, 1};
+  const CallDescription SetegidDesc{{"setegid"}, 1};
+  const CallDescription SetreuidDesc{{"setreuid"}, 2};
+  const CallDescription SetregidDesc{{"setregid"}, 2};
+  const CallDescription SetresuidDesc{{"setresuid"}, 3};
+  const CallDescription SetresgidDesc{{"setresgid"}, 3};
+
+public:
+  SetgidSetuidOrderChecker() {}
+
+  void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
+  void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
+  ProgramStateRef evalAssume(ProgramStateRef State, SVal Cond,
+ bool Assumption) const;
+
+private:
+  ProgramStateRef processSetuid(ProgramStateRef State, const CallEvent &Call,
+CheckerContext &C) const;
+  ProgramStateRef processSetgid(ProgramStateRef State, const CallEvent &Call,
+CheckerContext &C) const;
+  ProgramStateRef processOther(ProgramStateRef State, const CallEvent &Call,
+   CheckerContext &C) const;
+  /// Check if a function like \c getuid or \c getgid is called directly from
+  /// the first argument of function called from \a Call.
+  bool isFunctionCalledInArg(llvm::StringRef FnName,
+ const CallEvent &Call) const;
+  void emitReport(ProgramStateRef State, CheckerContext &C) const;
+};
+
+enum SetPrivilegeFunctionKind { Irrelevant, Setuid, Setgid };
+
+} // end anonymous namespace
+
+/// Store if there was a call to 'setuid(getuid())' or 'setgid(getgid())' not
+/// followed by other different privilege-change functions.
+/// If the value \c Setuid is stored and a 'setgid(getgid())' call is found we
+/// have found the bug to be reported. Value \c Setgid is used too to prevent
+/// warnings at a setgid-setuid-setgid sequence.
+REGISTER_TRAIT_WITH_PROGRAMSTATE(LastSetPrivilegeCall, 
SetPrivilegeFunctionKind)
+/// Store the symbol value of the last 'setuid(getuid())' call. This is used to
+/// detect if the result is compared to -1 and avoid warnings on that branch
+/// (which is the failure branch of the call).
+REGISTER_TRAIT_WITH_PROGRAMSTATE(LastSetuidCallSVal, SymbolRef)
+
+void SetgidSetuidOrderChecker::checkPostCall(const CallEvent &Call,
+ CheckerContext &C) const {
+  ProgramStateRef State = C.getState();
+  if (SetuidDesc.matches(Call)) {
+State = processSetuid(State, Call, C);
+  } else if (SetgidDesc.matches(Call)) {
+State = processSetgid(State, Call, C);
+  } else if (matchesAny(Call, SeteuidDesc, SetegidDesc, SetreuidDesc,
+SetregidDesc, SetresuidDesc, SetresgidDesc)) {
+State = processOther(State, Call, C);
+  }
+  if (State)
+C.addTransition(State);
+}
+
+void SetgidSetuidOrderChecker::checkDeadSymbols(SymbolReaper &SymReaper,
+CheckerContext &C) const {
+  ProgramStateRef State = C.getState();
+
+  SymbolRef LastSetuidSym = State->get();
+  if (!LastSetuidSym)
+return;
+
+  if (!SymReaper.isDead(LastSetuidSym))
+return;
+
+  State = State->set(SymbolRef{});
+  C.addTransition(State, C.getPredecessor());
+}
+
+ProgramStateRef SetgidSetuidOrderChecker::evalAssume(ProgramStateRef State,
+ SVal Cond,
+ bool Assumption) const {
+  SValBuilder &SVB = Stat

[clang] [clang][analyzer] Add checker 'Security.SetgidSetuidOrder'. (PR #91445)

2024-05-08 Thread Donát Nagy via cfe-commits

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


[clang] [clang][analyzer] Add checker 'Security.SetgidSetuidOrder'. (PR #91445)

2024-05-08 Thread Donát Nagy via cfe-commits


@@ -0,0 +1,197 @@
+//===-- SetgidSetuidOrderChecker.cpp - check privilege revocation calls 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines a checker to detect possible reversed order of privilege
+//  revocations when 'setgid' and 'setuid' is used.
+//
+//===--===//
+
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
+
+using namespace clang;
+using namespace ento;
+
+namespace {
+
+class SetgidSetuidOrderChecker
+: public Checker {
+  const BugType BT_WrongRevocationOrder{
+  this, "Possible wrong order of privilege revocation"};
+
+  const CallDescription SetuidDesc{{"setuid"}, 1};
+  const CallDescription SetgidDesc{{"setgid"}, 1};
+  const CallDescription SeteuidDesc{{"seteuid"}, 1};
+  const CallDescription SetegidDesc{{"setegid"}, 1};
+  const CallDescription SetreuidDesc{{"setreuid"}, 2};
+  const CallDescription SetregidDesc{{"setregid"}, 2};
+  const CallDescription SetresuidDesc{{"setresuid"}, 3};
+  const CallDescription SetresgidDesc{{"setresgid"}, 3};
+
+public:
+  SetgidSetuidOrderChecker() {}
+
+  void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
+  void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
+  ProgramStateRef evalAssume(ProgramStateRef State, SVal Cond,
+ bool Assumption) const;
+
+private:
+  ProgramStateRef processSetuid(ProgramStateRef State, const CallEvent &Call,
+CheckerContext &C) const;
+  ProgramStateRef processSetgid(ProgramStateRef State, const CallEvent &Call,
+CheckerContext &C) const;
+  ProgramStateRef processOther(ProgramStateRef State, const CallEvent &Call,
+   CheckerContext &C) const;
+  /// Check if a function like \c getuid or \c getgid is called directly from
+  /// the first argument of function called from \a Call.
+  bool isFunctionCalledInArg(llvm::StringRef FnName,
+ const CallEvent &Call) const;
+  void emitReport(ProgramStateRef State, CheckerContext &C) const;
+};
+
+enum SetPrivilegeFunctionKind { Irrelevant, Setuid, Setgid };
+
+} // end anonymous namespace
+
+/// Store if there was a call to 'setuid(getuid())' or 'setgid(getgid())' not
+/// followed by other different privilege-change functions.
+/// If the value \c Setuid is stored and a 'setgid(getgid())' call is found we
+/// have found the bug to be reported. Value \c Setgid is used too to prevent
+/// warnings at a setgid-setuid-setgid sequence.
+REGISTER_TRAIT_WITH_PROGRAMSTATE(LastSetPrivilegeCall, 
SetPrivilegeFunctionKind)
+/// Store the symbol value of the last 'setuid(getuid())' call. This is used to
+/// detect if the result is compared to -1 and avoid warnings on that branch
+/// (which is the failure branch of the call).
+REGISTER_TRAIT_WITH_PROGRAMSTATE(LastSetuidCallSVal, SymbolRef)
+
+void SetgidSetuidOrderChecker::checkPostCall(const CallEvent &Call,
+ CheckerContext &C) const {
+  ProgramStateRef State = C.getState();
+  if (SetuidDesc.matches(Call)) {
+State = processSetuid(State, Call, C);
+  } else if (SetgidDesc.matches(Call)) {
+State = processSetgid(State, Call, C);
+  } else if (matchesAny(Call, SeteuidDesc, SetegidDesc, SetreuidDesc,
+SetregidDesc, SetresuidDesc, SetresgidDesc)) {
+State = processOther(State, Call, C);
+  }
+  if (State)
+C.addTransition(State);
+}
+
+void SetgidSetuidOrderChecker::checkDeadSymbols(SymbolReaper &SymReaper,
+CheckerContext &C) const {
+  ProgramStateRef State = C.getState();
+
+  SymbolRef LastSetuidSym = State->get();
+  if (!LastSetuidSym)
+return;
+
+  if (!SymReaper.isDead(LastSetuidSym))
+return;
+
+  State = State->set(SymbolRef{});
+  C.addTransition(State, C.getPredecessor());
+}
+
+ProgramStateRef SetgidSetuidOrderChecker::evalAssume(ProgramStateRef State,
+ SVal Cond,
+ bool Assumption) const {
+  SValBuilder &SVB = Stat

[clang] [clang][analyzer] Add checker 'Security.SetgidSetuidOrder'. (PR #91445)

2024-05-08 Thread Donát Nagy via cfe-commits


@@ -0,0 +1,170 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,security.SetgidSetuidOrder 
-verify %s
+
+#include "Inputs/system-header-simulator-setgid-setuid.h"
+
+void correct_order() {
+  if (setgid(getgid()) == -1)
+return;
+  if (setuid(getuid()) == -1)
+return;
+  if (setgid(getgid()) == -1)
+return;

NagyDonat wrote:

Why is this block here? Should this "try to set the gid again" attempt appear 
in normal code?

(I see that this is intentionally allowed in the checker, but it would be good 
to add a short comment that explains the rationale behind this.)

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


[clang] [clang][analyzer] Add checker 'Security.SetgidSetuidOrder'. (PR #91445)

2024-05-08 Thread Donát Nagy via cfe-commits


@@ -0,0 +1,170 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,security.SetgidSetuidOrder 
-verify %s
+
+#include "Inputs/system-header-simulator-setgid-setuid.h"
+
+void correct_order() {
+  if (setgid(getgid()) == -1)
+return;
+  if (setuid(getuid()) == -1)
+return;
+  if (setgid(getgid()) == -1)
+return;
+}
+
+void incorrect_order() {
+  if (setuid(getuid()) == -1)
+return;
+  if (setgid(getgid()) == -1) // expected-warning{{A 'setgid(getgid())' call 
following a 'setuid(getuid())' call is likely to fail}}
+return;
+  if (setgid(getgid()) == -1)
+return;
+}
+
+void warn_at_second_time() {
+  if (setuid(getuid()) == -1)
+return;
+  if (setgid(getgid()) == -1) // expected-warning{{A 'setgid(getgid())' call 
following a 'setuid(getuid())' call is likely to fail}}
+return;
+  if (setuid(getuid()) == -1)
+return;
+  if (setgid(getgid()) == -1) // expected-warning{{A 'setgid(getgid())' call 
following a 'setuid(getuid())' call is likely to fail}}
+return;
+}
+
+uid_t f_uid();
+gid_t f_gid();
+
+void setuid_other() {
+  if (setuid(f_uid()) == -1)
+return;
+  if (setgid(getgid()) == -1)
+return;
+}
+
+void setgid_other() {
+  if (setuid(getuid()) == -1)
+return;
+  if (setgid(f_gid()) == -1)
+return;
+  if (setgid(getgid()) == -1)
+return;
+}
+
+void setuid_other_between() {
+  if (setuid(getuid()) == -1)
+return;
+  if (setuid(f_uid()) == -1)
+return;
+  if (setgid(getgid()) == -1)
+return;
+}
+
+void setgid_with_getuid() {
+  if (setuid(getuid()) == -1)
+return;
+  if (setgid(getuid()) == -1)
+return;
+}
+
+void setuid_with_getgid() {
+  if (setuid(getgid()) == -1)
+return;
+  if (setgid(getgid()) == -1)
+return;
+}

NagyDonat wrote:

By  the way it would be nice to create an unrelated checker that emits warnings 
for these, because these are very hard to spot and they could be typos.

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


[clang] [clang][analyzer] Add checker 'Security.SetgidSetuidOrder'. (PR #91445)

2024-05-08 Thread Donát Nagy via cfe-commits


@@ -0,0 +1,197 @@
+//===-- SetgidSetuidOrderChecker.cpp - check privilege revocation calls 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines a checker to detect possible reversed order of privilege
+//  revocations when 'setgid' and 'setuid' is used.
+//
+//===--===//
+
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
+
+using namespace clang;
+using namespace ento;
+
+namespace {
+
+class SetgidSetuidOrderChecker
+: public Checker {
+  const BugType BT_WrongRevocationOrder{
+  this, "Possible wrong order of privilege revocation"};
+
+  const CallDescription SetuidDesc{{"setuid"}, 1};
+  const CallDescription SetgidDesc{{"setgid"}, 1};
+  const CallDescription SeteuidDesc{{"seteuid"}, 1};
+  const CallDescription SetegidDesc{{"setegid"}, 1};
+  const CallDescription SetreuidDesc{{"setreuid"}, 2};
+  const CallDescription SetregidDesc{{"setregid"}, 2};
+  const CallDescription SetresuidDesc{{"setresuid"}, 3};
+  const CallDescription SetresgidDesc{{"setresgid"}, 3};
+
+public:
+  SetgidSetuidOrderChecker() {}
+
+  void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
+  void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
+  ProgramStateRef evalAssume(ProgramStateRef State, SVal Cond,
+ bool Assumption) const;
+
+private:
+  ProgramStateRef processSetuid(ProgramStateRef State, const CallEvent &Call,
+CheckerContext &C) const;
+  ProgramStateRef processSetgid(ProgramStateRef State, const CallEvent &Call,
+CheckerContext &C) const;
+  ProgramStateRef processOther(ProgramStateRef State, const CallEvent &Call,
+   CheckerContext &C) const;
+  /// Check if a function like \c getuid or \c getgid is called directly from
+  /// the first argument of function called from \a Call.
+  bool isFunctionCalledInArg(llvm::StringRef FnName,
+ const CallEvent &Call) const;
+  void emitReport(ProgramStateRef State, CheckerContext &C) const;
+};
+
+enum SetPrivilegeFunctionKind { Irrelevant, Setuid, Setgid };
+
+} // end anonymous namespace
+
+/// Store if there was a call to 'setuid(getuid())' or 'setgid(getgid())' not
+/// followed by other different privilege-change functions.
+/// If the value \c Setuid is stored and a 'setgid(getgid())' call is found we
+/// have found the bug to be reported. Value \c Setgid is used too to prevent
+/// warnings at a setgid-setuid-setgid sequence.
+REGISTER_TRAIT_WITH_PROGRAMSTATE(LastSetPrivilegeCall, 
SetPrivilegeFunctionKind)
+/// Store the symbol value of the last 'setuid(getuid())' call. This is used to
+/// detect if the result is compared to -1 and avoid warnings on that branch
+/// (which is the failure branch of the call).
+REGISTER_TRAIT_WITH_PROGRAMSTATE(LastSetuidCallSVal, SymbolRef)
+
+void SetgidSetuidOrderChecker::checkPostCall(const CallEvent &Call,
+ CheckerContext &C) const {
+  ProgramStateRef State = C.getState();
+  if (SetuidDesc.matches(Call)) {
+State = processSetuid(State, Call, C);
+  } else if (SetgidDesc.matches(Call)) {
+State = processSetgid(State, Call, C);
+  } else if (matchesAny(Call, SeteuidDesc, SetegidDesc, SetreuidDesc,
+SetregidDesc, SetresuidDesc, SetresgidDesc)) {

NagyDonat wrote:

`matchesAny` is a nice tool, but it would be even better to use a 
`CallDescriptionSet` and its `contains` method, because then you wouldn't need 
to introduce individual variable names for these call descriptions. 

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


[clang] [clang][analyzer] Add checker 'Security.SetgidSetuidOrder'. (PR #91445)

2024-05-08 Thread Donát Nagy via cfe-commits


@@ -0,0 +1,197 @@
+//===-- SetgidSetuidOrderChecker.cpp - check privilege revocation calls 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines a checker to detect possible reversed order of privilege
+//  revocations when 'setgid' and 'setuid' is used.
+//
+//===--===//
+
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
+
+using namespace clang;
+using namespace ento;
+
+namespace {
+
+class SetgidSetuidOrderChecker
+: public Checker {
+  const BugType BT_WrongRevocationOrder{
+  this, "Possible wrong order of privilege revocation"};
+
+  const CallDescription SetuidDesc{{"setuid"}, 1};
+  const CallDescription SetgidDesc{{"setgid"}, 1};
+  const CallDescription SeteuidDesc{{"seteuid"}, 1};
+  const CallDescription SetegidDesc{{"setegid"}, 1};
+  const CallDescription SetreuidDesc{{"setreuid"}, 2};
+  const CallDescription SetregidDesc{{"setregid"}, 2};
+  const CallDescription SetresuidDesc{{"setresuid"}, 3};
+  const CallDescription SetresgidDesc{{"setresgid"}, 3};
+
+public:
+  SetgidSetuidOrderChecker() {}
+
+  void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
+  void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
+  ProgramStateRef evalAssume(ProgramStateRef State, SVal Cond,
+ bool Assumption) const;
+
+private:
+  ProgramStateRef processSetuid(ProgramStateRef State, const CallEvent &Call,
+CheckerContext &C) const;
+  ProgramStateRef processSetgid(ProgramStateRef State, const CallEvent &Call,
+CheckerContext &C) const;
+  ProgramStateRef processOther(ProgramStateRef State, const CallEvent &Call,
+   CheckerContext &C) const;
+  /// Check if a function like \c getuid or \c getgid is called directly from
+  /// the first argument of function called from \a Call.
+  bool isFunctionCalledInArg(llvm::StringRef FnName,
+ const CallEvent &Call) const;
+  void emitReport(ProgramStateRef State, CheckerContext &C) const;
+};
+
+enum SetPrivilegeFunctionKind { Irrelevant, Setuid, Setgid };
+
+} // end anonymous namespace
+
+/// Store if there was a call to 'setuid(getuid())' or 'setgid(getgid())' not
+/// followed by other different privilege-change functions.
+/// If the value \c Setuid is stored and a 'setgid(getgid())' call is found we
+/// have found the bug to be reported. Value \c Setgid is used too to prevent
+/// warnings at a setgid-setuid-setgid sequence.
+REGISTER_TRAIT_WITH_PROGRAMSTATE(LastSetPrivilegeCall, 
SetPrivilegeFunctionKind)
+/// Store the symbol value of the last 'setuid(getuid())' call. This is used to
+/// detect if the result is compared to -1 and avoid warnings on that branch
+/// (which is the failure branch of the call).
+REGISTER_TRAIT_WITH_PROGRAMSTATE(LastSetuidCallSVal, SymbolRef)
+
+void SetgidSetuidOrderChecker::checkPostCall(const CallEvent &Call,
+ CheckerContext &C) const {
+  ProgramStateRef State = C.getState();
+  if (SetuidDesc.matches(Call)) {
+State = processSetuid(State, Call, C);
+  } else if (SetgidDesc.matches(Call)) {
+State = processSetgid(State, Call, C);
+  } else if (matchesAny(Call, SeteuidDesc, SetegidDesc, SetreuidDesc,
+SetregidDesc, SetresuidDesc, SetresgidDesc)) {
+State = processOther(State, Call, C);
+  }
+  if (State)
+C.addTransition(State);
+}
+
+void SetgidSetuidOrderChecker::checkDeadSymbols(SymbolReaper &SymReaper,
+CheckerContext &C) const {
+  ProgramStateRef State = C.getState();
+
+  SymbolRef LastSetuidSym = State->get();
+  if (!LastSetuidSym)
+return;
+
+  if (!SymReaper.isDead(LastSetuidSym))
+return;
+
+  State = State->set(SymbolRef{});
+  C.addTransition(State, C.getPredecessor());
+}
+
+ProgramStateRef SetgidSetuidOrderChecker::evalAssume(ProgramStateRef State,
+ SVal Cond,
+ bool Assumption) const {
+  SValBuilder &SVB = Stat

[clang] [clang][analyzer] Add checker 'Security.SetgidSetuidOrder'. (PR #91445)

2024-05-08 Thread Donát Nagy via cfe-commits


@@ -0,0 +1,197 @@
+//===-- SetgidSetuidOrderChecker.cpp - check privilege revocation calls 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines a checker to detect possible reversed order of privilege
+//  revocations when 'setgid' and 'setuid' is used.
+//
+//===--===//
+
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
+
+using namespace clang;
+using namespace ento;
+
+namespace {
+
+class SetgidSetuidOrderChecker
+: public Checker {
+  const BugType BT_WrongRevocationOrder{
+  this, "Possible wrong order of privilege revocation"};
+
+  const CallDescription SetuidDesc{{"setuid"}, 1};
+  const CallDescription SetgidDesc{{"setgid"}, 1};
+  const CallDescription SeteuidDesc{{"seteuid"}, 1};
+  const CallDescription SetegidDesc{{"setegid"}, 1};
+  const CallDescription SetreuidDesc{{"setreuid"}, 2};
+  const CallDescription SetregidDesc{{"setregid"}, 2};
+  const CallDescription SetresuidDesc{{"setresuid"}, 3};
+  const CallDescription SetresgidDesc{{"setresgid"}, 3};
+
+public:
+  SetgidSetuidOrderChecker() {}
+
+  void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
+  void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
+  ProgramStateRef evalAssume(ProgramStateRef State, SVal Cond,
+ bool Assumption) const;
+
+private:
+  ProgramStateRef processSetuid(ProgramStateRef State, const CallEvent &Call,
+CheckerContext &C) const;
+  ProgramStateRef processSetgid(ProgramStateRef State, const CallEvent &Call,
+CheckerContext &C) const;
+  ProgramStateRef processOther(ProgramStateRef State, const CallEvent &Call,
+   CheckerContext &C) const;
+  /// Check if a function like \c getuid or \c getgid is called directly from
+  /// the first argument of function called from \a Call.
+  bool isFunctionCalledInArg(llvm::StringRef FnName,
+ const CallEvent &Call) const;
+  void emitReport(ProgramStateRef State, CheckerContext &C) const;
+};
+
+enum SetPrivilegeFunctionKind { Irrelevant, Setuid, Setgid };
+
+} // end anonymous namespace
+
+/// Store if there was a call to 'setuid(getuid())' or 'setgid(getgid())' not
+/// followed by other different privilege-change functions.
+/// If the value \c Setuid is stored and a 'setgid(getgid())' call is found we
+/// have found the bug to be reported. Value \c Setgid is used too to prevent
+/// warnings at a setgid-setuid-setgid sequence.
+REGISTER_TRAIT_WITH_PROGRAMSTATE(LastSetPrivilegeCall, 
SetPrivilegeFunctionKind)
+/// Store the symbol value of the last 'setuid(getuid())' call. This is used to
+/// detect if the result is compared to -1 and avoid warnings on that branch
+/// (which is the failure branch of the call).
+REGISTER_TRAIT_WITH_PROGRAMSTATE(LastSetuidCallSVal, SymbolRef)
+
+void SetgidSetuidOrderChecker::checkPostCall(const CallEvent &Call,
+ CheckerContext &C) const {
+  ProgramStateRef State = C.getState();
+  if (SetuidDesc.matches(Call)) {
+State = processSetuid(State, Call, C);
+  } else if (SetgidDesc.matches(Call)) {
+State = processSetgid(State, Call, C);
+  } else if (matchesAny(Call, SeteuidDesc, SetegidDesc, SetreuidDesc,
+SetregidDesc, SetresuidDesc, SetresgidDesc)) {
+State = processOther(State, Call, C);
+  }
+  if (State)
+C.addTransition(State);
+}
+
+void SetgidSetuidOrderChecker::checkDeadSymbols(SymbolReaper &SymReaper,
+CheckerContext &C) const {
+  ProgramStateRef State = C.getState();
+
+  SymbolRef LastSetuidSym = State->get();
+  if (!LastSetuidSym)
+return;
+
+  if (!SymReaper.isDead(LastSetuidSym))
+return;
+
+  State = State->set(SymbolRef{});
+  C.addTransition(State, C.getPredecessor());
+}
+
+ProgramStateRef SetgidSetuidOrderChecker::evalAssume(ProgramStateRef State,
+ SVal Cond,
+ bool Assumption) const {

NagyDonat

[clang] [clang][analyzer] Add checker 'Security.SetgidSetuidOrder'. (PR #91445)

2024-05-08 Thread Donát Nagy via cfe-commits


@@ -0,0 +1,197 @@
+//===-- SetgidSetuidOrderChecker.cpp - check privilege revocation calls 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines a checker to detect possible reversed order of privilege
+//  revocations when 'setgid' and 'setuid' is used.
+//
+//===--===//
+
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
+
+using namespace clang;
+using namespace ento;
+
+namespace {
+
+class SetgidSetuidOrderChecker
+: public Checker {
+  const BugType BT_WrongRevocationOrder{
+  this, "Possible wrong order of privilege revocation"};
+
+  const CallDescription SetuidDesc{{"setuid"}, 1};
+  const CallDescription SetgidDesc{{"setgid"}, 1};
+  const CallDescription SeteuidDesc{{"seteuid"}, 1};
+  const CallDescription SetegidDesc{{"setegid"}, 1};
+  const CallDescription SetreuidDesc{{"setreuid"}, 2};
+  const CallDescription SetregidDesc{{"setregid"}, 2};
+  const CallDescription SetresuidDesc{{"setresuid"}, 3};
+  const CallDescription SetresgidDesc{{"setresgid"}, 3};
+
+public:
+  SetgidSetuidOrderChecker() {}
+
+  void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
+  void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
+  ProgramStateRef evalAssume(ProgramStateRef State, SVal Cond,
+ bool Assumption) const;
+
+private:
+  ProgramStateRef processSetuid(ProgramStateRef State, const CallEvent &Call,
+CheckerContext &C) const;
+  ProgramStateRef processSetgid(ProgramStateRef State, const CallEvent &Call,
+CheckerContext &C) const;
+  ProgramStateRef processOther(ProgramStateRef State, const CallEvent &Call,
+   CheckerContext &C) const;
+  /// Check if a function like \c getuid or \c getgid is called directly from
+  /// the first argument of function called from \a Call.
+  bool isFunctionCalledInArg(llvm::StringRef FnName,
+ const CallEvent &Call) const;
+  void emitReport(ProgramStateRef State, CheckerContext &C) const;
+};
+
+enum SetPrivilegeFunctionKind { Irrelevant, Setuid, Setgid };

NagyDonat wrote:

Perhaps place this `enum` declaration above the checker class. (When I was 
looking for its definition, I automatically scrolled to the top, and I was 
surprised that I didn't see it there.)

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


[clang] [clang][analyzer] Add checker 'Security.SetgidSetuidOrder'. (PR #91445)

2024-05-08 Thread Donát Nagy via cfe-commits


@@ -0,0 +1,197 @@
+//===-- SetgidSetuidOrderChecker.cpp - check privilege revocation calls 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines a checker to detect possible reversed order of privilege
+//  revocations when 'setgid' and 'setuid' is used.
+//
+//===--===//
+
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
+
+using namespace clang;
+using namespace ento;
+
+namespace {
+
+class SetgidSetuidOrderChecker
+: public Checker {
+  const BugType BT_WrongRevocationOrder{
+  this, "Possible wrong order of privilege revocation"};
+
+  const CallDescription SetuidDesc{{"setuid"}, 1};
+  const CallDescription SetgidDesc{{"setgid"}, 1};
+  const CallDescription SeteuidDesc{{"seteuid"}, 1};
+  const CallDescription SetegidDesc{{"setegid"}, 1};
+  const CallDescription SetreuidDesc{{"setreuid"}, 2};
+  const CallDescription SetregidDesc{{"setregid"}, 2};
+  const CallDescription SetresuidDesc{{"setresuid"}, 3};
+  const CallDescription SetresgidDesc{{"setresgid"}, 3};

NagyDonat wrote:

Please use the `MatchAs` argument of the `CallDescription` constructor, which 
was recently introduced by my changes. In this case you'd probably use the 
matching mode `CDM::CLibrary`.

Without this these call descriptions would match even a C++ method if it has 
the right name and number of arguments.

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


[clang] [clang][analyzer] Add checker 'Security.SetgidSetuidOrder'. (PR #91445)

2024-05-08 Thread Donát Nagy via cfe-commits


@@ -0,0 +1,197 @@
+//===-- SetgidSetuidOrderChecker.cpp - check privilege revocation calls 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines a checker to detect possible reversed order of privilege
+//  revocations when 'setgid' and 'setuid' is used.
+//
+//===--===//
+
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
+
+using namespace clang;
+using namespace ento;
+
+namespace {
+
+class SetgidSetuidOrderChecker
+: public Checker {
+  const BugType BT_WrongRevocationOrder{
+  this, "Possible wrong order of privilege revocation"};

NagyDonat wrote:

Use `BT` instead of this long variable name -- this is the only bug type in 
this class.

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


[clang] [clang][analyzer] Add checker 'Security.SetgidSetuidOrder'. (PR #91445)

2024-05-08 Thread Donát Nagy via cfe-commits


@@ -0,0 +1,197 @@
+//===-- SetgidSetuidOrderChecker.cpp - check privilege revocation calls 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines a checker to detect possible reversed order of privilege
+//  revocations when 'setgid' and 'setuid' is used.
+//
+//===--===//
+
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
+
+using namespace clang;
+using namespace ento;
+
+namespace {
+
+class SetgidSetuidOrderChecker
+: public Checker {
+  const BugType BT_WrongRevocationOrder{
+  this, "Possible wrong order of privilege revocation"};
+
+  const CallDescription SetuidDesc{{"setuid"}, 1};
+  const CallDescription SetgidDesc{{"setgid"}, 1};
+  const CallDescription SeteuidDesc{{"seteuid"}, 1};
+  const CallDescription SetegidDesc{{"setegid"}, 1};
+  const CallDescription SetreuidDesc{{"setreuid"}, 2};
+  const CallDescription SetregidDesc{{"setregid"}, 2};
+  const CallDescription SetresuidDesc{{"setresuid"}, 3};
+  const CallDescription SetresgidDesc{{"setresgid"}, 3};
+
+public:
+  SetgidSetuidOrderChecker() {}
+
+  void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
+  void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
+  ProgramStateRef evalAssume(ProgramStateRef State, SVal Cond,
+ bool Assumption) const;
+
+private:
+  ProgramStateRef processSetuid(ProgramStateRef State, const CallEvent &Call,
+CheckerContext &C) const;
+  ProgramStateRef processSetgid(ProgramStateRef State, const CallEvent &Call,
+CheckerContext &C) const;
+  ProgramStateRef processOther(ProgramStateRef State, const CallEvent &Call,
+   CheckerContext &C) const;
+  /// Check if a function like \c getuid or \c getgid is called directly from
+  /// the first argument of function called from \a Call.
+  bool isFunctionCalledInArg(llvm::StringRef FnName,
+ const CallEvent &Call) const;
+  void emitReport(ProgramStateRef State, CheckerContext &C) const;
+};
+
+enum SetPrivilegeFunctionKind { Irrelevant, Setuid, Setgid };
+
+} // end anonymous namespace
+
+/// Store if there was a call to 'setuid(getuid())' or 'setgid(getgid())' not
+/// followed by other different privilege-change functions.
+/// If the value \c Setuid is stored and a 'setgid(getgid())' call is found we
+/// have found the bug to be reported. Value \c Setgid is used too to prevent
+/// warnings at a setgid-setuid-setgid sequence.
+REGISTER_TRAIT_WITH_PROGRAMSTATE(LastSetPrivilegeCall, 
SetPrivilegeFunctionKind)
+/// Store the symbol value of the last 'setuid(getuid())' call. This is used to
+/// detect if the result is compared to -1 and avoid warnings on that branch
+/// (which is the failure branch of the call).
+REGISTER_TRAIT_WITH_PROGRAMSTATE(LastSetuidCallSVal, SymbolRef)
+
+void SetgidSetuidOrderChecker::checkPostCall(const CallEvent &Call,
+ CheckerContext &C) const {
+  ProgramStateRef State = C.getState();
+  if (SetuidDesc.matches(Call)) {
+State = processSetuid(State, Call, C);
+  } else if (SetgidDesc.matches(Call)) {
+State = processSetgid(State, Call, C);
+  } else if (matchesAny(Call, SeteuidDesc, SetegidDesc, SetreuidDesc,
+SetregidDesc, SetresuidDesc, SetresgidDesc)) {
+State = processOther(State, Call, C);
+  }
+  if (State)
+C.addTransition(State);
+}
+
+void SetgidSetuidOrderChecker::checkDeadSymbols(SymbolReaper &SymReaper,
+CheckerContext &C) const {
+  ProgramStateRef State = C.getState();
+
+  SymbolRef LastSetuidSym = State->get();
+  if (!LastSetuidSym)
+return;
+
+  if (!SymReaper.isDead(LastSetuidSym))
+return;
+
+  State = State->set(SymbolRef{});
+  C.addTransition(State, C.getPredecessor());
+}
+
+ProgramStateRef SetgidSetuidOrderChecker::evalAssume(ProgramStateRef State,
+ SVal Cond,
+ bool Assumption) const {
+  SValBuilder &SVB = Stat

[clang] [clang][analyzer] Add checker 'security.SetgidSetuidOrder'. (PR #91445)

2024-05-08 Thread Donát Nagy via cfe-commits

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


[clang] 6fa0961 - [analyzer] Use explicit call description mode in MIGChecker (#91331)

2024-05-08 Thread via cfe-commits

Author: Donát Nagy
Date: 2024-05-08T12:38:33+02:00
New Revision: 6fa09616da7436f85eb7e1e1fd74e1ac078ddb0d

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

LOG: [analyzer] Use explicit call description mode in MIGChecker (#91331)

This commit explicitly specifies the matching mode (C library function,
any non-method function, or C++ method) for the `CallDescription`s
constructed in the checker `osx.MIG`.

The code was simplified to use a `CallDescriptionMap` instead of a raw
vector of pairs.

This change won't cause major functional changes, but isn't NFC because
it ensures that e.g. call descriptions for a non-method function won't
accidentally match a method that has the same name.

Separate commits have already performed this change in other checkers:
- easy cases: e2f1cbae45f81f3cd9a4d3c2bcf69a094eb060fa,
6d64f8e1feee014e72730a78b62d9d415df112ff
- MallocChecker: d6d84b5d1448e4f2e24b467a0abcf42fe9d543e9
- iterator checkers: 06eedffe0d2782922e63cc25cb927f4acdaf7b30
- InvalidPtr checker: 024281d4d26344f9613b9115ea1fcbdbdba23235
- apiModeling.llvm.ReturnValue: 97dd8e3c4f38ef345b01fbbf0a2052c7875ff7e0

... and follow-up commits will handle the remaining few checkers.

My goal is to ensure that the call description mode is always explicitly
specified and eliminate (or strongly restrict) the vague "may be either
a method or a simple function" mode that's the current default.

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/MIGChecker.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/MIGChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/MIGChecker.cpp
index 153a0a51e9802..9757a00f1fb2f 100644
--- a/clang/lib/StaticAnalyzer/Checkers/MIGChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/MIGChecker.cpp
@@ -46,13 +46,13 @@ class MIGChecker : public Checker,
   // additionally an argument of a MIG routine, the checker keeps track of that
   // information and issues a warning when an error is returned from the
   // respective routine.
-  std::vector> Deallocators = {
+  CallDescriptionMap Deallocators = {
 #define CALL(required_args, deallocated_arg, ...)  
\
-  {{{__VA_ARGS__}, required_args}, deallocated_arg}
-  // E.g., if the checker sees a C function 'vm_deallocate' that is
-  // defined on class 'IOUserClient' that has exactly 3 parameters, it 
knows
-  // that argument #1 (starting from 0, i.e. the second argument) is going
-  // to be consumed in the sense of the MIG consume-on-success convention.
+  {{CDM::SimpleFunc, {__VA_ARGS__}, required_args}, deallocated_arg}
+  // E.g., if the checker sees a C function 'vm_deallocate' that has
+  // exactly 3 parameters, it knows that argument #1 (starting from 0, i.e.
+  // the second argument) is going to be consumed in the sense of the MIG
+  // consume-on-success convention.
   CALL(3, 1, "vm_deallocate"),
   CALL(3, 1, "mach_vm_deallocate"),
   CALL(2, 0, "mig_deallocate"),
@@ -78,6 +78,9 @@ class MIGChecker : public Checker,
   CALL(1, 0, "thread_inspect_deallocate"),
   CALL(1, 0, "upl_deallocate"),
   CALL(1, 0, "vm_map_deallocate"),
+#undef CALL
+#define CALL(required_args, deallocated_arg, ...)  
\
+  {{CDM::CXXMethod, {__VA_ARGS__}, required_args}, deallocated_arg}
   // E.g., if the checker sees a method 'releaseAsyncReference64()' that is
   // defined on class 'IOUserClient' that takes exactly 1 argument, it 
knows
   // that the argument is going to be consumed in the sense of the MIG
@@ -87,7 +90,7 @@ class MIGChecker : public Checker,
 #undef CALL
   };
 
-  CallDescription OsRefRetain{{"os_ref_retain"}, 1};
+  CallDescription OsRefRetain{CDM::SimpleFunc, {"os_ref_retain"}, 1};
 
   void checkReturnAux(const ReturnStmt *RS, CheckerContext &C) const;
 
@@ -198,15 +201,12 @@ void MIGChecker::checkPostCall(const CallEvent &Call, 
CheckerContext &C) const {
   if (!isInMIGCall(C))
 return;
 
-  auto I = llvm::find_if(Deallocators,
- [&](const std::pair &Item) 
{
-   return Item.first.matches(Call);
- });
-  if (I == Deallocators.end())
+  const unsigned *ArgIdxPtr = Deallocators.lookup(Call);
+  if (!ArgIdxPtr)
 return;
 
   ProgramStateRef State = C.getState();
-  unsigned ArgIdx = I->second;
+  unsigned ArgIdx = *ArgIdxPtr;
   SVal Arg = Call.getArgSVal(ArgIdx);
   const ParmVarDecl *PVD = getOriginParam(Arg, C);
   if (!PVD || State->contains(PVD))



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


[clang] [analyzer] Use explicit call description mode in MIGChecker (PR #91331)

2024-05-08 Thread Donát Nagy via cfe-commits

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


[clang] [clang] CTAD: implement the missing IsDeducible constraint for alias templates (PR #89358)

2024-05-08 Thread Haojian Wu via cfe-commits

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


[clang] [clang] CTAD: implement the missing IsDeducible constraint for alias templates (PR #89358)

2024-05-08 Thread Haojian Wu via cfe-commits


@@ -3239,6 +3239,40 @@ static TemplateDeductionResult 
FinishTemplateArgumentDeduction(
 
   return TemplateDeductionResult::Success;
 }
+/// Complete template argument deduction for DeduceTemplateArgumentsFromType.
+/// FIXME: this is mostly duplicated with the above two versions. Deduplicate
+/// the three implementations.

hokein wrote:

It is in my TODO list, but its priority is currently low, so I don't anticipate 
addressing it in the near future. This seems like a good candidate for a 
"GoodFirst" issue, so I'm thinking we can file an issue in case someone wants 
to contribute.

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


[clang] [clang] CTAD: implement the missing IsDeducible constraint for alias templates (PR #89358)

2024-05-08 Thread Haojian Wu via cfe-commits


@@ -27,7 +27,8 @@ enum TypeTrait {
   ,
 #define TYPE_TRAIT_2(Spelling, Name, Key) BTT_##Name,
 #include "clang/Basic/TokenKinds.def"
-  BTT_Last = UTT_Last // BTT_Last == last BTT_XX in the enum.
+  BTT_Last = UTT_Last

hokein wrote:

oops, this is not intended. This was left when I reverted some changes.

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


[clang] [clang] CTAD: implement the missing IsDeducible constraint for alias templates (PR #89358)

2024-05-08 Thread Haojian Wu via cfe-commits


@@ -190,13 +196,15 @@ template  struct Foo { Foo(T); };
 
 template using AFoo = Foo;
 template concept False = false;
-template using BFoo = AFoo;
+template
+using BFoo = AFoo; // expected-note {{candidate template ignored: 
constraints not satisfied [with V = int]}} \
+  // expected-note {{because '__is_deducible(BFoo, Foo)' evaluated to false}} \

hokein wrote:

Do you think this is a blocker for landing this PR?  The current state is 
acceptable to me, although not ideal. I plan to send out a follow-up patch to 
address it.

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


[clang] [clang] CTAD: implement the missing IsDeducible constraint for alias templates (PR #89358)

2024-05-08 Thread Haojian Wu via cfe-commits


@@ -3307,6 +3341,58 @@ 
Sema::DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
   return ::DeduceTemplateArguments(*this, Partial, TemplateArgs, Info);
 }
 
+TemplateDeductionResult
+Sema::DeduceTemplateArgumentsFromType(TemplateDecl *TD, QualType FromType,

hokein wrote:

This function is public (the documentation and comments are in `Sema.h` header).

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


[clang] [clang] CTAD: implement the missing IsDeducible constraint for alias templates (PR #89358)

2024-05-08 Thread Haojian Wu via cfe-commits

https://github.com/hokein commented:

Replied some review comments. I haven't updated the code yet (plan to do it 
after #90961)

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


[clang] [clang][dataflow] Allow `DataflowAnalysisContext` to use a non-owned `Solver`. (PR #91316)

2024-05-08 Thread Mehdi Amini via cfe-commits

joker-eph wrote:

CI failure wasn't unrelated actually: the CI is consistently broken after this 
patch (you have got an email about it?), I'll revert for now.

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


[clang] [clang][dataflow] Allow `DataflowAnalysisContext` to use a non-owned `Solver`. (PR #91316)

2024-05-08 Thread Mehdi Amini via cfe-commits

joker-eph wrote:

Actually your premerge failure here was an infra issue, but the CI is still 
broken after this PR somehow: 
https://lab.llvm.org/buildbot/#/builders/271/builds/7420

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


[clang] [Clang][OpenMP][Tile] Ensure AST node uniqueness. (PR #91325)

2024-05-08 Thread Michael Kruse via cfe-commits

Meinersbur wrote:

Test failure is from unrelated test `DataFlowSanitizer-x86_64 :: 
release_shadow_space.c`

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


[clang] [Clang][OpenMP][Tile] Ensure AST node uniqueness. (PR #91325)

2024-05-08 Thread Michael Kruse via cfe-commits

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


[clang] [Clang][OpenMP][Tile] Ensure AST node uniqueness. (PR #91325)

2024-05-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Michael Kruse (Meinersbur)


Changes

One of the constraints of an AST is that every node object must appear at most 
once, hence we define lamdas that create a new AST node at every use.

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


1 Files Affected:

- (modified) clang/lib/Sema/SemaOpenMP.cpp (+50-25) 


``diff
diff --git a/clang/lib/Sema/SemaOpenMP.cpp b/clang/lib/Sema/SemaOpenMP.cpp
index cf5447f223d45..fff4c7350f0f7 100644
--- a/clang/lib/Sema/SemaOpenMP.cpp
+++ b/clang/lib/Sema/SemaOpenMP.cpp
@@ -15109,6 +15109,8 @@ StmtResult 
SemaOpenMP::ActOnOpenMPTileDirective(ArrayRef Clauses,
 SourceLocation StartLoc,
 SourceLocation EndLoc) {
   ASTContext &Context = getASTContext();
+  Scope *CurScope = SemaRef.getCurScope();
+
   auto SizesClauses =
   OMPExecutableDirective::getClausesOfKind(Clauses);
   if (SizesClauses.empty()) {
@@ -15137,6 +15139,7 @@ StmtResult 
SemaOpenMP::ActOnOpenMPTileDirective(ArrayRef Clauses,
 NumLoops, AStmt, nullptr, nullptr);
 
   SmallVector PreInits;
+  CaptureVars CopyTransformer(SemaRef);
 
   // Create iteration variables for the generated loops.
   SmallVector FloorIndVars;
@@ -15200,19 +15203,30 @@ StmtResult 
SemaOpenMP::ActOnOpenMPTileDirective(ArrayRef Clauses,
 Expr *NumIterations = LoopHelper.NumIterations;
 auto *OrigCntVar = cast(LoopHelper.Counters[0]);
 QualType CntTy = OrigCntVar->getType();
-Expr *DimTileSize = SizesClause->getSizesRefs()[I];
-Scope *CurScope = SemaRef.getCurScope();
 
-// Commonly used variables.
-DeclRefExpr *TileIV = buildDeclRefExpr(SemaRef, TileIndVars[I], CntTy,
-   OrigCntVar->getExprLoc());
-DeclRefExpr *FloorIV = buildDeclRefExpr(SemaRef, FloorIndVars[I], CntTy,
-OrigCntVar->getExprLoc());
+// Commonly used variables. One of the constraints of an AST is that every
+// node object must appear at most once, hence we define lamdas that create
+// a new AST node at every use.
+auto MakeDimTileSize = [&SemaRef = this->SemaRef, &CopyTransformer, I,
+SizesClause]() -> Expr * {
+  Expr *DimTileSize = SizesClause->getSizesRefs()[I];
+  return AssertSuccess(CopyTransformer.TransformExpr(DimTileSize));
+};
+auto MakeTileIVRef = [&SemaRef = this->SemaRef, &TileIndVars, I, CntTy,
+  OrigCntVar]() {
+  return buildDeclRefExpr(SemaRef, TileIndVars[I], CntTy,
+  OrigCntVar->getExprLoc());
+};
+auto MakeFloorIVRef = [&SemaRef = this->SemaRef, &FloorIndVars, I, CntTy,
+   OrigCntVar]() {
+  return buildDeclRefExpr(SemaRef, FloorIndVars[I], CntTy,
+  OrigCntVar->getExprLoc());
+};
 
 // For init-statement: auto .tile.iv = .floor.iv
-SemaRef.AddInitializerToDecl(TileIndVars[I],
- 
SemaRef.DefaultLvalueConversion(FloorIV).get(),
- /*DirectInit=*/false);
+SemaRef.AddInitializerToDecl(
+TileIndVars[I], 
SemaRef.DefaultLvalueConversion(MakeFloorIVRef()).get(),
+/*DirectInit=*/false);
 Decl *CounterDecl = TileIndVars[I];
 StmtResult InitStmt = new (Context)
 DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1),
@@ -15220,10 +15234,11 @@ StmtResult 
SemaOpenMP::ActOnOpenMPTileDirective(ArrayRef Clauses,
 if (!InitStmt.isUsable())
   return StmtError();
 
-// For cond-expression: .tile.iv < min(.floor.iv + DimTileSize,
-// NumIterations)
-ExprResult EndOfTile = SemaRef.BuildBinOp(
-CurScope, LoopHelper.Cond->getExprLoc(), BO_Add, FloorIV, DimTileSize);
+// For cond-expression:
+//   .tile.iv < min(.floor.iv + DimTileSize, NumIterations)
+ExprResult EndOfTile =
+SemaRef.BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_Add,
+   MakeFloorIVRef(), MakeDimTileSize());
 if (!EndOfTile.isUsable())
   return StmtError();
 ExprResult IsPartialTile =
@@ -15238,25 +15253,28 @@ StmtResult 
SemaOpenMP::ActOnOpenMPTileDirective(ArrayRef Clauses,
   return StmtError();
 ExprResult CondExpr =
 SemaRef.BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT,
-   TileIV, MinTileAndIterSpace.get());
+   MakeTileIVRef(), MinTileAndIterSpace.get());
 if (!CondExpr.isUsable())
   return StmtError();
 
 // For incr-statement: ++.tile.iv
 ExprResult IncrStmt = SemaRef.BuildUnaryOp(
-CurScope, LoopHelper.Inc->getExprLoc(), UO_PreInc, TileIV);
+CurScope, LoopHelper.Inc->getExprLoc(), UO_PreInc, MakeTileIVRef());
 if (!IncrStmt.isUsable())
   return StmtError();
 
 

[clang] [Clang][OpenMP][Tile] Ensure AST node uniqueness. (PR #91325)

2024-05-08 Thread Alexander Batashev via cfe-commits

alexbatashev wrote:

I think I'm the wrong person to review this PR. Is @alexey-bataev a more 
appropriate reviewer? 

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


[clang] [Clang][AArch64] Require SVE or SSVE for scalable types. (PR #91356)

2024-05-08 Thread Paul Walker via cfe-commits

https://github.com/paulwalker-arm requested changes to this pull request.

As discussed offline, I don't think we want to be this strict.  As demonstrated 
by the changes to the ACLE tests, this change makes it impossible to distribute 
a library in binary form that can work for both SVE and InStreamingMode 
environments.  I believe functions decorated with `__arm_streaming_compatible` 
should be allowed to assume the presence of the subset of instructions that is 
available to both environments. Library users get protected at the point they 
call such functions whereby a compilation error is emitted when the caller 
either doesn't have access to SVE or is not in streaming mode.

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


[clang] [clang][dataflow] Allow `DataflowAnalysisContext` to use a non-owned `Solver`. (PR #91316)

2024-05-08 Thread via cfe-commits

martinboehme wrote:

> Actually your premerge failure here was an infra issue, but the CI is still 
> broken after this PR somehow: 
> https://lab.llvm.org/buildbot/#/builders/271/builds/7420
> 
> ```
> # .---command stderr
> # | error: 'expected-error' diagnostics seen but not expected: 
> # |   (frontend): '-fsyntax-only' action ignored; '-ast-print' action 
> specified previously
> # `-
> ```

This is a failure in the test clang\test\OpenMP\target_ast_print.cpp, correct?

Are you sure this PR is the culprit? It touches only the dataflow framework, 
which is not used in OpenMP or the Clang compiler itself.

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


[clang] [clang][dataflow] Allow `DataflowAnalysisContext` to use a non-owned `Solver`. (PR #91316)

2024-05-08 Thread via cfe-commits

martinboehme wrote:

@joker-eph 

PS I don't see a revert of this PR, but I do see a revert of a different PR 
[here](https://github.com/llvm/llvm-project/commit/341aecc2dd0f6debcbe9f251a6d2e8a60d327eea),
 and that PR does look as if it could be the culprit.

Maybe you commented on this PR by mistake?

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


[clang] 943617d - Typo fix; NFC

2024-05-08 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2024-05-08T08:03:22-04:00
New Revision: 943617d12ccbd3cf317f0bbec03d9efc700f3953

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

LOG: Typo fix; NFC

Added: 


Modified: 
clang/lib/CodeGen/CGExprAgg.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGExprAgg.cpp b/clang/lib/CodeGen/CGExprAgg.cpp
index cd9936a6dc0b8..6172eb9cdc1bb 100644
--- a/clang/lib/CodeGen/CGExprAgg.cpp
+++ b/clang/lib/CodeGen/CGExprAgg.cpp
@@ -1736,7 +1736,7 @@ void AggExprEmitter::VisitCXXParenListOrInitListExpr(
   for (const auto *Field : record->fields())
 assert(
 (Field->isUnnamedBitField() || Field->isAnonymousStructOrUnion()) 
&&
-"Only unnamed bitfields or ananymous class allowed");
+"Only unnamed bitfields or anonymous class allowed");
 #endif
   return;
 }



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


[clang] [clang] CTAD: implement the missing IsDeducible constraint for alias templates (PR #89358)

2024-05-08 Thread via cfe-commits


@@ -190,13 +196,15 @@ template  struct Foo { Foo(T); };
 
 template using AFoo = Foo;
 template concept False = false;
-template using BFoo = AFoo;
+template
+using BFoo = AFoo; // expected-note {{candidate template ignored: 
constraints not satisfied [with V = int]}} \
+  // expected-note {{because '__is_deducible(BFoo, Foo)' evaluated to false}} \

cor3ntin wrote:

I certainly think it's not a good user-facing diagnostic, and i don't think the 
fix would be difficult
but doing it separately seems reasonable. WDYT @AaronBallman? 

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


[clang] [llvm] [clang][dataflow] Make `SolverTest` a type-parameterized test. (PR #91455)

2024-05-08 Thread Yitzhak Mandelbaum via cfe-commits

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


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


[clang] c5509fe - [HLSL] Support packoffset attribute in AST (#89836)

2024-05-08 Thread via cfe-commits

Author: Xiang Li
Date: 2024-05-08T05:26:34-07:00
New Revision: c5509fedc5757fffece385d9d068e36b26793ade

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

LOG: [HLSL] Support packoffset attribute in AST (#89836)

Add HLSLPackOffsetAttr to save packoffset in AST.

Since we have to parse the attribute manually in ParseHLSLAnnotations,
we could create the ParsedAttribute with a integer offset parameter
instead of string. This approach avoids parsing the string if the offset
is saved as a string in HLSLPackOffsetAttr.

For #57914.

Added: 
clang/test/AST/HLSL/packoffset.hlsl
clang/test/SemaHLSL/packoffset-invalid.hlsl

Modified: 
clang/include/clang/Basic/Attr.td
clang/include/clang/Basic/AttrDocs.td
clang/include/clang/Basic/DiagnosticGroups.td
clang/include/clang/Basic/DiagnosticParseKinds.td
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Parse/ParseHLSL.cpp
clang/lib/Sema/SemaDeclAttr.cpp
clang/lib/Sema/SemaHLSL.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 0225598cbbe8a..52552ba488560 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -4415,6 +4415,18 @@ def HLSLResourceBinding: InheritableAttr {
   let Documentation = [HLSLResourceBindingDocs];
 }
 
+def HLSLPackOffset: HLSLAnnotationAttr {
+  let Spellings = [HLSLAnnotation<"packoffset">];
+  let LangOpts = [HLSL];
+  let Args = [IntArgument<"Subcomponent">, IntArgument<"Component">];
+  let Documentation = [HLSLPackOffsetDocs];
+  let AdditionalMembers = [{
+  unsigned getOffset() {
+return subcomponent * 4 + component;
+  }
+  }];
+}
+
 def HLSLSV_DispatchThreadID: HLSLAnnotationAttr {
   let Spellings = [HLSLAnnotation<"SV_DispatchThreadID">];
   let Subjects = SubjectList<[ParmVar, Field]>;

diff  --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index 8e6faabfae647..f351822ac74bd 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -7408,6 +7408,26 @@ The full documentation is available here: 
https://docs.microsoft.com/en-us/windo
   }];
 }
 
+def HLSLPackOffsetDocs : Documentation {
+  let Category = DocCatFunction;
+  let Content = [{
+The packoffset attribute is used to change the layout of a cbuffer.
+Attribute spelling in HLSL is: ``packoffset( c[Subcomponent][.component] )``.
+A subcomponent is a register number, which is an integer. A component is in 
the form of [.xyzw].
+
+Examples:
+
+.. code-block:: c++
+
+  cbuffer A {
+float3 a : packoffset(c0.y);
+float4 b : packoffset(c4);
+  }
+
+The full documentation is available here: 
https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-variable-packoffset
+  }];
+}
+
 def HLSLSV_DispatchThreadIDDocs : Documentation {
   let Category = DocCatFunction;
   let Content = [{

diff  --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index 60f87da2a7387..2beb1d45124b4 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -1507,6 +1507,9 @@ def BranchProtection : DiagGroup<"branch-protection">;
 // Warnings for HLSL Clang extensions
 def HLSLExtension : DiagGroup<"hlsl-extensions">;
 
+// Warning for mix packoffset and non-packoffset.
+def HLSLMixPackOffset : DiagGroup<"mix-packoffset">;
+
 // Warnings for DXIL validation
 def DXILValidation : DiagGroup<"dxil-validation">;
 

diff  --git a/clang/include/clang/Basic/DiagnosticParseKinds.td 
b/clang/include/clang/Basic/DiagnosticParseKinds.td
index fdffb35ea0d95..bc9d7cacc50b7 100644
--- a/clang/include/clang/Basic/DiagnosticParseKinds.td
+++ b/clang/include/clang/Basic/DiagnosticParseKinds.td
@@ -1754,5 +1754,7 @@ def err_hlsl_separate_attr_arg_and_number : Error<"wrong 
argument format for hls
 def ext_hlsl_access_specifiers : ExtWarn<
   "access specifiers are a clang HLSL extension">,
   InGroup;
+def err_hlsl_unsupported_component : Error<"invalid component '%0' used; 
expected 'x', 'y', 'z', or 'w'">;
+def err_hlsl_packoffset_invalid_reg : Error<"invalid resource class specifier 
'%0' for packoffset, expected 'c'">;
 
 } // end of Parser diagnostics

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 9317ae675c72b..d6863f90edb6e 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -12184,6 +12184,11 @@ def err_hlsl_init_priority_unsupported : Error<
 def err_hlsl_unsupported_register_type : Error<"invalid resource class 
specifier '%0' used; expected 'b', 's', 't', or 'u'">;
 def err_hlsl_unsupported_reg

[clang] [HLSL] Support packoffset attribute in AST (PR #89836)

2024-05-08 Thread Xiang Li via cfe-commits

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


[clang] [clang][ExtractAPI] Distinguish between record kind for display and for RTTI (PR #91466)

2024-05-08 Thread Daniel Grumberg via cfe-commits

https://github.com/daniel-grumberg created 
https://github.com/llvm/llvm-project/pull/91466

rdar://127732562

>From d1118a8552d84e044cd0f22cd8b46e5e65b43cae Mon Sep 17 00:00:00 2001
From: Daniel Grumberg 
Date: Wed, 8 May 2024 11:55:15 +0100
Subject: [PATCH] [clang][ExtractAPI] Distinguish between record kind for
 display and for RTTI

---
 clang/include/clang/ExtractAPI/API.h  |  6 +++--
 .../clang/ExtractAPI/ExtractAPIVisitor.h  | 23 +++
 .../Serialization/SymbolGraphSerializer.cpp   |  4 ++--
 3 files changed, 20 insertions(+), 13 deletions(-)

diff --git a/clang/include/clang/ExtractAPI/API.h 
b/clang/include/clang/ExtractAPI/API.h
index d323e1668a72b..d2341f004c52f 100644
--- a/clang/include/clang/ExtractAPI/API.h
+++ b/clang/include/clang/ExtractAPI/API.h
@@ -266,6 +266,7 @@ struct APIRecord {
 
   AccessControl Access;
 
+  RecordKind KindForDisplay;
 private:
   const RecordKind Kind;
   friend class RecordContext;
@@ -277,6 +278,7 @@ struct APIRecord {
   APIRecord *getNextInContext() const { return NextInContext; }
 
   RecordKind getKind() const { return Kind; }
+  RecordKind getKindForDisplay() const { return KindForDisplay; }
 
   static APIRecord *castFromRecordContext(const RecordContext *Ctx);
   static RecordContext *castToRecordContext(const APIRecord *Record);
@@ -293,10 +295,10 @@ struct APIRecord {
 Availability(std::move(Availability)), Linkage(Linkage),
 Comment(Comment), Declaration(Declaration), SubHeading(SubHeading),
 IsFromSystemHeader(IsFromSystemHeader), Access(std::move(Access)),
-Kind(Kind) {}
+KindForDisplay(Kind), Kind(Kind) {}
 
   APIRecord(RecordKind Kind, StringRef USR, StringRef Name)
-  : USR(USR), Name(Name), Kind(Kind) {}
+  : USR(USR), Name(Name), KindForDisplay(Kind), Kind(Kind) {}
 
   // Pure virtual destructor to make APIRecord abstract
   virtual ~APIRecord() = 0;
diff --git a/clang/include/clang/ExtractAPI/ExtractAPIVisitor.h 
b/clang/include/clang/ExtractAPI/ExtractAPIVisitor.h
index 97cc457ea2a92..482a81f750a76 100644
--- a/clang/include/clang/ExtractAPI/ExtractAPIVisitor.h
+++ b/clang/include/clang/ExtractAPI/ExtractAPIVisitor.h
@@ -194,6 +194,15 @@ class ExtractAPIVisitorBase : public 
RecursiveASTVisitor {
 return Bases;
   }
 
+  APIRecord::RecordKind getKindForDisplay(const CXXRecordDecl *Decl) {
+if (Decl->isUnion())
+  return APIRecord::RK_Union;
+if (Decl->isStruct())
+  return APIRecord::RK_Struct;
+
+return APIRecord::RK_CXXClass;
+  }
+
   StringRef getOwningModuleName(const Decl &D) {
 if (auto *OwningModule = D.getImportedOwningModule())
   return OwningModule->Name;
@@ -599,13 +608,6 @@ bool ExtractAPIVisitorBase::VisitCXXRecordDecl(
   DeclarationFragments SubHeading =
   DeclarationFragmentsBuilder::getSubHeading(Decl);
 
-  APIRecord::RecordKind Kind;
-  if (Decl->isUnion())
-Kind = APIRecord::RecordKind::RK_Union;
-  else if (Decl->isStruct())
-Kind = APIRecord::RecordKind::RK_Struct;
-  else
-Kind = APIRecord::RecordKind::RK_CXXClass;
   auto Access = DeclarationFragmentsBuilder::getAccessControl(Decl);
 
   CXXClassRecord *Record;
@@ -619,13 +621,15 @@ bool ExtractAPIVisitorBase::VisitCXXRecordDecl(
 AvailabilityInfo::createFromDecl(Decl), Comment, Declaration,
 SubHeading, Template(Decl->getDescribedClassTemplate()), Access,
 isInSystemHeader(Decl));
-  } else
+  } else {
 Record = API.createRecord(
 USR, Name, createHierarchyInformationForDecl(*Decl), Loc,
 AvailabilityInfo::createFromDecl(Decl), Comment, Declaration,
-SubHeading, Kind, Access, isInSystemHeader(Decl),
+SubHeading, APIRecord::RecordKind::RK_CXXClass, Access, 
isInSystemHeader(Decl),
 isEmbeddedInVarDeclarator(*Decl));
+  }
 
+  Record->KindForDisplay = getKindForDisplay(Decl);
   Record->Bases = getBases(Decl);
 
   return true;
@@ -849,6 +853,7 @@ bool ExtractAPIVisitorBase::
   Template(Decl), DeclarationFragmentsBuilder::getAccessControl(Decl),
   isInSystemHeader(Decl));
 
+  CTPSR->KindForDisplay = getKindForDisplay(Decl);
   CTPSR->Bases = getBases(Decl);
 
   return true;
diff --git a/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp 
b/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
index 34278b5d40c42..952deccded07d 100644
--- a/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
+++ b/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
@@ -514,7 +514,7 @@ Object serializeSymbolKind(APIRecord::RecordKind RK, 
Language Lang) {
 /// which is prefixed by the source language name, useful for tooling to parse
 /// the kind, and a \c displayName for rendering human-readable names.
 Object serializeSymbolKind(const APIRecord &Record, Language Lang) {
-  return serializeSymbolKind(Record.getKind(), Lang);
+  return serializeSymbolKind(Record.KindForDisplay, Lang);
 }
 
 /// Serialize the function signature field, as specified by

[clang] [clang][ExtractAPI] Distinguish between record kind for display and for RTTI (PR #91466)

2024-05-08 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Daniel Grumberg (daniel-grumberg)


Changes

rdar://127732562

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


3 Files Affected:

- (modified) clang/include/clang/ExtractAPI/API.h (+4-2) 
- (modified) clang/include/clang/ExtractAPI/ExtractAPIVisitor.h (+14-9) 
- (modified) clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp 
(+2-2) 


``diff
diff --git a/clang/include/clang/ExtractAPI/API.h 
b/clang/include/clang/ExtractAPI/API.h
index d323e1668a72b..d2341f004c52f 100644
--- a/clang/include/clang/ExtractAPI/API.h
+++ b/clang/include/clang/ExtractAPI/API.h
@@ -266,6 +266,7 @@ struct APIRecord {
 
   AccessControl Access;
 
+  RecordKind KindForDisplay;
 private:
   const RecordKind Kind;
   friend class RecordContext;
@@ -277,6 +278,7 @@ struct APIRecord {
   APIRecord *getNextInContext() const { return NextInContext; }
 
   RecordKind getKind() const { return Kind; }
+  RecordKind getKindForDisplay() const { return KindForDisplay; }
 
   static APIRecord *castFromRecordContext(const RecordContext *Ctx);
   static RecordContext *castToRecordContext(const APIRecord *Record);
@@ -293,10 +295,10 @@ struct APIRecord {
 Availability(std::move(Availability)), Linkage(Linkage),
 Comment(Comment), Declaration(Declaration), SubHeading(SubHeading),
 IsFromSystemHeader(IsFromSystemHeader), Access(std::move(Access)),
-Kind(Kind) {}
+KindForDisplay(Kind), Kind(Kind) {}
 
   APIRecord(RecordKind Kind, StringRef USR, StringRef Name)
-  : USR(USR), Name(Name), Kind(Kind) {}
+  : USR(USR), Name(Name), KindForDisplay(Kind), Kind(Kind) {}
 
   // Pure virtual destructor to make APIRecord abstract
   virtual ~APIRecord() = 0;
diff --git a/clang/include/clang/ExtractAPI/ExtractAPIVisitor.h 
b/clang/include/clang/ExtractAPI/ExtractAPIVisitor.h
index 97cc457ea2a92..482a81f750a76 100644
--- a/clang/include/clang/ExtractAPI/ExtractAPIVisitor.h
+++ b/clang/include/clang/ExtractAPI/ExtractAPIVisitor.h
@@ -194,6 +194,15 @@ class ExtractAPIVisitorBase : public 
RecursiveASTVisitor {
 return Bases;
   }
 
+  APIRecord::RecordKind getKindForDisplay(const CXXRecordDecl *Decl) {
+if (Decl->isUnion())
+  return APIRecord::RK_Union;
+if (Decl->isStruct())
+  return APIRecord::RK_Struct;
+
+return APIRecord::RK_CXXClass;
+  }
+
   StringRef getOwningModuleName(const Decl &D) {
 if (auto *OwningModule = D.getImportedOwningModule())
   return OwningModule->Name;
@@ -599,13 +608,6 @@ bool ExtractAPIVisitorBase::VisitCXXRecordDecl(
   DeclarationFragments SubHeading =
   DeclarationFragmentsBuilder::getSubHeading(Decl);
 
-  APIRecord::RecordKind Kind;
-  if (Decl->isUnion())
-Kind = APIRecord::RecordKind::RK_Union;
-  else if (Decl->isStruct())
-Kind = APIRecord::RecordKind::RK_Struct;
-  else
-Kind = APIRecord::RecordKind::RK_CXXClass;
   auto Access = DeclarationFragmentsBuilder::getAccessControl(Decl);
 
   CXXClassRecord *Record;
@@ -619,13 +621,15 @@ bool ExtractAPIVisitorBase::VisitCXXRecordDecl(
 AvailabilityInfo::createFromDecl(Decl), Comment, Declaration,
 SubHeading, Template(Decl->getDescribedClassTemplate()), Access,
 isInSystemHeader(Decl));
-  } else
+  } else {
 Record = API.createRecord(
 USR, Name, createHierarchyInformationForDecl(*Decl), Loc,
 AvailabilityInfo::createFromDecl(Decl), Comment, Declaration,
-SubHeading, Kind, Access, isInSystemHeader(Decl),
+SubHeading, APIRecord::RecordKind::RK_CXXClass, Access, 
isInSystemHeader(Decl),
 isEmbeddedInVarDeclarator(*Decl));
+  }
 
+  Record->KindForDisplay = getKindForDisplay(Decl);
   Record->Bases = getBases(Decl);
 
   return true;
@@ -849,6 +853,7 @@ bool ExtractAPIVisitorBase::
   Template(Decl), DeclarationFragmentsBuilder::getAccessControl(Decl),
   isInSystemHeader(Decl));
 
+  CTPSR->KindForDisplay = getKindForDisplay(Decl);
   CTPSR->Bases = getBases(Decl);
 
   return true;
diff --git a/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp 
b/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
index 34278b5d40c42..952deccded07d 100644
--- a/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
+++ b/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
@@ -514,7 +514,7 @@ Object serializeSymbolKind(APIRecord::RecordKind RK, 
Language Lang) {
 /// which is prefixed by the source language name, useful for tooling to parse
 /// the kind, and a \c displayName for rendering human-readable names.
 Object serializeSymbolKind(const APIRecord &Record, Language Lang) {
-  return serializeSymbolKind(Record.getKind(), Lang);
+  return serializeSymbolKind(Record.KindForDisplay, Lang);
 }
 
 /// Serialize the function signature field, as specified by the
@@ -592,7 +592,7 @@ Array generateParentContexts(const 
SmallVectorImpl &Parents,
 Elem["name"] = Parent.Name;
 if (Parent.Record)
 

[clang] [Serialization] Check for stack exhaustion when reading declarations (PR #79875)

2024-05-08 Thread Aaron Ballman via cfe-commits

AaronBallman wrote:

> I think we should apply @ChuanqiXu9 suggestion and merge that without tests. 
> At worse it's harmless, at best it solves an actual issue for users. We have 
> precedent for not being able to test resource exhaustion fixes.

I would not be opposed to landing with a test, but I think such a test would be 
challenging because stack exhaustion is often slow to trigger and highly 
machine-dependent (so I can imagine the test failing "randomly" for different 
configurations or under different workloads, or being a very slow test to 
execute). So if there's a simple, quick-to-execute, reliably-failing test we 
can add, then great! But if there's not, I would be fine landing without tests.

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


[clang] [clang][ExtractAPI] Distinguish between record kind for display and for RTTI (PR #91466)

2024-05-08 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 01e91a2dde497b71b0b85d5ec0f101a21e9c892c 
d1118a8552d84e044cd0f22cd8b46e5e65b43cae -- 
clang/include/clang/ExtractAPI/API.h 
clang/include/clang/ExtractAPI/ExtractAPIVisitor.h 
clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/include/clang/ExtractAPI/API.h 
b/clang/include/clang/ExtractAPI/API.h
index d2341f004c..bf291074fd 100644
--- a/clang/include/clang/ExtractAPI/API.h
+++ b/clang/include/clang/ExtractAPI/API.h
@@ -267,6 +267,7 @@ struct APIRecord {
   AccessControl Access;
 
   RecordKind KindForDisplay;
+
 private:
   const RecordKind Kind;
   friend class RecordContext;
diff --git a/clang/include/clang/ExtractAPI/ExtractAPIVisitor.h 
b/clang/include/clang/ExtractAPI/ExtractAPIVisitor.h
index 482a81f750..8ccebe457e 100644
--- a/clang/include/clang/ExtractAPI/ExtractAPIVisitor.h
+++ b/clang/include/clang/ExtractAPI/ExtractAPIVisitor.h
@@ -625,8 +625,8 @@ bool ExtractAPIVisitorBase::VisitCXXRecordDecl(
 Record = API.createRecord(
 USR, Name, createHierarchyInformationForDecl(*Decl), Loc,
 AvailabilityInfo::createFromDecl(Decl), Comment, Declaration,
-SubHeading, APIRecord::RecordKind::RK_CXXClass, Access, 
isInSystemHeader(Decl),
-isEmbeddedInVarDeclarator(*Decl));
+SubHeading, APIRecord::RecordKind::RK_CXXClass, Access,
+isInSystemHeader(Decl), isEmbeddedInVarDeclarator(*Decl));
   }
 
   Record->KindForDisplay = getKindForDisplay(Decl);
diff --git a/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp 
b/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
index 952deccded..c16d4623f1 100644
--- a/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
+++ b/clang/lib/ExtractAPI/Serialization/SymbolGraphSerializer.cpp
@@ -591,8 +591,8 @@ Array generateParentContexts(const 
SmallVectorImpl &Parents,
 Elem["usr"] = Parent.USR;
 Elem["name"] = Parent.Name;
 if (Parent.Record)
-  Elem["kind"] =
-  serializeSymbolKind(Parent.Record->KindForDisplay, 
Lang)["identifier"];
+  Elem["kind"] = serializeSymbolKind(Parent.Record->KindForDisplay,
+ Lang)["identifier"];
 else
   Elem["kind"] =
   serializeSymbolKind(APIRecord::RK_Unknown, Lang)["identifier"];

``




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


[clang] Revise the modules document for clarity (PR #90237)

2024-05-08 Thread Aaron Ballman via cfe-commits


@@ -8,109 +8,91 @@ Standard C++ Modules
 Introduction
 
 
-The term ``modules`` has a lot of meanings. For the users of Clang, modules may
-refer to ``Objective-C Modules``, ``Clang C++ Modules`` (or ``Clang Header 
Modules``,
-etc.) or ``Standard C++ Modules``. The implementation of all these kinds of 
modules in Clang
-has a lot of shared code, but from the perspective of users, their semantics 
and
-command line interfaces are very different. This document focuses on
-an introduction of how to use standard C++ modules in Clang.
-
-There is already a detailed document about `Clang modules `_, it
-should be helpful to read `Clang modules `_ if you want to know
-more about the general idea of modules. Since standard C++ modules have 
different semantics
-(and work flows) from `Clang modules`, this page describes the background and 
use of
-Clang with standard C++ modules.
-
-Modules exist in two forms in the C++ Language Specification. They can refer to
-either "Named Modules" or to "Header Units". This document covers both forms.
+The term ``module`` has a lot of meanings. For Clang users, a module may refer
+to an ``Objective-C Module``, `Clang Module `_ (also called a
+``Clang Header Module``) or a ``C++20 Module`` (or a ``Standard C++ Module``).
+The implementation of all these kinds of modules in Clang shares a lot of code,
+but from the perspective of users, their semantics and command line interfaces
+are very different. This document focuses on an introduction to the use of
+C++20 modules in Clang. In the remainder of this document, the term ``module``
+will refer to Standard C++20 modules and the term ``Clang module`` will refer
+to the Clang modules extension.
+
+Modules exist in two forms in the C++ Standard. They can refer to either
+"Named Modules" or "Header Units". This document covers both forms.
 
 Standard C++ Named modules
 ==
 
-This document was intended to be a manual first and foremost, however, we 
consider it helpful to
-introduce some language background here for readers who are not familiar with
-the new language feature. This document is not intended to be a language
-tutorial; it will only introduce necessary concepts about the
-structure and building of the project.
+In order to understand compiler behavior, it is helpful to introduce some
+terms and definitions for readers who are not familiar with the C++ feature.
+This document is not a tutorial on C++; it only introduces necessary concepts
+to better understand use of modules in a project.
 
 Background and terminology
 --
 
-Modules
-~~~
-
-In this document, the term ``Modules``/``modules`` refers to standard C++ 
modules
-feature if it is not decorated by ``Clang``.
-
-Clang Modules
-~
-
-In this document, the term ``Clang Modules``/``Clang modules`` refer to Clang
-c++ modules extension. These are also known as ``Clang header modules``,
-``Clang module map modules`` or ``Clang c++ modules``.
-
 Module and module unit
 ~~
 
-A module consists of one or more module units. A module unit is a special
-translation unit. Every module unit must have a module declaration. The syntax
-of the module declaration is:
+A module consists of one or more module units. A module unit is a special kind
+of translation unit. Every module unit must have a module declaration. The
+syntax of the module declaration is:
 
 .. code-block:: c++
 
   [export] module module_name[:partition_name];
 
-Terms enclosed in ``[]`` are optional. The syntax of ``module_name`` and 
``partition_name``
-in regex form corresponds to ``[a-zA-Z_][a-zA-Z_0-9\.]*``. In particular, a 
literal dot ``.``
-in the name has no semantic meaning (e.g. implying a hierarchy).
+Terms enclosed in ``[]`` are optional. ``module_name`` and ``partition_name``
+are typical C++ identifiers, except that they may contain a period (``.``).
+Note that a ``.`` in the name has no semantic meaning (e.g. implying a
+hierarchy or referring to the file system).
 
-In this document, module units are classified into:
+In this document, module units are classified as:
 
-* Primary module interface unit.
-
-* Module implementation unit.
-
-* Module interface partition unit.
-
-* Internal module partition unit.
+* Primary module interface unit
+* Module implementation unit
+* Module partition interface unit
+* Module partition implementation unit
 
 A primary module interface unit is a module unit whose module declaration is
-``export module module_name;``. The ``module_name`` here denotes the name of 
the
+``export module module_name;`` where ``module_name`` denotes the name of the
 module. A module should have one and only one primary module interface unit.
 
 A module implementation unit is a module unit whose module declaration is
-``module module_name;``. A module could have multiple module implementation
-units with the same declaration.
+``module module_name;``. Multiple module 

[clang] [llvm] [AArch64] Fix feature flags dependecies (PR #90612)

2024-05-08 Thread via cfe-commits


@@ -291,18 +290,17 @@ inline constexpr ExtensionInfo Extensions[] = {
 {"tme", AArch64::AEK_TME, "+tme", "-tme", FEAT_INIT, "", 0},
 {"wfxt", AArch64::AEK_NONE, {}, {}, FEAT_WFXT, "+wfxt", 550},
 {"gcs", AArch64::AEK_GCS, "+gcs", "-gcs", FEAT_INIT, "", 0},
-{"fpmr", AArch64::AEK_FPMR, "+fpmr", "-fpmr", FEAT_INIT, "", 0},
-{"fp8", AArch64::AEK_FP8, "+fp8", "-fp8", FEAT_INIT, "+fpmr", 0},
+{"fp8", AArch64::AEK_FP8, "+fp8", "-fp8", FEAT_INIT, "+faminmax, +lut, 
+bf16", 0},
 {"faminmax", AArch64::AEK_FAMINMAX, "+faminmax", "-faminmax", FEAT_INIT, 
"", 0},
-{"fp8fma", AArch64::AEK_FP8FMA, "+fp8fma", "-fp8fma", FEAT_INIT, "+fpmr", 
0},
-{"ssve-fp8fma", AArch64::AEK_SSVE_FP8FMA, "+ssve-fp8fma", "-ssve-fp8fma", 
FEAT_INIT, "+sme2", 0},
-{"fp8dot2", AArch64::AEK_FP8DOT2, "+fp8dot2", "-fp8dot2", FEAT_INIT, "", 
0},
-{"ssve-fp8dot2", AArch64::AEK_SSVE_FP8DOT2, "+ssve-fp8dot2", 
"-ssve-fp8dot2", FEAT_INIT, "+sme2", 0},
-{"fp8dot4", AArch64::AEK_FP8DOT4, "+fp8dot4", "-fp8dot4", FEAT_INIT, "", 
0},
-{"ssve-fp8dot4", AArch64::AEK_SSVE_FP8DOT4, "+ssve-fp8dot4", 
"-ssve-fp8dot4", FEAT_INIT, "+sme2", 0},
+{"fp8fma", AArch64::AEK_FP8FMA, "+fp8fma", "-fp8fma", FEAT_INIT, "+fp8", 
0},

CarolineConcatto wrote:

Just in case, @tmatheson-arm left a comment in this patch:
https://github.com/llvm/llvm-project/pull/88860
About FEAT_INIT and function multi-version. 
If we have FEAT_INIT we should leave the list of dependencies empty, unless we 
want it to work with FMV
Maybe we should remove the dependencies from this file.
and only have 
`FEAT_INIT, ""`

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


[clang] [llvm] Update FEAT_PAuth_LR behaviour for AArch64 (PR #90614)

2024-05-08 Thread Jack Styles via cfe-commits

https://github.com/Stylie777 updated 
https://github.com/llvm/llvm-project/pull/90614

>From 59bc10d7418ed86f2fd94c8db5e34896164ef8e6 Mon Sep 17 00:00:00 2001
From: Jack Styles 
Date: Wed, 17 Apr 2024 14:17:51 +0100
Subject: [PATCH 1/4] [NFC] Add Extension Lookup to AArch64TargetParser

Currently, an extension cannot be found using the ExtID. To address this,
the function `lookupExtensionByID` has been added to the `ExtensionSet`
Class so it can be targeted from outside the function.

This will allow for the Extensions Information to be searched for and
stored externally to the ExtensionSet Class. This enables being able to
search for if Architecture Features have been enabled by the user in the
command line.
---
 llvm/include/llvm/TargetParser/AArch64TargetParser.h | 2 ++
 llvm/lib/TargetParser/AArch64TargetParser.cpp| 5 +
 2 files changed, 7 insertions(+)

diff --git a/llvm/include/llvm/TargetParser/AArch64TargetParser.h 
b/llvm/include/llvm/TargetParser/AArch64TargetParser.h
index 04fbaf07adfbc..05f5b3c0df029 100644
--- a/llvm/include/llvm/TargetParser/AArch64TargetParser.h
+++ b/llvm/include/llvm/TargetParser/AArch64TargetParser.h
@@ -799,6 +799,8 @@ inline constexpr Alias CpuAliases[] = {{"cobalt-100", 
"neoverse-n2"},
 
 inline constexpr Alias ExtAliases[] = {{"rdma", "rdm"}};
 
+const ExtensionInfo &getExtensionByID(ArchExtKind(ExtID));
+
 bool getExtensionFeatures(
 const AArch64::ExtensionBitset &Extensions,
 std::vector &Features);
diff --git a/llvm/lib/TargetParser/AArch64TargetParser.cpp 
b/llvm/lib/TargetParser/AArch64TargetParser.cpp
index 71099462d5ecf..026214e7e2eac 100644
--- a/llvm/lib/TargetParser/AArch64TargetParser.cpp
+++ b/llvm/lib/TargetParser/AArch64TargetParser.cpp
@@ -280,3 +280,8 @@ bool AArch64::ExtensionSet::parseModifier(StringRef 
Modifier) {
   }
   return false;
 }
+
+const AArch64::ExtensionInfo &
+AArch64::getExtensionByID(AArch64::ArchExtKind ExtID) {
+  return lookupExtensionByID(ExtID);
+}

>From 4f1549fa056442e8b71f1666b5f04ca6a4ee5bd3 Mon Sep 17 00:00:00 2001
From: Jack Styles 
Date: Wed, 17 Apr 2024 14:35:43 +0100
Subject: [PATCH 2/4] [AArch64] Enable PAuthLR by default for standard  branch
 protection when the feature is available

Currently, LLVM implements the `standard` option as `bti+pac-ret`
for ARM and AArch64. Following discussions with the GNU
developemnt team within Arm it was decided to align the
behaviour of `standard` to match across the different compilers.

To ensure the behaviour is aligned. LLVM has been updated to
implement `standard` as `bti+pac-ret+pc` by default when
`+pauth-lr` is passed as part of the `-march` argument.
---
 clang/lib/Basic/Targets/AArch64.cpp|  2 +-
 clang/lib/Driver/ToolChains/Clang.cpp  | 18 +-
 .../Preprocessor/aarch64-target-features.c |  4 
 llvm/docs/ReleaseNotes.rst |  5 +
 .../llvm/TargetParser/ARMTargetParserCommon.h  |  2 +-
 .../lib/TargetParser/ARMTargetParserCommon.cpp |  3 ++-
 6 files changed, 30 insertions(+), 4 deletions(-)

diff --git a/clang/lib/Basic/Targets/AArch64.cpp 
b/clang/lib/Basic/Targets/AArch64.cpp
index 1a02520d7bd1f..65717d2d39f1e 100644
--- a/clang/lib/Basic/Targets/AArch64.cpp
+++ b/clang/lib/Basic/Targets/AArch64.cpp
@@ -224,7 +224,7 @@ bool AArch64TargetInfo::validateBranchProtection(StringRef 
Spec, StringRef,
  BranchProtectionInfo &BPI,
  StringRef &Err) const {
   llvm::ARM::ParsedBranchProtection PBP;
-  if (!llvm::ARM::parseBranchProtection(Spec, PBP, Err))
+  if (!llvm::ARM::parseBranchProtection(Spec, PBP, Err, HasPAuthLR))
 return false;
 
   BPI.SignReturnAddr =
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 0a2ea96de7382..849ec5699ed56 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -1511,7 +1511,23 @@ static void CollectARMPACBTIOptions(const ToolChain &TC, 
const ArgList &Args,
   } else {
 StringRef DiagMsg;
 llvm::ARM::ParsedBranchProtection PBP;
-if (!llvm::ARM::parseBranchProtection(A->getValue(), PBP, DiagMsg))
+
+// To know if we need to enable PAuth-LR As part of the standard branch
+// protection option, it needs to be determined if the feature has been
+// activated in the `march` argument. This information is stored within the
+// CmdArgs variable and can be found using a search.
+if (isAArch64) {
+  auto isPAuthLR = [](const char *member) {
+llvm::AArch64::ExtensionInfo pauthlr_extension =
+llvm::AArch64::getExtensionByID(llvm::AArch64::AEK_PAUTHLR);
+return (pauthlr_extension.Feature.compare(member) == 0);
+  };
+
+  if (std::any_of(CmdArgs.begin(), CmdArgs.end(), isPAuthLR))
+EnablePAuthLR = true;
+}
+if (!llvm::ARM::parseBranchProtection(A->getValue(), PBP, DiagMsg,
+ 

[clang] [libclc] [llvm] [openmp] [Clang] `__attribute__((assume))` refactor (PR #84934)

2024-05-08 Thread Anastasia Stulova via cfe-commits

AnastasiaStulova wrote:

> From what I can tell, no-one except libclc is actually using this attribute? 
> At least on github, the only matches I’ve found for 
> __attribute__((assume("omp are in LLVM and various forks thereof. Given that 
> it’s not particularly widely used, I don’t think removal without deprecation 
> would be that big of a deal in this case, though if you think that that’s a 
> non-option, then I’d instead suggest deprecating it and removing it in a 
> later version of Clang.

This might be reasonable but I am not familiar enough with libclc to confirm. I 
imagine if someone volunteers to update it to use a new attribute this should 
be good enough or is there anything else needed? @svenvh or @efriedma-quic do 
you have an opinion or know anyone who could help answering this? 

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


[clang] [Clang][Sema] access checking of friend declaration should not be delayed (PR #91430)

2024-05-08 Thread Qizhi Hu via cfe-commits

https://github.com/jcsxky updated 
https://github.com/llvm/llvm-project/pull/91430

>From a4eee6db746e8de0743369f701d1b6a3fcc84754 Mon Sep 17 00:00:00 2001
From: Qizhi Hu <836744...@qq.com>
Date: Tue, 7 May 2024 22:32:39 +0800
Subject: [PATCH 1/2] [Clang][Sema] access checking of friend declaration
 should not be delayed

---
 clang/include/clang/Sema/Scope.h |  6 ++
 clang/lib/Parse/ParseDecl.cpp|  7 +--
 clang/lib/Sema/Scope.cpp |  2 ++
 clang/lib/Sema/SemaAccess.cpp| 12 ++--
 clang/test/SemaCXX/PR12361.cpp   | 30 ++
 5 files changed, 53 insertions(+), 4 deletions(-)
 create mode 100644 clang/test/SemaCXX/PR12361.cpp

diff --git a/clang/include/clang/Sema/Scope.h b/clang/include/clang/Sema/Scope.h
index 1752a25111a77..084db73034219 100644
--- a/clang/include/clang/Sema/Scope.h
+++ b/clang/include/clang/Sema/Scope.h
@@ -159,6 +159,9 @@ class Scope {
 
 /// This is a scope of type alias declaration.
 TypeAliasScope = 0x2000,
+
+/// This is a scope of friend declaration.
+FriendScope = 0x4000,
   };
 
 private:
@@ -586,6 +589,9 @@ class Scope {
   /// Determine whether this scope is a type alias scope.
   bool isTypeAliasScope() const { return getFlags() & Scope::TypeAliasScope; }
 
+  /// Determine whether this scope is a friend scope.
+  bool isFriendScope() const { return getFlags() & Scope::FriendScope; }
+
   /// Returns if rhs has a higher scope depth than this.
   ///
   /// The caller is responsible for calling this only if one of the two scopes
diff --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp
index 4e4b05b21383e..78a81c77f48c6 100644
--- a/clang/lib/Parse/ParseDecl.cpp
+++ b/clang/lib/Parse/ParseDecl.cpp
@@ -4332,9 +4332,12 @@ void Parser::ParseDeclarationSpecifiers(
 
 // friend
 case tok::kw_friend:
-  if (DSContext == DeclSpecContext::DSC_class)
+  if (DSContext == DeclSpecContext::DSC_class) {
 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
-  else {
+Scope *CurS = getCurScope();
+if (!isInvalid && CurS)
+  CurS->setFlags(CurS->getFlags() | Scope::FriendScope);
+  } else {
 PrevSpec = ""; // not actually used by the diagnostic
 DiagID = diag::err_friend_invalid_in_context;
 isInvalid = true;
diff --git a/clang/lib/Sema/Scope.cpp b/clang/lib/Sema/Scope.cpp
index 11a41753a1bda..780aa898b1085 100644
--- a/clang/lib/Sema/Scope.cpp
+++ b/clang/lib/Sema/Scope.cpp
@@ -229,6 +229,8 @@ void Scope::dumpImpl(raw_ostream &OS) const {
   {ClassInheritanceScope, "ClassInheritanceScope"},
   {CatchScope, "CatchScope"},
   {OpenACCComputeConstructScope, "OpenACCComputeConstructScope"},
+  {TypeAliasScope, "TypeAliasScope"},
+  {FriendScope, "FriendScope"},
   };
 
   for (auto Info : FlagInfo) {
diff --git a/clang/lib/Sema/SemaAccess.cpp b/clang/lib/Sema/SemaAccess.cpp
index 6a707eeb66d01..72c6736bb6648 100644
--- a/clang/lib/Sema/SemaAccess.cpp
+++ b/clang/lib/Sema/SemaAccess.cpp
@@ -1477,8 +1477,16 @@ static Sema::AccessResult CheckAccess(Sema &S, 
SourceLocation Loc,
   //   void foo(A::private_type);
   //   void B::foo(A::private_type);
   if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
-S.DelayedDiagnostics.add(DelayedDiagnostic::makeAccess(Loc, Entity));
-return Sema::AR_delayed;
+Scope *TS = S.getCurScope();
+bool IsFriendDeclaration = false;
+while (TS && !IsFriendDeclaration) {
+  IsFriendDeclaration = TS->isFriendScope();
+  TS = TS->getParent();
+}
+if (!IsFriendDeclaration) {
+  S.DelayedDiagnostics.add(DelayedDiagnostic::makeAccess(Loc, Entity));
+  return Sema::AR_delayed;
+}
   }
 
   EffectiveContext EC(S.CurContext);
diff --git a/clang/test/SemaCXX/PR12361.cpp b/clang/test/SemaCXX/PR12361.cpp
new file mode 100644
index 0..95ceb45b7ba04
--- /dev/null
+++ b/clang/test/SemaCXX/PR12361.cpp
@@ -0,0 +1,30 @@
+ // RUN: %clang_cc1 -fsyntax-only -verify -std=c++98 %s
+ // RUN: %clang_cc1 -fsyntax-only -verify -std=c++17 %s
+ 
+class D {
+class E{
+class F{}; // expected-note{{implicitly declared private here}}
+friend  void foo(D::E::F& q);
+};
+friend  void foo(D::E::F& q); // expected-error{{'F' is a private member 
of 'D::E'}}
+};
+
+void foo(D::E::F& q) {}
+
+class D1 {
+class E1{
+class F1{}; // expected-note{{implicitly declared private here}}
+friend  D1::E1::F1 foo1();
+};
+friend  D1::E1::F1 foo1(); // expected-error{{'F1' is a private member of 
'D1::E1'}}
+};
+
+D1::E1::F1 foo1() { return D1::E1::F1(); }
+
+class D2 {
+class E2{
+class F2{};
+friend  void foo2();
+};
+friend  void foo2(){ D2::E2::F2 c;}
+};

>From bce02c31f4b6601e7d031f74fa7e46d868a7d423 Mon Sep 17 00:00:00 2001
From: Qizhi Hu <836744...@qq.com>
Date: Wed, 8 May 2024 21:22:01 +0800
Subject: [PATCH 2/2] apply reviews

---
 clang/docs/ReleaseN

[clang] [Clang][Sema] access checking of friend declaration should not be delayed (PR #91430)

2024-05-08 Thread Qizhi Hu via cfe-commits

https://github.com/jcsxky updated 
https://github.com/llvm/llvm-project/pull/91430

>From ec4f21b7823a89a793b0799b22c6bbdb0bfb4c52 Mon Sep 17 00:00:00 2001
From: Qizhi Hu <836744...@qq.com>
Date: Tue, 7 May 2024 22:32:39 +0800
Subject: [PATCH 1/2] [Clang][Sema] access checking of friend declaration
 should not be delayed

---
 clang/include/clang/Sema/Scope.h |  6 ++
 clang/lib/Parse/ParseDecl.cpp|  7 +--
 clang/lib/Sema/Scope.cpp |  2 ++
 clang/lib/Sema/SemaAccess.cpp| 12 ++--
 clang/test/SemaCXX/PR12361.cpp   | 30 ++
 5 files changed, 53 insertions(+), 4 deletions(-)
 create mode 100644 clang/test/SemaCXX/PR12361.cpp

diff --git a/clang/include/clang/Sema/Scope.h b/clang/include/clang/Sema/Scope.h
index 1752a25111a77..084db73034219 100644
--- a/clang/include/clang/Sema/Scope.h
+++ b/clang/include/clang/Sema/Scope.h
@@ -159,6 +159,9 @@ class Scope {
 
 /// This is a scope of type alias declaration.
 TypeAliasScope = 0x2000,
+
+/// This is a scope of friend declaration.
+FriendScope = 0x4000,
   };
 
 private:
@@ -586,6 +589,9 @@ class Scope {
   /// Determine whether this scope is a type alias scope.
   bool isTypeAliasScope() const { return getFlags() & Scope::TypeAliasScope; }
 
+  /// Determine whether this scope is a friend scope.
+  bool isFriendScope() const { return getFlags() & Scope::FriendScope; }
+
   /// Returns if rhs has a higher scope depth than this.
   ///
   /// The caller is responsible for calling this only if one of the two scopes
diff --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp
index 4e4b05b21383e..78a81c77f48c6 100644
--- a/clang/lib/Parse/ParseDecl.cpp
+++ b/clang/lib/Parse/ParseDecl.cpp
@@ -4332,9 +4332,12 @@ void Parser::ParseDeclarationSpecifiers(
 
 // friend
 case tok::kw_friend:
-  if (DSContext == DeclSpecContext::DSC_class)
+  if (DSContext == DeclSpecContext::DSC_class) {
 isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID);
-  else {
+Scope *CurS = getCurScope();
+if (!isInvalid && CurS)
+  CurS->setFlags(CurS->getFlags() | Scope::FriendScope);
+  } else {
 PrevSpec = ""; // not actually used by the diagnostic
 DiagID = diag::err_friend_invalid_in_context;
 isInvalid = true;
diff --git a/clang/lib/Sema/Scope.cpp b/clang/lib/Sema/Scope.cpp
index 11a41753a1bda..780aa898b1085 100644
--- a/clang/lib/Sema/Scope.cpp
+++ b/clang/lib/Sema/Scope.cpp
@@ -229,6 +229,8 @@ void Scope::dumpImpl(raw_ostream &OS) const {
   {ClassInheritanceScope, "ClassInheritanceScope"},
   {CatchScope, "CatchScope"},
   {OpenACCComputeConstructScope, "OpenACCComputeConstructScope"},
+  {TypeAliasScope, "TypeAliasScope"},
+  {FriendScope, "FriendScope"},
   };
 
   for (auto Info : FlagInfo) {
diff --git a/clang/lib/Sema/SemaAccess.cpp b/clang/lib/Sema/SemaAccess.cpp
index 6a707eeb66d01..72c6736bb6648 100644
--- a/clang/lib/Sema/SemaAccess.cpp
+++ b/clang/lib/Sema/SemaAccess.cpp
@@ -1477,8 +1477,16 @@ static Sema::AccessResult CheckAccess(Sema &S, 
SourceLocation Loc,
   //   void foo(A::private_type);
   //   void B::foo(A::private_type);
   if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
-S.DelayedDiagnostics.add(DelayedDiagnostic::makeAccess(Loc, Entity));
-return Sema::AR_delayed;
+Scope *TS = S.getCurScope();
+bool IsFriendDeclaration = false;
+while (TS && !IsFriendDeclaration) {
+  IsFriendDeclaration = TS->isFriendScope();
+  TS = TS->getParent();
+}
+if (!IsFriendDeclaration) {
+  S.DelayedDiagnostics.add(DelayedDiagnostic::makeAccess(Loc, Entity));
+  return Sema::AR_delayed;
+}
   }
 
   EffectiveContext EC(S.CurContext);
diff --git a/clang/test/SemaCXX/PR12361.cpp b/clang/test/SemaCXX/PR12361.cpp
new file mode 100644
index 0..95ceb45b7ba04
--- /dev/null
+++ b/clang/test/SemaCXX/PR12361.cpp
@@ -0,0 +1,30 @@
+ // RUN: %clang_cc1 -fsyntax-only -verify -std=c++98 %s
+ // RUN: %clang_cc1 -fsyntax-only -verify -std=c++17 %s
+ 
+class D {
+class E{
+class F{}; // expected-note{{implicitly declared private here}}
+friend  void foo(D::E::F& q);
+};
+friend  void foo(D::E::F& q); // expected-error{{'F' is a private member 
of 'D::E'}}
+};
+
+void foo(D::E::F& q) {}
+
+class D1 {
+class E1{
+class F1{}; // expected-note{{implicitly declared private here}}
+friend  D1::E1::F1 foo1();
+};
+friend  D1::E1::F1 foo1(); // expected-error{{'F1' is a private member of 
'D1::E1'}}
+};
+
+D1::E1::F1 foo1() { return D1::E1::F1(); }
+
+class D2 {
+class E2{
+class F2{};
+friend  void foo2();
+};
+friend  void foo2(){ D2::E2::F2 c;}
+};

>From 77cfb6f93c8c91cfbe5d3d1ed4e90450afa026fa Mon Sep 17 00:00:00 2001
From: Qizhi Hu <836744...@qq.com>
Date: Wed, 8 May 2024 21:22:01 +0800
Subject: [PATCH 2/2] apply reviews

---
 clang/docs/ReleaseN

[clang] [Clang][Sema] access checking of friend declaration should not be delayed (PR #91430)

2024-05-08 Thread Qizhi Hu via cfe-commits


@@ -1477,8 +1477,16 @@ static Sema::AccessResult CheckAccess(Sema &S, 
SourceLocation Loc,
   //   void foo(A::private_type);

jcsxky wrote:

Done.

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


[clang] [Clang][Sema] access checking of friend declaration should not be delayed (PR #91430)

2024-05-08 Thread Qizhi Hu via cfe-commits


@@ -229,6 +229,8 @@ void Scope::dumpImpl(raw_ostream &OS) const {
   {ClassInheritanceScope, "ClassInheritanceScope"},
   {CatchScope, "CatchScope"},
   {OpenACCComputeConstructScope, "OpenACCComputeConstructScope"},
+  {TypeAliasScope, "TypeAliasScope"},

jcsxky wrote:

Removed. This will be done in a follow-up.

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


[clang] [Clang][Sema] access checking of friend declaration should not be delayed (PR #91430)

2024-05-08 Thread Qizhi Hu via cfe-commits


@@ -1477,8 +1477,16 @@ static Sema::AccessResult CheckAccess(Sema &S, 
SourceLocation Loc,
   //   void foo(A::private_type);
   //   void B::foo(A::private_type);
   if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
-S.DelayedDiagnostics.add(DelayedDiagnostic::makeAccess(Loc, Entity));
-return Sema::AR_delayed;
+Scope *TS = S.getCurScope();
+bool IsFriendDeclaration = false;
+while (TS && !IsFriendDeclaration) {
+  IsFriendDeclaration = TS->isFriendScope();
+  TS = TS->getParent();
+}
+if (!IsFriendDeclaration) {
+  S.DelayedDiagnostics.add(DelayedDiagnostic::makeAccess(Loc, Entity));
+  return Sema::AR_delayed;
+}

jcsxky wrote:

Added.

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


[clang] [Coro] Relax a debug-info test (PR #91401)

2024-05-08 Thread Paul T Robinson via cfe-commits

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


  1   2   3   4   >