[clang] [alpha.webkit.UncountedCallArgsChecker] Allow ASSERT and atomic operations in a trivial function (PR #82063)

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

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

>From c46f11b98f8ec159a19004952fb67705eb0988dd Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa 
Date: Fri, 16 Feb 2024 14:54:55 -0800
Subject: [PATCH] [alpha.webkit.UncountedCallArgsChecker] Allow ASSERT and
 atomic operations in a trivial function

This PR permits the use of WebKit's ASSERT macros as well as std::atomic 
operations to appear
within a trivial function. Also exempt ref() and deref() member function calls.
---
 .../Checkers/WebKit/ASTUtils.cpp  |  4 ++
 .../Checkers/WebKit/PtrTypesSemantics.cpp | 16 
 .../WebKit/UncountedCallArgsChecker.cpp   |  5 +++
 .../call-args-protected-return-value.cpp  |  6 ++-
 .../Analysis/Checkers/WebKit/mock-types.h | 20 +-
 .../Checkers/WebKit/uncounted-obj-arg.cpp | 39 +--
 6 files changed, 75 insertions(+), 15 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
index 94eaa81af51772..1a9d6d3127fb7f 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp
@@ -23,6 +23,10 @@ tryToFindPtrOrigin(const Expr *E, bool 
StopAtFirstRefCountedObj) {
   E = tempExpr->getSubExpr();
   continue;
 }
+if (auto *tempExpr = dyn_cast(E)) {
+  E = tempExpr->getSubExpr();
+  continue;
+}
 if (auto *cast = dyn_cast(E)) {
   if (StopAtFirstRefCountedObj) {
 if (auto *ConversionFunc =
diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
index 6f236db0474079..a7891d2da07c18 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
@@ -315,6 +315,8 @@ class TrivialFunctionAnalysisVisitor
 return false;
   }
 
+  bool VisitAtomicExpr(const AtomicExpr *E) { return VisitChildren(E); }
+
   bool VisitStaticAssertDecl(const StaticAssertDecl *SAD) {
 // Any static_assert is considered trivial.
 return true;
@@ -330,12 +332,18 @@ class TrivialFunctionAnalysisVisitor
 const auto &Name = safeGetName(Callee);
 
 if (Name == "WTFCrashWithInfo" || Name == "WTFBreakpointTrap" ||
+Name == "WTFReportAssertionFailure" ||
 Name == "compilerFenceForCrash" || Name == "__builtin_unreachable")
   return true;
 
 return TrivialFunctionAnalysis::isTrivialImpl(Callee, Cache);
   }
 
+  bool VisitPredefinedExpr(const PredefinedExpr *E) {
+// A predefined identifier such as "func" is considered trivial.
+return true;
+  }
+
   bool VisitCXXMemberCallExpr(const CXXMemberCallExpr *MCE) {
 if (!checkArguments(MCE))
   return false;
@@ -356,6 +364,14 @@ class TrivialFunctionAnalysisVisitor
 return TrivialFunctionAnalysis::isTrivialImpl(Callee, Cache);
   }
 
+  bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
+if (auto *Expr = E->getExpr()) {
+  if (!Visit(Expr))
+return false;
+}
+return true;
+  }
+
   bool checkArguments(const CallExpr *CE) {
 for (const Expr *Arg : CE->arguments()) {
   if (Arg && !Visit(Arg))
diff --git 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp
index 17a64e1b1b8e04..8d344f9b63961a 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp
@@ -73,6 +73,11 @@ class UncountedCallArgsChecker
   unsigned ArgIdx = isa(CE) && 
isa_and_nonnull(F);
 
   if (auto *MemberCallExpr = dyn_cast(CE)) {
+if (auto *MD = MemberCallExpr->getMethodDecl()) {
+  auto name = safeGetName(MD);
+  if (name == "ref" || name == "deref")
+return;
+}
 auto *E = MemberCallExpr->getImplicitObjectArgument();
 QualType ArgType = MemberCallExpr->getObjectType();
 std::optional IsUncounted =
diff --git 
a/clang/test/Analysis/Checkers/WebKit/call-args-protected-return-value.cpp 
b/clang/test/Analysis/Checkers/WebKit/call-args-protected-return-value.cpp
index 1c4b3df211b1e3..6a8b7464845a26 100644
--- a/clang/test/Analysis/Checkers/WebKit/call-args-protected-return-value.cpp
+++ b/clang/test/Analysis/Checkers/WebKit/call-args-protected-return-value.cpp
@@ -5,12 +5,14 @@
 
 class RefCounted {
 public:
-  void ref();
-  void deref();
+  void ref() const;
+  void deref() const;
 };
 
 class Object {
 public:
+  void ref() const;
+  void deref() const;
   void someFunction(RefCounted&);
 };
 
diff --git a/clang/test/Analysis/Checkers/WebKit/mock-types.h 
b/clang/test/Analysis/Checkers/WebKit/mock-types.h
index d08a997aa8c043..82db67bb031dd6 100644
--- a/clang/test/Analysis/Checkers/WebKit/mock-types.h
+++ b/clang/test/Analysis/Checkers/WebKit/mock-ty

[clang] [clang][Interp] Emit const references for Float arguments (PR #79753)

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

tbaederr wrote:

Ping

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


[clang] [clang][Interp] Handle complex values in visitBool() (PR #79452)

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

tbaederr wrote:

Ping

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


[clang] fcf3ca9 - [clang][Interp][NFC] Split emitRecordDestruction

2024-02-19 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-02-19T09:23:31+01:00
New Revision: fcf3ca9a5e50f32edcfe68c291edd1ecab7009a7

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

LOG: [clang][Interp][NFC] Split emitRecordDestruction

into a general part and a record part. This will be needed in future
patches.

Added: 


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

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 6ad75d4e034a9d..e8b0fffd5ee34d 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -3365,45 +3365,8 @@ bool ByteCodeExprGen::emitComplexReal(const 
Expr *SubExpr) {
   return true;
 }
 
-/// When calling this, we have a pointer of the local-to-destroy
-/// on the stack.
-/// Emit destruction of record types (or arrays of record types).
 template 
-bool ByteCodeExprGen::emitRecordDestruction(const Descriptor *Desc) {
-  assert(Desc);
-  assert(!Desc->isPrimitive());
-  assert(!Desc->isPrimitiveArray());
-
-  // Arrays.
-  if (Desc->isArray()) {
-const Descriptor *ElemDesc = Desc->ElemDesc;
-assert(ElemDesc);
-
-// Don't need to do anything for these.
-if (ElemDesc->isPrimitiveArray())
-  return this->emitPopPtr(SourceInfo{});
-
-// If this is an array of record types, check if we need
-// to call the element destructors at all. If not, try
-// to save the work.
-if (const Record *ElemRecord = ElemDesc->ElemRecord) {
-  if (const CXXDestructorDecl *Dtor = ElemRecord->getDestructor();
-  !Dtor || Dtor->isTrivial())
-return this->emitPopPtr(SourceInfo{});
-}
-
-for (ssize_t I = Desc->getNumElems() - 1; I >= 0; --I) {
-  if (!this->emitConstUint64(I, SourceInfo{}))
-return false;
-  if (!this->emitArrayElemPtrUint64(SourceInfo{}))
-return false;
-  if (!this->emitRecordDestruction(ElemDesc))
-return false;
-}
-return this->emitPopPtr(SourceInfo{});
-  }
-
-  const Record *R = Desc->ElemRecord;
+bool ByteCodeExprGen::emitRecordDestruction(const Record *R) {
   assert(R);
   // First, destroy all fields.
   for (const Record::Field &Field : llvm::reverse(R->fields())) {
@@ -3413,7 +3376,9 @@ bool 
ByteCodeExprGen::emitRecordDestruction(const Descriptor *Desc) {
 return false;
   if (!this->emitGetPtrField(Field.Offset, SourceInfo{}))
 return false;
-  if (!this->emitRecordDestruction(D))
+  if (!this->emitDestruction(D))
+return false;
+  if (!this->emitPopPtr(SourceInfo{}))
 return false;
 }
   }
@@ -3437,13 +3402,57 @@ bool 
ByteCodeExprGen::emitRecordDestruction(const Descriptor *Desc) {
   for (const Record::Base &Base : llvm::reverse(R->bases())) {
 if (!this->emitGetPtrBase(Base.Offset, SourceInfo{}))
   return false;
-if (!this->emitRecordDestruction(Base.Desc))
+if (!this->emitRecordDestruction(Base.R))
+  return false;
+if (!this->emitPopPtr(SourceInfo{}))
   return false;
   }
+
   // FIXME: Virtual bases.
+  return true;
+}
+/// When calling this, we have a pointer of the local-to-destroy
+/// on the stack.
+/// Emit destruction of record types (or arrays of record types).
+template 
+bool ByteCodeExprGen::emitDestruction(const Descriptor *Desc) {
+  assert(Desc);
+  assert(!Desc->isPrimitive());
+  assert(!Desc->isPrimitiveArray());
+
+  // Arrays.
+  if (Desc->isArray()) {
+const Descriptor *ElemDesc = Desc->ElemDesc;
+assert(ElemDesc);
+
+// Don't need to do anything for these.
+if (ElemDesc->isPrimitiveArray())
+  return true;
+
+// If this is an array of record types, check if we need
+// to call the element destructors at all. If not, try
+// to save the work.
+if (const Record *ElemRecord = ElemDesc->ElemRecord) {
+  if (const CXXDestructorDecl *Dtor = ElemRecord->getDestructor();
+  !Dtor || Dtor->isTrivial())
+return true;
+}
+
+for (ssize_t I = Desc->getNumElems() - 1; I >= 0; --I) {
+  if (!this->emitConstUint64(I, SourceInfo{}))
+return false;
+  if (!this->emitArrayElemPtrUint64(SourceInfo{}))
+return false;
+  if (!this->emitDestruction(ElemDesc))
+return false;
+  if (!this->emitPopPtr(SourceInfo{}))
+return false;
+}
+return true;
+  }
 
-  // Remove the instance pointer.
-  return this->emitPopPtr(SourceInfo{});
+  assert(Desc->ElemRecord);
+  return this->emitRecordDestruction(Desc->ElemRecord);
 }
 
 namespace clang {

diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.h 
b/clang/lib/AST/Interp/ByteCodeExprGen.h
index eeb56dc8456565..abaf28ac7d447d 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen

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

2024-02-19 Thread Bhuminjay Soni via cfe-commits

11happy wrote:

what would be the reason for windows build failing , is it a CI issue or 
specific to this PR & what can I do to resolve that.
Thank you

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


[clang] d61864f - [clang][Interp] Don't create Records for incomplete decls

2024-02-19 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-02-19T09:23:53+01:00
New Revision: d61864f813e33b4228e56f391ec53566aab9efda

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

LOG: [clang][Interp] Don't create Records for incomplete decls

We would previously create the Record instance with 0 fields,
which is incorrect. We later see it again with 1 field.

Fixes #82203

Added: 


Modified: 
clang/lib/AST/Interp/Program.cpp
clang/test/AST/Interp/lambda.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/Program.cpp 
b/clang/lib/AST/Interp/Program.cpp
index ec6cdebcd820fa..61293a3fef4709 100644
--- a/clang/lib/AST/Interp/Program.cpp
+++ b/clang/lib/AST/Interp/Program.cpp
@@ -232,6 +232,9 @@ Record *Program::getOrCreateRecord(const RecordDecl *RD) {
   if (!RD)
 return nullptr;
 
+  if (!RD->isCompleteDefinition())
+return nullptr;
+
   // Deduplicate records.
   if (auto It = Records.find(RD); It != Records.end())
 return It->second;

diff  --git a/clang/test/AST/Interp/lambda.cpp 
b/clang/test/AST/Interp/lambda.cpp
index 3040e6a1e386c7..a5e0d0f1fd9f48 100644
--- a/clang/test/AST/Interp/lambda.cpp
+++ b/clang/test/AST/Interp/lambda.cpp
@@ -222,3 +222,16 @@ namespace GH62611 {
 return 0;
   }
 }
+
+namespace LambdaToAPValue {
+  void wrapper() {
+constexpr auto f = []() constexpr {
+  return 0;
+};
+
+constexpr auto g = [f]() constexpr {
+  return f();
+};
+static_assert(g() == f(), "");
+  }
+}



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


[clang] [clang][analyzer] Simplify code of StreamChecker (NFC). (PR #82228)

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

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

Continuation of commit 42b5037, apply changes to the remaining functions.
Code for function `fflush` was not changed, because it is more special compared 
to the others.

From 0c93cbe17010dfd1382486952d80898ba1360243 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Bal=C3=A1zs=20K=C3=A9ri?= 
Date: Mon, 19 Feb 2024 09:39:30 +0100
Subject: [PATCH] [clang][analyzer] Simplify code of StreamChecker (NFC).

Continuation of commit 42b5037, apply changes to the remaining
functions.
Code for function `fflush` was not changed, because it is more
special compared to the others.
---
 .../StaticAnalyzer/Checkers/StreamChecker.cpp | 345 ++
 1 file changed, 112 insertions(+), 233 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index 354217c1e52922..82296e0b83649b 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -265,6 +265,11 @@ struct StreamOperationEvaluator {
SVB.makeIntVal(Val, CE->getCallReturnType(ACtx)));
   }
 
+  ProgramStateRef bindReturnValue(ProgramStateRef State, CheckerContext &C,
+  SVal Val) {
+return State->BindExpr(CE, C.getLocationContext(), Val);
+  }
+
   ProgramStateRef bindNullReturnValue(ProgramStateRef State,
   CheckerContext &C) {
 return State->BindExpr(CE, C.getLocationContext(),
@@ -280,6 +285,13 @@ struct StreamOperationEvaluator {
   return nullptr;
 return State->assume(*Cond, true);
   }
+
+  ProgramStatePair makeRetValAndAssumeDual(ProgramStateRef State,
+   CheckerContext &C) {
+DefinedSVal RetVal = makeRetVal(C, CE);
+State = State->BindExpr(CE, C.getLocationContext(), RetVal);
+return C.getConstraintManager().assumeDual(State, RetVal);
+  }
 };
 
 class StreamChecker : public Checker(Call.getOriginExpr());
-  if (!CE)
-return;
 
-  const StreamState *OldSS = State->get(StreamSym);
-  if (!OldSS)
+  ProgramStateRef State = C.getState();
+  StreamOperationEvaluator E(C);
+  if (!E.Init(Desc, Call, C, State))
 return;
 
-  assertStreamStateOpened(OldSS);
-
-  NonLoc RetVal = makeRetVal(C, CE).castAs();
-  State = State->BindExpr(CE, C.getLocationContext(), RetVal);
-  SValBuilder &SVB = C.getSValBuilder();
-  auto &ACtx = C.getASTContext();
-  auto Cond = SVB.evalBinOp(State, BO_GE, RetVal, SVB.makeZeroVal(ACtx.IntTy),
-SVB.getConditionType())
-  .getAs();
+  NonLoc RetVal = makeRetVal(C, E.CE).castAs();
+  State = State->BindExpr(E.CE, C.getLocationContext(), RetVal);
+  auto Cond =
+  E.SVB
+  .evalBinOp(State, BO_GE, RetVal, E.SVB.makeZeroVal(E.ACtx.IntTy),
+ E.SVB.getConditionType())
+  .getAs();
   if (!Cond)
 return;
   ProgramStateRef StateNotFailed, StateFailed;
   std::tie(StateNotFailed, StateFailed) = State->assume(*Cond);
 
   StateNotFailed =
-  StateNotFailed->set(StreamSym, StreamState::getOpened(Desc));
+  E.setStreamState(StateNotFailed, StreamState::getOpened(Desc));
   C.addTransition(StateNotFailed);
 
   // Add transition for the failed state. The resulting value of the file
   // position indicator for the stream is indeterminate.
-  StateFailed = StateFailed->set(
-  StreamSym, StreamState::getOpened(Desc, ErrorFError, true));
+  StateFailed = E.setStreamState(
+  StateFailed, StreamState::getOpened(Desc, ErrorFError, true));
   C.addTransition(StateFailed);
 }
 
 void StreamChecker::evalFscanf(const FnDescription *Desc, const CallEvent 
&Call,
CheckerContext &C) const {
-  ProgramStateRef State = C.getState();
   if (Call.getNumArgs() < 2)
 return;
-  SymbolRef StreamSym = getStreamArg(Desc, Call).getAsSymbol();
-  if (!StreamSym)
-return;
-
-  const CallExpr *CE = dyn_cast_or_null(Call.getOriginExpr());
-  if (!CE)
-return;
 
-  const StreamState *OldSS = State->get(StreamSym);
-  if (!OldSS)
+  ProgramStateRef State = C.getState();
+  StreamOperationEvaluator E(C);
+  if (!E.Init(Desc, Call, C, State))
 return;
 
-  assertStreamStateOpened(OldSS);
-
-  SValBuilder &SVB = C.getSValBuilder();
-  ASTContext &ACtx = C.getASTContext();
-
   // Add the success state.
   // In this context "success" means there is not an EOF or other read error
   // before any item is matched in 'fscanf'. But there may be match failure,
@@ -1007,19 +998,15 @@ void StreamChecker::evalFscanf(const FnDescription 
*Desc, const CallEvent &Call,
   // then EOF or read error happens. Now this case is handled like a "success"
   // case, and no error flags are set on the stream. This is probably not
   // accurate, and the POSIX documentation does not tell more.
-  if (OldSS->ErrorState != ErrorFEof) {
-NonLoc RetVal

[clang] e98abc3 - [clang][Interp] Emit dtors when ignoring CXXConstructExprs

2024-02-19 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-02-19T09:48:50+01:00
New Revision: e98abc3ea0796a5d78eb48f2ee9b3019e8133562

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

LOG: [clang][Interp] Emit dtors when ignoring CXXConstructExprs

The comment says we should emit destructors, but we didn't.

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.cpp
clang/test/AST/Interp/records.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index e8b0fffd5ee34d..a778c300fc33a0 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -1848,6 +1848,8 @@ bool ByteCodeExprGen::VisitCXXConstructExpr(
 
 // Immediately call the destructor if we have to.
 if (DiscardResult) {
+  if (!this->emitRecordDestruction(getRecord(E->getType(
+return false;
   if (!this->emitPopPtr(E))
 return false;
 }

diff  --git a/clang/test/AST/Interp/records.cpp 
b/clang/test/AST/Interp/records.cpp
index 62f1f1d6e426c3..7cc5987e0a958f 100644
--- a/clang/test/AST/Interp/records.cpp
+++ b/clang/test/AST/Interp/records.cpp
@@ -335,9 +335,9 @@ namespace InitializerTemporaries {
   };
 
   constexpr int f() {
-S{}; // ref-note {{in call to 'S{}.~S()'}}
-/// FIXME: Wrong source location below.
-return 12; // expected-note {{in call to '&S{}->~S()'}}
+S{}; // ref-note {{in call to 'S{}.~S()'}} \
+ // expected-note {{in call to '&S{}->~S()'}}
+return 12;
   }
   static_assert(f() == 12); // both-error {{not an integral constant 
expression}} \
 // both-note {{in call to 'f()'}}
@@ -604,9 +604,9 @@ namespace Destructors {
 }
   };
   constexpr int testS() {
-S{}; // ref-note {{in call to 'S{}.~S()'}}
-return 1; // expected-note {{in call to '&S{}->~S()'}}
-  // FIXME: ^ Wrong line
+S{}; // ref-note {{in call to 'S{}.~S()'}} \
+ // expected-note {{in call to '&S{}->~S()'}}
+return 1;
   }
   static_assert(testS() == 1); // both-error {{not an integral constant 
expression}} \
// both-note {{in call to 'testS()'}}



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


[clang-tools-extra] Fix 'newline in constant' encoding issue in clangd sources (PR #78085)

2024-02-19 Thread via cfe-commits

atomictoquark wrote:

> I am not sure if this is a viable solution in the long term as LLVM don't 
> really use BOMs in the sources (a quick scan shows only 4 files with BOMs), 
> hence these changes can easily be overridden without someone noticing.
> 
> Any reason you can't configure MSVC to treat all of the LLVM sources as UTF8 ?

On Windows with chinese env,the vs cmd console's default page code is 
936(GBK),this makes the problem.if edit file 
"llvm-project\llvm\cmake\modules\AddLLVM.cmake" line 37 ,add config like this
`elseif(MSVC)
  list(APPEND LLVM_COMPILE_DEFINITIONS _HAS_EXCEPTIONS=0)
  list(APPEND LLVM_COMPILE_FLAGS "/EHs-c-")
  list(APPEND LLVM_COMPILE_FLAGS "/utf-8")`
will solve this problem completely.
It's been a busy day,just for this problem...

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


[clang] [clang][analyzer] Simplify code of StreamChecker (NFC). (PR #82228)

2024-02-19 Thread via cfe-commits

llvmbot wrote:




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

Author: Balázs Kéri (balazske)


Changes

Continuation of commit 42b5037, apply changes to the remaining functions.
Code for function `fflush` was not changed, because it is more special compared 
to the others.

---

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


1 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp (+112-233) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index 354217c1e52922..82296e0b83649b 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -265,6 +265,11 @@ struct StreamOperationEvaluator {
SVB.makeIntVal(Val, CE->getCallReturnType(ACtx)));
   }
 
+  ProgramStateRef bindReturnValue(ProgramStateRef State, CheckerContext &C,
+  SVal Val) {
+return State->BindExpr(CE, C.getLocationContext(), Val);
+  }
+
   ProgramStateRef bindNullReturnValue(ProgramStateRef State,
   CheckerContext &C) {
 return State->BindExpr(CE, C.getLocationContext(),
@@ -280,6 +285,13 @@ struct StreamOperationEvaluator {
   return nullptr;
 return State->assume(*Cond, true);
   }
+
+  ProgramStatePair makeRetValAndAssumeDual(ProgramStateRef State,
+   CheckerContext &C) {
+DefinedSVal RetVal = makeRetVal(C, CE);
+State = State->BindExpr(CE, C.getLocationContext(), RetVal);
+return C.getConstraintManager().assumeDual(State, RetVal);
+  }
 };
 
 class StreamChecker : public Checker(Call.getOriginExpr());
-  if (!CE)
-return;
 
-  const StreamState *OldSS = State->get(StreamSym);
-  if (!OldSS)
+  ProgramStateRef State = C.getState();
+  StreamOperationEvaluator E(C);
+  if (!E.Init(Desc, Call, C, State))
 return;
 
-  assertStreamStateOpened(OldSS);
-
-  NonLoc RetVal = makeRetVal(C, CE).castAs();
-  State = State->BindExpr(CE, C.getLocationContext(), RetVal);
-  SValBuilder &SVB = C.getSValBuilder();
-  auto &ACtx = C.getASTContext();
-  auto Cond = SVB.evalBinOp(State, BO_GE, RetVal, SVB.makeZeroVal(ACtx.IntTy),
-SVB.getConditionType())
-  .getAs();
+  NonLoc RetVal = makeRetVal(C, E.CE).castAs();
+  State = State->BindExpr(E.CE, C.getLocationContext(), RetVal);
+  auto Cond =
+  E.SVB
+  .evalBinOp(State, BO_GE, RetVal, E.SVB.makeZeroVal(E.ACtx.IntTy),
+ E.SVB.getConditionType())
+  .getAs();
   if (!Cond)
 return;
   ProgramStateRef StateNotFailed, StateFailed;
   std::tie(StateNotFailed, StateFailed) = State->assume(*Cond);
 
   StateNotFailed =
-  StateNotFailed->set(StreamSym, StreamState::getOpened(Desc));
+  E.setStreamState(StateNotFailed, StreamState::getOpened(Desc));
   C.addTransition(StateNotFailed);
 
   // Add transition for the failed state. The resulting value of the file
   // position indicator for the stream is indeterminate.
-  StateFailed = StateFailed->set(
-  StreamSym, StreamState::getOpened(Desc, ErrorFError, true));
+  StateFailed = E.setStreamState(
+  StateFailed, StreamState::getOpened(Desc, ErrorFError, true));
   C.addTransition(StateFailed);
 }
 
 void StreamChecker::evalFscanf(const FnDescription *Desc, const CallEvent 
&Call,
CheckerContext &C) const {
-  ProgramStateRef State = C.getState();
   if (Call.getNumArgs() < 2)
 return;
-  SymbolRef StreamSym = getStreamArg(Desc, Call).getAsSymbol();
-  if (!StreamSym)
-return;
-
-  const CallExpr *CE = dyn_cast_or_null(Call.getOriginExpr());
-  if (!CE)
-return;
 
-  const StreamState *OldSS = State->get(StreamSym);
-  if (!OldSS)
+  ProgramStateRef State = C.getState();
+  StreamOperationEvaluator E(C);
+  if (!E.Init(Desc, Call, C, State))
 return;
 
-  assertStreamStateOpened(OldSS);
-
-  SValBuilder &SVB = C.getSValBuilder();
-  ASTContext &ACtx = C.getASTContext();
-
   // Add the success state.
   // In this context "success" means there is not an EOF or other read error
   // before any item is matched in 'fscanf'. But there may be match failure,
@@ -1007,19 +998,15 @@ void StreamChecker::evalFscanf(const FnDescription 
*Desc, const CallEvent &Call,
   // then EOF or read error happens. Now this case is handled like a "success"
   // case, and no error flags are set on the stream. This is probably not
   // accurate, and the POSIX documentation does not tell more.
-  if (OldSS->ErrorState != ErrorFEof) {
-NonLoc RetVal = makeRetVal(C, CE).castAs();
+  if (!E.isStreamEof()) {
+NonLoc RetVal = makeRetVal(C, E.CE).castAs();
 ProgramStateRef StateNotFailed =
-State->BindExpr(CE, C.getLocationContext(), RetVal);
-auto RetGeZero =
-SVB.evalBinOp(StateNotFail

[clang] [clang][analyzer] Simplify code of StreamChecker (NFC). (PR #82228)

2024-02-19 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Balázs Kéri (balazske)


Changes

Continuation of commit 42b5037, apply changes to the remaining functions.
Code for function `fflush` was not changed, because it is more special compared 
to the others.

---

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


1 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp (+112-233) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index 354217c1e52922..82296e0b83649b 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -265,6 +265,11 @@ struct StreamOperationEvaluator {
SVB.makeIntVal(Val, CE->getCallReturnType(ACtx)));
   }
 
+  ProgramStateRef bindReturnValue(ProgramStateRef State, CheckerContext &C,
+  SVal Val) {
+return State->BindExpr(CE, C.getLocationContext(), Val);
+  }
+
   ProgramStateRef bindNullReturnValue(ProgramStateRef State,
   CheckerContext &C) {
 return State->BindExpr(CE, C.getLocationContext(),
@@ -280,6 +285,13 @@ struct StreamOperationEvaluator {
   return nullptr;
 return State->assume(*Cond, true);
   }
+
+  ProgramStatePair makeRetValAndAssumeDual(ProgramStateRef State,
+   CheckerContext &C) {
+DefinedSVal RetVal = makeRetVal(C, CE);
+State = State->BindExpr(CE, C.getLocationContext(), RetVal);
+return C.getConstraintManager().assumeDual(State, RetVal);
+  }
 };
 
 class StreamChecker : public Checker(Call.getOriginExpr());
-  if (!CE)
-return;
 
-  const StreamState *OldSS = State->get(StreamSym);
-  if (!OldSS)
+  ProgramStateRef State = C.getState();
+  StreamOperationEvaluator E(C);
+  if (!E.Init(Desc, Call, C, State))
 return;
 
-  assertStreamStateOpened(OldSS);
-
-  NonLoc RetVal = makeRetVal(C, CE).castAs();
-  State = State->BindExpr(CE, C.getLocationContext(), RetVal);
-  SValBuilder &SVB = C.getSValBuilder();
-  auto &ACtx = C.getASTContext();
-  auto Cond = SVB.evalBinOp(State, BO_GE, RetVal, SVB.makeZeroVal(ACtx.IntTy),
-SVB.getConditionType())
-  .getAs();
+  NonLoc RetVal = makeRetVal(C, E.CE).castAs();
+  State = State->BindExpr(E.CE, C.getLocationContext(), RetVal);
+  auto Cond =
+  E.SVB
+  .evalBinOp(State, BO_GE, RetVal, E.SVB.makeZeroVal(E.ACtx.IntTy),
+ E.SVB.getConditionType())
+  .getAs();
   if (!Cond)
 return;
   ProgramStateRef StateNotFailed, StateFailed;
   std::tie(StateNotFailed, StateFailed) = State->assume(*Cond);
 
   StateNotFailed =
-  StateNotFailed->set(StreamSym, StreamState::getOpened(Desc));
+  E.setStreamState(StateNotFailed, StreamState::getOpened(Desc));
   C.addTransition(StateNotFailed);
 
   // Add transition for the failed state. The resulting value of the file
   // position indicator for the stream is indeterminate.
-  StateFailed = StateFailed->set(
-  StreamSym, StreamState::getOpened(Desc, ErrorFError, true));
+  StateFailed = E.setStreamState(
+  StateFailed, StreamState::getOpened(Desc, ErrorFError, true));
   C.addTransition(StateFailed);
 }
 
 void StreamChecker::evalFscanf(const FnDescription *Desc, const CallEvent 
&Call,
CheckerContext &C) const {
-  ProgramStateRef State = C.getState();
   if (Call.getNumArgs() < 2)
 return;
-  SymbolRef StreamSym = getStreamArg(Desc, Call).getAsSymbol();
-  if (!StreamSym)
-return;
-
-  const CallExpr *CE = dyn_cast_or_null(Call.getOriginExpr());
-  if (!CE)
-return;
 
-  const StreamState *OldSS = State->get(StreamSym);
-  if (!OldSS)
+  ProgramStateRef State = C.getState();
+  StreamOperationEvaluator E(C);
+  if (!E.Init(Desc, Call, C, State))
 return;
 
-  assertStreamStateOpened(OldSS);
-
-  SValBuilder &SVB = C.getSValBuilder();
-  ASTContext &ACtx = C.getASTContext();
-
   // Add the success state.
   // In this context "success" means there is not an EOF or other read error
   // before any item is matched in 'fscanf'. But there may be match failure,
@@ -1007,19 +998,15 @@ void StreamChecker::evalFscanf(const FnDescription 
*Desc, const CallEvent &Call,
   // then EOF or read error happens. Now this case is handled like a "success"
   // case, and no error flags are set on the stream. This is probably not
   // accurate, and the POSIX documentation does not tell more.
-  if (OldSS->ErrorState != ErrorFEof) {
-NonLoc RetVal = makeRetVal(C, CE).castAs();
+  if (!E.isStreamEof()) {
+NonLoc RetVal = makeRetVal(C, E.CE).castAs();
 ProgramStateRef StateNotFailed =
-State->BindExpr(CE, C.getLocationContext(), RetVal);
-auto RetGeZero =
-SVB.evalBinOp(StateNotFailed, BO_GE, RetVal,

[clang] 6d7de46 - [clang][Interp][NFC] Make Record field pointers const

2024-02-19 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-02-19T09:58:52+01:00
New Revision: 6d7de46155fece05ab5a44aedd573a811f4b208a

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

LOG: [clang][Interp][NFC] Make Record field pointers const

Added: 


Modified: 
clang/lib/AST/Interp/Record.h

Removed: 




diff  --git a/clang/lib/AST/Interp/Record.h b/clang/lib/AST/Interp/Record.h
index 284bb468d6af47..82294bb7dbbf96 100644
--- a/clang/lib/AST/Interp/Record.h
+++ b/clang/lib/AST/Interp/Record.h
@@ -80,7 +80,6 @@ class Record final {
 
   unsigned getNumFields() const { return Fields.size(); }
   const Field *getField(unsigned I) const { return &Fields[I]; }
-  Field *getField(unsigned I) { return &Fields[I]; }
 
   using const_base_iter = BaseList::const_iterator;
   llvm::iterator_range bases() const {
@@ -122,7 +121,7 @@ class Record final {
   /// Mapping from declarations to bases.
   llvm::DenseMap BaseMap;
   /// Mapping from field identifiers to descriptors.
-  llvm::DenseMap FieldMap;
+  llvm::DenseMap FieldMap;
   /// Mapping from declarations to virtual bases.
   llvm::DenseMap VirtualBaseMap;
   /// Size of the structure.



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


[clang] [clang][NFC] Regroup declarations in `Sema` (PR #82217)

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

tbaederr wrote:

> 11,427 additions, 11,178 deletions not shown because the diff is too large. 
> Please use a local Git client to view these changes.

Never seen that before, haha.

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


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

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

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

>From d169fddf3896bd334bc4776059258116ac08096a Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa 
Date: Sun, 18 Feb 2024 01:32:00 -0800
Subject: [PATCH] [alpha.webkit.UncountedCallArgsChecker] Ignore calls to WTF's
 container methods

This PR makes the checker ignore / skip calls to methods of Web Template 
Framework's container types
such as HashMap, HashSet, WeakHashSet, WeakHashMap, Vector, etc...
---
 .../WebKit/UncountedCallArgsChecker.cpp   |  32 
 .../WebKit/call-args-wtf-containers.cpp   | 146 ++
 2 files changed, 178 insertions(+)
 create mode 100644 
clang/test/Analysis/Checkers/WebKit/call-args-wtf-containers.cpp

diff --git 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp
index 17a64e1b1b8e04..9ed7f2a4e065d3 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp
@@ -25,6 +25,11 @@ using namespace ento;
 
 namespace {
 
+bool stringEndsWith(const std::string &str, const std::string &suffix) {
+  auto index = str.rfind(suffix);
+  return index != std::string::npos && str.size() - suffix.size() == index;
+}
+
 class UncountedCallArgsChecker
 : public Checker> {
   BugType Bug{this,
@@ -165,6 +170,9 @@ class UncountedCallArgsChecker
 if (!Callee)
   return false;
 
+if (isMethodOnWTFContainerType(Callee))
+  return true;
+
 auto overloadedOperatorType = Callee->getOverloadedOperator();
 if (overloadedOperatorType == OO_EqualEqual ||
 overloadedOperatorType == OO_ExclaimEqual ||
@@ -193,6 +201,30 @@ class UncountedCallArgsChecker
 return false;
   }
 
+  bool isMethodOnWTFContainerType(const FunctionDecl *Decl) const {
+if (!isa(Decl))
+  return false;
+auto *ClassDecl = Decl->getParent();
+if (!ClassDecl || !isa(ClassDecl))
+  return false;
+
+auto *NsDecl = ClassDecl->getParent();
+if (!NsDecl || !isa(NsDecl))
+  return false;
+
+auto methodName = safeGetName(Decl);
+auto clsName = safeGetName(ClassDecl);
+auto nsName = safeGetName(NsDecl);
+// FIXME: These should be implemented via attributes.
+return nsName == "WTF" &&
+   (methodName == "find" || methodName == "findIf" ||
+methodName == "reverseFind" || methodName == "reverseFindIf" ||
+methodName == "get" || methodName == "inlineGet" ||
+methodName == "contains" || methodName == "containsIf") &&
+   (stringEndsWith(clsName, "Vector") ||
+stringEndsWith(clsName, "Set") || stringEndsWith(clsName, "Map"));
+  }
+
   void reportBug(const Expr *CallArg, const ParmVarDecl *Param) const {
 assert(CallArg);
 
diff --git a/clang/test/Analysis/Checkers/WebKit/call-args-wtf-containers.cpp 
b/clang/test/Analysis/Checkers/WebKit/call-args-wtf-containers.cpp
new file mode 100644
index 00..0a63a789856127
--- /dev/null
+++ b/clang/test/Analysis/Checkers/WebKit/call-args-wtf-containers.cpp
@@ -0,0 +1,146 @@
+// RUN: %clang_analyze_cc1 
-analyzer-checker=alpha.webkit.UncountedCallArgsChecker -verify %s
+
+#include "mock-types.h"
+
+namespace WTF {
+
+  template 
+  class HashSet {
+  public:
+template  T* find(U&) const;
+template  bool contains(U&) const;
+unsigned size() { return m_size; }
+template  void add(U&) const;
+template  void remove(U&) const;
+
+  private:
+T* m_table { nullptr };
+unsigned m_size { 0 };
+  };
+
+  template 
+  class HashMap {
+  public:
+struct Item {
+  T key;
+  S value;
+};
+
+template  Item* find(U&) const;
+template  bool contains(U&) const;
+template  S* get(U&) const;
+template  S* inlineGet(U&) const;
+template  void add(U&) const;
+template  void remove(U&) const;
+
+  private:
+Item* m_table { nullptr };
+  };
+
+  template 
+  class WeakHashSet {
+  public:
+template  T* find(U&) const;
+template  bool contains(U&) const;
+template  void add(U&) const;
+template  void remove(U&) const;
+  };
+
+  template 
+  class Vector {
+  public:
+unsigned size() { return m_size; }
+T& at(unsigned i) { return m_buffer[i]; }
+T& operator[](unsigned i) { return m_buffer[i]; }
+template  unsigned find(U&);
+template  unsigned reverseFind(U&);
+template  bool contains(U&);
+template  unsigned findIf(const MatchFunction& 
match)
+{
+  for (unsigned i = 0; i < m_size; ++i) {
+if (match(at(i)))
+  return i;
+  }
+  return static_cast(-1);
+}
+template  unsigned reverseFindIf(const 
MatchFunction& match)
+{
+  for (unsigned i = 0; i < m_size; ++i) {
+if (match(at(m_size - i)))
+  return i;
+  }
+  return static_cast(-1);
+}
+template  bool containsIf(const MatchFunction& 
match)

[clang] [clang][StaticAnalyzer] Crash on loop unrolling mode (PR #82089)

2024-02-19 Thread via cfe-commits

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


[clang] [clang][StaticAnalyzer] Crash on loop unrolling mode (PR #82089)

2024-02-19 Thread via cfe-commits


@@ -226,6 +226,17 @@ static bool isPossiblyEscaped(ExplodedNode *N, const 
DeclRefExpr *DR) {
   return false;
   }
 }
+
+if (const SwitchStmt *SS = dyn_cast(S)) {
+  for (const Stmt *CB : dyn_cast(SS->getBody())->body()) {

NagyDonat wrote:

Be careful, this may cause a crash in standard-compliant but unusual code where 
the body of a `switch` statement is *not* a compound statement.

For example code like
```
switch (get_value()) case 0: case 1: run_foobar();
```
is completely valid; and here the body of the switch statement is a `CaseStmt` 
(which has another case statement as a child).

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


[clang] [clang][StaticAnalyzer] Crash on loop unrolling mode (PR #82089)

2024-02-19 Thread via cfe-commits

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


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


[clang] [clang][StaticAnalyzer] Crash on loop unrolling mode (PR #82089)

2024-02-19 Thread via cfe-commits


@@ -226,6 +226,17 @@ static bool isPossiblyEscaped(ExplodedNode *N, const 
DeclRefExpr *DR) {
   return false;
   }
 }
+
+if (const SwitchStmt *SS = dyn_cast(S)) {
+  for (const Stmt *CB : dyn_cast(SS->getBody())->body()) {
+for (const Decl *D : dyn_cast(CB)->decls()) {

NagyDonat wrote:

And this will crash on all statements that are within a switch and not 
`DeclStmt`s (because the `dyn_cast` returns a nullpointer and you're calling a 
method on it).

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


[clang] [clang-tools-extra] [clang-tidy] Add new check `modernize-use-designated-initializers` (PR #80541)

2024-02-19 Thread Danny Mösch via cfe-commits


@@ -0,0 +1,43 @@
+//===--- DesignatedInitializers.h ---*- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+///
+/// \file
+/// This file provides utilities for designated initializers.
+///
+//===--===//
+
+#include "clang/AST/Expr.h"
+#include "clang/Basic/SourceLocation.h"
+#include "llvm/ADT/DenseMap.h"
+
+namespace clang::tooling {
+
+/// Get designators describing the elements of a (syntactic) init list.
+///
+/// Given for example the type
+///
+/// struct S { int i, j; };
+///
+/// and the definition
+///
+/// S s{1, 2};
+///
+/// calling `getDesignators` for the initializer list expression `{1, 2}`
+/// would produce the map `{loc(1): ".i", loc(2): ".j"}`.
+///
+/// It does not produce designators for any explicitly-written nested lists,
+/// e.g. `{1, .j=2}` would only return `{loc(1): ".i"}`.
+///
+/// It also considers structs with fields of record types like
+/// `struct T { S s; };`. In this case, there would be designators of the
+/// form
+/// `.s.i` and `.s.j` in the returned map.
+llvm::DenseMap
+getDesignators(const clang::InitListExpr *Syn);

SimplyDanny wrote:

@PiotrZSL: One last confirmation please. 🙂 

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


[clang-tools-extra] [clangd] Do not offer extraction to variable for decl init expression (PR #69477)

2024-02-19 Thread kadir çetinkaya via cfe-commits


@@ -490,6 +491,13 @@ bool eligibleForExtraction(const SelectionTree::Node *N) {
 BO->getRHS() == OuterImplicit.ASTNode.get())
   return false;
   }
+  if (const auto *Decl = Parent->ASTNode.get()) {
+if (!Decl->isInitCapture() &&

kadircet wrote:

thanks for the example!

I guess one conceptual thing to note here is, clangd doesn't run it's 
refactorings on the exact selection user provided. instead it figures out an 
AST node that's "relevant" to this selection, and everything else is performed 
on that AST node, mostly independent of the selection.

So this approach is surely not always what the user means/wants, but let's us 
reason about the refactoring going on. For this case in particular, even if you 
said the refactoring is available for selection of `x = 1 + [[2 + 3]]` through 
these heuristics, clangd will still end up extracting the full RHS, because 
that's the AST node we associated with that selection.

Hence I'd actually lean towards not special casing it here, just to do the 
thing we're trying to prevent later on. Any particular reason why we should say 
extraction is available for such cases (and then still perform the extraction 
we're trying to avoid)?

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


[clang] [OpenMP][Clang] Handle unsupported inscan modifier for generic types (PR #79431)

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

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


[clang] [OpenMP][Clang] Handle unsupported inscan modifier for generic types (PR #79431)

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

animeshk-amd wrote:

Closing this PR because https://github.com/llvm/llvm-project/pull/82220 is 
fixing the issue #67002 

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


[clang] [clang][NFC] Regroup declarations in `Sema` (PR #82217)

2024-02-19 Thread via cfe-commits

cor3ntin wrote:

This is going to be rather disruptive on downstream projects.
At least we should wait until after the release of clang 18 to merge it, to 
avoid endless merge conflicts

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


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

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

https://github.com/rniwa created https://github.com/llvm/llvm-project/pull/82229

This PR makes alpha.webkit.UncountedLocalVarsChecker ignore raw references and 
pointers to a ref counted type which appears within "trival" statements. To do 
this, this PR extends TrivialFunctionAnalysis so that it can also analyze 
"triviality" of statements as well as that of functions Each Visit* function is 
now augmented with withCachedResult, which is responsible for looking up and 
updating the cache for each Visit* functions.

As this PR dramatically improves the false positive rate of the checker, it 
also deletes the code to ignore raw pointers and references within if and for 
statements.

>From 32d0e658edee46f99f8b9c9f09945079df8862df Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa 
Date: Mon, 19 Feb 2024 01:07:13 -0800
Subject: [PATCH] [alpha.webkit.UncountedLocalVarsChecker] Allow uncounted
 object references within trivial statements

This PR makes alpha.webkit.UncountedLocalVarsChecker ignore raw references and 
pointers to
a ref counted type which appears within "trival" statements. To do this, this 
PR extends
TrivialFunctionAnalysis so that it can also analyze "triviality" of statements 
as well as
that of functions Each Visit* function is now augmented with withCachedResult, 
which is
responsible for looking up and updating the cache for each Visit* functions.

As this PR dramatically improves the false positive rate of the checker, it 
also deletes
the code to ignore raw pointers and references within if and for statements.
---
 .../Checkers/WebKit/PtrTypesSemantics.cpp | 222 --
 .../Checkers/WebKit/PtrTypesSemantics.h   |  21 +-
 .../WebKit/UncountedLocalVarsChecker.cpp  |  69 +++---
 .../Analysis/Checkers/WebKit/mock-types.h |   2 +
 .../Checkers/WebKit/uncounted-local-vars.cpp  |  92 +++-
 5 files changed, 288 insertions(+), 118 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
index 6f236db0474079..9be1f10d097ab5 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
@@ -244,18 +244,42 @@ class TrivialFunctionAnalysisVisitor
 
   // Returns false if at least one child is non-trivial.
   bool VisitChildren(const Stmt *S) {
-for (const Stmt *Child : S->children()) {
-  if (Child && !Visit(Child))
+return withCachedResult(S, [&]() {
+  for (const Stmt *Child : S->children()) {
+if (Child && !Visit(Child))
+  return false;
+  }
+  return true;
+});
+  }
+  
+  bool VisitSubExpr(const Expr *E) {
+return withCachedResult(E, [&]() {
+  if (!Visit(E))
 return false;
-}
+  return true;
+});
+  }
 
-return true;
+  template 
+  bool withCachedResult(const StmtType *S, CheckFunction Function) {
+auto It = StatementCache.find(S);
+if (It != StatementCache.end())
+  return It->second;
+bool Result = Function();
+StatementCache[S] = Result;
+return Result;
   }
 
 public:
-  using CacheTy = TrivialFunctionAnalysis::CacheTy;
+  using FunctionCacheTy = TrivialFunctionAnalysis::FunctionCacheTy;
+  using StatementCacheTy = TrivialFunctionAnalysis::StatementCacheTy;
 
-  TrivialFunctionAnalysisVisitor(CacheTy &Cache) : Cache(Cache) {}
+  TrivialFunctionAnalysisVisitor(FunctionCacheTy &FunctionCache,
+ StatementCacheTy &StatementCache)
+: FunctionCache(FunctionCache)
+, StatementCache(StatementCache) {
+  }
 
   bool VisitStmt(const Stmt *S) {
 // All statements are non-trivial unless overriden later.
@@ -271,13 +295,21 @@ class TrivialFunctionAnalysisVisitor
 
   bool VisitReturnStmt(const ReturnStmt *RS) {
 // A return statement is allowed as long as the return value is trivial.
-if (auto *RV = RS->getRetValue())
-  return Visit(RV);
-return true;
+return withCachedResult(RS, [&]() {
+  if (auto *RV = RS->getRetValue())
+return Visit(RV);
+  return true;
+});
+  }
+
+  bool VisitCXXForRangeStmt(const CXXForRangeStmt *FS) {
+return VisitChildren(FS);
   }
 
   bool VisitDeclStmt(const DeclStmt *DS) { return VisitChildren(DS); }
   bool VisitDoStmt(const DoStmt *DS) { return VisitChildren(DS); }
+  bool VisitForStmt(const ForStmt *FS) { return VisitChildren(FS); }
+  bool VisitWhileStmt(const WhileStmt *WS) { return VisitChildren(WS); }
   bool VisitIfStmt(const IfStmt *IS) { return VisitChildren(IS); }
   bool VisitSwitchStmt(const SwitchStmt *SS) { return VisitChildren(SS); }
   bool VisitCaseStmt(const CaseStmt *CS) { return VisitChildren(CS); }
@@ -285,17 +317,27 @@ class TrivialFunctionAnalysisVisitor
 
   bool VisitUnaryOperator(const UnaryOperator *UO) {
 // Operator '*' and '!' are allowed as long as the operand is trivial.
-if (UO->getOpcode() == UO_Deref || UO->getOpcode() == UO_AddrOf ||
-  

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

2024-02-19 Thread via cfe-commits

llvmbot wrote:




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

Author: Ryosuke Niwa (rniwa)


Changes

This PR makes alpha.webkit.UncountedLocalVarsChecker ignore raw references and 
pointers to a ref counted type which appears within "trival" statements. To do 
this, this PR extends TrivialFunctionAnalysis so that it can also analyze 
"triviality" of statements as well as that of functions Each Visit* function is 
now augmented with withCachedResult, which is responsible for looking up and 
updating the cache for each Visit* functions.

As this PR dramatically improves the false positive rate of the checker, it 
also deletes the code to ignore raw pointers and references within if and for 
statements.

---

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


5 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp 
(+152-70) 
- (modified) clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h 
(+17-4) 
- (modified) 
clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp (+31-38) 
- (modified) clang/test/Analysis/Checkers/WebKit/mock-types.h (+2) 
- (modified) clang/test/Analysis/Checkers/WebKit/uncounted-local-vars.cpp 
(+86-6) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
index 6f236db0474079..9be1f10d097ab5 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
@@ -244,18 +244,42 @@ class TrivialFunctionAnalysisVisitor
 
   // Returns false if at least one child is non-trivial.
   bool VisitChildren(const Stmt *S) {
-for (const Stmt *Child : S->children()) {
-  if (Child && !Visit(Child))
+return withCachedResult(S, [&]() {
+  for (const Stmt *Child : S->children()) {
+if (Child && !Visit(Child))
+  return false;
+  }
+  return true;
+});
+  }
+  
+  bool VisitSubExpr(const Expr *E) {
+return withCachedResult(E, [&]() {
+  if (!Visit(E))
 return false;
-}
+  return true;
+});
+  }
 
-return true;
+  template 
+  bool withCachedResult(const StmtType *S, CheckFunction Function) {
+auto It = StatementCache.find(S);
+if (It != StatementCache.end())
+  return It->second;
+bool Result = Function();
+StatementCache[S] = Result;
+return Result;
   }
 
 public:
-  using CacheTy = TrivialFunctionAnalysis::CacheTy;
+  using FunctionCacheTy = TrivialFunctionAnalysis::FunctionCacheTy;
+  using StatementCacheTy = TrivialFunctionAnalysis::StatementCacheTy;
 
-  TrivialFunctionAnalysisVisitor(CacheTy &Cache) : Cache(Cache) {}
+  TrivialFunctionAnalysisVisitor(FunctionCacheTy &FunctionCache,
+ StatementCacheTy &StatementCache)
+: FunctionCache(FunctionCache)
+, StatementCache(StatementCache) {
+  }
 
   bool VisitStmt(const Stmt *S) {
 // All statements are non-trivial unless overriden later.
@@ -271,13 +295,21 @@ class TrivialFunctionAnalysisVisitor
 
   bool VisitReturnStmt(const ReturnStmt *RS) {
 // A return statement is allowed as long as the return value is trivial.
-if (auto *RV = RS->getRetValue())
-  return Visit(RV);
-return true;
+return withCachedResult(RS, [&]() {
+  if (auto *RV = RS->getRetValue())
+return Visit(RV);
+  return true;
+});
+  }
+
+  bool VisitCXXForRangeStmt(const CXXForRangeStmt *FS) {
+return VisitChildren(FS);
   }
 
   bool VisitDeclStmt(const DeclStmt *DS) { return VisitChildren(DS); }
   bool VisitDoStmt(const DoStmt *DS) { return VisitChildren(DS); }
+  bool VisitForStmt(const ForStmt *FS) { return VisitChildren(FS); }
+  bool VisitWhileStmt(const WhileStmt *WS) { return VisitChildren(WS); }
   bool VisitIfStmt(const IfStmt *IS) { return VisitChildren(IS); }
   bool VisitSwitchStmt(const SwitchStmt *SS) { return VisitChildren(SS); }
   bool VisitCaseStmt(const CaseStmt *CS) { return VisitChildren(CS); }
@@ -285,17 +317,27 @@ class TrivialFunctionAnalysisVisitor
 
   bool VisitUnaryOperator(const UnaryOperator *UO) {
 // Operator '*' and '!' are allowed as long as the operand is trivial.
-if (UO->getOpcode() == UO_Deref || UO->getOpcode() == UO_AddrOf ||
-UO->getOpcode() == UO_LNot)
-  return Visit(UO->getSubExpr());
-
-// Other operators are non-trivial.
-return false;
+return withCachedResult(UO, [&]() {
+  auto op = UO->getOpcode();
+  if (op == UO_Deref || op == UO_AddrOf || op == UO_LNot)
+return Visit(UO->getSubExpr());
+  if (UO->isIncrementOp() || UO->isDecrementOp()) {
+if (auto *RefExpr = dyn_cast(UO->getSubExpr())) {
+  if (auto *Decl = dyn_cast(RefExpr->getDecl()))
+return Decl->isLocalVarDeclOrParm() &&
+   Decl->getType().isPODType(Decl->getASTContext());
+   

[clang] 0b34d7e - [clang][Interp] Fix calling static operators

2024-02-19 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-02-19T10:34:18+01:00
New Revision: 0b34d7e9e2915510088aeee5592a845edd62b8ba

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

LOG: [clang][Interp] Fix calling static operators

They don't have an instance pointer anywhere but get one passed
via their CallExpr.

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.cpp
clang/test/AST/Interp/cxx23.cpp
clang/test/SemaCXX/cxx23-static-callop-lambda-expression.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index a778c300fc33a0..4316596bb32a56 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -1716,6 +1716,9 @@ bool ByteCodeExprGen::VisitTypeTraitExpr(const 
TypeTraitExpr *E) {
 
 template 
 bool ByteCodeExprGen::VisitLambdaExpr(const LambdaExpr *E) {
+  if (DiscardResult)
+return true;
+
   assert(Initializing);
   const Record *R = P.getOrCreateRecord(E->getLambdaClass());
 
@@ -2824,6 +2827,20 @@ bool ByteCodeExprGen::VisitCallExpr(const 
CallExpr *E) {
 }
   }
 
+  auto Args = E->arguments();
+  // Calling a static operator will still
+  // pass the instance, but we don't need it.
+  // Discard it here.
+  if (isa(E)) {
+if (const auto *MD =
+dyn_cast_if_present(E->getDirectCallee());
+MD && MD->isStatic()) {
+  if (!this->discard(E->getArg(0)))
+return false;
+  Args = drop_begin(Args, 1);
+}
+  }
+
   // Add the (optional, implicit) This pointer.
   if (const auto *MC = dyn_cast(E)) {
 if (!this->visit(MC->getImplicitObjectArgument()))
@@ -2831,7 +2848,7 @@ bool ByteCodeExprGen::VisitCallExpr(const 
CallExpr *E) {
   }
 
   // Put arguments on the stack.
-  for (const auto *Arg : E->arguments()) {
+  for (const auto *Arg : Args) {
 if (!this->visit(Arg))
   return false;
   }

diff  --git a/clang/test/AST/Interp/cxx23.cpp b/clang/test/AST/Interp/cxx23.cpp
index a50a9b7183699a..f1df936a5abe74 100644
--- a/clang/test/AST/Interp/cxx23.cpp
+++ b/clang/test/AST/Interp/cxx23.cpp
@@ -1,7 +1,7 @@
-// RUN: %clang_cc1 -std=c++20 -fsyntax-only -fcxx-exceptions -verify=ref20 %s
-// RUN: %clang_cc1 -std=c++23 -fsyntax-only -fcxx-exceptions -verify=ref23 %s
-// RUN: %clang_cc1 -std=c++20 -fsyntax-only -fcxx-exceptions 
-verify=expected20 %s -fexperimental-new-constant-interpreter
-// RUN: %clang_cc1 -std=c++23 -fsyntax-only -fcxx-exceptions 
-verify=expected23 %s -fexperimental-new-constant-interpreter
+// RUN: %clang_cc1 -std=c++20 -fsyntax-only -fcxx-exceptions -verify=ref20,all 
%s
+// RUN: %clang_cc1 -std=c++23 -fsyntax-only -fcxx-exceptions -verify=ref23,all 
%s
+// RUN: %clang_cc1 -std=c++20 -fsyntax-only -fcxx-exceptions 
-verify=expected20,all %s -fexperimental-new-constant-interpreter
+// RUN: %clang_cc1 -std=c++23 -fsyntax-only -fcxx-exceptions 
-verify=expected23,all %s -fexperimental-new-constant-interpreter
 
 /// FIXME: The new interpreter is missing all the 'control flows through...' 
diagnostics.
 
@@ -123,3 +123,24 @@ namespace StaticLambdas {
   }
   static_assert(capture_constexpr());
 }
+
+namespace StaticOperators {
+  auto lstatic = []() static { return 3; };  // ref20-warning {{C++23 
extension}} \
+ // expected20-warning {{C++23 
extension}}
+  static_assert(lstatic() == 3, "");
+  constexpr int (*f2)(void) = lstatic;
+  static_assert(f2() == 3);
+
+  struct S1 {
+constexpr S1() { // all-error {{never produces a constant expression}}
+  throw; // all-note 2{{not valid in a constant expression}}
+}
+static constexpr int operator()() { return 3; } // ref20-warning {{C++23 
extension}} \
+// expected20-warning 
{{C++23 extension}}
+  };
+  static_assert(S1{}() == 3, ""); // all-error {{not an integral constant 
expression}} \
+  // all-note {{in call to}}
+
+
+
+}

diff  --git a/clang/test/SemaCXX/cxx23-static-callop-lambda-expression.cpp 
b/clang/test/SemaCXX/cxx23-static-callop-lambda-expression.cpp
index fab76ffc423a3b..2b89e7a3a71291 100644
--- a/clang/test/SemaCXX/cxx23-static-callop-lambda-expression.cpp
+++ b/clang/test/SemaCXX/cxx23-static-callop-lambda-expression.cpp
@@ -1,5 +1,5 @@
 // RUN: %clang_cc1 -std=c++23 -fsyntax-only -verify %s
-
+// RUN: %clang_cc1 -std=c++23 -fsyntax-only -verify %s 
-fexperimental-new-constant-interpreter
 
 namespace ns1 {
   auto lstatic = []() static { return 3; }; 



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


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

2024-02-19 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 ead0a9777f8ccb5c26d50d96bade6cd5b47f496b 
32d0e658edee46f99f8b9c9f09945079df8862df -- 
clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp 
clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h 
clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp 
clang/test/Analysis/Checkers/WebKit/mock-types.h 
clang/test/Analysis/Checkers/WebKit/uncounted-local-vars.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
index 9be1f10d09..16789bc3f0 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
@@ -252,7 +252,7 @@ class TrivialFunctionAnalysisVisitor
   return true;
 });
   }
-  
+
   bool VisitSubExpr(const Expr *E) {
 return withCachedResult(E, [&]() {
   if (!Visit(E))
@@ -277,9 +277,7 @@ public:
 
   TrivialFunctionAnalysisVisitor(FunctionCacheTy &FunctionCache,
  StatementCacheTy &StatementCache)
-: FunctionCache(FunctionCache)
-, StatementCache(StatementCache) {
-  }
+  : FunctionCache(FunctionCache), StatementCache(StatementCache) {}
 
   bool VisitStmt(const Stmt *S) {
 // All statements are non-trivial unless overriden later.
@@ -335,9 +333,8 @@ public:
 
   bool VisitBinaryOperator(const BinaryOperator *BO) {
 // Binary operators are trivial if their operands are trivial.
-return withCachedResult(BO, [&]() {
-  return Visit(BO->getLHS()) && Visit(BO->getRHS());
-});
+return withCachedResult(
+BO, [&]() { return Visit(BO->getLHS()) && Visit(BO->getRHS()); });
   }
 
   bool VisitConditionalOperator(const ConditionalOperator *CO) {
@@ -425,9 +422,8 @@ public:
   }
 
   // Recursively descend into the callee to confirm that it's trivial.
-  return TrivialFunctionAnalysis::isTrivialImpl(CE->getConstructor(),
-FunctionCache,
-StatementCache);
+  return TrivialFunctionAnalysis::isTrivialImpl(
+  CE->getConstructor(), FunctionCache, StatementCache);
 });
   }
 
diff --git 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp
index 547e7fc089..4068b472cc 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLocalVarsChecker.cpp
@@ -195,7 +195,7 @@ public:
   if (MaybeGuardian->isLocalVarDecl() &&
   (isRefCounted(MaybeGuardianArgCXXRecord) ||
isRefcountedStringsHack(MaybeGuardian)) &&
-   isGuardedScopeEmbeddedInGuardianScope(V, MaybeGuardian))
+  isGuardedScopeEmbeddedInGuardianScope(V, MaybeGuardian))
 return;
 }
   }

``




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


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

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

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

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

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

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

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

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

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

>From 5e365d2a873aafc17d4b03eb7fee10029ff2bea1 Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa 
Date: Sun, 18 Feb 2024 21:47:48 -0800
Subject: [PATCH] [Analyzer] Support RefAllowingPartiallyDestroyed and
 RefPtrAllowingPartiallyDestroyed

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

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

[clang] [clang][analyzer] Simplify code of StreamChecker (NFC). (PR #82228)

2024-02-19 Thread via cfe-commits

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

Seems to be a nice improvement, I'm happy to see this boilerplate removal and 
reducing the code length by 120 lines is impressive. (Disclaimer: I didn't do a 
line-by-line review of the changes, but I hope that testing etc. validates that 
the change is indeed NFC.)

However, please add "part 2" to the title line of the commit, because it is/was 
confusing to have two commits with identical titles that are very close to each 
other.

In general, the title line should be an identifier that's reasonable unique for 
the human readers (while the commit hash is the machine-readable exact 
identifier). It's completely fine if a commit title happens to be identical to 
a 10-year-old commit, but please try to avoid confusion between commits that 
might "appear" in the same context.

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


[clang] [lldb] Enable aarch64-amazon-linux triple (PR #82231)

2024-02-19 Thread Sébastien Stormacq via cfe-commits

https://github.com/sebsto created 
https://github.com/llvm/llvm-project/pull/82231

Add aarch64-amazon-linux triplet to allow compilation for Amazon Linux 2023 on 
Graviton CPU

This should address https://github.com/apple/llvm-project/issues/8227

Also submitted to downstream `apple/llvm-project` 
https://github.com/apple/llvm-project/pull/8228


error: too big or took too long to generate
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [lldb] Enable aarch64-amazon-linux triple (PR #82231)

2024-02-19 Thread via cfe-commits

github-actions[bot] wrote:



Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be
notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this 
page.

If this is not working for you, it is probably because you do not have write
permissions for the repository. In which case you can instead tag reviewers by
name in a comment by using `@` followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review
by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate
is once a week. Please remember that you are asking for valuable time from 
other developers.

If you have further questions, they may be answered by the [LLVM GitHub User 
Guide](https://llvm.org/docs/GitHub.html).

You can also ask questions in a comment on this PR, on the [LLVM 
Discord](https://discord.com/invite/xS7Z362) or on the 
[forums](https://discourse.llvm.org/).

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


[clang] [lldb] Enable aarch64-amazon-linux triple (PR #82231)

2024-02-19 Thread Sébastien Stormacq via cfe-commits

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


[clang-tools-extra] c310782 - [clang-tidy][readability-identifier-naming] Resolve symlinks for checking style for file (#81985)

2024-02-19 Thread via cfe-commits

Author: Dmitry Polukhin
Date: 2024-02-19T10:02:24Z
New Revision: c3107821aeeeb12a13e7a85f0e23b884c2881417

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

LOG: [clang-tidy][readability-identifier-naming] Resolve symlinks for checking 
style for file (#81985)

Summary:
Some build systems create symlinks in a temporary build directory for
headers in the source tree for isolation purposes. These symlinks
prevent `readability-identifier-naming` detecting issues and applying
fixes. Without this fix clang-tidy is checking .clang-tidy config file
in a temporary directory instead of source source location.

Test Plan: check-clang-tools

Added: 

clang-tools-extra/test/clang-tidy/checkers/readability/Inputs/identifier-naming/symlink/include/.clang-tidy

clang-tools-extra/test/clang-tidy/checkers/readability/Inputs/identifier-naming/symlink/include/test.h

clang-tools-extra/test/clang-tidy/checkers/readability/identifier-naming-symlink.cpp

Modified: 
clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
clang-tools-extra/docs/ReleaseNotes.rst

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
index 5db9e99ab23708..335c3de25b861b 100644
--- a/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/IdentifierNamingCheck.cpp
@@ -1408,13 +1408,16 @@ const IdentifierNamingCheck::FileStyle &
 IdentifierNamingCheck::getStyleForFile(StringRef FileName) const {
   if (!GetConfigPerFile)
 return *MainFileStyle;
-  StringRef Parent = llvm::sys::path::parent_path(FileName);
+
+  SmallString<128> RealFileName;
+  llvm::sys::fs::real_path(FileName, RealFileName);
+  StringRef Parent = llvm::sys::path::parent_path(RealFileName);
   auto Iter = NamingStylesCache.find(Parent);
   if (Iter != NamingStylesCache.end())
 return Iter->getValue();
 
   llvm::StringRef CheckName = getID();
-  ClangTidyOptions Options = Context->getOptionsForFile(FileName);
+  ClangTidyOptions Options = Context->getOptionsForFile(RealFileName);
   if (Options.Checks && GlobList(*Options.Checks).contains(CheckName)) {
 auto It = NamingStylesCache.try_emplace(
 Parent,

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 58629426216ba8..a0b9fcfe0d7774 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -188,6 +188,10 @@ Changes in existing checks
   ` check to properly
   emit warnings for static data member with an in-class initializer.
 
+- Improved :doc:`readability-identifier-naming
+  ` check in 
`GetConfigPerFile`
+  mode by resolving symbolic links to header files.
+
 Removed checks
 ^^
 

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/readability/Inputs/identifier-naming/symlink/include/.clang-tidy
 
b/clang-tools-extra/test/clang-tidy/checkers/readability/Inputs/identifier-naming/symlink/include/.clang-tidy
new file mode 100644
index 00..296550f3aab1eb
--- /dev/null
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/readability/Inputs/identifier-naming/symlink/include/.clang-tidy
@@ -0,0 +1,4 @@
+Checks: readability-identifier-naming
+CheckOptions:
+  readability-identifier-naming.GlobalConstantCase: CamelCase
+  readability-identifier-naming.GlobalConstantPrefix: k

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/readability/Inputs/identifier-naming/symlink/include/test.h
 
b/clang-tools-extra/test/clang-tidy/checkers/readability/Inputs/identifier-naming/symlink/include/test.h
new file mode 100644
index 00..f3560e4e50b9ed
--- /dev/null
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/readability/Inputs/identifier-naming/symlink/include/test.h
@@ -0,0 +1 @@
+const int global_const = 5;

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/readability/identifier-naming-symlink.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/readability/identifier-naming-symlink.cpp
new file mode 100644
index 00..34dc340178dccc
--- /dev/null
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/readability/identifier-naming-symlink.cpp
@@ -0,0 +1,18 @@
+// Specify `-std=c++20` to run test only once becuase test expects changes
+// in the header file so it fails if runs multiple times with 
diff erent
+// `-std` flags as check_clang_tidy doesn by default.
+//
+// RUN: rm -rf %T/symlink
+// RUN: cp -r %S/Inputs/identifier-naming/symlink %T/symlink
+// RUN: mkdir -p %T/symlink/build
+// RUN: ln -s %T/symlink/include/test.h %T/symlink/build/test.h
+// RUN: %check_clang_tidy -std=c++20 %s readability-identifier-naming %t -- 
--header-filter="test.h" 
--confi

[clang-tools-extra] [clang-tidy][readability-identifier-naming] Resolve symlinks for checking style for file (PR #81985)

2024-02-19 Thread Dmitry Polukhin via cfe-commits

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


[clang] [clang][StaticAnalyzer] Crash on loop unrolling mode (PR #82089)

2024-02-19 Thread via cfe-commits


@@ -226,6 +226,17 @@ static bool isPossiblyEscaped(ExplodedNode *N, const 
DeclRefExpr *DR) {
   return false;
   }
 }
+
+if (const SwitchStmt *SS = dyn_cast(S)) {
+  for (const Stmt *CB : dyn_cast(SS->getBody())->body()) {

huang-me wrote:

I didn't think of this scenario, thanks for reminding me.

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


[clang] [clang][StaticAnalyzer] Crash on loop unrolling mode (PR #82089)

2024-02-19 Thread via cfe-commits


@@ -226,6 +226,17 @@ static bool isPossiblyEscaped(ExplodedNode *N, const 
DeclRefExpr *DR) {
   return false;
   }
 }
+
+if (const SwitchStmt *SS = dyn_cast(S)) {
+  for (const Stmt *CB : dyn_cast(SS->getBody())->body()) {
+for (const Decl *D : dyn_cast(CB)->decls()) {

huang-me wrote:

Oh, that's a stupid mistake. Thanks again.

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


[clang] a2535a5 - [clang][Interp] Remove assertion to fix comma operators...

2024-02-19 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-02-19T11:16:35+01:00
New Revision: a2535a5786894c54fb657f3b142ce88e8810e1ea

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

LOG: [clang][Interp] Remove assertion to fix comma operators...

... involving function pointers on the RHS. The conversion to
an RValue _can_ be requested, but we just ignore it.

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

Modified: 
clang/lib/AST/Interp/EvalEmitter.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/EvalEmitter.cpp 
b/clang/lib/AST/Interp/EvalEmitter.cpp
index 6715921ff1d975..d90cf1812bb774 100644
--- a/clang/lib/AST/Interp/EvalEmitter.cpp
+++ b/clang/lib/AST/Interp/EvalEmitter.cpp
@@ -152,7 +152,6 @@ template <> bool EvalEmitter::emitRet(const 
SourceInfo &Info) {
   if (!isActive())
 return true;
   // Function pointers cannot be converted to rvalues.
-  assert(!ConvertResultToRValue);
   EvalResult.setFunctionPointer(S.Stk.pop());
   return true;
 }

diff  --git a/clang/test/AST/Interp/comma.cpp b/clang/test/AST/Interp/comma.cpp
new file mode 100644
index 00..795958e90b0921
--- /dev/null
+++ b/clang/test/AST/Interp/comma.cpp
@@ -0,0 +1,10 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+// RUN: %clang_cc1 -fsyntax-only -verify %s 
-fexperimental-new-constant-interpreter
+// expected-no-diagnostics
+
+// PR6076
+void f();
+void (&g)() = (void(), f);
+
+int a[1];
+int (&b)[1] = (void(), a);



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


[clang] [clang] Implement `__is_layout_compatible` (PR #81506)

2024-02-19 Thread Vlad Serebrennikov via cfe-commits

https://github.com/Endilll updated 
https://github.com/llvm/llvm-project/pull/81506

>From 52b239153b2fc4f52e889ad2044daa6ed5cbc836 Mon Sep 17 00:00:00 2001
From: Vlad Serebrennikov 
Date: Mon, 12 Feb 2024 17:44:38 +0300
Subject: [PATCH 01/12] Initial implementation

---
 clang/include/clang/Basic/TokenKinds.def |  1 +
 clang/include/clang/Sema/Sema.h  |  2 +
 clang/lib/Parse/ParseDeclCXX.cpp |  1 +
 clang/lib/Parse/ParseExpr.cpp|  1 +
 clang/lib/Sema/SemaChecking.cpp  |  4 ++
 clang/lib/Sema/SemaExprCXX.cpp   |  3 +
 clang/test/SemaCXX/type-traits.cpp   | 77 
 7 files changed, 89 insertions(+)

diff --git a/clang/include/clang/Basic/TokenKinds.def 
b/clang/include/clang/Basic/TokenKinds.def
index 23817cde7a9354..112bfe8b23c2c0 100644
--- a/clang/include/clang/Basic/TokenKinds.def
+++ b/clang/include/clang/Basic/TokenKinds.def
@@ -520,6 +520,7 @@ TYPE_TRAIT_1(__is_trivially_copyable, IsTriviallyCopyable, 
KEYCXX)
 TYPE_TRAIT_1(__is_union, IsUnion, KEYCXX)
 TYPE_TRAIT_1(__has_unique_object_representations,
  HasUniqueObjectRepresentations, KEYCXX)
+TYPE_TRAIT_2(__is_layout_compatible, IsLayoutCompatible, KEYCXX)
 
 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) KEYWORD(__##Trait, KEYCXX)
 #include "clang/Basic/TransformTypeTraits.def"
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 851560f759f0e4..ddeba328749653 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -14040,6 +14040,8 @@ class Sema final {
   bool SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum);
 
 public:
+  bool SemaIsLayoutCompatible(QualType T1, QualType T2);
+  
   // Used by C++ template instantiation.
   ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
   ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
diff --git a/clang/lib/Parse/ParseDeclCXX.cpp b/clang/lib/Parse/ParseDeclCXX.cpp
index 79928ddb5af599..c9360981c1c1e4 100644
--- a/clang/lib/Parse/ParseDeclCXX.cpp
+++ b/clang/lib/Parse/ParseDeclCXX.cpp
@@ -1717,6 +1717,7 @@ void Parser::ParseClassSpecifier(tok::TokenKind 
TagTokKind,
   tok::kw___is_fundamental,
   tok::kw___is_integral,
   tok::kw___is_interface_class,
+  tok::kw___is_layout_compatible,
   tok::kw___is_literal,
   tok::kw___is_lvalue_expr,
   tok::kw___is_lvalue_reference,
diff --git a/clang/lib/Parse/ParseExpr.cpp b/clang/lib/Parse/ParseExpr.cpp
index 52cebdb6f64bac..db21a7f1e9e368 100644
--- a/clang/lib/Parse/ParseExpr.cpp
+++ b/clang/lib/Parse/ParseExpr.cpp
@@ -1114,6 +1114,7 @@ ExprResult Parser::ParseCastExpression(CastParseKind 
ParseKind,
   REVERTIBLE_TYPE_TRAIT(__is_fundamental);
   REVERTIBLE_TYPE_TRAIT(__is_integral);
   REVERTIBLE_TYPE_TRAIT(__is_interface_class);
+  REVERTIBLE_TYPE_TRAIT(__is_layout_compatible);
   REVERTIBLE_TYPE_TRAIT(__is_literal);
   REVERTIBLE_TYPE_TRAIT(__is_lvalue_expr);
   REVERTIBLE_TYPE_TRAIT(__is_lvalue_reference);
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 71e6e7230fc455..8aa744873f3704 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -19150,6 +19150,10 @@ static bool isLayoutCompatible(ASTContext &C, QualType 
T1, QualType T2) {
   return false;
 }
 
+bool Sema::SemaIsLayoutCompatible(QualType T1, QualType T2) {
+  return isLayoutCompatible(getASTContext(), T1, T2);
+}
+
 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match //
 
 /// Given a type tag expression find the type tag itself.
diff --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp
index 246d2313e089f3..b279c367342fce 100644
--- a/clang/lib/Sema/SemaExprCXX.cpp
+++ b/clang/lib/Sema/SemaExprCXX.cpp
@@ -5922,6 +5922,9 @@ static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait 
BTT, QualType LhsT,
 
 llvm_unreachable("unhandled type trait");
 return false;
+  }
+  case BTT_IsLayoutCompatible: {
+return Self.SemaIsLayoutCompatible(LhsT, RhsT);
   }
 default: llvm_unreachable("not a BTT");
   }
diff --git a/clang/test/SemaCXX/type-traits.cpp 
b/clang/test/SemaCXX/type-traits.cpp
index 5659594577111e..f50bedc275359b 100644
--- a/clang/test/SemaCXX/type-traits.cpp
+++ b/clang/test/SemaCXX/type-traits.cpp
@@ -1558,6 +1558,83 @@ void is_standard_layout()
   int t71[F(__is_standard_layout(HasEmptyIndirectBaseAsSecondUnionMember))];
 }
 
+struct CStruct2 {
+  int one;
+  int two;
+};
+
+struct CEmptyStruct2 {};
+
+struct CppEmptyStruct2 : CStruct2 {};
+struct CppStructStandard2 : CEmptyStruct2 {
+  int three;
+  int four;
+};
+struct CppStructNonStandardByBase2 : CStruct2 {
+  int three;
+  int four;
+};
+struct CppStructNonStandardByVirt2 : CStruct2 {
+  virtual void method() {}
+};
+struct CppStructNonStandardByMemb2 : CStruct2 {
+  CppStructNonStandardByVirt member;
+};
+struct CppStructNonStandar

[clang] [clang][StaticAnalyzer] Crash on loop unrolling mode (PR #82089)

2024-02-19 Thread via cfe-commits

https://github.com/huang-me updated 
https://github.com/llvm/llvm-project/pull/82089

>From 2802ef4b9ed88da3cacb16ab7738907ee806 Mon Sep 17 00:00:00 2001
From: huang-me 
Date: Sat, 17 Feb 2024 10:43:48 +0800
Subject: [PATCH 1/2] Fix crash on StaticAnalyzer loop unrolling

---
 clang/lib/StaticAnalyzer/Core/LoopUnrolling.cpp | 11 +++
 1 file changed, 11 insertions(+)

diff --git a/clang/lib/StaticAnalyzer/Core/LoopUnrolling.cpp 
b/clang/lib/StaticAnalyzer/Core/LoopUnrolling.cpp
index a80352816be613..4001268bde6677 100644
--- a/clang/lib/StaticAnalyzer/Core/LoopUnrolling.cpp
+++ b/clang/lib/StaticAnalyzer/Core/LoopUnrolling.cpp
@@ -226,6 +226,17 @@ static bool isPossiblyEscaped(ExplodedNode *N, const 
DeclRefExpr *DR) {
   return false;
   }
 }
+
+if (const SwitchStmt *SS = dyn_cast(S)) {
+  for (const Stmt *CB : dyn_cast(SS->getBody())->body()) {
+for (const Decl *D : dyn_cast(CB)->decls()) {
+  // Once we reach the declaration of the VD we can return.
+  if (D->getCanonicalDecl() == VD)
+return false;
+}
+  }
+}
+
 // Check the usage of the pass-by-ref function calls and adress-of operator
 // on VD and reference initialized by VD.
 ASTContext &ASTCtx =

>From e9e195e4462da7f3ca2317096ddace6ce3e88d13 Mon Sep 17 00:00:00 2001
From: huang-me 
Date: Mon, 19 Feb 2024 18:17:27 +0800
Subject: [PATCH 2/2] Check if dynamic cast get pointer to valid elements

---
 clang/lib/StaticAnalyzer/Core/LoopUnrolling.cpp | 14 +-
 1 file changed, 9 insertions(+), 5 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Core/LoopUnrolling.cpp 
b/clang/lib/StaticAnalyzer/Core/LoopUnrolling.cpp
index 4001268bde6677..093e9bbf4ce5e0 100644
--- a/clang/lib/StaticAnalyzer/Core/LoopUnrolling.cpp
+++ b/clang/lib/StaticAnalyzer/Core/LoopUnrolling.cpp
@@ -228,11 +228,15 @@ static bool isPossiblyEscaped(ExplodedNode *N, const 
DeclRefExpr *DR) {
 }
 
 if (const SwitchStmt *SS = dyn_cast(S)) {
-  for (const Stmt *CB : dyn_cast(SS->getBody())->body()) {
-for (const Decl *D : dyn_cast(CB)->decls()) {
-  // Once we reach the declaration of the VD we can return.
-  if (D->getCanonicalDecl() == VD)
-return false;
+  if (const CompoundStmt *CST = dyn_cast(SS->getBody())) {
+for (const Stmt *CB : CST->body()) {
+  if (const DeclStmt *DST = dyn_cast(CB)) {
+for (const Decl *D : DST->decls()) {
+  // Once we reach the declaration of the VD we can return.
+  if (D->getCanonicalDecl() == VD)
+return false;
+}
+  }
 }
   }
 }

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


[clang] Enable aarch64-amazon-linux triple (PR #82232)

2024-02-19 Thread Sébastien Stormacq via cfe-commits

https://github.com/sebsto created 
https://github.com/llvm/llvm-project/pull/82232

Add aarch64-amazon-linux triplet to allow compilation for Amazon Linux 2023 on 
Graviton CPU

This should address https://github.com/apple/llvm-project/issues/8227

Also submitted to Apple's repo https://github.com/apple/llvm-project/pull/8228

From c6d774983c8e71074b17fe97fb7205a27b741354 Mon Sep 17 00:00:00 2001
From: Sebastien Stormacq 
Date: Mon, 19 Feb 2024 11:13:55 +0100
Subject: [PATCH] Enable aarch64-amazon-linux triple

---
 clang/lib/Driver/ToolChains/Gnu.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/Driver/ToolChains/Gnu.cpp 
b/clang/lib/Driver/ToolChains/Gnu.cpp
index a2526a2b903964..3aa870d4c4236d 100644
--- a/clang/lib/Driver/ToolChains/Gnu.cpp
+++ b/clang/lib/Driver/ToolChains/Gnu.cpp
@@ -2456,7 +2456,7 @@ void 
Generic_GCC::GCCInstallationDetector::AddDefaultGCCPrefixes(
   static const char *const AArch64LibDirs[] = {"/lib64", "/lib"};
   static const char *const AArch64Triples[] = {
   "aarch64-none-linux-gnu", "aarch64-linux-gnu", "aarch64-redhat-linux",
-  "aarch64-suse-linux"};
+  "aarch64-suse-linux", "aarch64-amazon-linux"};
   static const char *const AArch64beLibDirs[] = {"/lib"};
   static const char *const AArch64beTriples[] = {"aarch64_be-none-linux-gnu",
  "aarch64_be-linux-gnu"};

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


[clang] Enable aarch64-amazon-linux triple (PR #82232)

2024-02-19 Thread via cfe-commits

github-actions[bot] wrote:



Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be
notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this 
page.

If this is not working for you, it is probably because you do not have write
permissions for the repository. In which case you can instead tag reviewers by
name in a comment by using `@` followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review
by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate
is once a week. Please remember that you are asking for valuable time from 
other developers.

If you have further questions, they may be answered by the [LLVM GitHub User 
Guide](https://llvm.org/docs/GitHub.html).

You can also ask questions in a comment on this PR, on the [LLVM 
Discord](https://discord.com/invite/xS7Z362) or on the 
[forums](https://discourse.llvm.org/).

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


[clang] Enable aarch64-amazon-linux triple (PR #82232)

2024-02-19 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-driver

Author: Sébastien Stormacq (sebsto)


Changes

Add aarch64-amazon-linux triplet to allow compilation for Amazon Linux 2023 on 
Graviton CPU

This should address https://github.com/apple/llvm-project/issues/8227

Also submitted to Apple's repo https://github.com/apple/llvm-project/pull/8228

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


1 Files Affected:

- (modified) clang/lib/Driver/ToolChains/Gnu.cpp (+1-1) 


``diff
diff --git a/clang/lib/Driver/ToolChains/Gnu.cpp 
b/clang/lib/Driver/ToolChains/Gnu.cpp
index a2526a2b903964..3aa870d4c4236d 100644
--- a/clang/lib/Driver/ToolChains/Gnu.cpp
+++ b/clang/lib/Driver/ToolChains/Gnu.cpp
@@ -2456,7 +2456,7 @@ void 
Generic_GCC::GCCInstallationDetector::AddDefaultGCCPrefixes(
   static const char *const AArch64LibDirs[] = {"/lib64", "/lib"};
   static const char *const AArch64Triples[] = {
   "aarch64-none-linux-gnu", "aarch64-linux-gnu", "aarch64-redhat-linux",
-  "aarch64-suse-linux"};
+  "aarch64-suse-linux", "aarch64-amazon-linux"};
   static const char *const AArch64beLibDirs[] = {"/lib"};
   static const char *const AArch64beTriples[] = {"aarch64_be-none-linux-gnu",
  "aarch64_be-linux-gnu"};

``




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


[clang] [clang] Implement `__is_layout_compatible` (PR #81506)

2024-02-19 Thread A. Jiang via cfe-commits


@@ -1558,6 +1558,89 @@ void is_standard_layout()
   int t71[F(__is_standard_layout(HasEmptyIndirectBaseAsSecondUnionMember))];
 }
 
+struct CStruct2 {
+  int one;
+  int two;
+};
+
+struct CEmptyStruct2 {};
+
+struct CppEmptyStruct2 : CStruct2 {};
+struct CppStructStandard2 : CEmptyStruct2 {
+  int three;
+  int four;
+};
+struct CppStructNonStandardByBase2 : CStruct2 {
+  int three;
+  int four;
+};
+struct CppStructNonStandardByVirt2 : CStruct2 {
+  virtual void method() {}
+};
+struct CppStructNonStandardByMemb2 : CStruct2 {
+  CppStructNonStandardByVirt member;
+};
+struct CppStructNonStandardByProt2 : CStruct2 {
+  int five;
+protected:
+  int six;
+};
+struct CppStructNonStandardByVirtBase2 : virtual CStruct2 {
+};
+struct CppStructNonStandardBySameBase2 : CEmptyStruct2 {
+  CEmptyStruct member;
+};
+struct CppStructNonStandardBy2ndVirtBase2 : CEmptyStruct2 {
+  CEmptyStruct member;
+};
+
+struct CStructWithQualifiers {
+  const int one;
+  volatile int two;
+};
+
+struct CStructNoUniqueAddress {
+  int one;
+  [[no_unique_address]] int two;
+};
+
+struct CStructNoUniqueAddress2 {
+  int one;
+  [[no_unique_address]] int two;
+};
+
+struct CStructAlignment {
+  int one;
+  alignas(16) int two;
+};
+
+struct CStructIncomplete;
+
+void is_layout_compatible()
+{
+  static_assert(__is_layout_compatible(void, void), "");
+  static_assert(__is_layout_compatible(int, int), "");
+  static_assert(__is_layout_compatible(int[], int[]), "");
+  static_assert(__is_layout_compatible(int[2], int[2]), "");
+  static_assert(__is_layout_compatible(CStruct, CStruct2), "");
+  static_assert(__is_layout_compatible(CEmptyStruct, CEmptyStruct2), "");
+  static_assert(__is_layout_compatible(CppEmptyStruct, CppEmptyStruct2), "");
+  static_assert(__is_layout_compatible(CppStructStandard, CppStructStandard2), 
"");
+  static_assert(!__is_layout_compatible(CppStructNonStandardByBase, 
CppStructNonStandardByBase2), "");
+  static_assert(!__is_layout_compatible(CppStructNonStandardByVirt, 
CppStructNonStandardByVirt2), "");
+  static_assert(!__is_layout_compatible(CppStructNonStandardByMemb, 
CppStructNonStandardByMemb2), "");
+  static_assert(!__is_layout_compatible(CppStructNonStandardByProt, 
CppStructNonStandardByProt2), "");
+  static_assert(!__is_layout_compatible(CppStructNonStandardByVirtBase, 
CppStructNonStandardByVirtBase2), "");
+  static_assert(!__is_layout_compatible(CppStructNonStandardBySameBase, 
CppStructNonStandardBySameBase2), "");
+  static_assert(!__is_layout_compatible(CppStructNonStandardBy2ndVirtBase, 
CppStructNonStandardBy2ndVirtBase2), "");
+  static_assert(!__is_layout_compatible(CStruct, CStructWithQualifiers), ""); 
// FIXME: this is CWG1719
+  static_assert(__is_layout_compatible(CStruct, CStructNoUniqueAddress) == 
bool(__has_cpp_attribute(no_unique_address)), ""); // FIXME: this is CWG2759
+  static_assert(__is_layout_compatible(CStructNoUniqueAddress, 
CStructNoUniqueAddress2) == bool(__has_cpp_attribute(no_unique_address)), ""); 
// FIXME: this is CWG2759
+  static_assert(__is_layout_compatible(CStruct, CStructAlignment), "");
+  static_assert(__is_layout_compatible(CStructIncomplete, CStructIncomplete), 
"");
+  static_assert(!__is_layout_compatible(CStruct, CStructIncomplete), "");
+}

frederick-vs-ja wrote:

> * That an enumeration type and its underlying type are not layout compatible

This is possibly a defect 
(https://github.com/cplusplus/CWG/issues/39#issuecomment-1184791364, 
https://github.com/cplusplus/CWG/issues/95#issuecomment-1185260854), but no CWG 
issue is filed yet.

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


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

2024-02-19 Thread via cfe-commits

https://github.com/cor3ntin created 
https://github.com/llvm/llvm-project/pull/82234

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

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

Fixes #81697

>From 55eb380c43740d3ce6843f2ea5b4055b38104124 Mon Sep 17 00:00:00 2001
From: Corentin Jabot 
Date: Mon, 19 Feb 2024 11:36:00 +0100
Subject: [PATCH] [Clang] Fix assert when transforming a pack indexing type.

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

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

Fixes #81697
---
 clang/lib/Sema/TreeTransform.h |  4 +++-
 clang/test/SemaCXX/cxx2c-pack-indexing.cpp | 19 +++
 2 files changed, 22 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index a32a585531873a..964ddeefc5a088 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -6561,7 +6561,9 @@ 
TreeTransform::TransformPackIndexingType(TypeLocBuilder &TLB,
   return QualType();
 if (!ShouldExpand) {
   Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
-  QualType Pack = getDerived().TransformType(T);
+  // FIXME: should we keep TypeLoc for individual expansions in 
PackIndexingTypeLoc?
+  TypeSourceInfo* TI = SemaRef.getASTContext().getTrivialTypeSourceInfo(T, 
TL.getBeginLoc());
+  QualType Pack = getDerived().TransformType(TLB, TI->getTypeLoc());
   if (Pack.isNull())
 return QualType();
   if (NotYetExpanded) {
diff --git a/clang/test/SemaCXX/cxx2c-pack-indexing.cpp 
b/clang/test/SemaCXX/cxx2c-pack-indexing.cpp
index 625a56031598b7..e13635383b6ca6 100644
--- a/clang/test/SemaCXX/cxx2c-pack-indexing.cpp
+++ b/clang/test/SemaCXX/cxx2c-pack-indexing.cpp
@@ -135,3 +135,22 @@ using Splice = typename SpliceImpl::type;
 using type = Splice, IL<1, 2>>;
 static_assert(is_same>);
 }
+
+
+namespace GH81697 {
+
+template struct tuple {
+int __x0;
+};
+
+template
+Ts...[I]& get(tuple& t) {
+  return t.__x0;
+}
+
+void f() {
+  tuple x;
+  get<0>(x);
+}
+
+}

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


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

2024-02-19 Thread Jan Patrick Lehr via cfe-commits


@@ -102,6 +80,121 @@ function(add_entrypoint_library target_name)
 list(APPEND all_deps ${entrypoint_target})
   endforeach(dep)
   list(REMOVE_DUPLICATES all_deps)
+  set(${result} ${all_deps} PARENT_SCOPE)
+endfunction()
+
+# A rule to build a library from a collection of entrypoint objects and bundle
+# it into a GPU fatbinary. Usage is the same as 'add_entrypoint_library'.
+# Usage:
+# add_gpu_entrypoint_library(
+#   DEPENDS 
+# )
+function(add_gpu_entrypoint_library target_name)
+  cmake_parse_arguments(
+"ENTRYPOINT_LIBRARY"
+"" # No optional arguments
+"" # No single value arguments
+"DEPENDS" # Multi-value arguments
+${ARGN}
+  )
+  if(NOT ENTRYPOINT_LIBRARY_DEPENDS)
+message(FATAL_ERROR "'add_entrypoint_library' target requires a DEPENDS 
list "
+"of 'add_entrypoint_object' targets.")
+  endif()
+
+  get_fq_deps_list(fq_deps_list ${ENTRYPOINT_LIBRARY_DEPENDS})
+  get_all_object_file_deps(all_deps "${fq_deps_list}")
+
+  # The GPU 'libc' needs to be exported in a format that can be linked with
+  # offloading langauges like OpenMP or CUDA. This wraps every GPU object into 
a
+  # fat binary and adds them to a static library.
+  set(objects "")
+  foreach(dep IN LISTS all_deps)
+set(object 
$<$,${dep}>:$>)
+string(FIND ${dep} "." last_dot_loc REVERSE)
+math(EXPR name_loc "${last_dot_loc} + 1")
+string(SUBSTRING ${dep} ${name_loc} -1 name)
+if(LIBC_TARGET_ARCHITECTURE_IS_NVPTX)
+  set(prefix 
--image=arch=generic,triple=nvptx64-nvidia-cuda,feature=+ptx63)
+else()

jplehr wrote:

Other places do `elseif(LIBC_TARGET_ARCHITECTURE_IS_AMDGPU)`. Maybe here as 
well for consistency?

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


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

2024-02-19 Thread Jan Patrick Lehr via cfe-commits

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


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

2024-02-19 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: cor3ntin (cor3ntin)


Changes

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

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

Fixes #81697

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


2 Files Affected:

- (modified) clang/lib/Sema/TreeTransform.h (+3-1) 
- (modified) clang/test/SemaCXX/cxx2c-pack-indexing.cpp (+19) 


``diff
diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index a32a585531873a..964ddeefc5a088 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -6561,7 +6561,9 @@ 
TreeTransform::TransformPackIndexingType(TypeLocBuilder &TLB,
   return QualType();
 if (!ShouldExpand) {
   Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
-  QualType Pack = getDerived().TransformType(T);
+  // FIXME: should we keep TypeLoc for individual expansions in 
PackIndexingTypeLoc?
+  TypeSourceInfo* TI = SemaRef.getASTContext().getTrivialTypeSourceInfo(T, 
TL.getBeginLoc());
+  QualType Pack = getDerived().TransformType(TLB, TI->getTypeLoc());
   if (Pack.isNull())
 return QualType();
   if (NotYetExpanded) {
diff --git a/clang/test/SemaCXX/cxx2c-pack-indexing.cpp 
b/clang/test/SemaCXX/cxx2c-pack-indexing.cpp
index 625a56031598b7..e13635383b6ca6 100644
--- a/clang/test/SemaCXX/cxx2c-pack-indexing.cpp
+++ b/clang/test/SemaCXX/cxx2c-pack-indexing.cpp
@@ -135,3 +135,22 @@ using Splice = typename SpliceImpl::type;
 using type = Splice, IL<1, 2>>;
 static_assert(is_same>);
 }
+
+
+namespace GH81697 {
+
+template struct tuple {
+int __x0;
+};
+
+template
+Ts...[I]& get(tuple& t) {
+  return t.__x0;
+}
+
+void f() {
+  tuple x;
+  get<0>(x);
+}
+
+}

``




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


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

2024-02-19 Thread Jan Patrick Lehr via cfe-commits

https://github.com/jplehr commented:

I looked at the changes and from the little I understand CMake they seem ok.
I added one nit.

Maybe @saiislam can have a look as well.

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


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

2024-02-19 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 3496927edcd0685807351ba88a7e2cfb006e1c0d 
55eb380c43740d3ce6843f2ea5b4055b38104124 -- clang/lib/Sema/TreeTransform.h 
clang/test/SemaCXX/cxx2c-pack-indexing.cpp
``





View the diff from clang-format here.


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

``




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


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

2024-02-19 Thread via cfe-commits

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

>From 55eb380c43740d3ce6843f2ea5b4055b38104124 Mon Sep 17 00:00:00 2001
From: Corentin Jabot 
Date: Mon, 19 Feb 2024 11:36:00 +0100
Subject: [PATCH 1/2] [Clang] Fix assert when transforming a pack indexing
 type.

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

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

Fixes #81697
---
 clang/lib/Sema/TreeTransform.h |  4 +++-
 clang/test/SemaCXX/cxx2c-pack-indexing.cpp | 19 +++
 2 files changed, 22 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index a32a585531873a..964ddeefc5a088 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -6561,7 +6561,9 @@ 
TreeTransform::TransformPackIndexingType(TypeLocBuilder &TLB,
   return QualType();
 if (!ShouldExpand) {
   Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
-  QualType Pack = getDerived().TransformType(T);
+  // FIXME: should we keep TypeLoc for individual expansions in 
PackIndexingTypeLoc?
+  TypeSourceInfo* TI = SemaRef.getASTContext().getTrivialTypeSourceInfo(T, 
TL.getBeginLoc());
+  QualType Pack = getDerived().TransformType(TLB, TI->getTypeLoc());
   if (Pack.isNull())
 return QualType();
   if (NotYetExpanded) {
diff --git a/clang/test/SemaCXX/cxx2c-pack-indexing.cpp 
b/clang/test/SemaCXX/cxx2c-pack-indexing.cpp
index 625a56031598b7..e13635383b6ca6 100644
--- a/clang/test/SemaCXX/cxx2c-pack-indexing.cpp
+++ b/clang/test/SemaCXX/cxx2c-pack-indexing.cpp
@@ -135,3 +135,22 @@ using Splice = typename SpliceImpl::type;
 using type = Splice, IL<1, 2>>;
 static_assert(is_same>);
 }
+
+
+namespace GH81697 {
+
+template struct tuple {
+int __x0;
+};
+
+template
+Ts...[I]& get(tuple& t) {
+  return t.__x0;
+}
+
+void f() {
+  tuple x;
+  get<0>(x);
+}
+
+}

>From 579f41b6d37c9bf98a57994d382391616d97d014 Mon Sep 17 00:00:00 2001
From: Corentin Jabot 
Date: Mon, 19 Feb 2024 11:45:32 +0100
Subject: [PATCH 2/2] clang format

---
 clang/lib/Sema/TreeTransform.h | 6 --
 1 file changed, 4 insertions(+), 2 deletions(-)

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

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


[clang] 6b32ba6 - [clang][Interp][NFC] Make Record::BaseMap use const pointers

2024-02-19 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-02-19T11:52:13+01:00
New Revision: 6b32ba6129941b42d929366eb0477696d53ceb2b

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

LOG: [clang][Interp][NFC] Make Record::BaseMap use const pointers

Added: 


Modified: 
clang/lib/AST/Interp/Record.h

Removed: 




diff  --git a/clang/lib/AST/Interp/Record.h b/clang/lib/AST/Interp/Record.h
index 82294bb7dbbf96..a6bde01062531b 100644
--- a/clang/lib/AST/Interp/Record.h
+++ b/clang/lib/AST/Interp/Record.h
@@ -119,7 +119,7 @@ class Record final {
   VirtualBaseList VirtualBases;
 
   /// Mapping from declarations to bases.
-  llvm::DenseMap BaseMap;
+  llvm::DenseMap BaseMap;
   /// Mapping from field identifiers to descriptors.
   llvm::DenseMap FieldMap;
   /// Mapping from declarations to virtual bases.



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


[clang] eddf9cf - [clang][Interp] Fix failure to allocate local variables

2024-02-19 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-02-19T11:52:13+01:00
New Revision: eddf9cf38a116bcce016f147cab216fef98721ab

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

LOG: [clang][Interp] Fix failure to allocate local variables

We were incorrectly returning true when the allocateLocal() call
failed.

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.cpp
clang/test/AST/Interp/arrays.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 4316596bb32a56..e9a58289f6fc07 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -2749,10 +2749,9 @@ bool ByteCodeExprGen::visitVarDecl(const 
VarDecl *VD) {
 return this->emitSetLocal(*VarT, Offset, VD);
   }
 } else {
-  if (std::optional Offset = this->allocateLocal(VD)) {
-if (Init)
-  return this->visitLocalInitializer(Init, *Offset);
-  }
+  if (std::optional Offset = this->allocateLocal(VD))
+return !Init || this->visitLocalInitializer(Init, *Offset);
+  return false;
 }
 return true;
   }

diff  --git a/clang/test/AST/Interp/arrays.cpp 
b/clang/test/AST/Interp/arrays.cpp
index a9450d827f6be6..e1af2e80e3ad77 100644
--- a/clang/test/AST/Interp/arrays.cpp
+++ b/clang/test/AST/Interp/arrays.cpp
@@ -545,3 +545,22 @@ namespace LocalIndex {
 array[const_subscript] = 0;  // both-warning {{array index 3 is past the 
end of the array (that has type 'int[2]')}}
   }
 }
+
+namespace LocalVLA {
+  struct Foo {
+int x;
+Foo(int x) : x(x) {}
+  };
+  struct Elidable {
+Elidable();
+  };
+
+  void foo(int size) {
+Elidable elidableDynArray[size];
+#if __cplusplus >= 202002L
+ // both-note@-3 {{declared here}}
+ // both-warning@-3 {{variable length array}}
+ // both-note@-4 {{function parameter 'size' with unknown value}}
+#endif
+  }
+}



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


[clang] e488fe5 - [clang][Interp] Fix non-initializing MemberExprs

2024-02-19 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-02-19T11:57:01+01:00
New Revision: e488fe5a97ba8da9be31926c219932db92298f21

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

LOG: [clang][Interp] Fix non-initializing MemberExprs

We need to create a value for them, do that via visit()

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

Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index e9a58289f6fc07..e36a7a0c0a7175 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -1157,8 +1157,13 @@ bool ByteCodeExprGen::VisitMemberExpr(const 
MemberExpr *E) {
   if (DiscardResult)
 return this->discard(Base);
 
-  if (!this->delegate(Base))
-return false;
+  if (Initializing) {
+if (!this->delegate(Base))
+  return false;
+  } else {
+if (!this->visit(Base))
+  return false;
+  }
 
   // Base above gives us a pointer on the stack.
   // TODO: Implement non-FieldDecl members.

diff  --git a/clang/test/AST/Interp/cxx03.cpp b/clang/test/AST/Interp/cxx03.cpp
new file mode 100644
index 00..d30cbb2fd7a201
--- /dev/null
+++ b/clang/test/AST/Interp/cxx03.cpp
@@ -0,0 +1,12 @@
+// RUN: %clang_cc1 -std=c++03 -verify=expected,both %s 
-fexperimental-new-constant-interpreter
+// RUN: %clang_cc1 -std=c++03 -verify=ref,both %s
+
+namespace NonInitializingMemberExpr {
+  struct NonLit {
+NonLit() : value(0) {}
+int value;
+  };
+  __attribute__((require_constant_initialization)) const int &nl_subobj_ref = 
NonLit().value; // both-error {{variable does not have a constant initializer}} 
\
+   
   // both-note {{required by}} \
+   
   // both-note {{subexpression not valid}}
+}



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


[clang] [clang] support Wold-style-declaration (PR #78837)

2024-02-19 Thread via cfe-commits

SihangZhu wrote:

> ping

repeat:)

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


[clang] 21431e0 - [clang][Interp] Remove questionable initializer special case

2024-02-19 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-02-19T12:18:49+01:00
New Revision: 21431e0f94c95703bd76e9ec5d2f0b39b8509680

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

LOG: [clang][Interp] Remove questionable initializer special case

I'm not sure where this would be needed, but for the time being,
removing it fixes a problem.

Added: 


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

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index e36a7a0c0a7175..74ed436bdb544b 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -2473,17 +2473,6 @@ bool ByteCodeExprGen::dereferenceVar(
 }
   }
 
-  // If the declaration is a constant value, emit it here even
-  // though the declaration was not evaluated in the current scope.
-  // The access mode can only be read in this case.
-  if (!DiscardResult && AK == DerefKind::Read) {
-if (VD->hasLocalStorage() && VD->hasInit() && !VD->isConstexpr()) {
-  QualType VT = VD->getType();
-  if (VT.isConstQualified() && VT->isFundamentalType())
-return this->visit(VD->getInit());
-}
-  }
-
   // Value cannot be produced - try to emit pointer.
   return visit(LV) && Indirect(T);
 }

diff  --git a/clang/test/AST/Interp/functions.cpp 
b/clang/test/AST/Interp/functions.cpp
index bf582362460ebc..51269741eb9018 100644
--- a/clang/test/AST/Interp/functions.cpp
+++ b/clang/test/AST/Interp/functions.cpp
@@ -543,3 +543,12 @@ namespace StaticLocals {
 static_assert(m == 0, "");
   }
 }
+
+namespace Local {
+  /// We used to run into infinite recursin here because we were
+  /// trying to evaluate t's initializer while evaluating t's initializer.
+  int a() {
+const int t=t;
+return t;
+  }
+}



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


[clang-tools-extra] [clangd] SelectionTree marks nodes as complete only if children are complete (PR #82237)

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

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

This seems to be the semantics expected by ~all callers, and simplifies
upcoming patches extending extract-variable.


>From 517d60a66ecae616e7c4037980b61fb4162b0c29 Mon Sep 17 00:00:00 2001
From: Sam McCall 
Date: Mon, 19 Feb 2024 12:25:31 +0100
Subject: [PATCH] [clangd] SelectionTree marks nodes as complete only if
 children are complete

This seems to be the semantics expected by ~all callers, and simplifies
upcoming patches extending extract-variable.
---
 clang-tools-extra/clangd/unittests/SelectionTests.cpp | 1 +
 1 file changed, 1 insertion(+)

diff --git a/clang-tools-extra/clangd/unittests/SelectionTests.cpp 
b/clang-tools-extra/clangd/unittests/SelectionTests.cpp
index 754e8c287c5148..162428f8169158 100644
--- a/clang-tools-extra/clangd/unittests/SelectionTests.cpp
+++ b/clang-tools-extra/clangd/unittests/SelectionTests.cpp
@@ -688,6 +688,7 @@ TEST(SelectionTest, Selected) {
   )cpp",
   R"cpp( $C[[^$C[[int]] a^]]; )cpp",
   R"cpp( $C[[^$C[[int]] a = $C[[5]]^]]; )cpp",
+  R"cpp( int x = [[2 ^+ $C[[2]]^]]; )cpp",
   };
   for (const char *C : Cases) {
 Annotations Test(C);

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


[clang-tools-extra] [clangd] SelectionTree marks nodes as complete only if children are complete (PR #82237)

2024-02-19 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang-tools-extra

@llvm/pr-subscribers-clangd

Author: Sam McCall (sam-mccall)


Changes

This seems to be the semantics expected by ~all callers, and simplifies
upcoming patches extending extract-variable.


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


1 Files Affected:

- (modified) clang-tools-extra/clangd/unittests/SelectionTests.cpp (+1) 


``diff
diff --git a/clang-tools-extra/clangd/unittests/SelectionTests.cpp 
b/clang-tools-extra/clangd/unittests/SelectionTests.cpp
index 754e8c287c5148..162428f8169158 100644
--- a/clang-tools-extra/clangd/unittests/SelectionTests.cpp
+++ b/clang-tools-extra/clangd/unittests/SelectionTests.cpp
@@ -688,6 +688,7 @@ TEST(SelectionTest, Selected) {
   )cpp",
   R"cpp( $C[[^$C[[int]] a^]]; )cpp",
   R"cpp( $C[[^$C[[int]] a = $C[[5]]^]]; )cpp",
+  R"cpp( int x = [[2 ^+ $C[[2]]^]]; )cpp",
   };
   for (const char *C : Cases) {
 Annotations Test(C);

``




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


[clang] [clang][dataflow][NFC] Add a FIXME to handling of union initialization. (PR #82239)

2024-02-19 Thread via cfe-commits

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

We want to make it clear that the current behavior doesn't yet handle unions
properly.

>From eb81951622c11c2f23c8dde61eac6ad79fdd67cb Mon Sep 17 00:00:00 2001
From: Martin Braenne 
Date: Mon, 19 Feb 2024 11:48:47 +
Subject: [PATCH] [clang][dataflow][NFC] Add a FIXME to handling of union
 initialization.

We want to make it clear that the current behavior doesn't yet handle unions
properly.
---
 clang/lib/Analysis/FlowSensitive/Transfer.cpp | 1 +
 1 file changed, 1 insertion(+)

diff --git a/clang/lib/Analysis/FlowSensitive/Transfer.cpp 
b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
index 513f22d8aa0f9c..fe13e919bddcd8 100644
--- a/clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -664,6 +664,7 @@ class TransferVisitor : public 
ConstStmtVisitor {
 QualType Type = S->getType();
 
 if (Type->isUnionType()) {
+  // FIXME: Initialize unions properly.
   if (auto *Val = Env.createValue(Type))
 Env.setValue(*S, *Val);
   return;

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


[clang] [clang][dataflow][NFC] Add a FIXME to handling of union initialization. (PR #82239)

2024-02-19 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-analysis

Author: None (martinboehme)


Changes

We want to make it clear that the current behavior doesn't yet handle unions
properly.

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


1 Files Affected:

- (modified) clang/lib/Analysis/FlowSensitive/Transfer.cpp (+1) 


``diff
diff --git a/clang/lib/Analysis/FlowSensitive/Transfer.cpp 
b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
index 513f22d8aa0f9c..fe13e919bddcd8 100644
--- a/clang/lib/Analysis/FlowSensitive/Transfer.cpp
+++ b/clang/lib/Analysis/FlowSensitive/Transfer.cpp
@@ -664,6 +664,7 @@ class TransferVisitor : public 
ConstStmtVisitor {
 QualType Type = S->getType();
 
 if (Type->isUnionType()) {
+  // FIXME: Initialize unions properly.
   if (auto *Val = Env.createValue(Type))
 Env.setValue(*S, *Val);
   return;

``




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


[clang] [OpenMP][Clang] Enable inscan modifier for generic datatypes (PR #82220)

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

animeshk-amd wrote:

The older PR didn't need to be merged. I've closed that one. This PR is 
independent.

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


[clang] 19f6689 - [clang] Remove unused variable [NFC]

2024-02-19 Thread Mikael Holmen via cfe-commits

Author: Mikael Holmen
Date: 2024-02-19T13:03:17+01:00
New Revision: 19f6689f3bd330c631525a7409bc824d8dc95303

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

LOG: [clang] Remove unused variable [NFC]

Without the fix gcc warned like
 ../../clang/lib/Analysis/UnsafeBufferUsage.cpp:2203:26: warning: unused 
variable 'CArrTy' [-Wunused-variable]
  2203 |   } else if (const auto *CArrTy = Ctx.getAsConstantArrayType(
   |  ^~

Added: 


Modified: 
clang/lib/Analysis/UnsafeBufferUsage.cpp

Removed: 




diff  --git a/clang/lib/Analysis/UnsafeBufferUsage.cpp 
b/clang/lib/Analysis/UnsafeBufferUsage.cpp
index a11f224170d5a6..701f1ac852c256 100644
--- a/clang/lib/Analysis/UnsafeBufferUsage.cpp
+++ b/clang/lib/Analysis/UnsafeBufferUsage.cpp
@@ -2200,8 +2200,7 @@ FixVarInitializerWithSpan(const Expr *Init, ASTContext 
&Ctx,
   // Although the initializer is not allocating a buffer, the pointer
   // variable could still be used in buffer access operations.
   ExtentText = One;
-  } else if (const auto *CArrTy = Ctx.getAsConstantArrayType(
- Init->IgnoreImpCasts()->getType())) {
+  } else if (Ctx.getAsConstantArrayType(Init->IgnoreImpCasts()->getType())) {
 // std::span has a single parameter constructor for initialization with
 // constant size array. The size is auto-deduced as the constructor is a
 // function template. The correct fixit is empty - no changes should 
happen.



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


[clang] 48439bd - [clang][Interp] Handle rewritten binary operators

2024-02-19 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-02-19T13:05:56+01:00
New Revision: 48439bd7a79b117b3072f422fdf7e5599925ec72

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

LOG: [clang][Interp] Handle rewritten binary operators

Just delegate to the syntactic form.

Added: 


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

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 74ed436bdb544b..2fdc6f4f32bed9 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -2156,6 +2156,12 @@ bool 
ByteCodeExprGen::VisitConceptSpecializationExpr(
   return this->emitConstBool(E->isSatisfied(), E);
 }
 
+template 
+bool ByteCodeExprGen::VisitCXXRewrittenBinaryOperator(
+const CXXRewrittenBinaryOperator *E) {
+  return this->delegate(E->getSemanticForm());
+}
+
 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 abaf28ac7d447d..3ede86a6979eea 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.h
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -116,6 +116,7 @@ class ByteCodeExprGen : public 
ConstStmtVisitor, bool>,
   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
   bool VisitRequiresExpr(const RequiresExpr *E);
   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
+  bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E);
 
 protected:
   bool visitExpr(const Expr *E) override;

diff  --git a/clang/test/AST/Interp/cxx20.cpp b/clang/test/AST/Interp/cxx20.cpp
index 0fc5d977b59f4c..78c09661c6dd73 100644
--- a/clang/test/AST/Interp/cxx20.cpp
+++ b/clang/test/AST/Interp/cxx20.cpp
@@ -763,3 +763,16 @@ namespace IgnoredConstantExpr {
 ReferenceToNestedMembers j{0};
   } test_reference_to_nested_members;
 }
+
+namespace RewrittenBinaryOperators {
+  template 
+  struct Conv {
+constexpr operator T() const { return Val; }
+operator T() { return Val; }
+  };
+
+  struct X {
+constexpr const Conv operator<=>(X) { return {}; }
+  };
+  static_assert(X() < X(), "");
+}



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


[clang] [clang] Implement `__is_layout_compatible` (PR #81506)

2024-02-19 Thread Vlad Serebrennikov via cfe-commits

https://github.com/Endilll updated 
https://github.com/llvm/llvm-project/pull/81506

>From 52b239153b2fc4f52e889ad2044daa6ed5cbc836 Mon Sep 17 00:00:00 2001
From: Vlad Serebrennikov 
Date: Mon, 12 Feb 2024 17:44:38 +0300
Subject: [PATCH 01/13] Initial implementation

---
 clang/include/clang/Basic/TokenKinds.def |  1 +
 clang/include/clang/Sema/Sema.h  |  2 +
 clang/lib/Parse/ParseDeclCXX.cpp |  1 +
 clang/lib/Parse/ParseExpr.cpp|  1 +
 clang/lib/Sema/SemaChecking.cpp  |  4 ++
 clang/lib/Sema/SemaExprCXX.cpp   |  3 +
 clang/test/SemaCXX/type-traits.cpp   | 77 
 7 files changed, 89 insertions(+)

diff --git a/clang/include/clang/Basic/TokenKinds.def 
b/clang/include/clang/Basic/TokenKinds.def
index 23817cde7a9354..112bfe8b23c2c0 100644
--- a/clang/include/clang/Basic/TokenKinds.def
+++ b/clang/include/clang/Basic/TokenKinds.def
@@ -520,6 +520,7 @@ TYPE_TRAIT_1(__is_trivially_copyable, IsTriviallyCopyable, 
KEYCXX)
 TYPE_TRAIT_1(__is_union, IsUnion, KEYCXX)
 TYPE_TRAIT_1(__has_unique_object_representations,
  HasUniqueObjectRepresentations, KEYCXX)
+TYPE_TRAIT_2(__is_layout_compatible, IsLayoutCompatible, KEYCXX)
 
 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) KEYWORD(__##Trait, KEYCXX)
 #include "clang/Basic/TransformTypeTraits.def"
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 851560f759f0e4..ddeba328749653 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -14040,6 +14040,8 @@ class Sema final {
   bool SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum);
 
 public:
+  bool SemaIsLayoutCompatible(QualType T1, QualType T2);
+  
   // Used by C++ template instantiation.
   ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
   ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
diff --git a/clang/lib/Parse/ParseDeclCXX.cpp b/clang/lib/Parse/ParseDeclCXX.cpp
index 79928ddb5af599..c9360981c1c1e4 100644
--- a/clang/lib/Parse/ParseDeclCXX.cpp
+++ b/clang/lib/Parse/ParseDeclCXX.cpp
@@ -1717,6 +1717,7 @@ void Parser::ParseClassSpecifier(tok::TokenKind 
TagTokKind,
   tok::kw___is_fundamental,
   tok::kw___is_integral,
   tok::kw___is_interface_class,
+  tok::kw___is_layout_compatible,
   tok::kw___is_literal,
   tok::kw___is_lvalue_expr,
   tok::kw___is_lvalue_reference,
diff --git a/clang/lib/Parse/ParseExpr.cpp b/clang/lib/Parse/ParseExpr.cpp
index 52cebdb6f64bac..db21a7f1e9e368 100644
--- a/clang/lib/Parse/ParseExpr.cpp
+++ b/clang/lib/Parse/ParseExpr.cpp
@@ -1114,6 +1114,7 @@ ExprResult Parser::ParseCastExpression(CastParseKind 
ParseKind,
   REVERTIBLE_TYPE_TRAIT(__is_fundamental);
   REVERTIBLE_TYPE_TRAIT(__is_integral);
   REVERTIBLE_TYPE_TRAIT(__is_interface_class);
+  REVERTIBLE_TYPE_TRAIT(__is_layout_compatible);
   REVERTIBLE_TYPE_TRAIT(__is_literal);
   REVERTIBLE_TYPE_TRAIT(__is_lvalue_expr);
   REVERTIBLE_TYPE_TRAIT(__is_lvalue_reference);
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 71e6e7230fc455..8aa744873f3704 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -19150,6 +19150,10 @@ static bool isLayoutCompatible(ASTContext &C, QualType 
T1, QualType T2) {
   return false;
 }
 
+bool Sema::SemaIsLayoutCompatible(QualType T1, QualType T2) {
+  return isLayoutCompatible(getASTContext(), T1, T2);
+}
+
 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match //
 
 /// Given a type tag expression find the type tag itself.
diff --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp
index 246d2313e089f3..b279c367342fce 100644
--- a/clang/lib/Sema/SemaExprCXX.cpp
+++ b/clang/lib/Sema/SemaExprCXX.cpp
@@ -5922,6 +5922,9 @@ static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait 
BTT, QualType LhsT,
 
 llvm_unreachable("unhandled type trait");
 return false;
+  }
+  case BTT_IsLayoutCompatible: {
+return Self.SemaIsLayoutCompatible(LhsT, RhsT);
   }
 default: llvm_unreachable("not a BTT");
   }
diff --git a/clang/test/SemaCXX/type-traits.cpp 
b/clang/test/SemaCXX/type-traits.cpp
index 5659594577111e..f50bedc275359b 100644
--- a/clang/test/SemaCXX/type-traits.cpp
+++ b/clang/test/SemaCXX/type-traits.cpp
@@ -1558,6 +1558,83 @@ void is_standard_layout()
   int t71[F(__is_standard_layout(HasEmptyIndirectBaseAsSecondUnionMember))];
 }
 
+struct CStruct2 {
+  int one;
+  int two;
+};
+
+struct CEmptyStruct2 {};
+
+struct CppEmptyStruct2 : CStruct2 {};
+struct CppStructStandard2 : CEmptyStruct2 {
+  int three;
+  int four;
+};
+struct CppStructNonStandardByBase2 : CStruct2 {
+  int three;
+  int four;
+};
+struct CppStructNonStandardByVirt2 : CStruct2 {
+  virtual void method() {}
+};
+struct CppStructNonStandardByMemb2 : CStruct2 {
+  CppStructNonStandardByVirt member;
+};
+struct CppStructNonStandar

[clang] d022f32 - Revert "[ARM] __ARM_ARCH macro definition fix (#81493)"

2024-02-19 Thread Tomas Matheson via cfe-commits

Author: Tomas Matheson
Date: 2024-02-19T12:19:16Z
New Revision: d022f32c73c57b59a9121eba909f5034e89c628e

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

LOG: Revert "[ARM] __ARM_ARCH macro definition fix (#81493)"

This reverts commit 89c1bf1230e011f2f0e43554c278205fa1819de5.

This has been unimplemenented for a while, and GCC does not implement
it, therefore we need to consider whether we should just deprecate it
in the ACLE instead.

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Basic/Targets/AArch64.cpp
clang/lib/Basic/Targets/ARM.cpp
clang/lib/Basic/Targets/ARM.h
clang/test/Preprocessor/arm-target-features.c
llvm/include/llvm/TargetParser/ARMTargetParser.h
llvm/lib/TargetParser/ARMTargetParser.cpp
llvm/unittests/TargetParser/TargetParserTest.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 45ace4191592d3..649ad655905af2 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -292,8 +292,6 @@ X86 Support
 Arm and AArch64 Support
 ^^^
 
-- Fixed the incorrect definition of the __ARM_ARCH macro for architectures 
greater than or equal to v8.1.
-
 Android Support
 ^^^
 

diff  --git a/clang/lib/Basic/Targets/AArch64.cpp 
b/clang/lib/Basic/Targets/AArch64.cpp
index dd0218e6ebed81..68032961451d90 100644
--- a/clang/lib/Basic/Targets/AArch64.cpp
+++ b/clang/lib/Basic/Targets/AArch64.cpp
@@ -367,20 +367,8 @@ void AArch64TargetInfo::getTargetDefines(const LangOptions 
&Opts,
 
   // ACLE predefines. Many can only have one possible value on v8 AArch64.
   Builder.defineMacro("__ARM_ACLE", "200");
-
-  // __ARM_ARCH is defined as an integer value indicating the current ARM ISA.
-  // For ISAs up to and including v8, __ARM_ARCH is equal to the major version
-  // number. For ISAs from v8.1 onwards, __ARM_ARCH is scaled up to include the
-  // minor version number, e.g. for ARM architecture ARMvX.Y:
-  // __ARM_ARCH = X * 100 + Y.
-  if (ArchInfo->Version.getMajor() == 8 && ArchInfo->Version.getMinor() == 0)
-Builder.defineMacro("__ARM_ARCH",
-std::to_string(ArchInfo->Version.getMajor()));
-  else
-Builder.defineMacro("__ARM_ARCH",
-std::to_string(ArchInfo->Version.getMajor() * 100 +
-   ArchInfo->Version.getMinor().value()));
-
+  Builder.defineMacro("__ARM_ARCH",
+  std::to_string(ArchInfo->Version.getMajor()));
   Builder.defineMacro("__ARM_ARCH_PROFILE",
   std::string("'") + (char)ArchInfo->Profile + "'");
 

diff  --git a/clang/lib/Basic/Targets/ARM.cpp b/clang/lib/Basic/Targets/ARM.cpp
index cd7fb95259d9db..55b71557452fa0 100644
--- a/clang/lib/Basic/Targets/ARM.cpp
+++ b/clang/lib/Basic/Targets/ARM.cpp
@@ -130,7 +130,6 @@ void ARMTargetInfo::setArchInfo(llvm::ARM::ArchKind Kind) {
   SubArch = llvm::ARM::getSubArch(ArchKind);
   ArchProfile = llvm::ARM::parseArchProfile(SubArch);
   ArchVersion = llvm::ARM::parseArchVersion(SubArch);
-  ArchMinorVersion = llvm::ARM::parseArchMinorVersion(SubArch);
 
   // cache CPU related strings
   CPUAttr = getCPUAttr();
@@ -737,16 +736,9 @@ void ARMTargetInfo::getTargetDefines(const LangOptions 
&Opts,
   if (!CPUAttr.empty())
 Builder.defineMacro("__ARM_ARCH_" + CPUAttr + "__");
 
-  // __ARM_ARCH is defined as an integer value indicating the current ARM ISA.
-  // For ISAs up to and including v8, __ARM_ARCH is equal to the major version
-  // number. For ISAs from v8.1 onwards, __ARM_ARCH is scaled up to include the
-  // minor version number, e.g. for ARM architecture ARMvX.Y:
-  // __ARM_ARCH = X * 100 + Y.
-  if (ArchVersion >= 9 || ArchMinorVersion != 0)
-Builder.defineMacro("__ARM_ARCH",
-Twine(ArchVersion * 100 + ArchMinorVersion));
-  else
-Builder.defineMacro("__ARM_ARCH", Twine(ArchVersion));
+  // ACLE 6.4.1 ARM/Thumb instruction set architecture
+  // __ARM_ARCH is defined as an integer value indicating the current ARM ISA
+  Builder.defineMacro("__ARM_ARCH", Twine(ArchVersion));
 
   if (ArchVersion >= 8) {
 // ACLE 6.5.7 Crypto Extension

diff  --git a/clang/lib/Basic/Targets/ARM.h b/clang/lib/Basic/Targets/ARM.h
index df06e4d120637a..71322a094f5edb 100644
--- a/clang/lib/Basic/Targets/ARM.h
+++ b/clang/lib/Basic/Targets/ARM.h
@@ -60,7 +60,6 @@ class LLVM_LIBRARY_VISIBILITY ARMTargetInfo : public 
TargetInfo {
   llvm::ARM::ArchKind ArchKind = llvm::ARM::ArchKind::ARMV4T;
   llvm::ARM::ProfileKind ArchProfile;
   unsigned ArchVersion;
-  unsigned ArchMinorVersion;
 
   LLVM_PREFERRED_TYPE(FPUMode)
   unsigned FPU : 5;

diff  --git a/clang/test/Preprocessor/arm-target-features.c 
b/clang/test/Preprocessor/arm-target-

[clang] [clang] Implement `__is_layout_compatible` (PR #81506)

2024-02-19 Thread Vlad Serebrennikov via cfe-commits


@@ -1558,6 +1558,89 @@ void is_standard_layout()
   int t71[F(__is_standard_layout(HasEmptyIndirectBaseAsSecondUnionMember))];
 }
 
+struct CStruct2 {
+  int one;
+  int two;
+};
+
+struct CEmptyStruct2 {};
+
+struct CppEmptyStruct2 : CStruct2 {};
+struct CppStructStandard2 : CEmptyStruct2 {
+  int three;
+  int four;
+};
+struct CppStructNonStandardByBase2 : CStruct2 {
+  int three;
+  int four;
+};
+struct CppStructNonStandardByVirt2 : CStruct2 {
+  virtual void method() {}
+};
+struct CppStructNonStandardByMemb2 : CStruct2 {
+  CppStructNonStandardByVirt member;
+};
+struct CppStructNonStandardByProt2 : CStruct2 {
+  int five;
+protected:
+  int six;
+};
+struct CppStructNonStandardByVirtBase2 : virtual CStruct2 {
+};
+struct CppStructNonStandardBySameBase2 : CEmptyStruct2 {
+  CEmptyStruct member;
+};
+struct CppStructNonStandardBy2ndVirtBase2 : CEmptyStruct2 {
+  CEmptyStruct member;
+};
+
+struct CStructWithQualifiers {
+  const int one;
+  volatile int two;
+};
+
+struct CStructNoUniqueAddress {
+  int one;
+  [[no_unique_address]] int two;
+};
+
+struct CStructNoUniqueAddress2 {
+  int one;
+  [[no_unique_address]] int two;
+};
+
+struct CStructAlignment {
+  int one;
+  alignas(16) int two;
+};
+
+struct CStructIncomplete;
+
+void is_layout_compatible()
+{
+  static_assert(__is_layout_compatible(void, void), "");
+  static_assert(__is_layout_compatible(int, int), "");
+  static_assert(__is_layout_compatible(int[], int[]), "");
+  static_assert(__is_layout_compatible(int[2], int[2]), "");
+  static_assert(__is_layout_compatible(CStruct, CStruct2), "");
+  static_assert(__is_layout_compatible(CEmptyStruct, CEmptyStruct2), "");
+  static_assert(__is_layout_compatible(CppEmptyStruct, CppEmptyStruct2), "");
+  static_assert(__is_layout_compatible(CppStructStandard, CppStructStandard2), 
"");
+  static_assert(!__is_layout_compatible(CppStructNonStandardByBase, 
CppStructNonStandardByBase2), "");
+  static_assert(!__is_layout_compatible(CppStructNonStandardByVirt, 
CppStructNonStandardByVirt2), "");
+  static_assert(!__is_layout_compatible(CppStructNonStandardByMemb, 
CppStructNonStandardByMemb2), "");
+  static_assert(!__is_layout_compatible(CppStructNonStandardByProt, 
CppStructNonStandardByProt2), "");
+  static_assert(!__is_layout_compatible(CppStructNonStandardByVirtBase, 
CppStructNonStandardByVirtBase2), "");
+  static_assert(!__is_layout_compatible(CppStructNonStandardBySameBase, 
CppStructNonStandardBySameBase2), "");
+  static_assert(!__is_layout_compatible(CppStructNonStandardBy2ndVirtBase, 
CppStructNonStandardBy2ndVirtBase2), "");
+  static_assert(!__is_layout_compatible(CStruct, CStructWithQualifiers), ""); 
// FIXME: this is CWG1719
+  static_assert(__is_layout_compatible(CStruct, CStructNoUniqueAddress) == 
bool(__has_cpp_attribute(no_unique_address)), ""); // FIXME: this is CWG2759
+  static_assert(__is_layout_compatible(CStructNoUniqueAddress, 
CStructNoUniqueAddress2) == bool(__has_cpp_attribute(no_unique_address)), ""); 
// FIXME: this is CWG2759
+  static_assert(__is_layout_compatible(CStruct, CStructAlignment), "");
+  static_assert(__is_layout_compatible(CStructIncomplete, CStructIncomplete), 
"");
+  static_assert(!__is_layout_compatible(CStruct, CStructIncomplete), "");
+}

Endilll wrote:

Thank you for mentioning that! I left a comment around enum tests.

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


[clang] [clang] Implement `__is_layout_compatible` (PR #81506)

2024-02-19 Thread Vlad Serebrennikov via cfe-commits

https://github.com/Endilll updated 
https://github.com/llvm/llvm-project/pull/81506

>From 52b239153b2fc4f52e889ad2044daa6ed5cbc836 Mon Sep 17 00:00:00 2001
From: Vlad Serebrennikov 
Date: Mon, 12 Feb 2024 17:44:38 +0300
Subject: [PATCH 01/14] Initial implementation

---
 clang/include/clang/Basic/TokenKinds.def |  1 +
 clang/include/clang/Sema/Sema.h  |  2 +
 clang/lib/Parse/ParseDeclCXX.cpp |  1 +
 clang/lib/Parse/ParseExpr.cpp|  1 +
 clang/lib/Sema/SemaChecking.cpp  |  4 ++
 clang/lib/Sema/SemaExprCXX.cpp   |  3 +
 clang/test/SemaCXX/type-traits.cpp   | 77 
 7 files changed, 89 insertions(+)

diff --git a/clang/include/clang/Basic/TokenKinds.def 
b/clang/include/clang/Basic/TokenKinds.def
index 23817cde7a9354..112bfe8b23c2c0 100644
--- a/clang/include/clang/Basic/TokenKinds.def
+++ b/clang/include/clang/Basic/TokenKinds.def
@@ -520,6 +520,7 @@ TYPE_TRAIT_1(__is_trivially_copyable, IsTriviallyCopyable, 
KEYCXX)
 TYPE_TRAIT_1(__is_union, IsUnion, KEYCXX)
 TYPE_TRAIT_1(__has_unique_object_representations,
  HasUniqueObjectRepresentations, KEYCXX)
+TYPE_TRAIT_2(__is_layout_compatible, IsLayoutCompatible, KEYCXX)
 
 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) KEYWORD(__##Trait, KEYCXX)
 #include "clang/Basic/TransformTypeTraits.def"
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 851560f759f0e4..ddeba328749653 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -14040,6 +14040,8 @@ class Sema final {
   bool SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum);
 
 public:
+  bool SemaIsLayoutCompatible(QualType T1, QualType T2);
+  
   // Used by C++ template instantiation.
   ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
   ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
diff --git a/clang/lib/Parse/ParseDeclCXX.cpp b/clang/lib/Parse/ParseDeclCXX.cpp
index 79928ddb5af599..c9360981c1c1e4 100644
--- a/clang/lib/Parse/ParseDeclCXX.cpp
+++ b/clang/lib/Parse/ParseDeclCXX.cpp
@@ -1717,6 +1717,7 @@ void Parser::ParseClassSpecifier(tok::TokenKind 
TagTokKind,
   tok::kw___is_fundamental,
   tok::kw___is_integral,
   tok::kw___is_interface_class,
+  tok::kw___is_layout_compatible,
   tok::kw___is_literal,
   tok::kw___is_lvalue_expr,
   tok::kw___is_lvalue_reference,
diff --git a/clang/lib/Parse/ParseExpr.cpp b/clang/lib/Parse/ParseExpr.cpp
index 52cebdb6f64bac..db21a7f1e9e368 100644
--- a/clang/lib/Parse/ParseExpr.cpp
+++ b/clang/lib/Parse/ParseExpr.cpp
@@ -1114,6 +1114,7 @@ ExprResult Parser::ParseCastExpression(CastParseKind 
ParseKind,
   REVERTIBLE_TYPE_TRAIT(__is_fundamental);
   REVERTIBLE_TYPE_TRAIT(__is_integral);
   REVERTIBLE_TYPE_TRAIT(__is_interface_class);
+  REVERTIBLE_TYPE_TRAIT(__is_layout_compatible);
   REVERTIBLE_TYPE_TRAIT(__is_literal);
   REVERTIBLE_TYPE_TRAIT(__is_lvalue_expr);
   REVERTIBLE_TYPE_TRAIT(__is_lvalue_reference);
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 71e6e7230fc455..8aa744873f3704 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -19150,6 +19150,10 @@ static bool isLayoutCompatible(ASTContext &C, QualType 
T1, QualType T2) {
   return false;
 }
 
+bool Sema::SemaIsLayoutCompatible(QualType T1, QualType T2) {
+  return isLayoutCompatible(getASTContext(), T1, T2);
+}
+
 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match //
 
 /// Given a type tag expression find the type tag itself.
diff --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp
index 246d2313e089f3..b279c367342fce 100644
--- a/clang/lib/Sema/SemaExprCXX.cpp
+++ b/clang/lib/Sema/SemaExprCXX.cpp
@@ -5922,6 +5922,9 @@ static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait 
BTT, QualType LhsT,
 
 llvm_unreachable("unhandled type trait");
 return false;
+  }
+  case BTT_IsLayoutCompatible: {
+return Self.SemaIsLayoutCompatible(LhsT, RhsT);
   }
 default: llvm_unreachable("not a BTT");
   }
diff --git a/clang/test/SemaCXX/type-traits.cpp 
b/clang/test/SemaCXX/type-traits.cpp
index 5659594577111e..f50bedc275359b 100644
--- a/clang/test/SemaCXX/type-traits.cpp
+++ b/clang/test/SemaCXX/type-traits.cpp
@@ -1558,6 +1558,83 @@ void is_standard_layout()
   int t71[F(__is_standard_layout(HasEmptyIndirectBaseAsSecondUnionMember))];
 }
 
+struct CStruct2 {
+  int one;
+  int two;
+};
+
+struct CEmptyStruct2 {};
+
+struct CppEmptyStruct2 : CStruct2 {};
+struct CppStructStandard2 : CEmptyStruct2 {
+  int three;
+  int four;
+};
+struct CppStructNonStandardByBase2 : CStruct2 {
+  int three;
+  int four;
+};
+struct CppStructNonStandardByVirt2 : CStruct2 {
+  virtual void method() {}
+};
+struct CppStructNonStandardByMemb2 : CStruct2 {
+  CppStructNonStandardByVirt member;
+};
+struct CppStructNonStandar

[clang] [clang] Implement `__is_layout_compatible` (PR #81506)

2024-02-19 Thread Vlad Serebrennikov via cfe-commits


@@ -90,6 +90,12 @@ C++20 Feature Support
   behavior can use the flag '-Xclang -fno-skip-odr-check-in-gmf'.
   (`#79240 `_).
 
+- Implemented `__is_layout_compatible` intrinsic, which backs up
+  `P0466R5: Layout-compatibility and Pointer-interconvertibility Traits 
`_.
+  `CWG1719: Layout compatibility and cv-qualification revisited  
`_
+  and `CWG2759: [[no_unique_address] and common initial sequence 
`_
+  are not yet implemented.
+

Endilll wrote:

Done

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


[clang] [clang][StaticAnalyzer] Crash on loop unrolling mode (PR #82089)

2024-02-19 Thread via cfe-commits

NagyDonat wrote:

If I understand it correctly, your change doesn't handle declarations that are 
in inner statements, e.g. the variable "x" in the following code:
```cpp
switch (get_value()) {
case 42:
  do {
int x;
// ...
  } while (running);
//...
}
```
Is this compatible with the goals of your commit, or would the original crash 
remain in a situation like this?

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


[clang] [OpenMP][Clang] Enable inscan modifier for generic datatypes (PR #82220)

2024-02-19 Thread Alexey Bataev via cfe-commits

alexey-bataev wrote:

Add a test

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


[clang] [clang] Implement `__is_layout_compatible` (PR #81506)

2024-02-19 Thread Vlad Serebrennikov via cfe-commits

https://github.com/Endilll updated 
https://github.com/llvm/llvm-project/pull/81506

>From 52b239153b2fc4f52e889ad2044daa6ed5cbc836 Mon Sep 17 00:00:00 2001
From: Vlad Serebrennikov 
Date: Mon, 12 Feb 2024 17:44:38 +0300
Subject: [PATCH 01/15] Initial implementation

---
 clang/include/clang/Basic/TokenKinds.def |  1 +
 clang/include/clang/Sema/Sema.h  |  2 +
 clang/lib/Parse/ParseDeclCXX.cpp |  1 +
 clang/lib/Parse/ParseExpr.cpp|  1 +
 clang/lib/Sema/SemaChecking.cpp  |  4 ++
 clang/lib/Sema/SemaExprCXX.cpp   |  3 +
 clang/test/SemaCXX/type-traits.cpp   | 77 
 7 files changed, 89 insertions(+)

diff --git a/clang/include/clang/Basic/TokenKinds.def 
b/clang/include/clang/Basic/TokenKinds.def
index 23817cde7a9354..112bfe8b23c2c0 100644
--- a/clang/include/clang/Basic/TokenKinds.def
+++ b/clang/include/clang/Basic/TokenKinds.def
@@ -520,6 +520,7 @@ TYPE_TRAIT_1(__is_trivially_copyable, IsTriviallyCopyable, 
KEYCXX)
 TYPE_TRAIT_1(__is_union, IsUnion, KEYCXX)
 TYPE_TRAIT_1(__has_unique_object_representations,
  HasUniqueObjectRepresentations, KEYCXX)
+TYPE_TRAIT_2(__is_layout_compatible, IsLayoutCompatible, KEYCXX)
 
 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) KEYWORD(__##Trait, KEYCXX)
 #include "clang/Basic/TransformTypeTraits.def"
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 851560f759f0e4..ddeba328749653 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -14040,6 +14040,8 @@ class Sema final {
   bool SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum);
 
 public:
+  bool SemaIsLayoutCompatible(QualType T1, QualType T2);
+  
   // Used by C++ template instantiation.
   ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
   ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
diff --git a/clang/lib/Parse/ParseDeclCXX.cpp b/clang/lib/Parse/ParseDeclCXX.cpp
index 79928ddb5af599..c9360981c1c1e4 100644
--- a/clang/lib/Parse/ParseDeclCXX.cpp
+++ b/clang/lib/Parse/ParseDeclCXX.cpp
@@ -1717,6 +1717,7 @@ void Parser::ParseClassSpecifier(tok::TokenKind 
TagTokKind,
   tok::kw___is_fundamental,
   tok::kw___is_integral,
   tok::kw___is_interface_class,
+  tok::kw___is_layout_compatible,
   tok::kw___is_literal,
   tok::kw___is_lvalue_expr,
   tok::kw___is_lvalue_reference,
diff --git a/clang/lib/Parse/ParseExpr.cpp b/clang/lib/Parse/ParseExpr.cpp
index 52cebdb6f64bac..db21a7f1e9e368 100644
--- a/clang/lib/Parse/ParseExpr.cpp
+++ b/clang/lib/Parse/ParseExpr.cpp
@@ -1114,6 +1114,7 @@ ExprResult Parser::ParseCastExpression(CastParseKind 
ParseKind,
   REVERTIBLE_TYPE_TRAIT(__is_fundamental);
   REVERTIBLE_TYPE_TRAIT(__is_integral);
   REVERTIBLE_TYPE_TRAIT(__is_interface_class);
+  REVERTIBLE_TYPE_TRAIT(__is_layout_compatible);
   REVERTIBLE_TYPE_TRAIT(__is_literal);
   REVERTIBLE_TYPE_TRAIT(__is_lvalue_expr);
   REVERTIBLE_TYPE_TRAIT(__is_lvalue_reference);
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 71e6e7230fc455..8aa744873f3704 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -19150,6 +19150,10 @@ static bool isLayoutCompatible(ASTContext &C, QualType 
T1, QualType T2) {
   return false;
 }
 
+bool Sema::SemaIsLayoutCompatible(QualType T1, QualType T2) {
+  return isLayoutCompatible(getASTContext(), T1, T2);
+}
+
 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match //
 
 /// Given a type tag expression find the type tag itself.
diff --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp
index 246d2313e089f3..b279c367342fce 100644
--- a/clang/lib/Sema/SemaExprCXX.cpp
+++ b/clang/lib/Sema/SemaExprCXX.cpp
@@ -5922,6 +5922,9 @@ static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait 
BTT, QualType LhsT,
 
 llvm_unreachable("unhandled type trait");
 return false;
+  }
+  case BTT_IsLayoutCompatible: {
+return Self.SemaIsLayoutCompatible(LhsT, RhsT);
   }
 default: llvm_unreachable("not a BTT");
   }
diff --git a/clang/test/SemaCXX/type-traits.cpp 
b/clang/test/SemaCXX/type-traits.cpp
index 5659594577111e..f50bedc275359b 100644
--- a/clang/test/SemaCXX/type-traits.cpp
+++ b/clang/test/SemaCXX/type-traits.cpp
@@ -1558,6 +1558,83 @@ void is_standard_layout()
   int t71[F(__is_standard_layout(HasEmptyIndirectBaseAsSecondUnionMember))];
 }
 
+struct CStruct2 {
+  int one;
+  int two;
+};
+
+struct CEmptyStruct2 {};
+
+struct CppEmptyStruct2 : CStruct2 {};
+struct CppStructStandard2 : CEmptyStruct2 {
+  int three;
+  int four;
+};
+struct CppStructNonStandardByBase2 : CStruct2 {
+  int three;
+  int four;
+};
+struct CppStructNonStandardByVirt2 : CStruct2 {
+  virtual void method() {}
+};
+struct CppStructNonStandardByMemb2 : CStruct2 {
+  CppStructNonStandardByVirt member;
+};
+struct CppStructNonStandar

[clang] [NVPTX][AMDGPU][CodeGen] Fix `local_space nullptr` handling for NVPTX and local/private `nullptr` value for AMDGPU. (PR #78759)

2024-02-19 Thread via cfe-commits

https://github.com/mmoadeli updated 
https://github.com/llvm/llvm-project/pull/78759

>From 717ad72ef5f1f318ef707cc829df8d4a9b46b131 Mon Sep 17 00:00:00 2001
From: m moadeli 
Date: Fri, 19 Jan 2024 18:42:24 +
Subject: [PATCH 1/2] - Address space cast of a `local_space` specialized
 `nullptr` into a generic space for the CUDA backend. - In the context of AMD
 GPU, assigns a NULL value of `~0` for the address spaces of `sycl_local` and
 `sycl_private`

---
 clang/lib/Basic/Targets/AMDGPU.h  |   6 +-
 clang/lib/CodeGen/Targets/NVPTX.cpp   |  18 +++
 .../CodeGenSYCL/address-space-conversions.cpp |   4 +
 .../amd-address-space-conversions.cpp | 128 ++
 .../cuda-address-space-conversions.cpp| 122 +
 5 files changed, 276 insertions(+), 2 deletions(-)
 create mode 100644 clang/test/CodeGenSYCL/amd-address-space-conversions.cpp
 create mode 100644 clang/test/CodeGenSYCL/cuda-address-space-conversions.cpp

diff --git a/clang/lib/Basic/Targets/AMDGPU.h b/clang/lib/Basic/Targets/AMDGPU.h
index e80589dde0ecb5..94d9ba93ed226f 100644
--- a/clang/lib/Basic/Targets/AMDGPU.h
+++ b/clang/lib/Basic/Targets/AMDGPU.h
@@ -414,8 +414,10 @@ class LLVM_LIBRARY_VISIBILITY AMDGPUTargetInfo final : 
public TargetInfo {
   // value ~0.
   uint64_t getNullPointerValue(LangAS AS) const override {
 // FIXME: Also should handle region.
-return (AS == LangAS::opencl_local || AS == LangAS::opencl_private)
-  ? ~0 : 0;
+return (AS == LangAS::opencl_local || AS == LangAS::opencl_private ||
+AS == LangAS::sycl_local || AS == LangAS::sycl_private)
+   ? ~0
+   : 0;
   }
 
   void setAuxTarget(const TargetInfo *Aux) override;
diff --git a/clang/lib/CodeGen/Targets/NVPTX.cpp 
b/clang/lib/CodeGen/Targets/NVPTX.cpp
index d0dc7c258a03a6..8718f1ecf3a7e0 100644
--- a/clang/lib/CodeGen/Targets/NVPTX.cpp
+++ b/clang/lib/CodeGen/Targets/NVPTX.cpp
@@ -47,6 +47,10 @@ class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
CodeGen::CodeGenModule &M) const override;
   bool shouldEmitStaticExternCAliases() const override;
 
+  llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
+ llvm::PointerType *T,
+ QualType QT) const override;
+
   llvm::Type *getCUDADeviceBuiltinSurfaceDeviceType() const override {
 // On the device side, surface reference is represented as an object handle
 // in 64-bit integer.
@@ -285,6 +289,20 @@ void 
NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::GlobalValue *GV,
 bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
   return false;
 }
+
+llvm::Constant *
+NVPTXTargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
+   llvm::PointerType *PT,
+   QualType QT) const {
+  auto &Ctx = CGM.getContext();
+  if (PT->getAddressSpace() != Ctx.getTargetAddressSpace(LangAS::opencl_local))
+return llvm::ConstantPointerNull::get(PT);
+
+  auto NPT = llvm::PointerType::get(
+  PT->getContext(), Ctx.getTargetAddressSpace(LangAS::opencl_generic));
+  return llvm::ConstantExpr::getAddrSpaceCast(
+  llvm::ConstantPointerNull::get(NPT), PT);
+}
 }
 
 void CodeGenModule::handleCUDALaunchBoundsAttr(llvm::Function *F,
diff --git a/clang/test/CodeGenSYCL/address-space-conversions.cpp 
b/clang/test/CodeGenSYCL/address-space-conversions.cpp
index 3933ad375412da..10a181318a174b 100644
--- a/clang/test/CodeGenSYCL/address-space-conversions.cpp
+++ b/clang/test/CodeGenSYCL/address-space-conversions.cpp
@@ -25,6 +25,10 @@ void usages() {
   __attribute__((opencl_local)) int *LOC;
   // CHECK-DAG: [[NoAS:%[a-zA-Z0-9]+]] = alloca ptr addrspace(4)
   // CHECK-DAG: [[NoAS]].ascast = addrspacecast ptr [[NoAS]] to ptr 
addrspace(4)
+  LOC = nullptr;
+  // CHECK-DAG: store ptr addrspace(3) null, ptr addrspace(4) [[LOC]].ascast, 
align 8
+  GLOB = nullptr;
+  // CHECK-DAG: store ptr addrspace(1) null, ptr addrspace(4) [[GLOB]].ascast, 
align 8
   int *NoAS;
   // CHECK-DAG: [[PRIV:%[a-zA-Z0-9]+]] = alloca ptr
   // CHECK-DAG: [[PRIV]].ascast = addrspacecast ptr [[PRIV]] to ptr 
addrspace(4)
diff --git a/clang/test/CodeGenSYCL/amd-address-space-conversions.cpp 
b/clang/test/CodeGenSYCL/amd-address-space-conversions.cpp
new file mode 100644
index 00..35da61cd8cbbe3
--- /dev/null
+++ b/clang/test/CodeGenSYCL/amd-address-space-conversions.cpp
@@ -0,0 +1,128 @@
+// RUN: %clang_cc1 -triple amdgcn-amd-amdhsa -fsycl-is-device 
-disable-llvm-passes -emit-llvm %s -o - | FileCheck %s
+void bar(int &Data) {}
+// CHECK-DAG: define dso_local void @[[RAW_REF:[a-zA-Z0-9_]+]](ptr noundef 
nonnull align 4 dereferenceable(4) %
+void bar2(int &Data) {}
+// CHECK-DAG: define dso_local void @[[RAW_REF2:[a-zA-Z0-9_]+]](ptr noundef 
nonnull align 4 dereferenceable(4) %
+void bar(__attribute__((opencl_local)) int &Data) {}
+// CHEC

[clang-tools-extra] [clangd] Do not offer extraction to variable for decl init expression (PR #69477)

2024-02-19 Thread Christian Kandeler via cfe-commits


@@ -490,6 +491,13 @@ bool eligibleForExtraction(const SelectionTree::Node *N) {
 BO->getRHS() == OuterImplicit.ASTNode.get())
   return false;
   }
+  if (const auto *Decl = Parent->ASTNode.get()) {
+if (!Decl->isInitCapture() &&

ckandeler wrote:

> For this case in particular, even if you said the refactoring is available 
> for selection of `x = 1 + [[2 + 3]]` through 
> these heuristics, clangd will still end up extracting the full RHS, because 
> that's the AST node we associated with that 
> selection.

I'm not sure I follow. In the example given above, invoking the tweak on the 
selection results in:
```
auto placeholder = 2 + 3;
int x = 1 + placeholder;
```
Which is exactly what I (the user) wanted. Am I misunderstanding something?

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


[clang-tools-extra] [clangd] Do not offer extraction to variable for decl init expression (PR #69477)

2024-02-19 Thread kadir çetinkaya via cfe-commits


@@ -490,6 +491,13 @@ bool eligibleForExtraction(const SelectionTree::Node *N) {
 BO->getRHS() == OuterImplicit.ASTNode.get())
   return false;
   }
+  if (const auto *Decl = Parent->ASTNode.get()) {
+if (!Decl->isInitCapture() &&

kadircet wrote:

sorry I don't think you can get that kind of behavior from a regular clangd. 
can you add a test case demonstrating how that comes to be?

here's a sample clangd test proving my point:
```
Content-Length: 1290

{"id":1,"jsonrpc":"2.0","method":"initialize","params":{"capabilities":{"textDocument":{"codeAction":{"codeActionLiteralSupport":{"codeActionKind":{"valueSet":["","quickfix","refactor","refactor.extract","refactor.inline","refactor.rewrite","source","source.organizeImports"]}}},"completion":{"completionItem":{"documentationFormat":["plaintext","markdown"]},"completionItemKind":{"valueSet":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]}},"documentSymbol":{"hierarchicalDocumentSymbolSupport":false,"labelSupport":false,"symbolKind":{"valueSet":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26]}},"hover":{"contentFormat":["plaintext","markdown"]},"signatureHelp":{"signatureInformation":{"documentationFormat":["plaintext","markdown"],"parameterInformation":{"labelOffsetSupport":true}}},"synchronization":{"didSave":true}},"workspace":{"applyEdit":true,"didChangeWatchedFiles":{"dynamicRegistration":true},"symbol":{"symbolKind":{"valueSet":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26]}},"workspaceEdit":{"documentChanges":true}}},"initializationOptions":{"clangdFileStatus":true},"processId":4179957,"rootPath":"/usr/local/google/home/kadircet/repos/tmp","rootUri":"file:///usr/local/google/home/kadircet/repos/tmp"}}Content-Length:
 52

{"jsonrpc":"2.0","method":"initialized","params":{}}Content-Length: 109

{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{"clangdFileStatus":true}}}Content-Length:
 193

{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{"textDocument":{"languageId":"cpp","text":"void
 foo() {\n  int x = 1 + 2 + 3;\n  
return;\n}\n","uri":"file:///tmp/a.cc","version":1}}}Content-Length: 217

{"id":2,"jsonrpc":"2.0","method":"textDocument/codeAction","params":{"context":{"diagnostics":[]},"range":{"end":{"character":18,"line":1},"start":{"character":14,"line":1}},"textDocument":{"uri":"file:///tmp/a.cc"}}}Content-Length:
 251

{"id":3,"jsonrpc":"2.0","method":"workspace/executeCommand","params":{"arguments":[{"file":"file:///tmp/a.cc","selection":{"end":{"character":18,"line":1},"start":{"character":14,"line":1}},"tweakID":"ExtractVariable"}],"command":"clangd.applyTweak"}}Content-Length:
 50

{"id":0,"jsonrpc":"2.0","result":{"applied":true}}Content-Length: 232

{"jsonrpc":"2.0","method":"textDocument/didChange","params":{"contentChanges":[{"text":"void
 foo() {\n  auto placeholder = 1 + 2 + 3;\n  int x = placeholder;\n  
return;\n}\n"}],"textDocument":{"uri":"file:///tmp/a.cc","version":2}}}Content-Length:
 115

{"jsonrpc":"2.0","method":"textDocument/didClose","params":{"textDocument":{"uri":"file:///tmp/a.cc","version":2}}}Content-Length:
 58

{"id":4,"jsonrpc":"2.0","method":"shutdown","params":null}Content-Length: 47

{"jsonrpc":"2.0","method":"exit","params":null}
```

some notable points here are:
- original file contents: `"text":"void foo() {\n  int x = 1 + 2 + 3;\n  
return;\n}\n"`
- code action request range: 
`,"range":{"end":{"character":18,"line":1},"start":{"character":14,"line":1}}`, 
namely `[[2 + 3]]`.
- code action response: `"contentChanges":[{"text":"void foo() {\n  auto 
placeholder = 1 + 2 + 3;\n  int x = placeholder;\n  return;\n}\n"}]`

that's my clangd version string: `clangd version 19.0.0git 
(g...@github.com:llvm/llvm-project.git 
7e3fb372b0e8899958ec7e9241797e7e136a7a23)`

you can feed in the json request above into clangd with ` /path/to/clangd 
-log=verbose -sync < /tmp/clangd_input.mirror`.

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


[clang-tools-extra] [clangd] Do not offer extraction to variable for decl init expression (PR #69477)

2024-02-19 Thread kadir çetinkaya via cfe-commits

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


[clang] [clang][StaticAnalyzer] Crash on loop unrolling mode (PR #82089)

2024-02-19 Thread via cfe-commits

huang-me wrote:

> If I understand it correctly, your change doesn't handle declarations that 
> are in inner statements, e.g. the variable "x" in the following code:
> 
> ```c++
> switch (get_value()) {
> case 42:
>   do {
> int x;
> // ...
>   } while (running);
> //...
> }
> ```
> 
> Is this compatible with the goals of your commit, or would the original crash 
> remain in a situation like this?

As far as I understand it, the declaration within the `CaseStmt` would be found 
before reaching `SwitchStmt` so I don't think we need to consider this 
situation.

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


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

2024-02-19 Thread Rajveer Singh Bharadwaj via cfe-commits

https://github.com/Rajveer100 created 
https://github.com/llvm/llvm-project/pull/82251

Resolves Issue #82249

As described in the issue, any deallocation function for a `class X` is a 
static member (even if not explicitly declared static).

>From 3ad4e85144739e16be13a4d5641b24d1a7e5b00b Mon Sep 17 00:00:00 2001
From: Rajveer 
Date: Mon, 19 Feb 2024 19:29:48 +0530
Subject: [PATCH] [clang] [SemaCXX] Disallow deducing "this" on operator `new`
 and `delete`

Resolves Issue #82249
---
 clang/lib/Sema/SemaDeclCXX.cpp | 4 +++-
 clang/test/SemaCXX/cxx2b-deducing-this.cpp | 4 
 2 files changed, 7 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index ab8a967b06a456..7a7b544d82b640 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -11391,7 +11391,9 @@ void Sema::CheckExplicitObjectMemberFunction(Declarator 
&D,
 << ExplicitObjectParam->getSourceRange();
   }
 
-  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static) {
+  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
+  (D.getContext() == clang::DeclaratorContext::Member &&
+   D.isStaticMember())) {
 Diag(ExplicitObjectParam->getBeginLoc(),
  diag::err_explicit_object_parameter_nonmember)
 << D.getSourceRange() << /*static=*/0 << IsLambda;
diff --git a/clang/test/SemaCXX/cxx2b-deducing-this.cpp 
b/clang/test/SemaCXX/cxx2b-deducing-this.cpp
index aab35828096a8e..530f8bf6af1b6b 100644
--- a/clang/test/SemaCXX/cxx2b-deducing-this.cpp
+++ b/clang/test/SemaCXX/cxx2b-deducing-this.cpp
@@ -16,6 +16,10 @@ struct S {
 static void f(this auto); // expected-error{{an explicit object parameter 
cannot appear in a static function}}
 virtual void f(this S); // expected-error{{an explicit object parameter 
cannot appear in a virtual function}}
 
+// new and delete are implicitly static
+void *operator new(this unsigned long); // expected-error{{an explicit 
object parameter cannot appear in a static function}}
+void operator delete(this void*); // expected-error{{an explicit object 
parameter cannot appear in a static function}}
+
 void g(this auto) const; // expected-error{{explicit object member 
function cannot have 'const' qualifier}}
 void h(this auto) &; // expected-error{{explicit object member function 
cannot have '&' qualifier}}
 void i(this auto) &&; // expected-error{{explicit object member function 
cannot have '&&' qualifier}}

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


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

2024-02-19 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Rajveer Singh Bharadwaj (Rajveer100)


Changes

Resolves Issue #82249

As described in the issue, any deallocation function for a `class X` is a 
static member (even if not explicitly declared static).

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


2 Files Affected:

- (modified) clang/lib/Sema/SemaDeclCXX.cpp (+3-1) 
- (modified) clang/test/SemaCXX/cxx2b-deducing-this.cpp (+4) 


``diff
diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index ab8a967b06a456..7a7b544d82b640 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -11391,7 +11391,9 @@ void Sema::CheckExplicitObjectMemberFunction(Declarator 
&D,
 << ExplicitObjectParam->getSourceRange();
   }
 
-  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static) {
+  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
+  (D.getContext() == clang::DeclaratorContext::Member &&
+   D.isStaticMember())) {
 Diag(ExplicitObjectParam->getBeginLoc(),
  diag::err_explicit_object_parameter_nonmember)
 << D.getSourceRange() << /*static=*/0 << IsLambda;
diff --git a/clang/test/SemaCXX/cxx2b-deducing-this.cpp 
b/clang/test/SemaCXX/cxx2b-deducing-this.cpp
index aab35828096a8e..530f8bf6af1b6b 100644
--- a/clang/test/SemaCXX/cxx2b-deducing-this.cpp
+++ b/clang/test/SemaCXX/cxx2b-deducing-this.cpp
@@ -16,6 +16,10 @@ struct S {
 static void f(this auto); // expected-error{{an explicit object parameter 
cannot appear in a static function}}
 virtual void f(this S); // expected-error{{an explicit object parameter 
cannot appear in a virtual function}}
 
+// new and delete are implicitly static
+void *operator new(this unsigned long); // expected-error{{an explicit 
object parameter cannot appear in a static function}}
+void operator delete(this void*); // expected-error{{an explicit object 
parameter cannot appear in a static function}}
+
 void g(this auto) const; // expected-error{{explicit object member 
function cannot have 'const' qualifier}}
 void h(this auto) &; // expected-error{{explicit object member function 
cannot have '&' qualifier}}
 void i(this auto) &&; // expected-error{{explicit object member function 
cannot have '&&' qualifier}}

``




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


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

2024-02-19 Thread via cfe-commits

cor3ntin wrote:

This change needs a release note.
Please add an entry to `clang/docs/ReleaseNotes.rst` in the section the most 
adapted to the change, and referencing any Github issue this change fixes. 
Thanks!

Besides that, I think the change makes sense, thanks!

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


[clang] [analyzer] Improve handling of unsigned values in ArrayBoundCheckerV2 (PR #81034)

2024-02-19 Thread via cfe-commits

NagyDonat wrote:

I did an open source evaluation of this commit and there are surprisingly many 
changes:

| Project | With this commit | Without this commit |
|-|-|--|
| memcached | 
[View](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=memcached_1.6.8_without_arrayboundv2_generalize_negative_vs_unsigned&newcheck=memcached_1.6.8_with_arrayboundv2_generalize_negative_vs_unsigned&diff-type=New&is-unique=on)
 | 
[View](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=memcached_1.6.8_without_arrayboundv2_generalize_negative_vs_unsigned&newcheck=memcached_1.6.8_with_arrayboundv2_generalize_negative_vs_unsigned&diff-type=Resolved&is-unique=on)
 |
| tmux | No new reports | No resolved reports |
| curl | 
[View](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=curl_curl-7_66_0_without_arrayboundv2_generalize_negative_vs_unsigned&newcheck=curl_curl-7_66_0_with_arrayboundv2_generalize_negative_vs_unsigned&diff-type=New&is-unique=on)
 | 
[View](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=curl_curl-7_66_0_without_arrayboundv2_generalize_negative_vs_unsigned&newcheck=curl_curl-7_66_0_with_arrayboundv2_generalize_negative_vs_unsigned&diff-type=Resolved&is-unique=on)
 |
| twin | 
[View](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=twin_v0.8.1_without_arrayboundv2_generalize_negative_vs_unsigned&newcheck=twin_v0.8.1_with_arrayboundv2_generalize_negative_vs_unsigned&diff-type=New&is-unique=on)
 | 
[View](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=twin_v0.8.1_without_arrayboundv2_generalize_negative_vs_unsigned&newcheck=twin_v0.8.1_with_arrayboundv2_generalize_negative_vs_unsigned&diff-type=Resolved&is-unique=on)
 |
| vim | 
[View](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=vim_v8.2.1920_without_arrayboundv2_generalize_negative_vs_unsigned&newcheck=vim_v8.2.1920_with_arrayboundv2_generalize_negative_vs_unsigned&diff-type=New&is-unique=on)
 | 
[View](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=vim_v8.2.1920_without_arrayboundv2_generalize_negative_vs_unsigned&newcheck=vim_v8.2.1920_with_arrayboundv2_generalize_negative_vs_unsigned&diff-type=Resolved&is-unique=on)
 |
| openssl | 
[View](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=openssl_openssl-3.0.0-alpha7_without_arrayboundv2_generalize_negative_vs_unsigned&newcheck=openssl_openssl-3.0.0-alpha7_with_arrayboundv2_generalize_negative_vs_unsigned&diff-type=New&is-unique=on)
 | 
[View](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=openssl_openssl-3.0.0-alpha7_without_arrayboundv2_generalize_negative_vs_unsigned&newcheck=openssl_openssl-3.0.0-alpha7_with_arrayboundv2_generalize_negative_vs_unsigned&diff-type=Resolved&is-unique=on)
 |
| sqlite | 
[View](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=sqlite_version-3.33.0_without_arrayboundv2_generalize_negative_vs_unsigned&newcheck=sqlite_version-3.33.0_with_arrayboundv2_generalize_negative_vs_unsigned&diff-type=New&is-unique=on)
 | 
[View](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=sqlite_version-3.33.0_without_arrayboundv2_generalize_negative_vs_unsigned&newcheck=sqlite_version-3.33.0_with_arrayboundv2_generalize_negative_vs_unsigned&diff-type=Resolved&is-unique=on)
 |
| ffmpeg | 
[View](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=ffmpeg_n4.3.1_without_arrayboundv2_generalize_negative_vs_unsigned&newcheck=ffmpeg_n4.3.1_with_arrayboundv2_generalize_negative_vs_unsigned&diff-type=New&is-unique=on)
 | 
[View](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=ffmpeg_n4.3.1_without_arrayboundv2_generalize_negative_vs_unsigned&newcheck=ffmpeg_n4.3.1_with_arrayboundv2_generalize_negative_vs_unsigned&diff-type=Resolved&is-unique=on)
 |
| postgres | 
[View](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=postgres_REL_13_0_without_arrayboundv2_generalize_negative_vs_unsigned&newcheck=postgres_REL_13_0_with_arrayboundv2_generalize_negative_vs_unsigned&diff-type=New&is-unique=on)
 | 
[View](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=postgres_REL_13_0_without_arrayboundv2_generalize_negative_vs_unsigned&newcheck=postgres_REL_13_0_with_arrayboundv2_generalize_negative_vs_unsigned&diff-type=Resolved&is-unique=on)
 |
| tinyxml2 | 
[View](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=tinyxml2_8.0.0_without_arrayboundv2_generalize_negative_vs_unsigned&newcheck=tinyxml2_8.0.0_with_arrayboundv2_generalize_negative_vs_unsigned&diff-type=New&is-unique=on)
 | 
[View](https://codechecker-demo.eastus.cloudapp.azure.com/Default/reports?run=tinyxml2_8.0.0_without_arrayboundv2_generalize_negative_vs_unsigned&newcheck=tinyxml2_8.0.0_with_arrayboundv2_generalize_negative_vs_unsigned&diff-type=R

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

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

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

>From 85f7218baa72307699b48bffa3da4005597ec719 Mon Sep 17 00:00:00 2001
From: Joseph Huber 
Date: Tue, 13 Feb 2024 21:08:02 -0600
Subject: [PATCH] [libc] Rework the GPU build to be a regular target

Summary:
This is a massive patch because it reworks the entire build and
everything that depends on it. This is not split up because various bots
would fail otherwise. I will attempt to describe the necessary changes
here.

This patch completely reworks how the GPU build is built and targeted.
Previously, we used a standard runtimes build and handled both NVPTX and
AMDGPU in a single build via multi-targeting. This added a lot of
divergence in the build system and prevented us from doing various
things like building for the CPU / GPU at the same time, or exporting
the startup libraries or running tests without a full rebuild.

The new appraoch is to handle the GPU builds as strict cross-compiling
runtimes. The first step required
https://github.com/llvm/llvm-project/pull/81557 to allow the `LIBC`
target to build for the GPU without touching the other targets. This
means that the GPU uses all the same handling as the other builds in
`libc`.

The new expected way to build the GPU libc is with
`LLVM_LIBC_RUNTIME_TARGETS=amdgcn-amd-amdhsa;nvptx64-nvidia-cuda`.

The second step was reworking how we generated the embedded GPU library
by moving it into the library install step. Where we previously had one
`libcgpu.a` we now have `libcgpu-amdgpu.a` and `libcgpu-nvptx.a`. This
patch includes the necessary clang / OpenMP changes to make that not
break the bots when this lands.

We unfortunately still require that the NVPTX target has an `internal`
target for tests. This is because the NVPTX target needs to do LTO for
the provided version (The offloading toolchain can handle it) but cannot
use it for the native toolchain which is used for making tests.

This approach is vastly suprerior in every way, allowing us to treat the
GPU as a standard cross-compiling target. We can now install the GPU
utilities to do things like use the offload tests and other fun things.

Depends on https://github.com/llvm/llvm-project/pull/81557
---
 clang/lib/Driver/ToolChains/CommonArgs.cpp|  37 +-
 clang/test/Driver/openmp-offload-gpu.c|  14 +-
 libc/CMakeLists.txt   |  20 +-
 .../cmake/modules/LLVMLibCArchitectures.cmake |  28 +-
 libc/cmake/modules/LLVMLibCCheckMPFR.cmake|   2 +-
 .../modules/LLVMLibCCompileOptionRules.cmake  | 104 ++
 libc/cmake/modules/LLVMLibCHeaderRules.cmake  |   2 +-
 libc/cmake/modules/LLVMLibCLibraryRules.cmake | 141 +--
 libc/cmake/modules/LLVMLibCObjectRules.cmake  | 348 --
 libc/cmake/modules/LLVMLibCTestRules.cmake|  67 ++--
 .../modules/prepare_libc_gpu_build.cmake  | 108 ++
 libc/include/CMakeLists.txt   |   6 +-
 libc/lib/CMakeLists.txt   |  42 ++-
 libc/src/__support/File/CMakeLists.txt|   2 +-
 libc/src/__support/GPU/CMakeLists.txt |   2 +-
 libc/src/__support/OSUtil/CMakeLists.txt  |   2 +-
 libc/src/__support/RPC/CMakeLists.txt |   2 +-
 libc/src/math/CMakeLists.txt  |  16 +-
 libc/src/math/gpu/vendor/CMakeLists.txt   |   1 -
 libc/src/stdio/CMakeLists.txt |   2 +-
 libc/src/stdlib/CMakeLists.txt|   4 +-
 libc/src/string/CMakeLists.txt|  12 +-
 libc/startup/gpu/CMakeLists.txt   |  35 +-
 libc/startup/gpu/amdgpu/CMakeLists.txt|  13 -
 libc/startup/gpu/nvptx/CMakeLists.txt |   9 -
 libc/test/CMakeLists.txt  |   6 +-
 libc/test/IntegrationTest/CMakeLists.txt  |  16 -
 libc/test/UnitTest/CMakeLists.txt |   6 +-
 libc/test/src/__support/CMakeLists.txt|  49 +--
 libc/test/src/__support/CPP/CMakeLists.txt|   2 +-
 libc/test/src/__support/File/CMakeLists.txt   |   2 +-
 libc/test/src/errno/CMakeLists.txt|   2 +-
 libc/test/src/math/CMakeLists.txt |  20 +-
 libc/test/src/math/smoke/CMakeLists.txt   |   8 +-
 libc/test/src/stdio/CMakeLists.txt|   2 +-
 libc/test/src/stdlib/CMakeLists.txt   |   6 +-
 libc/test/utils/UnitTest/CMakeLists.txt   |   2 +-
 libc/utils/CMakeLists.txt |   2 +-
 libc/utils/MPFRWrapper/CMakeLists.txt |   2 +-
 libc/utils/gpu/CMakeLists.txt |   4 +-
 libc/utils/gpu/loader/CMakeLists.txt  |  48 ++-
 libc/utils/gpu/loader/amdgpu/CMakeLists.txt   |   6 +-
 libc/utils/gpu/loader/nvptx/CMakeLists.txt|  10 +-
 libc/utils/gpu/server/CMakeLists.txt  |   9 +
 llvm/CMakeLists.txt   |   8 +
 llvm/cmake/modules/HandleLLVMOptions.cmake|   7 +
 llvm/runtimes/CMakeLists.txt  |  10 +-
 openmp/libomptarget/CMakeLists.txt|   9 +-
 .../plugins-nextgen/common/CMakeLists.txt |  

[clang-tools-extra] [clangd] Do not offer extraction to variable for decl init expression (PR #69477)

2024-02-19 Thread Christian Kandeler via cfe-commits


@@ -490,6 +491,13 @@ bool eligibleForExtraction(const SelectionTree::Node *N) {
 BO->getRHS() == OuterImplicit.ASTNode.get())
   return false;
   }
+  if (const auto *Decl = Parent->ASTNode.get()) {
+if (!Decl->isInitCapture() &&

ckandeler wrote:

> * "end":{"character":18,"

But that's [[2 + ]]3, no? I get an end character position of 19 with both Qt 
Creator and VSCode for the [[2 + 3]] selection.

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


[clang] [Driver] Remove dead -freroll-loops flag (PR #82254)

2024-02-19 Thread Nikita Popov via cfe-commits

https://github.com/nikic created https://github.com/llvm/llvm-project/pull/82254

Remove the `-freroll-loops` flag, which has not had any effect since the 
migration to the new pass manager. The underlying pass has been removed 
entirely in #80972 due to lack of maintenance and known bugs.

>From 9243af902d0fbb44009ac0c1a45fa05826a8d7f4 Mon Sep 17 00:00:00 2001
From: Nikita Popov 
Date: Mon, 19 Feb 2024 16:12:56 +0100
Subject: [PATCH] [Driver] Remove dead -freroll-loops flag

Remove the `-freroll-loops` flag, which has not had any effect
since the migration to the new pass manager. The underlying
pass has been removed entirely in #80972 due to lack of maintenance
and known bugs.
---
 clang/docs/ReleaseNotes.rst   | 2 ++
 clang/include/clang/Driver/Options.td | 4 
 clang/lib/Driver/ToolChains/Clang.cpp | 5 -
 clang/test/Driver/clang_f_opts.c  | 7 ---
 4 files changed, 2 insertions(+), 16 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 45ace4191592d3..3093e903410540 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -167,6 +167,8 @@ Modified Compiler Flags
 Removed Compiler Flags
 -
 
+- The ``-freroll-loops`` flag has been removed. It had no effect since Clang 
13.
+
 Attribute Changes in Clang
 --
 
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 53f23f9abb4c96..36a42b1b050c23 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -3871,10 +3871,6 @@ def funroll_loops : Flag<["-"], "funroll-loops">, 
Group,
   HelpText<"Turn on loop unroller">, Visibility<[ClangOption, CC1Option]>;
 def fno_unroll_loops : Flag<["-"], "fno-unroll-loops">, Group,
   HelpText<"Turn off loop unroller">, Visibility<[ClangOption, CC1Option]>;
-defm reroll_loops : BoolFOption<"reroll-loops",
-  CodeGenOpts<"RerollLoops">, DefaultFalse,
-  PosFlag,
-  NegFlag>;
 def ffinite_loops: Flag<["-"],  "ffinite-loops">, Group,
   HelpText<"Assume all loops are finite.">, Visibility<[ClangOption, 
CC1Option]>;
 def fno_finite_loops: Flag<["-"], "fno-finite-loops">, Group,
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 47305f798c5fee..7daf945ae12712 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -6660,11 +6660,6 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
   CmdArgs.push_back("-fwrapv");
   }
 
-  if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
-   options::OPT_fno_reroll_loops))
-if (A->getOption().matches(options::OPT_freroll_loops))
-  CmdArgs.push_back("-freroll-loops");
-
   Args.AddLastArg(CmdArgs, options::OPT_ffinite_loops,
   options::OPT_fno_finite_loops);
 
diff --git a/clang/test/Driver/clang_f_opts.c b/clang/test/Driver/clang_f_opts.c
index 33e4aa8386c3b3..472d0725a79340 100644
--- a/clang/test/Driver/clang_f_opts.c
+++ b/clang/test/Driver/clang_f_opts.c
@@ -45,13 +45,6 @@
 // CHECK-UNROLL-LOOPS: "-funroll-loops"
 // CHECK-NO-UNROLL-LOOPS: "-fno-unroll-loops"
 
-// RUN: %clang -### -S -freroll-loops %s 2>&1 | FileCheck 
-check-prefix=CHECK-REROLL-LOOPS %s
-// RUN: %clang -### -S -fno-reroll-loops %s 2>&1 | FileCheck 
-check-prefix=CHECK-NO-REROLL-LOOPS %s
-// RUN: %clang -### -S -fno-reroll-loops -freroll-loops %s 2>&1 | FileCheck 
-check-prefix=CHECK-REROLL-LOOPS %s
-// RUN: %clang -### -S -freroll-loops -fno-reroll-loops %s 2>&1 | FileCheck 
-check-prefix=CHECK-NO-REROLL-LOOPS %s
-// CHECK-REROLL-LOOPS: "-freroll-loops"
-// CHECK-NO-REROLL-LOOPS-NOT: "-freroll-loops"
-
 // RUN: %clang -### -S -fprofile-sample-accurate %s 2>&1 | FileCheck 
-check-prefix=CHECK-PROFILE-SAMPLE-ACCURATE %s
 // CHECK-PROFILE-SAMPLE-ACCURATE: "-fprofile-sample-accurate"
 

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


[clang] [Driver] Remove dead -freroll-loops flag (PR #82254)

2024-02-19 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-driver

Author: Nikita Popov (nikic)


Changes

Remove the `-freroll-loops` flag, which has not had any effect since the 
migration to the new pass manager. The underlying pass has been removed 
entirely in #80972 due to lack of maintenance and known bugs.

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


4 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+2) 
- (modified) clang/include/clang/Driver/Options.td (-4) 
- (modified) clang/lib/Driver/ToolChains/Clang.cpp (-5) 
- (modified) clang/test/Driver/clang_f_opts.c (-7) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 45ace4191592d3..3093e903410540 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -167,6 +167,8 @@ Modified Compiler Flags
 Removed Compiler Flags
 -
 
+- The ``-freroll-loops`` flag has been removed. It had no effect since Clang 
13.
+
 Attribute Changes in Clang
 --
 
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 53f23f9abb4c96..36a42b1b050c23 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -3871,10 +3871,6 @@ def funroll_loops : Flag<["-"], "funroll-loops">, 
Group,
   HelpText<"Turn on loop unroller">, Visibility<[ClangOption, CC1Option]>;
 def fno_unroll_loops : Flag<["-"], "fno-unroll-loops">, Group,
   HelpText<"Turn off loop unroller">, Visibility<[ClangOption, CC1Option]>;
-defm reroll_loops : BoolFOption<"reroll-loops",
-  CodeGenOpts<"RerollLoops">, DefaultFalse,
-  PosFlag,
-  NegFlag>;
 def ffinite_loops: Flag<["-"],  "ffinite-loops">, Group,
   HelpText<"Assume all loops are finite.">, Visibility<[ClangOption, 
CC1Option]>;
 def fno_finite_loops: Flag<["-"], "fno-finite-loops">, Group,
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 47305f798c5fee..7daf945ae12712 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -6660,11 +6660,6 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
   CmdArgs.push_back("-fwrapv");
   }
 
-  if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
-   options::OPT_fno_reroll_loops))
-if (A->getOption().matches(options::OPT_freroll_loops))
-  CmdArgs.push_back("-freroll-loops");
-
   Args.AddLastArg(CmdArgs, options::OPT_ffinite_loops,
   options::OPT_fno_finite_loops);
 
diff --git a/clang/test/Driver/clang_f_opts.c b/clang/test/Driver/clang_f_opts.c
index 33e4aa8386c3b3..472d0725a79340 100644
--- a/clang/test/Driver/clang_f_opts.c
+++ b/clang/test/Driver/clang_f_opts.c
@@ -45,13 +45,6 @@
 // CHECK-UNROLL-LOOPS: "-funroll-loops"
 // CHECK-NO-UNROLL-LOOPS: "-fno-unroll-loops"
 
-// RUN: %clang -### -S -freroll-loops %s 2>&1 | FileCheck 
-check-prefix=CHECK-REROLL-LOOPS %s
-// RUN: %clang -### -S -fno-reroll-loops %s 2>&1 | FileCheck 
-check-prefix=CHECK-NO-REROLL-LOOPS %s
-// RUN: %clang -### -S -fno-reroll-loops -freroll-loops %s 2>&1 | FileCheck 
-check-prefix=CHECK-REROLL-LOOPS %s
-// RUN: %clang -### -S -freroll-loops -fno-reroll-loops %s 2>&1 | FileCheck 
-check-prefix=CHECK-NO-REROLL-LOOPS %s
-// CHECK-REROLL-LOOPS: "-freroll-loops"
-// CHECK-NO-REROLL-LOOPS-NOT: "-freroll-loops"
-
 // RUN: %clang -### -S -fprofile-sample-accurate %s 2>&1 | FileCheck 
-check-prefix=CHECK-PROFILE-SAMPLE-ACCURATE %s
 // CHECK-PROFILE-SAMPLE-ACCURATE: "-fprofile-sample-accurate"
 

``




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


[clang] [clang][AArch64] multilib: fix deduction of "-march=" option (PR #81474)

2024-02-19 Thread Dominik Wójt via cfe-commits

https://github.com/domin144 updated 
https://github.com/llvm/llvm-project/pull/81474

From 4eda12594dbc07e3d3509a309d6691dcc983e5cc Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Dominik=20W=C3=B3jt?= 
Date: Mon, 12 Feb 2024 13:38:14 +0100
Subject: [PATCH 1/3] [clang][AArch64] multilib: fix deduction of "-march="
 option

The deduced "-march=" option always started with aarch64, which is not a
valid value. There was also no way to distinguish between armv8-r and
armv8-a. After this commit, the deduced "-march=" option will start with
greatest available "armv*-a" value or "armv8-r".
---
 clang/lib/Driver/ToolChain.cpp | 6 +-
 1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Driver/ToolChain.cpp b/clang/lib/Driver/ToolChain.cpp
index 657577cea6c7d8..623d52e9471f23 100644
--- a/clang/lib/Driver/ToolChain.cpp
+++ b/clang/lib/Driver/ToolChain.cpp
@@ -191,7 +191,11 @@ static void getAArch64MultilibFlags(const Driver &D,
   for (const auto &Ext : AArch64::Extensions)
 if (FeatureSet.contains(Ext.NegFeature))
   MArch.push_back(("no" + Ext.Name).str());
-  MArch.insert(MArch.begin(), ("-march=" + Triple.getArchName()).str());
+  StringRef ArchName;
+  for (const auto &ArchInfo : AArch64::ArchInfos)
+if (FeatureSet.contains(ArchInfo->ArchFeature))
+  ArchName = ArchInfo->Name;
+  MArch.insert(MArch.begin(), ("-march=" + ArchName).str());
   Result.push_back(llvm::join(MArch, "+"));
 }
 

From 35e57e5825e1a12734dae0ce8eabfd3b145d2b23 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Dominik=20W=C3=B3jt?= 
Date: Mon, 12 Feb 2024 14:46:26 +0100
Subject: [PATCH 2/3] fix tests

---
 clang/test/Driver/print-multi-selection-flags.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/clang/test/Driver/print-multi-selection-flags.c 
b/clang/test/Driver/print-multi-selection-flags.c
index 248d9a3cdf49b2..06a12db9d97792 100644
--- a/clang/test/Driver/print-multi-selection-flags.c
+++ b/clang/test/Driver/print-multi-selection-flags.c
@@ -51,9 +51,10 @@
 // CHECK-M85_NO_FP_DP: -mfpu=fp-armv8-fullfp16-sp-d16
 
 // RUN: %clang -print-multi-flags-experimental --target=aarch64-none-elf 
-march=armv8-a+lse | FileCheck --check-prefix=CHECK-LSE %s
-// CHECK-LSE: -march=aarch64{{.*}}+lse{{.*}}
+// CHECK-LSE: --target=aarch64-none-unknown-elf
+// CHECK-LSE: -march=armv8-a{{.*}}+lse{{.*}}
 
 // RUN: %clang -print-multi-flags-experimental --target=aarch64-none-elf 
-march=armv8.5-a+sve+sve2 | FileCheck --check-prefix=CHECK-SVE2 %s
 // RUN: %clang -print-multi-flags-experimental --target=aarch64-none-elf 
-march=armv9-a| FileCheck --check-prefix=CHECK-SVE2 %s
 // CHECK-SVE2: --target=aarch64-none-unknown-elf
-// CHECK-SVE2: -march=aarch64{{.*}}+simd{{.*}}+sve{{.*}}+sve2{{.*}}
+// CHECK-SVE2: -march=armv{{.*}}-a{{.*}}+simd{{.*}}+sve{{.*}}+sve2{{.*}}

From 5f1590d8a40f62caa9c95a60160f29dff849dacc Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Dominik=20W=C3=B3jt?= 
Date: Thu, 15 Feb 2024 12:55:11 +0100
Subject: [PATCH 3/3] add assert for missing arch feature

---
 clang/lib/Driver/ToolChain.cpp | 1 +
 1 file changed, 1 insertion(+)

diff --git a/clang/lib/Driver/ToolChain.cpp b/clang/lib/Driver/ToolChain.cpp
index 623d52e9471f23..0415e37f2e32f0 100644
--- a/clang/lib/Driver/ToolChain.cpp
+++ b/clang/lib/Driver/ToolChain.cpp
@@ -195,6 +195,7 @@ static void getAArch64MultilibFlags(const Driver &D,
   for (const auto &ArchInfo : AArch64::ArchInfos)
 if (FeatureSet.contains(ArchInfo->ArchFeature))
   ArchName = ArchInfo->Name;
+  assert(!ArchName.empty() && "at least one architecture should be found");
   MArch.insert(MArch.begin(), ("-march=" + ArchName).str());
   Result.push_back(llvm::join(MArch, "+"));
 }

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


[clang] [analyzer] UnixAPIMisuseChecker Get O_CREAT from preprocessor (PR #81855)

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

https://github.com/balazske commented:

Code change looks good, but I could not verify the new test. Probably it is not 
tested if it works with a non-usual O_CREAT value (that is parsed by the 
checker).

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


[clang] [clang][StaticAnalyzer] Crash on loop unrolling mode (PR #82089)

2024-02-19 Thread via cfe-commits

NagyDonat wrote:

That sounds reasonable. Unfortunately I don't know much about the context of 
this change, so let's wait for a review from @danix800 (or somebody else who's 
knows enough) before merging this change.

Also, perhaps it would be a good idea to add a testcase (or a few of them) in 
the directory `clang/test/Analysis` to prevent regressions and illustrate the 
goals of this change. (As far as I know our test system is just a heap of 
random C/C++ files with a "how to compile/analyze this" header and "what 
warnings/errors should appear" markers in comments. I usually add testcases by 
following the example of older analogous cases.)

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


[clang] 17a1b8f - [clang][Interp] Fix `nullptr - nullptr` expressions

2024-02-19 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-02-19T16:30:57+01:00
New Revision: 17a1b8f8481783ca9c318db6b6133631015726e9

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

LOG: [clang][Interp] Fix `nullptr - nullptr` expressions

They can happen and we used to run into an assertion.

Added: 


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

Removed: 




diff  --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index 344f523ed855a2..5e9c07545ae1fb 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -1579,6 +1579,11 @@ inline bool SubPtr(InterpState &S, CodePtr OpPC) {
 return false;
   }
 
+  if (LHS.isZero() && RHS.isZero()) {
+S.Stk.push();
+return true;
+  }
+
   T A = T::from(LHS.getIndex());
   T B = T::from(RHS.getIndex());
   return AddSubMulHelper(S, OpPC, A.bitWidth(), A, B);

diff  --git a/clang/test/AST/Interp/literals.cpp 
b/clang/test/AST/Interp/literals.cpp
index bc994c3191ce8e..8ea1c1155143e9 100644
--- a/clang/test/AST/Interp/literals.cpp
+++ b/clang/test/AST/Interp/literals.cpp
@@ -1124,3 +1124,10 @@ namespace rdar8769025 {
 f1(0); // both-warning{{null passed to a callee that requires a non-null 
argument}}
   }
 }
+
+namespace nullptrsub {
+  void a() {
+char *f = (char *)0;
+f = (char *)((char *)0 - (char *)0);
+  }
+}



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


[clang] [analyzer] UnixAPIMisuseChecker Get O_CREAT from preprocessor (PR #81855)

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

https://github.com/alejandro-alvarez-sonarsource updated 
https://github.com/llvm/llvm-project/pull/81855

From 702ab6679c3b030c42e8d18acd10f438b4880eeb Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Alejandro=20=C3=81lvarez=20Ayll=C3=B3n?=
 
Date: Thu, 15 Feb 2024 13:22:40 +0100
Subject: [PATCH 1/2] [analyzer] UnixAPIMisuseChecker Get O_CREAT from
 preprocessor

Now calling `open` with the `O_CREAT` flag and no mode parameter will
raise an issue in any system that defines `O_CREAT`.

The value for this flag is obtained after the full source code
has been parsed, leveraging `checkASTDecl`.
Hence, any `#define` or `#undefine` of `O_CREAT` following an
`open` may alter the results. Nevertheless, since redefining
reserved identifiers is UB, this is probably ok.
---
 .../Checkers/UnixAPIChecker.cpp   |  42 +-
 .../Inputs/expected-plists/unix-fns.c.plist   | 678 +-
 clang/test/Analysis/unix-fns.c|   2 +
 3 files changed, 365 insertions(+), 357 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
index b05ce610067cfa..19f1ca2dc824c9 100644
--- a/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
@@ -18,6 +18,7 @@
 #include "clang/StaticAnalyzer/Core/Checker.h"
 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringExtras.h"
@@ -39,13 +40,18 @@ enum class OpenVariant {
 
 namespace {
 
-class UnixAPIMisuseChecker : public Checker< check::PreStmt > {
+class UnixAPIMisuseChecker
+: public Checker,
+ check::ASTDecl> {
   const BugType BT_open{this, "Improper use of 'open'", categories::UnixAPI};
   const BugType BT_pthreadOnce{this, "Improper use of 'pthread_once'",
categories::UnixAPI};
   mutable std::optional Val_O_CREAT;
 
 public:
+  void checkASTDecl(const TranslationUnitDecl *TU, AnalysisManager &Mgr,
+BugReporter &BR) const;
+
   void checkPreStmt(const CallExpr *CE, CheckerContext &C) const;
 
   void CheckOpen(CheckerContext &C, const CallExpr *CE) const;
@@ -55,11 +61,8 @@ class UnixAPIMisuseChecker : public Checker< 
check::PreStmt > {
   void CheckOpenVariant(CheckerContext &C,
 const CallExpr *CE, OpenVariant Variant) const;
 
-  void ReportOpenBug(CheckerContext &C,
- ProgramStateRef State,
- const char *Msg,
+  void ReportOpenBug(CheckerContext &C, ProgramStateRef State, const char *Msg,
  SourceRange SR) const;
-
 };
 
 class UnixAPIPortabilityChecker : public Checker< check::PreStmt > {
@@ -90,7 +93,21 @@ class UnixAPIPortabilityChecker : public Checker< 
check::PreStmt > {
 const char *fn) const;
 };
 
-} //end anonymous namespace
+} // end anonymous namespace
+
+void UnixAPIMisuseChecker::checkASTDecl(const TranslationUnitDecl *TU,
+AnalysisManager &Mgr,
+BugReporter &) const {
+  // The definition of O_CREAT is platform specific.
+  // Try to get the macro value from the preprocessor.
+  Val_O_CREAT = tryExpandAsInteger("O_CREAT", Mgr.getPreprocessor());
+  // If we failed, fall-back to known values.
+  if (!Val_O_CREAT) {
+if (TU->getASTContext().getTargetInfo().getTriple().getVendor() ==
+llvm::Triple::Apple)
+  Val_O_CREAT = 0x0200;
+  }
+}
 
 
//===--===//
 // "open" (man 2 open)
@@ -204,19 +221,8 @@ void UnixAPIMisuseChecker::CheckOpenVariant(CheckerContext 
&C,
 return;
   }
 
-  // The definition of O_CREAT is platform specific.  We need a better way
-  // of querying this information from the checking environment.
   if (!Val_O_CREAT) {
-if (C.getASTContext().getTargetInfo().getTriple().getVendor()
-  == llvm::Triple::Apple)
-  Val_O_CREAT = 0x0200;
-else {
-  // FIXME: We need a more general way of getting the O_CREAT value.
-  // We could possibly grovel through the preprocessor state, but
-  // that would require passing the Preprocessor object to the ExprEngine.
-  // See also: MallocChecker.cpp / M_ZERO.
-  return;
-}
+return;
   }
 
   // Now check if oflags has O_CREAT set.
diff --git a/clang/test/Analysis/Inputs/expected-plists/unix-fns.c.plist 
b/clang/test/Analysis/Inputs/expected-plists/unix-fns.c.plist
index 2594f3b6d097d5..d7913cbc338fd0 100644
--- a/clang/test/Analysis/Inputs/expected-plists/unix-fns.c.plist
+++ b/clang/test/Analysis/Inputs/expected-plists/unix-fns.c.plist
@@ -16,12 +16,12 @@
 start
  
 

[clang] [analyzer] UnixAPIMisuseChecker Get O_CREAT from preprocessor (PR #81855)

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

alejandro-alvarez-sonarsource wrote:

Thanks! I have added a new test file where the values are those of 
[FreeRTOS](https://www.freertos.org/Documentation/api-ref/POSIX/fcntl_8h.html)

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


[clang] [clang][Interp] Handle complex values in visitBool() (PR #79452)

2024-02-19 Thread via cfe-commits

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


[clang] [clang][Interp] Handle complex values in visitBool() (PR #79452)

2024-02-19 Thread via cfe-commits

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

LGTM!

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


[clang] [clang][Interp] Handle complex values in visitBool() (PR #79452)

2024-02-19 Thread via cfe-commits


@@ -2120,8 +2074,15 @@ bool ByteCodeExprGen::visitInitializer(const 
Expr *E) {
 template 
 bool ByteCodeExprGen::visitBool(const Expr *E) {
   std::optional T = classify(E->getType());
-  if (!T)
+  if (!T) {
+// Convert complex values to bool.
+if (E->getType()->isAnyComplexType()) {
+  if (!this->visit(E))
+return false;
+  return this->emitComplexBoolCast(E);
+}

sethp wrote:

This feels a little odd: I wonder if Sema opts not to insert a 
`*ComplexToBoolean` cast because "in C, we might not have Boolean"? Though I'm 
not sure if there's any situation where we would have `_Complex` but not 
`_Bool`. I know gcc opts to extend support for complex types "backwards" in 
time as an extension (i.e. under a different name), but I think it also does so 
for booleans too. Maybe clang has a similar policy?

Put another way, this feels like the sort of "deep" implicit logic (i.e. that's 
not apparent from the AST) which keeps tripping me up when working with the 
evaluator in `ExprConstant`; it seems to me like it should either be in Sema 
(i.e. there ought to be a `*ComplexToBoolean` cast node) or maybe one level up 
in Visit[Conditional/Ternary/etc.] (whatever there's an implicit boolean 
context).

I'm just a [dog at a 
keyboard](https://en.wikipedia.org/wiki/On_the_Internet%2C_nobody_knows_you're_a_dog),
 though, so take my very much non-expert opinion for what it's worth.



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


[clang] [clang][Interp] Handle complex values in visitBool() (PR #79452)

2024-02-19 Thread via cfe-commits


@@ -125,3 +125,7 @@ struct XY { int before; struct XX xx, *xp; float* after; } 
xy[] = {
   0,  // all-warning {{initializer overrides prior initialization 
of this subobject}}
   &xy[2].xx.a, &xy[2].xx, &global_float
 };
+
+const int A =  ((_Complex double)1.0 ? 21 : 1);
+_Static_assert(A == 21, ""); // pedantic-ref-warning {{GNU extension}} \
+ // pedantic-expected-warning {{GNU extension}}

sethp wrote:

Some other test cases that might be interesting:

```C
const int foo = (__builtin_complex(0.0, 1.0));
const _Bool bar = (_Bool)(__builtin_complex(0.0, 1.0));
const _Bool baz = __builtin_complex(0.0, 1.0);
```

gcc (but not clang) seems to think `baz` ought not produce a constant value: 
https://godbolt.org/z/TEYWzzK7c 

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


[clang] [clang][Interp] Handle complex values in visitBool() (PR #79452)

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


@@ -125,3 +125,7 @@ struct XY { int before; struct XX xx, *xp; float* after; } 
xy[] = {
   0,  // all-warning {{initializer overrides prior initialization 
of this subobject}}
   &xy[2].xx.a, &xy[2].xx, &global_float
 };
+
+const int A =  ((_Complex double)1.0 ? 21 : 1);
+_Static_assert(A == 21, ""); // pedantic-ref-warning {{GNU extension}} \
+ // pedantic-expected-warning {{GNU extension}}

tbaederr wrote:

Added those without the `__builtin_complex`, which I don't support yet.

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


[clang] [clang][Interp] Handle complex values in visitBool() (PR #79452)

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

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

>From 720f2f869a11dd7c905f8d91180f3eb517ab9279 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Thu, 25 Jan 2024 15:20:52 +0100
Subject: [PATCH] [clang][Interp] Handle complex values in visitBool()

In C++, we get a ComplexToBool cast, but we might not in C.
---
 clang/lib/AST/Interp/ByteCodeExprGen.cpp | 118 +--
 clang/lib/AST/Interp/ByteCodeExprGen.h   |   1 +
 clang/test/AST/Interp/c.c|  11 +++
 clang/test/AST/Interp/complex.cpp|   2 +
 4 files changed, 82 insertions(+), 50 deletions(-)

diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 2fdc6f4f32bed9..d4b285941d46d1 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -241,57 +241,11 @@ bool ByteCodeExprGen::VisitCastExpr(const 
CastExpr *CE) {
 
   case CK_IntegralComplexToBoolean:
   case CK_FloatingComplexToBoolean: {
-PrimType ElemT = classifyComplexElementType(SubExpr->getType());
-// We emit the expression (__real(E) != 0 || __imag(E) != 0)
-// for us, that means (bool)E[0] || (bool)E[1]
+if (DiscardResult)
+  return this->discard(SubExpr);
 if (!this->visit(SubExpr))
   return false;
-if (!this->emitConstUint8(0, CE))
-  return false;
-if (!this->emitArrayElemPtrUint8(CE))
-  return false;
-if (!this->emitLoadPop(ElemT, CE))
-  return false;
-if (ElemT == PT_Float) {
-  if (!this->emitCastFloatingIntegral(PT_Bool, CE))
-return false;
-} else {
-  if (!this->emitCast(ElemT, PT_Bool, CE))
-return false;
-}
-
-// We now have the bool value of E[0] on the stack.
-LabelTy LabelTrue = this->getLabel();
-if (!this->jumpTrue(LabelTrue))
-  return false;
-
-if (!this->emitConstUint8(1, CE))
-  return false;
-if (!this->emitArrayElemPtrPopUint8(CE))
-  return false;
-if (!this->emitLoadPop(ElemT, CE))
-  return false;
-if (ElemT == PT_Float) {
-  if (!this->emitCastFloatingIntegral(PT_Bool, CE))
-return false;
-} else {
-  if (!this->emitCast(ElemT, PT_Bool, CE))
-return false;
-}
-// Leave the boolean value of E[1] on the stack.
-LabelTy EndLabel = this->getLabel();
-this->jump(EndLabel);
-
-this->emitLabel(LabelTrue);
-if (!this->emitPopPtr(CE))
-  return false;
-if (!this->emitConstBool(true, CE))
-  return false;
-
-this->fallthrough(EndLabel);
-this->emitLabel(EndLabel);
-
-return true;
+return this->emitComplexBoolCast(SubExpr);
   }
 
   case CK_IntegralComplexToReal:
@@ -2223,8 +2177,15 @@ bool ByteCodeExprGen::visitInitializer(const 
Expr *E) {
 template 
 bool ByteCodeExprGen::visitBool(const Expr *E) {
   std::optional T = classify(E->getType());
-  if (!T)
+  if (!T) {
+// Convert complex values to bool.
+if (E->getType()->isAnyComplexType()) {
+  if (!this->visit(E))
+return false;
+  return this->emitComplexBoolCast(E);
+}
 return false;
+  }
 
   if (!this->visit(E))
 return false;
@@ -3383,6 +3344,63 @@ bool ByteCodeExprGen::emitComplexReal(const 
Expr *SubExpr) {
   return true;
 }
 
+template 
+bool ByteCodeExprGen::emitComplexBoolCast(const Expr *E) {
+  assert(!DiscardResult);
+  PrimType ElemT = classifyComplexElementType(E->getType());
+  // We emit the expression (__real(E) != 0 || __imag(E) != 0)
+  // for us, that means (bool)E[0] || (bool)E[1]
+  if (!this->emitConstUint8(0, E))
+return false;
+  if (!this->emitArrayElemPtrUint8(E))
+return false;
+  if (!this->emitLoadPop(ElemT, E))
+return false;
+  if (ElemT == PT_Float) {
+if (!this->emitCastFloatingIntegral(PT_Bool, E))
+  return false;
+  } else {
+if (!this->emitCast(ElemT, PT_Bool, E))
+  return false;
+  }
+
+  // We now have the bool value of E[0] on the stack.
+  LabelTy LabelTrue = this->getLabel();
+  if (!this->jumpTrue(LabelTrue))
+return false;
+
+  if (!this->emitConstUint8(1, E))
+return false;
+  if (!this->emitArrayElemPtrPopUint8(E))
+return false;
+  if (!this->emitLoadPop(ElemT, E))
+return false;
+  if (ElemT == PT_Float) {
+if (!this->emitCastFloatingIntegral(PT_Bool, E))
+  return false;
+  } else {
+if (!this->emitCast(ElemT, PT_Bool, E))
+  return false;
+  }
+  // Leave the boolean value of E[1] on the stack.
+  LabelTy EndLabel = this->getLabel();
+  this->jump(EndLabel);
+
+  this->emitLabel(LabelTrue);
+  if (!this->emitPopPtr(E))
+return false;
+  if (!this->emitConstBool(true, E))
+return false;
+
+  this->fallthrough(EndLabel);
+  this->emitLabel(EndLabel);
+
+  return true;
+}
+
+/// When calling this, we have a pointer of the local-to-destroy
+/// on the stack.
+/// Emit destruction of record types (or arrays of record types).
 template 
 bool ByteCodeExprGen::emitRecordDestruction(c

[clang] [clang][Interp] Handle complex values in visitBool() (PR #79452)

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


@@ -2120,8 +2074,15 @@ bool ByteCodeExprGen::visitInitializer(const 
Expr *E) {
 template 
 bool ByteCodeExprGen::visitBool(const Expr *E) {
   std::optional T = classify(E->getType());
-  if (!T)
+  if (!T) {
+// Convert complex values to bool.
+if (E->getType()->isAnyComplexType()) {
+  if (!this->visit(E))
+return false;
+  return this->emitComplexBoolCast(E);
+}

tbaederr wrote:

@AaronBallman probably knows a reason for this.

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


[clang] [clang][AArch64] multilib: fix deduction of "-march=" option (PR #81474)

2024-02-19 Thread Dominik Wójt via cfe-commits

domin144 wrote:

@mplatings Can you merge for me? I don't have needed rights.
I rebased hoping the check will pass now, but there are still some unrelated 
failures on windows.

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


[clang-tools-extra] [clangd] Do not offer extraction to variable for decl init expression (PR #69477)

2024-02-19 Thread Christian Kandeler via cfe-commits


@@ -490,6 +491,13 @@ bool eligibleForExtraction(const SelectionTree::Node *N) {
 BO->getRHS() == OuterImplicit.ASTNode.get())
   return false;
   }
+  if (const auto *Decl = Parent->ASTNode.get()) {
+if (!Decl->isInitCapture() &&

ckandeler wrote:

Note also that there are already (pre-existing) tests for such selections, e.g.:
```
  {R"cpp(void f() {
   int x = 1 + 2 + [[3 + 4 + 5]];
 })cpp",
   R"cpp(void f() {
   auto placeholder = 3 + 4 + 5; int x = 1 + 2 + placeholder;
 })cpp"},
```

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


[clang] [clang] Preserve found-decl when constructing VarTemplateIds (PR #82265)

2024-02-19 Thread kadir çetinkaya via cfe-commits

https://github.com/kadircet created 
https://github.com/llvm/llvm-project/pull/82265

None

From 05e1d91361b4ce4226d21b00a312eb7642057c8f Mon Sep 17 00:00:00 2001
From: Kadir Cetinkaya 
Date: Mon, 19 Feb 2024 17:42:34 +0100
Subject: [PATCH] [clang] Preserve found-decl when constructing VarTemplateIds

---
 clang/include/clang/Sema/Sema.h   |  2 +-
 clang/lib/Sema/SemaTemplate.cpp   | 18 --
 clang/test/AST/ast-dump-using.cpp |  7 +++
 3 files changed, 16 insertions(+), 11 deletions(-)

diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 1f1cbd11ff7358..6c0c8945d7de25 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -8416,7 +8416,7 @@ class Sema final {
   /// if the arguments are dependent.
   ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
 const DeclarationNameInfo &NameInfo,
-VarTemplateDecl *Template,
+VarTemplateDecl *Template, NamedDecl *FoundD,
 SourceLocation TemplateLoc,
 const TemplateArgumentListInfo *TemplateArgs);
 
diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 9bfa71dc8bcf1d..ee00b1e119e042 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -4960,11 +4960,10 @@ Sema::CheckVarTemplateId(VarTemplateDecl *Template, 
SourceLocation TemplateLoc,
   return Decl;
 }
 
-ExprResult
-Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
- const DeclarationNameInfo &NameInfo,
- VarTemplateDecl *Template, SourceLocation TemplateLoc,
- const TemplateArgumentListInfo *TemplateArgs) {
+ExprResult Sema::CheckVarTemplateId(
+const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
+VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
+const TemplateArgumentListInfo *TemplateArgs) {
 
   DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, 
NameInfo.getLoc(),
*TemplateArgs);
@@ -4980,8 +4979,7 @@ Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
NameInfo.getLoc());
 
   // Build an ordinary singleton decl ref.
-  return BuildDeclarationNameExpr(SS, NameInfo, Var,
-  /*FoundD=*/nullptr, TemplateArgs);
+  return BuildDeclarationNameExpr(SS, NameInfo, Var, FoundD, TemplateArgs);
 }
 
 void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
@@ -5068,9 +5066,9 @@ ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec 
&SS,
   bool KnownDependent = false;
   // In C++1y, check variable template ids.
   if (R.getAsSingle()) {
-ExprResult Res = CheckVarTemplateId(SS, R.getLookupNameInfo(),
-R.getAsSingle(),
-TemplateKWLoc, TemplateArgs);
+ExprResult Res = CheckVarTemplateId(
+SS, R.getLookupNameInfo(), R.getAsSingle(),
+R.getRepresentativeDecl(), TemplateKWLoc, TemplateArgs);
 if (Res.isInvalid() || Res.isUsable())
   return Res;
 // Result is dependent. Carry on to build an UnresolvedLookupEpxr.
diff --git a/clang/test/AST/ast-dump-using.cpp 
b/clang/test/AST/ast-dump-using.cpp
index c007ecd8bda583..32826bb95676f3 100644
--- a/clang/test/AST/ast-dump-using.cpp
+++ b/clang/test/AST/ast-dump-using.cpp
@@ -2,6 +2,7 @@
 
 namespace a {
 struct S;
+template  T x = {};
 }
 namespace b {
 using a::S;
@@ -15,4 +16,10 @@ typedef S f; // to dump the introduced type
 // CHECK-NEXT:   `-UsingType {{.*}} 'a::S' sugar
 // CHECK-NEXT: |-UsingShadow {{.*}} 'S'
 // CHECK-NEXT: `-RecordType {{.*}} 'a::S'
+using a::x;
+
+void foo() {
+  x = 3;
+  // CHECK: DeclRefExpr {{.*}} 'x' {{.*}} (UsingShadow {{.*}} 'x')
+}
 }

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


  1   2   3   >