[clang] [clang] Update -Wformat warnings for fixed-point format specifiers (PR #82855)

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

MaskRay wrote:

Do you know a libc implementation that actually implements `%k` `%r` and who 
are the potential users? From a quick glance, gcc avr supports fixed-point 
types but avr-libc doesn't seem to support %k %r.

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


[clang] [Clang][Sema] Fix incorrect rejection default construction of union with nontrivial member (PR #82407)

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

https://github.com/shafik updated 
https://github.com/llvm/llvm-project/pull/82407

>From 5fcaeaddccc0f7e370bf7bebce113d8d52e1b1bd Mon Sep 17 00:00:00 2001
From: Shafik Yaghmour 
Date: Tue, 20 Feb 2024 11:22:39 -0800
Subject: [PATCH] [Clang][Sema] Fix incorrect rejection default construction of
 union with nontrivial member

In 765d8a192180f8f33618087b15c022fe758044af we impelemented a fix for incorrect 
deletion of
default constructors in unions. This fix missed a case and so this PR will
extend the fix to cover the additional case.

Fixes: https://github.com/llvm/llvm-project/issues/81774
---
 clang/docs/ReleaseNotes.rst|  3 +++
 clang/lib/Sema/SemaDeclCXX.cpp | 18 +++---
 .../test/CodeGen/union-non-trivial-member.cpp  | 17 +
 clang/test/SemaCXX/cxx0x-nontrivial-union.cpp  | 11 +++
 4 files changed, 46 insertions(+), 3 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 5bca2c965c866b..452382eb6c4a1e 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -292,6 +292,9 @@ Bug Fixes to C++ Support
   was only accepted at namespace scope but not at local function scope.
 - Clang no longer tries to call consteval constructors at runtime when they 
appear in a member initializer.
   (`#782154 `_`)
+- Fix for clang incorrectly rejecting the default construction of a union with
+  nontrivial member when another member has an initializer.
+  (`#81774 `_)
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 79263bc3ff671d..25a4b4381ca25e 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -9442,9 +9442,21 @@ bool 
SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
 
   int DiagKind = -1;
 
-  if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
-DiagKind = !Decl ? 0 : 1;
-  else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
+  if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) {
+if (CSM == Sema::CXXDefaultConstructor && Field &&
+Field->getParent()->isUnion()) {
+  // [class.default.ctor]p2:
+  //   A defaulted default constructor for class X is defined as deleted if
+  //   - X is a union that has a variant member with a non-trivial default
+  // constructor and no variant member of X has a default member
+  // initializer
+  const auto *RD = cast(Field->getParent());
+  if (!RD->hasInClassInitializer())
+DiagKind = !Decl ? 0 : 1;
+} else {
+  DiagKind = !Decl ? 0 : 1;
+}
+  } else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
 DiagKind = 2;
   else if (!isAccessible(Subobj, Decl))
 DiagKind = 3;
diff --git a/clang/test/CodeGen/union-non-trivial-member.cpp 
b/clang/test/CodeGen/union-non-trivial-member.cpp
index fdc9fd16911e14..8b055a9970fc75 100644
--- a/clang/test/CodeGen/union-non-trivial-member.cpp
+++ b/clang/test/CodeGen/union-non-trivial-member.cpp
@@ -15,14 +15,25 @@ union UnionNonTrivial {
 non_trivial_constructor b{};
 };
 
+struct Handle {
+Handle(int) {}
+};
+
+union UnionNonTrivialEqualInit {
+int NoState = 0;
+Handle CustomState;
+};
+
 void f() {
 UnionInt u1;
 UnionNonTrivial u2;
+UnionNonTrivialEqualInit u3;
 }
 
 // CHECK:  define dso_local void @_Z1fv()
 // CHECK:call void @_ZN8UnionIntC1Ev
 // CHECK-NEXT:   call void @_ZN15UnionNonTrivialC1Ev
+// CHECK-NEXT:   call void @_ZN24UnionNonTrivialEqualInitC1Ev
 
 // CHECK:  define {{.*}}void @_ZN8UnionIntC1Ev
 // CHECK:call void @_ZN8UnionIntC2Ev
@@ -30,8 +41,14 @@ void f() {
 // CHECK:  define {{.*}}void @_ZN15UnionNonTrivialC1Ev
 // CHECK:call void @_ZN15UnionNonTrivialC2Ev
 
+// CHECK:  define {{.*}}void @_ZN24UnionNonTrivialEqualInitC1Ev
+// CHECK:call void @_ZN24UnionNonTrivialEqualInitC2Ev
+
 // CHECK:  define {{.*}}void @_ZN8UnionIntC2Ev
 // CHECK:store i32 1000
 
 // CHECK:  define {{.*}}void @_ZN15UnionNonTrivialC2Ev
 // CHECK:call void @_ZN23non_trivial_constructorC1Ev
+
+// CHECK:  define {{.*}}void @_ZN24UnionNonTrivialEqualInitC2Ev
+// CHECK:store i32 0
diff --git a/clang/test/SemaCXX/cxx0x-nontrivial-union.cpp 
b/clang/test/SemaCXX/cxx0x-nontrivial-union.cpp
index c7cdf76d850dbe..833642b3d739ab 100644
--- a/clang/test/SemaCXX/cxx0x-nontrivial-union.cpp
+++ b/clang/test/SemaCXX/cxx0x-nontrivial-union.cpp
@@ -188,3 +188,14 @@ static_assert(U2().b.x == 100, "");
 static_assert(U3().b.x == 100, "");
 
 } // namespace GH48416
+
+namespace GH81774 {
+struct Handle {
+Handle(int) {}
+};
+// Should be well-formed because NoState has a brace-or-equal-initializer.
+union a {
+int NoState = 0;
+ 

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

2024-02-23 Thread via cfe-commits

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


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

2024-02-23 Thread via cfe-commits

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

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

These keep tripping up the build bots for clang and preventing libc++ tests 
from proceeding.
---
 clang/docs/HLSL/ExpectedDifferences.rst | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

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

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


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

2024-02-23 Thread via cfe-commits

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


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

2024-02-23 Thread via cfe-commits

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

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

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

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

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


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

2024-02-23 Thread via cfe-commits

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


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

2024-02-23 Thread via cfe-commits

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

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

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

diff --git a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m 
b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
index 788b3220af3067..c4bb1ebc9a80be 100644
--- a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
+++ b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
@@ -1,6 +1,13 @@
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 -emit-llvm %s -o - | 
FileCheck %s
 
 // CHECK: @"OBJC_IVAR_$_StaticLayout.static_layout_ivar" = hidden constant i64 
20
+// CHECK: @"OBJC_IVAR_$_SuperClass.superClassIvar" = hidden constant i64 20
+// CHECK: @"OBJC_IVAR_$_SuperClass._superClassProperty" = hidden constant i64 
24
+// CHECK: @"OBJC_IVAR_$_IntermediateClass.intermediateClassIvar" = global i64 
32
+// CHECK: @"OBJC_IVAR_$_IntermediateClass.intermediateClassIvar2" = global i64 
40
+// CHECK: @"OBJC_IVAR_$_IntermediateClass._intermediateProperty" = hidden 
global i64 48
+// CHECK: @"OBJC_IVAR_$_SubClass.subClassIvar" = global i64 56
+// CHECK: @"OBJC_IVAR_$_SubClass._subClassProperty" = hidden global i64 64
 // CHECK: @"OBJC_IVAR_$_NotStaticLayout.not_static_layout_ivar" = hidden 
global i64 12
 
 @interface NSObject {
@@ -20,6 +27,95 @@ -(void)meth {
 }
 @end
 
+// Ivars declared in the @interface
+@interface SuperClass : NSObject
+@property (nonatomic, assign) int superClassProperty;
+@end
+
+@implementation SuperClass {
+  int superClassIvar; // Declare an ivar
+}
+
+// CHECK-LABEL: define internal void @"\01-[SuperClass superClassMethod]"
+- (void)superClassMethod {
+_superClassProperty = 42;
+superClassIvar = 10;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SuperClass
+// CHECK: getelementptr inbounds i8, ptr %1, i64 20
+}
+
+// implicitly synthesized method here
+// CHECK-LABEL: define internal i32 @"\01-[SuperClass superClassProperty]"
+// CHECK: getelementptr inbounds i8, ptr %0, i64 24
+
+// CHECK-LABEL: define internal void @"\01-[SuperClass setSuperClassProperty:]"
+// CHECK: getelementptr inbounds i8, ptr %1, i64 24
+@end
+
+// Inheritance and Ivars
+@interface IntermediateClass : SuperClass
+{
+double intermediateClassIvar;
+
+@protected
+int intermediateClassIvar2;
+}
+@property (nonatomic, strong) SuperClass *intermediateProperty;
+@end
+
+@implementation IntermediateClass
+@synthesize intermediateProperty = _intermediateProperty;
+- (void)intermediateClassMethod {
+intermediateClassIvar = 3.14;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_IntermediateClass
+// CHECK: getelementptr inbounds i8, ptr %0, i64 %ivar
+}
+
+// CHECK-LABEL: define internal void @"\01-[IntermediateClass 
intermediateClassPropertyMethod]"
+- (void)intermediateClassPropertyMethod {
+self.intermediateProperty = 0;
+// CHECK: load ptr, ptr @OBJC_SELECTOR_REFERENCES_
+// CHECK: call void @objc_msgSend(ptr noundef %0, ptr noundef %1, ptr 
noundef null)
+}
+
+// CHECK-LABEL: define internal void @"\01-[IntermediateClass 
intermediateClassPropertyMethodDirect]"
+- (void)intermediateClassPropertyMethodDirect {
+_intermediateProperty = 0;
+// CHECK: load i64, ptr 
@"OBJC_IVAR_$_IntermediateClass._intermediateProperty"
+}
+@end
+
+@interface SubClass : IntermediateClass
+{
+double subClassIvar;
+}
+@property (nonatomic, assign) SubClass *subClassProperty;
+@end
+
+@implementation SubClass
+// CHECK-LABEL: define internal void @"\01-[SubClass subclassVar]"
+- (void)subclassVar {
+
+subClassIvar = 6.28;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SubClass
+// CHECK: getelementptr inbounds i8, ptr %0, i64 %ivar
+}
+
+// CHECK-LABEL: define internal void @"\01-[SubClass intermediateSubclassVar]"
+-(void)intermediateSubclassVar {
+intermediateClassIvar = 3.14;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_IntermediateClass
+// CHECK: getelementptr inbounds i8, ptr %0, i64 %ivar
+}
+
+// implicit synthesized method here:
+// CHECK-LABEL: define internal ptr @"\01-[SubClass subClassProperty]"
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SubClass._subClassProperty"
+
+// CHECK-LABEL: define internal void @"\01-[SubClass setSubClassProperty:]"
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SubClass._subClassProperty"
+@end
+
 @interface NotNSObject {
   int these, might, change;
 }

>From 728e60a38824fd23aa63bda7e853677084f55c36 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 is statically known

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

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

2024-02-23 Thread via cfe-commits

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


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

2024-02-23 Thread via cfe-commits

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

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

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

diff --git a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m 
b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
index 788b3220af3067..c4bb1ebc9a80be 100644
--- a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
+++ b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
@@ -1,6 +1,13 @@
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 -emit-llvm %s -o - | 
FileCheck %s
 
 // CHECK: @"OBJC_IVAR_$_StaticLayout.static_layout_ivar" = hidden constant i64 
20
+// CHECK: @"OBJC_IVAR_$_SuperClass.superClassIvar" = hidden constant i64 20
+// CHECK: @"OBJC_IVAR_$_SuperClass._superClassProperty" = hidden constant i64 
24
+// CHECK: @"OBJC_IVAR_$_IntermediateClass.intermediateClassIvar" = global i64 
32
+// CHECK: @"OBJC_IVAR_$_IntermediateClass.intermediateClassIvar2" = global i64 
40
+// CHECK: @"OBJC_IVAR_$_IntermediateClass._intermediateProperty" = hidden 
global i64 48
+// CHECK: @"OBJC_IVAR_$_SubClass.subClassIvar" = global i64 56
+// CHECK: @"OBJC_IVAR_$_SubClass._subClassProperty" = hidden global i64 64
 // CHECK: @"OBJC_IVAR_$_NotStaticLayout.not_static_layout_ivar" = hidden 
global i64 12
 
 @interface NSObject {
@@ -20,6 +27,95 @@ -(void)meth {
 }
 @end
 
+// Ivars declared in the @interface
+@interface SuperClass : NSObject
+@property (nonatomic, assign) int superClassProperty;
+@end
+
+@implementation SuperClass {
+  int superClassIvar; // Declare an ivar
+}
+
+// CHECK-LABEL: define internal void @"\01-[SuperClass superClassMethod]"
+- (void)superClassMethod {
+_superClassProperty = 42;
+superClassIvar = 10;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SuperClass
+// CHECK: getelementptr inbounds i8, ptr %1, i64 20
+}
+
+// implicitly synthesized method here
+// CHECK-LABEL: define internal i32 @"\01-[SuperClass superClassProperty]"
+// CHECK: getelementptr inbounds i8, ptr %0, i64 24
+
+// CHECK-LABEL: define internal void @"\01-[SuperClass setSuperClassProperty:]"
+// CHECK: getelementptr inbounds i8, ptr %1, i64 24
+@end
+
+// Inheritance and Ivars
+@interface IntermediateClass : SuperClass
+{
+double intermediateClassIvar;
+
+@protected
+int intermediateClassIvar2;
+}
+@property (nonatomic, strong) SuperClass *intermediateProperty;
+@end
+
+@implementation IntermediateClass
+@synthesize intermediateProperty = _intermediateProperty;
+- (void)intermediateClassMethod {
+intermediateClassIvar = 3.14;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_IntermediateClass
+// CHECK: getelementptr inbounds i8, ptr %0, i64 %ivar
+}
+
+// CHECK-LABEL: define internal void @"\01-[IntermediateClass 
intermediateClassPropertyMethod]"
+- (void)intermediateClassPropertyMethod {
+self.intermediateProperty = 0;
+// CHECK: load ptr, ptr @OBJC_SELECTOR_REFERENCES_
+// CHECK: call void @objc_msgSend(ptr noundef %0, ptr noundef %1, ptr 
noundef null)
+}
+
+// CHECK-LABEL: define internal void @"\01-[IntermediateClass 
intermediateClassPropertyMethodDirect]"
+- (void)intermediateClassPropertyMethodDirect {
+_intermediateProperty = 0;
+// CHECK: load i64, ptr 
@"OBJC_IVAR_$_IntermediateClass._intermediateProperty"
+}
+@end
+
+@interface SubClass : IntermediateClass
+{
+double subClassIvar;
+}
+@property (nonatomic, assign) SubClass *subClassProperty;
+@end
+
+@implementation SubClass
+// CHECK-LABEL: define internal void @"\01-[SubClass subclassVar]"
+- (void)subclassVar {
+
+subClassIvar = 6.28;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SubClass
+// CHECK: getelementptr inbounds i8, ptr %0, i64 %ivar
+}
+
+// CHECK-LABEL: define internal void @"\01-[SubClass intermediateSubclassVar]"
+-(void)intermediateSubclassVar {
+intermediateClassIvar = 3.14;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_IntermediateClass
+// CHECK: getelementptr inbounds i8, ptr %0, i64 %ivar
+}
+
+// implicit synthesized method here:
+// CHECK-LABEL: define internal ptr @"\01-[SubClass subClassProperty]"
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SubClass._subClassProperty"
+
+// CHECK-LABEL: define internal void @"\01-[SubClass setSubClassProperty:]"
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SubClass._subClassProperty"
+@end
+
 @interface NotNSObject {
   int these, might, change;
 }

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

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

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

2024-02-23 Thread via cfe-commits

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

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

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

diff --git a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m 
b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
index 788b3220af3067..c4bb1ebc9a80be 100644
--- a/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
+++ b/clang/test/CodeGenObjC/constant-non-fragile-ivar-offset.m
@@ -1,6 +1,13 @@
 // RUN: %clang_cc1 -triple x86_64-apple-macosx10.14.0 -emit-llvm %s -o - | 
FileCheck %s
 
 // CHECK: @"OBJC_IVAR_$_StaticLayout.static_layout_ivar" = hidden constant i64 
20
+// CHECK: @"OBJC_IVAR_$_SuperClass.superClassIvar" = hidden constant i64 20
+// CHECK: @"OBJC_IVAR_$_SuperClass._superClassProperty" = hidden constant i64 
24
+// CHECK: @"OBJC_IVAR_$_IntermediateClass.intermediateClassIvar" = global i64 
32
+// CHECK: @"OBJC_IVAR_$_IntermediateClass.intermediateClassIvar2" = global i64 
40
+// CHECK: @"OBJC_IVAR_$_IntermediateClass._intermediateProperty" = hidden 
global i64 48
+// CHECK: @"OBJC_IVAR_$_SubClass.subClassIvar" = global i64 56
+// CHECK: @"OBJC_IVAR_$_SubClass._subClassProperty" = hidden global i64 64
 // CHECK: @"OBJC_IVAR_$_NotStaticLayout.not_static_layout_ivar" = hidden 
global i64 12
 
 @interface NSObject {
@@ -20,6 +27,95 @@ -(void)meth {
 }
 @end
 
+// Ivars declared in the @interface
+@interface SuperClass : NSObject
+@property (nonatomic, assign) int superClassProperty;
+@end
+
+@implementation SuperClass {
+  int superClassIvar; // Declare an ivar
+}
+
+// CHECK-LABEL: define internal void @"\01-[SuperClass superClassMethod]"
+- (void)superClassMethod {
+_superClassProperty = 42;
+superClassIvar = 10;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SuperClass
+// CHECK: getelementptr inbounds i8, ptr %1, i64 20
+}
+
+// implicitly synthesized method here
+// CHECK-LABEL: define internal i32 @"\01-[SuperClass superClassProperty]"
+// CHECK: getelementptr inbounds i8, ptr %0, i64 24
+
+// CHECK-LABEL: define internal void @"\01-[SuperClass setSuperClassProperty:]"
+// CHECK: getelementptr inbounds i8, ptr %1, i64 24
+@end
+
+// Inheritance and Ivars
+@interface IntermediateClass : SuperClass
+{
+double intermediateClassIvar;
+
+@protected
+int intermediateClassIvar2;
+}
+@property (nonatomic, strong) SuperClass *intermediateProperty;
+@end
+
+@implementation IntermediateClass
+@synthesize intermediateProperty = _intermediateProperty;
+- (void)intermediateClassMethod {
+intermediateClassIvar = 3.14;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_IntermediateClass
+// CHECK: getelementptr inbounds i8, ptr %0, i64 %ivar
+}
+
+// CHECK-LABEL: define internal void @"\01-[IntermediateClass 
intermediateClassPropertyMethod]"
+- (void)intermediateClassPropertyMethod {
+self.intermediateProperty = 0;
+// CHECK: load ptr, ptr @OBJC_SELECTOR_REFERENCES_
+// CHECK: call void @objc_msgSend(ptr noundef %0, ptr noundef %1, ptr 
noundef null)
+}
+
+// CHECK-LABEL: define internal void @"\01-[IntermediateClass 
intermediateClassPropertyMethodDirect]"
+- (void)intermediateClassPropertyMethodDirect {
+_intermediateProperty = 0;
+// CHECK: load i64, ptr 
@"OBJC_IVAR_$_IntermediateClass._intermediateProperty"
+}
+@end
+
+@interface SubClass : IntermediateClass
+{
+double subClassIvar;
+}
+@property (nonatomic, assign) SubClass *subClassProperty;
+@end
+
+@implementation SubClass
+// CHECK-LABEL: define internal void @"\01-[SubClass subclassVar]"
+- (void)subclassVar {
+
+subClassIvar = 6.28;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SubClass
+// CHECK: getelementptr inbounds i8, ptr %0, i64 %ivar
+}
+
+// CHECK-LABEL: define internal void @"\01-[SubClass intermediateSubclassVar]"
+-(void)intermediateSubclassVar {
+intermediateClassIvar = 3.14;
+// CHECK: load i64, ptr @"OBJC_IVAR_$_IntermediateClass
+// CHECK: getelementptr inbounds i8, ptr %0, i64 %ivar
+}
+
+// implicit synthesized method here:
+// CHECK-LABEL: define internal ptr @"\01-[SubClass subClassProperty]"
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SubClass._subClassProperty"
+
+// CHECK-LABEL: define internal void @"\01-[SubClass setSubClassProperty:]"
+// CHECK: load i64, ptr @"OBJC_IVAR_$_SubClass._subClassProperty"
+@end
+
 @interface NotNSObject {
   int these, might, change;
 }

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

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

[clang] [Clang][Sema] Fix incorrect rejection default construction of union with nontrivial member (PR #82407)

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

https://github.com/shafik updated 
https://github.com/llvm/llvm-project/pull/82407

>From 5fcaeaddccc0f7e370bf7bebce113d8d52e1b1bd Mon Sep 17 00:00:00 2001
From: Shafik Yaghmour 
Date: Tue, 20 Feb 2024 11:22:39 -0800
Subject: [PATCH] [Clang][Sema] Fix incorrect rejection default construction of
 union with nontrivial member

In 765d8a192180f8f33618087b15c022fe758044af we impelemented a fix for incorrect 
deletion of
default constructors in unions. This fix missed a case and so this PR will
extend the fix to cover the additional case.

Fixes: https://github.com/llvm/llvm-project/issues/81774
---
 clang/docs/ReleaseNotes.rst|  3 +++
 clang/lib/Sema/SemaDeclCXX.cpp | 18 +++---
 .../test/CodeGen/union-non-trivial-member.cpp  | 17 +
 clang/test/SemaCXX/cxx0x-nontrivial-union.cpp  | 11 +++
 4 files changed, 46 insertions(+), 3 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 5bca2c965c866b..452382eb6c4a1e 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -292,6 +292,9 @@ Bug Fixes to C++ Support
   was only accepted at namespace scope but not at local function scope.
 - Clang no longer tries to call consteval constructors at runtime when they 
appear in a member initializer.
   (`#782154 `_`)
+- Fix for clang incorrectly rejecting the default construction of a union with
+  nontrivial member when another member has an initializer.
+  (`#81774 `_)
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 79263bc3ff671d..25a4b4381ca25e 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -9442,9 +9442,21 @@ bool 
SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
 
   int DiagKind = -1;
 
-  if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
-DiagKind = !Decl ? 0 : 1;
-  else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
+  if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) {
+if (CSM == Sema::CXXDefaultConstructor && Field &&
+Field->getParent()->isUnion()) {
+  // [class.default.ctor]p2:
+  //   A defaulted default constructor for class X is defined as deleted if
+  //   - X is a union that has a variant member with a non-trivial default
+  // constructor and no variant member of X has a default member
+  // initializer
+  const auto *RD = cast(Field->getParent());
+  if (!RD->hasInClassInitializer())
+DiagKind = !Decl ? 0 : 1;
+} else {
+  DiagKind = !Decl ? 0 : 1;
+}
+  } else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
 DiagKind = 2;
   else if (!isAccessible(Subobj, Decl))
 DiagKind = 3;
diff --git a/clang/test/CodeGen/union-non-trivial-member.cpp 
b/clang/test/CodeGen/union-non-trivial-member.cpp
index fdc9fd16911e14..8b055a9970fc75 100644
--- a/clang/test/CodeGen/union-non-trivial-member.cpp
+++ b/clang/test/CodeGen/union-non-trivial-member.cpp
@@ -15,14 +15,25 @@ union UnionNonTrivial {
 non_trivial_constructor b{};
 };
 
+struct Handle {
+Handle(int) {}
+};
+
+union UnionNonTrivialEqualInit {
+int NoState = 0;
+Handle CustomState;
+};
+
 void f() {
 UnionInt u1;
 UnionNonTrivial u2;
+UnionNonTrivialEqualInit u3;
 }
 
 // CHECK:  define dso_local void @_Z1fv()
 // CHECK:call void @_ZN8UnionIntC1Ev
 // CHECK-NEXT:   call void @_ZN15UnionNonTrivialC1Ev
+// CHECK-NEXT:   call void @_ZN24UnionNonTrivialEqualInitC1Ev
 
 // CHECK:  define {{.*}}void @_ZN8UnionIntC1Ev
 // CHECK:call void @_ZN8UnionIntC2Ev
@@ -30,8 +41,14 @@ void f() {
 // CHECK:  define {{.*}}void @_ZN15UnionNonTrivialC1Ev
 // CHECK:call void @_ZN15UnionNonTrivialC2Ev
 
+// CHECK:  define {{.*}}void @_ZN24UnionNonTrivialEqualInitC1Ev
+// CHECK:call void @_ZN24UnionNonTrivialEqualInitC2Ev
+
 // CHECK:  define {{.*}}void @_ZN8UnionIntC2Ev
 // CHECK:store i32 1000
 
 // CHECK:  define {{.*}}void @_ZN15UnionNonTrivialC2Ev
 // CHECK:call void @_ZN23non_trivial_constructorC1Ev
+
+// CHECK:  define {{.*}}void @_ZN24UnionNonTrivialEqualInitC2Ev
+// CHECK:store i32 0
diff --git a/clang/test/SemaCXX/cxx0x-nontrivial-union.cpp 
b/clang/test/SemaCXX/cxx0x-nontrivial-union.cpp
index c7cdf76d850dbe..833642b3d739ab 100644
--- a/clang/test/SemaCXX/cxx0x-nontrivial-union.cpp
+++ b/clang/test/SemaCXX/cxx0x-nontrivial-union.cpp
@@ -188,3 +188,14 @@ static_assert(U2().b.x == 100, "");
 static_assert(U3().b.x == 100, "");
 
 } // namespace GH48416
+
+namespace GH81774 {
+struct Handle {
+Handle(int) {}
+};
+// Should be well-formed because NoState has a brace-or-equal-initializer.
+union a {
+int NoState = 0;
+ 

[clang] [llvm] [nfc]Generalize PGOFuncName helper methods for general global objects (PR #73570)

2024-02-23 Thread Mingming Liu via cfe-commits

minglotus-6 wrote:

This is superseded by https://github.com/llvm/llvm-project/pull/75954 

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


[clang] [llvm] [nfc]Generalize PGOFuncName helper methods for general global objects (PR #73570)

2024-02-23 Thread Mingming Liu via cfe-commits

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


[clang] [flang] [flang] Fixes for LIT testing of FLANG_RUNTIME_F128_MATH_LIB build. (PR #82832)

2024-02-23 Thread Slava Zakharin via cfe-commits

https://github.com/vzakhari updated 
https://github.com/llvm/llvm-project/pull/82832

>From 4ad0b005081fe2286970b4c22721fe72ed26cf8b Mon Sep 17 00:00:00 2001
From: Slava Zakharin 
Date: Fri, 23 Feb 2024 13:08:49 -0800
Subject: [PATCH 1/2] [flang] Fixes for LIT testing of
 FLANG_RUNTIME_F128_MATH_LIB build.

Follow-up for #81971 to fix the disabled LIT test and add
LIT tests for lowering of the added math intrinsics.
---
 clang/lib/Driver/ToolChains/CommonArgs.cpp| 15 
 flang/test/Driver/linker-flags.f90| 34 +--
 flang/test/Lower/Intrinsics/cabs_real16.f90   | 10 ++
 .../Lower/Intrinsics/missing-math-runtime.f90 | 12 +++
 flang/test/Lower/Intrinsics/sin_real16.f90|  9 +
 flang/test/Lower/Intrinsics/sqrt_real16.f90   |  9 +
 flang/test/lit.cfg.py | 21 
 flang/test/lit.site.cfg.py.in |  1 +
 8 files changed, 87 insertions(+), 24 deletions(-)
 create mode 100644 flang/test/Lower/Intrinsics/cabs_real16.f90
 create mode 100644 flang/test/Lower/Intrinsics/sin_real16.f90
 create mode 100644 flang/test/Lower/Intrinsics/sqrt_real16.f90

diff --git a/clang/lib/Driver/ToolChains/CommonArgs.cpp 
b/clang/lib/Driver/ToolChains/CommonArgs.cpp
index 347b250260c4c4..faceee85a2f8dc 100644
--- a/clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ b/clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -1316,13 +1316,16 @@ void tools::addFortranRuntimeLibs(const ToolChain , 
const ArgList ,
   // add the correct libraries to link against as dependents in the object
   // file.
   if (!TC.getTriple().isKnownWindowsMSVCEnvironment()) {
-StringRef f128LibName = TC.getDriver().getFlangF128MathLibrary();
-f128LibName.consume_front_insensitive("lib");
-if (!f128LibName.empty()) {
+StringRef F128LibName = TC.getDriver().getFlangF128MathLibrary();
+F128LibName.consume_front_insensitive("lib");
+if (!F128LibName.empty()) {
+  bool AsNeeded = !TC.getTriple().isOSAIX();
   CmdArgs.push_back("-lFortranFloat128Math");
-  addAsNeededOption(TC, Args, CmdArgs, /*as_needed=*/true);
-  CmdArgs.push_back(Args.MakeArgString("-l" + f128LibName));
-  addAsNeededOption(TC, Args, CmdArgs, /*as_needed=*/false);
+  if (AsNeeded)
+addAsNeededOption(TC, Args, CmdArgs, /*as_needed=*/true);
+  CmdArgs.push_back(Args.MakeArgString("-l" + F128LibName));
+  if (AsNeeded)
+addAsNeededOption(TC, Args, CmdArgs, /*as_needed=*/false);
 }
 CmdArgs.push_back("-lFortranRuntime");
 CmdArgs.push_back("-lFortranDecimal");
diff --git a/flang/test/Driver/linker-flags.f90 
b/flang/test/Driver/linker-flags.f90
index 5e00520fcc098c..4d3d528b5e99e0 100644
--- a/flang/test/Driver/linker-flags.f90
+++ b/flang/test/Driver/linker-flags.f90
@@ -2,15 +2,15 @@
 ! invocation. These libraries are added on top of other standard runtime
 ! libraries that the Clang driver will include.
 
-! RUN: %flang -### --target=ppc64le-linux-gnu %S/Inputs/hello.f90 2>&1 | 
FileCheck %s --check-prefixes=CHECK,UNIX
-! RUN: %flang -### --target=aarch64-apple-darwin %S/Inputs/hello.f90 2>&1 | 
FileCheck %s --check-prefixes=CHECK,DARWIN
-! RUN: %flang -### --target=sparc-sun-solaris2.11 %S/Inputs/hello.f90 2>&1 | 
FileCheck %s --check-prefixes=CHECK,UNIX
-! RUN: %flang -### --target=x86_64-unknown-freebsd %S/Inputs/hello.f90 2>&1 | 
FileCheck %s --check-prefixes=CHECK,UNIX
-! RUN: %flang -### --target=x86_64-unknown-netbsd %S/Inputs/hello.f90 2>&1 | 
FileCheck %s --check-prefixes=CHECK,UNIX
-! RUN: %flang -### --target=x86_64-unknown-openbsd %S/Inputs/hello.f90 2>&1 | 
FileCheck %s --check-prefixes=CHECK,UNIX
-! RUN: %flang -### --target=x86_64-unknown-dragonfly %S/Inputs/hello.f90 2>&1 
| FileCheck %s --check-prefixes=CHECK,UNIX
-! RUN: %flang -### --target=x86_64-unknown-haiku %S/Inputs/hello.f90 2>&1 | 
FileCheck %s --check-prefixes=CHECK,HAIKU
-! RUN: %flang -### --target=x86_64-windows-gnu %S/Inputs/hello.f90 2>&1 | 
FileCheck %s --check-prefixes=CHECK,MINGW
+! RUN: %flang -### --target=ppc64le-linux-gnu %S/Inputs/hello.f90 2>&1 | 
FileCheck %s --check-prefixes=CHECK,UNIX,UNIX-F128%f128-lib
+! RUN: %flang -### --target=aarch64-apple-darwin %S/Inputs/hello.f90 2>&1 | 
FileCheck %s --check-prefixes=CHECK,DARWIN,DARWIN-F128%f128-lib
+! RUN: %flang -### --target=sparc-sun-solaris2.11 %S/Inputs/hello.f90 2>&1 | 
FileCheck %s --check-prefixes=CHECK,UNIX,SOLARIS-F128%f128-lib
+! RUN: %flang -### --target=x86_64-unknown-freebsd %S/Inputs/hello.f90 2>&1 | 
FileCheck %s --check-prefixes=CHECK,UNIX,UNIX-F128%f128-lib
+! RUN: %flang -### --target=x86_64-unknown-netbsd %S/Inputs/hello.f90 2>&1 | 
FileCheck %s --check-prefixes=CHECK,UNIX,UNIX-F128%f128-lib
+! RUN: %flang -### --target=x86_64-unknown-openbsd %S/Inputs/hello.f90 2>&1 | 
FileCheck %s --check-prefixes=CHECK,UNIX,UNIX-F128%f128-lib
+! RUN: %flang -### --target=x86_64-unknown-dragonfly %S/Inputs/hello.f90 2>&1 
| FileCheck %s 

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

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

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


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

2024-02-23 Thread via cfe-commits

Author: Owen Pan
Date: 2024-02-23T20:03:13-08:00
New Revision: b0d2a52c87b36afab4734e1810fb9266aec1128f

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

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

Also insert separators for decimal integers longer than 4 digits.

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 10ab406a15c6e1..2f6b52510099a7 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -1591,7 +1591,7 @@ FormatStyle getLLVMStyle(FormatStyle::LanguageKind 
Language) {
   LLVMStyle.PenaltyBreakScopeResolution = 500;
   LLVMStyle.PenaltyBreakString = 1000;
   LLVMStyle.PenaltyBreakTemplateDeclaration = prec::Relational;
-  LLVMStyle.PenaltyExcessCharacter = 100;
+  LLVMStyle.PenaltyExcessCharacter = 1'000'000;
   LLVMStyle.PenaltyIndentedWhitespace = 0;
   LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
 
@@ -1914,9 +1914,12 @@ FormatStyle getClangFormatStyle() {
   FormatStyle Style = getLLVMStyle();
   Style.InsertBraces = true;
   Style.InsertNewlineAtEOF = true;
+  Style.IntegerLiteralSeparator.Decimal = 3;
+  Style.IntegerLiteralSeparator.DecimalMinDigits = 5;
   Style.LineEnding = FormatStyle::LE_LF;
   Style.RemoveBracesLLVM = true;
   Style.RemoveParentheses = FormatStyle::RPS_ReturnStatement;
+  Style.RemoveSemicolon = true;
   return Style;
 }
 

diff  --git a/clang/lib/Format/FormatToken.cpp 
b/clang/lib/Format/FormatToken.cpp
index b791c5a26bbe3a..56a7b2d6387765 100644
--- a/clang/lib/Format/FormatToken.cpp
+++ b/clang/lib/Format/FormatToken.cpp
@@ -137,7 +137,7 @@ unsigned CommaSeparatedList::formatAfterToken(LineState 
,
   // bin-packed. Add a severe penalty to this so that column layouts are
   // preferred if possible.
   if (!Format)
-return 1;
+return 10'000;
 
   // Format the entire list.
   unsigned Penalty = 0;

diff  --git a/clang/lib/Format/UnwrappedLineFormatter.cpp 
b/clang/lib/Format/UnwrappedLineFormatter.cpp
index adeb072434873f..fb31980ab9f491 100644
--- a/clang/lib/Format/UnwrappedLineFormatter.cpp
+++ b/clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -1221,7 +1221,7 @@ class OptimizingLineFormatter : public LineFormatter {
 // While not empty, take first element and follow edges.
 while (!Queue.empty()) {
   // Quit if we still haven't found a solution by now.
-  if (Count > 2500)
+  if (Count > 25'000'000)
 return 0;
 
   Penalty = Queue.top().first.first;
@@ -1235,7 +1235,7 @@ class OptimizingLineFormatter : public LineFormatter {
 
   // Cut off the analysis of certain solutions if the analysis gets too
   // complex. See description of IgnoreStackForComparison.
-  if (Count > 5)
+  if (Count > 50'000)
 Node->State.IgnoreStackForComparison = true;
 
   if (!Seen.insert(>State).second) {

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index b8dc01f55b4faa..d9752c73e34e79 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -21669,7 +21669,7 @@ TEST_F(FormatTest, BreakPenaltyAfterCastLParen) {
"int));",
 
Style);
-  Style.PenaltyBreakOpenParenthesis = 10;
+  Style.PenaltyBreakOpenParenthesis = 100'000;
   verifyFormat("foo((int)\n"
");",
"foo((\n"



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


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

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

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

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

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

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

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

2024-02-23 Thread via cfe-commits


@@ -0,0 +1,177 @@
+//===--- CrtpConstructorAccessibilityCheck.cpp - clang-tidy
+//-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "CrtpConstructorAccessibilityCheck.h"
+#include "../utils/LexerUtils.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+static bool hasPrivateConstructor(const CXXRecordDecl *RD) {
+  return llvm::any_of(RD->ctors(), [](const CXXConstructorDecl *Ctor) {
+return Ctor->getAccess() == AS_private;
+  });
+}
+
+static bool isDerivedParameterBefriended(const CXXRecordDecl *CRTP,
+ const NamedDecl *Param) {
+  return llvm::any_of(CRTP->friends(), [&](const FriendDecl *Friend) {
+const auto *TTPT =
+dyn_cast(Friend->getFriendType()->getType());
+
+return TTPT && TTPT->getDecl() == Param;
+  });
+}
+
+static bool isDerivedClassBefriended(const CXXRecordDecl *CRTP,
+ const CXXRecordDecl *Derived) {
+  return llvm::any_of(CRTP->friends(), [&](const FriendDecl *Friend) {
+return Friend->getFriendType()->getType()->getAsCXXRecordDecl() == Derived;
+  });
+}
+
+static const NamedDecl *
+getDerivedParameter(const ClassTemplateSpecializationDecl *CRTP,
+const CXXRecordDecl *Derived) {
+  size_t Idx = 0;
+  const bool AnyOf = llvm::any_of(
+  CRTP->getTemplateArgs().asArray(), [&](const TemplateArgument ) {
+++Idx;
+return Arg.getKind() == TemplateArgument::Type &&
+   Arg.getAsType()->getAsCXXRecordDecl() == Derived;
+  });
+
+  return AnyOf ? CRTP->getSpecializedTemplate()
+ ->getTemplateParameters()
+ ->getParam(Idx - 1)
+   : nullptr;
+}
+
+static std::vector
+hintMakeCtorPrivate(const CXXConstructorDecl *Ctor,
+const std::string ) {
+  std::vector Hints;
+
+  Hints.emplace_back(FixItHint::CreateInsertion(
+  Ctor->getBeginLoc().getLocWithOffset(-1), "private:\n"));
+
+  const ASTContext  = Ctor->getASTContext();
+  const SourceLocation CtorEndLoc =
+  Ctor->isExplicitlyDefaulted()
+  ? utils::lexer::findNextTerminator(Ctor->getEndLoc(),
+ ASTCtx.getSourceManager(),
+ ASTCtx.getLangOpts())
+  : Ctor->getEndLoc();
+  Hints.emplace_back(FixItHint::CreateInsertion(
+  CtorEndLoc.getLocWithOffset(1), '\n' + OriginalAccess + ':' + '\n'));
+
+  return Hints;
+}
+
+void CrtpConstructorAccessibilityCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  classTemplateSpecializationDecl(
+  decl().bind("crtp"),
+  hasAnyTemplateArgument(refersToType(recordType(hasDeclaration(
+  cxxRecordDecl(
+  isDerivedFrom(cxxRecordDecl(equalsBoundNode("crtp"
+  .bind("derived")),
+  this);
+}
+
+void CrtpConstructorAccessibilityCheck::check(
+const MatchFinder::MatchResult ) {
+  const auto *CRTPInstantiation =
+  Result.Nodes.getNodeAs("crtp");
+  const auto *DerivedRecord = Result.Nodes.getNodeAs("derived");
+  const CXXRecordDecl *CRTPDeclaration =
+  CRTPInstantiation->getSpecializedTemplate()->getTemplatedDecl();
+
+  const auto *DerivedTemplateParameter =
+  getDerivedParameter(CRTPInstantiation, DerivedRecord);
+
+  assert(DerivedTemplateParameter &&
+ "No template parameter corresponds to the derived class of the 
CRTP.");
+
+  bool NeedsFriend = !isDerivedParameterBefriended(CRTPDeclaration,
+   DerivedTemplateParameter) &&
+ !isDerivedClassBefriended(CRTPDeclaration, DerivedRecord);
+
+  const FixItHint HintFriend = FixItHint::CreateInsertion(
+  CRTPDeclaration->getBraceRange().getEnd(),
+  "friend " + DerivedTemplateParameter->getNameAsString() + ';' + '\n');
+
+  if (hasPrivateConstructor(CRTPDeclaration) && NeedsFriend) {
+diag(CRTPDeclaration->getLocation(),
+ "the CRTP cannot be constructed from the derived class")
+<< CRTPDeclaration << HintFriend;

isuckatcs wrote:

What do you mean?

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


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

2024-02-23 Thread via cfe-commits


@@ -0,0 +1,177 @@
+//===--- CrtpConstructorAccessibilityCheck.cpp - clang-tidy
+//-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "CrtpConstructorAccessibilityCheck.h"
+#include "../utils/LexerUtils.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+static bool hasPrivateConstructor(const CXXRecordDecl *RD) {
+  return llvm::any_of(RD->ctors(), [](const CXXConstructorDecl *Ctor) {
+return Ctor->getAccess() == AS_private;
+  });
+}
+
+static bool isDerivedParameterBefriended(const CXXRecordDecl *CRTP,
+ const NamedDecl *Param) {
+  return llvm::any_of(CRTP->friends(), [&](const FriendDecl *Friend) {
+const auto *TTPT =
+dyn_cast(Friend->getFriendType()->getType());
+
+return TTPT && TTPT->getDecl() == Param;
+  });
+}
+
+static bool isDerivedClassBefriended(const CXXRecordDecl *CRTP,
+ const CXXRecordDecl *Derived) {
+  return llvm::any_of(CRTP->friends(), [&](const FriendDecl *Friend) {
+return Friend->getFriendType()->getType()->getAsCXXRecordDecl() == Derived;
+  });
+}
+
+static const NamedDecl *
+getDerivedParameter(const ClassTemplateSpecializationDecl *CRTP,
+const CXXRecordDecl *Derived) {
+  size_t Idx = 0;
+  const bool AnyOf = llvm::any_of(
+  CRTP->getTemplateArgs().asArray(), [&](const TemplateArgument ) {
+++Idx;
+return Arg.getKind() == TemplateArgument::Type &&
+   Arg.getAsType()->getAsCXXRecordDecl() == Derived;
+  });
+
+  return AnyOf ? CRTP->getSpecializedTemplate()
+ ->getTemplateParameters()
+ ->getParam(Idx - 1)
+   : nullptr;
+}
+
+static std::vector
+hintMakeCtorPrivate(const CXXConstructorDecl *Ctor,
+const std::string ) {
+  std::vector Hints;
+
+  Hints.emplace_back(FixItHint::CreateInsertion(
+  Ctor->getBeginLoc().getLocWithOffset(-1), "private:\n"));
+
+  const ASTContext  = Ctor->getASTContext();
+  const SourceLocation CtorEndLoc =
+  Ctor->isExplicitlyDefaulted()
+  ? utils::lexer::findNextTerminator(Ctor->getEndLoc(),
+ ASTCtx.getSourceManager(),
+ ASTCtx.getLangOpts())
+  : Ctor->getEndLoc();
+  Hints.emplace_back(FixItHint::CreateInsertion(
+  CtorEndLoc.getLocWithOffset(1), '\n' + OriginalAccess + ':' + '\n'));
+
+  return Hints;
+}
+
+void CrtpConstructorAccessibilityCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  classTemplateSpecializationDecl(
+  decl().bind("crtp"),
+  hasAnyTemplateArgument(refersToType(recordType(hasDeclaration(
+  cxxRecordDecl(
+  isDerivedFrom(cxxRecordDecl(equalsBoundNode("crtp"
+  .bind("derived")),
+  this);
+}
+
+void CrtpConstructorAccessibilityCheck::check(
+const MatchFinder::MatchResult ) {
+  const auto *CRTPInstantiation =
+  Result.Nodes.getNodeAs("crtp");
+  const auto *DerivedRecord = Result.Nodes.getNodeAs("derived");
+  const CXXRecordDecl *CRTPDeclaration =
+  CRTPInstantiation->getSpecializedTemplate()->getTemplatedDecl();
+
+  const auto *DerivedTemplateParameter =
+  getDerivedParameter(CRTPInstantiation, DerivedRecord);
+
+  assert(DerivedTemplateParameter &&
+ "No template parameter corresponds to the derived class of the 
CRTP.");
+
+  bool NeedsFriend = !isDerivedParameterBefriended(CRTPDeclaration,
+   DerivedTemplateParameter) &&
+ !isDerivedClassBefriended(CRTPDeclaration, DerivedRecord);
+
+  const FixItHint HintFriend = FixItHint::CreateInsertion(
+  CRTPDeclaration->getBraceRange().getEnd(),
+  "friend " + DerivedTemplateParameter->getNameAsString() + ';' + '\n');
+
+  if (hasPrivateConstructor(CRTPDeclaration) && NeedsFriend) {
+diag(CRTPDeclaration->getLocation(),
+ "the CRTP cannot be constructed from the derived class")
+<< CRTPDeclaration << HintFriend;
+diag(CRTPDeclaration->getLocation(),

isuckatcs wrote:

See [my previous 
comment](https://github.com/llvm/llvm-project/pull/82403#discussion_r1500139723).
 @njames93 what's your view on this?

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


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

2024-02-23 Thread via cfe-commits

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


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

2024-02-23 Thread via cfe-commits


@@ -0,0 +1,177 @@
+//===--- CrtpConstructorAccessibilityCheck.cpp - clang-tidy
+//-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "CrtpConstructorAccessibilityCheck.h"
+#include "../utils/LexerUtils.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+static bool hasPrivateConstructor(const CXXRecordDecl *RD) {
+  return llvm::any_of(RD->ctors(), [](const CXXConstructorDecl *Ctor) {
+return Ctor->getAccess() == AS_private;
+  });
+}
+
+static bool isDerivedParameterBefriended(const CXXRecordDecl *CRTP,
+ const NamedDecl *Param) {
+  return llvm::any_of(CRTP->friends(), [&](const FriendDecl *Friend) {
+const auto *TTPT =
+dyn_cast(Friend->getFriendType()->getType());
+
+return TTPT && TTPT->getDecl() == Param;
+  });
+}
+
+static bool isDerivedClassBefriended(const CXXRecordDecl *CRTP,
+ const CXXRecordDecl *Derived) {
+  return llvm::any_of(CRTP->friends(), [&](const FriendDecl *Friend) {
+return Friend->getFriendType()->getType()->getAsCXXRecordDecl() == Derived;
+  });
+}
+
+static const NamedDecl *
+getDerivedParameter(const ClassTemplateSpecializationDecl *CRTP,
+const CXXRecordDecl *Derived) {
+  size_t Idx = 0;
+  const bool AnyOf = llvm::any_of(
+  CRTP->getTemplateArgs().asArray(), [&](const TemplateArgument ) {
+++Idx;
+return Arg.getKind() == TemplateArgument::Type &&
+   Arg.getAsType()->getAsCXXRecordDecl() == Derived;
+  });
+
+  return AnyOf ? CRTP->getSpecializedTemplate()
+ ->getTemplateParameters()
+ ->getParam(Idx - 1)
+   : nullptr;
+}
+
+static std::vector
+hintMakeCtorPrivate(const CXXConstructorDecl *Ctor,
+const std::string ) {
+  std::vector Hints;
+
+  Hints.emplace_back(FixItHint::CreateInsertion(
+  Ctor->getBeginLoc().getLocWithOffset(-1), "private:\n"));
+
+  const ASTContext  = Ctor->getASTContext();
+  const SourceLocation CtorEndLoc =
+  Ctor->isExplicitlyDefaulted()
+  ? utils::lexer::findNextTerminator(Ctor->getEndLoc(),
+ ASTCtx.getSourceManager(),
+ ASTCtx.getLangOpts())
+  : Ctor->getEndLoc();
+  Hints.emplace_back(FixItHint::CreateInsertion(
+  CtorEndLoc.getLocWithOffset(1), '\n' + OriginalAccess + ':' + '\n'));
+
+  return Hints;
+}
+
+void CrtpConstructorAccessibilityCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  classTemplateSpecializationDecl(
+  decl().bind("crtp"),
+  hasAnyTemplateArgument(refersToType(recordType(hasDeclaration(
+  cxxRecordDecl(
+  isDerivedFrom(cxxRecordDecl(equalsBoundNode("crtp"
+  .bind("derived")),
+  this);
+}
+
+void CrtpConstructorAccessibilityCheck::check(
+const MatchFinder::MatchResult ) {
+  const auto *CRTPInstantiation =
+  Result.Nodes.getNodeAs("crtp");
+  const auto *DerivedRecord = Result.Nodes.getNodeAs("derived");
+  const CXXRecordDecl *CRTPDeclaration =
+  CRTPInstantiation->getSpecializedTemplate()->getTemplatedDecl();
+
+  const auto *DerivedTemplateParameter =
+  getDerivedParameter(CRTPInstantiation, DerivedRecord);
+
+  assert(DerivedTemplateParameter &&
+ "No template parameter corresponds to the derived class of the 
CRTP.");
+
+  bool NeedsFriend = !isDerivedParameterBefriended(CRTPDeclaration,
+   DerivedTemplateParameter) &&
+ !isDerivedClassBefriended(CRTPDeclaration, DerivedRecord);
+
+  const FixItHint HintFriend = FixItHint::CreateInsertion(
+  CRTPDeclaration->getBraceRange().getEnd(),
+  "friend " + DerivedTemplateParameter->getNameAsString() + ';' + '\n');
+
+  if (hasPrivateConstructor(CRTPDeclaration) && NeedsFriend) {
+diag(CRTPDeclaration->getLocation(),
+ "the CRTP cannot be constructed from the derived class")
+<< CRTPDeclaration << HintFriend;
+diag(CRTPDeclaration->getLocation(),
+ "consider declaring the derived class as friend", 
DiagnosticIDs::Note);
+  }
+
+  auto DiagNoteFriendPrivate = [&](const SourceLocation , bool Friend) {
+return diag(Loc,
+"consider making it private%select{| and declaring the "
+"derived class "
+"as friend}0",
+DiagnosticIDs::Note)
+   << Friend;
+  };
+
+  auto WithFriendHintIfNeeded = [&](DiagnosticBuilder Diag, bool NeedsFriend) {
+

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

2024-02-23 Thread via cfe-commits


@@ -0,0 +1,82 @@
+.. title:: clang-tidy - bugprone-crtp-constructor-accessibility
+
+bugprone-crtp-constructor-accessibility
+===
+
+Finds Curiously Recurring Template Pattern used in an error-prone way.
+
+The CRTP is an idiom, in which a class derives from a template class, where 
+itself is the template argument. It should be ensured that if a class is
+intended to be a base class in this idiom, it can only be instantiated if
+the derived class is it's template argument.
+
+Example:
+
+.. code-block:: c++
+
+  template  class CRTP {
+  private:
+CRTP() = default;
+friend T;
+  };
+
+  class Derived : CRTP {};
+
+Below can be seen some common mistakes that will allow the breaking of the 
idiom.
+
+If the constructor of a class intended to be used in a CRTP is public, then
+it allows users to construct that class on its own.
+
+Example:
+
+.. code-block:: c++
+
+  template  class CRTP {
+  public:
+CRTP() = default;
+  };
+
+  class Good : CRTP {};
+  Good GoodInstance;
+
+  CRTP BadInstance;
+
+If the constructor is protected, the possibility of an accidental instantiation
+is prevented, however it can fade an error, when a different class is used as
+the template parameter instead of the derived one.
+
+Example:
+
+.. code-block:: c++
+
+  template  class CRTP {
+  protected:
+CRTP() = default;
+  };
+
+  class Good : CRTP {};
+  Good GoodInstance;
+
+  class Bad : CRTP {};
+  Bad BadInstance;
+
+To ensure that no accidental instantiation happens, the best practice is to 
make
+the constructor private and declare the derived class as friend. Note that as 
a tradeoff, 
+this also gives the derived class access to every other private members of the 
CRTP.
+
+Example:
+
+.. code-block:: c++
+
+  template  class CRTP {
+CRTP() = default;
+friend T;
+  };
+
+  class Good : CRTP {};
+  Good GoodInstance;
+
+  class Bad : CRTP {};
+  Bad CompileTimeError;
+
+  CRTP AlsoCompileTimeError;

isuckatcs wrote:

The issue with previous standards is the friend declaration. See [my previous 
comment](https://github.com/llvm/llvm-project/pull/82403#discussion_r1500091382)
 for more details.

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


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

2024-02-23 Thread via cfe-commits


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

[clang] [llvm] [clang][ScanDeps] Allow PCHs to have different VFS overlays (PR #82294)

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

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


[clang] de3b2c2 - [clang][ScanDeps] Allow PCHs to have different VFS overlays (#82294)

2024-02-23 Thread via cfe-commits

Author: Michael Spencer
Date: 2024-02-23T17:48:58-08:00
New Revision: de3b2c293b8bf336f8e1380148cf16b54a794c0c

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

LOG: [clang][ScanDeps] Allow PCHs to have different VFS overlays (#82294)

It turns out it's not that uncommon for real code to pass a different
set of VFSs while building a PCH than while using the PCH. This can
cause problems as seen in `test/ClangScanDeps/optimize-vfs-pch.m`. If
you scan `compile-commands-tu-no-vfs-error.json` without -Werror and run
the resulting commands, Clang will emit a fatal error while trying to
emit a note saying that it can't find a remapped header.

This also adds textual tracking of VFSs for prebuilt modules that are
part of an included PCH, as the same issue can occur in a module we are
building if we drop VFSs. This has to be textual because we have no
guarantee the PCH had the same list of VFSs as the current TU.

This uses the `PrebuiltModuleListener` to collect `VFSOverlayFiles`
instead of trying to extract it out of a `serialization::ModuleFile`
each time it's needed. There's not a great way to just store a pointer
to the list of strings in the serialized AST.

Added: 


Modified: 
clang/include/clang/Basic/DiagnosticSerializationKinds.td
clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
clang/lib/Tooling/DependencyScanning/ModuleDepCollector.cpp
clang/test/ClangScanDeps/optimize-vfs-pch.m
llvm/include/llvm/ADT/StringSet.h

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticSerializationKinds.td 
b/clang/include/clang/Basic/DiagnosticSerializationKinds.td
index 4c4659ed517e0a..eb27de5921d6a1 100644
--- a/clang/include/clang/Basic/DiagnosticSerializationKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSerializationKinds.td
@@ -44,7 +44,9 @@ def err_pch_diagopt_mismatch : Error<"%0 is currently 
enabled, but was not in "
   "the PCH file">;
 def err_pch_modulecache_mismatch : Error<"PCH was compiled with module cache "
   "path '%0', but the path is currently '%1'">;
-def err_pch_vfsoverlay_mismatch : Error<"PCH was compiled with 
diff erent VFS overlay files than are currently in use">;
+def warn_pch_vfsoverlay_mismatch : Warning<
+  "PCH was compiled with 
diff erent VFS overlay files than are currently in use">,
+  InGroup>;
 def note_pch_vfsoverlay_files : Note<"%select{PCH|current translation unit}0 
has the following VFS overlays:\n%1">;
 def note_pch_vfsoverlay_empty : Note<"%select{PCH|current translation unit}0 
has no VFS overlays">;
 

diff  --git 
a/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h 
b/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
index 13ad2530864927..081899cc2c8503 100644
--- a/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
+++ b/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
@@ -149,6 +149,8 @@ struct ModuleDeps {
   BuildInfo;
 };
 
+using PrebuiltModuleVFSMapT = llvm::StringMap>;
+
 class ModuleDepCollector;
 
 /// Callback that records textual includes and direct modular includes/imports
@@ -214,6 +216,7 @@ class ModuleDepCollector final : public DependencyCollector 
{
  CompilerInstance , DependencyConsumer ,
  DependencyActionController ,
  CompilerInvocation OriginalCI,
+ PrebuiltModuleVFSMapT PrebuiltModuleVFSMap,
  ScanningOptimizations OptimizeArgs, bool EagerLoadModules,
  bool IsStdModuleP1689Format);
 
@@ -233,6 +236,8 @@ class ModuleDepCollector final : public DependencyCollector 
{
   DependencyConsumer 
   /// Callbacks for computing dependency information.
   DependencyActionController 
+  /// Mapping from prebuilt AST files to their sorted list of VFS overlay 
files.
+  PrebuiltModuleVFSMapT PrebuiltModuleVFSMap;
   /// Path to the main source file.
   std::string MainFile;
   /// Hash identifying the compilation conditions of the current TU.

diff  --git a/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp 
b/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
index 7477b930188b4f..2b882f8a5e0793 100644
--- a/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
+++ b/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
@@ -24,6 +24,7 @@
 #include "clang/Tooling/DependencyScanning/DependencyScanningService.h"
 #include "clang/Tooling/DependencyScanning/ModuleDepCollector.h"
 #include "clang/Tooling/Tooling.h"
+#include "llvm/ADT/ScopeExit.h"
 #include "llvm/Support/Allocator.h"
 #include "llvm/Support/Error.h"
 #include "llvm/TargetParser/Host.h"
@@ -67,7 +68,7 @@ 

[clang] [llvm] [clang][ScanDeps] Allow PCHs to have different VFS overlays (PR #82294)

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

Bigcheese wrote:

CI failure is a preexisting Flang test failure and a preexisting trailing 
whitespace issue.

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


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

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

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


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

2024-02-23 Thread via cfe-commits

Author: Michael Spencer
Date: 2024-02-23T17:44:32-08:00
New Revision: d42de86eb37b08b3007a67650b3ca73b9ae174b1

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

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

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.

Previous version of this had issues with sed differences between macOS,
Linux, and Windows. This test doesn't check paths, so just don't run
sed.
Other tests should use `sed -E 's:?:/:g'` to get portable behavior.

Windows has different command line parsing behavior than Linux for
compilation databases, so the test has been adjusted to ignore that
difference.

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 

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

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

Bigcheese wrote:

CI failure was a preexisting trailing whitespace issue.

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


[clang] [CLANG][DWARF] Do not emit -ggnu-pubnames for split dwarf version 5. (PR #82840)

2024-02-23 Thread Alexander Yermolovich via cfe-commits

ayermolo wrote:

Changed to tunning.

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


[clang] [CLANG][DWARF] Do not emit -ggnu-pubnames for split dwarf version 5. (PR #82840)

2024-02-23 Thread Alexander Yermolovich via cfe-commits

https://github.com/ayermolo updated 
https://github.com/llvm/llvm-project/pull/82840

>From 714cc804f2716bbd3c666d8922403299e4c19893 Mon Sep 17 00:00:00 2001
From: Alexander Yermolovich 
Date: Fri, 23 Feb 2024 14:52:04 -0800
Subject: [PATCH 1/2] [CLANG][DWARF] Do not emit -ggnu-pubnames for split dwarf
 version 5.

When -gsplit-dwarf is passed in clang emmmits -ggnu-pubnames which results in
.debug_gnu_pubnames/..debug_gnu_pubtypes being generated. For DWARF5 we have
functional .debug_names.

TBH not sure what the right behavior should be. Should we not generate anything
at all by default or generate .debug_names? Doing some archeological digging
initially -gnu-pubnames was always generated to be in line with what gcc does.. 
It was then
changed so that it was generated when split-dwarf was enabled:
https://github.com/llvm/llvm-project/commit/658645241bf0c624d4b7a67c195c239bbc193e3f#diff-bac41c71569f27df21a843bcd74d2e604ed508afbdf14161dfb545c5d228

For LLDB these gnu sections are not useful and just waste space. Maybe a better
check is to be based on tunning?
---
 clang/lib/Driver/ToolChains/Clang.cpp | 7 ---
 clang/test/Driver/split-debug.c   | 1 -
 2 files changed, 4 insertions(+), 4 deletions(-)

diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 6e1b7e8657d0dc..27a5aef17c8d71 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -4479,9 +4479,10 @@ renderDebugOptions(const ToolChain , const Driver , 
const llvm::Triple ,
   options::OPT_gpubnames, options::OPT_gno_pubnames);
   if (DwarfFission != DwarfFissionKind::None ||
   (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC)))
-if (!PubnamesArg ||
-(!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
- !PubnamesArg->getOption().matches(options::OPT_gno_pubnames)))
+if (EffectiveDWARFVersion < 5 &&
+(!PubnamesArg ||
+ (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
+  !PubnamesArg->getOption().matches(options::OPT_gno_pubnames
   CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
options::OPT_gpubnames)
 ? "-gpubnames"
diff --git a/clang/test/Driver/split-debug.c b/clang/test/Driver/split-debug.c
index 968f33b4cc035c..1d5f0fa42fdeea 100644
--- a/clang/test/Driver/split-debug.c
+++ b/clang/test/Driver/split-debug.c
@@ -11,7 +11,6 @@
 // NOINLINE-NOT: "-fsplit-dwarf-inlining"
 // SPLIT-NOT:  "-dumpdir"
 // SPLIT:  "-debug-info-kind=constructor"
-// SPLIT-SAME: "-ggnu-pubnames"
 // SPLIT-SAME: "-split-dwarf-file" "split-debug.dwo" "-split-dwarf-output" 
"split-debug.dwo"
 
 // RUN: %clang -### -c -target wasm32 -gsplit-dwarf -g %s 2>&1 | FileCheck %s 
--check-prefix=SPLIT

>From 8784b440cd3792925179ea1e058b762397bcdf6a Mon Sep 17 00:00:00 2001
From: Alexander Yermolovich 
Date: Fri, 23 Feb 2024 17:35:36 -0800
Subject: [PATCH 2/2] changred to tunning, added test

---
 clang/lib/Driver/ToolChains/Clang.cpp | 2 +-
 clang/test/Driver/split-debug.c   | 6 ++
 2 files changed, 7 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 27a5aef17c8d71..dbfc729bba24c7 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -4479,7 +4479,7 @@ renderDebugOptions(const ToolChain , const Driver , 
const llvm::Triple ,
   options::OPT_gpubnames, options::OPT_gno_pubnames);
   if (DwarfFission != DwarfFissionKind::None ||
   (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC)))
-if (EffectiveDWARFVersion < 5 &&
+if (DebuggerTuning != llvm::DebuggerKind::LLDB &&
 (!PubnamesArg ||
  (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
   !PubnamesArg->getOption().matches(options::OPT_gno_pubnames
diff --git a/clang/test/Driver/split-debug.c b/clang/test/Driver/split-debug.c
index 1d5f0fa42fdeea..a2a3dc02354503 100644
--- a/clang/test/Driver/split-debug.c
+++ b/clang/test/Driver/split-debug.c
@@ -11,6 +11,7 @@
 // NOINLINE-NOT: "-fsplit-dwarf-inlining"
 // SPLIT-NOT:  "-dumpdir"
 // SPLIT:  "-debug-info-kind=constructor"
+// SPLIT-SAME: "-ggnu-pubnames"
 // SPLIT-SAME: "-split-dwarf-file" "split-debug.dwo" "-split-dwarf-output" 
"split-debug.dwo"
 
 // RUN: %clang -### -c -target wasm32 -gsplit-dwarf -g %s 2>&1 | FileCheck %s 
--check-prefix=SPLIT
@@ -123,3 +124,8 @@
 // G1_NOSPLIT: "-debug-info-kind=line-tables-only"
 // G1_NOSPLIT-NOT: "-split-dwarf-file"
 // G1_NOSPLIT-NOT: "-split-dwarf-output"
+
+/// Do not generate -ggnu-pubnames for -glldb
+// RUN: %clang -### -c -target x86_64 -gsplit-dwarf -g -glldb %s 2>&1 | 
FileCheck %s --check-prefixes=GLLDBSPLIT
+
+// GLLDBSPLIT-NOT: "-ggnu-pubnames"

___

[clang] [clang] Use getDefaultArgRange instead of getDefaultArg to retrieve the (PR #79296)

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

https://github.com/sam-mccall approved this pull request.

Sorry for missing this!

Would be nice to have a testcase but I see it's hard to get into the crashing 
state (maybe even not possible via clang).
Seems worthwhile to be robust to such conditions and getDefaultArgRange appears 
less fragile.

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


[clang] Revert "[clang][dataflow] Correctly handle `InitListExpr` of union type." (PR #82856)

2024-02-23 Thread Samira Bazuzi via cfe-commits

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


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

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

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

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

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

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

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

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

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

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

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

[clang] [HLSL] Fix casting asserts (PR #82827)

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

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

>From 15eee3edd9ad834dc46fb5a1053874093b41a65a Mon Sep 17 00:00:00 2001
From: Farzon Lotfi 
Date: Fri, 23 Feb 2024 15:28:13 -0500
Subject: [PATCH 1/2] [HLSL] Fix casting asserts There are two issues here.
 first ICK_Floating_Integral were always defaulting to CK_FloatingToIntegral
 for vectors regardless of  direction of cast. Check was scalar only so added
 a vec float check to the conditional. Second issue was float to int  casts
 were resolving to ICK_Integral_Promotion when they need to be resolving to
 CK_FloatingToIntegral. This was fixed by changing the ordering of conversion
 checks.

This fixes #82826
---
 clang/lib/Sema/SemaExprCXX.cpp|  2 +-
 clang/lib/Sema/SemaOverload.cpp   | 14 +++---
 .../SemaHLSL/VectorOverloadResolution.hlsl| 44 +++
 3 files changed, 52 insertions(+), 8 deletions(-)

diff --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp
index 322bd1c87b1d71..99f8abf77c0cb6 100644
--- a/clang/lib/Sema/SemaExprCXX.cpp
+++ b/clang/lib/Sema/SemaExprCXX.cpp
@@ -4843,7 +4843,7 @@ Sema::PerformImplicitConversion(Expr *From, QualType 
ToType,
  .get();
   break;
 case ICK_Floating_Integral:
-  if (ToType->isRealFloatingType())
+  if (ToType->isRealFloatingType() || ToType->hasFloatingRepresentation())
 From =
 ImpCastExprToType(From, ToType, CK_IntegralToFloating, VK_PRValue,
   /*BasePath=*/nullptr, CCK)
diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index f7645422348b65..ecad2b96816553 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -1884,6 +1884,13 @@ static bool IsVectorElementConversion(Sema , QualType 
FromType,
 return true;
   }
 
+  if ((FromType->isRealFloatingType() && ToType->isIntegralType(S.Context)) ||
+  (FromType->isIntegralOrUnscopedEnumerationType() &&
+   ToType->isRealFloatingType())) {
+ICK = ICK_Floating_Integral;
+return true;
+  }
+
   if (S.IsIntegralPromotion(From, FromType, ToType)) {
 ICK = ICK_Integral_Promotion;
 return true;
@@ -1895,13 +1902,6 @@ static bool IsVectorElementConversion(Sema , QualType 
FromType,
 return true;
   }
 
-  if ((FromType->isRealFloatingType() && ToType->isIntegralType(S.Context)) ||
-  (FromType->isIntegralOrUnscopedEnumerationType() &&
-   ToType->isRealFloatingType())) {
-ICK = ICK_Floating_Integral;
-return true;
-  }
-
   return false;
 }
 
diff --git a/clang/test/SemaHLSL/VectorOverloadResolution.hlsl 
b/clang/test/SemaHLSL/VectorOverloadResolution.hlsl
index e07391f803f899..d8794ef675768b 100644
--- a/clang/test/SemaHLSL/VectorOverloadResolution.hlsl
+++ b/clang/test/SemaHLSL/VectorOverloadResolution.hlsl
@@ -1,4 +1,8 @@
 // RUN: %clang_cc1 -triple dxil-unknown-shadermodel6.6-library -S 
-fnative-half-type -finclude-default-header -o - -ast-dump %s | FileCheck %s
+// RUN: %clang_cc1 -std=hlsl2021 -finclude-default-header -x hlsl -triple \
+// RUN:   dxil-pc-shadermodel6.3-library %s -fnative-half-type \
+// RUN:   -emit-llvm -disable-llvm-passes -O3 -o - | FileCheck %s \ 
+// RUN:   --check-prefixes=CHECKIR
 void Fn(double2 D);
 void Fn(half2 H);
 
@@ -28,3 +32,43 @@ void Fn2(int16_t2 S);
 void Call2(int2 I) {
   Fn2(I);
 }
+
+void Fn3( int64_t2 p0);
+
+// CHECK: FunctionDecl {{.*}} Call3 'void (half2)'
+// CHECK: CallExpr {{.*}} 'void'
+// CHECK-NEXT: ImplicitCastExpr {{.*}} 'void (*)(int64_t2)' 

+// CHECK-NEXT: DeclRefExpr {{.*}} 'void (int64_t2)' lvalue Function {{.*}} 
'Fn3' 'void (int64_t2)'
+// CHECK-NEXT: ImplicitCastExpr {{.*}} 'int64_t2':'long 
__attribute__((ext_vector_type(2)))' 
+// CHECK-NEXT: ImplicitCastExpr {{.*}} 'half2':'half 
__attribute__((ext_vector_type(2)))' 
+// CHECK-NEXT: DeclRefExpr {{.*}} 'half2':'half 
__attribute__((ext_vector_type(2)))' lvalue ParmVar {{.*}} 'p0' 'half2':'half 
__attribute__((ext_vector_type(2)))'
+// CHECKIR: %conv = fptosi <2 x half> %0 to <2 x i64>
+void Call3(half2 p0) {
+  Fn3(p0);
+}
+
+// CHECK: FunctionDecl {{.*}} Call4 'void (float2)'
+// CHECK: CallExpr {{.*}} 'void'
+// CHECK-NEXT: ImplicitCastExpr {{.*}} 'void (*)(int64_t2)' 

+// CHECK-NEXT: DeclRefExpr {{.*}} 'void (int64_t2)' lvalue Function {{.*}} 
'Fn3' 'void (int64_t2)'
+// CHECK-NEXT: ImplicitCastExpr {{.*}} 'int64_t2':'long 
__attribute__((ext_vector_type(2)))' 
+// CHECK-NEXT: ImplicitCastExpr {{.*}} 'float2':'float 
__attribute__((ext_vector_type(2)))' 
+// CHECK-NEXT: DeclRefExpr {{.*}} 'float2':'float 
__attribute__((ext_vector_type(2)))' lvalue ParmVar {{.*}} 'p0' 'float2':'float 
__attribute__((ext_vector_type(2)))'
+// CHECKIR: %conv = fptosi <2 x float> %0 to <2 x i64>
+void Call4(float2 p0) {
+  Fn3(p0);
+}
+
+void Fn4( float2 p0);
+
+// CHECK: FunctionDecl {{.*}} Call5 'void (int64_t2)'
+// CHECK: CallExpr {{.*}} 'void'
+// CHECK-NEXT: ImplicitCastExpr 

[clang] Revert "[clang][dataflow] Correctly handle `InitListExpr` of union type." (PR #82856)

2024-02-23 Thread via cfe-commits

github-actions[bot] wrote:

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


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


[clang] Revert "[clang][dataflow] Correctly handle `InitListExpr` of union type." (PR #82856)

2024-02-23 Thread Samira Bazuzi via cfe-commits

bazuzi wrote:

@ymand Can you merge this?

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


[clang] Revert "[clang][dataflow] Correctly handle `InitListExpr` of union type." (PR #82856)

2024-02-23 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Samira Bazuzi (bazuzi)


Changes

Reverts llvm/llvm-project#82348, which caused crashes when analyzing 
empty InitListExprs for unions.

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


5 Files Affected:

- (modified) clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h 
(+3-6) 
- (modified) clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp (+4-14) 
- (modified) clang/lib/Analysis/FlowSensitive/Transfer.cpp (+11-14) 
- (modified) clang/unittests/Analysis/FlowSensitive/TestingSupport.h (-19) 
- (modified) clang/unittests/Analysis/FlowSensitive/TransferTest.cpp (+2-12) 


``diff
diff --git a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
index b3dc940705f870..0aecc749bf415c 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -753,12 +753,9 @@ RecordStorageLocation *getImplicitObjectLocation(const 
CXXMemberCallExpr ,
 RecordStorageLocation *getBaseObjectLocation(const MemberExpr ,
  const Environment );
 
-/// Returns the fields of a `RecordDecl` that are initialized by an
-/// `InitListExpr`, in the order in which they appear in
-/// `InitListExpr::inits()`.
-/// `Init->getType()` must be a record type.
-std::vector
-getFieldsForInitListExpr(const InitListExpr *InitList);
+/// Returns the fields of `RD` that are initialized by an `InitListExpr`, in 
the
+/// order in which they appear in `InitListExpr::inits()`.
+std::vector getFieldsForInitListExpr(const RecordDecl *RD);
 
 /// Associates a new `RecordValue` with `Loc` and returns the new value.
 RecordValue (RecordStorageLocation , Environment );
diff --git a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp 
b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
index 0cfc26ea952cda..d487944ce92111 100644
--- a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -361,8 +361,8 @@ getFieldsGlobalsAndFuncs(const Stmt , FieldSet ,
 if (const auto *FD = dyn_cast(VD))
   Fields.insert(FD);
   } else if (auto *InitList = dyn_cast()) {
-if (InitList->getType()->isRecordType())
-  for (const auto *FD : getFieldsForInitListExpr(InitList))
+if (RecordDecl *RD = InitList->getType()->getAsRecordDecl())
+  for (const auto *FD : getFieldsForInitListExpr(RD))
 Fields.insert(FD);
   }
 }
@@ -1104,22 +1104,12 @@ RecordStorageLocation *getBaseObjectLocation(const 
MemberExpr ,
   return Env.get(*Base);
 }
 
-std::vector
-getFieldsForInitListExpr(const InitListExpr *InitList) {
-  const RecordDecl *RD = InitList->getType()->getAsRecordDecl();
-  assert(RD != nullptr);
-
-  std::vector Fields;
-
-  if (InitList->getType()->isUnionType()) {
-Fields.push_back(InitList->getInitializedFieldInUnion());
-return Fields;
-  }
-
+std::vector getFieldsForInitListExpr(const RecordDecl *RD) {
   // Unnamed bitfields are only used for padding and do not appear in
   // `InitListExpr`'s inits. However, those fields do appear in `RecordDecl`'s
   // field list, and we thus need to remove them before mapping inits to
   // fields to avoid mapping inits to the wrongs fields.
+  std::vector Fields;
   llvm::copy_if(
   RD->fields(), std::back_inserter(Fields),
   [](const FieldDecl *Field) { return !Field->isUnnamedBitfield(); });
diff --git a/clang/lib/Analysis/FlowSensitive/Transfer.cpp 
b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
index cd1f04e53cff68..fe13e919bddcd8 100644
--- a/clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -663,7 +663,14 @@ class TransferVisitor : public 
ConstStmtVisitor {
   void VisitInitListExpr(const InitListExpr *S) {
 QualType Type = S->getType();
 
-if (!Type->isRecordType()) {
+if (Type->isUnionType()) {
+  // FIXME: Initialize unions properly.
+  if (auto *Val = Env.createValue(Type))
+Env.setValue(*S, *Val);
+  return;
+}
+
+if (!Type->isStructureOrClassType()) {
   // Until array initialization is implemented, we don't need to care about
   // cases where `getNumInits() > 1`.
   if (S->getNumInits() == 1)
@@ -681,9 +688,10 @@ class TransferVisitor : public 
ConstStmtVisitor {
 llvm::DenseMap FieldLocs;
 
 // This only contains the direct fields for the given type.
-std::vector FieldsForInit = getFieldsForInitListExpr(S);
+std::vector FieldsForInit =
+getFieldsForInitListExpr(Type->getAsRecordDecl());
 
-// `S->inits()` contains all the initializer expressions, including the
+// `S->inits()` contains all the initializer epressions, including the
 // ones for direct base classes.
 auto Inits = S->inits();
 size_t InitIdx = 0;
@@ -723,17 +731,6 @@ class 

[clang] Revert "[clang][dataflow] Correctly handle `InitListExpr` of union type." (PR #82856)

2024-02-23 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-analysis

Author: Samira Bazuzi (bazuzi)


Changes

Reverts llvm/llvm-project#82348, which caused crashes when analyzing 
empty InitListExprs for unions.

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


5 Files Affected:

- (modified) clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h 
(+3-6) 
- (modified) clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp (+4-14) 
- (modified) clang/lib/Analysis/FlowSensitive/Transfer.cpp (+11-14) 
- (modified) clang/unittests/Analysis/FlowSensitive/TestingSupport.h (-19) 
- (modified) clang/unittests/Analysis/FlowSensitive/TransferTest.cpp (+2-12) 


``diff
diff --git a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
index b3dc940705f870..0aecc749bf415c 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -753,12 +753,9 @@ RecordStorageLocation *getImplicitObjectLocation(const 
CXXMemberCallExpr ,
 RecordStorageLocation *getBaseObjectLocation(const MemberExpr ,
  const Environment );
 
-/// Returns the fields of a `RecordDecl` that are initialized by an
-/// `InitListExpr`, in the order in which they appear in
-/// `InitListExpr::inits()`.
-/// `Init->getType()` must be a record type.
-std::vector
-getFieldsForInitListExpr(const InitListExpr *InitList);
+/// Returns the fields of `RD` that are initialized by an `InitListExpr`, in 
the
+/// order in which they appear in `InitListExpr::inits()`.
+std::vector getFieldsForInitListExpr(const RecordDecl *RD);
 
 /// Associates a new `RecordValue` with `Loc` and returns the new value.
 RecordValue (RecordStorageLocation , Environment );
diff --git a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp 
b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
index 0cfc26ea952cda..d487944ce92111 100644
--- a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -361,8 +361,8 @@ getFieldsGlobalsAndFuncs(const Stmt , FieldSet ,
 if (const auto *FD = dyn_cast(VD))
   Fields.insert(FD);
   } else if (auto *InitList = dyn_cast()) {
-if (InitList->getType()->isRecordType())
-  for (const auto *FD : getFieldsForInitListExpr(InitList))
+if (RecordDecl *RD = InitList->getType()->getAsRecordDecl())
+  for (const auto *FD : getFieldsForInitListExpr(RD))
 Fields.insert(FD);
   }
 }
@@ -1104,22 +1104,12 @@ RecordStorageLocation *getBaseObjectLocation(const 
MemberExpr ,
   return Env.get(*Base);
 }
 
-std::vector
-getFieldsForInitListExpr(const InitListExpr *InitList) {
-  const RecordDecl *RD = InitList->getType()->getAsRecordDecl();
-  assert(RD != nullptr);
-
-  std::vector Fields;
-
-  if (InitList->getType()->isUnionType()) {
-Fields.push_back(InitList->getInitializedFieldInUnion());
-return Fields;
-  }
-
+std::vector getFieldsForInitListExpr(const RecordDecl *RD) {
   // Unnamed bitfields are only used for padding and do not appear in
   // `InitListExpr`'s inits. However, those fields do appear in `RecordDecl`'s
   // field list, and we thus need to remove them before mapping inits to
   // fields to avoid mapping inits to the wrongs fields.
+  std::vector Fields;
   llvm::copy_if(
   RD->fields(), std::back_inserter(Fields),
   [](const FieldDecl *Field) { return !Field->isUnnamedBitfield(); });
diff --git a/clang/lib/Analysis/FlowSensitive/Transfer.cpp 
b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
index cd1f04e53cff68..fe13e919bddcd8 100644
--- a/clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -663,7 +663,14 @@ class TransferVisitor : public 
ConstStmtVisitor {
   void VisitInitListExpr(const InitListExpr *S) {
 QualType Type = S->getType();
 
-if (!Type->isRecordType()) {
+if (Type->isUnionType()) {
+  // FIXME: Initialize unions properly.
+  if (auto *Val = Env.createValue(Type))
+Env.setValue(*S, *Val);
+  return;
+}
+
+if (!Type->isStructureOrClassType()) {
   // Until array initialization is implemented, we don't need to care about
   // cases where `getNumInits() > 1`.
   if (S->getNumInits() == 1)
@@ -681,9 +688,10 @@ class TransferVisitor : public 
ConstStmtVisitor {
 llvm::DenseMap FieldLocs;
 
 // This only contains the direct fields for the given type.
-std::vector FieldsForInit = getFieldsForInitListExpr(S);
+std::vector FieldsForInit =
+getFieldsForInitListExpr(Type->getAsRecordDecl());
 
-// `S->inits()` contains all the initializer expressions, including the
+// `S->inits()` contains all the initializer epressions, including the
 // ones for direct base classes.
 auto Inits = S->inits();
 size_t InitIdx = 0;
@@ -723,17 +731,6 

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

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


@@ -0,0 +1,989 @@
+//===--- SemaAPINotes.cpp - API Notes Handling 
===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file implements the mapping from API notes to declaration attributes.
+//
+//===--===//
+
+#include "clang/APINotes/APINotesReader.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/DeclObjC.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Lex/Lexer.h"
+#include "clang/Sema/SemaInternal.h"
+
+using namespace clang;
+
+namespace {
+enum class IsActive_t : bool { Inactive, Active };
+enum class IsReplacement_t : bool { Original, Replacement };
+
+struct VersionedInfoMetadata {
+  /// An empty version refers to unversioned metadata.
+  VersionTuple Version;
+  unsigned IsActive : 1;
+  unsigned IsReplacement : 1;
+
+  VersionedInfoMetadata(VersionTuple Version, IsActive_t Active,
+IsReplacement_t Replacement)
+  : Version(Version), IsActive(Active == IsActive_t::Active),
+IsReplacement(Replacement == IsReplacement_t::Replacement) {}
+};
+} // end anonymous namespace
+
+/// Determine whether this is a multi-level pointer type.
+static bool isIndirectPointerType(QualType Type) {
+  QualType Pointee = Type->getPointeeType();
+  if (Pointee.isNull())
+return false;
+
+  return Pointee->isAnyPointerType() || Pointee->isObjCObjectPointerType() ||
+ Pointee->isMemberPointerType();
+}
+
+/// Apply nullability to the given declaration.
+static void applyNullability(Sema , Decl *D, NullabilityKind Nullability,
+ VersionedInfoMetadata Metadata) {
+  if (!Metadata.IsActive)
+return;
+
+  auto IsUnmodified = [&](Decl *D, QualType QT,
+  NullabilityKind Nullability) -> bool {
+QualType Original = QT;
+S.CheckImplicitNullabilityTypeSpecifier(QT, Nullability, D->getLocation(),
+isa(D),
+/*OverrideExisting=*/true);
+return QT.getTypePtr() == Original.getTypePtr();
+  };
+
+  if (auto Function = dyn_cast(D)) {
+if (IsUnmodified(D, Function->getReturnType(), Nullability)) {

egorzhdan wrote:

Oops, my bad, fixed.

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


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

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

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

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

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

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

[clang] Revert "[clang][dataflow] Correctly handle `InitListExpr` of union type." (PR #82856)

2024-02-23 Thread Samira Bazuzi via cfe-commits

https://github.com/bazuzi created 
https://github.com/llvm/llvm-project/pull/82856

Reverts llvm/llvm-project#82348, which caused crashes when analyzing empty 
InitListExprs for unions.

>From ae17f89f38d56c2aa9feaa1ebfc7a641b41dc068 Mon Sep 17 00:00:00 2001
From: Samira Bazuzi 
Date: Fri, 23 Feb 2024 20:12:33 -0500
Subject: [PATCH] =?UTF-8?q?Revert=20"[clang][dataflow]=20Correctly=20handl?=
 =?UTF-8?q?e=20`InitListExpr`=20of=20union=20type.=20(#82=E2=80=A6"?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

This reverts commit 4725993f1a812c86b9ad79d229a015d0216ff550.
---
 .../FlowSensitive/DataflowEnvironment.h   |  9 +++
 .../FlowSensitive/DataflowEnvironment.cpp | 18 +++--
 clang/lib/Analysis/FlowSensitive/Transfer.cpp | 25 ---
 .../Analysis/FlowSensitive/TestingSupport.h   | 19 --
 .../Analysis/FlowSensitive/TransferTest.cpp   | 14 ++-
 5 files changed, 20 insertions(+), 65 deletions(-)

diff --git a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
index b3dc940705f870..0aecc749bf415c 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -753,12 +753,9 @@ RecordStorageLocation *getImplicitObjectLocation(const 
CXXMemberCallExpr ,
 RecordStorageLocation *getBaseObjectLocation(const MemberExpr ,
  const Environment );
 
-/// Returns the fields of a `RecordDecl` that are initialized by an
-/// `InitListExpr`, in the order in which they appear in
-/// `InitListExpr::inits()`.
-/// `Init->getType()` must be a record type.
-std::vector
-getFieldsForInitListExpr(const InitListExpr *InitList);
+/// Returns the fields of `RD` that are initialized by an `InitListExpr`, in 
the
+/// order in which they appear in `InitListExpr::inits()`.
+std::vector getFieldsForInitListExpr(const RecordDecl *RD);
 
 /// Associates a new `RecordValue` with `Loc` and returns the new value.
 RecordValue (RecordStorageLocation , Environment );
diff --git a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp 
b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
index 0cfc26ea952cda..d487944ce92111 100644
--- a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -361,8 +361,8 @@ getFieldsGlobalsAndFuncs(const Stmt , FieldSet ,
 if (const auto *FD = dyn_cast(VD))
   Fields.insert(FD);
   } else if (auto *InitList = dyn_cast()) {
-if (InitList->getType()->isRecordType())
-  for (const auto *FD : getFieldsForInitListExpr(InitList))
+if (RecordDecl *RD = InitList->getType()->getAsRecordDecl())
+  for (const auto *FD : getFieldsForInitListExpr(RD))
 Fields.insert(FD);
   }
 }
@@ -1104,22 +1104,12 @@ RecordStorageLocation *getBaseObjectLocation(const 
MemberExpr ,
   return Env.get(*Base);
 }
 
-std::vector
-getFieldsForInitListExpr(const InitListExpr *InitList) {
-  const RecordDecl *RD = InitList->getType()->getAsRecordDecl();
-  assert(RD != nullptr);
-
-  std::vector Fields;
-
-  if (InitList->getType()->isUnionType()) {
-Fields.push_back(InitList->getInitializedFieldInUnion());
-return Fields;
-  }
-
+std::vector getFieldsForInitListExpr(const RecordDecl *RD) {
   // Unnamed bitfields are only used for padding and do not appear in
   // `InitListExpr`'s inits. However, those fields do appear in `RecordDecl`'s
   // field list, and we thus need to remove them before mapping inits to
   // fields to avoid mapping inits to the wrongs fields.
+  std::vector Fields;
   llvm::copy_if(
   RD->fields(), std::back_inserter(Fields),
   [](const FieldDecl *Field) { return !Field->isUnnamedBitfield(); });
diff --git a/clang/lib/Analysis/FlowSensitive/Transfer.cpp 
b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
index cd1f04e53cff68..fe13e919bddcd8 100644
--- a/clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -663,7 +663,14 @@ class TransferVisitor : public 
ConstStmtVisitor {
   void VisitInitListExpr(const InitListExpr *S) {
 QualType Type = S->getType();
 
-if (!Type->isRecordType()) {
+if (Type->isUnionType()) {
+  // FIXME: Initialize unions properly.
+  if (auto *Val = Env.createValue(Type))
+Env.setValue(*S, *Val);
+  return;
+}
+
+if (!Type->isStructureOrClassType()) {
   // Until array initialization is implemented, we don't need to care about
   // cases where `getNumInits() > 1`.
   if (S->getNumInits() == 1)
@@ -681,9 +688,10 @@ class TransferVisitor : public 
ConstStmtVisitor {
 llvm::DenseMap FieldLocs;
 
 // This only contains the direct fields for the given type.
-std::vector FieldsForInit = getFieldsForInitListExpr(S);
+std::vector FieldsForInit =
+

[clang] [clang-tools-extra] [compiler-rt] [flang] [libclc] [libcxx] [lld] [lldb] [llvm] [NFC] Remove trailing whitespace across all non-test related files (PR #82838)

2024-02-23 Thread David Blaikie via cfe-commits

dwblaikie wrote:

The dev policy says "Avoid committing formatting- or whitespace-only changes 
outside of code you plan to make subsequent changes to." - I think it's 
reasonable to consider changing this, but probably under the "clang-format 
everything" or a similar discussion (broad discussion before we worry about 
making pull requests

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


[clang] [clang-tools-extra] [compiler-rt] [flang] [libclc] [libcxx] [lld] [lldb] [llvm] [NFC] Remove trailing whitespace across all non-test related files (PR #82838)

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

jrtc27 wrote:

Also this is the kind of commit that should really be done by a core trusted 
member of the community. It's way too easy to hide something nefarious (not 
that I'm accusing you of that, just that we always need to be vigilant) in an 
8k+ diff, and it's not much fun to review that code. Also it's best when people 
provide the scripts used to do these kinds of mass changes; that (a) lets 
people verify what you did by auditing the script and running it themselves (b) 
lets downstreams easily perform the same change on their forks.

The fact that this is a +8347 -8382 diff also confuses me; I would expect the 
number of lines to remain constant, but maybe you're including trailing blank 
lines as trailing whitespace?..

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


[clang] [clang-tools-extra] [compiler-rt] [flang] [libclc] [libcxx] [lld] [lldb] [llvm] [NFC] Remove trailing whitespace across all non-test related files (PR #82838)

2024-02-23 Thread Alexander Richardson via cfe-commits

arichardson wrote:

This will cause huge merge conflicts for all downstreams. While they are easy 
to resolve it can be quite annoying. I think we should just do this as part of 
the global clang-format.

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


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

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

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

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

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

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

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

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

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

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

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

[clang] [clang] Update -Wformat warnings for fixed-point format specifiers (PR #82855)

2024-02-23 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: None (PiJoules)


Changes

ISO/IEC TR 18037 defines %r, %R, %k, and %K for fixed point format specifiers. 
-Wformat should not warn on these when they are provided.

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


6 Files Affected:

- (modified) clang/include/clang/AST/ASTContext.h (+4) 
- (modified) clang/include/clang/AST/FormatString.h (+11) 
- (modified) clang/lib/AST/ASTContext.cpp (+36) 
- (modified) clang/lib/AST/FormatString.cpp (+25) 
- (modified) clang/lib/AST/PrintfFormatString.cpp (+86-3) 
- (added) clang/test/Sema/format-fixed-point.c (+134) 


``diff
diff --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index 12ce9af1e53f63..ff6b64c7f72d57 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -2981,6 +2981,10 @@ class ASTContext : public RefCountedBase {
   // corresponding saturated type for a given fixed point type.
   QualType getCorrespondingSaturatedType(QualType Ty) const;
 
+  // Per ISO N1169, this method accepts fixed point types and returns the
+  // corresponding non-saturated type for a given fixed point type.
+  QualType getCorrespondingUnsaturatedType(QualType Ty) const;
+
   // This method accepts fixed point types and returns the corresponding signed
   // type. Unlike getCorrespondingUnsignedType(), this only accepts unsigned
   // fixed point types because there are unsigned integer types like bool and
diff --git a/clang/include/clang/AST/FormatString.h 
b/clang/include/clang/AST/FormatString.h
index 5c4ad9baaef608..e2232fb4a47153 100644
--- a/clang/include/clang/AST/FormatString.h
+++ b/clang/include/clang/AST/FormatString.h
@@ -171,6 +171,14 @@ class ConversionSpecifier {
 
 ZArg, // MS extension
 
+// ISO/IEC TR 18037 (fixed-point) specific specifiers.
+kArg, // %k for signed accum types
+KArg, // %K for unsigned accum types
+rArg, // %r for signed fract types
+RArg, // %R for unsigned fract types
+FixedPointArgBeg = kArg,
+FixedPointArgEnd = RArg,
+
 // Objective-C specific specifiers.
 ObjCObjArg, // '@'
 ObjCBeg = ObjCObjArg,
@@ -237,6 +245,9 @@ class ConversionSpecifier {
   bool isDoubleArg() const {
 return kind >= DoubleArgBeg && kind <= DoubleArgEnd;
   }
+  bool isFixedPointArg() const {
+return kind >= FixedPointArgBeg && kind <= FixedPointArgEnd;
+  }
 
   const char *toString() const;
 
diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index c475c841233c59..5a8fae76a43a4d 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -13314,6 +13314,42 @@ QualType ASTContext::getCommonSugaredType(QualType X, 
QualType Y,
   return R;
 }
 
+QualType ASTContext::getCorrespondingUnsaturatedType(QualType Ty) const {
+  assert(Ty->isFixedPointType());
+
+  if (Ty->isUnsaturatedFixedPointType())
+return Ty;
+
+  switch (Ty->castAs()->getKind()) {
+  default:
+llvm_unreachable("Not a saturated fixed point type!");
+  case BuiltinType::SatShortAccum:
+return ShortAccumTy;
+  case BuiltinType::SatAccum:
+return AccumTy;
+  case BuiltinType::SatLongAccum:
+return LongAccumTy;
+  case BuiltinType::SatUShortAccum:
+return UnsignedShortAccumTy;
+  case BuiltinType::SatUAccum:
+return UnsignedAccumTy;
+  case BuiltinType::SatULongAccum:
+return UnsignedLongAccumTy;
+  case BuiltinType::SatShortFract:
+return ShortFractTy;
+  case BuiltinType::SatFract:
+return FractTy;
+  case BuiltinType::SatLongFract:
+return LongFractTy;
+  case BuiltinType::SatUShortFract:
+return UnsignedShortFractTy;
+  case BuiltinType::SatUFract:
+return UnsignedFractTy;
+  case BuiltinType::SatULongFract:
+return UnsignedLongFractTy;
+  }
+}
+
 QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
   assert(Ty->isFixedPointType());
 
diff --git a/clang/lib/AST/FormatString.cpp b/clang/lib/AST/FormatString.cpp
index c5d14b4af7ff15..0c80ad109ccbb2 100644
--- a/clang/lib/AST/FormatString.cpp
+++ b/clang/lib/AST/FormatString.cpp
@@ -403,6 +403,10 @@ ArgType::matchesType(ASTContext , QualType argTy) const {
 else if (ETy->isUnscopedEnumerationType())
   argTy = ETy->getDecl()->getIntegerType();
   }
+
+  if (argTy->isSaturatedFixedPointType())
+argTy = C.getCorrespondingUnsaturatedType(argTy);
+
   argTy = C.getCanonicalType(argTy).getUnqualifiedType();
 
   if (T == argTy)
@@ -761,6 +765,16 @@ const char *ConversionSpecifier::toString() const {
 
   // MS specific specifiers.
   case ZArg: return "Z";
+
+  // ISO/IEC TR 18037 (fixed-point) specific specifiers.
+  case rArg:
+return "r";
+  case RArg:
+return "R";
+  case kArg:
+return "k";
+  case KArg:
+return "K";
   }
   return nullptr;
 }
@@ -825,6 +839,9 @@ bool FormatSpecifier::hasValidLengthModifier(const 
TargetInfo ,
   if (LO.OpenCL && CS.isDoubleArg())
  

[clang] [clang] Update -Wformat warnings for fixed-point format specifiers (PR #82855)

2024-02-23 Thread via cfe-commits

https://github.com/PiJoules created 
https://github.com/llvm/llvm-project/pull/82855

ISO/IEC TR 18037 defines %r, %R, %k, and %K for fixed point format specifiers. 
-Wformat should not warn on these when they are provided.

>From 6bf764e4d00a8ff00c9a810d4ae0ccd4ca537a2c Mon Sep 17 00:00:00 2001
From: Leonard Chan 
Date: Fri, 23 Feb 2024 16:57:58 -0800
Subject: [PATCH] [clang] Update -Wformat warnings for fixed-point format
 specifiers

ISO/IEC TR 18037 defines %r, %R, %k, and %K for fixed point format
specifiers. -Wformat should not warn on these when they are provided.
---
 clang/include/clang/AST/ASTContext.h   |   4 +
 clang/include/clang/AST/FormatString.h |  11 ++
 clang/lib/AST/ASTContext.cpp   |  36 +++
 clang/lib/AST/FormatString.cpp |  25 +
 clang/lib/AST/PrintfFormatString.cpp   |  89 +++-
 clang/test/Sema/format-fixed-point.c   | 134 +
 6 files changed, 296 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/Sema/format-fixed-point.c

diff --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index 12ce9af1e53f63..ff6b64c7f72d57 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -2981,6 +2981,10 @@ class ASTContext : public RefCountedBase {
   // corresponding saturated type for a given fixed point type.
   QualType getCorrespondingSaturatedType(QualType Ty) const;
 
+  // Per ISO N1169, this method accepts fixed point types and returns the
+  // corresponding non-saturated type for a given fixed point type.
+  QualType getCorrespondingUnsaturatedType(QualType Ty) const;
+
   // This method accepts fixed point types and returns the corresponding signed
   // type. Unlike getCorrespondingUnsignedType(), this only accepts unsigned
   // fixed point types because there are unsigned integer types like bool and
diff --git a/clang/include/clang/AST/FormatString.h 
b/clang/include/clang/AST/FormatString.h
index 5c4ad9baaef608..e2232fb4a47153 100644
--- a/clang/include/clang/AST/FormatString.h
+++ b/clang/include/clang/AST/FormatString.h
@@ -171,6 +171,14 @@ class ConversionSpecifier {
 
 ZArg, // MS extension
 
+// ISO/IEC TR 18037 (fixed-point) specific specifiers.
+kArg, // %k for signed accum types
+KArg, // %K for unsigned accum types
+rArg, // %r for signed fract types
+RArg, // %R for unsigned fract types
+FixedPointArgBeg = kArg,
+FixedPointArgEnd = RArg,
+
 // Objective-C specific specifiers.
 ObjCObjArg, // '@'
 ObjCBeg = ObjCObjArg,
@@ -237,6 +245,9 @@ class ConversionSpecifier {
   bool isDoubleArg() const {
 return kind >= DoubleArgBeg && kind <= DoubleArgEnd;
   }
+  bool isFixedPointArg() const {
+return kind >= FixedPointArgBeg && kind <= FixedPointArgEnd;
+  }
 
   const char *toString() const;
 
diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index c475c841233c59..5a8fae76a43a4d 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -13314,6 +13314,42 @@ QualType ASTContext::getCommonSugaredType(QualType X, 
QualType Y,
   return R;
 }
 
+QualType ASTContext::getCorrespondingUnsaturatedType(QualType Ty) const {
+  assert(Ty->isFixedPointType());
+
+  if (Ty->isUnsaturatedFixedPointType())
+return Ty;
+
+  switch (Ty->castAs()->getKind()) {
+  default:
+llvm_unreachable("Not a saturated fixed point type!");
+  case BuiltinType::SatShortAccum:
+return ShortAccumTy;
+  case BuiltinType::SatAccum:
+return AccumTy;
+  case BuiltinType::SatLongAccum:
+return LongAccumTy;
+  case BuiltinType::SatUShortAccum:
+return UnsignedShortAccumTy;
+  case BuiltinType::SatUAccum:
+return UnsignedAccumTy;
+  case BuiltinType::SatULongAccum:
+return UnsignedLongAccumTy;
+  case BuiltinType::SatShortFract:
+return ShortFractTy;
+  case BuiltinType::SatFract:
+return FractTy;
+  case BuiltinType::SatLongFract:
+return LongFractTy;
+  case BuiltinType::SatUShortFract:
+return UnsignedShortFractTy;
+  case BuiltinType::SatUFract:
+return UnsignedFractTy;
+  case BuiltinType::SatULongFract:
+return UnsignedLongFractTy;
+  }
+}
+
 QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
   assert(Ty->isFixedPointType());
 
diff --git a/clang/lib/AST/FormatString.cpp b/clang/lib/AST/FormatString.cpp
index c5d14b4af7ff15..0c80ad109ccbb2 100644
--- a/clang/lib/AST/FormatString.cpp
+++ b/clang/lib/AST/FormatString.cpp
@@ -403,6 +403,10 @@ ArgType::matchesType(ASTContext , QualType argTy) const {
 else if (ETy->isUnscopedEnumerationType())
   argTy = ETy->getDecl()->getIntegerType();
   }
+
+  if (argTy->isSaturatedFixedPointType())
+argTy = C.getCorrespondingUnsaturatedType(argTy);
+
   argTy = C.getCanonicalType(argTy).getUnqualifiedType();
 
   if (T == argTy)
@@ -761,6 +765,16 @@ const char *ConversionSpecifier::toString() const {
 
   // MS specific 

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

2024-02-23 Thread Saleem Abdulrasool via cfe-commits


@@ -0,0 +1,989 @@
+//===--- SemaAPINotes.cpp - API Notes Handling 
===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file implements the mapping from API notes to declaration attributes.
+//
+//===--===//
+
+#include "clang/APINotes/APINotesReader.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/DeclObjC.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Lex/Lexer.h"
+#include "clang/Sema/SemaInternal.h"
+
+using namespace clang;
+
+namespace {
+enum class IsActive_t : bool { Inactive, Active };
+enum class IsReplacement_t : bool { Original, Replacement };
+
+struct VersionedInfoMetadata {
+  /// An empty version refers to unversioned metadata.
+  VersionTuple Version;
+  unsigned IsActive : 1;
+  unsigned IsReplacement : 1;
+
+  VersionedInfoMetadata(VersionTuple Version, IsActive_t Active,
+IsReplacement_t Replacement)
+  : Version(Version), IsActive(Active == IsActive_t::Active),
+IsReplacement(Replacement == IsReplacement_t::Replacement) {}
+};
+} // end anonymous namespace
+
+/// Determine whether this is a multi-level pointer type.
+static bool isIndirectPointerType(QualType Type) {
+  QualType Pointee = Type->getPointeeType();
+  if (Pointee.isNull())
+return false;
+
+  return Pointee->isAnyPointerType() || Pointee->isObjCObjectPointerType() ||
+ Pointee->isMemberPointerType();
+}
+
+/// Apply nullability to the given declaration.
+static void applyNullability(Sema , Decl *D, NullabilityKind Nullability,
+ VersionedInfoMetadata Metadata) {
+  if (!Metadata.IsActive)
+return;
+
+  auto IsUnmodified = [&](Decl *D, QualType QT,
+  NullabilityKind Nullability) -> bool {
+QualType Original = QT;
+S.CheckImplicitNullabilityTypeSpecifier(QT, Nullability, D->getLocation(),
+isa(D),
+/*OverrideExisting=*/true);
+return QT.getTypePtr() == Original.getTypePtr();
+  };
+
+  if (auto Function = dyn_cast(D)) {
+if (IsUnmodified(D, Function->getReturnType(), Nullability)) {
+  QualType FnType = Function->getType();
+  Function->setType(FnType);
+}
+  } else if (auto Method = dyn_cast(D)) {
+QualType Type = Method->getReturnType();
+if (IsUnmodified(D, Type, Nullability)) {
+  Method->setReturnType(Type);
+
+  // Make it a context-sensitive keyword if we can.
+  if (!isIndirectPointerType(Type))
+Method->setObjCDeclQualifier(Decl::ObjCDeclQualifier(
+Method->getObjCDeclQualifier() | Decl::OBJC_TQ_CSNullability));
+}
+  } else if (auto Value = dyn_cast(D)) {
+QualType Type = Value->getType();
+if (IsUnmodified(D, Type, Nullability)) {

compnerd wrote:

And here

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


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

2024-02-23 Thread Saleem Abdulrasool via cfe-commits


@@ -0,0 +1,989 @@
+//===--- SemaAPINotes.cpp - API Notes Handling 
===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file implements the mapping from API notes to declaration attributes.
+//
+//===--===//
+
+#include "clang/APINotes/APINotesReader.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/DeclObjC.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Lex/Lexer.h"
+#include "clang/Sema/SemaInternal.h"
+
+using namespace clang;
+
+namespace {
+enum class IsActive_t : bool { Inactive, Active };
+enum class IsReplacement_t : bool { Original, Replacement };
+
+struct VersionedInfoMetadata {
+  /// An empty version refers to unversioned metadata.
+  VersionTuple Version;
+  unsigned IsActive : 1;
+  unsigned IsReplacement : 1;
+
+  VersionedInfoMetadata(VersionTuple Version, IsActive_t Active,
+IsReplacement_t Replacement)
+  : Version(Version), IsActive(Active == IsActive_t::Active),
+IsReplacement(Replacement == IsReplacement_t::Replacement) {}
+};
+} // end anonymous namespace
+
+/// Determine whether this is a multi-level pointer type.
+static bool isIndirectPointerType(QualType Type) {
+  QualType Pointee = Type->getPointeeType();
+  if (Pointee.isNull())
+return false;
+
+  return Pointee->isAnyPointerType() || Pointee->isObjCObjectPointerType() ||
+ Pointee->isMemberPointerType();
+}
+
+/// Apply nullability to the given declaration.
+static void applyNullability(Sema , Decl *D, NullabilityKind Nullability,
+ VersionedInfoMetadata Metadata) {
+  if (!Metadata.IsActive)
+return;
+
+  auto IsUnmodified = [&](Decl *D, QualType QT,
+  NullabilityKind Nullability) -> bool {
+QualType Original = QT;
+S.CheckImplicitNullabilityTypeSpecifier(QT, Nullability, D->getLocation(),
+isa(D),
+/*OverrideExisting=*/true);
+return QT.getTypePtr() == Original.getTypePtr();
+  };
+
+  if (auto Function = dyn_cast(D)) {
+if (IsUnmodified(D, Function->getReturnType(), Nullability)) {
+  QualType FnType = Function->getType();
+  Function->setType(FnType);
+}
+  } else if (auto Method = dyn_cast(D)) {
+QualType Type = Method->getReturnType();
+if (IsUnmodified(D, Type, Nullability)) {
+  Method->setReturnType(Type);
+
+  // Make it a context-sensitive keyword if we can.
+  if (!isIndirectPointerType(Type))
+Method->setObjCDeclQualifier(Decl::ObjCDeclQualifier(
+Method->getObjCDeclQualifier() | Decl::OBJC_TQ_CSNullability));
+}
+  } else if (auto Value = dyn_cast(D)) {
+QualType Type = Value->getType();
+if (IsUnmodified(D, Type, Nullability)) {
+  Value->setType(Type);
+
+  // Make it a context-sensitive keyword if we can.
+  if (auto Parm = dyn_cast(D)) {
+if (Parm->isObjCMethodParameter() && !isIndirectPointerType(Type))
+  Parm->setObjCDeclQualifier(Decl::ObjCDeclQualifier(
+  Parm->getObjCDeclQualifier() | Decl::OBJC_TQ_CSNullability));
+  }
+}
+  } else if (auto Property = dyn_cast(D)) {
+QualType Type = Property->getType();
+if (IsUnmodified(D, Type, Nullability)) {

compnerd wrote:

And here

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


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

2024-02-23 Thread Saleem Abdulrasool via cfe-commits


@@ -0,0 +1,989 @@
+//===--- SemaAPINotes.cpp - API Notes Handling 
===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file implements the mapping from API notes to declaration attributes.
+//
+//===--===//
+
+#include "clang/APINotes/APINotesReader.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/DeclObjC.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Lex/Lexer.h"
+#include "clang/Sema/SemaInternal.h"
+
+using namespace clang;
+
+namespace {
+enum class IsActive_t : bool { Inactive, Active };
+enum class IsReplacement_t : bool { Original, Replacement };
+
+struct VersionedInfoMetadata {
+  /// An empty version refers to unversioned metadata.
+  VersionTuple Version;
+  unsigned IsActive : 1;
+  unsigned IsReplacement : 1;
+
+  VersionedInfoMetadata(VersionTuple Version, IsActive_t Active,
+IsReplacement_t Replacement)
+  : Version(Version), IsActive(Active == IsActive_t::Active),
+IsReplacement(Replacement == IsReplacement_t::Replacement) {}
+};
+} // end anonymous namespace
+
+/// Determine whether this is a multi-level pointer type.
+static bool isIndirectPointerType(QualType Type) {
+  QualType Pointee = Type->getPointeeType();
+  if (Pointee.isNull())
+return false;
+
+  return Pointee->isAnyPointerType() || Pointee->isObjCObjectPointerType() ||
+ Pointee->isMemberPointerType();
+}
+
+/// Apply nullability to the given declaration.
+static void applyNullability(Sema , Decl *D, NullabilityKind Nullability,
+ VersionedInfoMetadata Metadata) {
+  if (!Metadata.IsActive)
+return;
+
+  auto IsUnmodified = [&](Decl *D, QualType QT,
+  NullabilityKind Nullability) -> bool {
+QualType Original = QT;
+S.CheckImplicitNullabilityTypeSpecifier(QT, Nullability, D->getLocation(),
+isa(D),
+/*OverrideExisting=*/true);
+return QT.getTypePtr() == Original.getTypePtr();
+  };
+
+  if (auto Function = dyn_cast(D)) {
+if (IsUnmodified(D, Function->getReturnType(), Nullability)) {

compnerd wrote:

Wait if there is no change to the nullability, why reset the type?

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


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

2024-02-23 Thread Saleem Abdulrasool via cfe-commits


@@ -0,0 +1,989 @@
+//===--- SemaAPINotes.cpp - API Notes Handling 
===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file implements the mapping from API notes to declaration attributes.
+//
+//===--===//
+
+#include "clang/APINotes/APINotesReader.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/DeclObjC.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Lex/Lexer.h"
+#include "clang/Sema/SemaInternal.h"
+
+using namespace clang;
+
+namespace {
+enum class IsActive_t : bool { Inactive, Active };
+enum class IsReplacement_t : bool { Original, Replacement };
+
+struct VersionedInfoMetadata {
+  /// An empty version refers to unversioned metadata.
+  VersionTuple Version;
+  unsigned IsActive : 1;
+  unsigned IsReplacement : 1;
+
+  VersionedInfoMetadata(VersionTuple Version, IsActive_t Active,
+IsReplacement_t Replacement)
+  : Version(Version), IsActive(Active == IsActive_t::Active),
+IsReplacement(Replacement == IsReplacement_t::Replacement) {}
+};
+} // end anonymous namespace
+
+/// Determine whether this is a multi-level pointer type.
+static bool isIndirectPointerType(QualType Type) {
+  QualType Pointee = Type->getPointeeType();
+  if (Pointee.isNull())
+return false;
+
+  return Pointee->isAnyPointerType() || Pointee->isObjCObjectPointerType() ||
+ Pointee->isMemberPointerType();
+}
+
+/// Apply nullability to the given declaration.
+static void applyNullability(Sema , Decl *D, NullabilityKind Nullability,
+ VersionedInfoMetadata Metadata) {
+  if (!Metadata.IsActive)
+return;
+
+  auto IsUnmodified = [&](Decl *D, QualType QT,
+  NullabilityKind Nullability) -> bool {
+QualType Original = QT;
+S.CheckImplicitNullabilityTypeSpecifier(QT, Nullability, D->getLocation(),
+isa(D),
+/*OverrideExisting=*/true);
+return QT.getTypePtr() == Original.getTypePtr();
+  };
+
+  if (auto Function = dyn_cast(D)) {
+if (IsUnmodified(D, Function->getReturnType(), Nullability)) {
+  QualType FnType = Function->getType();
+  Function->setType(FnType);
+}
+  } else if (auto Method = dyn_cast(D)) {
+QualType Type = Method->getReturnType();
+if (IsUnmodified(D, Type, Nullability)) {

compnerd wrote:

Similar

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


[clang] [Driver] Allow -fbasic-block-address-map for AArch64 ELF (PR #82662)

2024-02-23 Thread Daniel Hoekwater via cfe-commits

https://github.com/dhoekwater updated 
https://github.com/llvm/llvm-project/pull/82662

>From 1072e0bc65a4d658fb4b0d19b8dad998eee60e31 Mon Sep 17 00:00:00 2001
From: Daniel Hoekwater 
Date: Thu, 22 Feb 2024 17:39:15 +
Subject: [PATCH] [Driver] Allow -fbasic-block-address-map for AArch64 ELF

Emitting the basic block address map with
`-fbasic-block-sections=labels` is allowed for AArch64 ELF since
7eaf94fefa1250fc8a46982cea8ce99abacae11f. Allow doing so with
`-fbasic-block-address-map`.
---
 clang/lib/Driver/ToolChains/Clang.cpp   | 2 +-
 clang/test/Driver/basic-block-address-map.c | 1 +
 2 files changed, 2 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 6e1b7e8657d0dc..66c3a237c12117 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -5958,7 +5958,7 @@ void Clang::ConstructJob(Compilation , const JobAction 
,
 
   if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_address_map,
options::OPT_fno_basic_block_address_map)) {
-if (Triple.isX86() && Triple.isOSBinFormatELF()) {
+if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF()) {
   if (A->getOption().matches(options::OPT_fbasic_block_address_map))
 A->render(Args, CmdArgs);
 } else {
diff --git a/clang/test/Driver/basic-block-address-map.c 
b/clang/test/Driver/basic-block-address-map.c
index 022f972b412d6b..d561d1771cc9a0 100644
--- a/clang/test/Driver/basic-block-address-map.c
+++ b/clang/test/Driver/basic-block-address-map.c
@@ -1,4 +1,5 @@
 // RUN: %clang -### -target x86_64 -fbasic-block-address-map %s -S 2>&1 | 
FileCheck -check-prefix=CHECK-PRESENT %s
+// RUN: %clang -### -target aarch64 -fbasic-block-address-map %s -S 2>&1 | 
FileCheck -check-prefix=CHECK-PRESENT %s
 // CHECK-PRESENT: -fbasic-block-address-map
 
 // RUN: %clang -### -target x86_64 -fno-basic-block-address-map %s -S 2>&1 | 
FileCheck %s --check-prefix=CHECK-ABSENT

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


[clang] [CLANG][DWARF] Do not emit -ggnu-pubnames for split dwarf version 5. (PR #82840)

2024-02-23 Thread Greg Clayton via cfe-commits

clayborg wrote:

I just noticed the naming difference. I am thinking of the standard older 
`.debug_pubnames` and `.debug_pubtypes`. Are the `.debug_gnu_pubnames` and 
`.debug_gnu_pubtypes` more complete and usable by debuggers? If so, then we 
should use the `-dlldb` to disable these GNU specific pubnames and pubtypes 
sections. And ensure that `-ggdb` enables these if GDB still uses them and if 
it doesn't support `.debug_names` very well.

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


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

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


@@ -0,0 +1,1014 @@
+//===--- SemaAPINotes.cpp - API Notes Handling 
===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file implements the mapping from API notes to declaration attributes.
+//
+//===--===//
+
+#include "clang/APINotes/APINotesReader.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/DeclObjC.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Lex/Lexer.h"
+#include "clang/Sema/SemaInternal.h"
+
+using namespace clang;
+
+namespace {
+enum IsActive_t : bool { IsNotActive, IsActive };
+enum IsReplacement_t : bool { IsNotReplacement, IsReplacement };
+
+struct VersionedInfoMetadata {
+  /// An empty version refers to unversioned metadata.
+  VersionTuple Version;
+  unsigned IsActive : 1;
+  unsigned IsReplacement : 1;
+
+  VersionedInfoMetadata(VersionTuple Version, IsActive_t Active,
+IsReplacement_t Replacement)
+  : Version(Version), IsActive(Active == IsActive_t::IsActive),
+IsReplacement(Replacement == IsReplacement_t::IsReplacement) {}
+};
+} // end anonymous namespace
+
+/// Determine whether this is a multi-level pointer type.
+static bool isMultiLevelPointerType(QualType Type) {
+  QualType Pointee = Type->getPointeeType();
+  if (Pointee.isNull())
+return false;
+
+  return Pointee->isAnyPointerType() || Pointee->isObjCObjectPointerType() ||
+ Pointee->isMemberPointerType();
+}
+
+/// Apply nullability to the given declaration.
+static void applyNullability(Sema , Decl *D, NullabilityKind Nullability,
+ VersionedInfoMetadata Metadata) {
+  if (!Metadata.IsActive)
+return;
+
+  QualType Type;
+
+  // Nullability for a function/method appertains to the retain type.
+  if (auto Function = dyn_cast(D))
+Type = Function->getReturnType();
+  else if (auto Method = dyn_cast(D))
+Type = Method->getReturnType();
+  else if (auto Value = dyn_cast(D))
+Type = Value->getType();
+  else if (auto Property = dyn_cast(D))
+Type = Property->getType();
+  else
+return;
+
+  // Check the nullability specifier on this type.
+  QualType OrigType = Type;
+  S.CheckImplicitNullabilityTypeSpecifier(Type, Nullability, D->getLocation(),
+  isa(D),
+  /*overrideExisting=*/true);
+  if (Type.getTypePtr() == OrigType.getTypePtr())
+return;

egorzhdan wrote:

Ah, I see, thanks for explaining! Done

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


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

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

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

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

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

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

[clang] [CLANG][DWARF] Do not emit -ggnu-pubnames for split dwarf version 5. (PR #82840)

2024-02-23 Thread Greg Clayton via cfe-commits

clayborg wrote:

I am fine with `-glldb` doing the right thing for LLDB. 

That being said, I don't believe that LLDB or GDB use `.debug_pubnames` or 
`.debug_pubtypes` as they are incomplete and can't be relied upon. So I would 
say we should never emit these tables unless these older GNU tables unless the 
user explicitly asks for them.

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


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

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


@@ -17959,6 +17964,54 @@ llvm::Value 
*CodeGenFunction::EmitScalarOrConstFoldImmArg(unsigned ICEArguments,
   return Arg;
 }
 
+Value *CodeGenFunction::EmitHLSLBuiltinExpr(unsigned BuiltinID,
+const CallExpr *E) {
+  if (!getLangOpts().HLSL)
+return nullptr;
+
+  switch (BuiltinID) {
+  case Builtin::BI__builtin_hlsl_dot: {
+Value *Op0 = EmitScalarExpr(E->getArg(0));
+Value *Op1 = EmitScalarExpr(E->getArg(1));
+llvm::Type *T0 = Op0->getType();
+llvm::Type *T1 = Op1->getType();
+if (!T0->isVectorTy() && !T1->isVectorTy()) {
+  if (T0->isFloatingPointTy()) {
+return Builder.CreateFMul(Op0, Op1, "dx.dot");
+  }

llvm-beanz wrote:

nit:

```suggestion
  if (T0->isFloatingPointTy())
return Builder.CreateFMul(Op0, Op1, "dx.dot");
```

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


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

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


@@ -17959,6 +17964,54 @@ llvm::Value 
*CodeGenFunction::EmitScalarOrConstFoldImmArg(unsigned ICEArguments,
   return Arg;
 }
 
+Value *CodeGenFunction::EmitHLSLBuiltinExpr(unsigned BuiltinID,
+const CallExpr *E) {
+  if (!getLangOpts().HLSL)
+return nullptr;
+
+  switch (BuiltinID) {
+  case Builtin::BI__builtin_hlsl_dot: {
+Value *Op0 = EmitScalarExpr(E->getArg(0));
+Value *Op1 = EmitScalarExpr(E->getArg(1));
+llvm::Type *T0 = Op0->getType();
+llvm::Type *T1 = Op1->getType();
+if (!T0->isVectorTy() && !T1->isVectorTy()) {
+  if (T0->isFloatingPointTy()) {
+return Builder.CreateFMul(Op0, Op1, "dx.dot");
+  }
+
+  if (T0->isIntegerTy()) {
+return Builder.CreateMul(Op0, Op1, "dx.dot");
+  }

llvm-beanz wrote:

nit:
```suggestion
  if (T0->isIntegerTy())
return Builder.CreateMul(Op0, Op1, "dx.dot");
```

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


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

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


@@ -0,0 +1,110 @@
+// RUN: %clang_cc1 -finclude-default-header -triple 
dxil-pc-shadermodel6.6-library %s -fnative-half-type -emit-llvm 
-disable-llvm-passes -verify -verify-ignore-unexpected
+
+float test_no_second_arg ( float2 p0) {
+  return __builtin_hlsl_dot ( p0 );
+  // expected-error@-1 {{too few arguments to function call, expected 2, have 
1}}
+}
+
+float test_too_many_arg ( float2 p0) {
+  return __builtin_hlsl_dot ( p0, p0, p0 );
+  // expected-error@-1 {{too many arguments to function call, expected 2, have 
3}}
+}
+
+//NOTE: eventually behavior should match builtin

llvm-beanz wrote:

I’m not sure this comment is accurate.

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


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

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


@@ -17959,6 +17964,54 @@ llvm::Value 
*CodeGenFunction::EmitScalarOrConstFoldImmArg(unsigned ICEArguments,
   return Arg;
 }
 
+Value *CodeGenFunction::EmitHLSLBuiltinExpr(unsigned BuiltinID,
+const CallExpr *E) {
+  if (!getLangOpts().HLSL)
+return nullptr;
+
+  switch (BuiltinID) {
+  case Builtin::BI__builtin_hlsl_dot: {
+Value *Op0 = EmitScalarExpr(E->getArg(0));
+Value *Op1 = EmitScalarExpr(E->getArg(1));
+llvm::Type *T0 = Op0->getType();
+llvm::Type *T1 = Op1->getType();
+if (!T0->isVectorTy() && !T1->isVectorTy()) {
+  if (T0->isFloatingPointTy()) {
+return Builder.CreateFMul(Op0, Op1, "dx.dot");
+  }
+
+  if (T0->isIntegerTy()) {
+return Builder.CreateMul(Op0, Op1, "dx.dot");
+  }
+  // Bools should have been promoted
+  assert(
+  false &&
+  "Dot product on a scalar is only supported on integers and floats.");

llvm-beanz wrote:

Generally `assert(false)` should be unreachable.
```suggestion
  llvm_unreachable("Scalar dot product is only supported on ints and 
floats.");
```

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


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

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

https://github.com/llvm-beanz approved this pull request.

A few small notes, but otherwise looks good.

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


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

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


@@ -0,0 +1,110 @@
+// RUN: %clang_cc1 -finclude-default-header -triple 
dxil-pc-shadermodel6.6-library %s -fnative-half-type -emit-llvm 
-disable-llvm-passes -verify -verify-ignore-unexpected
+
+float test_no_second_arg ( float2 p0) {
+  return __builtin_hlsl_dot ( p0 );
+  // expected-error@-1 {{too few arguments to function call, expected 2, have 
1}}
+}
+
+float test_too_many_arg ( float2 p0) {
+  return __builtin_hlsl_dot ( p0, p0, p0 );
+  // expected-error@-1 {{too many arguments to function call, expected 2, have 
3}}
+}
+
+//NOTE: eventually behavior should match builtin
+float test_dot_no_second_arg ( float2 p0) {
+  return dot ( p0 );
+  // expected-error@-1 {{no matching function for call to 'dot'}}
+}
+
+float test_dot_vector_size_mismatch ( float3 p0, float2 p1 ) {
+  return dot ( p0, p1 );
+  // expected-warning@-1 {{implicit conversion truncates vector: 'float3' (aka 
'vector') to 'float __attribute__((ext_vector_type(2)))' (vector of 2 
'float' values)}}
+}
+
+float test_dot_builtin_vector_size_mismatch ( float3 p0, float2 p1 ) {
+  return __builtin_hlsl_dot ( p0, p1 );
+  // expected-error@-1 {{first two arguments to '__builtin_hlsl_dot' must have 
the same type}}
+}
+
+float test_dot_scalar_mismatch ( float p0, int p1 ) {
+  return dot ( p0, p1 );
+  // expected-error@-1 {{call to 'dot' is ambiguous}}
+}
+
+float test_dot_element_type_mismatch ( int2 p0, float2 p1 ) {
+  return dot ( p0, p1 );
+  // expected-error@-1 {{call to 'dot' is ambiguous}}

llvm-beanz wrote:

Can you add the cases like this that should work but fail to the XFAIL’d test 
case that has the other overload resolution bugs?

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


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

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

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


[clang] [CLANG][DWARF] Do not emit -ggnu-pubnames for split dwarf version 5. (PR #82840)

2024-02-23 Thread David Blaikie via cfe-commits

dwblaikie wrote:

If you're debugging with lldb you should probably be using -glldb - if you're 
doing that, certainly gnu-pubnames should not be enabled by default or 
implicitly by gsplit-dwarf.

I'd say -gsplit-dwarf -glldb probably doesn't need any names/accelerator table 
by default (any more than the non-split dwarf should default enable names in 
-glldb - which, maybe it should be, since it is the default on apple platforms, 
I think?) - split dwarf for gcc needed to (& I think should still be the 
default, under -ggdb (the default on Linux etc)) enable gnuoubnames by default 
for correctness (gdb would assume it was present/accurate and fail lookups, 
rather than falling back to slow performance/exhaustive search)

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


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

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

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

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

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

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

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

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

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

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

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

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

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

https://github.com/shafik commented:

I think a more appropriate title would be "Fix for overflow in enumerators"

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


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

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


@@ -18,6 +19,40 @@ enum x  // expected-warning 
{{enumeration values exceed rang
 { y = -9223372036854775807LL-1,  // expected-warning {{ISO C restricts 
enumerator values to range of 'int'}}
 z = 9223372036854775808ULL };// expected-warning {{ISO C restricts 
enumerator values to range of 'int'}}
 
+
+enum GH24667 {   GH24667_x = 9223372036854775807UL, };
+// expected-warning@-1 {{ISO C restricts enumerator values to range of 'int' 
(9223372036854775807 is too large)}}
+
+#else
+enum e {A,
+B = 42LL << 32,
+  C = -4, D = 12456 };
+
+enum g {  // too negative

shafik wrote:

What does this comment mean? There is no diagnostic here? This also applies to 
the `too pos` comment below.

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


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

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

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


[clang] [llvm] [clang][ScanDeps] Allow PCHs to have different VFS overlays (PR #82294)

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

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

>From 45852f569575d0735c686376ad30753fe791db26 Mon Sep 17 00:00:00 2001
From: Michael Spencer 
Date: Thu, 15 Feb 2024 16:44:45 -0800
Subject: [PATCH] [clang][ScanDeps] Allow PCHs to have different VFS overlays

It turns out it's not that uncommon for real code to pass a different
set of VFSs while building a PCH than while using the PCH. This can
cause problems as seen in `test/ClangScanDeps/optimize-vfs-pch.m`. If
you scan `compile-commands-tu-no-vfs-error.json` without -Werror and
run the resulting commands, Clang will emit a fatal error while trying
to emit a note saying that it can't find a remapped header.

This also adds textual tracking of VFSs for prebuilt modules that are
part of an included PCH, as the same issue can occur in a module we
are building if we drop VFSs. This has to be textual because we have
no guarantee the PCH had the same list of VFSs as the current TU.
---
 .../Basic/DiagnosticSerializationKinds.td |   4 +-
 .../DependencyScanning/ModuleDepCollector.h   |   5 +
 .../DependencyScanningWorker.cpp  |  58 +++--
 .../DependencyScanning/ModuleDepCollector.cpp |  34 --
 clang/test/ClangScanDeps/optimize-vfs-pch.m   | 114 --
 llvm/include/llvm/ADT/StringSet.h |   4 +
 6 files changed, 190 insertions(+), 29 deletions(-)

diff --git a/clang/include/clang/Basic/DiagnosticSerializationKinds.td 
b/clang/include/clang/Basic/DiagnosticSerializationKinds.td
index 4c4659ed517e0a..eb27de5921d6a1 100644
--- a/clang/include/clang/Basic/DiagnosticSerializationKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSerializationKinds.td
@@ -44,7 +44,9 @@ def err_pch_diagopt_mismatch : Error<"%0 is currently 
enabled, but was not in "
   "the PCH file">;
 def err_pch_modulecache_mismatch : Error<"PCH was compiled with module cache "
   "path '%0', but the path is currently '%1'">;
-def err_pch_vfsoverlay_mismatch : Error<"PCH was compiled with different VFS 
overlay files than are currently in use">;
+def warn_pch_vfsoverlay_mismatch : Warning<
+  "PCH was compiled with different VFS overlay files than are currently in 
use">,
+  InGroup>;
 def note_pch_vfsoverlay_files : Note<"%select{PCH|current translation unit}0 
has the following VFS overlays:\n%1">;
 def note_pch_vfsoverlay_empty : Note<"%select{PCH|current translation unit}0 
has no VFS overlays">;
 
diff --git 
a/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h 
b/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
index 13ad2530864927..081899cc2c8503 100644
--- a/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
+++ b/clang/include/clang/Tooling/DependencyScanning/ModuleDepCollector.h
@@ -149,6 +149,8 @@ struct ModuleDeps {
   BuildInfo;
 };
 
+using PrebuiltModuleVFSMapT = llvm::StringMap>;
+
 class ModuleDepCollector;
 
 /// Callback that records textual includes and direct modular includes/imports
@@ -214,6 +216,7 @@ class ModuleDepCollector final : public DependencyCollector 
{
  CompilerInstance , DependencyConsumer ,
  DependencyActionController ,
  CompilerInvocation OriginalCI,
+ PrebuiltModuleVFSMapT PrebuiltModuleVFSMap,
  ScanningOptimizations OptimizeArgs, bool EagerLoadModules,
  bool IsStdModuleP1689Format);
 
@@ -233,6 +236,8 @@ class ModuleDepCollector final : public DependencyCollector 
{
   DependencyConsumer 
   /// Callbacks for computing dependency information.
   DependencyActionController 
+  /// Mapping from prebuilt AST files to their sorted list of VFS overlay 
files.
+  PrebuiltModuleVFSMapT PrebuiltModuleVFSMap;
   /// Path to the main source file.
   std::string MainFile;
   /// Hash identifying the compilation conditions of the current TU.
diff --git a/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp 
b/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
index 3cf3ad8a4e4907..b252463a08b8d7 100644
--- a/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
+++ b/clang/lib/Tooling/DependencyScanning/DependencyScanningWorker.cpp
@@ -24,6 +24,7 @@
 #include "clang/Tooling/DependencyScanning/DependencyScanningService.h"
 #include "clang/Tooling/DependencyScanning/ModuleDepCollector.h"
 #include "clang/Tooling/Tooling.h"
+#include "llvm/ADT/ScopeExit.h"
 #include "llvm/Support/Allocator.h"
 #include "llvm/Support/Error.h"
 #include "llvm/TargetParser/Host.h"
@@ -67,7 +68,7 @@ static bool checkHeaderSearchPaths(const HeaderSearchOptions 
,
   if (LangOpts.Modules) {
 if (HSOpts.VFSOverlayFiles != ExistingHSOpts.VFSOverlayFiles) {
   if (Diags) {
-Diags->Report(diag::err_pch_vfsoverlay_mismatch);
+Diags->Report(diag::warn_pch_vfsoverlay_mismatch);
 auto VFSNote = [&](int Type, ArrayRef VFSOverlays) {
   if (VFSOverlays.empty()) {
  

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

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

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

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

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

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

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

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

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


@@ -5161,6 +5166,157 @@ bool Sema::CheckPPCMMAType(QualType Type, 
SourceLocation TypeLoc) {
   return false;
 }
 
+// Helper function for CheckHLSLBuiltinFunctionCall
+// Note: UsualArithmeticConversions handles the case where at least
+// one arg isn't a bool
+bool PromoteBoolsToInt(Sema *S, CallExpr *TheCall) {
+  unsigned NumArgs = TheCall->getNumArgs();
+
+  for (unsigned i = 0; i < NumArgs; ++i) {
+ExprResult A = TheCall->getArg(i);
+if (!A.get()->getType()->isBooleanType())
+  return false;
+  }
+  // if we got here all args are bool
+  for (unsigned i = 0; i < NumArgs; ++i) {
+ExprResult A = TheCall->getArg(i);
+ExprResult ResA = S->PerformImplicitConversion(A.get(), S->Context.IntTy,
+   Sema::AA_Converting);
+if (ResA.isInvalid())
+  return true;
+TheCall->setArg(i, ResA.get());
+  }
+  return false;
+}
+
+// Helper function for CheckHLSLBuiltinFunctionCall
+// Handles the CK_HLSLVectorTruncation case for builtins
+void PromoteVectorArgTruncation(Sema *S, CallExpr *TheCall) {
+  assert(TheCall->getNumArgs() > 1);
+  ExprResult A = TheCall->getArg(0);
+  ExprResult B = TheCall->getArg(1);
+  QualType ArgTyA = A.get()->getType();
+  QualType ArgTyB = B.get()->getType();
+
+  auto *VecTyA = ArgTyA->getAs();
+  auto *VecTyB = ArgTyB->getAs();
+  if (VecTyA == nullptr && VecTyB == nullptr)
+return;
+  if (VecTyA == nullptr || VecTyB == nullptr)
+return;
+  if (VecTyA->getNumElements() == VecTyB->getNumElements())
+return;
+
+  Expr *LargerArg = B.get();
+  Expr *SmallerArg = A.get();
+  int largerIndex = 1;
+  if (VecTyA->getNumElements() > VecTyB->getNumElements()) {
+LargerArg = A.get();
+SmallerArg = B.get();
+largerIndex = 0;
+  }
+
+  S->Diag(TheCall->getExprLoc(), diag::warn_hlsl_impcast_vector_truncation)
+  << LargerArg->getType() << SmallerArg->getType()
+  << LargerArg->getSourceRange() << SmallerArg->getSourceRange();
+  ExprResult ResLargerArg = S->ImpCastExprToType(
+  LargerArg, SmallerArg->getType(), CK_HLSLVectorTruncation);
+  TheCall->setArg(largerIndex, ResLargerArg.get());
+  return;
+}
+
+// Helper function for CheckHLSLBuiltinFunctionCall
+void CheckVectorFloatPromotion(Sema *S, ExprResult , QualType targetTy,
+   SourceRange targetSrcRange,
+   SourceLocation BuiltinLoc) {
+  auto *vecTyTarget = source.get()->getType()->getAs();
+  assert(vecTyTarget);
+  QualType vecElemT = vecTyTarget->getElementType();
+  if (!vecElemT->isFloatingType() && targetTy->isFloatingType()) {
+QualType floatVecTy = S->Context.getVectorType(
+S->Context.FloatTy, vecTyTarget->getNumElements(), 
VectorKind::Generic);
+
+S->Diag(BuiltinLoc, diag::warn_impcast_integer_float_precision)
+<< source.get()->getType() << floatVecTy
+<< source.get()->getSourceRange() << targetSrcRange;
+source = S->SemaConvertVectorExpr(
+source.get(), S->Context.CreateTypeSourceInfo(floatVecTy), BuiltinLoc,
+source.get()->getBeginLoc());
+  }
+}
+
+// Helper function for CheckHLSLBuiltinFunctionCall
+void PromoteVectorArgSplat(Sema *S, ExprResult , QualType targetTy) {
+  QualType sourceTy = source.get()->getType();
+  auto *vecTyTarget = targetTy->getAs();
+  QualType vecElemT = vecTyTarget->getElementType();
+  if (vecElemT->isFloatingType() && sourceTy != vecElemT)
+// if float vec splat wil do an unnecessary cast to double
+source = S->ImpCastExprToType(source.get(), vecElemT, CK_FloatingCast);
+  source = S->ImpCastExprToType(source.get(), targetTy, CK_VectorSplat);
+}
+
+// Helper function for CheckHLSLBuiltinFunctionCall
+bool CheckVectorElementCallArgs(Sema *S, CallExpr *TheCall) {
+  assert(TheCall->getNumArgs() > 1);
+  ExprResult A = TheCall->getArg(0);
+  ExprResult B = TheCall->getArg(1);
+  QualType ArgTyA = A.get()->getType();
+  QualType ArgTyB = B.get()->getType();
+  auto *VecTyA = ArgTyA->getAs();
+  auto *VecTyB = ArgTyB->getAs();
+
+  if (VecTyA == nullptr && VecTyB == nullptr)
+return false;
+
+  if (VecTyA && VecTyB) {
+if (VecTyA->getElementType() == VecTyB->getElementType()) {
+  TheCall->setType(VecTyA->getElementType());
+  return false;
+}
+// Note: type promotion is intended to be handeled via the intrinsics
+//  and not the builtin itself.
+S->Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_incompatible_vector)
+<< TheCall->getDirectCallee()
+<< SourceRange(A.get()->getBeginLoc(), B.get()->getEndLoc());
+return true;
+  }
+
+  if (VecTyB) {
+CheckVectorFloatPromotion(S, B, ArgTyA, A.get()->getSourceRange(),
+  TheCall->getBeginLoc());
+PromoteVectorArgSplat(S, A, B.get()->getType());
+  }
+  if (VecTyA) {
+CheckVectorFloatPromotion(S, A, ArgTyB, B.get()->getSourceRange(),
+  TheCall->getBeginLoc());
+PromoteVectorArgSplat(S, 

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

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

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

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

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

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

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

[clang] [HLSL] Fix casting asserts (PR #82827)

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


@@ -1,4 +1,5 @@
 // RUN: %clang_cc1 -triple dxil-unknown-shadermodel6.6-library -S 
-fnative-half-type -finclude-default-header -o - -ast-dump %s | FileCheck %s
+// RUN: %clang_cc1 -std=hlsl2021 -finclude-default-header -x hlsl -triple 
dxil-pc-shadermodel6.6-library %s -fnative-half-type -emit-llvm 
-disable-llvm-passes -O3 -o - | FileCheck %s --check-prefixes=CHECKIR

farzonl wrote:

that's my bad I copied that from another test case.

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


[clang] [CLANG][DWARF] Do not emit -ggnu-pubnames for split dwarf version 5. (PR #82840)

2024-02-23 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Alexander Yermolovich (ayermolo)


Changes

When -gsplit-dwarf is passed in clang emmmits -ggnu-pubnames which results in
.debug_gnu_pubnames/..debug_gnu_pubtypes being generated. For DWARF5 we have
functional .debug_names.

TBH not sure what the right behavior should be. Should we not generate anything
at all by default or generate .debug_names? Doing some archeological digging
initially -gnu-pubnames was always generated to be in line with what gcc does.. 
It was then
changed so that it was generated when split-dwarf was enabled:
https://github.com/llvm/llvm-project/commit/658645241bf0c624d4b7a67c195c239bbc193e3f#diff-bac41c71569f27df21a843bcd74d2e604ed508afbdf14161dfb545c5d228

For LLDB these gnu sections are not useful and just waste space. Maybe a better
check is to be based on tunning?


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


2 Files Affected:

- (modified) clang/lib/Driver/ToolChains/Clang.cpp (+4-3) 
- (modified) clang/test/Driver/split-debug.c (-1) 


``diff
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 6e1b7e8657d0dc..27a5aef17c8d71 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -4479,9 +4479,10 @@ renderDebugOptions(const ToolChain , const Driver , 
const llvm::Triple ,
   options::OPT_gpubnames, options::OPT_gno_pubnames);
   if (DwarfFission != DwarfFissionKind::None ||
   (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC)))
-if (!PubnamesArg ||
-(!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
- !PubnamesArg->getOption().matches(options::OPT_gno_pubnames)))
+if (EffectiveDWARFVersion < 5 &&
+(!PubnamesArg ||
+ (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
+  !PubnamesArg->getOption().matches(options::OPT_gno_pubnames
   CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
options::OPT_gpubnames)
 ? "-gpubnames"
diff --git a/clang/test/Driver/split-debug.c b/clang/test/Driver/split-debug.c
index 968f33b4cc035c..1d5f0fa42fdeea 100644
--- a/clang/test/Driver/split-debug.c
+++ b/clang/test/Driver/split-debug.c
@@ -11,7 +11,6 @@
 // NOINLINE-NOT: "-fsplit-dwarf-inlining"
 // SPLIT-NOT:  "-dumpdir"
 // SPLIT:  "-debug-info-kind=constructor"
-// SPLIT-SAME: "-ggnu-pubnames"
 // SPLIT-SAME: "-split-dwarf-file" "split-debug.dwo" "-split-dwarf-output" 
"split-debug.dwo"
 
 // RUN: %clang -### -c -target wasm32 -gsplit-dwarf -g %s 2>&1 | FileCheck %s 
--check-prefix=SPLIT

``




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


[clang] [CLANG][DWARF] Do not emit -ggnu-pubnames for split dwarf version 5. (PR #82840)

2024-02-23 Thread Alexander Yermolovich via cfe-commits

https://github.com/ayermolo created 
https://github.com/llvm/llvm-project/pull/82840

When -gsplit-dwarf is passed in clang emmmits -ggnu-pubnames which results in
.debug_gnu_pubnames/..debug_gnu_pubtypes being generated. For DWARF5 we have
functional .debug_names.

TBH not sure what the right behavior should be. Should we not generate anything
at all by default or generate .debug_names? Doing some archeological digging
initially -gnu-pubnames was always generated to be in line with what gcc does.. 
It was then
changed so that it was generated when split-dwarf was enabled:
https://github.com/llvm/llvm-project/commit/658645241bf0c624d4b7a67c195c239bbc193e3f#diff-bac41c71569f27df21a843bcd74d2e604ed508afbdf14161dfb545c5d228

For LLDB these gnu sections are not useful and just waste space. Maybe a better
check is to be based on tunning?


>From 714cc804f2716bbd3c666d8922403299e4c19893 Mon Sep 17 00:00:00 2001
From: Alexander Yermolovich 
Date: Fri, 23 Feb 2024 14:52:04 -0800
Subject: [PATCH] [CLANG][DWARF] Do not emit -ggnu-pubnames for split dwarf
 version 5.

When -gsplit-dwarf is passed in clang emmmits -ggnu-pubnames which results in
.debug_gnu_pubnames/..debug_gnu_pubtypes being generated. For DWARF5 we have
functional .debug_names.

TBH not sure what the right behavior should be. Should we not generate anything
at all by default or generate .debug_names? Doing some archeological digging
initially -gnu-pubnames was always generated to be in line with what gcc does.. 
It was then
changed so that it was generated when split-dwarf was enabled:
https://github.com/llvm/llvm-project/commit/658645241bf0c624d4b7a67c195c239bbc193e3f#diff-bac41c71569f27df21a843bcd74d2e604ed508afbdf14161dfb545c5d228

For LLDB these gnu sections are not useful and just waste space. Maybe a better
check is to be based on tunning?
---
 clang/lib/Driver/ToolChains/Clang.cpp | 7 ---
 clang/test/Driver/split-debug.c   | 1 -
 2 files changed, 4 insertions(+), 4 deletions(-)

diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 6e1b7e8657d0dc..27a5aef17c8d71 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -4479,9 +4479,10 @@ renderDebugOptions(const ToolChain , const Driver , 
const llvm::Triple ,
   options::OPT_gpubnames, options::OPT_gno_pubnames);
   if (DwarfFission != DwarfFissionKind::None ||
   (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC)))
-if (!PubnamesArg ||
-(!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
- !PubnamesArg->getOption().matches(options::OPT_gno_pubnames)))
+if (EffectiveDWARFVersion < 5 &&
+(!PubnamesArg ||
+ (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
+  !PubnamesArg->getOption().matches(options::OPT_gno_pubnames
   CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
options::OPT_gpubnames)
 ? "-gpubnames"
diff --git a/clang/test/Driver/split-debug.c b/clang/test/Driver/split-debug.c
index 968f33b4cc035c..1d5f0fa42fdeea 100644
--- a/clang/test/Driver/split-debug.c
+++ b/clang/test/Driver/split-debug.c
@@ -11,7 +11,6 @@
 // NOINLINE-NOT: "-fsplit-dwarf-inlining"
 // SPLIT-NOT:  "-dumpdir"
 // SPLIT:  "-debug-info-kind=constructor"
-// SPLIT-SAME: "-ggnu-pubnames"
 // SPLIT-SAME: "-split-dwarf-file" "split-debug.dwo" "-split-dwarf-output" 
"split-debug.dwo"
 
 // RUN: %clang -### -c -target wasm32 -gsplit-dwarf -g %s 2>&1 | FileCheck %s 
--check-prefix=SPLIT

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


[clang] Diagnose misuse of the cleanup attribute (PR #80040)

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

https://github.com/shafik commented:

The failure of the Windows CI is due to a know problem w/ false detection of a 
virus. You can use `--allow-empty` to make an empty commit and restart the 
process. You have approval, so once it goes green you should be good to squash 
and merge.

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


[clang] [cmake] Enable backtraces by default for Fuchsia toolchains (PR #82839)

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

ilovepi wrote:

After discussing internally, this isn't required, so I'm abandoning this change.

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


[clang] [cmake] Enable backtraces by default for Fuchsia toolchains (PR #82839)

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

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


[clang] [clang-tools-extra] [compiler-rt] [flang] [libclc] [libcxx] [lld] [lldb] [llvm] [NFC] Remove trailing whitespace across all non-test related files (PR #82838)

2024-02-23 Thread Felipe de Azevedo Piovezan via cfe-commits

felipepiovezan wrote:

Juuust to make sure, was this discussed before? This seems akin to running 
clang-format on the entire project, which last time we talked about still faced 
opposition: 
https://discourse.llvm.org/t/rfc-clang-format-all-the-things/76614/11

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


[clang] [clang] Add __builtin_start_object_lifetime builtin. (PR #82776)

2024-02-23 Thread Richard Smith via cfe-commits


@@ -896,6 +896,12 @@ def Launder : Builtin {
   let Prototype = "void*(void*)";
 }
 
+def StartObjectLifeTime : Builtin {

zygoloid wrote:

Nit: lifetime is one word not two, so the `T` should not be capitalized.

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


[clang] Refactor clang::Linkage (PR #80063)

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

https://github.com/shafik commented:

Hello, the diff is only showing a single whitespace change which from the title 
does not seem the intent.

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


[clang] [clang][Diagnostic] Don't warn about binary literals when using C23. (PR #80244)

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

https://github.com/shafik commented:

Thank you for this PR. This change should have some tests to verify the 
behavior is correct. I am a little surprised that this does not change any 
existing tests but maybe we don't have good test coverage.

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


[clang] [cmake] Enable backtraces by default for Fuchsia toolchains (PR #82839)

2024-02-23 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Paul Kirth (ilovepi)


Changes



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


1 Files Affected:

- (modified) clang/cmake/caches/Fuchsia-stage2.cmake (+1-1) 


``diff
diff --git a/clang/cmake/caches/Fuchsia-stage2.cmake 
b/clang/cmake/caches/Fuchsia-stage2.cmake
index eee37c5e7901fa..8f6de881d40a9d 100644
--- a/clang/cmake/caches/Fuchsia-stage2.cmake
+++ b/clang/cmake/caches/Fuchsia-stage2.cmake
@@ -9,7 +9,7 @@ set(PACKAGE_VENDOR Fuchsia CACHE STRING "")
 set(_FUCHSIA_ENABLE_PROJECTS 
"bolt;clang;clang-tools-extra;libc;lld;llvm;polly")
 set(LLVM_ENABLE_RUNTIMES "compiler-rt;libcxx;libcxxabi;libunwind" CACHE STRING 
"")
 
-set(LLVM_ENABLE_BACKTRACES OFF CACHE BOOL "")
+set(LLVM_ENABLE_BACKTRACES ON CACHE BOOL "")
 set(LLVM_ENABLE_DIA_SDK OFF CACHE BOOL "")
 set(LLVM_ENABLE_HTTPLIB ON CACHE BOOL "")
 set(LLVM_ENABLE_LIBCXX ON CACHE BOOL "")

``




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


[clang] [cmake] Enable backtraces by default for Fuchsia toolchains (PR #82839)

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

https://github.com/ilovepi created 
https://github.com/llvm/llvm-project/pull/82839

None

>From 25208080e025db4adaa906b1076aa983e805f55e Mon Sep 17 00:00:00 2001
From: Paul Kirth 
Date: Fri, 23 Feb 2024 22:56:41 +
Subject: [PATCH] =?UTF-8?q?[=F0=9D=98=80=F0=9D=97=BD=F0=9D=97=BF]=20initia?=
 =?UTF-8?q?l=20version?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Created using spr 1.3.4
---
 clang/cmake/caches/Fuchsia-stage2.cmake | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/cmake/caches/Fuchsia-stage2.cmake 
b/clang/cmake/caches/Fuchsia-stage2.cmake
index eee37c5e7901fa..8f6de881d40a9d 100644
--- a/clang/cmake/caches/Fuchsia-stage2.cmake
+++ b/clang/cmake/caches/Fuchsia-stage2.cmake
@@ -9,7 +9,7 @@ set(PACKAGE_VENDOR Fuchsia CACHE STRING "")
 set(_FUCHSIA_ENABLE_PROJECTS 
"bolt;clang;clang-tools-extra;libc;lld;llvm;polly")
 set(LLVM_ENABLE_RUNTIMES "compiler-rt;libcxx;libcxxabi;libunwind" CACHE STRING 
"")
 
-set(LLVM_ENABLE_BACKTRACES OFF CACHE BOOL "")
+set(LLVM_ENABLE_BACKTRACES ON CACHE BOOL "")
 set(LLVM_ENABLE_DIA_SDK OFF CACHE BOOL "")
 set(LLVM_ENABLE_HTTPLIB ON CACHE BOOL "")
 set(LLVM_ENABLE_LIBCXX ON CACHE BOOL "")

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


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

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

sam-mccall wrote:

> For some context: When I’m talking about * finding the ranges to rename based 
> on an index that’s not clangd’s built-in index* I meant a request like 
> [apple#7973](https://github.com/apple/llvm-project/pull/7973).

I see. That makes sense, it's just a bit non-obvious because we don't usually 
design these pieces as libraries to be consumed outside clangd (either by code 
calling into clangd's internals, or a modified version of clangd).

I think we usually won't support major design changes to accommodate these, but 
small ones like this look totally fine.
(There are exceptions, e.g. adding XPC support required significant changes. 
After these, XPC lives in llvm-project but could just as easily be downstream).

> Functionality-wise, I would be fine with using a `optional>` 
> instead of `Selector` in `collectRenameIdentifierRanges`. FWIW I disagree 
> that using a `vector` is cleaner than using a dedicated type for it 
> because there’s no type-level information about what the `vector` 
> represents

Yeah, "clean" can mean various things, e.g. "clearly communicating intent" here 
is in tension with "fewer moving parts".
I'd be fine with `struct SelectorName { vector Chunks; }` or `using 
SelectorName = vector`, more than that is (for my taste) more noise 
than signal here. I think it should go in `clangd/refactor/Rename.h` though - 
it's just a part of that API.



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


[clang] [Clang][Sema] Fix incorrect rejection default construction of union with nontrivial member (PR #82407)

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

https://github.com/shafik updated 
https://github.com/llvm/llvm-project/pull/82407

>From 5fcaeaddccc0f7e370bf7bebce113d8d52e1b1bd Mon Sep 17 00:00:00 2001
From: Shafik Yaghmour 
Date: Tue, 20 Feb 2024 11:22:39 -0800
Subject: [PATCH] [Clang][Sema] Fix incorrect rejection default construction of
 union with nontrivial member

In 765d8a192180f8f33618087b15c022fe758044af we impelemented a fix for incorrect 
deletion of
default constructors in unions. This fix missed a case and so this PR will
extend the fix to cover the additional case.

Fixes: https://github.com/llvm/llvm-project/issues/81774
---
 clang/docs/ReleaseNotes.rst|  3 +++
 clang/lib/Sema/SemaDeclCXX.cpp | 18 +++---
 .../test/CodeGen/union-non-trivial-member.cpp  | 17 +
 clang/test/SemaCXX/cxx0x-nontrivial-union.cpp  | 11 +++
 4 files changed, 46 insertions(+), 3 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 5bca2c965c866b..452382eb6c4a1e 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -292,6 +292,9 @@ Bug Fixes to C++ Support
   was only accepted at namespace scope but not at local function scope.
 - Clang no longer tries to call consteval constructors at runtime when they 
appear in a member initializer.
   (`#782154 `_`)
+- Fix for clang incorrectly rejecting the default construction of a union with
+  nontrivial member when another member has an initializer.
+  (`#81774 `_)
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 79263bc3ff671d..25a4b4381ca25e 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -9442,9 +9442,21 @@ bool 
SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
 
   int DiagKind = -1;
 
-  if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
-DiagKind = !Decl ? 0 : 1;
-  else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
+  if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) {
+if (CSM == Sema::CXXDefaultConstructor && Field &&
+Field->getParent()->isUnion()) {
+  // [class.default.ctor]p2:
+  //   A defaulted default constructor for class X is defined as deleted if
+  //   - X is a union that has a variant member with a non-trivial default
+  // constructor and no variant member of X has a default member
+  // initializer
+  const auto *RD = cast(Field->getParent());
+  if (!RD->hasInClassInitializer())
+DiagKind = !Decl ? 0 : 1;
+} else {
+  DiagKind = !Decl ? 0 : 1;
+}
+  } else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
 DiagKind = 2;
   else if (!isAccessible(Subobj, Decl))
 DiagKind = 3;
diff --git a/clang/test/CodeGen/union-non-trivial-member.cpp 
b/clang/test/CodeGen/union-non-trivial-member.cpp
index fdc9fd16911e14..8b055a9970fc75 100644
--- a/clang/test/CodeGen/union-non-trivial-member.cpp
+++ b/clang/test/CodeGen/union-non-trivial-member.cpp
@@ -15,14 +15,25 @@ union UnionNonTrivial {
 non_trivial_constructor b{};
 };
 
+struct Handle {
+Handle(int) {}
+};
+
+union UnionNonTrivialEqualInit {
+int NoState = 0;
+Handle CustomState;
+};
+
 void f() {
 UnionInt u1;
 UnionNonTrivial u2;
+UnionNonTrivialEqualInit u3;
 }
 
 // CHECK:  define dso_local void @_Z1fv()
 // CHECK:call void @_ZN8UnionIntC1Ev
 // CHECK-NEXT:   call void @_ZN15UnionNonTrivialC1Ev
+// CHECK-NEXT:   call void @_ZN24UnionNonTrivialEqualInitC1Ev
 
 // CHECK:  define {{.*}}void @_ZN8UnionIntC1Ev
 // CHECK:call void @_ZN8UnionIntC2Ev
@@ -30,8 +41,14 @@ void f() {
 // CHECK:  define {{.*}}void @_ZN15UnionNonTrivialC1Ev
 // CHECK:call void @_ZN15UnionNonTrivialC2Ev
 
+// CHECK:  define {{.*}}void @_ZN24UnionNonTrivialEqualInitC1Ev
+// CHECK:call void @_ZN24UnionNonTrivialEqualInitC2Ev
+
 // CHECK:  define {{.*}}void @_ZN8UnionIntC2Ev
 // CHECK:store i32 1000
 
 // CHECK:  define {{.*}}void @_ZN15UnionNonTrivialC2Ev
 // CHECK:call void @_ZN23non_trivial_constructorC1Ev
+
+// CHECK:  define {{.*}}void @_ZN24UnionNonTrivialEqualInitC2Ev
+// CHECK:store i32 0
diff --git a/clang/test/SemaCXX/cxx0x-nontrivial-union.cpp 
b/clang/test/SemaCXX/cxx0x-nontrivial-union.cpp
index c7cdf76d850dbe..833642b3d739ab 100644
--- a/clang/test/SemaCXX/cxx0x-nontrivial-union.cpp
+++ b/clang/test/SemaCXX/cxx0x-nontrivial-union.cpp
@@ -188,3 +188,14 @@ static_assert(U2().b.x == 100, "");
 static_assert(U3().b.x == 100, "");
 
 } // namespace GH48416
+
+namespace GH81774 {
+struct Handle {
+Handle(int) {}
+};
+// Should be well-formed because NoState has a brace-or-equal-initializer.
+union a {
+int NoState = 0;
+ 

[clang] [flang] [flang] Fixes for LIT testing of FLANG_RUNTIME_F128_MATH_LIB build. (PR #82832)

2024-02-23 Thread Slava Zakharin via cfe-commits

https://github.com/vzakhari updated 
https://github.com/llvm/llvm-project/pull/82832

>From fea6f95d3cfaa3ae75e0f8312198a20c36e79ad7 Mon Sep 17 00:00:00 2001
From: Slava Zakharin 
Date: Fri, 23 Feb 2024 13:08:49 -0800
Subject: [PATCH 1/2] [flang] Fixes for LIT testing of
 FLANG_RUNTIME_F128_MATH_LIB build.

Follow-up for #81971 to fix the disabled LIT test and add
LIT tests for lowering of the added math intrinsics.
---
 clang/lib/Driver/ToolChains/CommonArgs.cpp| 15 
 flang/test/Driver/linker-flags.f90| 34 +--
 flang/test/Lower/Intrinsics/cabs_real16.f90   | 10 ++
 .../Lower/Intrinsics/missing-math-runtime.f90 | 12 +++
 flang/test/Lower/Intrinsics/sin_real16.f90|  9 +
 flang/test/Lower/Intrinsics/sqrt_real16.f90   |  9 +
 flang/test/lit.cfg.py | 21 
 flang/test/lit.site.cfg.py.in |  1 +
 8 files changed, 87 insertions(+), 24 deletions(-)
 create mode 100644 flang/test/Lower/Intrinsics/cabs_real16.f90
 create mode 100644 flang/test/Lower/Intrinsics/sin_real16.f90
 create mode 100644 flang/test/Lower/Intrinsics/sqrt_real16.f90

diff --git a/clang/lib/Driver/ToolChains/CommonArgs.cpp 
b/clang/lib/Driver/ToolChains/CommonArgs.cpp
index 347b250260c4c4..faceee85a2f8dc 100644
--- a/clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ b/clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -1316,13 +1316,16 @@ void tools::addFortranRuntimeLibs(const ToolChain , 
const ArgList ,
   // add the correct libraries to link against as dependents in the object
   // file.
   if (!TC.getTriple().isKnownWindowsMSVCEnvironment()) {
-StringRef f128LibName = TC.getDriver().getFlangF128MathLibrary();
-f128LibName.consume_front_insensitive("lib");
-if (!f128LibName.empty()) {
+StringRef F128LibName = TC.getDriver().getFlangF128MathLibrary();
+F128LibName.consume_front_insensitive("lib");
+if (!F128LibName.empty()) {
+  bool AsNeeded = !TC.getTriple().isOSAIX();
   CmdArgs.push_back("-lFortranFloat128Math");
-  addAsNeededOption(TC, Args, CmdArgs, /*as_needed=*/true);
-  CmdArgs.push_back(Args.MakeArgString("-l" + f128LibName));
-  addAsNeededOption(TC, Args, CmdArgs, /*as_needed=*/false);
+  if (AsNeeded)
+addAsNeededOption(TC, Args, CmdArgs, /*as_needed=*/true);
+  CmdArgs.push_back(Args.MakeArgString("-l" + F128LibName));
+  if (AsNeeded)
+addAsNeededOption(TC, Args, CmdArgs, /*as_needed=*/false);
 }
 CmdArgs.push_back("-lFortranRuntime");
 CmdArgs.push_back("-lFortranDecimal");
diff --git a/flang/test/Driver/linker-flags.f90 
b/flang/test/Driver/linker-flags.f90
index 5e00520fcc098c..4d3d528b5e99e0 100644
--- a/flang/test/Driver/linker-flags.f90
+++ b/flang/test/Driver/linker-flags.f90
@@ -2,15 +2,15 @@
 ! invocation. These libraries are added on top of other standard runtime
 ! libraries that the Clang driver will include.
 
-! RUN: %flang -### --target=ppc64le-linux-gnu %S/Inputs/hello.f90 2>&1 | 
FileCheck %s --check-prefixes=CHECK,UNIX
-! RUN: %flang -### --target=aarch64-apple-darwin %S/Inputs/hello.f90 2>&1 | 
FileCheck %s --check-prefixes=CHECK,DARWIN
-! RUN: %flang -### --target=sparc-sun-solaris2.11 %S/Inputs/hello.f90 2>&1 | 
FileCheck %s --check-prefixes=CHECK,UNIX
-! RUN: %flang -### --target=x86_64-unknown-freebsd %S/Inputs/hello.f90 2>&1 | 
FileCheck %s --check-prefixes=CHECK,UNIX
-! RUN: %flang -### --target=x86_64-unknown-netbsd %S/Inputs/hello.f90 2>&1 | 
FileCheck %s --check-prefixes=CHECK,UNIX
-! RUN: %flang -### --target=x86_64-unknown-openbsd %S/Inputs/hello.f90 2>&1 | 
FileCheck %s --check-prefixes=CHECK,UNIX
-! RUN: %flang -### --target=x86_64-unknown-dragonfly %S/Inputs/hello.f90 2>&1 
| FileCheck %s --check-prefixes=CHECK,UNIX
-! RUN: %flang -### --target=x86_64-unknown-haiku %S/Inputs/hello.f90 2>&1 | 
FileCheck %s --check-prefixes=CHECK,HAIKU
-! RUN: %flang -### --target=x86_64-windows-gnu %S/Inputs/hello.f90 2>&1 | 
FileCheck %s --check-prefixes=CHECK,MINGW
+! RUN: %flang -### --target=ppc64le-linux-gnu %S/Inputs/hello.f90 2>&1 | 
FileCheck %s --check-prefixes=CHECK,UNIX,UNIX-F128%f128-lib
+! RUN: %flang -### --target=aarch64-apple-darwin %S/Inputs/hello.f90 2>&1 | 
FileCheck %s --check-prefixes=CHECK,DARWIN,DARWIN-F128%f128-lib
+! RUN: %flang -### --target=sparc-sun-solaris2.11 %S/Inputs/hello.f90 2>&1 | 
FileCheck %s --check-prefixes=CHECK,UNIX,SOLARIS-F128%f128-lib
+! RUN: %flang -### --target=x86_64-unknown-freebsd %S/Inputs/hello.f90 2>&1 | 
FileCheck %s --check-prefixes=CHECK,UNIX,UNIX-F128%f128-lib
+! RUN: %flang -### --target=x86_64-unknown-netbsd %S/Inputs/hello.f90 2>&1 | 
FileCheck %s --check-prefixes=CHECK,UNIX,UNIX-F128%f128-lib
+! RUN: %flang -### --target=x86_64-unknown-openbsd %S/Inputs/hello.f90 2>&1 | 
FileCheck %s --check-prefixes=CHECK,UNIX,UNIX-F128%f128-lib
+! RUN: %flang -### --target=x86_64-unknown-dragonfly %S/Inputs/hello.f90 2>&1 
| FileCheck %s 

[clang] [clang-tools-extra] [compiler-rt] [flang] [libclc] [libcxx] [lld] [lldb] [llvm] [NFC] Remove trailing whitespace across all non-test related files (PR #82838)

2024-02-23 Thread Mehdi Amini via cfe-commits

joker-eph wrote:

Fine with me if we want to land this as is, but per-top-level subproject may be 
a better granularity.

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


[clang] [clang-tools-extra] [compiler-rt] [flang] [libclc] [libcxx] [lld] [lldb] [llvm] [NFC] Remove trailing whitespace across all non-test related files (PR #82838)

2024-02-23 Thread via cfe-commits

github-actions[bot] wrote:

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


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


[clang] [clang-tools-extra] [compiler-rt] [flang] [libclc] [libcxx] [lld] [lldb] [llvm] [NFC] Remove trailing whitespace across all non-test related files (PR #82838)

2024-02-23 Thread via cfe-commits

AtariDreams wrote:

I'm just gonna split this up. Sorry.

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


[clang] [clang-tools-extra] [compiler-rt] [flang] [libclc] [libcxx] [lld] [lldb] [llvm] [NFC] Remove trailing whitespace across all non-test related files (PR #82838)

2024-02-23 Thread via cfe-commits

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


[clang] [clang-tools-extra] [compiler-rt] [flang] [libclc] [libcxx] [lld] [lldb] [llvm] [NFC] Remove trailing whitespace across all non-test related files (PR #82838)

2024-02-23 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-backend-arm

@llvm/pr-subscribers-clang

Author: AtariDreams (AtariDreams)


Changes

Every once in a while, some formatting scanner will cause the CI to stop 
because of whitespace issues, so it is is best to just remove them in one go, 
especially since it seems only non-test files tend to be under scrutiny by 
automatic formatting checkers.

---

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


599 Files Affected:

- (modified) .github/workflows/scorecard.yml (+2-2) 
- (modified) clang-tools-extra/clang-tidy/abseil/DurationDivisionCheck.h (+1-1) 
- (modified) clang-tools-extra/clang-tidy/abseil/RedundantStrcatCallsCheck.cpp 
(+10-10) 
- (modified) clang-tools-extra/clang-tidy/abseil/RedundantStrcatCallsCheck.h 
(+2-2) 
- (modified) clang-tools-extra/clang-tidy/abseil/StrCatAppendCheck.cpp (+2-2) 
- (modified) clang-tools-extra/clang-tidy/abseil/StrCatAppendCheck.h (+1-1) 
- (modified) 
clang-tools-extra/clang-tidy/bugprone/SpuriouslyWakeUpFunctionsCheck.h (+3-3) 
- (modified) 
clang-tools-extra/clang-tidy/fuchsia/StaticallyConstructedObjectsCheck.h (+1-1) 
- (modified) clang-tools-extra/clang-tidy/fuchsia/TrailingReturnCheck.h (+2-2) 
- (modified) clang-tools-extra/clang-tidy/hicpp/MultiwayPathsCoveredCheck.cpp 
(+1-1) 
- (modified) clang-tools-extra/clang-tidy/misc/ConfusableTable/confusables.txt 
(+4701-4701) 
- (modified) clang-tools-extra/clangd/ClangdLSPServer.h (+1-1) 
- (modified) clang-tools-extra/clangd/CodeComplete.cpp (+2-2) 
- (modified) clang-tools-extra/clangd/IncludeCleaner.cpp (+3-3) 
- (modified) clang-tools-extra/clangd/Protocol.h (+2-2) 
- (modified) clang-tools-extra/clangd/quality/CompletionModel.cmake (+2-2) 
- (modified) clang-tools-extra/clangd/quality/README.md (+8-8) 
- (modified) clang-tools-extra/clangd/refactor/tweaks/PopulateSwitch.cpp (+1-1) 
- (modified) clang-tools-extra/clangd/test/Inputs/symbols.test.yaml (+4-4) 
- (modified) clang-tools-extra/clangd/tool/Check.cpp (+1-1) 
- (modified) 
clang-tools-extra/docs/clang-tidy/checks/bugprone/assignment-in-if-condition.rst
 (+1-1) 
- (modified) 
clang-tools-extra/docs/clang-tidy/checks/bugprone/signal-handler.rst (+1-1) 
- (modified) 
clang-tools-extra/docs/clang-tidy/checks/bugprone/suspicious-realloc-usage.rst 
(+1-1) 
- (modified) clang-tools-extra/docs/clang-tidy/checks/misc/include-cleaner.rst 
(+2-2) 
- (modified) clang-tools-extra/docs/clang-tidy/checks/modernize/type-traits.rst 
(+1-1) 
- (modified) clang-tools-extra/docs/clang-tidy/checks/objc/nsdate-formatter.rst 
(+26-26) 
- (modified) 
clang-tools-extra/docs/clang-tidy/checks/readability/redundant-inline-specifier.rst
 (+1-1) 
- (modified) clang-tools-extra/pseudo/Disambiguation.md (+3-3) 
- (modified) clang-tools-extra/pseudo/gen/Main.cpp (+1-1) 
- (modified) clang/docs/HLSL/ExpectedDifferences.rst (+2-2) 
- (modified) clang/examples/PrintFunctionNames/PrintFunctionNames.cpp (+1-1) 
- (modified) clang/tools/clang-format-vs/ClangFormat/ClangFormatPackage.cs 
(+4-3) 
- (modified) 
clang/tools/clang-format-vs/ClangFormat/RunningDocTableEventsDispatcher.cs 
(+1-1) 
- (modified) clang/tools/clang-fuzzer/CMakeLists.txt (+1-1) 
- (modified) clang/tools/clang-fuzzer/fuzzer-initialize/fuzzer_initialize.cpp 
(+1-1) 
- (modified) clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp (+2-2) 
- (modified) clang/tools/clang-linker-wrapper/LinkerWrapperOpts.td (+2-2) 
- (modified) clang/tools/clang-offload-packager/CMakeLists.txt (+1-1) 
- (modified) clang/tools/diagtool/DiagTool.cpp (+3-3) 
- (modified) clang/tools/diagtool/DiagTool.h (+7-7) 
- (modified) clang/tools/diagtool/diagtool_main.cpp (+1-1) 
- (modified) clang/tools/libclang/ARCMigrate.cpp (-1) 
- (modified) clang/tools/libclang/CIndexCXX.cpp (+13-13) 
- (modified) clang/tools/libclang/CIndexCodeCompletion.cpp (+42-48) 
- (modified) clang/tools/libclang/CIndexDiagnostic.cpp (+22-22) 
- (modified) clang/tools/libclang/CIndexDiagnostic.h (+13-13) 
- (modified) clang/tools/libclang/CIndexHigh.cpp (+4-4) 
- (modified) clang/tools/libclang/CIndexer.h (+1-1) 
- (modified) clang/tools/libclang/CXIndexDataConsumer.cpp (+16-16) 
- (modified) clang/tools/libclang/CXIndexDataConsumer.h (+4-4) 
- (modified) clang/tools/libclang/CXLoadedDiagnostic.cpp (+10-11) 
- (modified) clang/tools/libclang/CXLoadedDiagnostic.h (+3-3) 
- (modified) clang/tools/libclang/CXSourceLocation.cpp (+19-20) 
- (modified) clang/tools/libclang/CXSourceLocation.h (+4-4) 
- (modified) clang/tools/libclang/CXStoredDiagnostic.cpp (+6-7) 
- (modified) clang/tools/libclang/CXTranslationUnit.h (+1-1) 
- (modified) clang/tools/libclang/CXType.cpp (+10-10) 
- (modified) clang/tools/libclang/CXType.h (+1-2) 
- (modified) clang/tools/libclang/Index_Internal.h (+1-1) 
- (modified) clang/tools/libclang/Indexing.cpp (+7-7) 
- (modified) clang/tools/scan-build-py/README.md (+6-6) 
- (modified) clang/tools/scan-build/bin/scan-build (+1-1) 
- (modified) 

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

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


@@ -5161,6 +5166,157 @@ bool Sema::CheckPPCMMAType(QualType Type, 
SourceLocation TypeLoc) {
   return false;
 }
 
+// Helper function for CheckHLSLBuiltinFunctionCall
+// Note: UsualArithmeticConversions handles the case where at least
+// one arg isn't a bool
+bool PromoteBoolsToInt(Sema *S, CallExpr *TheCall) {
+  unsigned NumArgs = TheCall->getNumArgs();
+
+  for (unsigned i = 0; i < NumArgs; ++i) {
+ExprResult A = TheCall->getArg(i);
+if (!A.get()->getType()->isBooleanType())
+  return false;
+  }
+  // if we got here all args are bool
+  for (unsigned i = 0; i < NumArgs; ++i) {
+ExprResult A = TheCall->getArg(i);
+ExprResult ResA = S->PerformImplicitConversion(A.get(), S->Context.IntTy,
+   Sema::AA_Converting);
+if (ResA.isInvalid())
+  return true;
+TheCall->setArg(i, ResA.get());
+  }
+  return false;
+}
+
+// Helper function for CheckHLSLBuiltinFunctionCall
+// Handles the CK_HLSLVectorTruncation case for builtins
+void PromoteVectorArgTruncation(Sema *S, CallExpr *TheCall) {
+  assert(TheCall->getNumArgs() > 1);
+  ExprResult A = TheCall->getArg(0);
+  ExprResult B = TheCall->getArg(1);
+  QualType ArgTyA = A.get()->getType();
+  QualType ArgTyB = B.get()->getType();
+
+  auto *VecTyA = ArgTyA->getAs();
+  auto *VecTyB = ArgTyB->getAs();
+  if (VecTyA == nullptr && VecTyB == nullptr)
+return;
+  if (VecTyA == nullptr || VecTyB == nullptr)
+return;
+  if (VecTyA->getNumElements() == VecTyB->getNumElements())
+return;
+
+  Expr *LargerArg = B.get();
+  Expr *SmallerArg = A.get();
+  int largerIndex = 1;
+  if (VecTyA->getNumElements() > VecTyB->getNumElements()) {
+LargerArg = A.get();
+SmallerArg = B.get();
+largerIndex = 0;
+  }
+
+  S->Diag(TheCall->getExprLoc(), diag::warn_hlsl_impcast_vector_truncation)
+  << LargerArg->getType() << SmallerArg->getType()
+  << LargerArg->getSourceRange() << SmallerArg->getSourceRange();
+  ExprResult ResLargerArg = S->ImpCastExprToType(
+  LargerArg, SmallerArg->getType(), CK_HLSLVectorTruncation);
+  TheCall->setArg(largerIndex, ResLargerArg.get());
+  return;
+}
+
+// Helper function for CheckHLSLBuiltinFunctionCall
+void CheckVectorFloatPromotion(Sema *S, ExprResult , QualType targetTy,
+   SourceRange targetSrcRange,
+   SourceLocation BuiltinLoc) {
+  auto *vecTyTarget = source.get()->getType()->getAs();
+  assert(vecTyTarget);
+  QualType vecElemT = vecTyTarget->getElementType();
+  if (!vecElemT->isFloatingType() && targetTy->isFloatingType()) {
+QualType floatVecTy = S->Context.getVectorType(
+S->Context.FloatTy, vecTyTarget->getNumElements(), 
VectorKind::Generic);
+
+S->Diag(BuiltinLoc, diag::warn_impcast_integer_float_precision)
+<< source.get()->getType() << floatVecTy
+<< source.get()->getSourceRange() << targetSrcRange;
+source = S->SemaConvertVectorExpr(
+source.get(), S->Context.CreateTypeSourceInfo(floatVecTy), BuiltinLoc,
+source.get()->getBeginLoc());
+  }
+}
+
+// Helper function for CheckHLSLBuiltinFunctionCall
+void PromoteVectorArgSplat(Sema *S, ExprResult , QualType targetTy) {
+  QualType sourceTy = source.get()->getType();
+  auto *vecTyTarget = targetTy->getAs();
+  QualType vecElemT = vecTyTarget->getElementType();
+  if (vecElemT->isFloatingType() && sourceTy != vecElemT)
+// if float vec splat wil do an unnecessary cast to double
+source = S->ImpCastExprToType(source.get(), vecElemT, CK_FloatingCast);
+  source = S->ImpCastExprToType(source.get(), targetTy, CK_VectorSplat);
+}
+
+// Helper function for CheckHLSLBuiltinFunctionCall
+bool CheckVectorElementCallArgs(Sema *S, CallExpr *TheCall) {
+  assert(TheCall->getNumArgs() > 1);
+  ExprResult A = TheCall->getArg(0);
+  ExprResult B = TheCall->getArg(1);
+  QualType ArgTyA = A.get()->getType();
+  QualType ArgTyB = B.get()->getType();
+  auto *VecTyA = ArgTyA->getAs();
+  auto *VecTyB = ArgTyB->getAs();
+
+  if (VecTyA == nullptr && VecTyB == nullptr)
+return false;
+
+  if (VecTyA && VecTyB) {
+if (VecTyA->getElementType() == VecTyB->getElementType()) {
+  TheCall->setType(VecTyA->getElementType());
+  return false;
+}
+// Note: type promotion is intended to be handeled via the intrinsics
+//  and not the builtin itself.
+S->Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_incompatible_vector)
+<< TheCall->getDirectCallee()
+<< SourceRange(A.get()->getBeginLoc(), B.get()->getEndLoc());
+return true;
+  }
+
+  if (VecTyB) {
+CheckVectorFloatPromotion(S, B, ArgTyA, A.get()->getSourceRange(),
+  TheCall->getBeginLoc());
+PromoteVectorArgSplat(S, A, B.get()->getType());
+  }
+  if (VecTyA) {
+CheckVectorFloatPromotion(S, A, ArgTyB, B.get()->getSourceRange(),
+  TheCall->getBeginLoc());
+PromoteVectorArgSplat(S, 

[clang] [clang] Add __builtin_start_object_lifetime builtin. (PR #82776)

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


@@ -896,6 +896,12 @@ def Launder : Builtin {
   let Prototype = "void*(void*)";
 }
 
+def StartObjectLifeTime : Builtin {

sam-mccall wrote:

For creating-objects-via-memcpy, what are we planning to do about the memcpy 
part being UB and the start_lifetime part being correspondingly hard to specify 
(what's the relationship between the bytes and the new objects?)

I thought a combined memcpy + start_object_lifetime intrinsic would solve this 
neatly (values of new objects are the values of the old objects), but certainly 
we want the start-lifetime-only part to support start_lifetime_as.  

I don't see a great way out for non-implicit-lifetime types though...

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


[clang] [clang] Add __builtin_start_object_lifetime builtin. (PR #82776)

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


@@ -896,6 +896,12 @@ def Launder : Builtin {
   let Prototype = "void*(void*)";
 }
 
+def StartObjectLifeTime : Builtin {
+  let Spellings = ["__builtin_start_object_lifetime"];

sam-mccall wrote:

nit, I'd consider `__builtin_start_lifetime` both for brevity and to parallel 
`std::start_lifetime_as`.
I don't think it's really ambiguous what we're starting the lifetime of.

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


[clang] [clang] Add __builtin_start_object_lifetime builtin. (PR #82776)

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


@@ -4386,6 +4386,7 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
 
 return RValue::get(nullptr);
   }
+  case Builtin::BI__builtin_start_object_lifetime:

sam-mccall wrote:

is there something to be commented here about why what we do here is sufficient?
It seems surprising to my very-untrained eye that start_lifetime is the same as 
launder, and we don't need any extra TBAA metadata or so...

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


[clang] [clang] Add __builtin_start_object_lifetime builtin. (PR #82776)

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

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


[clang] [clang] Add __builtin_start_object_lifetime builtin. (PR #82776)

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

https://github.com/sam-mccall commented:

Thanks for working on this! I'm far from an expert on the LLVM side so we'll 
need someone to weigh in.


We need to specify specify the behavior somewhere. I think we should add a 
description to `docs/LanguageExtensions.html`, which describes various other 
`__builtin_*`.

I'm not sure defining this in terms of "like start_lifetime_as but..." is ideal 
because:

 - implicit object creation recurses into only implicit-lifetimes subobjects, 
where this will recurse into everything. (Whether this is the same or different 
depends on your persepctive.
 - Unlike start_lifetime_as, it's clearly more useful to say "this starts an 
object's lifetime" than "this may start an object's lifetime as needed to avoid 
UB", I think this clarifies when you can/must call destructors. In this sense 
it's more like placement-new than start-lifetime-as.

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


  1   2   3   4   >