[clang] [clang] [SemaCXX] Disallow deducing "this" on operator `new` and `delete` (PR #82251)

2024-02-20 Thread via cfe-commits

cor3ntin wrote:

@Rajveer100 you need us to merge that for you?

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


[clang] 351e4fa - [Clang] Fix assert when transforming a pack indexing type. (#82234)

2024-02-20 Thread via cfe-commits

Author: cor3ntin
Date: 2024-02-21T08:46:47+01:00
New Revision: 351e4fa2bfe5b13073c1675a1b1693ea766c1e25

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

LOG: [Clang] Fix assert when transforming a pack indexing type. (#82234)

When a pack in a pack indexing specifier cannot be immediately expanded,
we were creating an incomplete TypeLoc
(causing assertion failure).

As we do not keep track of typelocs of expanded elements, we create a
trivial typeloc

Fixes #81697

Added: 


Modified: 
clang/lib/Sema/TreeTransform.h
clang/test/SemaCXX/cxx2c-pack-indexing.cpp

Removed: 




diff  --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index a32a585531873a..7389a48fe56fcc 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -6561,7 +6561,11 @@ 
TreeTransform::TransformPackIndexingType(TypeLocBuilder ,
   return QualType();
 if (!ShouldExpand) {
   Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
-  QualType Pack = getDerived().TransformType(T);
+  // FIXME: should we keep TypeLoc for individual expansions in
+  // PackIndexingTypeLoc?
+  TypeSourceInfo *TI =
+  SemaRef.getASTContext().getTrivialTypeSourceInfo(T, 
TL.getBeginLoc());
+  QualType Pack = getDerived().TransformType(TLB, TI->getTypeLoc());
   if (Pack.isNull())
 return QualType();
   if (NotYetExpanded) {

diff  --git a/clang/test/SemaCXX/cxx2c-pack-indexing.cpp 
b/clang/test/SemaCXX/cxx2c-pack-indexing.cpp
index 625a56031598b7..e13635383b6ca6 100644
--- a/clang/test/SemaCXX/cxx2c-pack-indexing.cpp
+++ b/clang/test/SemaCXX/cxx2c-pack-indexing.cpp
@@ -135,3 +135,22 @@ using Splice = typename SpliceImpl::type;
 using type = Splice, IL<1, 2>>;
 static_assert(is_same>);
 }
+
+
+namespace GH81697 {
+
+template struct tuple {
+int __x0;
+};
+
+template
+Ts...[I]& get(tuple& t) {
+  return t.__x0;
+}
+
+void f() {
+  tuple x;
+  get<0>(x);
+}
+
+}



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


[clang] [Clang] Fix assert when transforming a pack indexing type. (PR #82234)

2024-02-20 Thread via cfe-commits

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


[clang] [llvm] [AMDGPU] Add an option to disable unsafe uses of atomic xor (PR #69229)

2024-02-20 Thread Pierre van Houtryve via cfe-commits

Pierre-vh wrote:

> Thanks for the comments @arsenm @yxsamliu @b-sumner.
> 
> By approaching a similar solution, do you mean MMRAs (#78569) ?
> 
> If so, should I rebase/adapt my patch to the MMRA PR? Or will this PR be 
> redundant and needs closing?
> 
> @yxsamliu These concise names look good to me.

In this case, MMRAs would only help in the sense that you won't need any new 
attributes and can just add an MMRA such as `atomic-lowering:fine-grained`. 
It's not really what MMRAs were made for (because this attribute doesn't affect 
semantics, just lowering style I think?), but all of the boilerplate would be 
there to preserve this annotation until the backend, and as long as you don't 
add any other `atomic-lowering:` flag, you shouldn't have issues with 
compatibility relations - if you plan to add other flags like that then it may 
be an issue because you could end up with two operations being considered 
incompatible (= can reorder them) when they're still technically compatible

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


[clang] [Clang] Fix assert when transforming a pack indexing type. (PR #82234)

2024-02-20 Thread Shafik Yaghmour via cfe-commits

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

LGTM

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


[clang] [llvm] [AMDGPU] Emit a waitcnt instruction after each memory instruction (PR #79236)

2024-02-20 Thread Pierre van Houtryve via cfe-commits


@@ -167,6 +167,10 @@ def FeatureCuMode : SubtargetFeature<"cumode",
   "Enable CU wavefront execution mode"
 >;
 
+def FeaturePreciseMemory

Pierre-vh wrote:

Just remove `m_amdgpu_Features_Group` from your option's `SimpleMFlag`, follow 
the same pattern as `wavefrontsize64`

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


[clang] [clang] [SemaCXX] Disallow deducing "this" on operator `new` and `delete` (PR #82251)

2024-02-20 Thread Shafik Yaghmour via cfe-commits

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

LGTM, thanks for submitting a fix.

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


[clang] [llvm] [MC/DC][Coverage] Loosen the limit of NumConds from 6 (PR #82448)

2024-02-20 Thread Hana Dusíková via cfe-commits

hanickadot wrote:

> @hanickadot Your comments to `llvm/CoverageMapping.cpp` are not for this PR. 
> See #80676 .
> 
> They are my preferences.

Didn't know the context, I saw it green as added. Just ignore it.

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


[clang] 8b23d68 - [Analyzer] Support RefAllowingPartiallyDestroyed and RefPtrAllowingPartiallyDestroyed (#82209)

2024-02-20 Thread via cfe-commits

Author: Ryosuke Niwa
Date: 2024-02-20T23:02:03-08:00
New Revision: 8b23d68a621f16b6d66e68cb64b99f1221b9df2c

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

LOG: [Analyzer] Support RefAllowingPartiallyDestroyed and 
RefPtrAllowingPartiallyDestroyed (#82209)

This PR adds the support for WebKit's RefAllowingPartiallyDestroyed and
RefPtrAllowingPartiallyDestroyed, which are smart pointer types which
may be used after the destructor had started running.

Added: 
clang/test/Analysis/Checkers/WebKit/ref-allowing-partially-destroyed.cpp

Modified: 
clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
clang/test/Analysis/Checkers/WebKit/mock-types.h

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
index a7891d2da07c18..defd83ec8e179c 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
@@ -103,15 +103,18 @@ std::optional isRefCountable(const CXXRecordDecl* R)
   return hasRef && hasDeref;
 }
 
+bool isRefType(const std::string ) {
+  return Name == "Ref" || Name == "RefAllowingPartiallyDestroyed" ||
+ Name == "RefPtr" || Name == "RefPtrAllowingPartiallyDestroyed";
+}
+
 bool isCtorOfRefCounted(const clang::FunctionDecl *F) {
   assert(F);
-  const auto  = safeGetName(F);
-
-  return FunctionName == "Ref" || FunctionName == "makeRef"
-
- || FunctionName == "RefPtr" || FunctionName == "makeRefPtr"
+  const std::string  = safeGetName(F);
 
- || FunctionName == "UniqueRef" || FunctionName == "makeUniqueRef" ||
+  return isRefType(FunctionName) || FunctionName == "makeRef" ||
+ FunctionName == "makeRefPtr" || FunctionName == "UniqueRef" ||
+ FunctionName == "makeUniqueRef" ||
  FunctionName == "makeUniqueRefWithoutFastMallocCheck"
 
  || FunctionName == "String" || FunctionName == "AtomString" ||
@@ -131,7 +134,7 @@ bool isReturnValueRefCounted(const clang::FunctionDecl *F) {
 if (auto *specialT = type->getAs()) {
   if (auto *decl = specialT->getTemplateName().getAsTemplateDecl()) {
 auto name = decl->getNameAsString();
-return name == "Ref" || name == "RefPtr";
+return isRefType(name);
   }
   return false;
 }
@@ -172,20 +175,18 @@ std::optional isGetterOfRefCounted(const 
CXXMethodDecl* M)
   if (isa(M)) {
 const CXXRecordDecl *calleeMethodsClass = M->getParent();
 auto className = safeGetName(calleeMethodsClass);
-auto methodName = safeGetName(M);
+auto method = safeGetName(M);
 
-if (((className == "Ref" || className == "RefPtr") &&
- methodName == "get") ||
-(className == "Ref" && methodName == "ptr") ||
+if ((isRefType(className) && (method == "get" || method == "ptr")) ||
 ((className == "String" || className == "AtomString" ||
   className == "AtomStringImpl" || className == "UniqueString" ||
   className == "UniqueStringImpl" || className == "Identifier") &&
- methodName == "impl"))
+ method == "impl"))
   return true;
 
 // Ref -> T conversion
 // FIXME: Currently allowing any Ref -> whatever cast.
-if (className == "Ref" || className == "RefPtr") {
+if (isRefType(className)) {
   if (auto *maybeRefToRawOperator = dyn_cast(M)) {
 if (auto *targetConversionType =
 maybeRefToRawOperator->getConversionType().getTypePtrOrNull()) 
{
@@ -202,7 +203,7 @@ bool isRefCounted(const CXXRecordDecl *R) {
   if (auto *TmplR = R->getTemplateInstantiationPattern()) {
 // FIXME: String/AtomString/UniqueString
 const auto  = safeGetName(TmplR);
-return ClassName == "RefPtr" || ClassName == "Ref";
+return isRefType(ClassName);
   }
   return false;
 }

diff  --git a/clang/test/Analysis/Checkers/WebKit/mock-types.h 
b/clang/test/Analysis/Checkers/WebKit/mock-types.h
index 82db67bb031dd6..e2b3401d407392 100644
--- a/clang/test/Analysis/Checkers/WebKit/mock-types.h
+++ b/clang/test/Analysis/Checkers/WebKit/mock-types.h
@@ -16,6 +16,7 @@ template  struct Ref {
   }
   T *get() { return t; }
   T *ptr() { return t; }
+  T *operator->() { return t; }
   operator const T &() const { return *t; }
   operator T &() { return *t; }
 };

diff  --git 
a/clang/test/Analysis/Checkers/WebKit/ref-allowing-partially-destroyed.cpp 
b/clang/test/Analysis/Checkers/WebKit/ref-allowing-partially-destroyed.cpp
new file mode 100644
index 00..6d96c14102a902
--- /dev/null
+++ b/clang/test/Analysis/Checkers/WebKit/ref-allowing-partially-destroyed.cpp
@@ -0,0 +1,44 @@
+// RUN: %clang_analyze_cc1 
-analyzer-checker=alpha.webkit.UncountedCallArgsChecker -verify %s

[clang] [Analyzer] Support RefAllowingPartiallyDestroyed and RefPtrAllowingPartiallyDestroyed (PR #82209)

2024-02-20 Thread Ryosuke Niwa via cfe-commits

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


[clang] [llvm] [MC/DC][Coverage] Loosen the limit of NumConds from 6 (PR #82448)

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

chapuni wrote:

@hanickadot Your comments to `llvm/CoverageMapping.cpp` are not for this PR. 
See #80676 .

They are my preferences.

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


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

2024-02-20 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Wentao Zhang (whentojump)


Changes

Currently, upon seeing [unsupported 
decisions](https://clang.llvm.org/docs/SourceBasedCodeCoverage.html#mc-dc-instrumentation)
 (more than 6 conditions, or split nesting), the post-visitor hook 
`dataTraverseStmtPost()` returns a `false`. As a result, in the rest of tree 
even supported decisions will be skipped as well. Like in the below code:

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

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

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

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


1 Files Affected:

- (modified) clang/lib/CodeGen/CodeGenPGO.cpp (+7-4) 


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

``




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


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

2024-02-20 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-codegen

Author: Wentao Zhang (whentojump)


Changes

Currently, upon seeing [unsupported 
decisions](https://clang.llvm.org/docs/SourceBasedCodeCoverage.html#mc-dc-instrumentation)
 (more than 6 conditions, or split nesting), the post-visitor hook 
`dataTraverseStmtPost()` returns a `false`. As a result, in the rest of tree 
even supported decisions will be skipped as well. Like in the below code:

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

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

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

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


1 Files Affected:

- (modified) clang/lib/CodeGen/CodeGenPGO.cpp (+7-4) 


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

``




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


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

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

https://github.com/whentojump created 
https://github.com/llvm/llvm-project/pull/82464

Currently, upon seeing [unsupported 
decisions](https://clang.llvm.org/docs/SourceBasedCodeCoverage.html#mc-dc-instrumentation)
 (more than 6 conditions, or split nesting), the post-visitor hook 
`dataTraverseStmtPost()` returns a `false`. As a result, in the rest of tree 
even supported decisions will be skipped as well. Like in the below code:

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

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

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

>From 67a2c10b044e0e9c2eceb6646300e546ee990e0b Mon Sep 17 00:00:00 2001
From: Wentao Zhang 
Date: Wed, 21 Feb 2024 01:48:11 -0500
Subject: [PATCH] [clang][CodeGen] Keep processing the rest of AST after
 encountering unsupported MC/DC expressions

---
 clang/lib/CodeGen/CodeGenPGO.cpp | 11 +++
 1 file changed, 7 insertions(+), 4 deletions(-)

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

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


[clang] [llvm] [MC/DC][Coverage] Loosen the limit of NumConds from 6 (PR #82448)

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


@@ -1959,9 +2013,44 @@ struct CounterCoverageMappingBuilder
subtractCounters(ParentCount, TrueCount));
   }
 
+  void RewindDecision(unsigned Since) {
+#ifndef NDEBUG
+llvm::DenseSet SeenIDs;
+#endif
+unsigned NConds = 0;

chapuni wrote:

Thanks. I haven't found it anyways. Will do.

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


[clang] [llvm] [MC/DC][Coverage] Loosen the limit of NumConds from 6 (PR #82448)

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


@@ -723,7 +737,15 @@ struct MCDCCoverageBuilder {
 if (I == CondIDs.end())
   return -1;
 else
-  return I->second;
+  return I->second.ID;
+  }
+
+  void ccc(const Expr *CondExpr, mcdc::ConditionIDs IDs) {

chapuni wrote:

This is w-i-p. Thanks for pointing this out.

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


[clang] [llvm] [MC/DC][Coverage] Loosen the limit of NumConds from 6 (PR #82448)

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

https://github.com/chapuni commented:

Thanks for your comments and sorry for my hasty w-i-p work . I know a few rough 
implementations would be there.

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


[clang] [llvm] [MC/DC][Coverage] Loosen the limit of NumConds from 6 (PR #82448)

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

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


[clang] [Clang][Sema] Diagnosis for constexpr constructor not initializing a union member (PR #81225)

2024-02-20 Thread Shafik Yaghmour via cfe-commits


@@ -2471,6 +2480,23 @@ static bool CheckConstexprFunctionBody(Sema , 
const FunctionDecl *Dcl,
   return true;
 }
 
+static bool
+checkUnionConstructorIntializer(Sema , const FunctionDecl *Dcl,
+const CXXConstructorDecl *Constructor,
+const CXXRecordDecl *RD,
+Sema::CheckConstexprKind Kind) {
+  if (Constructor->getNumCtorInitializers() == 0 && RD->hasVariantMembers()) {
+if (Kind == Sema::CheckConstexprKind::Diagnose) {
+  SemaRef.Diag(Dcl->getLocation(),
+   SemaRef.getLangOpts().CPlusPlus20
+   ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
+   : diag::ext_constexpr_union_ctor_no_init);
+} else if (!SemaRef.getLangOpts().CPlusPlus20) {

shafik wrote:

I don't see what this check is doing exactly, can you explain what is being 
checked here?

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


[clang] [Clang][Sema] Diagnosis for constexpr constructor not initializing a union member (PR #81225)

2024-02-20 Thread Shafik Yaghmour via cfe-commits


@@ -2343,17 +2349,9 @@ static bool CheckConstexprFunctionBody(Sema , 
const FunctionDecl *Dcl,
 // - if the class is a union having variant members, exactly one of them
 //   shall be initialized;

shafik wrote:

We need add a reference to [cwg2424](https://wg21.link/cwg2424) as well as a 
reference to 
[P1331r2](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1331r2.pdf).

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


[clang] [Clang][Sema] Diagnosis for constexpr constructor not initializing a union member (PR #81225)

2024-02-20 Thread Shafik Yaghmour via cfe-commits


@@ -2471,6 +2480,23 @@ static bool CheckConstexprFunctionBody(Sema , 
const FunctionDecl *Dcl,
   return true;
 }
 
+static bool
+checkUnionConstructorIntializer(Sema , const FunctionDecl *Dcl,
+const CXXConstructorDecl *Constructor,
+const CXXRecordDecl *RD,
+Sema::CheckConstexprKind Kind) {
+  if (Constructor->getNumCtorInitializers() == 0 && RD->hasVariantMembers()) {
+if (Kind == Sema::CheckConstexprKind::Diagnose) {
+  SemaRef.Diag(Dcl->getLocation(),
+   SemaRef.getLangOpts().CPlusPlus20
+   ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
+   : diag::ext_constexpr_union_ctor_no_init);
+} else if (!SemaRef.getLangOpts().CPlusPlus20) {
+  return true;

shafik wrote:

I don't like that we changed this to return `true` while in the location we 
moved this from it was returning `false`. This goes back to the name not really 
explain what this does, so it is not clear what the return value really 
represents. 

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


[clang] [Clang][Sema] Diagnosis for constexpr constructor not initializing a union member (PR #81225)

2024-02-20 Thread Shafik Yaghmour via cfe-commits


@@ -2471,6 +2480,23 @@ static bool CheckConstexprFunctionBody(Sema , 
const FunctionDecl *Dcl,
   return true;
 }
 
+static bool
+checkUnionConstructorIntializer(Sema , const FunctionDecl *Dcl,

shafik wrote:

I really don't like this name, I don't feel like it really describes what this 
function does. I don't have a good substitute off the top of my head. CC 
@Endilll for some help.

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


[clang] [Clang][Sema] Diagnosis for constexpr constructor not initializing a union member (PR #81225)

2024-02-20 Thread Shafik Yaghmour via cfe-commits


@@ -2393,6 +2391,17 @@ static bool CheckConstexprFunctionBody(Sema , 
const FunctionDecl *Dcl,
  Kind))
 return false;
   }
+} else if (!Constructor->isDelegatingConstructor()) {

shafik wrote:

Can you explain why we need this change? 

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


[clang] [llvm] [MC/DC][Coverage] Loosen the limit of NumConds from 6 (PR #82448)

2024-02-20 Thread Hana Dusíková via cfe-commits


@@ -223,9 +223,130 @@ Expected CounterMappingContext::evaluate(const 
Counter ) const {
   return LastPoppedValue;
 }
 
+mcdc::TVIdxBuilder::TVIdxBuilder(const SmallVectorImpl ,
+ int Offset)
+: Indices(NextIDs.size()) {
+  // Construct Nodes and set up each InCount
+  auto N = NextIDs.size();
+  SmallVector Nodes(N);
+  for (unsigned ID = 0; ID < N; ++ID) {
+for (unsigned C = 0; C < 2; ++C) {
+#ifndef NDEBUG
+  Indices[ID][C] = INT_MIN;
+#endif
+  auto NextID = NextIDs[ID][C];
+  Nodes[ID].NextIDs[C] = NextID;
+  if (NextID >= 0)
+++Nodes[NextID].InCount;
+}
+  }
+
+  // Sort key ordered by <-Width, Ord>
+  SmallVector>
+  Decisions;
+
+  // Traverse Nodes to assign Idx
+  SmallVector Q;
+  assert(Nodes[0].InCount == 0);
+  Nodes[0].Width = 1;
+  Q.push_back(0);
+
+  unsigned Ord = 0;
+  while (!Q.empty()) {
+auto IID = Q.begin();
+int ID = *IID;
+Q.erase(IID);
+auto  = Nodes[ID];
+assert(Node.Width > 0);
+
+for (unsigned I = 0; I < 2; ++I) {
+  auto NextID = Node.NextIDs[I];
+  assert(NextID != 0 && "NextID should not point to the top");
+  if (NextID < 0) {
+// Decision
+Decisions.emplace_back(-Node.Width, Ord++, ID, I);
+assert(Ord == Decisions.size());
+continue;
+  }
+
+  // Inter Node
+  auto  = Nodes[NextID];
+  assert(NextNode.InCount > 0);
+
+  // Assign Idx
+  assert(Indices[ID][I] == INT_MIN);
+  Indices[ID][I] = NextNode.Width;
+  auto NextWidth = int64_t(NextNode.Width) + Node.Width;
+  if (NextWidth > HardMaxTVs) {
+NumTestVectors = HardMaxTVs; // Overflow
+return;
+  }
+  NextNode.Width = NextWidth;
+
+  // Ready if all incomings are processed.
+  // Or NextNode.Width hasn't been confirmed yet.
+  if (--NextNode.InCount == 0)
+Q.push_back(NextID);
+}
+  }
+
+  std::sort(Decisions.begin(), Decisions.end());
+
+  // Assign TestVector Indices in Decision Nodes
+  int64_t CurIdx = 0;
+  for (auto [NegWidth, Ord, ID, C] : Decisions) {
+int Width = -NegWidth;

hanickadot wrote:

change it also here if you change Decision to a smallvector of defined struct 

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


[clang] [llvm] [MC/DC][Coverage] Loosen the limit of NumConds from 6 (PR #82448)

2024-02-20 Thread Hana Dusíková via cfe-commits


@@ -223,9 +223,130 @@ Expected CounterMappingContext::evaluate(const 
Counter ) const {
   return LastPoppedValue;
 }
 
+mcdc::TVIdxBuilder::TVIdxBuilder(const SmallVectorImpl ,
+ int Offset)
+: Indices(NextIDs.size()) {
+  // Construct Nodes and set up each InCount
+  auto N = NextIDs.size();
+  SmallVector Nodes(N);
+  for (unsigned ID = 0; ID < N; ++ID) {
+for (unsigned C = 0; C < 2; ++C) {
+#ifndef NDEBUG
+  Indices[ID][C] = INT_MIN;
+#endif
+  auto NextID = NextIDs[ID][C];
+  Nodes[ID].NextIDs[C] = NextID;
+  if (NextID >= 0)
+++Nodes[NextID].InCount;
+}
+  }
+
+  // Sort key ordered by <-Width, Ord>
+  SmallVector>
+  Decisions;
+
+  // Traverse Nodes to assign Idx
+  SmallVector Q;
+  assert(Nodes[0].InCount == 0);
+  Nodes[0].Width = 1;
+  Q.push_back(0);
+
+  unsigned Ord = 0;
+  while (!Q.empty()) {
+auto IID = Q.begin();
+int ID = *IID;
+Q.erase(IID);
+auto  = Nodes[ID];
+assert(Node.Width > 0);
+
+for (unsigned I = 0; I < 2; ++I) {
+  auto NextID = Node.NextIDs[I];
+  assert(NextID != 0 && "NextID should not point to the top");
+  if (NextID < 0) {
+// Decision
+Decisions.emplace_back(-Node.Width, Ord++, ID, I);

hanickadot wrote:

The negation shouldn't be here. It's error prone.

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


[clang] [llvm] [MC/DC][Coverage] Loosen the limit of NumConds from 6 (PR #82448)

2024-02-20 Thread Hana Dusíková via cfe-commits


@@ -1959,9 +2013,44 @@ struct CounterCoverageMappingBuilder
subtractCounters(ParentCount, TrueCount));
   }
 
+  void RewindDecision(unsigned Since) {
+#ifndef NDEBUG
+llvm::DenseSet SeenIDs;
+#endif
+unsigned NConds = 0;

hanickadot wrote:

move the `NConds` into `ifndef NDEBUG` block as it's just a sanity check

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


[clang] [llvm] [MC/DC][Coverage] Loosen the limit of NumConds from 6 (PR #82448)

2024-02-20 Thread Hana Dusíková via cfe-commits


@@ -223,9 +223,130 @@ Expected CounterMappingContext::evaluate(const 
Counter ) const {
   return LastPoppedValue;
 }
 
+mcdc::TVIdxBuilder::TVIdxBuilder(const SmallVectorImpl ,
+ int Offset)
+: Indices(NextIDs.size()) {
+  // Construct Nodes and set up each InCount
+  auto N = NextIDs.size();
+  SmallVector Nodes(N);
+  for (unsigned ID = 0; ID < N; ++ID) {
+for (unsigned C = 0; C < 2; ++C) {
+#ifndef NDEBUG
+  Indices[ID][C] = INT_MIN;
+#endif
+  auto NextID = NextIDs[ID][C];
+  Nodes[ID].NextIDs[C] = NextID;
+  if (NextID >= 0)
+++Nodes[NextID].InCount;
+}
+  }
+
+  // Sort key ordered by <-Width, Ord>
+  SmallVector>
+  Decisions;

hanickadot wrote:

I think this would be better as a defined struct with defined `operator<`, as 
this mandates inserting `-Width`  and negating it when reading just for sorting 
purposes. It will be error prone for future someone editing this code.

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


[clang] [llvm] [MC/DC][Coverage] Loosen the limit of NumConds from 6 (PR #82448)

2024-02-20 Thread Hana Dusíková via cfe-commits

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


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


[clang] [llvm] [MC/DC][Coverage] Loosen the limit of NumConds from 6 (PR #82448)

2024-02-20 Thread Hana Dusíková via cfe-commits


@@ -723,7 +737,15 @@ struct MCDCCoverageBuilder {
 if (I == CondIDs.end())
   return -1;
 else
-  return I->second;
+  return I->second.ID;
+  }
+
+  void ccc(const Expr *CondExpr, mcdc::ConditionIDs IDs) {

hanickadot wrote:

this should be named differently, based on name I don't understand what it is 
doing

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


[clang] [llvm] [MC/DC][Coverage] Loosen the limit of NumConds from 6 (PR #82448)

2024-02-20 Thread Hana Dusíková via cfe-commits

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


[clang] [clang-format] Fix crash in TokenAnnotator (PR #82349)

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


@@ -13503,6 +13503,9 @@ TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
   verifyFormat("{");
   verifyFormat("#})");
   verifyNoCrash("(/**/[:!] ?[).");
+  verifyNoCrash("struct X{"
+"  operator iunt("

owenca wrote:

```suggestion
  verifyNoCrash("struct X {\n"
"  operator iunt(\n"
```

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


[clang] [llvm] [AMDGPU] Enable OpenCL hostcall printf (WIP) (PR #72556)

2024-02-20 Thread Sameer Sahasrabuddhe via cfe-commits


@@ -199,15 +214,31 @@ RValue 
CodeGenFunction::EmitAMDGPUDevicePrintfCallExpr(const CallExpr *E) {
 }
 
 llvm::Value *Arg = A.getRValue(*this).getScalarVal();
+if (isString(A.getType().getTypePtr()) && CGM.getLangOpts().OpenCL)

ssahasra wrote:

The typecast can be inserted later when the arguments are actually processed. 
At that point, we already know which args are strings because we have parsed 
the format string.

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


[clang] [llvm] [AMDGPU] Enable OpenCL hostcall printf (WIP) (PR #72556)

2024-02-20 Thread Sameer Sahasrabuddhe via cfe-commits


@@ -198,15 +213,31 @@ RValue 
CodeGenFunction::EmitAMDGPUDevicePrintfCallExpr(const CallExpr *E) {
 }
 
 llvm::Value *Arg = A.getRValue(*this).getScalarVal();
+if (isString(A.getType().getTypePtr()) && CGM.getLangOpts().OpenCL)
+  Arg = Builder.CreateAddrSpaceCast(Arg, CGM.Int8PtrTy);
 Args.push_back(Arg);
   }
 
-  llvm::IRBuilder<> IRB(Builder.GetInsertBlock(), Builder.GetInsertPoint());
-  IRB.SetCurrentDebugLocation(Builder.getCurrentDebugLocation());
+  auto PFK = CGM.getTarget().getTargetOpts().AMDGPUPrintfKindVal;
+  bool isBuffered =
+   (PFK == clang::TargetOptions::AMDGPUPrintfKind::Buffered);
+
+  StringRef FmtStr;
+  if (llvm::getConstantStringInfo(Args[0], FmtStr)) {
+if (FmtStr.empty())
+  FmtStr = StringRef("", 1);
+  } else {
+if (CGM.getLangOpts().OpenCL) {

ssahasra wrote:

The diagnostic should be replaced with an assert() or an llvm_unreachable(). 
The OpenCL spec says that the format string should be resolvable at compile 
time, but this is not the right place to check that. By now, the frontend or 
sema should have rejected the program as ill-formed.

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


[clang] [llvm] [AMDGPU] Enable OpenCL hostcall printf (WIP) (PR #72556)

2024-02-20 Thread Sameer Sahasrabuddhe via cfe-commits


@@ -178,17 +181,29 @@ RValue 
CodeGenFunction::EmitNVPTXDevicePrintfCallExpr(const CallExpr *E) {
   E, this, GetVprintfDeclaration(CGM.getModule()), false);
 }
 
+// Deterimines if an argument is a string
+static bool isString(const clang::Type *argXTy) {

ssahasra wrote:

This could be called "MayBeString()" at best. It's not necessary that a char* 
argument type is a C-style string.

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


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

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

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


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

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


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

phoebewang wrote:

Can we remove the blank line to make to more compact?

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


[clang] [clang-format] Fix crash in TokenAnnotator (PR #82349)

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


@@ -3817,7 +3817,7 @@ void 
TokenAnnotator::calculateFormattingInformation(AnnotatedLine ) const {
 do {
   Tok = Tok->Next;
 } while (Tok && Tok->isNot(TT_OverloadedOperatorLParen));
-if (!Tok)
+if (!Tok || !Tok->Next)

owenca wrote:

```suggestion
if (!Tok || !Tok->MatchingParen)
```
Otherwise, it would still crash if the unmatched `l_paren` is not the last 
token on the line, e.g.:
```
struct Foo {
  operator foo(bar
};

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


[clang] [llvm] [RISCV] RISCV vector calling convention (1/2) (PR #77560)

2024-02-20 Thread Brandon Wu via cfe-commits

4vtomat wrote:

Rebase

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


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

2024-02-20 Thread Nathan Ridge via cfe-commits

HighCommander4 wrote:

> The OOM is not limited to `guessLanguage()`. [...]  It occurs even if you 
> rename the header files to .cpp files and clang-format the renamed files 
> directly.

I'm aware of that.

However, for clangd users, a crucial difference between `guessLanguage()` vs. 
other code in libFormat that uses `UnwrappedLineParser`, is that 
`guessLanguage()` gets called as soon as a file is opened in the editor, while 
the other code is only called if the user explicitly tries to format the file.

For the files affected by this OOM (single-file libraries like 
[miniaudio](https://github.com/mackron/miniaudio/blob/master/miniaudio.h), 
[mathlink](https://github.com/clangd/clangd/issues/1384), 
[minilzo](http://www.oberhumer.com/opensource/lzo/#minilzo), 
[blis](https://github.com/llvm/llvm-project/issues/60151), where the large 
number of configuration-related preprocessor branches and the large number of 
lines in the file conspire to make the combined length of all permutations 
intractable to work with), the number of users who merely use these libraries 
(and so may open them in the editor to look at the header, but will not try to 
format it) far exceeds the number of users who actually develop these libraries 
(who would edit and format the header). Thus, by avoiding the problem in 
`guessLanguage()`, we would resolve the issue for >99% of clangd users that run 
into it, which would be a significant improvement.

> (See 
> [119a728](https://github.com/llvm/llvm-project/commit/119a72866f0e143127355fe6e03f57c4f8bab1ae)
>  for an improvement to the performance of `guessLanguage()`.)

Thanks for this improvement. However, it does not meaningfully help avoid the 
OOM for the above libaries (the OOM happens while we're still in 
[`UnwrappedLineParser::parse()`](https://github.com/llvm/llvm-project/blob/04fbc461e0fd1c6f2b014761e9c03ca80d17b33b/clang/lib/Format/TokenAnalyzer.cpp#L113)).

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


[clang] 04fbc46 - [clang-format] Fix RemoveSemicolon for empty functions (#82278)

2024-02-20 Thread via cfe-commits

Author: Owen Pan
Date: 2024-02-20T21:51:51-08:00
New Revision: 04fbc461e0fd1c6f2b014761e9c03ca80d17b33b

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

LOG: [clang-format] Fix RemoveSemicolon for empty functions (#82278)

Fixes #79833.

Added: 


Modified: 
clang/lib/Format/Format.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 2c815128b1a59d..10ab406a15c6e1 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -2261,27 +2261,36 @@ class SemiRemover : public TokenAnalyzer {
   FormatTokenLexer ) override {
 AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
 tooling::Replacements Result;
-removeSemi(AnnotatedLines, Result);
+removeSemi(Annotator, AnnotatedLines, Result);
 return {Result, 0};
   }
 
 private:
-  void removeSemi(SmallVectorImpl ,
+  void removeSemi(TokenAnnotator ,
+  SmallVectorImpl ,
   tooling::Replacements ) {
+auto PrecededByFunctionRBrace = [](const FormatToken ) {
+  const auto *Prev = Tok.Previous;
+  if (!Prev || Prev->isNot(tok::r_brace))
+return false;
+  const auto *LBrace = Prev->MatchingParen;
+  return LBrace && LBrace->is(TT_FunctionLBrace);
+};
 const auto  = Env.getSourceManager();
 const auto End = Lines.end();
 for (auto I = Lines.begin(); I != End; ++I) {
   const auto Line = *I;
-  removeSemi(Line->Children, Result);
+  removeSemi(Annotator, Line->Children, Result);
   if (!Line->Affected)
 continue;
+  Annotator.calculateFormattingInformation(*Line);
   const auto NextLine = I + 1 == End ? nullptr : I[1];
   for (auto Token = Line->First; Token && !Token->Finalized;
Token = Token->Next) {
-if (!Token->Optional)
-  continue;
-if (Token->isNot(tok::semi))
+if (Token->isNot(tok::semi) ||
+(!Token->Optional && !PrecededByFunctionRBrace(*Token))) {
   continue;
+}
 auto Next = Token->Next;
 assert(Next || Token == Line->Last);
 if (!Next && NextLine)
@@ -3677,7 +3686,7 @@ reformat(const FormatStyle , StringRef Code,
   FormatStyle S = Expanded;
   S.RemoveSemicolon = true;
   Passes.emplace_back([&, S = std::move(S)](const Environment ) {
-return SemiRemover(Env, S).process(/*SkipAnnotation=*/true);
+return SemiRemover(Env, S).process();
   });
 }
 

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 24f62af8ddcb87..8282e75bd847f4 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -26720,13 +26720,20 @@ TEST_F(FormatTest, RemoveSemicolon) {
 
   verifyIncompleteFormat("class C final [[deprecated(l]] {});", Style);
 
-  // These tests are here to show a problem that may not be easily
-  // solved, our implementation to remove semicolons is only as good
-  // as our FunctionLBrace detection and this fails for empty braces
-  // because we can't distringuish this from a bracelist.
-  // We will enable when that is resolved.
-#if 0
   verifyFormat("void main() {}", "void main() {};", Style);
+
+  verifyFormat("struct Foo {\n"
+   "  Foo() {}\n"
+   "  ~Foo() {}\n"
+   "};",
+   "struct Foo {\n"
+   "  Foo() {};\n"
+   "  ~Foo() {};\n"
+   "};",
+   Style);
+
+// We can't (and probably shouldn't) support the following.
+#if 0
   verifyFormat("void foo() {} //\n"
"int bar;",
"void foo() {}; //\n"



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


[clang] [clang-format] Fix RemoveSemicolon for empty functions (PR #82278)

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

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


[clang] [llvm] [AMDGPU] Enable OpenCL hostcall printf (WIP) (PR #72556)

2024-02-20 Thread Vikram Hegde via cfe-commits

vikramRH wrote:

The new set of changes adds following changes,
1. The iteration over vector elements now happens using vector size from the 
format specifier as reference, this is inline with runtime implementation and 
helps handling undefined behavior when we have a mismatch.
2. The error flag "-Werror=format-invalid-specifier" has been removed.

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


[clang] [Clang][Sema] fix crash in codegen stage when an lambda expression declared in an unevaluated context (PR #80802)

2024-02-20 Thread Qizhi Hu via cfe-commits

jcsxky wrote:

> @jcsxky Do you have more test cases other than the one from #76674? I wonder 
> what'll happen if constraint checking is involved.

Do you mean `concept`? If yes, I will have a try.

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


[clang] [alpha.webkit.UncountedLocalVarsChecker] Allow uncounted object references within trivial statements (PR #82229)

2024-02-20 Thread Artem Dergachev via cfe-commits

haoNoQ wrote:

Ooo interesting. I want to spend a bit more time thinking whether this has to 
go into every callback, maybe it can be a set-and-forget thing? (Probably not.)

Also it might be a good idea to cache only statements that may ever get 
directly queried. (This seems to be exactly necessary and sufficient.) For now 
they're just the 5 control flow statements right? Maybe add caching to these 5 
callbacks and skip the rest? (I suspect it may matter for performance as well, 
dunno hard to tell though.)

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


[clang] [clang] Allow MCTargetOptions to be parseable by -mllvm. (PR #66347)

2024-02-20 Thread via cfe-commits

hstk30-hw wrote:

Some project use `Werror`  strictly,
https://github.com/ClangBuiltLinux/linux/issues/306 add the 
`-no-deprecated-warn` option, 
but we can't pass the flags from clang to llvm-mc, change the makefile to use 
`llvm-mc` to generate obj just for some file is inconvenience.

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


[clang] [InstallAPI] Set InstallAPI as a standalone tool instead of CC1 action (PR #82293)

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

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

>From bd648b50002a64ec098ff450cc6dacc0bc6b Mon Sep 17 00:00:00 2001
From: Cyndy Ishida 
Date: Tue, 20 Feb 2024 10:06:30 -0800
Subject: [PATCH 1/2] Revert " [clang][InstallAPI] Introduce basic driver to
 write out tbd files (#81571)"

This reverts commit 09e98950bfcff7ad376922932efb2b56e4db9898.
---
 .../clang/Basic/DiagnosticDriverKinds.td  |  3 -
 clang/include/clang/Driver/Action.h   | 12 
 clang/include/clang/Driver/Options.td | 12 +---
 clang/include/clang/Driver/Types.def  |  1 -
 .../include/clang/Frontend/CompilerInstance.h |  7 --
 .../clang/Frontend/CompilerInvocation.h   |  9 +--
 .../include/clang/Frontend/FrontendActions.h  | 10 ---
 .../include/clang/Frontend/FrontendOptions.h  |  3 -
 .../clang/Frontend/InstallAPIOptions.h| 28 
 clang/include/clang/InstallAPI/Context.h  | 65 ---
 clang/lib/CMakeLists.txt  |  1 -
 clang/lib/Driver/Action.cpp   |  7 --
 clang/lib/Driver/Driver.cpp   | 16 +
 clang/lib/Driver/ToolChain.cpp|  1 -
 clang/lib/Driver/ToolChains/Clang.cpp | 11 
 clang/lib/Frontend/CMakeLists.txt |  3 -
 clang/lib/Frontend/CompilerInvocation.cpp | 41 +---
 clang/lib/Frontend/InstallAPIConsumer.cpp | 43 
 .../ExecuteCompilerInvocation.cpp |  2 -
 clang/lib/InstallAPI/Context.cpp  | 27 
 clang/test/CMakeLists.txt |  1 -
 clang/test/Driver/installapi.h| 13 
 clang/test/InstallAPI/installapi-basic.test   | 34 --
 clang/test/lit.cfg.py |  1 -
 24 files changed, 5 insertions(+), 346 deletions(-)
 delete mode 100644 clang/include/clang/Frontend/InstallAPIOptions.h
 delete mode 100644 clang/include/clang/InstallAPI/Context.h
 delete mode 100644 clang/lib/Frontend/InstallAPIConsumer.cpp
 delete mode 100644 clang/lib/InstallAPI/Context.cpp
 delete mode 100644 clang/test/Driver/installapi.h
 delete mode 100644 clang/test/InstallAPI/installapi-basic.test

diff --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index 0807d8877591a6..b13181f6e70894 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -804,7 +804,4 @@ def warn_android_unversioned_fallback : Warning<
 
 def err_drv_triple_version_invalid : Error<
   "version '%0' in target triple '%1' is invalid">;
-
-def err_drv_installapi_unsupported : Error<
-  "InstallAPI is not supported for '%0'">;
 }
diff --git a/clang/include/clang/Driver/Action.h 
b/clang/include/clang/Driver/Action.h
index 2768e2f5df1a9e..04fa8b01b418f8 100644
--- a/clang/include/clang/Driver/Action.h
+++ b/clang/include/clang/Driver/Action.h
@@ -59,7 +59,6 @@ class Action {
 PreprocessJobClass,
 PrecompileJobClass,
 ExtractAPIJobClass,
-InstallAPIJobClass,
 AnalyzeJobClass,
 MigrateJobClass,
 CompileJobClass,
@@ -449,17 +448,6 @@ class ExtractAPIJobAction : public JobAction {
   void addHeaderInput(Action *Input) { getInputs().push_back(Input); }
 };
 
-class InstallAPIJobAction : public JobAction {
-  void anchor() override;
-
-public:
-  InstallAPIJobAction(Action *Input, types::ID OutputType);
-
-  static bool classof(const Action *A) {
-return A->getKind() == InstallAPIJobClass;
-  }
-};
-
 class AnalyzeJobAction : public JobAction {
   void anchor() override;
 
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 36a42b1b050c23..3a028fadb25b18 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -336,8 +336,6 @@ class AnalyzerOpts
   : KeyPathAndMacro<"AnalyzerOpts->", base, "ANALYZER_"> {}
 class MigratorOpts
   : KeyPathAndMacro<"MigratorOpts.", base, "MIGRATOR_"> {}
-class InstallAPIOpts
-  : KeyPathAndMacro<"InstallAPIOpts.", base, "INSTALLAPI_"> {}
 
 // A boolean option which is opt-in in CC1. The positive option exists in CC1 
and
 // Args.hasArg(OPT_ffoo) can be used to check that the flag is enabled.
@@ -1143,8 +1141,7 @@ def config_user_dir_EQ : Joined<["--"], 
"config-user-dir=">,
 def coverage : Flag<["-", "--"], "coverage">, Group,
   Visibility<[ClangOption, CLOption]>;
 def cpp_precomp : Flag<["-"], "cpp-precomp">, Group;
-def current__version : JoinedOrSeparate<["-"], "current_version">,
-  Visibility<[ClangOption, CC1Option]>;
+def current__version : JoinedOrSeparate<["-"], "current_version">;
 def cxx_isystem : JoinedOrSeparate<["-"], "cxx-isystem">, Group,
   HelpText<"Add directory to the C++ SYSTEM include search path">,
   Visibility<[ClangOption, CC1Option]>,
@@ -1559,9 +1556,6 @@ def static_libsan : Flag<["-"], "static-libsan">,
   HelpText<"Statically link the sanitizer runtime (Not supported for ASan, 

[clang] [llvm] [MC/DC][Coverage] Loosen the limit of NumConds from 6 (PR #82448)

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


@@ -983,7 +979,7 @@ void CodeGenPGO::mapRegionCounters(const Decl *D) {
   // for most embedded applications. Setting a maximum value prevents the
   // bitmap footprint from growing too large without the user's knowledge. In
   // the future, this value could be adjusted with a command-line option.
-  unsigned MCDCMaxConditions = (CGM.getCodeGenOpts().MCDCCoverage) ? 6 : 0;
+  unsigned MCDCMaxConditions = (CGM.getCodeGenOpts().MCDCCoverage) ? 32767 : 0;

chapuni wrote:

`MaxCond` is one of options. I guess it could be configurable just for theirs 
coding rules, since I think controlling `MaxCond` would not make sense.
I know we have to introduce other options as well. I will do later.
* `MaxCond`
* `MaxTVs` to restrict per-expression number of TVs
* "Max bytes of bitmap in the CU" to restict inter-function size of the bitmap.

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


[clang] [ObjC] Check entire chain of superclasses to see if class layout can be statically known (PR #81335)

2024-02-20 Thread via cfe-commits

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

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

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

diff --git a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m 
b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
index 788b3220af3067..0bf3336527b0a0 100644
--- a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
+++ b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
@@ -1,6 +1,12 @@
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 -emit-llvm %s -o - | 
FileCheck %s
 
 // CHECK: @"OBJC_IVAR_$_StaticLayout.static_layout_ivar" = hidden constant i64 
20
+// CHECK: @"OBJC_IVAR_$_SuperClass.superClassIvar" = hidden constant i64 20
+// CHECK: @"OBJC_IVAR_$_SuperClass._superClassProperty" = hidden constant i64 
24
+// CHECK: @"OBJC_IVAR_$_IntermediateClass.intermediateClassIvar" = global i64 
32
+// CHECK: @"OBJC_IVAR_$_IntermediateClass.intermediateClassIvar2" = global i64 
40
+// CHECK: @"OBJC_IVAR_$_IntermediateClass._intermediateProperty" = hidden 
global i64 48
+// CHECK: @"OBJC_IVAR_$_SubClass.subClassIvar" = global i64 56
 // CHECK: @"OBJC_IVAR_$_NotStaticLayout.not_static_layout_ivar" = hidden 
global i64 12
 
 @interface NSObject {
@@ -20,6 +26,70 @@ -(void)meth {
 }
 @end
 
+// Ivars declared in the @interface
+@interface SuperClass : NSObject
+@property (nonatomic, assign) int superClassProperty;
+@end
+
+@implementation SuperClass {
+  int superClassIvar; // Declare an ivar
+}
+- (void)superClassMethod {
+_superClassProperty = 42;
+superClassIvar = 10;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SuperClass
+// CHECK: getelementptr inbounds i8, ptr %1, i64 20
+}
+@end
+
+// Inheritance and Ivars
+@interface IntermediateClass : SuperClass
+{
+double intermediateClassIvar;
+
+@protected
+int intermediateClassIvar2;
+}
+@property (nonatomic, strong) SuperClass *intermediateProperty;
+@end
+
+@implementation IntermediateClass
+@synthesize intermediateProperty = _intermediateProperty;
+- (void)intermediateClassMethod {
+intermediateClassIvar = 3.14;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_IntermediateClass
+// CHECK: getelementptr inbounds i8, ptr %0, i64 %ivar
+}
+
+- (void)intermediateClassPropertyMethod {
+self.intermediateProperty = 0;
+// CHECK: getelementptr inbounds i8, ptr %2, i64 24
+}
+@end
+
+@interface SubClass : IntermediateClass
+{
+double subClassIvar;
+}
+@end
+
+@implementation SubClass
+- (void)subclassVar {
+
+subClassIvar = 6.28;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SubClass
+// CHECK: getelementptr inbounds i8, ptr %0, i64 %ivar
+}
+
+-(void)intermediateSubclassVar
+{
+intermediateClassIvar = 3.14;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_IntermediateClass
+// CHECK: getelementptr inbounds i8, ptr %0, i64 %ivar
+}
+
+@end
+
 @interface NotNSObject {
   int these, might, change;
 }

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

As of now, we only check if a class directly inherits from NSObject to 
determine if said class has fixed offsets and can therefore have its memory 
layout statically known.

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

To determine this, we need to find that the compiler can see the implementation 
of each intermediate class, as that means it is statically linked.
---
 clang/lib/CodeGen/CGObjCMac.cpp   | 22 ++
 .../constant-non-fragile-ivar-offset.m| 30 +--
 2 files changed, 31 insertions(+), 21 deletions(-)

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

[clang] [ObjC] Check entire chain of superclasses to see if class layout can be statically known (PR #81335)

2024-02-20 Thread via cfe-commits

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

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

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

diff --git a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m 
b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
index 788b3220af3067..0bf3336527b0a0 100644
--- a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
+++ b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
@@ -1,6 +1,12 @@
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 -emit-llvm %s -o - | 
FileCheck %s
 
 // CHECK: @"OBJC_IVAR_$_StaticLayout.static_layout_ivar" = hidden constant i64 
20
+// CHECK: @"OBJC_IVAR_$_SuperClass.superClassIvar" = hidden constant i64 20
+// CHECK: @"OBJC_IVAR_$_SuperClass._superClassProperty" = hidden constant i64 
24
+// CHECK: @"OBJC_IVAR_$_IntermediateClass.intermediateClassIvar" = global i64 
32
+// CHECK: @"OBJC_IVAR_$_IntermediateClass.intermediateClassIvar2" = global i64 
40
+// CHECK: @"OBJC_IVAR_$_IntermediateClass._intermediateProperty" = hidden 
global i64 48
+// CHECK: @"OBJC_IVAR_$_SubClass.subClassIvar" = global i64 56
 // CHECK: @"OBJC_IVAR_$_NotStaticLayout.not_static_layout_ivar" = hidden 
global i64 12
 
 @interface NSObject {
@@ -20,6 +26,70 @@ -(void)meth {
 }
 @end
 
+// Ivars declared in the @interface
+@interface SuperClass : NSObject
+@property (nonatomic, assign) int superClassProperty;
+@end
+
+@implementation SuperClass {
+  int superClassIvar; // Declare an ivar
+}
+- (void)superClassMethod {
+_superClassProperty = 42;
+superClassIvar = 10;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SuperClass
+// CHECK: getelementptr inbounds i8, ptr %1, i64 20
+}
+@end
+
+// Inheritance and Ivars
+@interface IntermediateClass : SuperClass
+{
+double intermediateClassIvar;
+
+@protected
+int intermediateClassIvar2;
+}
+@property (nonatomic, strong) SuperClass *intermediateProperty;
+@end
+
+@implementation IntermediateClass
+@synthesize intermediateProperty = _intermediateProperty;
+- (void)intermediateClassMethod {
+intermediateClassIvar = 3.14;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_IntermediateClass
+// CHECK: getelementptr inbounds i8, ptr %0, i64 %ivar
+}
+
+- (void)intermediateClassPropertyMethod {
+self.intermediateProperty = 0;
+// CHECK: getelementptr inbounds i8, ptr %2, i64 24
+}
+@end
+
+@interface SubClass : IntermediateClass
+{
+double subClassIvar;
+}
+@end
+
+@implementation SubClass
+- (void)subclassVar {
+
+subClassIvar = 6.28;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SubClass
+// CHECK: getelementptr inbounds i8, ptr %0, i64 %ivar
+}
+
+-(void)intermediateSubclassVar
+{
+intermediateClassIvar = 3.14;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_IntermediateClass
+// CHECK: getelementptr inbounds i8, ptr %0, i64 %ivar
+}
+
+@end
+
 @interface NotNSObject {
   int these, might, change;
 }

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

As of now, we only check if a class directly inherits from NSObject to 
determine if said class has fixed offsets and can therefore have its memory 
layout statically known.

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

To determine this, we need to find that the compiler can see the implementation 
of each intermediate class, as that means it is statically linked.
---
 clang/lib/CodeGen/CGObjCMac.cpp   | 22 ++-
 .../constant-non-fragile-ivar-offset.m| 18 +++
 2 files changed, 25 insertions(+), 15 deletions(-)

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

[clang] [ObjC] Check entire chain of superclasses to see if class layout can be statically known (PR #81335)

2024-02-20 Thread via cfe-commits

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

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

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

diff --git a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m 
b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
index 788b3220af3067..0bf3336527b0a0 100644
--- a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
+++ b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
@@ -1,6 +1,12 @@
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 -emit-llvm %s -o - | 
FileCheck %s
 
 // CHECK: @"OBJC_IVAR_$_StaticLayout.static_layout_ivar" = hidden constant i64 
20
+// CHECK: @"OBJC_IVAR_$_SuperClass.superClassIvar" = hidden constant i64 20
+// CHECK: @"OBJC_IVAR_$_SuperClass._superClassProperty" = hidden constant i64 
24
+// CHECK: @"OBJC_IVAR_$_IntermediateClass.intermediateClassIvar" = global i64 
32
+// CHECK: @"OBJC_IVAR_$_IntermediateClass.intermediateClassIvar2" = global i64 
40
+// CHECK: @"OBJC_IVAR_$_IntermediateClass._intermediateProperty" = hidden 
global i64 48
+// CHECK: @"OBJC_IVAR_$_SubClass.subClassIvar" = global i64 56
 // CHECK: @"OBJC_IVAR_$_NotStaticLayout.not_static_layout_ivar" = hidden 
global i64 12
 
 @interface NSObject {
@@ -20,6 +26,70 @@ -(void)meth {
 }
 @end
 
+// Ivars declared in the @interface
+@interface SuperClass : NSObject
+@property (nonatomic, assign) int superClassProperty;
+@end
+
+@implementation SuperClass {
+  int superClassIvar; // Declare an ivar
+}
+- (void)superClassMethod {
+_superClassProperty = 42;
+superClassIvar = 10;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SuperClass
+// CHECK: getelementptr inbounds i8, ptr %1, i64 20
+}
+@end
+
+// Inheritance and Ivars
+@interface IntermediateClass : SuperClass
+{
+double intermediateClassIvar;
+
+@protected
+int intermediateClassIvar2;
+}
+@property (nonatomic, strong) SuperClass *intermediateProperty;
+@end
+
+@implementation IntermediateClass
+@synthesize intermediateProperty = _intermediateProperty;
+- (void)intermediateClassMethod {
+intermediateClassIvar = 3.14;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_IntermediateClass
+// CHECK: getelementptr inbounds i8, ptr %0, i64 %ivar
+}
+
+- (void)intermediateClassPropertyMethod {
+self.intermediateProperty = 0;
+// CHECK: getelementptr inbounds i8, ptr %2, i64 24
+}
+@end
+
+@interface SubClass : IntermediateClass
+{
+double subClassIvar;
+}
+@end
+
+@implementation SubClass
+- (void)subclassVar {
+
+subClassIvar = 6.28;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SubClass
+// CHECK: getelementptr inbounds i8, ptr %0, i64 %ivar
+}
+
+-(void)intermediateSubclassVar
+{
+intermediateClassIvar = 3.14;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_IntermediateClass
+// CHECK: getelementptr inbounds i8, ptr %0, i64 %ivar
+}
+
+@end
+
 @interface NotNSObject {
   int these, might, change;
 }

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

As of now, we only check if a class directly inherits from NSObject to 
determine if said class has fixed offsets and can therefore have its memory 
layout statically known.

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

To determine this, we need to find that the compiler can see the implementation 
of each intermediate class, as that means it is statically linked.
---
 clang/lib/CodeGen/CGObjCMac.cpp   | 22 ++-
 .../constant-non-fragile-ivar-offset.m| 19 
 2 files changed, 25 insertions(+), 16 deletions(-)

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

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

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

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

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

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

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

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

2024-02-20 Thread Eli Friedman via cfe-commits


@@ -886,28 +886,16 @@ llvm::ARM::FPUKind arm::getARMTargetFeatures(const Driver 
,
   } else {
 // Assume pre-ARMv6 doesn't support unaligned accesses.
 //
-// ARMv6 may or may not support unaligned accesses depending on the
-// SCTLR.U bit, which is architecture-specific. We assume ARMv6
-// Darwin and NetBSD targets support unaligned accesses, and others don't.
+// Assume ARMv6+ supports unaligned accesses, except Armv6-M, and Armv8-M
+// without the Main Extension. This aligns with the default behavior of
+// ARM's downstream versions of GCC and Clang
 //
-// ARMv7 always has SCTLR.U set to 1, but it has a new SCTLR.A bit
-// which raises an alignment fault on unaligned accesses. Linux
-// defaults this bit to 0 and handles it as a system-wide (not
-// per-process) setting. It is therefore safe to assume that ARMv7+
-// Linux targets support unaligned accesses. The same goes for NaCl
-// and Windows.
-//
-// The above behavior is consistent with GCC.
+// Users can disable behavior via -mno-unaliged-access.
 int VersionNum = getARMSubArchVersionNumber(Triple);
-if (Triple.isOSDarwin() || Triple.isOSNetBSD()) {
-  if (VersionNum < 6 ||
-  Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
-Features.push_back("+strict-align");
-} else if (Triple.isOSLinux() || Triple.isOSNaCl() ||
-   Triple.isOSWindows()) {
-  if (VersionNum < 7)
-Features.push_back("+strict-align");
-} else
+if (VersionNum < 6 ||
+Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m ||
+Triple.getSubArch() ==
+llvm::Triple::SubArchType::ARMSubArch_v8m_baseline)

efriedma-quic wrote:

I don't have a strong opinion on how we treat v6a. I guess I'd lean towards 
being conservative, I guess, like what you wrote?

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


[clang] [Analyzer] Support RefAllowingPartiallyDestroyed and RefPtrAllowingPartiallyDestroyed (PR #82209)

2024-02-20 Thread Ryosuke Niwa via cfe-commits

https://github.com/rniwa updated https://github.com/llvm/llvm-project/pull/82209

>From 1d53adbe50d8afb7c91e8b393c64d6f590256602 Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa 
Date: Sun, 18 Feb 2024 21:47:48 -0800
Subject: [PATCH 1/2] [analyzer] Support RefAllowingPartiallyDestroyed and
 RefPtrAllowingPartiallyDestroyed

This PR adds the support for WebKit's RefAllowingPartiallyDestroyed and
RefPtrAllowingPartiallyDestroyed, which are smart pointer types which may be 
used
after the destructor had started running.
---
 .../Checkers/WebKit/PtrTypesSemantics.cpp | 27 ++--
 .../Analysis/Checkers/WebKit/mock-types.h |  1 +
 .../ref-allowing-partially-destroyed.cpp  | 44 +++
 3 files changed, 59 insertions(+), 13 deletions(-)
 create mode 100644 
clang/test/Analysis/Checkers/WebKit/ref-allowing-partially-destroyed.cpp

diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
index a7891d2da07c18..c97e7a7a379b96 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
@@ -103,15 +103,18 @@ std::optional isRefCountable(const CXXRecordDecl* R)
   return hasRef && hasDeref;
 }
 
+bool isRefType(const std::string ) {
+  return name == "Ref" || name == "RefAllowingPartiallyDestroyed" ||
+ name == "RefPtr" || name == "RefPtrAllowingPartiallyDestroyed";
+}
+
 bool isCtorOfRefCounted(const clang::FunctionDecl *F) {
   assert(F);
   const auto  = safeGetName(F);
 
-  return FunctionName == "Ref" || FunctionName == "makeRef"
-
- || FunctionName == "RefPtr" || FunctionName == "makeRefPtr"
-
- || FunctionName == "UniqueRef" || FunctionName == "makeUniqueRef" ||
+  return isRefType(FunctionName) || FunctionName == "makeRef" ||
+ FunctionName == "makeRefPtr" || FunctionName == "UniqueRef" ||
+ FunctionName == "makeUniqueRef" ||
  FunctionName == "makeUniqueRefWithoutFastMallocCheck"
 
  || FunctionName == "String" || FunctionName == "AtomString" ||
@@ -131,7 +134,7 @@ bool isReturnValueRefCounted(const clang::FunctionDecl *F) {
 if (auto *specialT = type->getAs()) {
   if (auto *decl = specialT->getTemplateName().getAsTemplateDecl()) {
 auto name = decl->getNameAsString();
-return name == "Ref" || name == "RefPtr";
+return isRefType(name);
   }
   return false;
 }
@@ -172,20 +175,18 @@ std::optional isGetterOfRefCounted(const 
CXXMethodDecl* M)
   if (isa(M)) {
 const CXXRecordDecl *calleeMethodsClass = M->getParent();
 auto className = safeGetName(calleeMethodsClass);
-auto methodName = safeGetName(M);
+auto method = safeGetName(M);
 
-if (((className == "Ref" || className == "RefPtr") &&
- methodName == "get") ||
-(className == "Ref" && methodName == "ptr") ||
+if ((isRefType(className) && (method == "get" || method == "ptr")) ||
 ((className == "String" || className == "AtomString" ||
   className == "AtomStringImpl" || className == "UniqueString" ||
   className == "UniqueStringImpl" || className == "Identifier") &&
- methodName == "impl"))
+ method == "impl"))
   return true;
 
 // Ref -> T conversion
 // FIXME: Currently allowing any Ref -> whatever cast.
-if (className == "Ref" || className == "RefPtr") {
+if (isRefType(className)) {
   if (auto *maybeRefToRawOperator = dyn_cast(M)) {
 if (auto *targetConversionType =
 maybeRefToRawOperator->getConversionType().getTypePtrOrNull()) 
{
@@ -202,7 +203,7 @@ bool isRefCounted(const CXXRecordDecl *R) {
   if (auto *TmplR = R->getTemplateInstantiationPattern()) {
 // FIXME: String/AtomString/UniqueString
 const auto  = safeGetName(TmplR);
-return ClassName == "RefPtr" || ClassName == "Ref";
+return isRefType(ClassName);
   }
   return false;
 }
diff --git a/clang/test/Analysis/Checkers/WebKit/mock-types.h 
b/clang/test/Analysis/Checkers/WebKit/mock-types.h
index 82db67bb031dd6..e2b3401d407392 100644
--- a/clang/test/Analysis/Checkers/WebKit/mock-types.h
+++ b/clang/test/Analysis/Checkers/WebKit/mock-types.h
@@ -16,6 +16,7 @@ template  struct Ref {
   }
   T *get() { return t; }
   T *ptr() { return t; }
+  T *operator->() { return t; }
   operator const T &() const { return *t; }
   operator T &() { return *t; }
 };
diff --git 
a/clang/test/Analysis/Checkers/WebKit/ref-allowing-partially-destroyed.cpp 
b/clang/test/Analysis/Checkers/WebKit/ref-allowing-partially-destroyed.cpp
new file mode 100644
index 00..6d96c14102a902
--- /dev/null
+++ b/clang/test/Analysis/Checkers/WebKit/ref-allowing-partially-destroyed.cpp
@@ -0,0 +1,44 @@
+// RUN: %clang_analyze_cc1 
-analyzer-checker=alpha.webkit.UncountedCallArgsChecker -verify %s
+// expected-no-diagnostics
+
+#include "mock-types.h"
+
+template  struct 

[clang] [Analyzer] Support RefAllowingPartiallyDestroyed and RefPtrAllowingPartiallyDestroyed (PR #82209)

2024-02-20 Thread Ryosuke Niwa via cfe-commits


@@ -103,15 +103,18 @@ std::optional isRefCountable(const CXXRecordDecl* R)
   return hasRef && hasDeref;
 }
 
+bool isRefType(const std::string ) {
+  return name == "Ref" || name == "RefAllowingPartiallyDestroyed" ||
+ name == "RefPtr" || name == "RefPtrAllowingPartiallyDestroyed";
+}
+
 bool isCtorOfRefCounted(const clang::FunctionDecl *F) {
   assert(F);
   const auto  = safeGetName(F);

rniwa wrote:

Changed it to use `std::string &`.

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


[clang] [llvm] [MC/DC][Coverage] Loosen the limit of NumConds from 6 (PR #82448)

2024-02-20 Thread Jessica Paquette via cfe-commits


@@ -983,7 +979,7 @@ void CodeGenPGO::mapRegionCounters(const Decl *D) {
   // for most embedded applications. Setting a maximum value prevents the
   // bitmap footprint from growing too large without the user's knowledge. In
   // the future, this value could be adjusted with a command-line option.
-  unsigned MCDCMaxConditions = (CGM.getCodeGenOpts().MCDCCoverage) ? 6 : 0;
+  unsigned MCDCMaxConditions = (CGM.getCodeGenOpts().MCDCCoverage) ? 32767 : 0;

ornata wrote:

I think the limit should be controlled by a flag, with a reasonable default 
value.

E.g.

`-mcdc-max-conditions=`

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


[clang] Sanitizer: Support -fwrapv with -fsanitize=signed-integer-overflow (PR #82432)

2024-02-20 Thread Kees Cook via cfe-commits

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

Working as expected for me!

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


[clang] 84ed55e - Revert "[clang][ScanDeps] Canonicalize -D and -U flags (#82298)"

2024-02-20 Thread Nico Weber via cfe-commits

Author: Nico Weber
Date: 2024-02-20T20:24:32-05:00
New Revision: 84ed55e11f8d8f434395f869a1caa8485dd0c187

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

LOG: Revert "[clang][ScanDeps] Canonicalize -D and -U flags (#82298)"

This reverts commit 3ff805540173b83d73b673b39ac5760fc19bac15.

Test is failing on bots, see
https://github.com/llvm/llvm-project/pull/82298#issuecomment-1955664462

Added: 


Modified: 
clang/include/clang/Tooling/DependencyScanning/DependencyScanningService.h
clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
clang/tools/clang-scan-deps/ClangScanDeps.cpp

Removed: 
clang/test/ClangScanDeps/optimize-canonicalize-macros.m



diff  --git 
a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningService.h 
b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningService.h
index 557f0e547ab4a8..4f9867262a275c 100644
--- a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningService.h
+++ b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningService.h
@@ -60,10 +60,7 @@ enum class ScanningOptimizations {
   /// Remove unused -ivfsoverlay arguments.
   VFS = 4,
 
-  /// Canonicalize -D and -U options.
-  Macros = 8,
-
-  DSS_LAST_BITMASK_ENUM(Macros),
+  DSS_LAST_BITMASK_ENUM(VFS),
   Default = All
 };
 

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

[clang] [clang][ScanDeps] Canonicalize -D and -U flags (PR #82298)

2024-02-20 Thread Nico Weber via cfe-commits

nico wrote:

Also failing here https://lab.llvm.org/buildbot/#/builders/259/builds/126 and 
here https://lab.llvm.org/buildbot/#/builders/139/builds/59858

Given that the bots have been broken for a few hours now, I'll revert.

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


[clang] [clang][ScanDeps] Canonicalize -D and -U flags (PR #82298)

2024-02-20 Thread Nico Weber via cfe-commits

nico wrote:

The test is failing at least on my bot: 
http://45.33.8.238/linux/131314/step_7.txt

I'm guessing this is some unicode/sed thing? It's a pretty vanilla linux 
machine.

(It uses a non-standard non-supported build system, but at least from a 
distance that looks unrelated?)

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


[clang] [clang][analyzer] Change modeling of 'fileno' in checkers. (PR #81842)

2024-02-20 Thread Ben Shi via cfe-commits
=?utf-8?q?Balázs_Kéri?= 
Message-ID:
In-Reply-To: 



@@ -1404,6 +1486,47 @@ void StreamChecker::evalFeofFerror(const FnDescription 
*Desc,
   }
 }
 
+void StreamChecker::evalFileno(const FnDescription *Desc, const CallEvent 
,
+   CheckerContext ) const {
+  // Fileno should fail only if the passed pointer is invalid.
+  // Some of the preconditions are checked already in preDefault.
+  // Here we can assume that the operation does not fail.
+  // An added failure case causes many unexpected warnings because a file 
number
+  // becomes -1 that is not expected by the program.
+  // The stream error states are not modified by 'fileno', and not the 'errno'.
+  // (To ensure that errno is not changed, this evalCall is needed to not
+  // invalidate 'errno' like in a default case.)
+  ProgramStateRef State = C.getState();
+  SymbolRef StreamSym = getStreamArg(Desc, Call).getAsSymbol();
+  if (!StreamSym)
+return;
+
+  const CallExpr *CE = dyn_cast_or_null(Call.getOriginExpr());

benshi001 wrote:

Shall we change to `StreamOperationEvaluator` which is introduced by your 
previous simplification patch ?

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


[clang] [clang][analyzer] Change modeling of 'fileno' in checkers. (PR #81842)

2024-02-20 Thread Ben Shi via cfe-commits
=?utf-8?q?Bal=C3=A1zs_K=C3=A9ri?= 
Message-ID:
In-Reply-To: 



@@ -268,6 +268,16 @@ void test_clearerr(FILE *F) {
// expected-warning@-1{{FALSE}}
 }
 
+void test_fileno(FILE *F) {
+  errno = 0;
+  int A = fileno(F);
+  clang_analyzer_eval(F != NULL); // expected-warning{{TRUE}}
+  clang_analyzer_eval(A >= 0); // expected-warning{{TRUE}}

benshi001 wrote:

It looks better to making the comment lines begin from the same column.

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


[clang] [clang][analyzer] Change modeling of 'fileno' in checkers. (PR #81842)

2024-02-20 Thread Ben Shi via cfe-commits
=?utf-8?q?Bal=C3=A1zs_K=C3=A9ri?= 
Message-ID:
In-Reply-To: 


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


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


[clang] [clang][analyzer] Change modeling of 'fileno' in checkers. (PR #81842)

2024-02-20 Thread Ben Shi via cfe-commits
=?utf-8?q?Balázs_Kéri?= 
Message-ID:
In-Reply-To: 


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


[clang] Sanitizer: Support -fwrapv with -fsanitize=signed-integer-overflow (PR #82432)

2024-02-20 Thread Kees Cook via cfe-commits

kees wrote:

This doesn't seem to do anything for me with the Linux kernel's -next branch 
(which supports -sio as `CONFIG_UBSAN_SIGNED_WRAP=y`). e.g. I see no behavioral 
difference with test_ubsan.ko nor the expected atomic overflows.

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


[clang] [alpha.webkit.UncountedCallArgsChecker] Ignore calls to WTF's container methods (PR #82156)

2024-02-20 Thread Ryosuke Niwa via cfe-commits

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


[clang] 031f9f3 - [alpha.webkit.UncountedCallArgsChecker] Ignore calls to WTF's container methods (#82156)

2024-02-20 Thread via cfe-commits

Author: Ryosuke Niwa
Date: 2024-02-20T17:12:24-08:00
New Revision: 031f9f331723e6bebc405ffdee4b8a87a5fc0472

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

LOG: [alpha.webkit.UncountedCallArgsChecker] Ignore calls to WTF's container 
methods (#82156)

This PR makes the checker ignore / skip calls to methods of Web Template
Platform's container types such as HashMap, HashSet, WeakHashSet,
WeakHashMap, Vector, etc...

Added: 
clang/test/Analysis/Checkers/WebKit/call-args-wtf-containers.cpp

Modified: 
clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp

Removed: 




diff  --git 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp
index 8d344f9b63961a..8b41a949fd6734 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp
@@ -170,6 +170,9 @@ class UncountedCallArgsChecker
 if (!Callee)
   return false;
 
+if (isMethodOnWTFContainerType(Callee))
+  return true;
+
 auto overloadedOperatorType = Callee->getOverloadedOperator();
 if (overloadedOperatorType == OO_EqualEqual ||
 overloadedOperatorType == OO_ExclaimEqual ||
@@ -198,6 +201,31 @@ class UncountedCallArgsChecker
 return false;
   }
 
+  bool isMethodOnWTFContainerType(const FunctionDecl *Decl) const {
+if (!isa(Decl))
+  return false;
+auto *ClassDecl = Decl->getParent();
+if (!ClassDecl || !isa(ClassDecl))
+  return false;
+
+auto *NsDecl = ClassDecl->getParent();
+if (!NsDecl || !isa(NsDecl))
+  return false;
+
+auto MethodName = safeGetName(Decl);
+auto ClsNameStr = safeGetName(ClassDecl);
+StringRef ClsName = ClsNameStr; // FIXME: Make safeGetName return 
StringRef.
+auto NamespaceName = safeGetName(NsDecl);
+// FIXME: These should be implemented via attributes.
+return NamespaceName == "WTF" &&
+   (MethodName == "find" || MethodName == "findIf" ||
+MethodName == "reverseFind" || MethodName == "reverseFindIf" ||
+MethodName == "get" || MethodName == "inlineGet" ||
+MethodName == "contains" || MethodName == "containsIf") &&
+   (ClsName.ends_with("Vector") || ClsName.ends_with("Set") ||
+ClsName.ends_with("Map"));
+  }
+
   void reportBug(const Expr *CallArg, const ParmVarDecl *Param) const {
 assert(CallArg);
 

diff  --git a/clang/test/Analysis/Checkers/WebKit/call-args-wtf-containers.cpp 
b/clang/test/Analysis/Checkers/WebKit/call-args-wtf-containers.cpp
new file mode 100644
index 00..0a63a789856127
--- /dev/null
+++ b/clang/test/Analysis/Checkers/WebKit/call-args-wtf-containers.cpp
@@ -0,0 +1,146 @@
+// RUN: %clang_analyze_cc1 
-analyzer-checker=alpha.webkit.UncountedCallArgsChecker -verify %s
+
+#include "mock-types.h"
+
+namespace WTF {
+
+  template 
+  class HashSet {
+  public:
+template  T* find(U&) const;
+template  bool contains(U&) const;
+unsigned size() { return m_size; }
+template  void add(U&) const;
+template  void remove(U&) const;
+
+  private:
+T* m_table { nullptr };
+unsigned m_size { 0 };
+  };
+
+  template 
+  class HashMap {
+  public:
+struct Item {
+  T key;
+  S value;
+};
+
+template  Item* find(U&) const;
+template  bool contains(U&) const;
+template  S* get(U&) const;
+template  S* inlineGet(U&) const;
+template  void add(U&) const;
+template  void remove(U&) const;
+
+  private:
+Item* m_table { nullptr };
+  };
+
+  template 
+  class WeakHashSet {
+  public:
+template  T* find(U&) const;
+template  bool contains(U&) const;
+template  void add(U&) const;
+template  void remove(U&) const;
+  };
+
+  template 
+  class Vector {
+  public:
+unsigned size() { return m_size; }
+T& at(unsigned i) { return m_buffer[i]; }
+T& operator[](unsigned i) { return m_buffer[i]; }
+template  unsigned find(U&);
+template  unsigned reverseFind(U&);
+template  bool contains(U&);
+template  unsigned findIf(const MatchFunction& 
match)
+{
+  for (unsigned i = 0; i < m_size; ++i) {
+if (match(at(i)))
+  return i;
+  }
+  return static_cast(-1);
+}
+template  unsigned reverseFindIf(const 
MatchFunction& match)
+{
+  for (unsigned i = 0; i < m_size; ++i) {
+if (match(at(m_size - i)))
+  return i;
+  }
+  return static_cast(-1);
+}
+template  bool containsIf(const MatchFunction& 
match)
+{
+  for (unsigned i = 0; i < m_size; ++i) {
+if (match(at(m_size - i)))
+  return true;
+  }
+  return false;
+}
+  

[clang] [alpha.webkit.UncountedCallArgsChecker] Ignore calls to WTF's container methods (PR #82156)

2024-02-20 Thread Ryosuke Niwa via cfe-commits

rniwa wrote:

Yeah, indeed. Thank you for the review!

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


[clang] [Analyzer] Support RefAllowingPartiallyDestroyed and RefPtrAllowingPartiallyDestroyed (PR #82209)

2024-02-20 Thread Ryosuke Niwa via cfe-commits


@@ -103,15 +103,18 @@ std::optional isRefCountable(const CXXRecordDecl* R)
   return hasRef && hasDeref;
 }
 
+bool isRefType(const std::string ) {
+  return name == "Ref" || name == "RefAllowingPartiallyDestroyed" ||
+ name == "RefPtr" || name == "RefPtrAllowingPartiallyDestroyed";
+}
+
 bool isCtorOfRefCounted(const clang::FunctionDecl *F) {
   assert(F);
   const auto  = safeGetName(F);

rniwa wrote:

So we want to explicitly say `std::string &`?

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


[clang] [Analyzer] Support RefAllowingPartiallyDestroyed and RefPtrAllowingPartiallyDestroyed (PR #82209)

2024-02-20 Thread Artem Dergachev via cfe-commits

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

LGTM! I have one stylistic nitpick.

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


[clang] [Analyzer] Support RefAllowingPartiallyDestroyed and RefPtrAllowingPartiallyDestroyed (PR #82209)

2024-02-20 Thread Artem Dergachev via cfe-commits


@@ -103,15 +103,18 @@ std::optional isRefCountable(const CXXRecordDecl* R)
   return hasRef && hasDeref;
 }
 
+bool isRefType(const std::string ) {
+  return name == "Ref" || name == "RefAllowingPartiallyDestroyed" ||
+ name == "RefPtr" || name == "RefPtrAllowingPartiallyDestroyed";
+}
+
 bool isCtorOfRefCounted(const clang::FunctionDecl *F) {
   assert(F);
   const auto  = safeGetName(F);

haoNoQ wrote:

I think folks don't want you to use `auto` in such cases 
(https://llvm.org/docs/CodingStandards.html#use-auto-type-deduction-to-make-code-more-readable).

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


[clang] [Analyzer] Support RefAllowingPartiallyDestroyed and RefPtrAllowingPartiallyDestroyed (PR #82209)

2024-02-20 Thread Artem Dergachev via cfe-commits

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


[clang] [llvm] [MC/DC][Coverage] Loosen the limit of NumConds from 6 (PR #82448)

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

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


[clang] [Driver] Improve error when a compiler-rt library is not found (PR #81037)

2024-02-20 Thread Fangrui Song via cfe-commits

https://github.com/MaskRay updated 
https://github.com/llvm/llvm-project/pull/81037

>From c9dc3ca27e6978a3b6595d094e32cbd9cd102f64 Mon Sep 17 00:00:00 2001
From: Fangrui Song 
Date: Wed, 7 Feb 2024 12:56:05 -0800
Subject: [PATCH] [Driver] Improve error when a compiler-rt library is not
 found

BSD, Linux, and z/OS enable `LLVM_ENABLE_PER_TARGET_RUNTIME_DIR` by default.
When a compiler-rt library is not found, we currently report an
incorrect filename `libclang_rt.XXX-$arch.a`
```
% /tmp/Debug/bin/clang++ a.cc -fsanitize=address -o a
ld.lld: error: cannot open 
/tmp/Debug/lib/clang/19/lib/linux/libclang_rt.asan-x86_64.a: No such file or 
directory
clang++: error: linker command failed with exit code 1 (use -v to see 
invocation)
```

With this change, we will correctly report:
```
% /tmp/Debug/bin/clang++ a.cc -fsanitize=address -o a
ld.lld: error: cannot open 
/tmp/Debug/lib/clang/19/lib/x86_64-unknown-linux-gnu/libclang_rt.asan.a: No 
such file or directory
clang++: error: linker command failed with exit code 1 (use -v to see 
invocation)
```

Link: https://discourse.llvm.org/t/runtime-directory-fallback/76860
---
 clang/lib/Driver/ToolChain.cpp|  18 ++-
 .../libclang_rt.hwasan.a} |   0
 .../libclang_rt.hwasan.a.syms}|   0
 .../libclang_rt.asan.a}   |   0
 .../libclang_rt.asan.a.syms}  |   0
 .../clang_rt.crtbegin.o}  |   0
 .../clang_rt.crtend.o}|   0
 .../clang_rt.crtbegin.o}  |   0
 .../clang_rt.crtend.o}|   0
 .../libclang_rt.asan.a}   |   0
 .../libclang_rt.asan.a.syms}  |   0
 .../libclang_rt.hwasan.a} |   0
 .../libclang_rt.hwasan.a.syms}|   0
 .../x86_64-unknown-linux/libclang_rt.msan.a   |   0
 .../libclang_rt.msan.a.syms   |   0
 .../libclang_rt.msan_cxx.a|   0
 .../libclang_rt.msan_cxx.a.syms   |   0
 .../x86_64-unknown-linux/libclang_rt.tsan.a   |   0
 .../libclang_rt.tsan.a.syms   |   0
 .../libclang_rt.tsan_cxx.a|   0
 .../libclang_rt.tsan_cxx.a.syms   |   0
 clang/test/Driver/arch-specific-libdir.c  |   2 +-
 clang/test/Driver/arm-compiler-rt.c   |   2 +-
 clang/test/Driver/baremetal-sysroot.cpp   |   2 +-
 clang/test/Driver/baremetal.cpp   |  38 +++---
 clang/test/Driver/compiler-rt-unwind.c|   8 +-
 clang/test/Driver/coverage-ld.c   |   4 +-
 clang/test/Driver/fuchsia.c   |   6 +-
 clang/test/Driver/instrprof-ld.c  |  10 +-
 clang/test/Driver/linux-ld.c  |  16 +--
 .../Driver/print-libgcc-file-name-clangrt.c   |   2 +-
 clang/test/Driver/sanitizer-ld.c  | 110 +-
 32 files changed, 114 insertions(+), 104 deletions(-)
 rename 
clang/test/Driver/Inputs/resource_dir/lib/{linux/libclang_rt.asan-i386.a.syms 
=> aarch64-unknown-linux/libclang_rt.hwasan.a} (100%)
 rename 
clang/test/Driver/Inputs/resource_dir/lib/{linux/libclang_rt.asan-x86_64.a.syms 
=> aarch64-unknown-linux/libclang_rt.hwasan.a.syms} (100%)
 rename 
clang/test/Driver/Inputs/resource_dir/lib/{linux/libclang_rt.hwasan-aarch64.a.syms
 => i386-unknown-linux/libclang_rt.asan.a} (100%)
 rename 
clang/test/Driver/Inputs/resource_dir/lib/{linux/libclang_rt.hwasan-x86_64.a.syms
 => i386-unknown-linux/libclang_rt.asan.a.syms} (100%)
 rename 
clang/test/Driver/Inputs/resource_dir/lib/{linux/libclang_rt.msan-x86_64.a.syms 
=> i686-unknown-linux/clang_rt.crtbegin.o} (100%)
 rename 
clang/test/Driver/Inputs/resource_dir/lib/{linux/libclang_rt.msan_cxx-x86_64.a.syms
 => i686-unknown-linux/clang_rt.crtend.o} (100%)
 rename 
clang/test/Driver/Inputs/resource_dir/lib/{linux/libclang_rt.tsan-x86_64.a.syms 
=> x86_64-unknown-linux/clang_rt.crtbegin.o} (100%)
 rename 
clang/test/Driver/Inputs/resource_dir/lib/{linux/libclang_rt.tsan_cxx-x86_64.a.syms
 => x86_64-unknown-linux/clang_rt.crtend.o} (100%)
 rename 
clang/test/Driver/Inputs/resource_dir/lib/{linux/libclang_rt.ubsan-i386.a.syms 
=> x86_64-unknown-linux/libclang_rt.asan.a} (100%)
 rename 
clang/test/Driver/Inputs/resource_dir/lib/{linux/libclang_rt.ubsan-x86_64.a.syms
 => x86_64-unknown-linux/libclang_rt.asan.a.syms} (100%)
 rename 
clang/test/Driver/Inputs/resource_dir/lib/{linux/libclang_rt.ubsan_cxx-i386.a.syms
 => x86_64-unknown-linux/libclang_rt.hwasan.a} (100%)
 rename 
clang/test/Driver/Inputs/resource_dir/lib/{linux/libclang_rt.ubsan_cxx-x86_64.a.syms
 => x86_64-unknown-linux/libclang_rt.hwasan.a.syms} (100%)
 create mode 100644 
clang/test/Driver/Inputs/resource_dir/lib/x86_64-unknown-linux/libclang_rt.msan.a
 create mode 100644 
clang/test/Driver/Inputs/resource_dir/lib/x86_64-unknown-linux/libclang_rt.msan.a.syms
 create mode 100644 
clang/test/Driver/Inputs/resource_dir/lib/x86_64-unknown-linux/libclang_rt.msan_cxx.a
 

[clang] [Driver,BareMetal] Replace -lclang_rt.builtins{,-$arch}.a with an absolute path (PR #82424)

2024-02-20 Thread Fangrui Song via cfe-commits

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


[clang] 4ca0480 - [Driver,BareMetal] Replace -lclang_rt.builtins{,-$arch}.a with an absolute path (#82424)

2024-02-20 Thread via cfe-commits

Author: Fangrui Song
Date: 2024-02-20T16:54:27-08:00
New Revision: 4ca0480a4fefe25c2f6e36c04f02998af79274a0

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

LOG: [Driver,BareMetal] Replace -lclang_rt.builtins{,-$arch}.a with an absolute 
path (#82424)

The generic `tools::AddRunTimeLibs` uses an absolute path. Change
BareMetal to match.

I believe users are not supposed to place other files under the
directory containing `libclang_rt.builtins-$arch.a`. If they rely on the
implicit -L, they now need to explicitly specify -L.

Added: 


Modified: 
clang/lib/Driver/ToolChains/BareMetal.cpp
clang/test/Driver/arm-compiler-rt.c
clang/test/Driver/baremetal-multilib.yaml
clang/test/Driver/baremetal-sysroot.cpp
clang/test/Driver/baremetal.cpp

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/BareMetal.cpp 
b/clang/lib/Driver/ToolChains/BareMetal.cpp
index cd955b6c849456..d5fc1d5dd25a8b 100644
--- a/clang/lib/Driver/ToolChains/BareMetal.cpp
+++ b/clang/lib/Driver/ToolChains/BareMetal.cpp
@@ -368,11 +368,7 @@ void BareMetal::AddLinkRuntimeLib(const ArgList ,
   ToolChain::RuntimeLibType RLT = GetRuntimeLibType(Args);
   switch (RLT) {
   case ToolChain::RLT_CompilerRT: {
-const std::string FileName = getCompilerRT(Args, "builtins");
-llvm::StringRef BaseName = llvm::sys::path::filename(FileName);
-BaseName.consume_front("lib");
-BaseName.consume_back(".a");
-CmdArgs.push_back(Args.MakeArgString("-l" + BaseName));
+CmdArgs.push_back(getCompilerRTArgString(Args, "builtins"));
 return;
   }
   case ToolChain::RLT_Libgcc:
@@ -462,11 +458,6 @@ void baremetal::Linker::ConstructJob(Compilation , const 
JobAction ,
   for (const auto  : TC.getLibraryPaths())
 CmdArgs.push_back(Args.MakeArgString(llvm::Twine("-L", LibPath)));
 
-  const std::string FileName = TC.getCompilerRT(Args, "builtins");
-  llvm::SmallString<128> PathBuf{FileName};
-  llvm::sys::path::remove_filename(PathBuf);
-  CmdArgs.push_back(Args.MakeArgString("-L" + PathBuf));
-
   if (TC.ShouldLinkCXXStdlib(Args))
 TC.AddCXXStdlibLibArgs(Args, CmdArgs);
 

diff  --git a/clang/test/Driver/arm-compiler-rt.c 
b/clang/test/Driver/arm-compiler-rt.c
index 954947bb890f87..adecacbcaabf9c 100644
--- a/clang/test/Driver/arm-compiler-rt.c
+++ b/clang/test/Driver/arm-compiler-rt.c
@@ -3,7 +3,7 @@
 // RUN: -resource-dir=%S/Inputs/resource_dir_with_arch_subdir \
 // RUN: -rtlib=compiler-rt -### %s 2>&1 \
 // RUN:   | FileCheck %s -check-prefix ARM-EABI
-// ARM-EABI: "-lclang_rt.builtins-arm"
+// ARM-EABI: "{{[^"]*}}libclang_rt.builtins-arm.a"
 
 // RUN: %clang -target arm-linux-gnueabi \
 // RUN: --sysroot=%S/Inputs/resource_dir_with_arch_subdir \

diff  --git a/clang/test/Driver/baremetal-multilib.yaml 
b/clang/test/Driver/baremetal-multilib.yaml
index af26e82621c91e..3f026cbeb437b2 100644
--- a/clang/test/Driver/baremetal-multilib.yaml
+++ b/clang/test/Driver/baremetal-multilib.yaml
@@ -17,7 +17,7 @@
 # CHECK-SAME: "-x" "c++" "{{.*}}baremetal-multilib.yaml"
 # CHECK-NEXT: ld{{(.exe)?}}" "{{.*}}.o" "-Bstatic"
 # CHECK-SAME: 
"-L[[SYSROOT]]/bin/../lib/clang-runtimes/arm-none-eabi/thumb/v8-m.main/fp/lib"
-# CHECK-SAME: "-lc" "-lm" "-lclang_rt.builtins"
+# CHECK-SAME: "-lc" "-lm" "{{[^"]*}}libclang_rt.builtins.a"
 # CHECK-SAME: "-o" "{{.*}}.tmp.out"
 
 # RUN: %T/baremetal_multilib/bin/clang -no-canonical-prefixes -x c++ %s -### 
-o %t.out 2>&1 \

diff  --git a/clang/test/Driver/baremetal-sysroot.cpp 
b/clang/test/Driver/baremetal-sysroot.cpp
index fc66020772a771..46338185ffd9d5 100644
--- a/clang/test/Driver/baremetal-sysroot.cpp
+++ b/clang/test/Driver/baremetal-sysroot.cpp
@@ -18,5 +18,5 @@
 // CHECK-V6M-C-SAME: "-x" "c++" "{{.*}}baremetal-sysroot.cpp"
 // CHECK-V6M-C-NEXT: "{{[^"]*}}ld{{(\.(lld|bfd|gold))?}}{{(\.exe)?}}" 
"{{.*}}.o" "-Bstatic"
 // CHECK-V6M-C-SAME: 
"-L{{.*}}/baremetal_default_sysroot{{[/\\]+}}bin{{[/\\]+}}..{{[/\\]+}}lib{{[/\\]+}}clang-runtimes{{[/\\]+}}armv6m-none-eabi{{[/\\]+}}lib"
-// CHECK-V6M-C-SAME: "-lc" "-lm" "-lclang_rt.builtins-armv6m"
+// CHECK-V6M-C-SAME: "-lc" "-lm" "{{[^"]*}}libclang_rt.builtins-armv6m.a"
 // CHECK-V6M-C-SAME: "-o" "{{.*}}.o"

diff  --git a/clang/test/Driver/baremetal.cpp b/clang/test/Driver/baremetal.cpp
index 7511d7d1adb4dd..8baf388894eb27 100644
--- a/clang/test/Driver/baremetal.cpp
+++ b/clang/test/Driver/baremetal.cpp
@@ -18,8 +18,7 @@
 // CHECK-V6M-C-NEXT: ld{{(.exe)?}}" "{{.*}}.o" "-Bstatic" "-EL"
 // CHECK-V6M-C-SAME: "-T" "semihosted.lds" 
"-Lsome{{[/\\]+}}directory{{[/\\]+}}user{{[/\\]+}}asked{{[/\\]+}}for"
 // CHECK-V6M-C-SAME: "-L[[SYSROOT:[^"]+]]{{[/\\]+}}lib"
-// CHECK-V6M-C-SAME: "-L[[RESOURCE_DIR:[^"]+]]{{[/\\]+}}lib{{[/\\]+}}baremetal"
-// CHECK-V6M-C-SAME: "-lc" "-lm" "-lclang_rt.builtins-armv6m" 

[clang] [llvm] [AMDGPU] Emit a waitcnt instruction after each memory instruction (PR #79236)

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

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


[clang] [llvm] [AMDGPU] Emit a waitcnt instruction after each memory instruction (PR #79236)

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


@@ -167,6 +167,10 @@ def FeatureCuMode : SubtargetFeature<"cumode",
   "Enable CU wavefront execution mode"
 >;
 
+def FeaturePreciseMemory

jwanggit86 wrote:

A possible fix is to check `hasFlag` after calling `handleTargetFeaturesGroup`, 
and if the check is true, replace the string `"+amdgpu-precise-memory-op"` in 
the `Features` vector with `"+precise-memory"`, as follows:
```
  handleTargetFeaturesGroup(D, Triple, Args, Features,
options::OPT_m_amdgpu_Features_Group);

  if (Args.hasFlag(options::OPT_mamdgpu_precise_memory_op,
   options::OPT_mno_amdgpu_precise_memory_op, false)) {
for (auto It = Features.begin(); It != Features.end(); ++It) {
  if (*It == "+amdgpu-precise-memory-op")
*It = StringRef("+precise-memory");
}
```
@Pierre-vh Your thoughts?

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


[clang] [llvm] [AMDGPU] Emit a waitcnt instruction after each memory instruction (PR #79236)

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

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


[clang] [llvm] [AMDGPU] Emit a waitcnt instruction after each memory instruction (PR #79236)

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


@@ -167,6 +167,10 @@ def FeatureCuMode : SubtargetFeature<"cumode",
   "Enable CU wavefront execution mode"
 >;
 
+def FeaturePreciseMemory

jwanggit86 wrote:

@Pierre-vh With the suggested change, the func `getAMDGPUTargetFeatures` looks 
something like the following:
```
void amdgpu::getAMDGPUTargetFeatures(...) {
...
  if (Args.hasFlag(options::OPT_mwavefrontsize64,
   options::OPT_mno_wavefrontsize64, false))
Features.push_back("+wavefrontsize64");

  if (Args.hasFlag(options::OPT_mamdgpu_precise_memory_op,
   options::OPT_mno_amdgpu_precise_memory_op, false)) {
Features.push_back("+precise-memory");
  }
  handleTargetFeaturesGroup(D, Triple, Args, Features,
options::OPT_m_amdgpu_Features_Group);
}

However, `handleTargetFeaturesGroup` does not seem to care whether an Arg is 
claimed or not. It will process every Arg, and we end up with the following:
`"-target-feature" "+precise-memory" "-target-feature" 
"+amdgpu-precise-memory-op"`

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


[clang] [llvm] [clang] Use separator for large numeric values in overflow diagnostic (PR #80939)

2024-02-20 Thread Atousa Duprat via cfe-commits

Atousa wrote:

humble ping @AaronBallman 

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


[clang] Sanitizer: Support -fwrapv with -fsanitize=signed-integer-overflow (PR #82432)

2024-02-20 Thread Fangrui Song via cfe-commits

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


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


[clang] [NVPTX] Enable the _Float16 type for NVPTX compilation (PR #82436)

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

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


[clang] 53e9698 - [NVPTX] Enable the _Float16 type for NVPTX compilation (#82436)

2024-02-20 Thread via cfe-commits

Author: Joseph Huber
Date: 2024-02-20T18:12:27-06:00
New Revision: 53e96984b6dbb9d8ff55d2ccd0c27ffc1d27315f

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

LOG: [NVPTX] Enable the _Float16 type for NVPTX compilation (#82436)

Summary:
The PTX target supports the f16 type natively and we alreaqdy have a few
LLVM backend tests that support the LLVM-IR. We should be able to enable
this for generic use. This is done prior the f16 math functions being
written in the GPU libc case.

Added: 


Modified: 
clang/docs/LanguageExtensions.rst
clang/lib/Basic/Targets/NVPTX.cpp
clang/test/SemaCUDA/float16.cu

Removed: 




diff  --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index fb4d7a02dd086f..711baf45f449a0 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -833,6 +833,7 @@ to ``float``; see below for more information on this 
emulation.
   * 32-bit ARM (natively on some architecture versions)
   * 64-bit ARM (AArch64) (natively on ARMv8.2a and above)
   * AMDGPU (natively)
+  * NVPTX (natively)
   * SPIR (natively)
   * X86 (if SSE2 is available; natively if AVX512-FP16 is also available)
   * RISC-V (natively if Zfh or Zhinx is available)

diff  --git a/clang/lib/Basic/Targets/NVPTX.cpp 
b/clang/lib/Basic/Targets/NVPTX.cpp
index a8efae3a1ce388..b47c399fef6042 100644
--- a/clang/lib/Basic/Targets/NVPTX.cpp
+++ b/clang/lib/Basic/Targets/NVPTX.cpp
@@ -61,6 +61,10 @@ NVPTXTargetInfo::NVPTXTargetInfo(const llvm::Triple ,
   NoAsmVariants = true;
   GPU = CudaArch::UNUSED;
 
+  // PTX supports f16 as a fundamental type.
+  HasLegalHalfType = true;
+  HasFloat16 = true;
+
   if (TargetPointerWidth == 32)
 resetDataLayout("e-p:32:32-i64:64-i128:128-v16:16-v32:32-n16:32:64");
   else if (Opts.NVPTXUseShortPointers)

diff  --git a/clang/test/SemaCUDA/float16.cu b/clang/test/SemaCUDA/float16.cu
index a9cbe87f32c100..bb5ed606438491 100644
--- a/clang/test/SemaCUDA/float16.cu
+++ b/clang/test/SemaCUDA/float16.cu
@@ -1,4 +1,5 @@
 // RUN: %clang_cc1 -fsyntax-only -triple x86_64 -aux-triple amdgcn -verify %s
+// RUN: %clang_cc1 -fsyntax-only -triple x86_64 -aux-triple nvptx64 -verify %s
 // expected-no-diagnostics
 #include "Inputs/cuda.h"
 



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


[clang] [NVPTX] Enable the _Float16 type for NVPTX compilation (PR #82436)

2024-02-20 Thread Artem Belevich via cfe-commits

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


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


[clang] [HLSL][Doc] Add doc about expected differences (PR #82395)

2024-02-20 Thread Chris B via cfe-commits

https://github.com/llvm-beanz updated 
https://github.com/llvm/llvm-project/pull/82395

>From 558dd6182a4dc6fc5c5383358cac422289a7a90b Mon Sep 17 00:00:00 2001
From: Chris Bieneman 
Date: Tue, 20 Feb 2024 12:01:16 -0600
Subject: [PATCH 1/5] [HLSL][Doc] Add doc about expected differences

This document covers expected differences between Clang and the HLSL
reference compiler implementations (FXC & DXC). The document is not
intended to be exhaustive, but it should be a best effort to cover known
cases.

This document should document both the behavioral difference and the
explanation of why Clang differs.

The initail document covers known overload resolution differences.
---
 clang/docs/HLSL/ExpectedDifferences.rst | 108 
 clang/docs/HLSL/HLSLDocs.rst|   1 +
 2 files changed, 109 insertions(+)
 create mode 100644 clang/docs/HLSL/ExpectedDifferences.rst

diff --git a/clang/docs/HLSL/ExpectedDifferences.rst 
b/clang/docs/HLSL/ExpectedDifferences.rst
new file mode 100644
index 00..f1d52b52092466
--- /dev/null
+++ b/clang/docs/HLSL/ExpectedDifferences.rst
@@ -0,0 +1,108 @@
+
+Expected Differences vs DXC and FXC
+===
+
+.. contents::
+   :local:
+
+Introduction
+
+
+HLSL currently has two reference compilers, the `DirectX Shader Compiler (DXC)
+`_ and the
+`Effect-Compiler (FXC) 
`_.
+The two reference compilers do not fully agree. Some known disagreements in the
+references are tracked on
+`DXC's GitHub
+`_,
+but many more are known to exist.
+
+HLSL as implemented by Clang will also not fully match either of the reference
+implementations, it is instead being written to match the `draft language
+specification `_.
+
+This document is a non-exhaustive collection the known differences between
+Clang's implementation of HLSL and the existing reference compilers.
+
+General Principles
+--
+
+Most of the intended differences between Clang and the earlier reference
+compilers are focused on increased consistency and correctness. Both reference
+compilers do not always apply language rules the same in all contexts.
+
+Clang also deviates from the reference compilers by providing different
+diagnostics, both in terms of the textual messages and the contexts in which
+diagnostics are produced. While striving for a high level of source
+compatibility with conforming HLSL code, Clang may produce earlier and more
+robust diagnostics for incorrect code or reject code that a reference compiler
+incorrectly accepted.
+
+Language Version
+
+
+Clang targets language compatibility for HLSL 2021 as implemented by DXC.
+Language features that were removed in earlier versions of HLSL may be added on
+a case-by-case basis, but are not planned for the initial implementation.
+
+Overload Resolution
+===
+
+Clang's HLSL implementation adopts C++ overload resolution rules as proposed 
for
+HLSL 202x based on proposal
+`0007 
`_
+and
+`0008 
`_.
+
+Clang's implementation extends standard overload resolution rules to HLSL
+library functionality. This causes subtle changes in overload resolution
+behavior between Clang and DXC. Some examples include:
+
+.. code-block:: c++
+
+  void halfOrInt16(half H);
+  void halfOrInt16(uint16_t I);
+
+  void takesDoubles(double, double, double);
+
+  cbuffer CB {
+uint U;
+uint I;
+float X, Y, Z;
+double3 A, B;
+  }
+
+  export void call() {
+halfOrInt16(U); // All: Resolves to halfOrInt16(uint16_t).
+halfOrInt16(I); // All: Resolves to halfOrInt16(uint16_t).
+  #ifndef IGNORE_ERRORS
+half H = asfloat16(I); // DXC: Fails to resolve overload for int.
+  // Clang: Resolves to halfOrInt16(uint16_t).
+half H = asfloat16(U); // DXC: Fails to resolve overload for int.
+  // Clang: Resolves to halfOrInt16(uint16_t).
+  #endif
+half H = asfloat16(0x01); // DXC: Resolves to halfOrInt16(half).
+  // Clang: Resolves to halfOrInt16(uint16_t).
+
+takesDoubles(X, Y, Z); // Works on all compilers
+  #ifndef IGNORE_ERRORS
+fma(X, Y, Z); // DXC: Fails to resolve no known conversion from float to 
double.
+  // Clang: Resolces to fma(double,double,double).
+  #endif
+
+double D = dot(A, B); // DXC: Resolves to dot(double3, double3), fails 
DXIL Validation.
+  // FXC: Expands to compute double dot product with 
fmul/fadd
+  // 

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

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

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


[clang] [alpha.webkit.UncountedCallArgsChecker] Ignore calls to WTF's container methods (PR #82156)

2024-02-20 Thread Artem Dergachev via cfe-commits

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

Ooo this is much cleaner!

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


[clang] Sanitizer: Support -fwrapv with -fsanitize=signed-integer-overflow (PR #82432)

2024-02-20 Thread Justin Stitt via cfe-commits

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


[clang] Sanitizer: Support -fwrapv with -fsanitize=signed-integer-overflow (PR #82432)

2024-02-20 Thread Justin Stitt via cfe-commits


@@ -70,6 +77,7 @@ void test1(void) {
   // WRAPV: add i8 {{.*}}, 1

JustinStitt wrote:

How's 
[1d9cb0a](https://github.com/llvm/llvm-project/pull/82432/commits/1d9cb0aca8985aa1636780b3ff9a863962cc2d57)
 look?

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


[clang] Sanitizer: Support -fwrapv with -fsanitize=signed-integer-overflow (PR #82432)

2024-02-20 Thread Justin Stitt via cfe-commits

https://github.com/JustinStitt updated 
https://github.com/llvm/llvm-project/pull/82432

>From b02b09b9eb4f9a8ac60dd077d95c67b959db3b70 Mon Sep 17 00:00:00 2001
From: Justin Stitt 
Date: Tue, 20 Feb 2024 22:21:02 +
Subject: [PATCH 1/4] support fwrapv with signed int overflow sanitizer

---
 clang/docs/ReleaseNotes.rst   |  3 +++
 clang/docs/UndefinedBehaviorSanitizer.rst |  9 +
 clang/lib/CodeGen/CGExprScalar.cpp| 16 
 clang/test/CodeGen/integer-overflow.c | 12 
 4 files changed, 32 insertions(+), 8 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 5bca2c965c866b..685b19cabeb82c 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -399,6 +399,9 @@ Moved checkers
 Sanitizers
 --
 
+- ``-fsanitize=signed-integer-overflow`` now instruments signed arithmetic even
+  when ``-fwrapv`` is enabled. Previously, only division checks were enabled.
+
 Python Binding Changes
 --
 
diff --git a/clang/docs/UndefinedBehaviorSanitizer.rst 
b/clang/docs/UndefinedBehaviorSanitizer.rst
index b8ad3804f18903..8f58c92bd2a163 100644
--- a/clang/docs/UndefinedBehaviorSanitizer.rst
+++ b/clang/docs/UndefinedBehaviorSanitizer.rst
@@ -190,10 +190,11 @@ Available checks are:
   -  ``-fsanitize=signed-integer-overflow``: Signed integer overflow, where the
  result of a signed integer computation cannot be represented in its type.
  This includes all the checks covered by ``-ftrapv``, as well as checks for
- signed division overflow (``INT_MIN/-1``), but not checks for
- lossy implicit conversions performed before the computation
- (see ``-fsanitize=implicit-conversion``). Both of these two issues are
- handled by ``-fsanitize=implicit-conversion`` group of checks.
+ signed division overflow (``INT_MIN/-1``). Note that checks are still
+ added even when ``-fwrapv`` is enabled. This sanitizer does not check for
+ lossy implicit conversions performed before the computation (see
+ ``-fsanitize=implicit-conversion``). Both of these two issues are handled
+ by ``-fsanitize=implicit-conversion`` group of checks.
   -  ``-fsanitize=unreachable``: If control flow reaches an unreachable
  program point.
   -  ``-fsanitize=unsigned-integer-overflow``: Unsigned integer overflow, where
diff --git a/clang/lib/CodeGen/CGExprScalar.cpp 
b/clang/lib/CodeGen/CGExprScalar.cpp
index 576734e460b9c1..7621d9bcdec991 100644
--- a/clang/lib/CodeGen/CGExprScalar.cpp
+++ b/clang/lib/CodeGen/CGExprScalar.cpp
@@ -723,7 +723,9 @@ class ScalarExprEmitter
 if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
   switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
   case LangOptions::SOB_Defined:
-return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
+if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
+  return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
+[[fallthrough]];
   case LangOptions::SOB_Undefined:
 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
   return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
@@ -2568,7 +2570,9 @@ llvm::Value 
*ScalarExprEmitter::EmitIncDecConsiderOverflowBehavior(
   StringRef Name = IsInc ? "inc" : "dec";
   switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
   case LangOptions::SOB_Defined:
-return Builder.CreateAdd(InVal, Amount, Name);
+if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
+return Builder.CreateAdd(InVal, Amount, Name);
+[[fallthrough]];
   case LangOptions::SOB_Undefined:
 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
   return Builder.CreateNSWAdd(InVal, Amount, Name);
@@ -3913,7 +3917,9 @@ Value *ScalarExprEmitter::EmitAdd(const BinOpInfo ) {
   if (op.Ty->isSignedIntegerOrEnumerationType()) {
 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
 case LangOptions::SOB_Defined:
-  return Builder.CreateAdd(op.LHS, op.RHS, "add");
+  if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
+return Builder.CreateAdd(op.LHS, op.RHS, "add");
+  [[fallthrough]];
 case LangOptions::SOB_Undefined:
   if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
@@ -4067,7 +4073,9 @@ Value *ScalarExprEmitter::EmitSub(const BinOpInfo ) {
 if (op.Ty->isSignedIntegerOrEnumerationType()) {
   switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
   case LangOptions::SOB_Defined:
-return Builder.CreateSub(op.LHS, op.RHS, "sub");
+if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
+  return Builder.CreateSub(op.LHS, op.RHS, "sub");
+[[fallthrough]];
   case LangOptions::SOB_Undefined:
 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
   return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
diff 

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

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


@@ -886,28 +886,16 @@ llvm::ARM::FPUKind arm::getARMTargetFeatures(const Driver 
,
   } else {
 // Assume pre-ARMv6 doesn't support unaligned accesses.
 //
-// ARMv6 may or may not support unaligned accesses depending on the
-// SCTLR.U bit, which is architecture-specific. We assume ARMv6
-// Darwin and NetBSD targets support unaligned accesses, and others don't.
+// Assume ARMv6+ supports unaligned accesses, except Armv6-M, and Armv8-M
+// without the Main Extension. This aligns with the default behavior of
+// ARM's downstream versions of GCC and Clang
 //
-// ARMv7 always has SCTLR.U set to 1, but it has a new SCTLR.A bit
-// which raises an alignment fault on unaligned accesses. Linux
-// defaults this bit to 0 and handles it as a system-wide (not
-// per-process) setting. It is therefore safe to assume that ARMv7+
-// Linux targets support unaligned accesses. The same goes for NaCl
-// and Windows.
-//
-// The above behavior is consistent with GCC.
+// Users can disable behavior via -mno-unaliged-access.
 int VersionNum = getARMSubArchVersionNumber(Triple);
-if (Triple.isOSDarwin() || Triple.isOSNetBSD()) {
-  if (VersionNum < 6 ||
-  Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
-Features.push_back("+strict-align");
-} else if (Triple.isOSLinux() || Triple.isOSNaCl() ||
-   Triple.isOSWindows()) {
-  if (VersionNum < 7)
-Features.push_back("+strict-align");
-} else
+if (VersionNum < 6 ||
+Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m ||
+Triple.getSubArch() ==
+llvm::Triple::SubArchType::ARMSubArch_v8m_baseline)

ilovepi wrote:

@efriedma-quic I'm not too sure what the correct check would be here given your 
comment. Maybe this? 

```cpp
if (Triple.isOSDarwin() || Triple.isOSNetBSD()) {
  if (VersionNum < 6 ||
  Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
Features.push_back("+strict-align");
} else if (VersionNum < 7 ||
Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m ||
Triple.getSubArch() ==
llvm::Triple::SubArchType::ARMSubArch_v8m_baseline)
Features.push_back("+strict-align");
} 
```

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


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

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


@@ -305,6 +305,16 @@ X86 Support
 Arm and AArch64 Support
 ^^^
 
+- ARMv6+ targets now default to allowing unaligned access, except Armv6-M, and
+  Armv8-M without the Main Extension. Baremetal targets should check that the
+  new default will work with their system configurations, since it requires
+  that SCTLR.A is 0, SCTLR.U is 1, and that the memory in question is
+  configured as "normal" memory. We've made the value judgment that the
+  performance gains here outweigh breakages, since it is difficult to identify
+  performance loss from disabling unaligned access, but incorrect enabling
+  unaligned access will generate an obvious alignment fault on ARMv7+. This is
+  also the default setting for ARM's downstream compilers.
+

ilovepi wrote:

@efriedma-quic @davemgreen Is this more in line with what you would expect in 
the release notes?

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


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

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

https://github.com/ilovepi updated 
https://github.com/llvm/llvm-project/pull/82400

>From 20634c2f54ae667ee8374d12e58e582aa6cdd051 Mon Sep 17 00:00:00 2001
From: Paul Kirth 
Date: Tue, 20 Feb 2024 10:34:57 -0800
Subject: [PATCH 1/4] =?UTF-8?q?[=F0=9D=98=80=F0=9D=97=BD=F0=9D=97=BF]=20in?=
 =?UTF-8?q?itial=20version?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Created using spr 1.3.4
---
 clang/lib/Driver/ToolChains/Arch/ARM.cpp | 14 ++
 clang/test/Driver/arm-alignment.c|  8 
 2 files changed, 14 insertions(+), 8 deletions(-)

diff --git a/clang/lib/Driver/ToolChains/Arch/ARM.cpp 
b/clang/lib/Driver/ToolChains/Arch/ARM.cpp
index e6ee2f88a84edf..3bf6056f0c3ecc 100644
--- a/clang/lib/Driver/ToolChains/Arch/ARM.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/ARM.cpp
@@ -895,20 +895,18 @@ llvm::ARM::FPUKind arm::getARMTargetFeatures(const Driver 
,
 // defaults this bit to 0 and handles it as a system-wide (not
 // per-process) setting. It is therefore safe to assume that ARMv7+
 // Linux targets support unaligned accesses. The same goes for NaCl
-// and Windows.
-//
-// The above behavior is consistent with GCC.
+// and Windows. However, ARM's forks of GCC and Clang both allow
+// unaligned accesses by default for all targets. We follow this
+// behavior and enable unaligned accesses by default for ARMv7+ targets.
+// Users can disable behavior via compiler options (-mno-unaliged-access).
+// See https://github.com/llvm/llvm-project/issues/59560 for more info.
 int VersionNum = getARMSubArchVersionNumber(Triple);
 if (Triple.isOSDarwin() || Triple.isOSNetBSD()) {
   if (VersionNum < 6 ||
   Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
 Features.push_back("+strict-align");
-} else if (Triple.isOSLinux() || Triple.isOSNaCl() ||
-   Triple.isOSWindows()) {
-  if (VersionNum < 7)
+} else if (VersionNum < 7)
 Features.push_back("+strict-align");
-} else
-  Features.push_back("+strict-align");
   }
 
   // llvm does not support reserving registers in general. There is support
diff --git a/clang/test/Driver/arm-alignment.c 
b/clang/test/Driver/arm-alignment.c
index 9177b625729b85..6d0084451e82c7 100644
--- a/clang/test/Driver/arm-alignment.c
+++ b/clang/test/Driver/arm-alignment.c
@@ -22,6 +22,14 @@
 // RUN: %clang -target armv7-windows -### %s 2> %t
 // RUN: FileCheck --check-prefix=CHECK-UNALIGNED-ARM < %t %s
 
+/// Ensure that by default before ARMv7 we default to +strict-align
+// RUN: %clang -target armv6 -### %s 2> %t
+// RUN: FileCheck --check-prefix=CHECK-ALIGNED-ARM < %t %s
+
+/// After ARMv7 by default we allow unaligned accesses for all targets
+// RUN: %clang -target armv7 -### %s 2> %t
+// RUN: FileCheck --check-prefix=CHECK-UNALIGNED-ARM < %t %s
+
 // RUN: %clang --target=aarch64 -munaligned-access -### %s 2> %t
 // RUN: FileCheck --check-prefix=CHECK-UNALIGNED-AARCH64 < %t %s
 

>From a078e658bdcd851d87331ecf87224dc2ddb13c69 Mon Sep 17 00:00:00 2001
From: Paul Kirth 
Date: Tue, 20 Feb 2024 10:38:50 -0800
Subject: [PATCH 2/4] git clang-format

Created using spr 1.3.4
---
 clang/lib/Driver/ToolChains/Arch/ARM.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/Driver/ToolChains/Arch/ARM.cpp 
b/clang/lib/Driver/ToolChains/Arch/ARM.cpp
index 3bf6056f0c3ecc..a1aea397925931 100644
--- a/clang/lib/Driver/ToolChains/Arch/ARM.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/ARM.cpp
@@ -906,7 +906,7 @@ llvm::ARM::FPUKind arm::getARMTargetFeatures(const Driver 
,
   Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
 Features.push_back("+strict-align");
 } else if (VersionNum < 7)
-Features.push_back("+strict-align");
+  Features.push_back("+strict-align");
   }
 
   // llvm does not support reserving registers in general. There is support

>From c21f9aa16bb4d081f41a108171e88ecac2bf2884 Mon Sep 17 00:00:00 2001
From: Paul Kirth 
Date: Tue, 20 Feb 2024 12:05:48 -0800
Subject: [PATCH 3/4] Address comments, and update checking

Created using spr 1.3.4
---
 clang/docs/ReleaseNotes.rst  |  2 ++
 clang/lib/Driver/ToolChains/Arch/ARM.cpp | 26 
 clang/test/Driver/arm-alignment.c| 12 +--
 3 files changed, 15 insertions(+), 25 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 762e8133f5d536..6a4182474b3345 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -304,6 +304,8 @@ X86 Support
 
 Arm and AArch64 Support
 ^^^
+- ARMv6+ targets now default to allowing unaligned access, except Armv6-M, and
+  Armv8-M without the Main Extension.
 
 Android Support
 ^^^
diff --git a/clang/lib/Driver/ToolChains/Arch/ARM.cpp 
b/clang/lib/Driver/ToolChains/Arch/ARM.cpp
index a1aea397925931..8f37895eaee242 100644
--- 

[clang] [HLSL][Doc] Add doc about expected differences (PR #82395)

2024-02-20 Thread Damyan Pepper via cfe-commits

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


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


[clang] [clang][ScanDeps] Canonicalize -D and -U flags (PR #82298)

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

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


[clang] 3ff8055 - [clang][ScanDeps] Canonicalize -D and -U flags (#82298)

2024-02-20 Thread via cfe-commits

Author: Michael Spencer
Date: 2024-02-20T15:20:40-08:00
New Revision: 3ff805540173b83d73b673b39ac5760fc19bac15

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

LOG: [clang][ScanDeps] Canonicalize -D and -U flags (#82298)

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

This optimization will only fire if all `-D` and `-U` flags start with a
simple identifier that we can guarantee a simple analysis of can
determine if two flags refer to the same identifier or not. See the
comment on `getSimpleMacroName()` for details of what the issues are.

Added: 
clang/test/ClangScanDeps/optimize-canonicalize-macros.m

Modified: 
clang/include/clang/Tooling/DependencyScanning/DependencyScanningService.h
clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
clang/tools/clang-scan-deps/ClangScanDeps.cpp

Removed: 




diff  --git 
a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningService.h 
b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningService.h
index 4f9867262a275c..557f0e547ab4a8 100644
--- a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningService.h
+++ b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningService.h
@@ -60,7 +60,10 @@ enum class ScanningOptimizations {
   /// Remove unused -ivfsoverlay arguments.
   VFS = 4,
 
-  DSS_LAST_BITMASK_ENUM(VFS),
+  /// Canonicalize -D and -U options.
+  Macros = 8,
+
+  DSS_LAST_BITMASK_ENUM(Macros),
   Default = All
 };
 

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

[clang] [clang][ScanDeps] Canonicalize -D and -U flags (PR #82298)

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

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

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

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

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

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

[clang] Sanitizer: Support -fwrapv with -fsanitize=signed-integer-overflow (PR #82432)

2024-02-20 Thread Fangrui Song via cfe-commits


@@ -70,6 +77,7 @@ void test1(void) {
   // WRAPV: add i8 {{.*}}, 1

MaskRay wrote:

L72 needs a `// CATCH_WRAP: getelementptr i32, ptr`

Actually, since -fsanitize=signed-integer-overflow and -fwrapv 
-fsanitize=signed-integer-overflow share so many checks. Perhaps share the 
check prefixes?

```
--check-prefixes=CATCH_UB,CATCH_UB_POINTER
--check-prefixes=CATCH_UB,NOCATCH_UB_POINTER
```

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


[clang-tools-extra] [clangd] Fix renaming single argument ObjC methods (PR #82396)

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

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

Thanks for fixing!

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


[clang] [attributes][analyzer] Generalize [[clang::suppress]] to declarations. (PR #80371)

2024-02-20 Thread Erich Keane via cfe-commits

erichkeane wrote:

> Ok gotcha thanks! In any case, I'll do my best to handle this more gracefully 
> in the future. Your advice is always appreciated!

Perfect!  I'll try to be better about this in the future as well.

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


  1   2   3   4   5   >