[clang] [clang][TSA] Make RequiresCapability a DeclOrType attribute (PR #67095)

2023-10-10 Thread Timm Baeder via cfe-commits
Timm =?utf-8?q?Bäder?= 
Message-ID:
In-Reply-To: 


tbaederr wrote:

> > This was much easier than expected actually.
> 
> Making it a `DeclOrType` attribute is indeed a nice idea, this would allow 
> existing attributes to stay where they are. Is it still inheritable, i.e. 
> does it also apply to later redeclarations?

I haven't tested this explicitly, but `DeclOrTypeAttr` is-a `InheritableAttr`:
https://github.com/llvm/llvm-project/blob/5dd9266c4e0b0a02cbb02a29bf2606224ccf2820/clang/include/clang/Basic/Attr.td#L644-L647C1

> Of course I'm also wondering why we don't have to change anything in the 
> analysis, aren't we currently only looking at declaration attributes, and 
> wouldn't consider attributes on the type? Or is there some mechanism that 
> gives us the combined set of declaration and type attributes?

Let me check why this just works.

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


[clang] [clang]Avoid diagnose invalid consteval call for invalid function decl (PR #68646)

2023-10-10 Thread via cfe-commits


@@ -358,6 +358,8 @@ Bug Fixes in This Version
   Fixes (`#67690 `_)
 - Fixes a ``clang-17`` regression where ``LLVM_UNREACHABLE_OPTIMIZE=OFF``
   cannot be used with ``Release`` mode builds. (`#68237 
`_).
+- Fix crash in evaluating ``constexpr`` value for invalid template function.

cor3ntin wrote:

```suggestion
- Fix crash when evaluating an invalid immediate function template.
```

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


[clang] [clang]Avoid diagnose invalid consteval call for invalid function decl (PR #68646)

2023-10-10 Thread via cfe-commits

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

I was about to work on that and figured the fix would be along those lines! 
Glad you got to it first, thanks!

The changes look great

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


[clang] [clang][Sema] Emit more specific diagnostic for auto in lambda before C++14 (#46059) (PR #68540)

2023-10-10 Thread via cfe-commits


@@ -2393,7 +2393,7 @@ def err_auto_not_allowed : Error<
   "|in type allocated by 'new'|in K&R-style function parameter"
   "|in template parameter|in friend declaration|in function prototype that is "
   "not a function declaration|in requires expression parameter"
-  "|in array declaration}1">;
+  "|in array declaration|in lambda parameter until C++14}1">;

cor3ntin wrote:

```suggestion
  "|in array declaration|in lambda parameter before C++14}1">;
```

To be consistent with other diagnostics

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


[clang] [clang][Sema] Emit more specific diagnostic for auto in lambda before C++14 (#46059) (PR #68540)

2023-10-10 Thread via cfe-commits

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

A small nit, otherwise LGTM

I'm not sure it's strictly necessary here, but you could add a release note in 
clang/docs/ReleaseNotes.rst - under the diagnostics improvement section

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


[clang] [clang][Sema] Emit more specific diagnostic for auto in lambda before C++14 (#46059) (PR #68540)

2023-10-10 Thread via cfe-commits

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


[clang] [clang] __is_trivially_equality_comparable for types containing lambdas (PR #68506)

2023-10-10 Thread via cfe-commits

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

I think there is an opportunity for a small refactor here, but feel free to 
land this and we can handle the refactor later as an NFC change if you prefer

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


[clang] [clang] __is_trivially_equality_comparable for types containing lambdas (PR #68506)

2023-10-10 Thread via cfe-commits

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


[clang] [clang] __is_trivially_equality_comparable for types containing lambdas (PR #68506)

2023-10-10 Thread via cfe-commits


@@ -2663,6 +2663,9 @@ static bool
 HasNonDeletedDefaultedEqualityComparison(const CXXRecordDecl *Decl) {
   if (Decl->isUnion())
 return false;
+  if (Decl->isLambda())
+return Decl->captures().empty() &&
+   (Decl->getLambdaCaptureDefault() == LCD_None);

cor3ntin wrote:

This pattern is used in a few places, maybe we should factor it out

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


[clang] [clang] static operators should evaluate object argument (PR #68485)

2023-10-10 Thread via cfe-commits


@@ -14935,15 +14935,15 @@ ExprResult 
Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
 CXXMethodDecl *Method = cast(FnDecl);
 SmallVector MethodArgs;
 
-// Handle 'this' parameter if the selected function is not static.
+// Initialize the explicit / implicit object parameter.

cor3ntin wrote:

```suggestion
// Initialize the object parameter.
```

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


[clang] [flang][driver] Mark -fcommon and -mtune as visible in Flang (PR #68657)

2023-10-10 Thread Fangcao Wang via cfe-commits

https://github.com/LittleMeepo updated 
https://github.com/llvm/llvm-project/pull/68657

>From d056372043e9ee55caf4a7c8d1f708658986cfd1 Mon Sep 17 00:00:00 2001
From: wangfc 
Date: Tue, 10 Oct 2023 11:06:11 +0800
Subject: [PATCH] [flang][driver] Mark -fcommon and -mtune as visible in Flang

---
 clang/include/clang/Driver/Options.td| 3 ++-
 flang/test/Driver/driver-help-hidden.f90 | 1 +
 flang/test/Driver/driver-help.f90| 1 +
 flang/test/Driver/misc-flags.f90 | 3 +++
 4 files changed, 7 insertions(+), 1 deletion(-)

diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 5415b18d3f406df..8936df388d2db97 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1786,7 +1786,7 @@ def fno_record_command_line : Flag<["-"], 
"fno-record-command-line">,
 def : Flag<["-"], "frecord-gcc-switches">, Alias;
 def : Flag<["-"], "fno-record-gcc-switches">, Alias;
 def fcommon : Flag<["-"], "fcommon">, Group,
-  Visibility<[ClangOption, CLOption, CC1Option]>,
+  Visibility<[ClangOption, CLOption, CC1Option, FlangOption]>,
   HelpText<"Place uninitialized global variables in a common block">,
   MarshallingInfoNegativeFlag>,
   DocBrief<[{Place definitions of variables with no storage class and no 
initializer
@@ -5077,6 +5077,7 @@ def module_file_info : Flag<["-"], "module-file-info">, 
Flags<[NoXarchOption]>,
   HelpText<"Provide information about a particular module file">;
 def mthumb : Flag<["-"], "mthumb">, Group;
 def mtune_EQ : Joined<["-"], "mtune=">, Group,
+  Flags<[TargetSpecific]>, Visibility<[ClangOption, CLOption, DXCOption, 
FlangOption]>,
   HelpText<"Only supported on AArch64, PowerPC, RISC-V, SystemZ, and X86">;
 def multi__module : Flag<["-"], "multi_module">;
 def multiply__defined__unused : Separate<["-"], "multiply_defined_unused">;
diff --git a/flang/test/Driver/driver-help-hidden.f90 
b/flang/test/Driver/driver-help-hidden.f90
index 807b0f938d27b5c..eddf7d0d59794a0 100644
--- a/flang/test/Driver/driver-help-hidden.f90
+++ b/flang/test/Driver/driver-help-hidden.f90
@@ -29,6 +29,7 @@
 ! CHECK-NEXT: -fapprox-func   Allow certain math function calls to be 
replaced with an approximately equivalent calculation
 ! CHECK-NEXT: -fbackslash Specify that backslash in string 
introduces an escape character
 ! CHECK-NEXT: -fcolor-diagnostics Enable colors in diagnostics
+! CHECK-NEXT: -fcommonPlace uninitialized global variables in 
a common block
 ! CHECK-NEXT: -fconvert=   Set endian conversion of data for 
unformatted files
 ! CHECK-NEXT: -fdefault-double-8  Set the default double precision kind to 
an 8 byte wide type
 ! CHECK-NEXT: -fdefault-integer-8 Set the default integer and logical kind 
to an 8 byte wide type
diff --git a/flang/test/Driver/driver-help.f90 
b/flang/test/Driver/driver-help.f90
index 4894f90f5310439..5c3273d825600a0 100644
--- a/flang/test/Driver/driver-help.f90
+++ b/flang/test/Driver/driver-help.f90
@@ -25,6 +25,7 @@
 ! HELP-NEXT: -fapprox-func   Allow certain math function calls to be 
replaced with an approximately equivalent calculation
 ! HELP-NEXT: -fbackslash Specify that backslash in string 
introduces an escape character
 ! HELP-NEXT: -fcolor-diagnostics Enable colors in diagnostics
+! HELP-NEXT: -fcommonPlace uninitialized global variables in a 
common block
 ! HELP-NEXT: -fconvert=   Set endian conversion of data for 
unformatted files
 ! HELP-NEXT: -fdefault-double-8  Set the default double precision kind to 
an 8 byte wide type
 ! HELP-NEXT: -fdefault-integer-8 Set the default integer and logical kind 
to an 8 byte wide type
diff --git a/flang/test/Driver/misc-flags.f90 b/flang/test/Driver/misc-flags.f90
index 61d763c5b64dd21..9412ccb8347ff89 100644
--- a/flang/test/Driver/misc-flags.f90
+++ b/flang/test/Driver/misc-flags.f90
@@ -10,6 +10,9 @@
 ! Make sure that `-L' is "visible" to Flang's driver
 ! RUN: %flang -L/ -### %s
 
+! Make sure that `-fcommon' is "visible" to Flang's driver
+! RUN: %flang -fcommon -### %s
+
 program hello
   write(*,*), "Hello world!"
 end program hello

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


[clang] 19d1da5 - [clang]Avoid diagnose invalid consteval call for invalid function decl (#68646)

2023-10-10 Thread via cfe-commits

Author: Congcong Cai
Date: 2023-10-10T15:32:10+08:00
New Revision: 19d1da59dcdea46d30d93a48c389856e89c57b5d

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

LOG: [clang]Avoid diagnose invalid consteval call for invalid function decl 
(#68646)

Fixes:#68542
It‘s meaningless to diagnose further error for invalid function
declaration.

Added: 
clang/test/SemaCXX/PR68542.cpp

Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaExpr.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 96928e98bcee156..9c320bc8b35d23d 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -375,6 +375,8 @@ Bug Fixes in This Version
   Fixes (`#67690 `_)
 - Fixes a ``clang-17`` regression where ``LLVM_UNREACHABLE_OPTIMIZE=OFF``
   cannot be used with ``Release`` mode builds. (`#68237 
`_).
+- Fix crash in evaluating ``constexpr`` value for invalid template function.
+  Fixes (`#68542 `_)
 
 Bug Fixes to Compiler Builtins
 ^^

diff  --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 15e2a7978f6b723..cf45fc388083ce6 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -18408,6 +18408,8 @@ static void EvaluateAndDiagnoseImmediateInvocation(
 
 assert(FD && FD->isImmediateFunction() &&
"could not find an immediate function in this expression");
+if (FD->isInvalidDecl())
+  return;
 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call)
 << FD << FD->isConsteval();
 if (auto Context =

diff  --git a/clang/test/SemaCXX/PR68542.cpp b/clang/test/SemaCXX/PR68542.cpp
new file mode 100644
index 000..fc767a78c8b0013
--- /dev/null
+++ b/clang/test/SemaCXX/PR68542.cpp
@@ -0,0 +1,20 @@
+// RUN: %clang_cc1 -verify -std=c++20 -fsyntax-only %s
+
+struct S {
+int e;
+};
+
+template
+consteval int get_format() {
+   return nullptr; // expected-error{{cannot initialize return object of 
type 'int' with an rvalue of type 'std::nullptr_t'}}
+}
+
+template
+constexpr S f(T) noexcept {
+   return get_format(); // expected-error{{no viable conversion from 
returned value of type 'int' to function return type 'S'}}
+}
+
+constexpr S x = f(0); // expected-error{{constexpr variable 'x' must be 
initialized by a constant expression}}
+// expected-note@-1{{in instantiation of function template specialization 
'f' requested here}}
+// expected-note@3{{candidate constructor (the implicit move constructor) not 
viable: no known conversion from 'int' to 'S &&' for 1st argument}}
+// expected-note@3{{candidate constructor (the implicit copy constructor) not 
viable: no known conversion from 'int' to 'const S &' for 1st argument}}



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


[clang] [clang]Avoid diagnose invalid consteval call for invalid function decl (PR #68646)

2023-10-10 Thread Congcong Cai via cfe-commits

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


[clang] [clang][dataflow]Use cast_or_null instead cast to prevent crash (PR #68510)

2023-10-10 Thread Congcong Cai via cfe-commits

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


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


[PATCH] D154951: [clang][Interp] __builtin_bit_cast, Take 2

2023-10-10 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder abandoned this revision.
tbaeder added a comment.

Abandoning this since I've migrated it to Github: 
https://github.com/llvm/llvm-project/pull/68288


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D154951/new/

https://reviews.llvm.org/D154951

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


[clang] [clang] static operators should evaluate object argument (PR #68485)

2023-10-10 Thread Tianlan Zhou via cfe-commits

https://github.com/SuperSodaSea updated 
https://github.com/llvm/llvm-project/pull/68485

>From 03276260c48d9cafb2a0d80825156e77cdf02eba Mon Sep 17 00:00:00 2001
From: SuperSodaSea 
Date: Sat, 7 Oct 2023 21:05:17 +0800
Subject: [PATCH 1/3] [clang] static operators should evaluate object argument

---
 clang/lib/AST/ExprConstant.cpp|  3 +-
 clang/lib/CodeGen/CGExpr.cpp  |  2 +-
 clang/lib/CodeGen/CGExprCXX.cpp   | 41 --
 clang/lib/CodeGen/CodeGenFunction.h   |  3 +
 clang/lib/Sema/SemaChecking.cpp   |  5 +-
 clang/lib/Sema/SemaOverload.cpp   | 33 ---
 clang/test/AST/ast-dump-static-operators.cpp  | 55 +++
 .../CodeGenCXX/cxx2b-static-call-operator.cpp | 26 ++---
 .../cxx2b-static-subscript-operator.cpp   | 11 +++-
 9 files changed, 137 insertions(+), 42 deletions(-)
 create mode 100644 clang/test/AST/ast-dump-static-operators.cpp

diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 5a33e918db8e8c0..a6c81f467fbe01c 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -7806,7 +7806,8 @@ class ExprEvaluatorBase
   // Overloaded operator calls to member functions are represented as 
normal
   // calls with '*this' as the first argument.
   const CXXMethodDecl *MD = dyn_cast(FD);
-  if (MD && MD->isImplicitObjectMemberFunction()) {
+  if (MD &&
+  (MD->isImplicitObjectMemberFunction() || (OCE && MD->isStatic( {
 // FIXME: When selecting an implicit conversion for an overloaded
 // operator delete, we sometimes try to evaluate calls to conversion
 // operators without a 'this' parameter!
diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index 54a1d300a9ac738..19406ff174dea14 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -5070,7 +5070,7 @@ RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
   if (const auto *CE = dyn_cast(E))
 if (const auto *MD =
 dyn_cast_if_present(CE->getCalleeDecl());
-MD && MD->isImplicitObjectMemberFunction())
+MD && !MD->isExplicitObjectMemberFunction())
   return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
 
   CGCallee callee = EmitCallee(E->getCallee());
diff --git a/clang/lib/CodeGen/CGExprCXX.cpp b/clang/lib/CodeGen/CGExprCXX.cpp
index 2e7059cc8f5b639..a580c635998510f 100644
--- a/clang/lib/CodeGen/CGExprCXX.cpp
+++ b/clang/lib/CodeGen/CGExprCXX.cpp
@@ -489,11 +489,42 @@ RValue
 CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
const CXXMethodDecl *MD,
ReturnValueSlot ReturnValue) {
-  assert(MD->isImplicitObjectMemberFunction() &&
- "Trying to emit a member call expr on a static method!");
-  return EmitCXXMemberOrOperatorMemberCallExpr(
-  E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr,
-  /*IsArrow=*/false, E->getArg(0));
+  assert(!MD->isExplicitObjectMemberFunction() &&
+ "Trying to emit a member call expr on an explicit object member "
+ "function!");
+
+  if (MD->isStatic())
+return EmitCXXStaticOperatorMemberCallExpr(E, MD, ReturnValue);
+  else
+return EmitCXXMemberOrOperatorMemberCallExpr(
+E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr,
+/*IsArrow=*/false, E->getArg(0));
+}
+
+RValue CodeGenFunction::EmitCXXStaticOperatorMemberCallExpr(
+const CXXOperatorCallExpr *E, const CXXMethodDecl *MD,
+ReturnValueSlot ReturnValue) {
+  assert(MD->isStatic());
+
+  CGCallee Callee = EmitCallee(E->getCallee());
+
+  // Emit and ignore `this` pointer.
+  EmitIgnoredExpr(E->getArg(0));
+
+  auto ProtoType = MD->getFunctionType()->castAs();
+
+  // Emit the rest of the call args.
+  CallArgList Args;
+  EmitCallArgs(Args, ProtoType, drop_begin(E->arguments(), 1),
+   E->getDirectCallee());
+
+  bool Chain = E == MustTailCall;
+  const CGFunctionInfo &FnInfo =
+  CGM.getTypes().arrangeFreeFunctionCall(Args, ProtoType, Chain);
+  llvm::CallBase *CallOrInvoke = nullptr;
+
+  return EmitCall(FnInfo, Callee, ReturnValue, Args, &CallOrInvoke, Chain,
+  E->getExprLoc());
 }
 
 RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
diff --git a/clang/lib/CodeGen/CodeGenFunction.h 
b/clang/lib/CodeGen/CodeGenFunction.h
index d5336382a2b9c95..42de125e7489911 100644
--- a/clang/lib/CodeGen/CodeGenFunction.h
+++ b/clang/lib/CodeGen/CodeGenFunction.h
@@ -4163,6 +4163,9 @@ class CodeGenFunction : public CodeGenTypeCache {
   RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
const CXXMethodDecl *MD,
ReturnValueSlot ReturnValue);
+  RValue EmitCXXStaticOperatorMemberCallExpr(const CXXOperatorCallEx

[clang] [AST] Use explicit type erasure in TypeSourceInfo constructor (PR #68435)

2023-10-10 Thread via cfe-commits


@@ -243,7 +243,7 @@ class TypeLoc {
 
 inline TypeSourceInfo::TypeSourceInfo(QualType ty, size_t DataSize) : Ty(ty) {
   // Init data attached to the object. See getTypeLoc.
-  memset(this + 1, 0, DataSize);
+  memset(const_cast(static_cast(this + 1)), 0, DataSize);

cor3ntin wrote:

```suggestion
  memset(static_cast(this + 1), 0, DataSize);
```

This should be enough, right?

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


[clang] [flang][driver] Mark -fcommon and -mtune as visible in Flang (PR #68657)

2023-10-10 Thread Fangcao Wang via cfe-commits

https://github.com/LittleMeepo updated 
https://github.com/llvm/llvm-project/pull/68657

>From b7de162c0cd91864b1637ec184457b825e8727bc Mon Sep 17 00:00:00 2001
From: wangfc 
Date: Tue, 10 Oct 2023 11:06:11 +0800
Subject: [PATCH] [flang][driver] Mark -fcommon and -mtune as visible in Flang

---
 clang/include/clang/Driver/Options.td| 3 ++-
 flang/test/Driver/driver-help-hidden.f90 | 2 ++
 flang/test/Driver/driver-help.f90| 2 ++
 flang/test/Driver/misc-flags.f90 | 3 +++
 4 files changed, 9 insertions(+), 1 deletion(-)

diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 5415b18d3f406df..8936df388d2db97 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1786,7 +1786,7 @@ def fno_record_command_line : Flag<["-"], 
"fno-record-command-line">,
 def : Flag<["-"], "frecord-gcc-switches">, Alias;
 def : Flag<["-"], "fno-record-gcc-switches">, Alias;
 def fcommon : Flag<["-"], "fcommon">, Group,
-  Visibility<[ClangOption, CLOption, CC1Option]>,
+  Visibility<[ClangOption, CLOption, CC1Option, FlangOption]>,
   HelpText<"Place uninitialized global variables in a common block">,
   MarshallingInfoNegativeFlag>,
   DocBrief<[{Place definitions of variables with no storage class and no 
initializer
@@ -5077,6 +5077,7 @@ def module_file_info : Flag<["-"], "module-file-info">, 
Flags<[NoXarchOption]>,
   HelpText<"Provide information about a particular module file">;
 def mthumb : Flag<["-"], "mthumb">, Group;
 def mtune_EQ : Joined<["-"], "mtune=">, Group,
+  Flags<[TargetSpecific]>, Visibility<[ClangOption, CLOption, DXCOption, 
FlangOption]>,
   HelpText<"Only supported on AArch64, PowerPC, RISC-V, SystemZ, and X86">;
 def multi__module : Flag<["-"], "multi_module">;
 def multiply__defined__unused : Separate<["-"], "multiply_defined_unused">;
diff --git a/flang/test/Driver/driver-help-hidden.f90 
b/flang/test/Driver/driver-help-hidden.f90
index 807b0f938d27b5c..55eb03256aa33bc 100644
--- a/flang/test/Driver/driver-help-hidden.f90
+++ b/flang/test/Driver/driver-help-hidden.f90
@@ -29,6 +29,7 @@
 ! CHECK-NEXT: -fapprox-func   Allow certain math function calls to be 
replaced with an approximately equivalent calculation
 ! CHECK-NEXT: -fbackslash Specify that backslash in string 
introduces an escape character
 ! CHECK-NEXT: -fcolor-diagnostics Enable colors in diagnostics
+! CHECK-NEXT: -fcommonPlace uninitialized global variables in 
a common block
 ! CHECK-NEXT: -fconvert=   Set endian conversion of data for 
unformatted files
 ! CHECK-NEXT: -fdefault-double-8  Set the default double precision kind to 
an 8 byte wide type
 ! CHECK-NEXT: -fdefault-integer-8 Set the default integer and logical kind 
to an 8 byte wide type
@@ -112,6 +113,7 @@
 ! CHECK-NEXT: -module-dirPut MODULE files in 
 ! CHECK-NEXT: -msve-vector-bits=
 ! CHECK-NEXT:  Specify the size in bits of an SVE 
vector register. Defaults to the vector length agnostic value of "scalable". 
(AArch64 only)
+! CHECK-NEXT: -mtune=  Only supported on AArch64, PowerPC, 
RISC-V, SystemZ, and X86
 ! CHECK-NEXT: --no-offload-arch=
 ! CHECK-NEXT: Remove CUDA/HIP offloading device 
architecture (e.g. sm_35, gfx906) from the list of devices to compile for. 
'all' resets the list to its default value.
 ! CHECK-NEXT: -nocpp  Disable predefined and command line 
preprocessor macros
diff --git a/flang/test/Driver/driver-help.f90 
b/flang/test/Driver/driver-help.f90
index 4894f90f5310439..289bf3397250f2d 100644
--- a/flang/test/Driver/driver-help.f90
+++ b/flang/test/Driver/driver-help.f90
@@ -25,6 +25,7 @@
 ! HELP-NEXT: -fapprox-func   Allow certain math function calls to be 
replaced with an approximately equivalent calculation
 ! HELP-NEXT: -fbackslash Specify that backslash in string 
introduces an escape character
 ! HELP-NEXT: -fcolor-diagnostics Enable colors in diagnostics
+! HELP-NEXT: -fcommonPlace uninitialized global variables in a 
common block
 ! HELP-NEXT: -fconvert=   Set endian conversion of data for 
unformatted files
 ! HELP-NEXT: -fdefault-double-8  Set the default double precision kind to 
an 8 byte wide type
 ! HELP-NEXT: -fdefault-integer-8 Set the default integer and logical kind 
to an 8 byte wide type
@@ -100,6 +101,7 @@
 ! HELP-NEXT: -module-dirPut MODULE files in 
 ! HELP-NEXT: -msve-vector-bits=
 ! HELP-NEXT:  Specify the size in bits of an SVE 
vector register. Defaults to the vector length agnostic value of "scalable". 
(AArch64 only)
+! HELP-NEXT: -mtune=  Only supported on AArch64, PowerPC, 
RISC-V, SystemZ, and X86
 ! HELP-NEXT: --no-offload-arch=
 ! HELP-NEXT: Remove CUDA/HIP offloading device 
architecture (e.g. sm_35, gfx906) from the list of devices to compile for. 
'all' resets the 

[clang] 3542dd8 - [clang][Interp][NFC] Move int128 tests to their own file

2023-10-10 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-10-10T09:54:08+02:00
New Revision: 3542dd8f9179dc25ac0a21972d1d4fe66da174e0

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

LOG: [clang][Interp][NFC] Move int128 tests to their own file

Added: 
clang/test/AST/Interp/intap.cpp

Modified: 
clang/test/AST/Interp/literals.cpp

Removed: 




diff  --git a/clang/test/AST/Interp/intap.cpp b/clang/test/AST/Interp/intap.cpp
new file mode 100644
index 000..4ca65e104048487
--- /dev/null
+++ b/clang/test/AST/Interp/intap.cpp
@@ -0,0 +1,79 @@
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -fms-extensions 
-std=c++11 -verify %s
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -fms-extensions 
-std=c++20 -verify %s
+// RUN: %clang_cc1 -std=c++11 -fms-extensions -verify=ref %s
+// RUN: %clang_cc1 -std=c++20 -fms-extensions -verify=ref %s
+
+#ifdef __SIZEOF_INT128__
+namespace i128 {
+  typedef __int128 int128_t;
+  typedef unsigned __int128 uint128_t;
+  constexpr int128_t I128_1 = 12;
+  static_assert(I128_1 == 12, "");
+  static_assert(I128_1 != 10, "");
+  static_assert(I128_1 != 12, ""); // expected-error{{failed}} \
+   // ref-error{{failed}} \
+   // expected-note{{evaluates to}} \
+   // ref-note{{evaluates to}}
+
+  static const __uint128_t UINT128_MAX =__uint128_t(__int128_t(-1L));
+  static_assert(UINT128_MAX == -1, "");
+
+  static const __int128_t INT128_MAX = UINT128_MAX >> (__int128_t)1;
+  static_assert(INT128_MAX != 0, "");
+  static const __int128_t INT128_MIN = -INT128_MAX - 1;
+  constexpr __int128 A = INT128_MAX + 1; // expected-error {{must be 
initialized by a constant expression}} \
+ // expected-note {{outside the 
range}} \
+ // ref-error {{must be initialized by 
a constant expression}} \
+ // ref-note {{outside the range}}
+  constexpr int128_t Two = (int128_t)1 << 1ul;
+  static_assert(Two == 2, "");
+
+  constexpr uint128_t AllOnes = ~static_cast(0);
+  static_assert(AllOnes == UINT128_MAX, "");
+
+#if __cplusplus >= 201402L
+  template 
+  constexpr T CastFrom(__int128_t A) {
+T B = (T)A;
+return B;
+  }
+  static_assert(CastFrom(12) == 12, "");
+  static_assert(CastFrom(12) == 12, "");
+  static_assert(CastFrom(12) == 12, "");
+  static_assert(CastFrom(12) == 12, "");
+  static_assert(CastFrom(12) == 12, "");
+  static_assert(CastFrom(12) == 12, "");
+  static_assert(CastFrom(12) == 12, "");
+  static_assert(CastFrom(12) == 12, "");
+
+  static_assert(CastFrom(AllOnes) == -1, "");
+  static_assert(CastFrom(AllOnes) == 0xFF, "");
+  static_assert(CastFrom(AllOnes) == -1, "");
+  static_assert(CastFrom(AllOnes) == 0x, "");
+  static_assert(CastFrom(AllOnes) == -1, "");
+  static_assert(CastFrom(AllOnes) == -1, "");
+  static_assert(CastFrom(AllOnes) == AllOnes, "");
+
+  template 
+  constexpr __int128 CastTo(T A) {
+int128_t B = (int128_t)A;
+return B;
+  }
+  static_assert(CastTo(12) == 12, "");
+  static_assert(CastTo(12) == 12, "");
+  static_assert(CastTo(12) == 12, "");
+  static_assert(CastTo(12) == 12, "");
+  static_assert(CastTo(12) == 12, "");
+  static_assert(CastTo(12) == 12, "");
+  static_assert(CastTo(12) == 12, "");
+#endif
+
+  constexpr int128_t Error = __LDBL_MAX__; // ref-warning {{implicit 
conversion of out of range value}} \
+   // ref-error {{must be initialized 
by a constant expression}} \
+   // ref-note {{is outside the range 
of representable values of type}} \
+   // expected-warning {{implicit 
conversion of out of range value}} \
+   // expected-error {{must be 
initialized by a constant expression}} \
+   // expected-note {{is outside the 
range of representable values of type}}
+}
+
+#endif

diff  --git a/clang/test/AST/Interp/literals.cpp 
b/clang/test/AST/Interp/literals.cpp
index 00875bcf44dc8e6..ceda59405ea9105 100644
--- a/clang/test/AST/Interp/literals.cpp
+++ b/clang/test/AST/Interp/literals.cpp
@@ -26,81 +26,6 @@ static_assert(number != 10, ""); // expected-error{{failed}} 
\
  // expected-note{{evaluates to}} \
  // ref-note{{evaluates to}}
 
-
-#ifdef __SIZEOF_INT128__
-namespace i128 {
-  typedef __int128 int128_t;
-  typedef unsigned __int128 uint128_t;
-  constexpr int128_t I128_1 = 12;
-  static_assert(I128_1 == 12, "");
-  static_assert(I128_1 != 10, "");
-  static_assert(I128_1 != 12, ""); // expected-error

[clang-tools-extra] [Legalizer] Expand fmaximum and fminimum (PR #67301)

2023-10-10 Thread Jay Foad via cfe-commits


@@ -8177,6 +8177,64 @@ SDValue TargetLowering::expandFMINNUM_FMAXNUM(SDNode 
*Node,
   return SDValue();
 }
 
+SDValue TargetLowering::expandFMINIMUM_FMAXIMUM(SDNode *N,

jayfoad wrote:

> Can MIR be valid input for legalizers?

No, sorry, please ignore that part. I was thinking about GlobalISel not 
SelectionDAG.

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


[clang] [Legalizer] Expand fmaximum and fminimum (PR #67301)

2023-10-10 Thread Jay Foad via cfe-commits


@@ -8177,6 +8177,64 @@ SDValue TargetLowering::expandFMINNUM_FMAXNUM(SDNode 
*Node,
   return SDValue();
 }
 
+SDValue TargetLowering::expandFMINIMUM_FMAXIMUM(SDNode *N,

jayfoad wrote:

> Can MIR be valid input for legalizers?

No, sorry, please ignore that part. I was thinking about GlobalISel not 
SelectionDAG.

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


[clang] [Sema] Handle large shift counts in GetExprRange (PR #68590)

2023-10-10 Thread Björn Pettersson via cfe-commits

https://github.com/bjope updated https://github.com/llvm/llvm-project/pull/68590

From 8ef4560759280bbc14e0dc6c01efc036d0410dca Mon Sep 17 00:00:00 2001
From: Bjorn Pettersson 
Date: Mon, 9 Oct 2023 16:13:39 +0200
Subject: [PATCH] [Sema] Handle large shift counts in GetExprRange

GetExprRange did not expect that very large shift counts when
narrowing the range based on logical right shifts. So with inputs
such as
*a >> 123456789012345678901uwb
it would hit assertions about trying to convert a too large APInt
into uint64_t.
This patch fixes that by using the APInt value when determining if
we should reduce the range by the shift count or not.
---
 clang/docs/ReleaseNotes.rst  |  4 
 clang/lib/Sema/SemaChecking.cpp  |  5 ++---
 clang/test/Sema/c2x-expr-range.c | 14 ++
 3 files changed, 20 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/Sema/c2x-expr-range.c

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 9c320bc8b35d23d..2d918967e7f0b02 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -378,6 +378,10 @@ Bug Fixes in This Version
 - Fix crash in evaluating ``constexpr`` value for invalid template function.
   Fixes (`#68542 `_)
 
+- Fixed an issue when a shift count larger than ``__INT64_MAX__``, in a right
+  shift operation, could result in missing warnings about
+  ``shift count >= width of type`` or internal compiler error.
+
 Bug Fixes to Compiler Builtins
 ^^
 
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 446e35218bff0ad..2594a8f97f7d94e 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -13596,11 +13596,10 @@ static IntRange GetExprRange(ASTContext &C, const 
Expr *E, unsigned MaxWidth,
   if (std::optional shift =
   BO->getRHS()->getIntegerConstantExpr(C)) {
 if (shift->isNonNegative()) {
-  unsigned zext = shift->getZExtValue();
-  if (zext >= L.Width)
+  if (shift->uge(L.Width))
 L.Width = (L.NonNegative ? 0 : 1);
   else
-L.Width -= zext;
+L.Width -= shift->getZExtValue();
 }
   }
 
diff --git a/clang/test/Sema/c2x-expr-range.c b/clang/test/Sema/c2x-expr-range.c
new file mode 100644
index 000..73683e6bfe684aa
--- /dev/null
+++ b/clang/test/Sema/c2x-expr-range.c
@@ -0,0 +1,14 @@
+// RUN: %clang_cc1 -verify -fsyntax-only -std=c2x -triple=x86_64-unknown-linux 
%s
+
+// Regression test for bug where we used to hit an assertion due to shift 
amount
+// being larger than 64 bits. We want to see a warning about too large shift
+// amount.
+void test1(int *a) {
+  (void)(*a >> 123456789012345678901uwb <= 0); // expected-warning {{shift 
count >= width of type}}
+}
+
+// Similar to test1 above, but using __uint128_t instead of __BitInt.
+// We want to see a warning about too large shift amount.
+void test2(__uint128_t *a) {
+  (void)(*a >> ((__uint128_t)__UINT64_MAX__ + 1) <= 0); // expected-warning 
{{shift count >= width of type}}
+}

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


[clang-tools-extra] [AMDGPU] Add encoding/decoding support for non-result-returning ATOMIC_CSUB instructions (PR #68197)

2023-10-10 Thread Stephen Thomas via cfe-commits

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


[clang] [clang][Interp] Handle CXXScalarValueInitExprs (PR #67147)

2023-10-10 Thread Timm Baeder via cfe-commits

https://github.com/tbaederr updated 
https://github.com/llvm/llvm-project/pull/67147

>From 54840541b94b5ccc02c1c563678991ea230acbb7 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Fri, 22 Sep 2023 16:27:11 +0200
Subject: [PATCH] [clang][Interp] Handle CXXScalarValueInitExprs

---
 clang/lib/AST/Interp/ByteCodeExprGen.cpp |  6 ++
 clang/lib/AST/Interp/ByteCodeExprGen.h   |  1 +
 clang/test/AST/Interp/literals.cpp   | 27 
 3 files changed, 34 insertions(+)

diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 02b35583636bf13..9bd040a208b3f95 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -1531,6 +1531,12 @@ bool ByteCodeExprGen::VisitOffsetOfExpr(const 
OffsetOfExpr *E) {
   return this->emitOffsetOf(T, E, E);
 }
 
+template 
+bool ByteCodeExprGen::VisitCXXScalarValueInitExpr(
+const CXXScalarValueInitExpr *E) {
+  return this->visitZeroInitializer(E->getType(), E);
+}
+
 template  bool ByteCodeExprGen::discard(const Expr *E) 
{
   if (E->containsErrors())
 return false;
diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.h 
b/clang/lib/AST/Interp/ByteCodeExprGen.h
index 47a3f75f13459d0..7cfe4d9251c5f05 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.h
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -106,6 +106,7 @@ class ByteCodeExprGen : public 
ConstStmtVisitor, bool>,
   bool VisitCXXConstructExpr(const CXXConstructExpr *E);
   bool VisitSourceLocExpr(const SourceLocExpr *E);
   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
+  bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
 
 protected:
   bool visitExpr(const Expr *E) override;
diff --git a/clang/test/AST/Interp/literals.cpp 
b/clang/test/AST/Interp/literals.cpp
index ceda59405ea9105..a83dcd234111587 100644
--- a/clang/test/AST/Interp/literals.cpp
+++ b/clang/test/AST/Interp/literals.cpp
@@ -31,6 +31,33 @@ static_assert(b, "");
 constexpr int one = true;
 static_assert(one == 1, "");
 
+constexpr bool b2 = bool();
+static_assert(!b2, "");
+
+namespace ScalarTypes {
+  constexpr int ScalarInitInt = int();
+  static_assert(ScalarInitInt == 0, "");
+  constexpr float ScalarInitFloat = float();
+  static_assert(ScalarInitFloat == 0.0f, "");
+
+  static_assert(decltype(nullptr)() == nullptr, "");
+
+  template
+  constexpr T getScalar() { return T(); }
+
+  static_assert(getScalar() == 0, "");
+  static_assert(getScalar() == 0.0, "");
+
+  static_assert(getScalar() == nullptr, "");
+  static_assert(getScalar() == nullptr, "");
+
+  enum E {
+First = 0,
+  };
+  static_assert(getScalar() == First, "");
+  /// FIXME: Member pointers.
+}
+
 namespace IntegralCasts {
   constexpr int i = 12;
   constexpr unsigned int ui = i;

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


[clang] [clang] Implement constexpr bit_cast for vectors (PR #66894)

2023-10-10 Thread via cfe-commits

https://github.com/DaMatrix updated 
https://github.com/llvm/llvm-project/pull/66894

>From 95c018c67b5ca10e86065fc3d0cb60f507626f34 Mon Sep 17 00:00:00 2001
From: DaPorkchop_ 
Date: Sun, 13 Aug 2023 22:39:12 +0200
Subject: [PATCH] [clang] Implement constexpr bit_cast for vectors

---
 .../include/clang/Basic/DiagnosticASTKinds.td |   3 +
 clang/lib/AST/ExprConstant.cpp| 263 +++---
 clang/lib/CodeGen/CGExprConstant.cpp  |   3 +
 clang/test/CodeGen/const-init.c   |   7 +-
 .../constexpr-builtin-bit-cast-fp80.cpp   |  38 +++
 .../SemaCXX/constexpr-builtin-bit-cast.cpp|  44 +++
 6 files changed, 261 insertions(+), 97 deletions(-)
 create mode 100644 clang/test/SemaCXX/constexpr-builtin-bit-cast-fp80.cpp

diff --git a/clang/include/clang/Basic/DiagnosticASTKinds.td 
b/clang/include/clang/Basic/DiagnosticASTKinds.td
index d2656310e79c9b8..3f06e18783dd558 100644
--- a/clang/include/clang/Basic/DiagnosticASTKinds.td
+++ b/clang/include/clang/Basic/DiagnosticASTKinds.td
@@ -326,6 +326,9 @@ def note_constexpr_bit_cast_invalid_type : Note<
   "%select{type|member}1 is not allowed in a constant expression">;
 def note_constexpr_bit_cast_invalid_subtype : Note<
   "invalid type %0 is a %select{member|base}1 of %2">;
+def note_constexpr_bit_cast_invalid_vector : Note<
+  "bit_cast involving type %0 is not allowed in a constant expression; "
+  "element size %1 * element count %2 is not a multiple of the byte size %3">;
 def note_constexpr_bit_cast_indet_dest : Note<
   "indeterminate value can only initialize an object of type 'unsigned char'"
   "%select{, 'char',|}1 or 'std::byte'; %0 is invalid">;
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index a142ea7c47a4730..7f52916b8a5809c 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -2732,53 +2732,6 @@ static bool truncateBitfieldValue(EvalInfo &Info, const 
Expr *E,
   return true;
 }
 
-static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
-  llvm::APInt &Res) {
-  APValue SVal;
-  if (!Evaluate(SVal, Info, E))
-return false;
-  if (SVal.isInt()) {
-Res = SVal.getInt();
-return true;
-  }
-  if (SVal.isFloat()) {
-Res = SVal.getFloat().bitcastToAPInt();
-return true;
-  }
-  if (SVal.isVector()) {
-QualType VecTy = E->getType();
-unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
-QualType EltTy = VecTy->castAs()->getElementType();
-unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
-bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
-Res = llvm::APInt::getZero(VecSize);
-for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
-  APValue &Elt = SVal.getVectorElt(i);
-  llvm::APInt EltAsInt;
-  if (Elt.isInt()) {
-EltAsInt = Elt.getInt();
-  } else if (Elt.isFloat()) {
-EltAsInt = Elt.getFloat().bitcastToAPInt();
-  } else {
-// Don't try to handle vectors of anything other than int or float
-// (not sure if it's possible to hit this case).
-Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
-return false;
-  }
-  unsigned BaseEltSize = EltAsInt.getBitWidth();
-  if (BigEndian)
-Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
-  else
-Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
-}
-return true;
-  }
-  // Give up if the input isn't an int, float, or vector.  For example, we
-  // reject "(v4i16)(intptr_t)&a".
-  Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
-  return false;
-}
-
 /// Perform the given integer operation, which is known to need at most 
BitWidth
 /// bits, and check for overflow in the original type (if that type was not an
 /// unsigned type).
@@ -7008,10 +6961,11 @@ class APValueToBufferConverter {
   return visitArray(Val, Ty, Offset);
 case APValue::Struct:
   return visitRecord(Val, Ty, Offset);
+case APValue::Vector:
+  return visitVector(Val, Ty, Offset);
 
 case APValue::ComplexInt:
 case APValue::ComplexFloat:
-case APValue::Vector:
 case APValue::FixedPoint:
   // FIXME: We should support these.
 
@@ -7098,6 +7052,69 @@ class APValueToBufferConverter {
 return true;
   }
 
+  bool visitVector(const APValue &Val, QualType Ty, CharUnits Offset) {
+const VectorType *VTy = Ty->castAs();
+QualType EltTy = VTy->getElementType();
+unsigned NElts = VTy->getNumElements();
+unsigned EltSize =
+VTy->isExtVectorBoolType() ? 1 : Info.Ctx.getTypeSize(EltTy);
+
+if ((NElts * EltSize) % Info.Ctx.getCharWidth() != 0) {
+  // The vector's size in bits is not a multiple of the target's byte size,
+  // so its layout is unspecified. For now, we'll simply treat these cases
+  // as unsupported (this should only be possible with OpenCL bool vectors
+  // whose element count isn't a multiple of the byte size).
+  I

[clang] [AArch64][SME] Remove immediate argument restriction for svldr and svstr (PR #68565)

2023-10-10 Thread Sander de Smalen via cfe-commits

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


[clang] [AArch64][SME] Remove immediate argument restriction for svldr and svstr (PR #68565)

2023-10-10 Thread Sander de Smalen via cfe-commits


@@ -9665,18 +9665,34 @@ Value *CodeGenFunction::EmitSMEZero(const SVETypeFlags 
&TypeFlags,
 Value *CodeGenFunction::EmitSMELdrStr(const SVETypeFlags &TypeFlags,
   SmallVectorImpl &Ops,
   unsigned IntID) {
-  if (Ops.size() == 3) {
-Function *Cntsb = CGM.getIntrinsic(Intrinsic::aarch64_sme_cntsb);
-llvm::Value *CntsbCall = Builder.CreateCall(Cntsb, {}, "svlb");
-llvm::Value *MulVL = Builder.CreateMul(
-CntsbCall,
-Builder.getInt64(cast(Ops[2])->getZExtValue()),
-"mulvl");
-
-Ops[1] = Builder.CreateGEP(Int8Ty, Ops[1], MulVL);
-Ops[0] = EmitTileslice(Ops[0], Ops[2]);
-Ops.erase(&Ops[2]);
-  }
+  if (Ops.size() == 2) {
+// Intrinsics without a vecnum also use this function, so just provide 0
+Ops.push_back(Ops[1]);
+Ops[1] = Builder.getInt32(0);
+  } else {
+int Imm = -1;
+if (ConstantInt* C = dyn_cast(Ops[2]))
+  if (C->getZExtValue() <= 15)
+  Imm = C->getZExtValue();
+
+if (Imm != -1) {

sdesmalen-arm wrote:

Rather than checking this in Clang, I think it makes more sense to handle this 
in SelectionDAG.
The reason for that is that when someone uses this intrinsic inside a loop like 
this:

```
for(int i=0; ihttps://github.com/llvm/llvm-project/pull/68565
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [AArch64][SME] Remove immediate argument restriction for svldr and svstr (PR #68565)

2023-10-10 Thread Sander de Smalen via cfe-commits


@@ -44,10 +44,9 @@ defm SVLD1_ZA32 : ZALoad<"za32", "i", "aarch64_sme_ld1w", 
[ImmCheck<0, ImmCheck0
 defm SVLD1_ZA64 : ZALoad<"za64", "l", "aarch64_sme_ld1d", [ImmCheck<0, 
ImmCheck0_7>]>;
 defm SVLD1_ZA128 : ZALoad<"za128", "q", "aarch64_sme_ld1q", [ImmCheck<0, 
ImmCheck0_15>]>;
 
-def SVLDR_VNUM_ZA : MInst<"svldr_vnum_za", "vmQi", "",
+def SVLDR_VNUM_ZA : MInst<"svldr_vnum_za", "vmQn", "",

sdesmalen-arm wrote:

It must be `vmQl`, because `vnum`is a signed 64-bit integer (`int64_t`)

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


[clang] [AArch64][SME] Remove immediate argument restriction for svldr and svstr (PR #68565)

2023-10-10 Thread Sander de Smalen via cfe-commits


@@ -2680,9 +2680,9 @@ let TargetPrefix = "aarch64" in {
 
   // Spill + fill
   def int_aarch64_sme_ldr : DefaultAttrsIntrinsic<
-[], [llvm_i32_ty, llvm_ptr_ty]>;
+[], [llvm_i32_ty, llvm_i32_ty, llvm_ptr_ty], [ImmArg>]>;

sdesmalen-arm wrote:

Is it easier to add the `vnum` argument last, so that you don't need to swap 
the operands in CGBuiltins?

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


[clang] [AArch64][SME] Remove immediate argument restriction for svldr and svstr (PR #68565)

2023-10-10 Thread Sander de Smalen via cfe-commits

https://github.com/sdesmalen-arm commented:

The changes to the LLVM IR intrinsics are to better utilise the reg+imm form of 
the instructions, but they aren't required to remove the immediate-argument 
restriction for svldr/svstr. I think it would be better to split the PR into 
two PRs:
* One patch that fixes `vnum` (uint64_t -> int64_t) and removes the 'must be 
immediate argument' restriction.
* Another patch that tries to better use the immediate in the instruction by 
changing the LLVM IR intrinsic with an extra parameter.

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


[clang] 7d2b569 - [Sema] Handle large shift counts in GetExprRange (#68590)

2023-10-10 Thread via cfe-commits

Author: Björn Pettersson
Date: 2023-10-10T10:25:01+02:00
New Revision: 7d2b569cc42487c85982aa3ebc8243204042d2ce

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

LOG: [Sema] Handle large shift counts in GetExprRange (#68590)

GetExprRange did not expect that very large shift counts when
narrowing the range based on logical right shifts. So with inputs
such as
*a >> 123456789012345678901uwb
it would hit assertions about trying to convert a too large APInt
into uint64_t.
This patch fixes that by using the APInt value when determining if
we should reduce the range by the shift count or not.

Added: 
clang/test/Sema/c2x-expr-range.c

Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaChecking.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 9c320bc8b35d23d..2d918967e7f0b02 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -378,6 +378,10 @@ Bug Fixes in This Version
 - Fix crash in evaluating ``constexpr`` value for invalid template function.
   Fixes (`#68542 `_)
 
+- Fixed an issue when a shift count larger than ``__INT64_MAX__``, in a right
+  shift operation, could result in missing warnings about
+  ``shift count >= width of type`` or internal compiler error.
+
 Bug Fixes to Compiler Builtins
 ^^
 

diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 446e35218bff0ad..2594a8f97f7d94e 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -13596,11 +13596,10 @@ static IntRange GetExprRange(ASTContext &C, const 
Expr *E, unsigned MaxWidth,
   if (std::optional shift =
   BO->getRHS()->getIntegerConstantExpr(C)) {
 if (shift->isNonNegative()) {
-  unsigned zext = shift->getZExtValue();
-  if (zext >= L.Width)
+  if (shift->uge(L.Width))
 L.Width = (L.NonNegative ? 0 : 1);
   else
-L.Width -= zext;
+L.Width -= shift->getZExtValue();
 }
   }
 

diff  --git a/clang/test/Sema/c2x-expr-range.c 
b/clang/test/Sema/c2x-expr-range.c
new file mode 100644
index 000..73683e6bfe684aa
--- /dev/null
+++ b/clang/test/Sema/c2x-expr-range.c
@@ -0,0 +1,14 @@
+// RUN: %clang_cc1 -verify -fsyntax-only -std=c2x -triple=x86_64-unknown-linux 
%s
+
+// Regression test for bug where we used to hit an assertion due to shift 
amount
+// being larger than 64 bits. We want to see a warning about too large shift
+// amount.
+void test1(int *a) {
+  (void)(*a >> 123456789012345678901uwb <= 0); // expected-warning {{shift 
count >= width of type}}
+}
+
+// Similar to test1 above, but using __uint128_t instead of __BitInt.
+// We want to see a warning about too large shift amount.
+void test2(__uint128_t *a) {
+  (void)(*a >> ((__uint128_t)__UINT64_MAX__ + 1) <= 0); // expected-warning 
{{shift count >= width of type}}
+}



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


[clang] [Sema] Handle large shift counts in GetExprRange (PR #68590)

2023-10-10 Thread Björn Pettersson via cfe-commits

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


[clang] [clang][Interp] Fix returning nullptr from functions (PR #67229)

2023-10-10 Thread Timm Baeder via cfe-commits

https://github.com/tbaederr updated 
https://github.com/llvm/llvm-project/pull/67229

>From 32d5ecddc5b6aff0924b48a0b35128be7b07 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Sat, 23 Sep 2023 11:41:52 +0200
Subject: [PATCH] [clang][Interp] Fix returning nullptr from functions

isLive() is false for null pointers, so we need to special-case
this here.
---
 clang/lib/AST/Interp/Interp.h   | 3 ++-
 clang/test/AST/Interp/functions.cpp | 7 +++
 2 files changed, 9 insertions(+), 1 deletion(-)

diff --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index d62e64bedb213ac..47dc1d08c9c4d8b 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -214,7 +214,8 @@ bool Ret(InterpState &S, CodePtr &PC, APValue &Result) {
 // FIXME: We could be calling isLive() here, but the emitted diagnostics
 // seem a little weird, at least if the returned expression is of
 // pointer type.
-if (!Ret.isLive())
+// Null pointers are considered live here.
+if (!Ret.isZero() && !Ret.isLive())
   return false;
   }
 
diff --git a/clang/test/AST/Interp/functions.cpp 
b/clang/test/AST/Interp/functions.cpp
index 5cdecbff1e9d3d4..68082576f2735e9 100644
--- a/clang/test/AST/Interp/functions.cpp
+++ b/clang/test/AST/Interp/functions.cpp
@@ -343,3 +343,10 @@ namespace TemplateUndefined {
   constexpr int l = consume(0);
   static_assert(l == 0, "");
 }
+
+namespace PtrReturn {
+  constexpr void *a() {
+return nullptr;
+  }
+  static_assert(a() == nullptr, "");
+}

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


[PATCH] D158156: [analyzer] Add C++ array delete checker

2023-10-10 Thread Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG71ae858c079f: [clang][analyzer] Rename 
DeleteWithNonVirtualDtorChecker to CXXDeleteChecker (authored by Viktor Cseh 
).

Changed prior to commit:
  https://reviews.llvm.org/D158156?vs=557439&id=557664#toc

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D158156/new/

https://reviews.llvm.org/D158156

Files:
  clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
  clang/lib/StaticAnalyzer/Checkers/CXXDeleteChecker.cpp
  clang/lib/StaticAnalyzer/Checkers/DeleteWithNonVirtualDtorChecker.cpp


Index: clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
===
--- clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
+++ clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
@@ -30,12 +30,12 @@
   CloneChecker.cpp
   ContainerModeling.cpp
   ConversionChecker.cpp
+  CXXDeleteChecker.cpp
   CXXSelfAssignmentChecker.cpp
   DeadStoresChecker.cpp
   DebugCheckers.cpp
   DebugContainerModeling.cpp
   DebugIteratorModeling.cpp
-  DeleteWithNonVirtualDtorChecker.cpp
   DereferenceChecker.cpp
   DirectIvarAssignment.cpp
   DivZeroChecker.cpp


Index: clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
===
--- clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
+++ clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
@@ -30,12 +30,12 @@
   CloneChecker.cpp
   ContainerModeling.cpp
   ConversionChecker.cpp
+  CXXDeleteChecker.cpp
   CXXSelfAssignmentChecker.cpp
   DeadStoresChecker.cpp
   DebugCheckers.cpp
   DebugContainerModeling.cpp
   DebugIteratorModeling.cpp
-  DeleteWithNonVirtualDtorChecker.cpp
   DereferenceChecker.cpp
   DirectIvarAssignment.cpp
   DivZeroChecker.cpp
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 0e246bb - [clang][analyzer] Add C++ array delete checker

2023-10-10 Thread Viktor Cseh via cfe-commits

Author: Viktor Cseh
Date: 2023-10-10T09:37:02+01:00
New Revision: 0e246bb67573799409d0085b89902a330998ddcc

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

LOG: [clang][analyzer] Add C++ array delete checker

This checker reports cases where an array of polymorphic objects are
deleted as their base class. Deleting an array where the array's static
type is different from its dynamic type is undefined.

Since the checker is similar to DeleteWithNonVirtualDtorChecker, I
refactored that checker to support more detection types.

This checker corresponds to the SEI Cert rule EXP51-CPP: Do not delete
an array through a pointer of the incorrect type.

Differential Revision: https://reviews.llvm.org/D158156

Added: 
clang/test/Analysis/ArrayDelete.cpp

Modified: 
clang/docs/analyzer/checkers.rst
clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
clang/lib/StaticAnalyzer/Checkers/CXXDeleteChecker.cpp
clang/test/Analysis/DeleteWithNonVirtualDtor.cpp
clang/www/analyzer/alpha_checks.html

Removed: 




diff  --git a/clang/docs/analyzer/checkers.rst 
b/clang/docs/analyzer/checkers.rst
index dbd6d7787823530..81f333e644f31c9 100644
--- a/clang/docs/analyzer/checkers.rst
+++ b/clang/docs/analyzer/checkers.rst
@@ -1834,6 +1834,30 @@ Either the comparison is useless or there is division by 
zero.
 alpha.cplusplus
 ^^^
 
+.. _alpha-cplusplus-ArrayDelete:
+
+alpha.cplusplus.ArrayDelete (C++)
+"
+Reports destructions of arrays of polymorphic objects that are destructed as 
their base class.
+This checker corresponds to the CERT rule `EXP51-CPP: Do not delete an array 
through a pointer of the incorrect type 
`_.
+
+.. code-block:: cpp
+
+ class Base {
+   virtual ~Base() {}
+ };
+ class Derived : public Base {}
+
+ Base *create() {
+   Base *x = new Derived[10]; // note: Casting from 'Derived' to 'Base' here
+   return x;
+ }
+
+ void foo() {
+   Base *x = create();
+   delete[] x; // warn: Deleting an array of 'Derived' objects as their base 
class 'Base' is undefined
+ }
+
 .. _alpha-cplusplus-DeleteWithNonVirtualDtor:
 
 alpha.cplusplus.DeleteWithNonVirtualDtor (C++)
@@ -1842,13 +1866,17 @@ Reports destructions of polymorphic objects with a 
non-virtual destructor in the
 
 .. code-block:: cpp
 
+ class NonVirtual {};
+ class NVDerived : public NonVirtual {};
+
  NonVirtual *create() {
-   NonVirtual *x = new NVDerived(); // note: conversion from derived to base
-//   happened here
+   NonVirtual *x = new NVDerived(); // note: Casting from 'NVDerived' to
+//   'NonVirtual' here
return x;
  }
 
- void sink(NonVirtual *x) {
+ void foo() {
+   NonVirtual *x = create();
delete x; // warn: destruction of a polymorphic object with no virtual
  //   destructor
  }

diff  --git a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td 
b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
index 65c1595eb6245dd..4ca8c98af8706aa 100644
--- a/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
+++ b/clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
@@ -758,6 +758,11 @@ def ContainerModeling : Checker<"ContainerModeling">,
   Documentation,
   Hidden;
 
+def CXXArrayDeleteChecker : Checker<"ArrayDelete">,
+  HelpText<"Reports destructions of arrays of polymorphic objects that are "
+   "destructed as their base class.">,
+  Documentation;
+
 def DeleteWithNonVirtualDtorChecker : Checker<"DeleteWithNonVirtualDtor">,
   HelpText<"Reports destructions of polymorphic objects with a non-virtual "
"destructor in their base class">,

diff  --git a/clang/lib/StaticAnalyzer/Checkers/CXXDeleteChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/CXXDeleteChecker.cpp
index 3c142b49ff7288d..1a1f5c530294038 100644
--- a/clang/lib/StaticAnalyzer/Checkers/CXXDeleteChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/CXXDeleteChecker.cpp
@@ -1,4 +1,4 @@
-//===-- DeleteWithNonVirtualDtorChecker.cpp ---*- C++ 
-*--//
+//=== CXXDeleteChecker.cpp -*- C++ 
-*--===//
 //
 // Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
 // See https://llvm.org/LICENSE.txt for license information.
@@ -6,17 +6,25 @@
 //
 
//===--===//
 //
-// Defines a checker for the OOP52-CPP CERT rule: Do not delete a polymorphic
-// object without a virtual destructor.
+// This file defines the following new checkers for C++ delete expressions:
 //
-// Diagnostic flags -Wnon-virtual-dt

[clang] 71ae858 - [clang][analyzer] Rename DeleteWithNonVirtualDtorChecker to CXXDeleteChecker

2023-10-10 Thread Viktor Cseh via cfe-commits

Author: Viktor Cseh
Date: 2023-10-10T09:37:02+01:00
New Revision: 71ae858c079f9b4a1a99511af57f47ffb6070920

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

LOG: [clang][analyzer] Rename DeleteWithNonVirtualDtorChecker to 
CXXDeleteChecker

This rename is done in a separate commit to preserve `git blame`,
before implementing CXXArrayDeleteChecker and refactoring the file.

Differential Revision: https://reviews.llvm.org/D158156

Added: 
clang/lib/StaticAnalyzer/Checkers/CXXDeleteChecker.cpp

Modified: 
clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt

Removed: 
clang/lib/StaticAnalyzer/Checkers/DeleteWithNonVirtualDtorChecker.cpp



diff  --git a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt 
b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
index ae849f59f90d3d9..d849649c96a0d13 100644
--- a/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
+++ b/clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt
@@ -30,12 +30,12 @@ add_clang_library(clangStaticAnalyzerCheckers
   CloneChecker.cpp
   ContainerModeling.cpp
   ConversionChecker.cpp
+  CXXDeleteChecker.cpp
   CXXSelfAssignmentChecker.cpp
   DeadStoresChecker.cpp
   DebugCheckers.cpp
   DebugContainerModeling.cpp
   DebugIteratorModeling.cpp
-  DeleteWithNonVirtualDtorChecker.cpp
   DereferenceChecker.cpp
   DirectIvarAssignment.cpp
   DivZeroChecker.cpp

diff  --git 
a/clang/lib/StaticAnalyzer/Checkers/DeleteWithNonVirtualDtorChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/CXXDeleteChecker.cpp
similarity index 100%
rename from 
clang/lib/StaticAnalyzer/Checkers/DeleteWithNonVirtualDtorChecker.cpp
rename to clang/lib/StaticAnalyzer/Checkers/CXXDeleteChecker.cpp



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


[clang] ce9077f - [clang][Interp] Fix intap tests if int128 is not supported

2023-10-10 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-10-10T10:38:05+02:00
New Revision: ce9077fe7f0ceb2800076aa1abb472de5df41f16

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

LOG: [clang][Interp] Fix intap tests if int128 is not supported

This test doesn't do anything in that case.
This broke some builders, e.g.:
https://lab.llvm.org/buildbot/#/builders/245/builds/15150

Added: 


Modified: 
clang/test/AST/Interp/intap.cpp

Removed: 




diff  --git a/clang/test/AST/Interp/intap.cpp b/clang/test/AST/Interp/intap.cpp
index 4ca65e104048487..b3f02d2b769531d 100644
--- a/clang/test/AST/Interp/intap.cpp
+++ b/clang/test/AST/Interp/intap.cpp
@@ -76,4 +76,9 @@ namespace i128 {
// expected-note {{is outside the 
range of representable values of type}}
 }
 
+#else
+/// No int128 support, so no expected directives.
+
+// expected-no-diagnostics
+// ref-no-diagnostics
 #endif



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


[clang] [clang][Interp] Fix returning nullptr from functions (PR #67229)

2023-10-10 Thread via cfe-commits

cor3ntin wrote:

@tbaederr Shafik already approved that - still looks good :)

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


[clang] [clang][Interp] Fix returning nullptr from functions (PR #67229)

2023-10-10 Thread Timm Baeder via cfe-commits

tbaederr wrote:

Yeah sorry for the unnecessary ping :) I'll push as soon as the CI is done.

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


[PATCH] D159351: [Sema] Change order of displayed overloads in diagnostics

2023-10-10 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added a subscriber: aaron.ballman.
cor3ntin added a comment.

+ @aaron.ballman


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D159351/new/

https://reviews.llvm.org/D159351

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


[PATCH] D156212: [clang][Interp] Implement remaining strcmp builtins

2023-10-10 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added a comment.

There are still unaddressed comment here. It would be nice to complete this 
before phab shuts down


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D156212/new/

https://reviews.llvm.org/D156212

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


[PATCH] D156212: [clang][Interp] Implement remaining strcmp builtins

2023-10-10 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder added a comment.

I have a local patch that implements these builtins by doing a bitcast to a 
buffer first. There is a comment in `ExprConstant.cpp` that talks about the 
same thing. That path probably makes more sense? I'd abandon this review then.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D156212/new/

https://reviews.llvm.org/D156212

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


[clang] [SVE][InstCombine] Delete redundante sel instructions with ptrue (PR #68463)

2023-10-10 Thread David Sherwood via cfe-commits


@@ -800,6 +800,13 @@ instCombineConvertFromSVBool(InstCombiner &IC, 
IntrinsicInst &II) {
 
 static std::optional instCombineSVESel(InstCombiner &IC,
   IntrinsicInst &II) {
+  // svsel(ptrue, x, y) => x
+  auto *OpPredicate = II.getOperand(0);

david-arm wrote:

This looks like a valid optimisation, but it also suggests that the ACLE code 
written in C/C++ would benefit from being rewritten in a way that avoids this.

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


[clang] [SVE][InstCombine] Delete redundante sel instructions with ptrue (PR #68463)

2023-10-10 Thread David Sherwood via cfe-commits


@@ -63,6 +63,20 @@ svint32_t test_svsel_s32(svbool_t pg, svint32_t op1, 
svint32_t op2)
   return SVE_ACLE_FUNC(svsel,_s32,,)(pg, op1, op2);
 }
 
+// CHECK-LABEL: @test_svsel_s32_ptrue(

david-arm wrote:

I'm not sure if this test really adds any more value, since the other test in 
Transforms/InstCombine/AArch64/sve-intrinsic-sel.ll is also testing the 
InstCombine.

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


[clang] [clang] Improve `_Alignas` on a `struct` declaration diagnostic (PR #65638)

2023-10-10 Thread via cfe-commits

https://github.com/cor3ntin commented:

LGTM modulo nitpick.
Maybe @AaronBallman will want to look at it too.
Do we want a release notes for this?

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


[clang] [clang] Improve `_Alignas` on a `struct` declaration diagnostic (PR #65638)

2023-10-10 Thread via cfe-commits

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


[clang] [clang] Improve `_Alignas` on a `struct` declaration diagnostic (PR #65638)

2023-10-10 Thread via cfe-commits


@@ -27,6 +27,7 @@
 #include "clang/AST/Randstruct.h"
 #include "clang/AST/StmtCXX.h"
 #include "clang/Basic/Builtins.h"
+#include "clang/Basic/DiagnosticSema.h"

cor3ntin wrote:

I don't think adding this header is necessary

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


[clang] [clang] static operators should evaluate object argument (PR #68485)

2023-10-10 Thread Tianlan Zhou via cfe-commits

https://github.com/SuperSodaSea updated 
https://github.com/llvm/llvm-project/pull/68485

>From 03276260c48d9cafb2a0d80825156e77cdf02eba Mon Sep 17 00:00:00 2001
From: SuperSodaSea 
Date: Sat, 7 Oct 2023 21:05:17 +0800
Subject: [PATCH 1/4] [clang] static operators should evaluate object argument

---
 clang/lib/AST/ExprConstant.cpp|  3 +-
 clang/lib/CodeGen/CGExpr.cpp  |  2 +-
 clang/lib/CodeGen/CGExprCXX.cpp   | 41 --
 clang/lib/CodeGen/CodeGenFunction.h   |  3 +
 clang/lib/Sema/SemaChecking.cpp   |  5 +-
 clang/lib/Sema/SemaOverload.cpp   | 33 ---
 clang/test/AST/ast-dump-static-operators.cpp  | 55 +++
 .../CodeGenCXX/cxx2b-static-call-operator.cpp | 26 ++---
 .../cxx2b-static-subscript-operator.cpp   | 11 +++-
 9 files changed, 137 insertions(+), 42 deletions(-)
 create mode 100644 clang/test/AST/ast-dump-static-operators.cpp

diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 5a33e918db8e8c0..a6c81f467fbe01c 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -7806,7 +7806,8 @@ class ExprEvaluatorBase
   // Overloaded operator calls to member functions are represented as 
normal
   // calls with '*this' as the first argument.
   const CXXMethodDecl *MD = dyn_cast(FD);
-  if (MD && MD->isImplicitObjectMemberFunction()) {
+  if (MD &&
+  (MD->isImplicitObjectMemberFunction() || (OCE && MD->isStatic( {
 // FIXME: When selecting an implicit conversion for an overloaded
 // operator delete, we sometimes try to evaluate calls to conversion
 // operators without a 'this' parameter!
diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index 54a1d300a9ac738..19406ff174dea14 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -5070,7 +5070,7 @@ RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
   if (const auto *CE = dyn_cast(E))
 if (const auto *MD =
 dyn_cast_if_present(CE->getCalleeDecl());
-MD && MD->isImplicitObjectMemberFunction())
+MD && !MD->isExplicitObjectMemberFunction())
   return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
 
   CGCallee callee = EmitCallee(E->getCallee());
diff --git a/clang/lib/CodeGen/CGExprCXX.cpp b/clang/lib/CodeGen/CGExprCXX.cpp
index 2e7059cc8f5b639..a580c635998510f 100644
--- a/clang/lib/CodeGen/CGExprCXX.cpp
+++ b/clang/lib/CodeGen/CGExprCXX.cpp
@@ -489,11 +489,42 @@ RValue
 CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
const CXXMethodDecl *MD,
ReturnValueSlot ReturnValue) {
-  assert(MD->isImplicitObjectMemberFunction() &&
- "Trying to emit a member call expr on a static method!");
-  return EmitCXXMemberOrOperatorMemberCallExpr(
-  E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr,
-  /*IsArrow=*/false, E->getArg(0));
+  assert(!MD->isExplicitObjectMemberFunction() &&
+ "Trying to emit a member call expr on an explicit object member "
+ "function!");
+
+  if (MD->isStatic())
+return EmitCXXStaticOperatorMemberCallExpr(E, MD, ReturnValue);
+  else
+return EmitCXXMemberOrOperatorMemberCallExpr(
+E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr,
+/*IsArrow=*/false, E->getArg(0));
+}
+
+RValue CodeGenFunction::EmitCXXStaticOperatorMemberCallExpr(
+const CXXOperatorCallExpr *E, const CXXMethodDecl *MD,
+ReturnValueSlot ReturnValue) {
+  assert(MD->isStatic());
+
+  CGCallee Callee = EmitCallee(E->getCallee());
+
+  // Emit and ignore `this` pointer.
+  EmitIgnoredExpr(E->getArg(0));
+
+  auto ProtoType = MD->getFunctionType()->castAs();
+
+  // Emit the rest of the call args.
+  CallArgList Args;
+  EmitCallArgs(Args, ProtoType, drop_begin(E->arguments(), 1),
+   E->getDirectCallee());
+
+  bool Chain = E == MustTailCall;
+  const CGFunctionInfo &FnInfo =
+  CGM.getTypes().arrangeFreeFunctionCall(Args, ProtoType, Chain);
+  llvm::CallBase *CallOrInvoke = nullptr;
+
+  return EmitCall(FnInfo, Callee, ReturnValue, Args, &CallOrInvoke, Chain,
+  E->getExprLoc());
 }
 
 RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
diff --git a/clang/lib/CodeGen/CodeGenFunction.h 
b/clang/lib/CodeGen/CodeGenFunction.h
index d5336382a2b9c95..42de125e7489911 100644
--- a/clang/lib/CodeGen/CodeGenFunction.h
+++ b/clang/lib/CodeGen/CodeGenFunction.h
@@ -4163,6 +4163,9 @@ class CodeGenFunction : public CodeGenTypeCache {
   RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
const CXXMethodDecl *MD,
ReturnValueSlot ReturnValue);
+  RValue EmitCXXStaticOperatorMemberCallExpr(const CXXOperatorCallEx

[clang] 17414ea - [clang][Interp] Fix returning nullptr from functions (#67229)

2023-10-10 Thread via cfe-commits

Author: Timm Baeder
Date: 2023-10-10T11:19:14+02:00
New Revision: 17414eae242b77fe40ce671793bce5fb2e6a3a04

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

LOG: [clang][Interp] Fix returning nullptr from functions (#67229)

isLive() is false for null pointers, so we need to special-case this
here.

Added: 


Modified: 
clang/lib/AST/Interp/Interp.h
clang/test/AST/Interp/functions.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index d62e64bedb213ac..47dc1d08c9c4d8b 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -214,7 +214,8 @@ bool Ret(InterpState &S, CodePtr &PC, APValue &Result) {
 // FIXME: We could be calling isLive() here, but the emitted diagnostics
 // seem a little weird, at least if the returned expression is of
 // pointer type.
-if (!Ret.isLive())
+// Null pointers are considered live here.
+if (!Ret.isZero() && !Ret.isLive())
   return false;
   }
 

diff  --git a/clang/test/AST/Interp/functions.cpp 
b/clang/test/AST/Interp/functions.cpp
index 5cdecbff1e9d3d4..68082576f2735e9 100644
--- a/clang/test/AST/Interp/functions.cpp
+++ b/clang/test/AST/Interp/functions.cpp
@@ -343,3 +343,10 @@ namespace TemplateUndefined {
   constexpr int l = consume(0);
   static_assert(l == 0, "");
 }
+
+namespace PtrReturn {
+  constexpr void *a() {
+return nullptr;
+  }
+  static_assert(a() == nullptr, "");
+}



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


[clang] [clang][Interp] Fix returning nullptr from functions (PR #67229)

2023-10-10 Thread Timm Baeder via cfe-commits

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


[clang] [clang][Interp] Handle CXXScalarValueInitExprs (PR #67147)

2023-10-10 Thread Timm Baeder via cfe-commits

https://github.com/tbaederr updated 
https://github.com/llvm/llvm-project/pull/67147

>From 367cf9517a425d410c120ce7bd201988e3075ff6 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Fri, 22 Sep 2023 16:27:11 +0200
Subject: [PATCH] [clang][Interp] Handle CXXScalarValueInitExprs

---
 clang/lib/AST/Interp/ByteCodeExprGen.cpp |  6 ++
 clang/lib/AST/Interp/ByteCodeExprGen.h   |  1 +
 clang/test/AST/Interp/literals.cpp   | 27 
 3 files changed, 34 insertions(+)

diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 02b35583636bf13..9bd040a208b3f95 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -1531,6 +1531,12 @@ bool ByteCodeExprGen::VisitOffsetOfExpr(const 
OffsetOfExpr *E) {
   return this->emitOffsetOf(T, E, E);
 }
 
+template 
+bool ByteCodeExprGen::VisitCXXScalarValueInitExpr(
+const CXXScalarValueInitExpr *E) {
+  return this->visitZeroInitializer(E->getType(), E);
+}
+
 template  bool ByteCodeExprGen::discard(const Expr *E) 
{
   if (E->containsErrors())
 return false;
diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.h 
b/clang/lib/AST/Interp/ByteCodeExprGen.h
index 47a3f75f13459d0..7cfe4d9251c5f05 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.h
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -106,6 +106,7 @@ class ByteCodeExprGen : public 
ConstStmtVisitor, bool>,
   bool VisitCXXConstructExpr(const CXXConstructExpr *E);
   bool VisitSourceLocExpr(const SourceLocExpr *E);
   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
+  bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
 
 protected:
   bool visitExpr(const Expr *E) override;
diff --git a/clang/test/AST/Interp/literals.cpp 
b/clang/test/AST/Interp/literals.cpp
index ceda59405ea9105..a83dcd234111587 100644
--- a/clang/test/AST/Interp/literals.cpp
+++ b/clang/test/AST/Interp/literals.cpp
@@ -31,6 +31,33 @@ static_assert(b, "");
 constexpr int one = true;
 static_assert(one == 1, "");
 
+constexpr bool b2 = bool();
+static_assert(!b2, "");
+
+namespace ScalarTypes {
+  constexpr int ScalarInitInt = int();
+  static_assert(ScalarInitInt == 0, "");
+  constexpr float ScalarInitFloat = float();
+  static_assert(ScalarInitFloat == 0.0f, "");
+
+  static_assert(decltype(nullptr)() == nullptr, "");
+
+  template
+  constexpr T getScalar() { return T(); }
+
+  static_assert(getScalar() == 0, "");
+  static_assert(getScalar() == 0.0, "");
+
+  static_assert(getScalar() == nullptr, "");
+  static_assert(getScalar() == nullptr, "");
+
+  enum E {
+First = 0,
+  };
+  static_assert(getScalar() == First, "");
+  /// FIXME: Member pointers.
+}
+
 namespace IntegralCasts {
   constexpr int i = 12;
   constexpr unsigned int ui = i;

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


[clang] [Clang] Support target attr specifying CPU (PR #68678)

2023-10-10 Thread Qiu Chaofan via cfe-commits

https://github.com/ecnelises created 
https://github.com/llvm/llvm-project/pull/68678

Currently targets except AArch64 cannot recognize function attribute specifying 
target CPU. Make it equivalent to `arch` directive.

>From 78f22a8a57f5b67660763b8c7731b9d3cddede72 Mon Sep 17 00:00:00 2001
From: Qiu Chaofan 
Date: Tue, 10 Oct 2023 17:20:00 +0800
Subject: [PATCH] [Clang] Support target attr specifying CPU

Currently targets except AArch64 cannot recognize function attribute
specifying target CPU. Make it equivalent to arch directive.
---
 clang/lib/Basic/TargetInfo.cpp | 7 ---
 clang/test/Sema/attr-target.c  | 4 
 2 files changed, 8 insertions(+), 3 deletions(-)

diff --git a/clang/lib/Basic/TargetInfo.cpp b/clang/lib/Basic/TargetInfo.cpp
index 6cd5d618a4acaa5..474f4173eb5257d 100644
--- a/clang/lib/Basic/TargetInfo.cpp
+++ b/clang/lib/Basic/TargetInfo.cpp
@@ -560,11 +560,12 @@ ParsedTargetAttr TargetInfo::parseTargetAttr(StringRef 
Features) const {
 }
 
 // While we're here iterating check for a different target cpu.
-if (Feature.startswith("arch=")) {
+if (Feature.startswith("arch=") || Feature.startswith("cpu=")) {
+  auto [Key, CPU] = Feature.split("=");
   if (!Ret.CPU.empty())
-Ret.Duplicate = "arch=";
+Ret.Duplicate = StringRef(Key.data(), Key.size() + 1);
   else
-Ret.CPU = Feature.split("=").second.trim();
+Ret.CPU = CPU.trim();
 } else if (Feature.startswith("tune=")) {
   if (!Ret.Tune.empty())
 Ret.Duplicate = "tune=";
diff --git a/clang/test/Sema/attr-target.c b/clang/test/Sema/attr-target.c
index 3416a3d0a6ba134..631e40b947ed69b 100644
--- a/clang/test/Sema/attr-target.c
+++ b/clang/test/Sema/attr-target.c
@@ -17,10 +17,14 @@ int __attribute__((target("avx,sse4.2,arch=hiss"))) 
meow(void) {  return 4; }
 int __attribute__((target("woof"))) bark(void) {  return 4; }
 // no warning, same as saying 'nothing'.
 int __attribute__((target("arch="))) turtle(void) { return 4; }
+// no warning, same as saying 'nothing'.
+int __attribute__((target("cpu="))) equus(void) { return 4; }
 //expected-warning@+1 {{unknown CPU 'hiss' in the 'target' attribute string; 
'target' attribute ignored}}
 int __attribute__((target("arch=hiss,arch=woof"))) pine_tree(void) { return 4; 
}
 //expected-warning@+1 {{duplicate 'arch=' in the 'target' attribute string; 
'target' attribute ignored}}
 int __attribute__((target("arch=ivybridge,arch=haswell"))) oak_tree(void) { 
return 4; }
+//expected-warning@+1 {{duplicate 'cpu=' in the 'target' attribute string; 
'target' attribute ignored}}
+int __attribute__((target("arch=ivybridge,cpu=haswell"))) cypress_tree(void) { 
return 4; }
 //expected-warning@+1 {{unsupported 'branch-protection' in the 'target' 
attribute string; 'target' attribute ignored}}
 int __attribute__((target("branch-protection=none"))) birch_tree(void) { 
return 5; }
 //expected-warning@+1 {{unknown tune CPU 'hiss' in the 'target' attribute 
string; 'target' attribute ignored}}

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


[clang] [Clang] Support target attr specifying CPU (PR #68678)

2023-10-10 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Qiu Chaofan (ecnelises)


Changes

Currently targets except AArch64 cannot recognize function attribute specifying 
target CPU. Make it equivalent to `arch` directive.

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


2 Files Affected:

- (modified) clang/lib/Basic/TargetInfo.cpp (+4-3) 
- (modified) clang/test/Sema/attr-target.c (+4) 


``diff
diff --git a/clang/lib/Basic/TargetInfo.cpp b/clang/lib/Basic/TargetInfo.cpp
index 6cd5d618a4acaa5..474f4173eb5257d 100644
--- a/clang/lib/Basic/TargetInfo.cpp
+++ b/clang/lib/Basic/TargetInfo.cpp
@@ -560,11 +560,12 @@ ParsedTargetAttr TargetInfo::parseTargetAttr(StringRef 
Features) const {
 }
 
 // While we're here iterating check for a different target cpu.
-if (Feature.startswith("arch=")) {
+if (Feature.startswith("arch=") || Feature.startswith("cpu=")) {
+  auto [Key, CPU] = Feature.split("=");
   if (!Ret.CPU.empty())
-Ret.Duplicate = "arch=";
+Ret.Duplicate = StringRef(Key.data(), Key.size() + 1);
   else
-Ret.CPU = Feature.split("=").second.trim();
+Ret.CPU = CPU.trim();
 } else if (Feature.startswith("tune=")) {
   if (!Ret.Tune.empty())
 Ret.Duplicate = "tune=";
diff --git a/clang/test/Sema/attr-target.c b/clang/test/Sema/attr-target.c
index 3416a3d0a6ba134..631e40b947ed69b 100644
--- a/clang/test/Sema/attr-target.c
+++ b/clang/test/Sema/attr-target.c
@@ -17,10 +17,14 @@ int __attribute__((target("avx,sse4.2,arch=hiss"))) 
meow(void) {  return 4; }
 int __attribute__((target("woof"))) bark(void) {  return 4; }
 // no warning, same as saying 'nothing'.
 int __attribute__((target("arch="))) turtle(void) { return 4; }
+// no warning, same as saying 'nothing'.
+int __attribute__((target("cpu="))) equus(void) { return 4; }
 //expected-warning@+1 {{unknown CPU 'hiss' in the 'target' attribute string; 
'target' attribute ignored}}
 int __attribute__((target("arch=hiss,arch=woof"))) pine_tree(void) { return 4; 
}
 //expected-warning@+1 {{duplicate 'arch=' in the 'target' attribute string; 
'target' attribute ignored}}
 int __attribute__((target("arch=ivybridge,arch=haswell"))) oak_tree(void) { 
return 4; }
+//expected-warning@+1 {{duplicate 'cpu=' in the 'target' attribute string; 
'target' attribute ignored}}
+int __attribute__((target("arch=ivybridge,cpu=haswell"))) cypress_tree(void) { 
return 4; }
 //expected-warning@+1 {{unsupported 'branch-protection' in the 'target' 
attribute string; 'target' attribute ignored}}
 int __attribute__((target("branch-protection=none"))) birch_tree(void) { 
return 5; }
 //expected-warning@+1 {{unknown tune CPU 'hiss' in the 'target' attribute 
string; 'target' attribute ignored}}

``




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


[clang] [clang][Interp] Support AddOffset with 128bit offsets (PR #68679)

2023-10-10 Thread Timm Baeder via cfe-commits

https://github.com/tbaederr created 
https://github.com/llvm/llvm-project/pull/68679

We do a similar things a few lines above for `Index`:

```
  // Get a version of the index comparable to the type.
  T Index = T::from(Ptr.getIndex(), Offset.bitWidth());
```

>From 10d205da4c220227589ce210bf921f86ead4d05f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Tue, 10 Oct 2023 08:52:43 +0200
Subject: [PATCH] [clang][Interp] Support AddOffset with 128bit offsets

---
 clang/lib/AST/Interp/Interp.h   | 2 +-
 clang/test/AST/Interp/intap.cpp | 9 +
 2 files changed, 10 insertions(+), 1 deletion(-)

diff --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index 47dc1d08c9c4d8b..620d797da27023f 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -1437,7 +1437,7 @@ bool OffsetHelper(InterpState &S, CodePtr OpPC, const T 
&Offset,
 return false;
   };
 
-  unsigned MaxOffset = MaxIndex - Ptr.getIndex();
+  T MaxOffset = T::from(MaxIndex - Ptr.getIndex(), Offset.bitWidth());
   if constexpr (Op == ArithOp::Add) {
 // If the new offset would be negative, bail out.
 if (Offset.isNegative() && (Offset.isMin() || -Offset > Index))
diff --git a/clang/test/AST/Interp/intap.cpp b/clang/test/AST/Interp/intap.cpp
index b3f02d2b769531d..e9e68438bb597aa 100644
--- a/clang/test/AST/Interp/intap.cpp
+++ b/clang/test/AST/Interp/intap.cpp
@@ -76,6 +76,15 @@ namespace i128 {
// expected-note {{is outside the 
range of representable values of type}}
 }
 
+namespace AddSubOffset {
+  constexpr __int128 A = 1;
+  constexpr int arr[] = {1,2,3};
+  constexpr const int *P = arr + A;
+  static_assert(*P == 2, "");
+  constexpr const int *P2 = P - A;
+  static_assert(*P2 == 1,"");
+}
+
 #else
 /// No int128 support, so no expected directives.
 

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


[clang] [clang][Interp] Support AddOffset with 128bit offsets (PR #68679)

2023-10-10 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Timm Baeder (tbaederr)


Changes

We do a similar things a few lines above for `Index`:

```
  // Get a version of the index comparable to the type.
  T Index = T::from(Ptr.getIndex(), Offset.bitWidth());
```

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


2 Files Affected:

- (modified) clang/lib/AST/Interp/Interp.h (+1-1) 
- (modified) clang/test/AST/Interp/intap.cpp (+9) 


``diff
diff --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index 47dc1d08c9c4d8b..620d797da27023f 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -1437,7 +1437,7 @@ bool OffsetHelper(InterpState &S, CodePtr OpPC, const T 
&Offset,
 return false;
   };
 
-  unsigned MaxOffset = MaxIndex - Ptr.getIndex();
+  T MaxOffset = T::from(MaxIndex - Ptr.getIndex(), Offset.bitWidth());
   if constexpr (Op == ArithOp::Add) {
 // If the new offset would be negative, bail out.
 if (Offset.isNegative() && (Offset.isMin() || -Offset > Index))
diff --git a/clang/test/AST/Interp/intap.cpp b/clang/test/AST/Interp/intap.cpp
index b3f02d2b769531d..e9e68438bb597aa 100644
--- a/clang/test/AST/Interp/intap.cpp
+++ b/clang/test/AST/Interp/intap.cpp
@@ -76,6 +76,15 @@ namespace i128 {
// expected-note {{is outside the 
range of representable values of type}}
 }
 
+namespace AddSubOffset {
+  constexpr __int128 A = 1;
+  constexpr int arr[] = {1,2,3};
+  constexpr const int *P = arr + A;
+  static_assert(*P == 2, "");
+  constexpr const int *P2 = P - A;
+  static_assert(*P2 == 1,"");
+}
+
 #else
 /// No int128 support, so no expected directives.
 

``




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


[clang] [clang][Interp] Support AddOffset with 128bit offsets (PR #68679)

2023-10-10 Thread Timm Baeder via cfe-commits

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


[clang] [analyzer] Removing untrusted buffer size taint warning (PR #68607)

2023-10-10 Thread Daniel Krupp via cfe-commits

https://github.com/dkrupp updated 
https://github.com/llvm/llvm-project/pull/68607

>From 143db26ffe8620c2b45eb15d331466c883bbfce0 Mon Sep 17 00:00:00 2001
From: Daniel Krupp 
Date: Mon, 9 Oct 2023 16:52:13 +0200
Subject: [PATCH 1/2] [analyzer] Removing untrusted buffer size taint warning

alpha.security.taint.TaintPropagation checker
emitted a false warning to the following code

char buf[100];
size_t size = tainted();
if (size > 100)
  return;
memset(buf, 0, size); // warn: untrusted data used as buffer size

The checker does not take into consideration that the
size tainted variable is bounded.

The false warning was emmitted also for the malloc/calloc calls.

These warning (the sink) should be implemented in the
MallocChecker and CStringChecker checkers instead, where more sophisticated
handling can be done taking into consideration buffer size and integer 
constraints.
---
 .../Checkers/GenericTaintChecker.cpp  | 49 +
 .../test/Analysis/taint-diagnostic-visitor.c  | 68 +--
 clang/test/Analysis/taint-generic.c   | 26 ---
 3 files changed, 67 insertions(+), 76 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
index 4ceaf933d0bfc84..b949cac504eddfe 100644
--- a/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
@@ -59,13 +59,6 @@ constexpr llvm::StringLiteral MsgSanitizeSystemArgs =
 "Untrusted data is passed to a system call "
 "(CERT/STR02-C. Sanitize data passed to complex subsystems)";
 
-/// Check if tainted data is used as a buffer size in strn.. functions,
-/// and allocators.
-constexpr llvm::StringLiteral MsgTaintedBufferSize =
-"Untrusted data is used to specify the buffer size "
-"(CERT/STR31-C. Guarantee that storage for strings has sufficient space "
-"for character data and the null terminator)";
-
 /// Check if tainted data is used as a custom sink's parameter.
 constexpr llvm::StringLiteral MsgCustomSink =
 "Untrusted data is passed to a user-defined sink";
@@ -733,13 +726,23 @@ void GenericTaintChecker::initTaintRules(CheckerContext 
&C) const {
   {{CDF_MaybeBuiltin, {{"stpcpy"}}},
TR::Prop({{1}}, {{0, ReturnValueIndex}})},
   {{CDF_MaybeBuiltin, {{"strcat"}}},
-   TR::Prop({{1}}, {{0, ReturnValueIndex}})},
+   TR::Prop({{0,1}}, {{0, ReturnValueIndex}})},
   {{CDF_MaybeBuiltin, {{"wcsncat"}}},
TR::Prop({{1}}, {{0, ReturnValueIndex}})},
   {{CDF_MaybeBuiltin, {{"strdup"}}}, TR::Prop({{0}}, 
{{ReturnValueIndex}})},
   {{CDF_MaybeBuiltin, {{"strdupa"}}},
TR::Prop({{0}}, {{ReturnValueIndex}})},
   {{CDF_MaybeBuiltin, {{"wcsdup"}}}, TR::Prop({{0}}, 
{{ReturnValueIndex}})},
+  {{CDF_MaybeBuiltin, BI.getName(Builtin::BImemcpy)},
+   TR::Prop({{1, 2}}, {{0, ReturnValueIndex}})},
+  {{CDF_MaybeBuiltin, {BI.getName(Builtin::BImemmove)}},
+   TR::Prop({{1, 2}}, {{0, ReturnValueIndex}})},
+  {{CDF_MaybeBuiltin, {BI.getName(Builtin::BIstrncpy)}},
+   TR::Prop({{1, 2}}, {{0, ReturnValueIndex}})},
+  {{CDF_MaybeBuiltin, {BI.getName(Builtin::BIstrndup)}},
+   TR::Prop({{0, 1}}, {{ReturnValueIndex}})},
+  {{CDF_MaybeBuiltin, {"bcopy"}},
+   TR::Prop({{0, 2}}, {{1}})},
 
   // Sinks
   {{{"system"}}, TR::Sink({{0}}, MsgSanitizeSystemArgs)},
@@ -753,32 +756,16 @@ void GenericTaintChecker::initTaintRules(CheckerContext 
&C) const {
   {{{"execvp"}}, TR::Sink({{0, 1}}, MsgSanitizeSystemArgs)},
   {{{"execvpe"}}, TR::Sink({{0, 1, 2}}, MsgSanitizeSystemArgs)},
   {{{"dlopen"}}, TR::Sink({{0}}, MsgSanitizeSystemArgs)},
-  {{CDF_MaybeBuiltin, {{"malloc"}}}, TR::Sink({{0}}, 
MsgTaintedBufferSize)},
-  {{CDF_MaybeBuiltin, {{"calloc"}}}, TR::Sink({{0}}, 
MsgTaintedBufferSize)},
-  {{CDF_MaybeBuiltin, {{"alloca"}}}, TR::Sink({{0}}, 
MsgTaintedBufferSize)},
-  {{CDF_MaybeBuiltin, {{"memccpy"}}},
-   TR::Sink({{3}}, MsgTaintedBufferSize)},
-  {{CDF_MaybeBuiltin, {{"realloc"}}},
-   TR::Sink({{1}}, MsgTaintedBufferSize)},
+   // malloc, calloc, alloca, realloc, memccpy
+   // are intentionally left out as taint sinks
+   // because unconditional reporting for these functions
+   // generate many false positives.
+   // These taint sinks should be implemented in other checkers
+   // with more sophisticated sanitation heuristics.
   "setproctitle"}}}, TR::Sink({{0}, 1}, MsgUncontrolledFormatString)},
   "setproctitle_fast"}}},
TR::Sink({{0}, 1}, MsgUncontrolledFormatString)},
-
-  // SinkProps
-  {{CDF_MaybeBuiltin, BI.getName(Builtin::BImemcpy)},
-   TR::SinkProp({{2}}, {{1, 2}}, {{0, ReturnValueIndex}},
-MsgTaintedBufferSize)},
-  {{CDF_MaybeBuiltin, {BI.getName(Builtin::BImemmove)}},
-   TR::SinkProp({{2}}, {{1, 2}}, {{0, ReturnValueIndex}},
-  

[clang] [analyzer] Removing untrusted buffer size taint warning (PR #68607)

2023-10-10 Thread Daniel Krupp via cfe-commits

https://github.com/dkrupp updated 
https://github.com/llvm/llvm-project/pull/68607

>From 143db26ffe8620c2b45eb15d331466c883bbfce0 Mon Sep 17 00:00:00 2001
From: Daniel Krupp 
Date: Mon, 9 Oct 2023 16:52:13 +0200
Subject: [PATCH 1/3] [analyzer] Removing untrusted buffer size taint warning

alpha.security.taint.TaintPropagation checker
emitted a false warning to the following code

char buf[100];
size_t size = tainted();
if (size > 100)
  return;
memset(buf, 0, size); // warn: untrusted data used as buffer size

The checker does not take into consideration that the
size tainted variable is bounded.

The false warning was emmitted also for the malloc/calloc calls.

These warning (the sink) should be implemented in the
MallocChecker and CStringChecker checkers instead, where more sophisticated
handling can be done taking into consideration buffer size and integer 
constraints.
---
 .../Checkers/GenericTaintChecker.cpp  | 49 +
 .../test/Analysis/taint-diagnostic-visitor.c  | 68 +--
 clang/test/Analysis/taint-generic.c   | 26 ---
 3 files changed, 67 insertions(+), 76 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
index 4ceaf933d0bfc84..b949cac504eddfe 100644
--- a/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
@@ -59,13 +59,6 @@ constexpr llvm::StringLiteral MsgSanitizeSystemArgs =
 "Untrusted data is passed to a system call "
 "(CERT/STR02-C. Sanitize data passed to complex subsystems)";
 
-/// Check if tainted data is used as a buffer size in strn.. functions,
-/// and allocators.
-constexpr llvm::StringLiteral MsgTaintedBufferSize =
-"Untrusted data is used to specify the buffer size "
-"(CERT/STR31-C. Guarantee that storage for strings has sufficient space "
-"for character data and the null terminator)";
-
 /// Check if tainted data is used as a custom sink's parameter.
 constexpr llvm::StringLiteral MsgCustomSink =
 "Untrusted data is passed to a user-defined sink";
@@ -733,13 +726,23 @@ void GenericTaintChecker::initTaintRules(CheckerContext 
&C) const {
   {{CDF_MaybeBuiltin, {{"stpcpy"}}},
TR::Prop({{1}}, {{0, ReturnValueIndex}})},
   {{CDF_MaybeBuiltin, {{"strcat"}}},
-   TR::Prop({{1}}, {{0, ReturnValueIndex}})},
+   TR::Prop({{0,1}}, {{0, ReturnValueIndex}})},
   {{CDF_MaybeBuiltin, {{"wcsncat"}}},
TR::Prop({{1}}, {{0, ReturnValueIndex}})},
   {{CDF_MaybeBuiltin, {{"strdup"}}}, TR::Prop({{0}}, 
{{ReturnValueIndex}})},
   {{CDF_MaybeBuiltin, {{"strdupa"}}},
TR::Prop({{0}}, {{ReturnValueIndex}})},
   {{CDF_MaybeBuiltin, {{"wcsdup"}}}, TR::Prop({{0}}, 
{{ReturnValueIndex}})},
+  {{CDF_MaybeBuiltin, BI.getName(Builtin::BImemcpy)},
+   TR::Prop({{1, 2}}, {{0, ReturnValueIndex}})},
+  {{CDF_MaybeBuiltin, {BI.getName(Builtin::BImemmove)}},
+   TR::Prop({{1, 2}}, {{0, ReturnValueIndex}})},
+  {{CDF_MaybeBuiltin, {BI.getName(Builtin::BIstrncpy)}},
+   TR::Prop({{1, 2}}, {{0, ReturnValueIndex}})},
+  {{CDF_MaybeBuiltin, {BI.getName(Builtin::BIstrndup)}},
+   TR::Prop({{0, 1}}, {{ReturnValueIndex}})},
+  {{CDF_MaybeBuiltin, {"bcopy"}},
+   TR::Prop({{0, 2}}, {{1}})},
 
   // Sinks
   {{{"system"}}, TR::Sink({{0}}, MsgSanitizeSystemArgs)},
@@ -753,32 +756,16 @@ void GenericTaintChecker::initTaintRules(CheckerContext 
&C) const {
   {{{"execvp"}}, TR::Sink({{0, 1}}, MsgSanitizeSystemArgs)},
   {{{"execvpe"}}, TR::Sink({{0, 1, 2}}, MsgSanitizeSystemArgs)},
   {{{"dlopen"}}, TR::Sink({{0}}, MsgSanitizeSystemArgs)},
-  {{CDF_MaybeBuiltin, {{"malloc"}}}, TR::Sink({{0}}, 
MsgTaintedBufferSize)},
-  {{CDF_MaybeBuiltin, {{"calloc"}}}, TR::Sink({{0}}, 
MsgTaintedBufferSize)},
-  {{CDF_MaybeBuiltin, {{"alloca"}}}, TR::Sink({{0}}, 
MsgTaintedBufferSize)},
-  {{CDF_MaybeBuiltin, {{"memccpy"}}},
-   TR::Sink({{3}}, MsgTaintedBufferSize)},
-  {{CDF_MaybeBuiltin, {{"realloc"}}},
-   TR::Sink({{1}}, MsgTaintedBufferSize)},
+   // malloc, calloc, alloca, realloc, memccpy
+   // are intentionally left out as taint sinks
+   // because unconditional reporting for these functions
+   // generate many false positives.
+   // These taint sinks should be implemented in other checkers
+   // with more sophisticated sanitation heuristics.
   "setproctitle"}}}, TR::Sink({{0}, 1}, MsgUncontrolledFormatString)},
   "setproctitle_fast"}}},
TR::Sink({{0}, 1}, MsgUncontrolledFormatString)},
-
-  // SinkProps
-  {{CDF_MaybeBuiltin, BI.getName(Builtin::BImemcpy)},
-   TR::SinkProp({{2}}, {{1, 2}}, {{0, ReturnValueIndex}},
-MsgTaintedBufferSize)},
-  {{CDF_MaybeBuiltin, {BI.getName(Builtin::BImemmove)}},
-   TR::SinkProp({{2}}, {{1, 2}}, {{0, ReturnValueIndex}},
-  

[clang] [analyzer] Removing untrusted buffer size taint warning (PR #68607)

2023-10-10 Thread Daniel Krupp via cfe-commits

https://github.com/dkrupp updated 
https://github.com/llvm/llvm-project/pull/68607

>From 143db26ffe8620c2b45eb15d331466c883bbfce0 Mon Sep 17 00:00:00 2001
From: Daniel Krupp 
Date: Mon, 9 Oct 2023 16:52:13 +0200
Subject: [PATCH 1/3] [analyzer] Removing untrusted buffer size taint warning

alpha.security.taint.TaintPropagation checker
emitted a false warning to the following code

char buf[100];
size_t size = tainted();
if (size > 100)
  return;
memset(buf, 0, size); // warn: untrusted data used as buffer size

The checker does not take into consideration that the
size tainted variable is bounded.

The false warning was emmitted also for the malloc/calloc calls.

These warning (the sink) should be implemented in the
MallocChecker and CStringChecker checkers instead, where more sophisticated
handling can be done taking into consideration buffer size and integer 
constraints.
---
 .../Checkers/GenericTaintChecker.cpp  | 49 +
 .../test/Analysis/taint-diagnostic-visitor.c  | 68 +--
 clang/test/Analysis/taint-generic.c   | 26 ---
 3 files changed, 67 insertions(+), 76 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
index 4ceaf933d0bfc84..b949cac504eddfe 100644
--- a/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
@@ -59,13 +59,6 @@ constexpr llvm::StringLiteral MsgSanitizeSystemArgs =
 "Untrusted data is passed to a system call "
 "(CERT/STR02-C. Sanitize data passed to complex subsystems)";
 
-/// Check if tainted data is used as a buffer size in strn.. functions,
-/// and allocators.
-constexpr llvm::StringLiteral MsgTaintedBufferSize =
-"Untrusted data is used to specify the buffer size "
-"(CERT/STR31-C. Guarantee that storage for strings has sufficient space "
-"for character data and the null terminator)";
-
 /// Check if tainted data is used as a custom sink's parameter.
 constexpr llvm::StringLiteral MsgCustomSink =
 "Untrusted data is passed to a user-defined sink";
@@ -733,13 +726,23 @@ void GenericTaintChecker::initTaintRules(CheckerContext 
&C) const {
   {{CDF_MaybeBuiltin, {{"stpcpy"}}},
TR::Prop({{1}}, {{0, ReturnValueIndex}})},
   {{CDF_MaybeBuiltin, {{"strcat"}}},
-   TR::Prop({{1}}, {{0, ReturnValueIndex}})},
+   TR::Prop({{0,1}}, {{0, ReturnValueIndex}})},
   {{CDF_MaybeBuiltin, {{"wcsncat"}}},
TR::Prop({{1}}, {{0, ReturnValueIndex}})},
   {{CDF_MaybeBuiltin, {{"strdup"}}}, TR::Prop({{0}}, 
{{ReturnValueIndex}})},
   {{CDF_MaybeBuiltin, {{"strdupa"}}},
TR::Prop({{0}}, {{ReturnValueIndex}})},
   {{CDF_MaybeBuiltin, {{"wcsdup"}}}, TR::Prop({{0}}, 
{{ReturnValueIndex}})},
+  {{CDF_MaybeBuiltin, BI.getName(Builtin::BImemcpy)},
+   TR::Prop({{1, 2}}, {{0, ReturnValueIndex}})},
+  {{CDF_MaybeBuiltin, {BI.getName(Builtin::BImemmove)}},
+   TR::Prop({{1, 2}}, {{0, ReturnValueIndex}})},
+  {{CDF_MaybeBuiltin, {BI.getName(Builtin::BIstrncpy)}},
+   TR::Prop({{1, 2}}, {{0, ReturnValueIndex}})},
+  {{CDF_MaybeBuiltin, {BI.getName(Builtin::BIstrndup)}},
+   TR::Prop({{0, 1}}, {{ReturnValueIndex}})},
+  {{CDF_MaybeBuiltin, {"bcopy"}},
+   TR::Prop({{0, 2}}, {{1}})},
 
   // Sinks
   {{{"system"}}, TR::Sink({{0}}, MsgSanitizeSystemArgs)},
@@ -753,32 +756,16 @@ void GenericTaintChecker::initTaintRules(CheckerContext 
&C) const {
   {{{"execvp"}}, TR::Sink({{0, 1}}, MsgSanitizeSystemArgs)},
   {{{"execvpe"}}, TR::Sink({{0, 1, 2}}, MsgSanitizeSystemArgs)},
   {{{"dlopen"}}, TR::Sink({{0}}, MsgSanitizeSystemArgs)},
-  {{CDF_MaybeBuiltin, {{"malloc"}}}, TR::Sink({{0}}, 
MsgTaintedBufferSize)},
-  {{CDF_MaybeBuiltin, {{"calloc"}}}, TR::Sink({{0}}, 
MsgTaintedBufferSize)},
-  {{CDF_MaybeBuiltin, {{"alloca"}}}, TR::Sink({{0}}, 
MsgTaintedBufferSize)},
-  {{CDF_MaybeBuiltin, {{"memccpy"}}},
-   TR::Sink({{3}}, MsgTaintedBufferSize)},
-  {{CDF_MaybeBuiltin, {{"realloc"}}},
-   TR::Sink({{1}}, MsgTaintedBufferSize)},
+   // malloc, calloc, alloca, realloc, memccpy
+   // are intentionally left out as taint sinks
+   // because unconditional reporting for these functions
+   // generate many false positives.
+   // These taint sinks should be implemented in other checkers
+   // with more sophisticated sanitation heuristics.
   "setproctitle"}}}, TR::Sink({{0}, 1}, MsgUncontrolledFormatString)},
   "setproctitle_fast"}}},
TR::Sink({{0}, 1}, MsgUncontrolledFormatString)},
-
-  // SinkProps
-  {{CDF_MaybeBuiltin, BI.getName(Builtin::BImemcpy)},
-   TR::SinkProp({{2}}, {{1, 2}}, {{0, ReturnValueIndex}},
-MsgTaintedBufferSize)},
-  {{CDF_MaybeBuiltin, {BI.getName(Builtin::BImemmove)}},
-   TR::SinkProp({{2}}, {{1, 2}}, {{0, ReturnValueIndex}},
-  

[clang] [Clang][PowerPC] Support tune directive in target attribute (PR #68681)

2023-10-10 Thread Qiu Chaofan via cfe-commits

https://github.com/ecnelises created 
https://github.com/llvm/llvm-project/pull/68681

None

>From c1fbd4242c135ecbf91882d0350dc7d4c1e84b69 Mon Sep 17 00:00:00 2001
From: Qiu Chaofan 
Date: Tue, 10 Oct 2023 17:50:59 +0800
Subject: [PATCH] [Clang][PowerPC] Support tune directive in target attribute

---
 clang/lib/Basic/Targets/PPC.h |  2 ++
 clang/test/Sema/attr-target.c | 24 
 2 files changed, 26 insertions(+)

diff --git a/clang/lib/Basic/Targets/PPC.h b/clang/lib/Basic/Targets/PPC.h
index ef667b3d511f0e6..4d62673ba7fb8c5 100644
--- a/clang/lib/Basic/Targets/PPC.h
+++ b/clang/lib/Basic/Targets/PPC.h
@@ -198,6 +198,8 @@ class LLVM_LIBRARY_VISIBILITY PPCTargetInfo : public 
TargetInfo {
   void setFeatureEnabled(llvm::StringMap &Features, StringRef Name,
  bool Enabled) const override;
 
+  bool supportsTargetAttributeTune() const override { return true; }
+
   ArrayRef getGCCRegNames() const override;
 
   ArrayRef getGCCRegAliases() const override;
diff --git a/clang/test/Sema/attr-target.c b/clang/test/Sema/attr-target.c
index 3416a3d0a6ba134..5328f056507a714 100644
--- a/clang/test/Sema/attr-target.c
+++ b/clang/test/Sema/attr-target.c
@@ -1,6 +1,8 @@
 // RUN: %clang_cc1 -triple x86_64-linux-gnu  -fsyntax-only -verify -std=c2x %s
 // RUN: %clang_cc1 -triple aarch64-linux-gnu  -fsyntax-only -verify -std=c2x %s
 // RUN: %clang_cc1 -triple arm-linux-gnu  -fsyntax-only -verify -std=c2x %s
+// RUN: %clang_cc1 -triple powerpc-linux-gnu  -fsyntax-only -verify -std=c2x %s
+// RUN: %clang_cc1 -triple ppc64le-linux-gnu  -fsyntax-only -verify -std=c2x %s
 
 #ifdef __x86_64__
 
@@ -61,6 +63,28 @@ int 
__attribute__((target("tune=cortex-a710,tune=neoverse-n2"))) pear_tree(void)
 // no warning - branch-protection should work on aarch64
 int __attribute__((target("branch-protection=none"))) birch_tree(void) { 
return 5; }
 
+#elifdef __powerpc__
+
+int __attribute__((target("float128,arch=pwr9"))) foo(void) { return 4; }
+//expected-error@+1 {{'target' attribute takes one argument}}
+int __attribute__((target())) bar(void) { return 4; }
+// no warning, tune is supported for PPC
+int __attribute__((target("tune=pwr8"))) baz(void) { return 4; }
+//expected-warning@+1 {{unsupported 'fpmath=' in the 'target' attribute 
string; 'target' attribute ignored}}
+int __attribute__((target("fpmath=387"))) walrus(void) { return 4; }
+//expected-warning@+1 {{unknown CPU 'hiss' in the 'target' attribute string; 
'target' attribute ignored}}
+int __attribute__((target("float128,arch=hiss"))) meow(void) {  return 4; }
+// no warning, same as saying 'nothing'.
+int __attribute__((target("arch="))) turtle(void) { return 4; }
+//expected-warning@+1 {{unknown CPU 'hiss' in the 'target' attribute string; 
'target' attribute ignored}}
+int __attribute__((target("arch=hiss,arch=woof"))) pine_tree(void) { return 4; 
}
+//expected-warning@+1 {{duplicate 'arch=' in the 'target' attribute string; 
'target' attribute ignored}}
+int __attribute__((target("arch=pwr9,arch=pwr10"))) oak_tree(void) { return 4; 
}
+//expected-warning@+1 {{unsupported 'branch-protection' in the 'target' 
attribute string; 'target' attribute ignored}}
+int __attribute__((target("branch-protection=none"))) birch_tree(void) { 
return 5; }
+//expected-warning@+1 {{unknown tune CPU 'hiss' in the 'target' attribute 
string; 'target' attribute ignored}}
+int __attribute__((target("tune=hiss,tune=woof"))) apple_tree(void) { return 
4; }
+
 #else
 
 // tune is not supported by other targets.

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


[clang] [libc++] Implement ranges::iota (PR #68494)

2023-10-10 Thread James E T Smith via cfe-commits

jamesETsmith wrote:

Thanks for taking a look @philnik777! I'll try to address your comments in the 
next couple of days and let you know if I have any questions.

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


[clang-tools-extra] [libc++] Implement ranges::iota (PR #68494)

2023-10-10 Thread James E T Smith via cfe-commits

jamesETsmith wrote:

Thanks for taking a look @philnik777! I'll try to address your comments in the 
next couple of days and let you know if I have any questions.

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


[clang] [clang][TSA] Make RequiresCapability a DeclOrType attribute (PR #67095)

2023-10-10 Thread Timm Baeder via cfe-commits
Timm =?utf-8?q?Bäder?= 
Message-ID:
In-Reply-To: 



@@ -8141,6 +8141,16 @@ static void handleRequiresCapabilityAttr(Sema &S, Decl 
*D,
   if (!AL.checkAtLeastNumArgs(S, 1))
 return;
 
+  // We allow this on function declaration as well as
+  // variable declarations of function pointer type.
+  if (!D->isFunctionPointerType() && !isa(D)) {

tbaederr wrote:

Yeah we attach the attribute to the declaration later in this function:

```c++
  RequiresCapabilityAttr *RCA = ::new (S.Context)
  RequiresCapabilityAttr(S.Context, AL, Args.data(), Args.size());

  D->addAttr(RCA);
```

and in `ThreadSafety.cpp` we then check the decl for the attribute in 
`VisitCallExpr()`:
```c++
  auto *D = dyn_cast_or_null(Exp->getCalleeDecl());
  if(!D || !D->hasAttrs())
return;
```

for the function pointer case, `D` will be the `VarDecl`, which now has the 
attribute attached.







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


[clang] [AST] Use explicit type erasure in TypeSourceInfo constructor (PR #68435)

2023-10-10 Thread via cfe-commits


@@ -243,7 +243,7 @@ class TypeLoc {
 
 inline TypeSourceInfo::TypeSourceInfo(QualType ty, size_t DataSize) : Ty(ty) {
   // Init data attached to the object. See getTypeLoc.
-  memset(this + 1, 0, DataSize);
+  memset(const_cast(static_cast(this + 1)), 0, DataSize);

bonktree wrote:

My intention here was to match the double cast in `::getTypeLoc()`, so the way 
this memory is referenced is the same throughout the impls.

I've just tested the single cast, and it does not trigger the warning as well. 
Will amend my patch then.

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


[clang] [AST] Use explicit type erasure in TypeSourceInfo constructor (PR #68435)

2023-10-10 Thread via cfe-commits

https://github.com/bonktree updated 
https://github.com/llvm/llvm-project/pull/68435

>From 021a0664905385b0bfb212316810bd15032d1df2 Mon Sep 17 00:00:00 2001
From: Arseny Maslennikov 
Date: Thu, 5 Oct 2023 10:05:14 +0300
Subject: [PATCH] [AST] Use explicit type erasure in TypeSourceInfo constructor

When this file is included in a project compiled with GCC 13 -Werror,
compilation fails with the following diagnostic:
  /usr/lib/llvm-17.0/include/clang/AST/TypeLoc.h: In constructor 
'clang::TypeSourceInfo::TypeSourceInfo(clang::QualType, size_t)':
  /usr/lib/llvm-17.0/include/clang/AST/TypeLoc.h:245:9: error: 'void* 
memset(void*, int, size_t)' clearing an object of non-trivial type 'class 
clang::TypeSourceInfo'; use assignment instead
  +[-Werror=class-memaccess]
245 |   memset(this + 1, 0, DataSize);
|   ~~^~~

To avoid this, we add an explicit type cast. The cast to void makes
sense, since other member functions of TypeSourceInfo also treat the
buffer `(this + 1)` of length `DataSize` as opaque memory, and was
likely left out by mistake.

Fixes: 4498663f3de0 ("[AST] Initialized data after TypeSourceInfo")
---
 clang/include/clang/AST/TypeLoc.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/include/clang/AST/TypeLoc.h 
b/clang/include/clang/AST/TypeLoc.h
index 98427a8dcbfe660..5bb487f1a7f4455 100644
--- a/clang/include/clang/AST/TypeLoc.h
+++ b/clang/include/clang/AST/TypeLoc.h
@@ -243,7 +243,7 @@ class TypeLoc {
 
 inline TypeSourceInfo::TypeSourceInfo(QualType ty, size_t DataSize) : Ty(ty) {
   // Init data attached to the object. See getTypeLoc.
-  memset(this + 1, 0, DataSize);
+  memset(static_cast(this + 1), 0, DataSize);
 }
 
 /// Return the TypeLoc for a type source info.

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


[clang] [AST] Use explicit type erasure in TypeSourceInfo constructor (PR #68435)

2023-10-10 Thread via cfe-commits


@@ -243,7 +243,7 @@ class TypeLoc {
 
 inline TypeSourceInfo::TypeSourceInfo(QualType ty, size_t DataSize) : Ty(ty) {
   // Init data attached to the object. See getTypeLoc.
-  memset(this + 1, 0, DataSize);
+  memset(const_cast(static_cast(this + 1)), 0, DataSize);

bonktree wrote:

> I've just tested the single cast, and it does not trigger the warning as 
> well. Will amend my patch then.

Done just now.

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


[clang] 1210738 - [clang][Interp] Handle CXXScalarValueInitExprs (#67147)

2023-10-10 Thread via cfe-commits

Author: Timm Baeder
Date: 2023-10-10T12:45:09+02:00
New Revision: 12107386ca13f206daf67b06bfe394ba4b2758fb

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

LOG: [clang][Interp] Handle CXXScalarValueInitExprs (#67147)

Handle those by just zero-initializing the result.

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.cpp
clang/lib/AST/Interp/ByteCodeExprGen.h
clang/test/AST/Interp/literals.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 02b35583636bf13..9bd040a208b3f95 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -1531,6 +1531,12 @@ bool ByteCodeExprGen::VisitOffsetOfExpr(const 
OffsetOfExpr *E) {
   return this->emitOffsetOf(T, E, E);
 }
 
+template 
+bool ByteCodeExprGen::VisitCXXScalarValueInitExpr(
+const CXXScalarValueInitExpr *E) {
+  return this->visitZeroInitializer(E->getType(), E);
+}
+
 template  bool ByteCodeExprGen::discard(const Expr *E) 
{
   if (E->containsErrors())
 return false;

diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.h 
b/clang/lib/AST/Interp/ByteCodeExprGen.h
index 47a3f75f13459d0..7cfe4d9251c5f05 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.h
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -106,6 +106,7 @@ class ByteCodeExprGen : public 
ConstStmtVisitor, bool>,
   bool VisitCXXConstructExpr(const CXXConstructExpr *E);
   bool VisitSourceLocExpr(const SourceLocExpr *E);
   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
+  bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
 
 protected:
   bool visitExpr(const Expr *E) override;

diff  --git a/clang/test/AST/Interp/literals.cpp 
b/clang/test/AST/Interp/literals.cpp
index ceda59405ea9105..a83dcd234111587 100644
--- a/clang/test/AST/Interp/literals.cpp
+++ b/clang/test/AST/Interp/literals.cpp
@@ -31,6 +31,33 @@ static_assert(b, "");
 constexpr int one = true;
 static_assert(one == 1, "");
 
+constexpr bool b2 = bool();
+static_assert(!b2, "");
+
+namespace ScalarTypes {
+  constexpr int ScalarInitInt = int();
+  static_assert(ScalarInitInt == 0, "");
+  constexpr float ScalarInitFloat = float();
+  static_assert(ScalarInitFloat == 0.0f, "");
+
+  static_assert(decltype(nullptr)() == nullptr, "");
+
+  template
+  constexpr T getScalar() { return T(); }
+
+  static_assert(getScalar() == 0, "");
+  static_assert(getScalar() == 0.0, "");
+
+  static_assert(getScalar() == nullptr, "");
+  static_assert(getScalar() == nullptr, "");
+
+  enum E {
+First = 0,
+  };
+  static_assert(getScalar() == First, "");
+  /// FIXME: Member pointers.
+}
+
 namespace IntegralCasts {
   constexpr int i = 12;
   constexpr unsigned int ui = i;



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


[clang] [clang][Interp] Handle CXXScalarValueInitExprs (PR #67147)

2023-10-10 Thread Timm Baeder via cfe-commits

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


[clang] [AST] Use explicit type erasure in TypeSourceInfo constructor (PR #68435)

2023-10-10 Thread via cfe-commits

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

LGTM, thanks!

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


[clang] [clang][Interp] Add basic support for _BitInt (PR #68069)

2023-10-10 Thread Timm Baeder via cfe-commits

https://github.com/tbaederr updated 
https://github.com/llvm/llvm-project/pull/68069

>From c93895b7e1b0727327178d73adc93cb988ad3966 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Tue, 3 Oct 2023 08:35:57 +0200
Subject: [PATCH] [clang][Interp] Add basic support for _BitInt

Make sure we pass the expected bitwidth around when casting to
IntAP/IntAPS and move the tests to their own file.
---
 clang/lib/AST/Interp/ByteCodeExprGen.cpp | 12 +
 clang/lib/AST/Interp/Context.h   |  2 +
 clang/lib/AST/Interp/IntegralAP.h| 16 ---
 clang/lib/AST/Interp/Interp.h| 58 +++-
 clang/lib/AST/Interp/InterpBuiltin.cpp   |  3 +-
 clang/lib/AST/Interp/Opcodes.td  | 30 +++-
 clang/test/AST/Interp/intap.cpp  | 13 --
 7 files changed, 119 insertions(+), 15 deletions(-)

diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 9bd040a208b3f95..cf82ec9c15eca1e 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -138,6 +138,13 @@ bool ByteCodeExprGen::VisitCastExpr(const 
CastExpr *CE) {
 if (!this->visit(SubExpr))
   return false;
 
+if (ToT == PT_IntAP)
+  return this->emitCastFloatingIntegralAP(Ctx.getBitWidth(CE->getType()),
+  CE);
+if (ToT == PT_IntAPS)
+  return this->emitCastFloatingIntegralAPS(Ctx.getBitWidth(CE->getType()),
+   CE);
+
 return this->emitCastFloatingIntegral(*ToT, CE);
   }
 
@@ -183,6 +190,11 @@ bool ByteCodeExprGen::VisitCastExpr(const 
CastExpr *CE) {
   return true;
 }
 
+if (ToT == PT_IntAP)
+  return this->emitCastAP(*FromT, Ctx.getBitWidth(CE->getType()), CE);
+if (ToT == PT_IntAPS)
+  return this->emitCastAPS(*FromT, Ctx.getBitWidth(CE->getType()), CE);
+
 return this->emitCast(*FromT, *ToT, CE);
   }
 
diff --git a/clang/lib/AST/Interp/Context.h b/clang/lib/AST/Interp/Context.h
index 958b50b1615ad18..6df61e93ad83abc 100644
--- a/clang/lib/AST/Interp/Context.h
+++ b/clang/lib/AST/Interp/Context.h
@@ -64,6 +64,8 @@ class Context final {
   unsigned getCharBit() const;
   /// Return the floating-point semantics for T.
   const llvm::fltSemantics &getFloatSemantics(QualType T) const;
+  /// Return the size of T in bits.
+  uint32_t getBitWidth(QualType T) const { return Ctx.getIntWidth(T); }
 
   /// Classifies an expression.
   std::optional classify(QualType T) const;
diff --git a/clang/lib/AST/Interp/IntegralAP.h 
b/clang/lib/AST/Interp/IntegralAP.h
index a8df431bef11784..f9a33bbcd7bd7fa 100644
--- a/clang/lib/AST/Interp/IntegralAP.h
+++ b/clang/lib/AST/Interp/IntegralAP.h
@@ -37,8 +37,12 @@ template  class IntegralAP final {
   APSInt V;
 
   template  static T truncateCast(const APSInt &V) {
-return std::is_signed_v ? V.trunc(sizeof(T) * 8).getSExtValue()
-   : V.trunc(sizeof(T) * 8).getZExtValue();
+constexpr unsigned BitSize = sizeof(T) * 8;
+if (BitSize >= V.getBitWidth())
+  return std::is_signed_v ? V.getSExtValue() : V.getZExtValue();
+
+return std::is_signed_v ? V.trunc(BitSize).getSExtValue()
+   : V.trunc(BitSize).getZExtValue();
   }
 
 public:
@@ -89,10 +93,9 @@ template  class IntegralAP final {
   }
 
   template 
-  static IntegralAP from(Integral I) {
-// FIXME: Take bits parameter.
+  static IntegralAP from(Integral I, unsigned BitWidth) {
 APSInt Copy =
-APSInt(APInt(128, static_cast(I), InputSigned), !Signed);
+APSInt(APInt(BitWidth, static_cast(I), InputSigned), !Signed);
 Copy.setIsSigned(Signed);
 
 assert(Copy.isSigned() == Signed);
@@ -108,8 +111,7 @@ template  class IntegralAP final {
 return IntegralAP(0);
   }
 
-  // FIXME: This can't be static if the bitwidth depends on V.
-  static constexpr unsigned bitWidth() { return 128; }
+  constexpr unsigned bitWidth() const { return V.getBitWidth(); }
 
   APSInt toAPSInt(unsigned Bits = 0) const { return V; }
   APValue toAPValue() const { return APValue(V); }
diff --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index 47dc1d08c9c4d8b..438cfb5a7eb90a4 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -1568,6 +1568,22 @@ inline bool CastFP(InterpState &S, CodePtr OpPC, const 
llvm::fltSemantics *Sem,
   return true;
 }
 
+/// Like Cast(), but we cast to an arbitrary-bitwidth integral, so we need
+/// to know what bitwidth the result should be.
+template ::T>
+bool CastAP(InterpState &S, CodePtr OpPC, uint32_t BitWidth) {
+  S.Stk.push>(
+  IntegralAP::from(S.Stk.pop(), BitWidth));
+  return true;
+}
+
+template ::T>
+bool CastAPS(InterpState &S, CodePtr OpPC, uint32_t BitWidth) {
+  S.Stk.push>(
+  IntegralAP::from(S.Stk.pop(), BitWidth));
+  return true;
+}
+
 template ::T>
 bool CastIntegralFloating(InterpState &S, 

[clang] [clang][Interp] Add basic support for _BitInt (PR #68069)

2023-10-10 Thread Timm Baeder via cfe-commits

https://github.com/tbaederr updated 
https://github.com/llvm/llvm-project/pull/68069

>From ae2201c2bb82ae26030800c62b3a0f93e2ec49a2 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Tue, 3 Oct 2023 08:35:57 +0200
Subject: [PATCH] [clang][Interp] Add basic support for _BitInt

Make sure we pass the expected bitwidth around when casting to
IntAP/IntAPS and move the tests to their own file.
---
 clang/lib/AST/Interp/ByteCodeExprGen.cpp | 12 +
 clang/lib/AST/Interp/Context.h   |  2 +
 clang/lib/AST/Interp/IntegralAP.h| 16 ---
 clang/lib/AST/Interp/Interp.h| 58 +++-
 clang/lib/AST/Interp/InterpBuiltin.cpp   |  3 +-
 clang/lib/AST/Interp/Opcodes.td  | 30 +++-
 clang/test/AST/Interp/intap.cpp  |  8 
 7 files changed, 118 insertions(+), 11 deletions(-)

diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 9bd040a208b3f95..cf82ec9c15eca1e 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -138,6 +138,13 @@ bool ByteCodeExprGen::VisitCastExpr(const 
CastExpr *CE) {
 if (!this->visit(SubExpr))
   return false;
 
+if (ToT == PT_IntAP)
+  return this->emitCastFloatingIntegralAP(Ctx.getBitWidth(CE->getType()),
+  CE);
+if (ToT == PT_IntAPS)
+  return this->emitCastFloatingIntegralAPS(Ctx.getBitWidth(CE->getType()),
+   CE);
+
 return this->emitCastFloatingIntegral(*ToT, CE);
   }
 
@@ -183,6 +190,11 @@ bool ByteCodeExprGen::VisitCastExpr(const 
CastExpr *CE) {
   return true;
 }
 
+if (ToT == PT_IntAP)
+  return this->emitCastAP(*FromT, Ctx.getBitWidth(CE->getType()), CE);
+if (ToT == PT_IntAPS)
+  return this->emitCastAPS(*FromT, Ctx.getBitWidth(CE->getType()), CE);
+
 return this->emitCast(*FromT, *ToT, CE);
   }
 
diff --git a/clang/lib/AST/Interp/Context.h b/clang/lib/AST/Interp/Context.h
index 958b50b1615ad18..6df61e93ad83abc 100644
--- a/clang/lib/AST/Interp/Context.h
+++ b/clang/lib/AST/Interp/Context.h
@@ -64,6 +64,8 @@ class Context final {
   unsigned getCharBit() const;
   /// Return the floating-point semantics for T.
   const llvm::fltSemantics &getFloatSemantics(QualType T) const;
+  /// Return the size of T in bits.
+  uint32_t getBitWidth(QualType T) const { return Ctx.getIntWidth(T); }
 
   /// Classifies an expression.
   std::optional classify(QualType T) const;
diff --git a/clang/lib/AST/Interp/IntegralAP.h 
b/clang/lib/AST/Interp/IntegralAP.h
index a8df431bef11784..f9a33bbcd7bd7fa 100644
--- a/clang/lib/AST/Interp/IntegralAP.h
+++ b/clang/lib/AST/Interp/IntegralAP.h
@@ -37,8 +37,12 @@ template  class IntegralAP final {
   APSInt V;
 
   template  static T truncateCast(const APSInt &V) {
-return std::is_signed_v ? V.trunc(sizeof(T) * 8).getSExtValue()
-   : V.trunc(sizeof(T) * 8).getZExtValue();
+constexpr unsigned BitSize = sizeof(T) * 8;
+if (BitSize >= V.getBitWidth())
+  return std::is_signed_v ? V.getSExtValue() : V.getZExtValue();
+
+return std::is_signed_v ? V.trunc(BitSize).getSExtValue()
+   : V.trunc(BitSize).getZExtValue();
   }
 
 public:
@@ -89,10 +93,9 @@ template  class IntegralAP final {
   }
 
   template 
-  static IntegralAP from(Integral I) {
-// FIXME: Take bits parameter.
+  static IntegralAP from(Integral I, unsigned BitWidth) {
 APSInt Copy =
-APSInt(APInt(128, static_cast(I), InputSigned), !Signed);
+APSInt(APInt(BitWidth, static_cast(I), InputSigned), !Signed);
 Copy.setIsSigned(Signed);
 
 assert(Copy.isSigned() == Signed);
@@ -108,8 +111,7 @@ template  class IntegralAP final {
 return IntegralAP(0);
   }
 
-  // FIXME: This can't be static if the bitwidth depends on V.
-  static constexpr unsigned bitWidth() { return 128; }
+  constexpr unsigned bitWidth() const { return V.getBitWidth(); }
 
   APSInt toAPSInt(unsigned Bits = 0) const { return V; }
   APValue toAPValue() const { return APValue(V); }
diff --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index 47dc1d08c9c4d8b..438cfb5a7eb90a4 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -1568,6 +1568,22 @@ inline bool CastFP(InterpState &S, CodePtr OpPC, const 
llvm::fltSemantics *Sem,
   return true;
 }
 
+/// Like Cast(), but we cast to an arbitrary-bitwidth integral, so we need
+/// to know what bitwidth the result should be.
+template ::T>
+bool CastAP(InterpState &S, CodePtr OpPC, uint32_t BitWidth) {
+  S.Stk.push>(
+  IntegralAP::from(S.Stk.pop(), BitWidth));
+  return true;
+}
+
+template ::T>
+bool CastAPS(InterpState &S, CodePtr OpPC, uint32_t BitWidth) {
+  S.Stk.push>(
+  IntegralAP::from(S.Stk.pop(), BitWidth));
+  return true;
+}
+
 template ::T>
 bool CastIntegralFloating(InterpState &S, Co

[clang] b4343ab - [clang][ExprConst] Short-circuit ConstantExpr evaluation

2023-10-10 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-10-10T13:27:03+02:00
New Revision: b4343aba9fa12ddb397e08208ec37fcf0fb93864

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

LOG: [clang][ExprConst] Short-circuit ConstantExpr evaluation

ConstantExprs already have a value attached we can just return here.

Differential Revision: https://reviews.llvm.org/D155548

Added: 


Modified: 
clang/lib/AST/ExprConstant.cpp

Removed: 




diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 5a33e918db8e8c0..e5539dedec02a4b 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -15327,6 +15327,17 @@ static bool FastEvaluateAsRValue(const Expr *Exp, 
Expr::EvalResult &Result,
 return true;
   }
 
+  if (const auto *CE = dyn_cast(Exp)) {
+if (CE->hasAPValueResult()) {
+  Result.Val = CE->getAPValueResult();
+  IsConst = true;
+  return true;
+}
+
+// The SubExpr is usually just an IntegerLiteral.
+return FastEvaluateAsRValue(CE->getSubExpr(), Result, Ctx, IsConst);
+  }
+
   // This case should be rare, but we need to check it before we check on
   // the type below.
   if (Exp->getType().isNull()) {



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


[PATCH] D155548: [clang][ExprConst] Short-circuit ConstantExpr evaluation

2023-10-10 Thread Timm Bäder via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGb4343aba9fa1: [clang][ExprConst] Short-circuit ConstantExpr 
evaluation (authored by tbaeder).

Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D155548/new/

https://reviews.llvm.org/D155548

Files:
  clang/lib/AST/ExprConstant.cpp


Index: clang/lib/AST/ExprConstant.cpp
===
--- clang/lib/AST/ExprConstant.cpp
+++ clang/lib/AST/ExprConstant.cpp
@@ -15327,6 +15327,17 @@
 return true;
   }
 
+  if (const auto *CE = dyn_cast(Exp)) {
+if (CE->hasAPValueResult()) {
+  Result.Val = CE->getAPValueResult();
+  IsConst = true;
+  return true;
+}
+
+// The SubExpr is usually just an IntegerLiteral.
+return FastEvaluateAsRValue(CE->getSubExpr(), Result, Ctx, IsConst);
+  }
+
   // This case should be rare, but we need to check it before we check on
   // the type below.
   if (Exp->getType().isNull()) {


Index: clang/lib/AST/ExprConstant.cpp
===
--- clang/lib/AST/ExprConstant.cpp
+++ clang/lib/AST/ExprConstant.cpp
@@ -15327,6 +15327,17 @@
 return true;
   }
 
+  if (const auto *CE = dyn_cast(Exp)) {
+if (CE->hasAPValueResult()) {
+  Result.Val = CE->getAPValueResult();
+  IsConst = true;
+  return true;
+}
+
+// The SubExpr is usually just an IntegerLiteral.
+return FastEvaluateAsRValue(CE->getSubExpr(), Result, Ctx, IsConst);
+  }
+
   // This case should be rare, but we need to check it before we check on
   // the type below.
   if (Exp->getType().isNull()) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Add /Zc:__STDC__ flag to clang-cl (PR #68690)

2023-10-10 Thread via cfe-commits

https://github.com/xbjfk created https://github.com/llvm/llvm-project/pull/68690

This commit adds the /Zc:__STDC__ argument from MSVC, which defines __STDC__.
This means, alongside stronger feature parity with MSVC, that things that rely 
on __STDC__, such as autoconf, can work.
Link to MSVC documentation of this flag: 
https://learn.microsoft.com/en-us/cpp/build/reference/zc-stdc?view=msvc-170

>From 49681eace80c60d22e4d9ced4fabe2872f716bab Mon Sep 17 00:00:00 2001
From: Reagan Bohan 
Date: Tue, 10 Oct 2023 11:32:47 +
Subject: [PATCH] [clang] Add /Zc:__STDC__ flag to clang-cl

This commit adds the /Zc:__STDC__ argument from MSVC, which defines __STDC__.
This means, alongside stronger feature parity with MSVC,
that things that rely on __STDC__, such as autoconf, can work.
---
 clang/include/clang/Basic/LangOptions.def |  2 +-
 clang/include/clang/Driver/Options.td |  7 +++
 clang/lib/Driver/ToolChains/Clang.cpp | 11 ++-
 clang/lib/Frontend/InitPreprocessor.cpp   |  2 +-
 clang/test/Driver/cl-zc.cpp   |  4 
 5 files changed, 23 insertions(+), 3 deletions(-)

diff --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index c0ea4ecb9806a5b..97101d0166a135a 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -282,7 +282,7 @@ LANGOPT(HIPUseNewLaunchAPI, 1, 0, "Use new kernel launching 
API for HIP")
 LANGOPT(OffloadUniformBlock, 1, 0, "Assume that kernels are launched with 
uniform block sizes (default true for CUDA/HIP and false otherwise)")
 LANGOPT(HIPStdPar, 1, 0, "Enable Standard Parallel Algorithm Acceleration for 
HIP (experimental)")
 LANGOPT(HIPStdParInterposeAlloc, 1, 0, "Replace allocations / deallocations 
with HIP RT calls when Standard Parallel Algorithm Acceleration for HIP is 
enabled (Experimental)")
-
+LANGOPT(MSVCEnableStdcMacro , 1, 0, "define __STDC__ with -fms-compatability")
 LANGOPT(SizedDeallocation , 1, 0, "sized deallocation")
 LANGOPT(AlignedAllocation , 1, 0, "aligned allocation")
 LANGOPT(AlignedAllocationUnavailable, 1, 0, "aligned allocation functions are 
unavailable")
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index c272a7f1c398aa6..fae1dcc2b5117f7 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -2821,6 +2821,10 @@ def fms_compatibility : Flag<["-"], 
"fms-compatibility">, Group,
   Visibility<[ClangOption, CC1Option, CLOption]>,
   HelpText<"Enable full Microsoft Visual C++ compatibility">,
   MarshallingInfoFlag>;
+def fms_define_stdc : Flag<["-"], "fms-define-stdc">, Group,
+  Visibility<[ClangOption, CC1Option]>,
+  HelpText<"Define __STDC__ in MSVC Compatibility mode">,
+  MarshallingInfoFlag>;
 def fms_extensions : Flag<["-"], "fms-extensions">, Group,
   Visibility<[ClangOption, CC1Option, CLOption]>,
   HelpText<"Accept some non-standard constructs supported by the Microsoft 
compiler">,
@@ -7933,6 +7937,9 @@ def _SLASH_vd : CLJoined<"vd">, HelpText<"Control 
vtordisp placement">,
   Alias;
 def _SLASH_X : CLFlag<"X">,
   HelpText<"Do not add %INCLUDE% to include search path">, Alias;
+def _SLASH_Zc___STDC__ : CLFlag<"Zc:__STDC__">,
+  HelpText<"Define __STDC__">,
+  Alias;
 def _SLASH_Zc_sizedDealloc : CLFlag<"Zc:sizedDealloc">,
   HelpText<"Enable C++14 sized global deallocation functions">,
   Alias;
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index bfd6c5c2864abf7..b8f3ff6cd4c91e4 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -6744,8 +6744,13 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
   options::OPT_fms_compatibility, options::OPT_fno_ms_compatibility,
   (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,
  options::OPT_fno_ms_extensions, true)));
-  if (IsMSVCCompat)
+  if (IsMSVCCompat) {
 CmdArgs.push_back("-fms-compatibility");
+bool IsMSVCDefineStdc = Args.hasArg(options::OPT_fms_define_stdc);
+if (IsMSVCDefineStdc)
+  CmdArgs.push_back("-fms-define-stdc");
+  }
+
 
   if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&
   Args.hasArg(options::OPT_fms_runtime_lib_EQ))
@@ -7922,6 +7927,10 @@ void Clang::AddClangCLArgs(const ArgList &Args, 
types::ID InputType,
CmdArgs.push_back("-fno-wchar");
  }
 
+ if (Args.hasArg(options::OPT_fms_define_stdc)) {
+   CmdArgs.push_back("-fms-define-stdc");
+ }
+
  if (Args.hasArg(options::OPT__SLASH_kernel)) {
llvm::Triple::ArchType Arch = getToolChain().getArch();
std::vector Values =
diff --git a/clang/lib/Frontend/InitPreprocessor.cpp 
b/clang/lib/Frontend/InitPreprocessor.cpp
index 846e5fce6de7b2c..46399f613257a74 100644
--- a/clang/lib/Frontend/InitPreprocessor.cpp
+++ b/clang/lib/Frontend/InitPreprocessor.cpp
@@ -423,7 +423,7 @@ static void InitializeStandardPredefinedMacros(cons

[clang] [clang] Add /Zc:__STDC__ flag to clang-cl (PR #68690)

2023-10-10 Thread via cfe-commits

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


[clang] [clang] Add /Zc:__STDC__ flag to clang-cl (PR #68690)

2023-10-10 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Reagan (xbjfk)


Changes

This commit adds the /Zc:\_\_STDC\_\_ argument from MSVC, which defines 
\_\_STDC_\_.
This means, alongside stronger feature parity with MSVC, that things that rely 
on \_\_STDC\_\_, such as autoconf, can work.
Link to MSVC documentation of this flag: 
https://learn.microsoft.com/en-us/cpp/build/reference/zc-stdc?view=msvc-170

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


5 Files Affected:

- (modified) clang/include/clang/Basic/LangOptions.def (+1-1) 
- (modified) clang/include/clang/Driver/Options.td (+7) 
- (modified) clang/lib/Driver/ToolChains/Clang.cpp (+10-1) 
- (modified) clang/lib/Frontend/InitPreprocessor.cpp (+1-1) 
- (modified) clang/test/Driver/cl-zc.cpp (+4) 


``diff
diff --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index c0ea4ecb9806a5b..97101d0166a135a 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -282,7 +282,7 @@ LANGOPT(HIPUseNewLaunchAPI, 1, 0, "Use new kernel launching 
API for HIP")
 LANGOPT(OffloadUniformBlock, 1, 0, "Assume that kernels are launched with 
uniform block sizes (default true for CUDA/HIP and false otherwise)")
 LANGOPT(HIPStdPar, 1, 0, "Enable Standard Parallel Algorithm Acceleration for 
HIP (experimental)")
 LANGOPT(HIPStdParInterposeAlloc, 1, 0, "Replace allocations / deallocations 
with HIP RT calls when Standard Parallel Algorithm Acceleration for HIP is 
enabled (Experimental)")
-
+LANGOPT(MSVCEnableStdcMacro , 1, 0, "define __STDC__ with -fms-compatability")
 LANGOPT(SizedDeallocation , 1, 0, "sized deallocation")
 LANGOPT(AlignedAllocation , 1, 0, "aligned allocation")
 LANGOPT(AlignedAllocationUnavailable, 1, 0, "aligned allocation functions are 
unavailable")
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index c272a7f1c398aa6..fae1dcc2b5117f7 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -2821,6 +2821,10 @@ def fms_compatibility : Flag<["-"], 
"fms-compatibility">, Group,
   Visibility<[ClangOption, CC1Option, CLOption]>,
   HelpText<"Enable full Microsoft Visual C++ compatibility">,
   MarshallingInfoFlag>;
+def fms_define_stdc : Flag<["-"], "fms-define-stdc">, Group,
+  Visibility<[ClangOption, CC1Option]>,
+  HelpText<"Define __STDC__ in MSVC Compatibility mode">,
+  MarshallingInfoFlag>;
 def fms_extensions : Flag<["-"], "fms-extensions">, Group,
   Visibility<[ClangOption, CC1Option, CLOption]>,
   HelpText<"Accept some non-standard constructs supported by the Microsoft 
compiler">,
@@ -7933,6 +7937,9 @@ def _SLASH_vd : CLJoined<"vd">, HelpText<"Control 
vtordisp placement">,
   Alias;
 def _SLASH_X : CLFlag<"X">,
   HelpText<"Do not add %INCLUDE% to include search path">, Alias;
+def _SLASH_Zc___STDC__ : CLFlag<"Zc:__STDC__">,
+  HelpText<"Define __STDC__">,
+  Alias;
 def _SLASH_Zc_sizedDealloc : CLFlag<"Zc:sizedDealloc">,
   HelpText<"Enable C++14 sized global deallocation functions">,
   Alias;
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index bfd6c5c2864abf7..b8f3ff6cd4c91e4 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -6744,8 +6744,13 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
   options::OPT_fms_compatibility, options::OPT_fno_ms_compatibility,
   (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,
  options::OPT_fno_ms_extensions, true)));
-  if (IsMSVCCompat)
+  if (IsMSVCCompat) {
 CmdArgs.push_back("-fms-compatibility");
+bool IsMSVCDefineStdc = Args.hasArg(options::OPT_fms_define_stdc);
+if (IsMSVCDefineStdc)
+  CmdArgs.push_back("-fms-define-stdc");
+  }
+
 
   if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&
   Args.hasArg(options::OPT_fms_runtime_lib_EQ))
@@ -7922,6 +7927,10 @@ void Clang::AddClangCLArgs(const ArgList &Args, 
types::ID InputType,
CmdArgs.push_back("-fno-wchar");
  }
 
+ if (Args.hasArg(options::OPT_fms_define_stdc)) {
+   CmdArgs.push_back("-fms-define-stdc");
+ }
+
  if (Args.hasArg(options::OPT__SLASH_kernel)) {
llvm::Triple::ArchType Arch = getToolChain().getArch();
std::vector Values =
diff --git a/clang/lib/Frontend/InitPreprocessor.cpp 
b/clang/lib/Frontend/InitPreprocessor.cpp
index 846e5fce6de7b2c..46399f613257a74 100644
--- a/clang/lib/Frontend/InitPreprocessor.cpp
+++ b/clang/lib/Frontend/InitPreprocessor.cpp
@@ -423,7 +423,7 @@ static void InitializeStandardPredefinedMacros(const 
TargetInfo &TI,
   //  [C++] Whether __STDC__ is predefined and if so, what its value is,
   //  are implementation-defined.
   // (Removed in C++20.)
-  if (!LangOpts.MSVCCompat && !LangOpts.TraditionalCPP)
+  if ((!LangOpts.MSVCCompat || LangOpts.MSVCEnableStdcMacro) && 
!LangOpts.TraditionalCPP)

[clang] [analyzer] Fix note for member reference (PR #68691)

2023-10-10 Thread Gábor Spaits via cfe-commits

https://github.com/spaits created 
https://github.com/llvm/llvm-project/pull/68691

In the following code
`
int main() {
struct Wrapper {char c; int &ref; };
Wrapper w = {.c = 'a', .ref = *(int *)0 };
w.ref = 1;
}`

The clang static analyzer will produce the following warnings and notes:
`/home/egspaba/referenceNotes/test.cpp:12:11: warning: Dereference of null 
pointer [core.NullDereference]
   12 | w.ref = 1;
  | ~~^~~
/home/egspaba/referenceNotes/test.cpp:11:5: note: 'w' initialized here
   11 | Wrapper w = {.c = 'a', .ref = *(int *)0 };
  | ^
/home/egspaba/referenceNotes/test.cpp:12:11: note: Dereference of null pointer
   12 | w.ref = 1;
  | ~~^~~
1 warning generated.
`
In the line where w is created

From bb9cb77cab7b073d45c0b998c926a0b60a75a35e Mon Sep 17 00:00:00 2001
From: Gabor Spaits 
Date: Tue, 10 Oct 2023 13:40:05 +0200
Subject: [PATCH] [analyzer] Fix note for member reference

---
 .../Core/BugReporterVisitors.cpp  | 57 ++-
 1 file changed, 43 insertions(+), 14 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp 
b/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
index 42d03f67510cf88..914011f367d8f2e 100644
--- a/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ b/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -132,6 +132,18 @@ const Expr *bugreporter::getDerefExpr(const Stmt *S) {
 }
 // Pattern match for a few useful cases: a[0], p->f, *p etc.
 else if (const auto *ME = dyn_cast(E)) {
+  // This handles the case when the dereferencing of a member reference
+  // happens. This is needed, because the ast for dereferencing of a
+  // member reference looks like the following:
+  // |-MemberExpr
+  //  `-DeclRefExpr
+  // This branch without the special case just takes out the DeclRefExpr
+  // of the struct, class or union.
+  // This is wrong, because this DeclRefExpr will be passed
+  // to the bug reporting and the notes will refer to wrong variable
+  // (the struct instead of the member).
+  if (ME->getMemberDecl()->getType()->isReferenceType())
+break;
   E = ME->getBase();
 } else if (const auto *IvarRef = dyn_cast(E)) {
   E = IvarRef->getBase();
@@ -157,26 +169,43 @@ const Expr *bugreporter::getDerefExpr(const Stmt *S) {
   return E;
 }
 
+static const VarDecl *getVarDeclForExpression(const Expr *E) {
+  if (const auto *DR = dyn_cast(E))
+return dyn_cast(DR->getDecl());
+  return nullptr;
+}
+
 static const MemRegion *
 getLocationRegionIfReference(const Expr *E, const ExplodedNode *N,
  bool LookingForReference = true) {
-  if (const auto *DR = dyn_cast(E)) {
-if (const auto *VD = dyn_cast(DR->getDecl())) {
-  if (LookingForReference && !VD->getType()->isReferenceType())
-return nullptr;
-  return N->getState()
-  ->getLValue(VD, N->getLocationContext())
-  .getAsRegion();
+  if (const auto *ME = dyn_cast(E)) {
+// This handles other kinds of null references,
+// for example, references from FieldRegions:
+//   struct Wrapper { int &ref; };
+//   Wrapper w = { *(int *)0 };
+//   w.ref = 1;
+const Expr *Base = ME->getBase();
+const VarDecl *VD = getVarDeclForExpression(Base);
+if (!VD)
+  return nullptr;
+
+const auto *FD = dyn_cast(ME->getMemberDecl());
+if (!FD)
+  return nullptr;
+
+if (FD->getType()->isReferenceType()) {
+  SVal StructSVal = N->getState()->getLValue(VD, N->getLocationContext());
+  return N->getState()->getLValue(FD, StructSVal).getAsRegion();
 }
+return nullptr;
   }
 
-  // FIXME: This does not handle other kinds of null references,
-  // for example, references from FieldRegions:
-  //   struct Wrapper { int &ref; };
-  //   Wrapper w = { *(int *)0 };
-  //   w.ref = 1;
-
-  return nullptr;
+  const VarDecl *VD = getVarDeclForExpression(E);
+  if (!VD)
+return nullptr;
+  if (LookingForReference && !VD->getType()->isReferenceType())
+return nullptr;
+  return N->getState()->getLValue(VD, N->getLocationContext()).getAsRegion();
 }
 
 /// Comparing internal representations of symbolic values (via

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


[clang] 6172960 - [clang][Interp] Basic support for bit fields

2023-10-10 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-10-10T13:38:26+02:00
New Revision: 6172960ceae2cbee743214af59018ea108f231d9

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

LOG: [clang][Interp] Basic support for bit fields

Differential Revision: https://reviews.llvm.org/D155548

Added: 
clang/test/AST/Interp/bitfields.cpp

Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.cpp
clang/lib/AST/Interp/ByteCodeStmtGen.cpp
clang/lib/AST/Interp/Interp.h
clang/lib/AST/Interp/Record.h

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 9bd040a208b3f95..e7a431ddee6f002 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -342,8 +342,10 @@ bool ByteCodeExprGen::VisitBinaryOperator(const 
BinaryOperator *BO) {
 return Discard(this->emitDiv(*T, BO));
   case BO_Assign:
 if (DiscardResult)
-  return this->emitStorePop(*T, BO);
-return this->emitStore(*T, BO);
+  return LHS->refersToBitField() ? this->emitStoreBitFieldPop(*T, BO)
+ : this->emitStorePop(*T, BO);
+return LHS->refersToBitField() ? this->emitStoreBitField(*T, BO)
+   : this->emitStore(*T, BO);
   case BO_And:
 return Discard(this->emitBitAnd(*T, BO));
   case BO_Or:
@@ -547,8 +549,15 @@ bool 
ByteCodeExprGen::visitInitList(ArrayRef Inits,
   const Record::Field *FieldToInit = R->getField(InitIndex);
   if (!this->visit(Init))
 return false;
-  if (!this->emitInitField(*T, FieldToInit->Offset, E))
-return false;
+
+  if (FieldToInit->isBitField()) {
+if (!this->emitInitBitField(*T, FieldToInit, E))
+  return false;
+  } else {
+if (!this->emitInitField(*T, FieldToInit->Offset, E))
+  return false;
+  }
+
   if (!this->emitPopPtr(E))
 return false;
   ++InitIndex;

diff  --git a/clang/lib/AST/Interp/ByteCodeStmtGen.cpp 
b/clang/lib/AST/Interp/ByteCodeStmtGen.cpp
index a81c82c38955e9c..6193a8d55a14685 100644
--- a/clang/lib/AST/Interp/ByteCodeStmtGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeStmtGen.cpp
@@ -166,8 +166,13 @@ bool ByteCodeStmtGen::visitFunc(const 
FunctionDecl *F) {
   if (!this->visit(InitExpr))
 return false;
 
-  if (!this->emitInitThisField(*T, F->Offset, InitExpr))
-return false;
+  if (F->isBitField()) {
+if (!this->emitInitThisBitField(*T, F, InitExpr))
+  return false;
+  } else {
+if (!this->emitInitThisField(*T, F->Offset, InitExpr))
+  return false;
+  }
 } else {
   // Non-primitive case. Get a pointer to the field-to-initialize
   // on the stack and call visitInitialzer() for it.

diff  --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index 47dc1d08c9c4d8b..25ce93ac03d3733 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -1071,6 +1071,7 @@ bool InitThisField(InterpState &S, CodePtr OpPC, uint32_t 
I) {
 
 template ::T>
 bool InitThisBitField(InterpState &S, CodePtr OpPC, const Record::Field *F) {
+  assert(F->isBitField());
   if (S.checkingPotentialConstantExpression())
 return false;
   const Pointer &This = S.Current->getThis();
@@ -1112,8 +1113,9 @@ bool InitField(InterpState &S, CodePtr OpPC, uint32_t I) {
 
 template ::T>
 bool InitBitField(InterpState &S, CodePtr OpPC, const Record::Field *F) {
+  assert(F->isBitField());
   const T &Value = S.Stk.pop();
-  const Pointer &Field = S.Stk.pop().atField(F->Offset);
+  const Pointer &Field = S.Stk.peek().atField(F->Offset);
   Field.deref() = Value.truncate(F->Decl->getBitWidthValue(S.getCtx()));
   Field.activate();
   Field.initialize();
@@ -1334,11 +1336,10 @@ bool StoreBitField(InterpState &S, CodePtr OpPC) {
 return false;
   if (!Ptr.isRoot())
 Ptr.initialize();
-  if (auto *FD = Ptr.getField()) {
+  if (const auto *FD = Ptr.getField())
 Ptr.deref() = Value.truncate(FD->getBitWidthValue(S.getCtx()));
-  } else {
+  else
 Ptr.deref() = Value;
-  }
   return true;
 }
 
@@ -1350,11 +1351,10 @@ bool StoreBitFieldPop(InterpState &S, CodePtr OpPC) {
 return false;
   if (!Ptr.isRoot())
 Ptr.initialize();
-  if (auto *FD = Ptr.getField()) {
+  if (const auto *FD = Ptr.getField())
 Ptr.deref() = Value.truncate(FD->getBitWidthValue(S.getCtx()));
-  } else {
+  else
 Ptr.deref() = Value;
-  }
   return true;
 }
 

diff  --git a/clang/lib/AST/Interp/Record.h b/clang/lib/AST/Interp/Record.h
index b81070aa77e8413..b0952af2d1ac6cc 100644
--- a/clang/lib/AST/Interp/Record.h
+++ b/clang/lib/AST/Interp/Record.h
@@ -29,6 +29,7 @@ class Record final {

[clang] [clang] Avoid evaluating the BitWidth expression over and over again (PR #66203)

2023-10-10 Thread Timm Baeder via cfe-commits

tbaederr wrote:

I've merged https://reviews.llvm.org/D155548, so closing this.

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


[clang] [clang] Avoid evaluating the BitWidth expression over and over again (PR #66203)

2023-10-10 Thread Timm Baeder via cfe-commits

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


[clang] [analyzer] Compute length of string literal initializers (#66990) (PR #68368)

2023-10-10 Thread via cfe-commits

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

Thanks for the updates!

Consider adding a "non-const array" testcase for the sake of completeness; but 
I feel that the patch is also OK as it is now.

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


[clang] [clang][Interp] Implement compound assign operators on bitfields (PR #67306)

2023-10-10 Thread Timm Baeder via cfe-commits

https://github.com/tbaederr updated 
https://github.com/llvm/llvm-project/pull/67306

>From d275b2de769bbae45c87c9ae7e04d744b4849c91 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Mon, 25 Sep 2023 11:39:02 +0200
Subject: [PATCH] [clang][Interp] Implement compound assign operators on
 bitfields

---
 clang/lib/AST/Interp/ByteCodeExprGen.cpp |  7 -
 clang/test/AST/Interp/bitfields.cpp  | 38 ++--
 2 files changed, 42 insertions(+), 3 deletions(-)

diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index e7a431ddee6f002..182c04fdd349f57 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -1158,8 +1158,13 @@ bool 
ByteCodeExprGen::VisitCompoundAssignOperator(
   }
 
   // And store the result in LHS.
-  if (DiscardResult)
+  if (DiscardResult) {
+if (LHS->refersToBitField())
+  return this->emitStoreBitFieldPop(*ResultT, E);
 return this->emitStorePop(*ResultT, E);
+  }
+  if (LHS->refersToBitField())
+return this->emitStoreBitField(*ResultT, E);
   return this->emitStore(*ResultT, E);
 }
 
diff --git a/clang/test/AST/Interp/bitfields.cpp 
b/clang/test/AST/Interp/bitfields.cpp
index e078704fce51ff0..9a144e2f0d9610e 100644
--- a/clang/test/AST/Interp/bitfields.cpp
+++ b/clang/test/AST/Interp/bitfields.cpp
@@ -31,8 +31,6 @@ namespace Basic {
 return a.a = 10;
   }
   static_assert(storeA2() == 2, "");
-
-  // TODO: +=, -=, etc. operators.
 }
 
 namespace Overflow {
@@ -45,3 +43,39 @@ namespace Overflow {
 
   static_assert(f() == 3, "");
 }
+
+namespace Compound {
+  struct A {
+unsigned int a : 2;
+constexpr A() : a(0) {}
+constexpr A(int a) : a(a) {}
+  };
+
+  constexpr unsigned add() {
+A a;
+a.a += 10;
+return a.a;
+  }
+  static_assert(add() == 2, "");
+
+  constexpr unsigned sub() {
+A a;
+a.a -= 10;
+return a.a;
+  }
+  static_assert(sub() == 2, "");
+
+  constexpr unsigned mul() {
+A a(1);
+a.a *= 5;
+return a.a;
+  }
+  static_assert(mul() == 1, "");
+
+  constexpr unsigned div() {
+A a(2);
+a.a /= 2;
+return a.a;
+  }
+  static_assert(div() == 1, "");
+}

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


[clang] [clang] Add /Zc:__STDC__ flag to clang-cl (PR #68690)

2023-10-10 Thread via cfe-commits

github-actions[bot] wrote:




:warning: C/C++ code formatter, clang-format found issues in your code. 
:warning:



You can test this locally with the following command:


``bash
git-clang-format --diff b4343aba9fa12ddb397e08208ec37fcf0fb93864 
49681eace80c60d22e4d9ced4fabe2872f716bab -- 
clang/lib/Driver/ToolChains/Clang.cpp clang/lib/Frontend/InitPreprocessor.cpp 
clang/test/Driver/cl-zc.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index b8f3ff6cd4c9..2834786ba17d 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -6751,7 +6751,6 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
   CmdArgs.push_back("-fms-define-stdc");
   }
 
-
   if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&
   Args.hasArg(options::OPT_fms_runtime_lib_EQ))
 ProcessVSRuntimeLibrary(Args, CmdArgs);
diff --git a/clang/lib/Frontend/InitPreprocessor.cpp 
b/clang/lib/Frontend/InitPreprocessor.cpp
index 46399f613257..e7ce08a8766d 100644
--- a/clang/lib/Frontend/InitPreprocessor.cpp
+++ b/clang/lib/Frontend/InitPreprocessor.cpp
@@ -423,7 +423,8 @@ static void InitializeStandardPredefinedMacros(const 
TargetInfo &TI,
   //  [C++] Whether __STDC__ is predefined and if so, what its value is,
   //  are implementation-defined.
   // (Removed in C++20.)
-  if ((!LangOpts.MSVCCompat || LangOpts.MSVCEnableStdcMacro) && 
!LangOpts.TraditionalCPP)
+  if ((!LangOpts.MSVCCompat || LangOpts.MSVCEnableStdcMacro) &&
+  !LangOpts.TraditionalCPP)
 Builder.defineMacro("__STDC__");
   //   -- __STDC_HOSTED__
   //  The integer literal 1 if the implementation is a hosted

``




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


[clang] [clang] Add /Zc:__STDC__ flag to clang-cl (PR #68690)

2023-10-10 Thread via cfe-commits

https://github.com/xbjfk updated https://github.com/llvm/llvm-project/pull/68690

>From 92899d94e91a6812de8fa5ec7c15c37a81280108 Mon Sep 17 00:00:00 2001
From: Reagan Bohan 
Date: Tue, 10 Oct 2023 11:32:47 +
Subject: [PATCH] [clang] Add /Zc:__STDC__ flag to clang-cl

This commit adds the /Zc:__STDC__ argument from MSVC, which defines __STDC__.
This means, alongside stronger feature parity with MSVC,
that things that rely on __STDC__, such as autoconf, can work.
---
 clang/include/clang/Basic/LangOptions.def |  2 +-
 clang/include/clang/Driver/Options.td |  7 +++
 clang/lib/Driver/ToolChains/Clang.cpp | 10 +-
 clang/lib/Frontend/InitPreprocessor.cpp   |  3 ++-
 clang/test/Driver/cl-zc.cpp   |  4 
 5 files changed, 23 insertions(+), 3 deletions(-)

diff --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index c0ea4ecb9806a5b..97101d0166a135a 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -282,7 +282,7 @@ LANGOPT(HIPUseNewLaunchAPI, 1, 0, "Use new kernel launching 
API for HIP")
 LANGOPT(OffloadUniformBlock, 1, 0, "Assume that kernels are launched with 
uniform block sizes (default true for CUDA/HIP and false otherwise)")
 LANGOPT(HIPStdPar, 1, 0, "Enable Standard Parallel Algorithm Acceleration for 
HIP (experimental)")
 LANGOPT(HIPStdParInterposeAlloc, 1, 0, "Replace allocations / deallocations 
with HIP RT calls when Standard Parallel Algorithm Acceleration for HIP is 
enabled (Experimental)")
-
+LANGOPT(MSVCEnableStdcMacro , 1, 0, "define __STDC__ with -fms-compatability")
 LANGOPT(SizedDeallocation , 1, 0, "sized deallocation")
 LANGOPT(AlignedAllocation , 1, 0, "aligned allocation")
 LANGOPT(AlignedAllocationUnavailable, 1, 0, "aligned allocation functions are 
unavailable")
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index c272a7f1c398aa6..fae1dcc2b5117f7 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -2821,6 +2821,10 @@ def fms_compatibility : Flag<["-"], 
"fms-compatibility">, Group,
   Visibility<[ClangOption, CC1Option, CLOption]>,
   HelpText<"Enable full Microsoft Visual C++ compatibility">,
   MarshallingInfoFlag>;
+def fms_define_stdc : Flag<["-"], "fms-define-stdc">, Group,
+  Visibility<[ClangOption, CC1Option]>,
+  HelpText<"Define __STDC__ in MSVC Compatibility mode">,
+  MarshallingInfoFlag>;
 def fms_extensions : Flag<["-"], "fms-extensions">, Group,
   Visibility<[ClangOption, CC1Option, CLOption]>,
   HelpText<"Accept some non-standard constructs supported by the Microsoft 
compiler">,
@@ -7933,6 +7937,9 @@ def _SLASH_vd : CLJoined<"vd">, HelpText<"Control 
vtordisp placement">,
   Alias;
 def _SLASH_X : CLFlag<"X">,
   HelpText<"Do not add %INCLUDE% to include search path">, Alias;
+def _SLASH_Zc___STDC__ : CLFlag<"Zc:__STDC__">,
+  HelpText<"Define __STDC__">,
+  Alias;
 def _SLASH_Zc_sizedDealloc : CLFlag<"Zc:sizedDealloc">,
   HelpText<"Enable C++14 sized global deallocation functions">,
   Alias;
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index bfd6c5c2864abf7..2834786ba17decf 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -6744,8 +6744,12 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
   options::OPT_fms_compatibility, options::OPT_fno_ms_compatibility,
   (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,
  options::OPT_fno_ms_extensions, true)));
-  if (IsMSVCCompat)
+  if (IsMSVCCompat) {
 CmdArgs.push_back("-fms-compatibility");
+bool IsMSVCDefineStdc = Args.hasArg(options::OPT_fms_define_stdc);
+if (IsMSVCDefineStdc)
+  CmdArgs.push_back("-fms-define-stdc");
+  }
 
   if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&
   Args.hasArg(options::OPT_fms_runtime_lib_EQ))
@@ -7922,6 +7926,10 @@ void Clang::AddClangCLArgs(const ArgList &Args, 
types::ID InputType,
CmdArgs.push_back("-fno-wchar");
  }
 
+ if (Args.hasArg(options::OPT_fms_define_stdc)) {
+   CmdArgs.push_back("-fms-define-stdc");
+ }
+
  if (Args.hasArg(options::OPT__SLASH_kernel)) {
llvm::Triple::ArchType Arch = getToolChain().getArch();
std::vector Values =
diff --git a/clang/lib/Frontend/InitPreprocessor.cpp 
b/clang/lib/Frontend/InitPreprocessor.cpp
index 846e5fce6de7b2c..e7ce08a8766d80c 100644
--- a/clang/lib/Frontend/InitPreprocessor.cpp
+++ b/clang/lib/Frontend/InitPreprocessor.cpp
@@ -423,7 +423,8 @@ static void InitializeStandardPredefinedMacros(const 
TargetInfo &TI,
   //  [C++] Whether __STDC__ is predefined and if so, what its value is,
   //  are implementation-defined.
   // (Removed in C++20.)
-  if (!LangOpts.MSVCCompat && !LangOpts.TraditionalCPP)
+  if ((!LangOpts.MSVCCompat || LangOpts.MSVCEnableStdcMacro) &&
+  !LangOpts.TraditionalCPP)
   

[clang] [analyzer] Fix note for member reference (PR #68691)

2023-10-10 Thread Gábor Spaits via cfe-commits

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


[clang] [analyzer] Fix note for member reference (PR #68691)

2023-10-10 Thread Gábor Spaits via cfe-commits

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


[clang] [analyzer] Fix note for member reference (PR #68691)

2023-10-10 Thread Gábor Spaits via cfe-commits

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


[clang] [SVE][InstCombine] Delete redundante sel instructions with ptrue (PR #68463)

2023-10-10 Thread via cfe-commits


@@ -800,6 +800,13 @@ instCombineConvertFromSVBool(InstCombiner &IC, 
IntrinsicInst &II) {
 
 static std::optional instCombineSVESel(InstCombiner &IC,
   IntrinsicInst &II) {
+  // svsel(ptrue, x, y) => x
+  auto *OpPredicate = II.getOperand(0);

vfdff wrote:

Yes, you are right. Writing more efficient code is another way to optimize.

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


[clang] [flang][driver] Mark -fcommon and -mtune as visible in Flang (PR #68657)

2023-10-10 Thread Fangcao Wang via cfe-commits

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


[clang] [analyzer] Fix note for member reference (PR #68691)

2023-10-10 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Gábor Spaits (spaits)


Changes

In the following code:
```cpp
int main() {
struct Wrapper {char c; int &ref; };
Wrapper w = {.c = 'a', .ref = *(int *)0 };
w.ref = 1;
}
```

The clang static analyzer will produce the following warnings and notes:
```
test.cpp:12:11: warning: Dereference of null pointer [core.NullDereference]
   12 | w.ref = 1;
  | ~~^~~
test.cpp:11:5: note: 'w' initialized here
   11 | Wrapper w = {.c = 'a', .ref = *(int *)0 };
  | ^
test.cpp:12:11: note: Dereference of null pointer
   12 | w.ref = 1;
  | ~~^~~
1 warning generated.
```
In the line where `w` is created, the note gives information about the 
initialization of `w` instead of `w.ref`. Let's compare it to a similar case 
where a null pointer de reference happens to a pointer member:

```cpp
int main() {
 struct Wrapper {char c; int *ptr; };
 Wrapper w = {.c = 'a', .ptr = nullptr };
 *w.ptr = 1;
}
```

Here the following error and notes are seen:
```
test.cpp:18:12: warning: Dereference of null pointer (loaded from field 'ptr') 
[core.NullDereference]
   18 | *w.ptr = 1;
  |~~~ ^
test.cpp:17:5: note: 'w.ptr' initialized to a null pointer value
   17 | Wrapper w = {.c = 'a', .ptr = nullptr };
  | ^
test.cpp:18:12: note: Dereference of null pointer (loaded from field 'ptr')
   18 | *w.ptr = 1;
  |~~~ ^
1 warning generated.
```
Here the note that shows the initialization the initialization of `w.ptr` in 
shown instead of `w`.

This commit is here to achieve similar notes for member reference as the notes 
of member pointers, so the report looks like the following:

```
test.cpp:12:11: warning: Dereference of null pointer [core.NullDereference]
   12 | w.ref = 1;
  | ~~^~~
test.cpp:11:5: note: 'w.ref' initialized to a null pointer value
   11 | Wrapper w = {.c = 'a', .ref = *(int *)0 };
  | ^
test.cpp:12:11: note: Dereference of null pointer
   12 | w.ref = 1;
  | ~~^~~
1 warning generated.
```
Here the initialization of `w.ref` is shown instead of `w`.

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


1 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp (+43-14) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp 
b/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
index 42d03f67510cf88..914011f367d8f2e 100644
--- a/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ b/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -132,6 +132,18 @@ const Expr *bugreporter::getDerefExpr(const Stmt *S) {
 }
 // Pattern match for a few useful cases: a[0], p->f, *p etc.
 else if (const auto *ME = dyn_cast(E)) {
+  // This handles the case when the dereferencing of a member reference
+  // happens. This is needed, because the ast for dereferencing of a
+  // member reference looks like the following:
+  // |-MemberExpr
+  //  `-DeclRefExpr
+  // This branch without the special case just takes out the DeclRefExpr
+  // of the struct, class or union.
+  // This is wrong, because this DeclRefExpr will be passed
+  // to the bug reporting and the notes will refer to wrong variable
+  // (the struct instead of the member).
+  if (ME->getMemberDecl()->getType()->isReferenceType())
+break;
   E = ME->getBase();
 } else if (const auto *IvarRef = dyn_cast(E)) {
   E = IvarRef->getBase();
@@ -157,26 +169,43 @@ const Expr *bugreporter::getDerefExpr(const Stmt *S) {
   return E;
 }
 
+static const VarDecl *getVarDeclForExpression(const Expr *E) {
+  if (const auto *DR = dyn_cast(E))
+return dyn_cast(DR->getDecl());
+  return nullptr;
+}
+
 static const MemRegion *
 getLocationRegionIfReference(const Expr *E, const ExplodedNode *N,
  bool LookingForReference = true) {
-  if (const auto *DR = dyn_cast(E)) {
-if (const auto *VD = dyn_cast(DR->getDecl())) {
-  if (LookingForReference && !VD->getType()->isReferenceType())
-return nullptr;
-  return N->getState()
-  ->getLValue(VD, N->getLocationContext())
-  .getAsRegion();
+  if (const auto *ME = dyn_cast(E)) {
+// This handles other kinds of null references,
+// for example, references from FieldRegions:
+//   struct Wrapper { int &ref; };
+//   Wrapper w = { *(int *)0 };
+//   w.ref = 1;
+const Expr *Base = ME->getBase();
+const VarDecl *VD = getVarDeclForExpression(Base);
+if (!VD)
+  return nullptr;
+
+const auto *FD = dyn_cast(ME->getMemberDecl());
+if (!FD)
+  return nullptr;
+
+if (FD->getType()->isReferenceType()) {
+  SVal StructSVal = N->getState()->getLValue(VD, N->getLocationContext());
+  return N->getState()->getLValue(FD, StructSVal).getAsRegion();
 }
+return

[PATCH] D154581: [clang][Interp] Track existing InitMaps in InterpState

2023-10-10 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 557670.
tbaeder marked an inline comment as done.

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D154581/new/

https://reviews.llvm.org/D154581

Files:
  clang/lib/AST/Interp/Descriptor.cpp
  clang/lib/AST/Interp/Descriptor.h
  clang/lib/AST/Interp/EvalEmitter.cpp
  clang/lib/AST/Interp/EvalEmitter.h
  clang/lib/AST/Interp/InterpBlock.h
  clang/lib/AST/Interp/InterpFrame.cpp
  clang/lib/AST/Interp/InterpState.cpp
  clang/lib/AST/Interp/Pointer.cpp
  clang/lib/AST/Interp/Pointer.h
  clang/test/AST/Interp/arrays.cpp

Index: clang/test/AST/Interp/arrays.cpp
===
--- clang/test/AST/Interp/arrays.cpp
+++ clang/test/AST/Interp/arrays.cpp
@@ -390,3 +390,52 @@
   static_assert(b[4] == '\0', "");
   static_assert(b[5] == '\0', "");
 }
+
+namespace NoInitMapLeak {
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdivision-by-zero"
+#pragma clang diagnostic ignored "-Wc++20-extensions"
+  constexpr int testLeak() { // expected-error {{never produces a constant expression}} \
+ // ref-error {{never produces a constant expression}}
+int a[2];
+a[0] = 1;
+// interrupts interpretation.
+(void)(1 / 0); // expected-note 2{{division by zero}} \
+   // ref-note 2{{division by zero}}
+
+
+return 1;
+  }
+#pragma clang diagnostic pop
+  static_assert(testLeak() == 1, ""); // expected-error {{not an integral constant expression}} \
+  // expected-note {{in call to 'testLeak()'}} \
+  // ref-error {{not an integral constant expression}} \
+  // ref-note {{in call to 'testLeak()'}}
+
+
+  constexpr int a[] = {1,2,3,4/0,5}; // expected-error {{must be initialized by a constant expression}} \
+ // expected-note {{division by zero}} \
+ // ref-error {{must be initialized by a constant expression}} \
+ // ref-note {{division by zero}} \
+ // ref-note {{declared here}}
+
+  /// FIXME: This should fail in the new interpreter as well.
+  constexpr int b = a[0]; // ref-error {{must be initialized by a constant expression}} \
+  // ref-note {{is not a constant expression}} \
+  // ref-note {{declared here}}
+  static_assert(b == 1, ""); // ref-error {{not an integral constant expression}} \
+ // ref-note {{not a constant expression}}
+
+  constexpr int f() { // expected-error {{never produces a constant expression}} \
+  // ref-error {{never produces a constant expression}}
+int a[] = {19,2,3/0,4}; // expected-note 2{{division by zero}} \
+// expected-warning {{is undefined}} \
+// ref-note 2{{division by zero}} \
+// ref-warning {{is undefined}}
+return 1;
+  }
+  static_assert(f() == 1, ""); // expected-error {{not an integral constant expression}} \
+   // expected-note {{in call to}} \
+   // ref-error {{not an integral constant expression}} \
+   // ref-note {{in call to}}
+}
Index: clang/lib/AST/Interp/Pointer.h
===
--- clang/lib/AST/Interp/Pointer.h
+++ clang/lib/AST/Interp/Pointer.h
@@ -99,7 +99,7 @@
 if (getFieldDesc()->ElemDesc)
   Off += sizeof(InlineDescriptor);
 else
-  Off += sizeof(InitMap *);
+  Off += sizeof(InitMapPtr);
 return Pointer(Pointee, Base, Base + Off);
   }
 
@@ -138,7 +138,7 @@
 if (inPrimitiveArray()) {
   if (Offset != Base)
 return *this;
-  return Pointer(Pointee, Base, Offset + sizeof(InitMap *));
+  return Pointer(Pointee, Base, Offset + sizeof(InitMapPtr));
 }
 
 // Pointer is to a field or array element - enter it.
@@ -159,7 +159,7 @@
   // Revert to an outer one-past-end pointer.
   unsigned Adjust;
   if (inPrimitiveArray())
-Adjust = sizeof(InitMap *);
+Adjust = sizeof(InitMapPtr);
   else
 Adjust = sizeof(InlineDescriptor);
   return Pointer(Pointee, Base, Base + getSize() + Adjust);
@@ -248,7 +248,7 @@
   if (getFieldDesc()->ElemDesc)
 Adjust = sizeof(InlineDescriptor);
   else
-Adjust = sizeof(InitMap *);
+Adjust = sizeof(InitMapPtr);
 }
 return Offset - Base - Adjust;
   }
@@ -344,7 +344,7 @@
 assert(isLive() && "Invalid pointer");
 if (isArrayRoot())
   return *reinterpret_cast(Pointee->rawData() + Base +
-sizeof(InitMap *));
+sizeof(InitMapPtr));
 
 return *reinterpret_cast(Pointee->rawData() + Offset);
  

[PATCH] D154581: [clang][Interp] Track existing InitMaps in InterpState

2023-10-10 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder added inline comments.



Comment at: clang/lib/AST/Interp/Descriptor.cpp:42
 const Descriptor *D) {
+  new (Ptr) InitMapPtr(std::nullopt);
+

aaron.ballman wrote:
> This worries me a little bit for a few reasons, but it might be okay:
> 
> * What validates that the bytes pointed to by `Ptr` are aligned properly for 
> an `InitMapPtr` object? Perhaps we need an `alignas` in the function 
> signature to ensure correct alignment of those bytes?
> * `InitMapPtr` is `std::optional>>` 
> and I *think* using placement new will ensure we have correct objects in all 
> the expected places, but I'm not 100% sure because we're calling the 
> `nullopt` constructor here.
> * I *think* it is correct that you are not assigning the result of the 
> placement `new` expression into anything; and I think we need this placement 
> `new` because of the `reinterpret_cast` happening in `dtorArrayTy()`. But it 
> is a bit strange to see the placement `new` hanging off on its own like this. 
> Might be worth some comments explaining. 
> 
> CC @hubert.reinterpretcast @rsmith in case my assessment is incorrect.
I thought using placement new would just call the normal constructors anyway?

BTW, does using a `shared_ptr` here even make sense? Since this is allocated in 
the `Block`, we need to call the constructor and destructors manually anyway.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D154581/new/

https://reviews.llvm.org/D154581

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


[clang] [analyzer] Fix note for member reference (PR #68691)

2023-10-10 Thread Gábor Spaits via cfe-commits

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


[clang-tools-extra] [Support] Add KnownBits::computeForSubBorrow (PR #67788)

2023-10-10 Thread Simon Pilgrim via cfe-commits


@@ -332,6 +332,10 @@ struct KnownBits {
   static KnownBits computeForAddSub(bool Add, bool NSW, const KnownBits &LHS,
 KnownBits RHS);
 
+  /// Compute known bits results from subtracting RHS from LHS.

RKSimon wrote:

Add to comment "and a 1-bit borrow"

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


[clang] [clang][Interp] Implement compound assign operators on bitfields (PR #67306)

2023-10-10 Thread via cfe-commits

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

LGTM. i tried to think of a nicer way to avoid the duplication for discarded 
statements but..i don't have anything

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


[clang] [analyzer] Fix core.VLASize checker false positive taint reports (PR #68140)

2023-10-10 Thread Daniel Krupp via cfe-commits

https://github.com/dkrupp updated 
https://github.com/llvm/llvm-project/pull/68140

>From 4b310278d2923ff718d074a7f7c8806ad03c6401 Mon Sep 17 00:00:00 2001
From: Daniel Krupp 
Date: Tue, 3 Oct 2023 19:58:28 +0200
Subject: [PATCH 1/2] [analyzer] Fix core.VLASize checker false positive taint
 reports

The checker reported a false positive on this code
void testTaintedSanitizedVLASize(void) {
  int x;
  scanf("%d", &x);
  if (x<1)
return;
  int vla[x]; // no-warning
}

After the fix, the checker only emits tainted warning if the vla size is
coming from a tainted source and it cannot prove that it is positive.
---
 .../StaticAnalyzer/Checkers/VLASizeChecker.cpp   | 16 
 clang/test/Analysis/taint-diagnostic-visitor.c   |  4 ++--
 clang/test/Analysis/taint-generic.c  | 11 ++-
 3 files changed, 20 insertions(+), 11 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/VLASizeChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/VLASizeChecker.cpp
index b195d912cadfe9b..46b5f5e10f0e65c 100644
--- a/clang/lib/StaticAnalyzer/Checkers/VLASizeChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/VLASizeChecker.cpp
@@ -162,12 +162,6 @@ ProgramStateRef 
VLASizeChecker::checkVLAIndexSize(CheckerContext &C,
   if (SizeV.isUnknown())
 return nullptr;
 
-  // Check if the size is tainted.
-  if (isTainted(State, SizeV)) {
-reportTaintBug(SizeE, State, C, SizeV);
-return nullptr;
-  }
-
   // Check if the size is zero.
   DefinedSVal SizeD = SizeV.castAs();
 
@@ -189,10 +183,10 @@ ProgramStateRef 
VLASizeChecker::checkVLAIndexSize(CheckerContext &C,
   DefinedOrUnknownSVal Zero = SVB.makeZeroVal(SizeTy);
 
   SVal LessThanZeroVal = SVB.evalBinOp(State, BO_LT, SizeD, Zero, SizeTy);
+  ProgramStateRef StatePos, StateNeg;
   if (std::optional LessThanZeroDVal =
   LessThanZeroVal.getAs()) {
 ConstraintManager &CM = C.getConstraintManager();
-ProgramStateRef StatePos, StateNeg;
 
 std::tie(StateNeg, StatePos) = CM.assumeDual(State, *LessThanZeroDVal);
 if (StateNeg && !StatePos) {
@@ -202,6 +196,12 @@ ProgramStateRef 
VLASizeChecker::checkVLAIndexSize(CheckerContext &C,
 State = StatePos;
   }
 
+  // Check if the size is tainted.
+  if ((StateNeg || StateZero) && isTainted(State, SizeV)) {
+reportTaintBug(SizeE, State, C, SizeV);
+return nullptr;
+  }
+
   return State;
 }
 
@@ -220,7 +220,7 @@ void VLASizeChecker::reportTaintBug(const Expr *SizeE, 
ProgramStateRef State,
   SmallString<256> buf;
   llvm::raw_svector_ostream os(buf);
   os << "Declared variable-length array (VLA) ";
-  os << "has tainted size";
+  os << "has a tainted (attacker controlled) size, that can be 0 or negative";
 
   auto report = std::make_unique(*TaintBT, os.str(), 
N);
   report->addRange(SizeE->getSourceRange());
diff --git a/clang/test/Analysis/taint-diagnostic-visitor.c 
b/clang/test/Analysis/taint-diagnostic-visitor.c
index 8a7510177f3e444..45369785ed6924e 100644
--- a/clang/test/Analysis/taint-diagnostic-visitor.c
+++ b/clang/test/Analysis/taint-diagnostic-visitor.c
@@ -46,8 +46,8 @@ void taintDiagnosticVLA(void) {
   scanf("%d", &x); // expected-note {{Value assigned to 'x'}}
// expected-note@-1 {{Taint originated here}}
// expected-note@-2 {{Taint propagated to the 2nd argument}}
-  int vla[x]; // expected-warning {{Declared variable-length array (VLA) has 
tainted size}}
-  // expected-note@-1 {{Declared variable-length array (VLA) has 
tainted size}}
+  int vla[x]; // expected-warning {{Declared variable-length array (VLA) has a 
tainted}}
+  // expected-note@-1 {{Declared variable-length array (VLA) has a 
tainted}}
 }
 
 
diff --git a/clang/test/Analysis/taint-generic.c 
b/clang/test/Analysis/taint-generic.c
index c6a01594f15abb7..ae2ae5b23aab3c6 100644
--- a/clang/test/Analysis/taint-generic.c
+++ b/clang/test/Analysis/taint-generic.c
@@ -405,7 +405,16 @@ int testDivByZero(void) {
 void testTaintedVLASize(void) {
   int x;
   scanf("%d", &x);
-  int vla[x]; // expected-warning{{Declared variable-length array (VLA) has 
tainted size}}
+  int vla[x]; // expected-warning{{Declared variable-length array (VLA) has a 
tainted (attacker controlled) size, that can be 0 or negative}}
+}
+
+// Tainted-sanitized VLAs.
+void testTaintedSanitizedVLASize(void) {
+  int x;
+  scanf("%d", &x);
+  if (x<1)
+return;
+  int vla[x]; // no-warning
 }
 
 int testTaintedAllocaMem() {

>From 94fa4af57d28854df1c6ab3e3be2a7a902b620f1 Mon Sep 17 00:00:00 2001
From: Daniel Krupp 
Date: Tue, 10 Oct 2023 14:35:52 +0200
Subject: [PATCH 2/2] fixup!

---
 clang/docs/analyzer/checkers.rst  | 27 ---
 .../Checkers/VLASizeChecker.cpp   |  2 +-
 clang/test/Analysis/taint-generic.c   |  2 +-
 3 files changed, 26 insertions(+), 5 deletions(-)

diff --git a/clang/docs/analyzer/checkers.rst b/clang/docs/analyzer/checkers.rst
index dbd6d7787823530..a48ba784ee94333 100644
--- a

[PATCH] D155850: [HIP][Clang][CodeGen][RFC] Add codegen support for C++ Parallel Algorithm Offload

2023-10-10 Thread Alex Voicu via Phabricator via cfe-commits
AlexVlx updated this revision to Diff 557672.
AlexVlx removed reviewers: tra, jlebar.
AlexVlx added a comment.

Rebase.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D155850/new/

https://reviews.llvm.org/D155850

Files:
  clang/lib/CodeGen/BackendUtil.cpp
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/CodeGen/CGStmt.cpp
  clang/lib/CodeGen/CMakeLists.txt
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/CodeGen/CodeGenModule.cpp
  clang/test/CodeGenHipStdPar/unannotated-functions-get-emitted.cpp
  clang/test/CodeGenHipStdPar/unsupported-ASM.cpp
  clang/test/CodeGenHipStdPar/unsupported-builtins.cpp

Index: clang/test/CodeGenHipStdPar/unsupported-builtins.cpp
===
--- /dev/null
+++ clang/test/CodeGenHipStdPar/unsupported-builtins.cpp
@@ -0,0 +1,8 @@
+// RUN: %clang_cc1 -triple amdgcn-amd-amdhsa -aux-triple x86_64-unknown-linux-gnu \
+// RUN:   --hipstdpar -x hip -emit-llvm -fcuda-is-device -o - %s | FileCheck %s
+
+#define __global__ __attribute__((global))
+
+__global__ void foo() { return __builtin_ia32_pause(); }
+
+// CHECK: declare void @__builtin_ia32_pause__hipstdpar_unsupported()
Index: clang/test/CodeGenHipStdPar/unsupported-ASM.cpp
===
--- /dev/null
+++ clang/test/CodeGenHipStdPar/unsupported-ASM.cpp
@@ -0,0 +1,10 @@
+// RUN: %clang_cc1 -triple amdgcn-amd-amdhsa -aux-triple x86_64-unknown-linux-gnu \
+// RUN:   --hipstdpar -x hip -emit-llvm -fcuda-is-device -o - %s | FileCheck %s
+
+#define __global__ __attribute__((global))
+
+__global__ void foo(int i) {
+asm ("addl %2, %1; seto %b0" : "=q" (i), "+g" (i) : "r" (i));
+}
+
+// CHECK: declare void @__ASM__hipstdpar_unsupported([{{.*}}])
Index: clang/test/CodeGenHipStdPar/unannotated-functions-get-emitted.cpp
===
--- /dev/null
+++ clang/test/CodeGenHipStdPar/unannotated-functions-get-emitted.cpp
@@ -0,0 +1,19 @@
+// RUN: %clang_cc1 -x hip -emit-llvm -fcuda-is-device \
+// RUN:   -o - %s | FileCheck --check-prefix=NO-HIPSTDPAR-DEV %s
+
+// RUN: %clang_cc1 --hipstdpar -emit-llvm -fcuda-is-device \
+// RUN:   -o - %s | FileCheck --check-prefix=HIPSTDPAR-DEV %s
+
+#define __device__ __attribute__((device))
+
+// NO-HIPSTDPAR-DEV-NOT: define {{.*}} void @_Z3fooPff({{.*}})
+// HIPSTDPAR-DEV: define {{.*}} void @_Z3fooPff({{.*}})
+void foo(float *a, float b) {
+  *a = b;
+}
+
+// NO-HIPSTDPAR-DEV: define {{.*}} void @_Z3barPff({{.*}})
+// HIPSTDPAR-DEV: define {{.*}} void @_Z3barPff({{.*}})
+__device__ void bar(float *a, float b) {
+  *a = b;
+}
Index: clang/lib/CodeGen/CodeGenModule.cpp
===
--- clang/lib/CodeGen/CodeGenModule.cpp
+++ clang/lib/CodeGen/CodeGenModule.cpp
@@ -3585,7 +3585,10 @@
   !Global->hasAttr() &&
   !Global->hasAttr() &&
   !Global->getType()->isCUDADeviceBuiltinSurfaceType() &&
-  !Global->getType()->isCUDADeviceBuiltinTextureType())
+  !Global->getType()->isCUDADeviceBuiltinTextureType() &&
+  !(LangOpts.HIPStdPar &&
+isa(Global) &&
+!Global->hasAttr()))
 return;
 } else {
   // We need to emit host-side 'shadows' for all global
Index: clang/lib/CodeGen/CodeGenFunction.cpp
===
--- clang/lib/CodeGen/CodeGenFunction.cpp
+++ clang/lib/CodeGen/CodeGenFunction.cpp
@@ -2595,10 +2595,15 @@
   std::string MissingFeature;
   llvm::StringMap CallerFeatureMap;
   CGM.getContext().getFunctionFeatureMap(CallerFeatureMap, FD);
+  // When compiling in HipStdPar mode we have to be conservative in rejecting
+  // target specific features in the FE, and defer the possible error to the
+  // AcceleratorCodeSelection pass, wherein iff an unsupported target builtin is
+  // referenced by an accelerator executable function, we emit an error.
+  bool IsHipStdPar = getLangOpts().HIPStdPar && getLangOpts().CUDAIsDevice;
   if (BuiltinID) {
 StringRef FeatureList(CGM.getContext().BuiltinInfo.getRequiredFeatures(BuiltinID));
 if (!Builtin::evaluateRequiredTargetFeatures(
-FeatureList, CallerFeatureMap)) {
+FeatureList, CallerFeatureMap) && !IsHipStdPar) {
   CGM.getDiags().Report(Loc, diag::err_builtin_needs_feature)
   << TargetDecl->getDeclName()
   << FeatureList;
@@ -2631,7 +2636,7 @@
 return false;
   }
   return true;
-}))
+}) && !IsHipStdPar)
   CGM.getDiags().Report(Loc, diag::err_function_needs_feature)
   << FD->getDeclName() << TargetDecl->getDeclName() << MissingFeature;
   } else if (!FD->isMultiVersion() && FD->hasAttr()) {
@@ -2640,7 +2645,8 @@
 
 for (const auto &F : CalleeFeatureMap) {
   if (F.getValue() && (!CallerFeatureMap.lookup(F.getKey()) ||
-   !CallerFeatureMap.find(F.getKey())->getValue()))
+  

[clang] [clang-format][NFC] Annotate control statement r_braces (PR #68621)

2023-10-10 Thread via cfe-commits

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

LGTM

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


[clang] [analyzer] Fix note for member reference (PR #68691)

2023-10-10 Thread Gábor Spaits via cfe-commits

https://github.com/spaits updated 
https://github.com/llvm/llvm-project/pull/68691

From bb9cb77cab7b073d45c0b998c926a0b60a75a35e Mon Sep 17 00:00:00 2001
From: Gabor Spaits 
Date: Tue, 10 Oct 2023 13:40:05 +0200
Subject: [PATCH 1/2] [analyzer] Fix note for member reference

---
 .../Core/BugReporterVisitors.cpp  | 57 ++-
 1 file changed, 43 insertions(+), 14 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp 
b/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
index 42d03f67510cf88..914011f367d8f2e 100644
--- a/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
+++ b/clang/lib/StaticAnalyzer/Core/BugReporterVisitors.cpp
@@ -132,6 +132,18 @@ const Expr *bugreporter::getDerefExpr(const Stmt *S) {
 }
 // Pattern match for a few useful cases: a[0], p->f, *p etc.
 else if (const auto *ME = dyn_cast(E)) {
+  // This handles the case when the dereferencing of a member reference
+  // happens. This is needed, because the ast for dereferencing of a
+  // member reference looks like the following:
+  // |-MemberExpr
+  //  `-DeclRefExpr
+  // This branch without the special case just takes out the DeclRefExpr
+  // of the struct, class or union.
+  // This is wrong, because this DeclRefExpr will be passed
+  // to the bug reporting and the notes will refer to wrong variable
+  // (the struct instead of the member).
+  if (ME->getMemberDecl()->getType()->isReferenceType())
+break;
   E = ME->getBase();
 } else if (const auto *IvarRef = dyn_cast(E)) {
   E = IvarRef->getBase();
@@ -157,26 +169,43 @@ const Expr *bugreporter::getDerefExpr(const Stmt *S) {
   return E;
 }
 
+static const VarDecl *getVarDeclForExpression(const Expr *E) {
+  if (const auto *DR = dyn_cast(E))
+return dyn_cast(DR->getDecl());
+  return nullptr;
+}
+
 static const MemRegion *
 getLocationRegionIfReference(const Expr *E, const ExplodedNode *N,
  bool LookingForReference = true) {
-  if (const auto *DR = dyn_cast(E)) {
-if (const auto *VD = dyn_cast(DR->getDecl())) {
-  if (LookingForReference && !VD->getType()->isReferenceType())
-return nullptr;
-  return N->getState()
-  ->getLValue(VD, N->getLocationContext())
-  .getAsRegion();
+  if (const auto *ME = dyn_cast(E)) {
+// This handles other kinds of null references,
+// for example, references from FieldRegions:
+//   struct Wrapper { int &ref; };
+//   Wrapper w = { *(int *)0 };
+//   w.ref = 1;
+const Expr *Base = ME->getBase();
+const VarDecl *VD = getVarDeclForExpression(Base);
+if (!VD)
+  return nullptr;
+
+const auto *FD = dyn_cast(ME->getMemberDecl());
+if (!FD)
+  return nullptr;
+
+if (FD->getType()->isReferenceType()) {
+  SVal StructSVal = N->getState()->getLValue(VD, N->getLocationContext());
+  return N->getState()->getLValue(FD, StructSVal).getAsRegion();
 }
+return nullptr;
   }
 
-  // FIXME: This does not handle other kinds of null references,
-  // for example, references from FieldRegions:
-  //   struct Wrapper { int &ref; };
-  //   Wrapper w = { *(int *)0 };
-  //   w.ref = 1;
-
-  return nullptr;
+  const VarDecl *VD = getVarDeclForExpression(E);
+  if (!VD)
+return nullptr;
+  if (LookingForReference && !VD->getType()->isReferenceType())
+return nullptr;
+  return N->getState()->getLValue(VD, N->getLocationContext()).getAsRegion();
 }
 
 /// Comparing internal representations of symbolic values (via

From 5bf3ba5f3b66d972e3c26c8f782ae077700e459a Mon Sep 17 00:00:00 2001
From: Gabor Spaits 
Date: Tue, 10 Oct 2023 15:26:28 +0200
Subject: [PATCH 2/2] Add test cases for null reference reports

---
 .../deref-track-symbolic-region.cpp   | 31 +++
 1 file changed, 31 insertions(+)

diff --git a/clang/test/Analysis/diagnostics/deref-track-symbolic-region.cpp 
b/clang/test/Analysis/diagnostics/deref-track-symbolic-region.cpp
index e258a60aa966a53..2442851da989b16 100644
--- a/clang/test/Analysis/diagnostics/deref-track-symbolic-region.cpp
+++ b/clang/test/Analysis/diagnostics/deref-track-symbolic-region.cpp
@@ -41,3 +41,34 @@ int testRefToNullPtr2() {
   return *p2; //expected-warning {{Dereference of null pointer}}
   // expected-note@-1{{Dereference of null pointer}}
 }
+
+void testMemberNullPointerDeref() {
+  struct Wrapper {char c; int *ptr; };  
+  Wrapper w = {'a', nullptr};   // expected-note {{'w.ptr' initialized 
to a null pointer value}}
+  *w.ptr = 1;   //expected-warning {{Dereference of 
null pointer}}
+// expected-note@-1{{Dereference of 
null pointer}}
+}
+
+void testMemberNullReferenceDeref() {
+  struct Wrapper {char c; int &ref; };
+  Wrapper w = {.c = 'a', .ref = *(int *)0 }; // expected-note {{'w.ref' 
initialized to a null pointer value}}
+   

[clang] [clang][Interp] Support AddOffset with 128bit offsets (PR #68679)

2023-10-10 Thread Erich Keane via cfe-commits


@@ -1437,7 +1437,7 @@ bool OffsetHelper(InterpState &S, CodePtr OpPC, const T 
&Offset,
 return false;
   };
 
-  unsigned MaxOffset = MaxIndex - Ptr.getIndex();
+  T MaxOffset = T::from(MaxIndex - Ptr.getIndex(), Offset.bitWidth());

erichkeane wrote:

Should MaxIndex just be a `T` as well?  I wonder if this function should just 
be 'fully dedicated' to being `T` instead of just this 1 variable here?

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


  1   2   3   >