[clang] [clang-repl] Fix generation of wasm binaries while running clang-repl in browser (PR #117978)

2024-11-28 Thread Anutosh Bhat via cfe-commits

https://github.com/anutosh491 updated 
https://github.com/llvm/llvm-project/pull/117978

>From 987f77db9d45dee264c60f434652131438784f6f Mon Sep 17 00:00:00 2001
From: anutosh491 
Date: Thu, 28 Nov 2024 14:02:00 +0530
Subject: [PATCH 1/3] Fix generation of wasm binaries while running clang-repl
 in browser

---
 clang/lib/Interpreter/CMakeLists.txt  |  2 +
 clang/lib/Interpreter/Interpreter.cpp |  1 +
 clang/lib/Interpreter/Wasm.cpp| 57 ---
 3 files changed, 45 insertions(+), 15 deletions(-)

diff --git a/clang/lib/Interpreter/CMakeLists.txt 
b/clang/lib/Interpreter/CMakeLists.txt
index df7ea82e0dada5..bf70cdfbee01e1 100644
--- a/clang/lib/Interpreter/CMakeLists.txt
+++ b/clang/lib/Interpreter/CMakeLists.txt
@@ -16,6 +16,7 @@ set(LLVM_LINK_COMPONENTS
 if (EMSCRIPTEN AND "lld" IN_LIST LLVM_ENABLE_PROJECTS)
   set(WASM_SRC Wasm.cpp)
   set(WASM_LINK lldWasm)
+  set(COMMON_LINK lldCommon)
 endif()
 
 add_clang_library(clangInterpreter
@@ -47,6 +48,7 @@ add_clang_library(clangInterpreter
   clangSema
   clangSerialization
   ${WASM_LINK}
+  ${COMMON_LINK}
   )
 
 if ((MINGW OR CYGWIN) AND BUILD_SHARED_LIBS)
diff --git a/clang/lib/Interpreter/Interpreter.cpp 
b/clang/lib/Interpreter/Interpreter.cpp
index 5dc67f6375098f..887b494ff98f19 100644
--- a/clang/lib/Interpreter/Interpreter.cpp
+++ b/clang/lib/Interpreter/Interpreter.cpp
@@ -201,6 +201,7 @@ IncrementalCompilerBuilder::CreateCpp() {
   Argv.push_back("-target");
   Argv.push_back("wasm32-unknown-emscripten");
   Argv.push_back("-shared");
+  Argv.push_back("-fvisibility=default");
 #endif
   Argv.insert(Argv.end(), UserArgs.begin(), UserArgs.end());
 
diff --git a/clang/lib/Interpreter/Wasm.cpp b/clang/lib/Interpreter/Wasm.cpp
index 79efbaa03982d0..0fd6ad509c2938 100644
--- a/clang/lib/Interpreter/Wasm.cpp
+++ b/clang/lib/Interpreter/Wasm.cpp
@@ -23,6 +23,31 @@
 #include 
 
 namespace lld {
+enum Flavor {
+  Invalid,
+  Gnu, // -flavor gnu
+  MinGW,   // -flavor gnu MinGW
+  WinLink, // -flavor link
+  Darwin,  // -flavor darwin
+  Wasm,// -flavor wasm
+};
+
+using Driver = bool (*)(llvm::ArrayRef, llvm::raw_ostream &,
+llvm::raw_ostream &, bool, bool);
+
+struct DriverDef {
+  Flavor f;
+  Driver d;
+};
+
+struct Result {
+int retCode;
+bool canRunAgain;
+};
+
+Result lldMain(llvm::ArrayRef args, llvm::raw_ostream &stdoutOS,
+llvm::raw_ostream &stderrOS, llvm::ArrayRef 
drivers);
+
 namespace wasm {
 bool link(llvm::ArrayRef args, llvm::raw_ostream &stdoutOS,
   llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput);
@@ -51,45 +76,47 @@ llvm::Error 
WasmIncrementalExecutor::addModule(PartialTranslationUnit &PTU) {
   llvm::TargetMachine *TargetMachine = Target->createTargetMachine(
   PTU.TheModule->getTargetTriple(), "", "", TO, llvm::Reloc::Model::PIC_);
   PTU.TheModule->setDataLayout(TargetMachine->createDataLayout());
-  std::string OutputFileName = PTU.TheModule->getName().str() + ".wasm";
+  std::string ObjectFileName = PTU.TheModule->getName().str() + ".o";  // For 
the wasm object
+  std::string BinaryFileName = PTU.TheModule->getName().str() + ".wasm";  // 
For the wasm binary
 
   std::error_code Error;
-  llvm::raw_fd_ostream OutputFile(llvm::StringRef(OutputFileName), Error);
+  llvm::raw_fd_ostream ObjectFileOutput(llvm::StringRef(ObjectFileName), 
Error);
 
   llvm::legacy::PassManager PM;
-  if (TargetMachine->addPassesToEmitFile(PM, OutputFile, nullptr,
+  if (TargetMachine->addPassesToEmitFile(PM, ObjectFileOutput, nullptr,
  llvm::CodeGenFileType::ObjectFile)) {
 return llvm::make_error(
 "Wasm backend cannot produce object.", llvm::inconvertibleErrorCode());
   }
 
   if (!PM.run(*PTU.TheModule)) {
-
 return llvm::make_error("Failed to emit Wasm object.",
llvm::inconvertibleErrorCode());
   }
 
-  OutputFile.close();
+  ObjectFileOutput.close();
 
   std::vector LinkerArgs = {"wasm-ld",
   "-shared",
   "--import-memory",
-  "--no-entry",
-  "--export-all",
   "--experimental-pic",
   "--stack-first",
   "--allow-undefined",
-  OutputFileName.c_str(),
+  ObjectFileName.c_str(),
   "-o",
-  OutputFileName.c_str()};
-  int Result =
-  lld::wasm::link(LinkerArgs, llvm::outs(), llvm::errs(), false, false);
-  if (!Result)
+  BinaryFileName.c_str()};
+
+  const lld::DriverDef WasmDriver = {lld::Flavor::Wasm, &lld::wasm::link};
+  std::vector WasmDriverArg

[clang] [clang-repl] Fix generation of wasm binaries while running clang-repl in browser (PR #117978)

2024-11-28 Thread Anutosh Bhat via cfe-commits


@@ -109,12 +139,12 @@ llvm::Error WasmIncrementalExecutor::runCtors() const {
   return llvm::Error::success();
 }
 
-llvm::Error WasmIncrementalExecutor::cleanUp() const {

anutosh491 wrote:

I think we would need it. I see a build error otherwise 
```
 │ │ 
/home/runner/work/recipes/recipes/output/bld/rattler-build_llvm_1732028457/work/clang/lib/Interpreter/Wasm.cpp:111:38:
 error: out-of-line definition of 'cl
 │ │ eanUp' does not match any declaration in 'clang::WasmIncrementalExecutor'
 │ │   111 | llvm::Error WasmIncrementalExecutor::cleanUp() const {
 │ │   |  ^~~
 │ │ 
/home/runner/work/recipes/recipes/output/bld/rattler-build_llvm_1732028457/work/clang/lib/Interpreter/Wasm.h:31:15:
 note: member declaration does not match
 │ │  because it is not const qualified
 │ │31 |   llvm::Error cleanUp() override;
 │ │   |   ^ 
 ```
 
 CleanUp is defined like this 
 
https://github.com/llvm/llvm-project/blob/b2d3cb1e7502a5ddb7d6688dce5cf51573f6189c/clang/lib/Interpreter/Wasm.h#L31

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


[clang] 8fcbba8 - [RISCV] Add Qualcomm uC Xqcisls (Scaled Load Store) extension (#117987)

2024-11-28 Thread via cfe-commits

Author: Sudharsan Veeravalli
Date: 2024-11-29T10:26:00+05:30
New Revision: 8fcbba82d6c8038c4a0c5859275523414107b198

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

LOG: [RISCV] Add Qualcomm uC Xqcisls (Scaled Load Store) extension (#117987)

This extension adds 8 load/store instructions with a scaled index
addressing mode.

The current spec can be found at:
https://github.com/quic/riscv-unified-db/releases/latest

This patch adds assembler only support.

Added: 
llvm/test/MC/RISCV/xqcisls-invalid.s
llvm/test/MC/RISCV/xqcisls-valid.s

Modified: 
clang/test/Driver/print-supported-extensions-riscv.c
llvm/docs/RISCVUsage.rst
llvm/docs/ReleaseNotes.md
llvm/lib/Target/RISCV/Disassembler/RISCVDisassembler.cpp
llvm/lib/Target/RISCV/RISCVFeatures.td
llvm/lib/Target/RISCV/RISCVInstrInfoXqci.td
llvm/lib/TargetParser/RISCVISAInfo.cpp
llvm/test/CodeGen/RISCV/attributes.ll
llvm/unittests/TargetParser/RISCVISAInfoTest.cpp

Removed: 




diff  --git a/clang/test/Driver/print-supported-extensions-riscv.c 
b/clang/test/Driver/print-supported-extensions-riscv.c
index 02edfc03e59cac..70b7a96daf1daf 100644
--- a/clang/test/Driver/print-supported-extensions-riscv.c
+++ b/clang/test/Driver/print-supported-extensions-riscv.c
@@ -189,6 +189,7 @@
 // CHECK-NEXT: ssctr1.0   'Ssctr' (Control Transfer 
Records Supervisor Level)
 // CHECK-NEXT: svukte   0.3   'Svukte' 
(Address-Independent Latency of User-Mode Faults to Supervisor Addresses)
 // CHECK-NEXT: xqcicsr  0.2   'Xqcicsr' (Qualcomm uC CSR 
Extension)
+// CHECK-NEXT: xqcisls  0.2   'Xqcisls' (Qualcomm uC 
Scaled Load Store Extension)
 // CHECK-EMPTY:
 // CHECK-NEXT: Supported Profiles
 // CHECK-NEXT: rva20s64

diff  --git a/llvm/docs/RISCVUsage.rst b/llvm/docs/RISCVUsage.rst
index a7000baa69d806..230bf66fcf461b 100644
--- a/llvm/docs/RISCVUsage.rst
+++ b/llvm/docs/RISCVUsage.rst
@@ -429,6 +429,9 @@ The current vendor extensions supported are:
 ``experimental-Xqcicsr``
   LLVM implements `version 0.2 of the Qualcomm uC CSR extension specification 
`__ by Qualcomm.  All 
instructions are prefixed with `qc.` as described in the specification. These 
instructions are only available for riscv32.
 
+``experimental-Xqcisls``
+  LLVM implements `version 0.2 of the Qualcomm uC Scaled Load Store extension 
specification `__ by 
Qualcomm.  All instructions are prefixed with `qc.` as described in the 
specification. These instructions are only available for riscv32.
+
 Experimental C Intrinsics
 =
 

diff  --git a/llvm/docs/ReleaseNotes.md b/llvm/docs/ReleaseNotes.md
index 8b155d77bbb397..6d50839d68953e 100644
--- a/llvm/docs/ReleaseNotes.md
+++ b/llvm/docs/ReleaseNotes.md
@@ -213,6 +213,8 @@ Changes to the RISC-V Backend
   between e.g. F and Zfinx code.
 * Adds experimental assembler support for the Qualcomm uC 'Xqcicsr` (CSR)
   extension.
+* Adds experimental assembler support for the Qualcomm uC 'Xqcisls` (Scaled 
Load Store)
+  extension.
 
 Changes to the WebAssembly Backend
 --

diff  --git a/llvm/lib/Target/RISCV/Disassembler/RISCVDisassembler.cpp 
b/llvm/lib/Target/RISCV/Disassembler/RISCVDisassembler.cpp
index e4f7ee323cf20b..95658f24f79e1c 100644
--- a/llvm/lib/Target/RISCV/Disassembler/RISCVDisassembler.cpp
+++ b/llvm/lib/Target/RISCV/Disassembler/RISCVDisassembler.cpp
@@ -684,6 +684,8 @@ DecodeStatus RISCVDisassembler::getInstruction32(MCInst 
&MI, uint64_t &Size,
 "CORE-V Immediate Branching custom opcode table");
   TRY_TO_DECODE_FEATURE(RISCV::FeatureVendorXqcicsr, DecoderTableXqcicsr32,
 "Qualcomm uC CSR custom opcode table");
+  TRY_TO_DECODE_FEATURE(RISCV::FeatureVendorXqcisls, DecoderTableXqcisls32,
+"Qualcomm uC Scaled Load Store custom opcode table");
   TRY_TO_DECODE(true, DecoderTable32, "RISCV32 table");
 
   return MCDisassembler::Fail;

diff  --git a/llvm/lib/Target/RISCV/RISCVFeatures.td 
b/llvm/lib/Target/RISCV/RISCVFeatures.td
index 48ae378c0e67ef..95a37a76836729 100644
--- a/llvm/lib/Target/RISCV/RISCVFeatures.td
+++ b/llvm/lib/Target/RISCV/RISCVFeatures.td
@@ -1351,6 +1351,14 @@ def HasVendorXqcicsr
   AssemblerPredicate<(all_of FeatureVendorXqcicsr),
  "'Xqcicsr' (Qualcomm uC CSR Extension)">;
 
+def FeatureVendorXqcisls
+: RISCVExperimentalExtension<"xqcisls", 0, 2,
+ "'Xqcisls' (Qualcomm uC Scaled Load Store 
Extension)">;
+def HasVendorXqcisls
+: Predicate<"Subtarget->hasVendorXqcisls()">,
+   

[clang] [llvm] [RISCV] Add Qualcomm uC Xqcisls (Scaled Load Store) extension (PR #117987)

2024-11-28 Thread Sudharsan Veeravalli via cfe-commits

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


[clang] [analyzer] Handle [[assume(cond)]] as __builtin_assume(cond) (PR #116462)

2024-11-28 Thread Vinay Deshmukh via cfe-commits

https://github.com/vinay-deshmukh updated 
https://github.com/llvm/llvm-project/pull/116462

>From daddb9e13db6ca8373dc7298d17aa36a03014aeb Mon Sep 17 00:00:00 2001
From: Vinay Deshmukh <32487576+vinay-deshm...@users.noreply.github.com>
Date: Fri, 15 Nov 2024 07:37:17 -0500
Subject: [PATCH 1/9] [analyzer] Handle `[[assume(cond)]]` as
 `__builtin_assume(cond)`

Resolves #100762
---
 .../Core/PathSensitive/ExprEngine.h   |  4 ++
 clang/lib/Analysis/CFG.cpp| 43 +++
 clang/lib/StaticAnalyzer/Core/ExprEngine.cpp  |  8 +++-
 .../lib/StaticAnalyzer/Core/ExprEngineCXX.cpp | 27 
 clang/test/Analysis/out-of-bounds-new.cpp | 16 +++
 5 files changed, 97 insertions(+), 1 deletion(-)

diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
index 8c7493e27fcaa6..078a1d840d0516 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
@@ -498,6 +498,10 @@ class ExprEngine {
   void VisitInitListExpr(const InitListExpr *E, ExplodedNode *Pred,
  ExplodedNodeSet &Dst);
 
+  /// VisitAttributedStmt - Transfer function logic for AttributedStmt
+  void VisitAttributedStmt(const AttributedStmt *A, ExplodedNode *Pred,
+   ExplodedNodeSet &Dst);
+
   /// VisitLogicalExpr - Transfer function logic for '&&', '||'
   void VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred,
 ExplodedNodeSet &Dst);
diff --git a/clang/lib/Analysis/CFG.cpp b/clang/lib/Analysis/CFG.cpp
index f678ac6f2ff36a..fab10f51cf5cfc 100644
--- a/clang/lib/Analysis/CFG.cpp
+++ b/clang/lib/Analysis/CFG.cpp
@@ -456,6 +456,36 @@ reverse_children::reverse_children(Stmt *S) {
 IE->getNumInits());
   return;
 }
+case Stmt::AttributedStmtClass: {
+  AttributedStmt *attrStmt = cast(S);
+  assert(attrStmt);
+
+  {
+// for an attributed stmt, the "children()" returns only the NullStmt
+// (;) but semantically the "children" are supposed to be the
+// expressions _within_ i.e. the two square brackets i.e. [[ HERE ]]
+// so we add the subexpressions first, _then_ add the "children"
+
+for (const Attr *attr : attrStmt->getAttrs()) {
+
+  // i.e. one `assume()`
+  CXXAssumeAttr const *assumeAttr = 
llvm::dyn_cast(attr);
+  if (!assumeAttr) {
+continue;
+  }
+  // Only handles [[ assume() ]] right now
+  Expr *assumption = assumeAttr->getAssumption();
+  childrenBuf.push_back(assumption);
+}
+
+// children() for an AttributedStmt is NullStmt(;)
+llvm::append_range(childrenBuf, attrStmt->children());
+
+// This needs to be done *after* childrenBuf has been populated.
+children = childrenBuf;
+  }
+  return;
+}
 default:
   break;
   }
@@ -2475,6 +2505,14 @@ static bool isFallthroughStatement(const AttributedStmt 
*A) {
   return isFallthrough;
 }
 
+static bool isCXXAssumeAttr(const AttributedStmt *A) {
+  bool hasAssumeAttr = hasSpecificAttr(A->getAttrs());
+
+  assert((!hasAssumeAttr || isa(A->getSubStmt())) &&
+ "expected [[assume]] not to have children");
+  return hasAssumeAttr;
+}
+
 CFGBlock *CFGBuilder::VisitAttributedStmt(AttributedStmt *A,
   AddStmtChoice asc) {
   // AttributedStmts for [[likely]] can have arbitrary statements as children,
@@ -2490,6 +2528,11 @@ CFGBlock *CFGBuilder::VisitAttributedStmt(AttributedStmt 
*A,
 appendStmt(Block, A);
   }
 
+  if (isCXXAssumeAttr(A) && asc.alwaysAdd(*this, A)) {
+autoCreateBlock();
+appendStmt(Block, A);
+  }
+
   return VisitChildren(A);
 }
 
diff --git a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp 
b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
index 22eab9f66418d4..cbc83f1dbda145 100644
--- a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -1946,7 +1946,6 @@ void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred,
 // to be explicitly evaluated.
 case Stmt::PredefinedExprClass:
 case Stmt::AddrLabelExprClass:
-case Stmt::AttributedStmtClass:
 case Stmt::IntegerLiteralClass:
 case Stmt::FixedPointLiteralClass:
 case Stmt::CharacterLiteralClass:
@@ -1977,6 +1976,13 @@ void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred,
   break;
 }
 
+case Stmt::AttributedStmtClass: {
+  Bldr.takeNodes(Pred);
+  VisitAttributedStmt(cast(S), Pred, Dst);
+  Bldr.addNodes(Dst);
+  break;
+}
+
 case Stmt::CXXDefaultArgExprClass:
 case Stmt::CXXDefaultInitExprClass: {
   Bldr.takeNodes(Pred);
diff --git a/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp 
b/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
index f

[clang] [analyzer] Handle [[assume(cond)]] as __builtin_assume(cond) (PR #116462)

2024-11-28 Thread Vinay Deshmukh via cfe-commits

https://github.com/vinay-deshmukh updated 
https://github.com/llvm/llvm-project/pull/116462

>From daddb9e13db6ca8373dc7298d17aa36a03014aeb Mon Sep 17 00:00:00 2001
From: Vinay Deshmukh <32487576+vinay-deshm...@users.noreply.github.com>
Date: Fri, 15 Nov 2024 07:37:17 -0500
Subject: [PATCH 1/9] [analyzer] Handle `[[assume(cond)]]` as
 `__builtin_assume(cond)`

Resolves #100762
---
 .../Core/PathSensitive/ExprEngine.h   |  4 ++
 clang/lib/Analysis/CFG.cpp| 43 +++
 clang/lib/StaticAnalyzer/Core/ExprEngine.cpp  |  8 +++-
 .../lib/StaticAnalyzer/Core/ExprEngineCXX.cpp | 27 
 clang/test/Analysis/out-of-bounds-new.cpp | 16 +++
 5 files changed, 97 insertions(+), 1 deletion(-)

diff --git a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
index 8c7493e27fcaa6..078a1d840d0516 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h
@@ -498,6 +498,10 @@ class ExprEngine {
   void VisitInitListExpr(const InitListExpr *E, ExplodedNode *Pred,
  ExplodedNodeSet &Dst);
 
+  /// VisitAttributedStmt - Transfer function logic for AttributedStmt
+  void VisitAttributedStmt(const AttributedStmt *A, ExplodedNode *Pred,
+   ExplodedNodeSet &Dst);
+
   /// VisitLogicalExpr - Transfer function logic for '&&', '||'
   void VisitLogicalExpr(const BinaryOperator* B, ExplodedNode *Pred,
 ExplodedNodeSet &Dst);
diff --git a/clang/lib/Analysis/CFG.cpp b/clang/lib/Analysis/CFG.cpp
index f678ac6f2ff36a..fab10f51cf5cfc 100644
--- a/clang/lib/Analysis/CFG.cpp
+++ b/clang/lib/Analysis/CFG.cpp
@@ -456,6 +456,36 @@ reverse_children::reverse_children(Stmt *S) {
 IE->getNumInits());
   return;
 }
+case Stmt::AttributedStmtClass: {
+  AttributedStmt *attrStmt = cast(S);
+  assert(attrStmt);
+
+  {
+// for an attributed stmt, the "children()" returns only the NullStmt
+// (;) but semantically the "children" are supposed to be the
+// expressions _within_ i.e. the two square brackets i.e. [[ HERE ]]
+// so we add the subexpressions first, _then_ add the "children"
+
+for (const Attr *attr : attrStmt->getAttrs()) {
+
+  // i.e. one `assume()`
+  CXXAssumeAttr const *assumeAttr = 
llvm::dyn_cast(attr);
+  if (!assumeAttr) {
+continue;
+  }
+  // Only handles [[ assume() ]] right now
+  Expr *assumption = assumeAttr->getAssumption();
+  childrenBuf.push_back(assumption);
+}
+
+// children() for an AttributedStmt is NullStmt(;)
+llvm::append_range(childrenBuf, attrStmt->children());
+
+// This needs to be done *after* childrenBuf has been populated.
+children = childrenBuf;
+  }
+  return;
+}
 default:
   break;
   }
@@ -2475,6 +2505,14 @@ static bool isFallthroughStatement(const AttributedStmt 
*A) {
   return isFallthrough;
 }
 
+static bool isCXXAssumeAttr(const AttributedStmt *A) {
+  bool hasAssumeAttr = hasSpecificAttr(A->getAttrs());
+
+  assert((!hasAssumeAttr || isa(A->getSubStmt())) &&
+ "expected [[assume]] not to have children");
+  return hasAssumeAttr;
+}
+
 CFGBlock *CFGBuilder::VisitAttributedStmt(AttributedStmt *A,
   AddStmtChoice asc) {
   // AttributedStmts for [[likely]] can have arbitrary statements as children,
@@ -2490,6 +2528,11 @@ CFGBlock *CFGBuilder::VisitAttributedStmt(AttributedStmt 
*A,
 appendStmt(Block, A);
   }
 
+  if (isCXXAssumeAttr(A) && asc.alwaysAdd(*this, A)) {
+autoCreateBlock();
+appendStmt(Block, A);
+  }
+
   return VisitChildren(A);
 }
 
diff --git a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp 
b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
index 22eab9f66418d4..cbc83f1dbda145 100644
--- a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -1946,7 +1946,6 @@ void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred,
 // to be explicitly evaluated.
 case Stmt::PredefinedExprClass:
 case Stmt::AddrLabelExprClass:
-case Stmt::AttributedStmtClass:
 case Stmt::IntegerLiteralClass:
 case Stmt::FixedPointLiteralClass:
 case Stmt::CharacterLiteralClass:
@@ -1977,6 +1976,13 @@ void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred,
   break;
 }
 
+case Stmt::AttributedStmtClass: {
+  Bldr.takeNodes(Pred);
+  VisitAttributedStmt(cast(S), Pred, Dst);
+  Bldr.addNodes(Dst);
+  break;
+}
+
 case Stmt::CXXDefaultArgExprClass:
 case Stmt::CXXDefaultInitExprClass: {
   Bldr.takeNodes(Pred);
diff --git a/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp 
b/clang/lib/StaticAnalyzer/Core/ExprEngineCXX.cpp
index f

[clang] [Clang] Don't add top-level const qualifiers to captured function types (PR #118050)

2024-11-28 Thread Younan Zhang via cfe-commits

https://github.com/zyn0217 created 
https://github.com/llvm/llvm-project/pull/118050

This aligns with the logic in `TreeTransform::RebuildQualifiedType()` where we 
refrain from adding const qualifiers to function types. Previously, we seemed 
to overlook this edge case when copy-capturing a variable that is of function 
type within a const-qualified lambda.

This issue also reveals other related problems as in incorrect type printout 
and a suspicious implementation in DeduceTemplateArguments. I decide to leave 
them in follow-up work.

Fixes #84961


>From 92b8a28eb7664b3cac6a8039834b099b010af3ed Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Fri, 29 Nov 2024 13:19:30 +0800
Subject: [PATCH] [Clang] Don't add top-level const qualifiers to captured
 function types

---
 clang/docs/ReleaseNotes.rst|  1 +
 clang/lib/Sema/SemaExpr.cpp| 11 +--
 .../test/SemaCXX/lambda-capture-type-deduction.cpp | 14 ++
 3 files changed, 24 insertions(+), 2 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 8bd06fadfdc984..553856f3060bc1 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -712,6 +712,7 @@ Bug Fixes to C++ Support
 - Name independent data members were not correctly initialized from default 
member initializers. (#GH114069)
 - Fixed expression transformation for ``[[assume(...)]]``, allowing using pack 
indexing expressions within the
   assumption if they also occur inside of a dependent lambda. (#GH114787)
+- Lambdas now capture function types without considering top-level const 
qualifiers. (#GH84961)
 - Clang now uses valid deduced type locations when diagnosing functions with 
trailing return type
   missing placeholder return type. (#GH78694)
 
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 6c7472ce92703b..04b713a91dedfa 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -18479,7 +18479,10 @@ static bool 
isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI,
 // are mutable in the sense that user can change their value - they are
 // private instances of the captured declarations.
 const Capture &Cap = CSI->getCapture(Var);
-if (Cap.isCopyCapture() &&
+// C++ [dcl.fct]p7:
+//   [When] adding cv-qualifications on top of the function type [...] the
+//   cv-qualifiers are ignored.
+if (Cap.isCopyCapture() && !DeclRefType->isFunctionType() &&
 !(isa(CSI) &&
   !cast(CSI)->lambdaCaptureShouldBeConst()) &&
 !(isa(CSI) &&
@@ -18789,7 +18792,11 @@ static bool captureInLambda(LambdaScopeInfo *LSI, 
ValueDecl *Var,
 //   parameter-declaration-clause is not followed by mutable.
 DeclRefType = CaptureType.getNonReferenceType();
 bool Const = LSI->lambdaCaptureShouldBeConst();
-if (Const && !CaptureType->isReferenceType())
+// C++ [dcl.fct]p7:
+//   [When] adding cv-qualifications on top of the function type [...] the
+//   cv-qualifiers are ignored.
+if (Const && !CaptureType->isReferenceType() &&
+!DeclRefType->isFunctionType())
   DeclRefType.addConst();
   }
 
diff --git a/clang/test/SemaCXX/lambda-capture-type-deduction.cpp 
b/clang/test/SemaCXX/lambda-capture-type-deduction.cpp
index a86f3018989927..ba7ab34f943be1 100644
--- a/clang/test/SemaCXX/lambda-capture-type-deduction.cpp
+++ b/clang/test/SemaCXX/lambda-capture-type-deduction.cpp
@@ -319,3 +319,17 @@ constexpr void foo() {
 }
 
 } // namespace GH47400
+
+namespace GH84961 {
+
+template  void g(const T &t) {}
+
+template  void f(const T &t) {
+  [t] { g(t); }();
+}
+
+void h() {
+  f(h);
+}
+
+} // namespace GH84961

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


[libunwind] [libunwind][Haiku] Improve support (PR #115462)

2024-11-28 Thread Brad Smith via cfe-commits


@@ -2917,7 +2980,8 @@ template  int UnwindCursor::step(bool stage2) {
 
   // Use unwinding info to modify register set as if function returned.
   int result;
-#if defined(_LIBUNWIND_CHECK_LINUX_SIGRETURN)
+#if defined(_LIBUNWIND_CHECK_LINUX_SIGRETURN) ||   
\
+(defined(_LIBUNWIND_TARGET_HAIKU) && defined(_LIBUNWIND_TARGET_X86_64))

brad0 wrote:

I think you could remove the _LIBUNWIND_TARGET_X86_64 checks for all but around 
line 2758.

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


[clang] [clang-tools-extra] [clang] Compute accurate begin location for CallExpr with explicit object parameter (PR #117841)

2024-11-28 Thread Younan Zhang via cfe-commits

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


[clang] [clang-tools-extra] [clang] Compute accurate begin location for CallExpr with explicit object parameter (PR #117841)

2024-11-28 Thread Younan Zhang via cfe-commits

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

Thanks, while I haven’t come up with a better solution to model this situation, 
I think this looks good for now.

Please give @cor3ntin some time before merging, in case there are some better 
approaches that I might have overlooked.

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


[clang] [clang-tools-extra] [clang] Compute accurate begin location for CallExpr with explicit object parameter (PR #117841)

2024-11-28 Thread Younan Zhang via cfe-commits


@@ -1639,11 +1639,19 @@ SourceLocation CallExpr::getBeginLoc() const {
   if (const auto *OCE = dyn_cast(this))
 return OCE->getBeginLoc();
 
+  if (const auto *Method =
+  dyn_cast_if_present(getCalleeDecl());

zyn0217 wrote:

nit: I presume the `const` in `` isn't necessary, right?

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


[clang] [Clang] fix crash due to incorrect argument position in merging deduced template arguments (PR #118041)

2024-11-28 Thread Younan Zhang via cfe-commits

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


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


[clang-tools-extra] 91285e2 - [clang-reorder-fields] Handle macros fields declarations. (#118005)

2024-11-28 Thread via cfe-commits

Author: Clement Courbet
Date: 2024-11-29T08:36:22+01:00
New Revision: 91285e26bf67179a6804c931203c93f07c08183d

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

LOG: [clang-reorder-fields] Handle macros fields declarations. (#118005)

Right now fields with macro declarations break the tool:

```

struct Foo {
  Mutex mu;
  int x GUARDED_BY(mu);
  int y;
};
```

reordered by mu,y,x yields:

```
struct Foo {
  Mutex mu;
  int y GUARDED_BY(mu);
  int x;
};
```

Added: 
clang-tools-extra/test/clang-reorder-fields/FieldAnnotationsInMacros.cpp

Modified: 
clang-tools-extra/clang-reorder-fields/ReorderFieldsAction.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-reorder-fields/ReorderFieldsAction.cpp 
b/clang-tools-extra/clang-reorder-fields/ReorderFieldsAction.cpp
index 346437e20322e6..dc3a3b6211b7e4 100644
--- a/clang-tools-extra/clang-reorder-fields/ReorderFieldsAction.cpp
+++ b/clang-tools-extra/clang-reorder-fields/ReorderFieldsAction.cpp
@@ -116,6 +116,28 @@ findMembersUsedInInitExpr(const CXXCtorInitializer 
*Initializer,
   return Results;
 }
 
+/// Returns the full source range for the field declaration up to (not
+/// including) the trailing semicolumn, including potential macro invocations,
+/// e.g. `int a GUARDED_BY(mu);`.
+static SourceRange getFullFieldSourceRange(const FieldDecl &Field,
+   const ASTContext &Context) {
+  SourceRange Range = Field.getSourceRange();
+  SourceLocation End = Range.getEnd();
+  const SourceManager &SM = Context.getSourceManager();
+  const LangOptions &LangOpts = Context.getLangOpts();
+  while (true) {
+std::optional CurrentToken = Lexer::findNextToken(End, SM, 
LangOpts);
+
+if (!CurrentToken || CurrentToken->is(tok::semi))
+  break;
+
+if (CurrentToken->is(tok::eof))
+  return Range; // Something is wrong, return the original range.
+End = CurrentToken->getLastLoc();
+  }
+  return SourceRange(Range.getBegin(), End);
+}
+
 /// Reorders fields in the definition of a struct/class.
 ///
 /// At the moment reordering of fields with
@@ -145,9 +167,10 @@ static bool reorderFieldsInDefinition(
 const auto FieldIndex = Field->getFieldIndex();
 if (FieldIndex == NewFieldsOrder[FieldIndex])
   continue;
-addReplacement(Field->getSourceRange(),
-   Fields[NewFieldsOrder[FieldIndex]]->getSourceRange(),
-   Context, Replacements);
+addReplacement(
+getFullFieldSourceRange(*Field, Context),
+getFullFieldSourceRange(*Fields[NewFieldsOrder[FieldIndex]], Context),
+Context, Replacements);
   }
   return true;
 }

diff  --git 
a/clang-tools-extra/test/clang-reorder-fields/FieldAnnotationsInMacros.cpp 
b/clang-tools-extra/test/clang-reorder-fields/FieldAnnotationsInMacros.cpp
new file mode 100644
index 00..aedec9556aa55a
--- /dev/null
+++ b/clang-tools-extra/test/clang-reorder-fields/FieldAnnotationsInMacros.cpp
@@ -0,0 +1,9 @@
+// RUN: clang-reorder-fields -record-name Foo -fields-order y,x %s -- | 
FileCheck %s
+
+#define GUARDED_BY(x) __attribute__((guarded_by(x)))
+
+class Foo {
+  int x GUARDED_BY(x); // CHECK: {{^  int y;}}
+  int y;   // CHECK-NEXT: {{^  int x GUARDED_BY\(x\);}}
+};
+



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


[clang-tools-extra] [clang-reorder-fields] Handle macros fields declarations. (PR #118005)

2024-11-28 Thread Clement Courbet via cfe-commits

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


[libunwind] [libunwind] Make sure `__STDC_FORMAT_MACROS` is defined to ensure `PRId64` is available (PR #117491)

2024-11-28 Thread via cfe-commits

Zentrik wrote:

@ldionne Do you mind merging this as I don't have commit rights. Thank you

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


[clang] [analyzer] Modernize, improve and promote chroot checker (PR #117791)

2024-11-28 Thread Balazs Benics via cfe-commits

https://github.com/steakhal updated 
https://github.com/llvm/llvm-project/pull/117791

>From ed174c8b52880d4f89415eb3a72da13f355438d7 Mon Sep 17 00:00:00 2001
From: einvbri 
Date: Mon, 25 Nov 2024 10:31:57 +0100
Subject: [PATCH 01/20] [analyzer] Modernize, improve and promote chroot
 checker

This change modernizes, improves and promotes the chroot checker from
alpha to the Unix family of checkers. This checker covers the POS05
recommendations for use of chroot.

The improvements included modeling of a success or failure from chroot
and not falsely reporting a warning along an error path. This was made
possible through modernizing the checker to be flow sensitive.
---
 clang/docs/ReleaseNotes.rst   |   3 +
 clang/docs/analyzer/checkers.rst  |  30 ++--
 .../clang/StaticAnalyzer/Checkers/Checkers.td |   8 +-
 .../StaticAnalyzer/Checkers/ChrootChecker.cpp | 149 ++
 .../test/Analysis/analyzer-enabled-checkers.c |   1 +
 clang/test/Analysis/chroot.c  |  36 -
 clang/test/Analysis/show-checker-list.c   |   9 --
 ...c-library-functions-arg-enabled-checkers.c |   1 +
 8 files changed, 174 insertions(+), 63 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 6c40e48e2f49b3..292a41e127bfd0 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -985,6 +985,9 @@ Moved checkers
   original checkers were implemented only using AST matching and make more
   sense as a single clang-tidy check.
 
+- The checker ``alpha.unix.Chroot`` was modernized, improved and moved from
+  alpha to a main Unix family checker.
+
 .. _release-notes-sanitizers:
 
 Sanitizers
diff --git a/clang/docs/analyzer/checkers.rst b/clang/docs/analyzer/checkers.rst
index f34b25cd04bd18..5149faa50f72cf 100644
--- a/clang/docs/analyzer/checkers.rst
+++ b/clang/docs/analyzer/checkers.rst
@@ -1750,6 +1750,21 @@ Critical section handling functions modeled by this 
checker:
}
  }
 
+.. _unix-Chroot:
+
+unix.Chroot (C)
+"
+Check improper use of chroot.
+
+.. code-block:: c
+
+ void f();
+
+ void test() {
+   chroot("/usr/local");
+   f(); // warn: no call of chdir("/") immediately after chroot
+ }
+
 .. _unix-Errno:
 
 unix.Errno (C)
@@ -3275,21 +3290,6 @@ SEI CERT checkers which tries to find errors based on 
their `C coding rules ,
   HelpText<"Check for proper usage of vfork">,
   Documentation;
 
-} // end "unix"
-
-let ParentPackage = UnixAlpha in {
-
 def ChrootChecker : Checker<"Chroot">,
   HelpText<"Check improper use of chroot">,
   Documentation;
 
+} // end "unix"
+
+let ParentPackage = UnixAlpha in {
+
 def PthreadLockChecker : Checker<"PthreadLock">,
   HelpText<"Simple lock -> unlock checker">,
   Dependencies<[PthreadLockBase]>,
diff --git a/clang/lib/StaticAnalyzer/Checkers/ChrootChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/ChrootChecker.cpp
index 3a0a01c23de03e..d957ce9ed2ffc7 100644
--- a/clang/lib/StaticAnalyzer/Checkers/ChrootChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/ChrootChecker.cpp
@@ -10,6 +10,8 @@
 //
 
//===--===//
 
+#include "clang/AST/ASTContext.h"
+#include "clang/Basic/TargetInfo.h"
 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
@@ -24,21 +26,30 @@
 using namespace clang;
 using namespace ento;
 
-namespace {
-
 // enum value that represent the jail state
-enum Kind { NO_CHROOT, ROOT_CHANGED, JAIL_ENTERED };
+enum ChrootKind { NO_CHROOT, ROOT_CHANGED, ROOT_CHANGE_FAILED, JAIL_ENTERED };
 
-bool isRootChanged(intptr_t k) { return k == ROOT_CHANGED; }
-//bool isJailEntered(intptr_t k) { return k == JAIL_ENTERED; }
+// Track chroot state changes for success, failure, state change
+// and "jail"
+REGISTER_TRAIT_WITH_PROGRAMSTATE(ChrootState, ChrootKind)
+
+// Track the call expression to chroot for accurate
+// warning messages
+REGISTER_TRAIT_WITH_PROGRAMSTATE(ChrootCall, const Expr *)
+
+namespace {
 
 // This checker checks improper use of chroot.
-// The state transition:
+// The state transitions
+//
+//  -> ROOT_CHANGE_FAILED
+//  |
 // NO_CHROOT ---chroot(path)--> ROOT_CHANGED ---chdir(/) --> JAIL_ENTERED
 //  |   |
 // ROOT_CHANGED<--chdir(..)--  JAIL_ENTERED<--chdir(..)--
 //  |   |
 //  bug<--foo()--  JAIL_ENTERED<--foo()--
+//
 class ChrootChecker : public Checker {
   // This bug refers to possibly break out of a chroot() jail.
   const BugType BT_BreakJail{this, "Break out of jail"};
@@ -49,20 +60,17 @@ class ChrootChecker : public Checker {
 public:
   ChrootChecker() {}
 
-  static void *getTag() {
-static int x;
-return &x;
-  }
-
   bool eva

[clang] [analyzer] Modernize, improve and promote chroot checker (PR #117791)

2024-11-28 Thread Balazs Benics via cfe-commits

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


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


[clang] [clang] Format bitfield width diagnostics with thousands-separators (PR #117763)

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


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

>From 07b326b59bf9a8e385840a590c5162b9d1914650 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Tue, 26 Nov 2024 19:26:32 +0100
Subject: [PATCH 1/2] [clang] Format bitfield width diagnostics with
 thousands-separators

---
 .../clang/Basic/DiagnosticSemaKinds.td|  2 +-
 clang/lib/Sema/SemaDecl.cpp   | 27 ++-
 clang/test/SemaCXX/bitfield-layout.cpp|  4 +--
 3 files changed, 24 insertions(+), 9 deletions(-)

diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 6ff24c2bc8faad..5ab0885c8414fd 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -6400,7 +6400,7 @@ def err_incorrect_number_of_vector_initializers : Error<
 // Used by C++ which allows bit-fields that are wider than the type.
 def warn_bitfield_width_exceeds_type_width: Warning<
   "width of bit-field %0 (%1 bits) exceeds the width of its type; value will "
-  "be truncated to %2 bit%s2">, InGroup;
+  "be truncated to %2 bits">, InGroup;
 def err_bitfield_too_wide : Error<
   "%select{bit-field %1|anonymous bit-field}0 is too wide (%2 bits)">;
 def warn_bitfield_too_small_for_enum : Warning<
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 74b0e5ad23bd48..7378edc1c5cecb 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -18307,16 +18307,22 @@ ExprResult Sema::VerifyBitField(SourceLocation 
FieldLoc,
   if (Value.isSigned() && Value.isNegative()) {
 if (FieldName)
   return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
-   << FieldName << toString(Value, 10);
+ << FieldName
+ << toString(Value, 10, Value.isSigned(),
+ /*formatAsCLiteral=*/false, /*UpperCase=*/true,
+ /*InsertSeparators=*/true);
 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
-  << toString(Value, 10);
+   << toString(Value, 10, Value.isSigned(), /*formatAsCLiteral=*/false,
+   /*UpperCase=*/true, /*InsertSeparators=*/true);
   }
 
   // The size of the bit-field must not exceed our maximum permitted object
   // size.
   if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
 return Diag(FieldLoc, diag::err_bitfield_too_wide)
-   << !FieldName << FieldName << toString(Value, 10);
+   << !FieldName << FieldName
+   << toString(Value, 10, Value.isSigned(), /*formatAsCLiteral=*/false,
+   /*UpperCase=*/true, /*InsertSeparators=*/true);
   }
 
   if (!FieldTy->isDependentType()) {
@@ -18335,7 +18341,10 @@ ExprResult Sema::VerifyBitField(SourceLocation 
FieldLoc,
   unsigned DiagWidth =
   CStdConstraintViolation ? TypeWidth : TypeStorageSize;
   return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
- << (bool)FieldName << FieldName << toString(Value, 10)
+ << (bool)FieldName << FieldName
+ << toString(Value, 10, Value.isSigned(),
+ /*formatAsCLiteral=*/false, /*UpperCase=*/true,
+ /*InsertSeparators=*/true)
  << !CStdConstraintViolation << DiagWidth;
 }
 
@@ -18343,9 +18352,15 @@ ExprResult Sema::VerifyBitField(SourceLocation 
FieldLoc,
 // specified bits as value bits: that's all integral types other than
 // 'bool'.
 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
+  llvm::APInt TypeWidthAP(sizeof(TypeWidth) * 8, TypeWidth,
+  /*IsSigned=*/false);
   Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
-  << FieldName << toString(Value, 10)
-  << (unsigned)TypeWidth;
+  << FieldName
+  << toString(Value, 10, Value.isSigned(), /*formatAsCLiteral=*/false,
+  /*UpperCase=*/true, /*InsertSeparators=*/true)
+  << toString(TypeWidthAP, 10, /*Signed=*/false,
+  /*formatAsCLiteral=*/false, /*UpperCase=*/true,
+  /*InsertSeparators=*/true);
 }
   }
 
diff --git a/clang/test/SemaCXX/bitfield-layout.cpp 
b/clang/test/SemaCXX/bitfield-layout.cpp
index 7efd1d38c682f5..951a4f72de1566 100644
--- a/clang/test/SemaCXX/bitfield-layout.cpp
+++ b/clang/test/SemaCXX/bitfield-layout.cpp
@@ -35,14 +35,14 @@ CHECK_SIZE(Test4, 8);
 CHECK_ALIGN(Test4, 8);
 
 struct Test5 {
-  char c : 0x10001; // expected-warning {{width of bit-field 'c' 
(4294967297 bits) exceeds the width of its type; value will be truncated to 8 
bits}}
+  char c : 0x10001; // expected-warning {{width of bit-field 'c' 
(4'294'967'297 bits) exceeds the width of its type; value will be truncated to 
8 bits}}
 };
 // Size and a

[clang] [clang-tools-extra] [clang] Compute accurate begin location for CallExpr with explicit object parameter (PR #117841)

2024-11-28 Thread Nathan Ridge via cfe-commits

https://github.com/HighCommander4 updated 
https://github.com/llvm/llvm-project/pull/117841

>From 367a0cc6b3e1e1f67d023c96e06ae438f8f37f37 Mon Sep 17 00:00:00 2001
From: Nathan Ridge 
Date: Tue, 26 Nov 2024 22:41:43 -0500
Subject: [PATCH] [clang] Compute accurate begin location for CallExpr with
 explicit object parameter

The explicit object parameter is written before the callee expression,
so the begin location should come from the explicit object parameter.
---
 .../clangd/unittests/XRefsTests.cpp   | 148 ++
 clang/lib/AST/Expr.cpp|   8 +
 clang/lib/Sema/SemaOverload.cpp   |   2 +-
 .../test/AST/ast-dump-cxx2b-deducing-this.cpp |   4 +-
 4 files changed, 90 insertions(+), 72 deletions(-)

diff --git a/clang-tools-extra/clangd/unittests/XRefsTests.cpp 
b/clang-tools-extra/clangd/unittests/XRefsTests.cpp
index d393c72974d447..87efb42be47121 100644
--- a/clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ b/clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -450,7 +450,7 @@ TEST(LocateSymbol, All) {
   //   $def is the definition location (if absent, symbol has no definition)
   //   unnamed range becomes both $decl and $def.
   const char *Tests[] = {
-  R"cpp(
+R"cpp(
 struct X {
   union {
 int [[a]];
@@ -462,7 +462,7 @@ TEST(LocateSymbol, All) {
 }
   )cpp",
 
-  R"cpp(// Local variable
+R"cpp(// Local variable
 int main() {
   int [[bonjour]];
   ^bonjour = 2;
@@ -470,7 +470,7 @@ TEST(LocateSymbol, All) {
 }
   )cpp",
 
-  R"cpp(// Struct
+R"cpp(// Struct
 namespace ns1 {
 struct [[MyClass]] {};
 } // namespace ns1
@@ -479,21 +479,21 @@ TEST(LocateSymbol, All) {
 }
   )cpp",
 
-  R"cpp(// Function definition via pointer
+R"cpp(// Function definition via pointer
 void [[foo]](int) {}
 int main() {
   auto *X = &^foo;
 }
   )cpp",
 
-  R"cpp(// Function declaration via call
+R"cpp(// Function declaration via call
 int $decl[[foo]](int);
 int main() {
   return ^foo(42);
 }
   )cpp",
 
-  R"cpp(// Field
+R"cpp(// Field
 struct Foo { int [[x]]; };
 int main() {
   Foo bar;
@@ -501,21 +501,21 @@ TEST(LocateSymbol, All) {
 }
   )cpp",
 
-  R"cpp(// Field, member initializer
+R"cpp(// Field, member initializer
 struct Foo {
   int [[x]];
   Foo() : ^x(0) {}
 };
   )cpp",
 
-  R"cpp(// Field, field designator
+R"cpp(// Field, field designator
 struct Foo { int [[x]]; };
 int main() {
   Foo bar = { .^x = 2 };
 }
   )cpp",
 
-  R"cpp(// Method call
+R"cpp(// Method call
 struct Foo { int $decl[[x]](); };
 int main() {
   Foo bar;
@@ -523,31 +523,31 @@ TEST(LocateSymbol, All) {
 }
   )cpp",
 
-  R"cpp(// Typedef
+R"cpp(// Typedef
 typedef int $decl[[Foo]];
 int main() {
   ^Foo bar;
 }
   )cpp",
 
-  R"cpp(// Template type parameter
+R"cpp(// Template type parameter
 template 
 void foo() { ^T t; }
   )cpp",
 
-  R"cpp(// Template template type parameter
+R"cpp(// Template template type parameter
 template  class [[T]]>
 void foo() { ^T t; }
   )cpp",
 
-  R"cpp(// Namespace
+R"cpp(// Namespace
 namespace $decl[[ns]] {
 struct Foo { static void bar(); };
 } // namespace ns
 int main() { ^ns::Foo::bar(); }
   )cpp",
 
-  R"cpp(// Macro
+R"cpp(// Macro
class TTT { public: int a; };
#define [[FF]](S) if (int b = S.a) {}
void f() {
@@ -556,12 +556,12 @@ TEST(LocateSymbol, All) {
}
   )cpp",
 
-  R"cpp(// Macro argument
+R"cpp(// Macro argument
int [[i]];
#define ADDRESSOF(X) &X;
int *j = ADDRESSOF(^i);
   )cpp",
-  R"cpp(// Macro argument appearing multiple times in expansion
+R"cpp(// Macro argument appearing multiple times in expansion
 #define VALIDATE_TYPE(x) (void)x;
 #define ASSERT(expr)   \
   do { \
@@ -573,37 +573,37 @@ TEST(LocateSymbol, All) {
   ASSERT(wa^ldo());
 }
   )cpp",
-  R"cpp(// Symbol concatenated inside macro (not supported)
+R"cpp(// Symbol concatenated inside macro (not supported)
int *pi;
#define POINTER(X) p ## X;
int x = *POINTER(^i);
   )cpp",
 
-  R"cpp(// Forward class declaration
+R"cpp(// Forward class declaration
 class $decl[[Foo]];
 class $def[[Foo]] {};
 F^oo* foo();
   )cpp",
 
-  R"cpp(// Function declaration
+R"cpp(// Function declaration
 void $decl[[foo]]();
 void g() { f^oo(); }
 void $def[[foo]]() {}
   )cpp",
 
-

[clang] [clang-tools-extra] [clang] Compute accurate begin location for CallExpr with explicit object parameter (PR #117841)

2024-11-28 Thread Nathan Ridge via cfe-commits

HighCommander4 wrote:

Updated to add a clangd test that fails with the previous fix approach.

> A more general implementation of `CallExpr::getBeginLoc` that occurs to me 
> is: return the earlier of the callee's begin loc and the first argument's (if 
> present) begin loc.

I did not do this because accurately determining which of two `SourceLocation`s 
is earlier requires calling `SourceManager::isBeforeInTranslationUnit()`, and a 
`SourceManager` does not seem to be available in `CallExpr::getBeginLoc()`.

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


[clang] [clang-tools-extra] [clang] Compute accurate begin location for CallExpr with explicit object parameter (PR #117841)

2024-11-28 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 9fde1a498f2dc97a737a3564cb427c6f2a7bfe6c 
367a0cc6b3e1e1f67d023c96e06ae438f8f37f37 --extensions cpp -- 
clang-tools-extra/clangd/unittests/XRefsTests.cpp clang/lib/AST/Expr.cpp 
clang/lib/Sema/SemaOverload.cpp clang/test/AST/ast-dump-cxx2b-deducing-this.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang-tools-extra/clangd/unittests/XRefsTests.cpp 
b/clang-tools-extra/clangd/unittests/XRefsTests.cpp
index 87efb42be4..7d824d659a 100644
--- a/clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ b/clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -450,7 +450,7 @@ TEST(LocateSymbol, All) {
   //   $def is the definition location (if absent, symbol has no definition)
   //   unnamed range becomes both $decl and $def.
   const char *Tests[] = {
-R"cpp(
+  R"cpp(
 struct X {
   union {
 int [[a]];
@@ -462,7 +462,7 @@ TEST(LocateSymbol, All) {
 }
   )cpp",
 
-R"cpp(// Local variable
+  R"cpp(// Local variable
 int main() {
   int [[bonjour]];
   ^bonjour = 2;
@@ -470,7 +470,7 @@ TEST(LocateSymbol, All) {
 }
   )cpp",
 
-R"cpp(// Struct
+  R"cpp(// Struct
 namespace ns1 {
 struct [[MyClass]] {};
 } // namespace ns1
@@ -479,21 +479,21 @@ TEST(LocateSymbol, All) {
 }
   )cpp",
 
-R"cpp(// Function definition via pointer
+  R"cpp(// Function definition via pointer
 void [[foo]](int) {}
 int main() {
   auto *X = &^foo;
 }
   )cpp",
 
-R"cpp(// Function declaration via call
+  R"cpp(// Function declaration via call
 int $decl[[foo]](int);
 int main() {
   return ^foo(42);
 }
   )cpp",
 
-R"cpp(// Field
+  R"cpp(// Field
 struct Foo { int [[x]]; };
 int main() {
   Foo bar;
@@ -501,21 +501,21 @@ TEST(LocateSymbol, All) {
 }
   )cpp",
 
-R"cpp(// Field, member initializer
+  R"cpp(// Field, member initializer
 struct Foo {
   int [[x]];
   Foo() : ^x(0) {}
 };
   )cpp",
 
-R"cpp(// Field, field designator
+  R"cpp(// Field, field designator
 struct Foo { int [[x]]; };
 int main() {
   Foo bar = { .^x = 2 };
 }
   )cpp",
 
-R"cpp(// Method call
+  R"cpp(// Method call
 struct Foo { int $decl[[x]](); };
 int main() {
   Foo bar;
@@ -523,31 +523,31 @@ TEST(LocateSymbol, All) {
 }
   )cpp",
 
-R"cpp(// Typedef
+  R"cpp(// Typedef
 typedef int $decl[[Foo]];
 int main() {
   ^Foo bar;
 }
   )cpp",
 
-R"cpp(// Template type parameter
+  R"cpp(// Template type parameter
 template 
 void foo() { ^T t; }
   )cpp",
 
-R"cpp(// Template template type parameter
+  R"cpp(// Template template type parameter
 template  class [[T]]>
 void foo() { ^T t; }
   )cpp",
 
-R"cpp(// Namespace
+  R"cpp(// Namespace
 namespace $decl[[ns]] {
 struct Foo { static void bar(); };
 } // namespace ns
 int main() { ^ns::Foo::bar(); }
   )cpp",
 
-R"cpp(// Macro
+  R"cpp(// Macro
class TTT { public: int a; };
#define [[FF]](S) if (int b = S.a) {}
void f() {
@@ -556,12 +556,12 @@ TEST(LocateSymbol, All) {
}
   )cpp",
 
-R"cpp(// Macro argument
+  R"cpp(// Macro argument
int [[i]];
#define ADDRESSOF(X) &X;
int *j = ADDRESSOF(^i);
   )cpp",
-R"cpp(// Macro argument appearing multiple times in expansion
+  R"cpp(// Macro argument appearing multiple times in expansion
 #define VALIDATE_TYPE(x) (void)x;
 #define ASSERT(expr)   \
   do { \
@@ -573,37 +573,37 @@ TEST(LocateSymbol, All) {
   ASSERT(wa^ldo());
 }
   )cpp",
-R"cpp(// Symbol concatenated inside macro (not supported)
+  R"cpp(// Symbol concatenated inside macro (not supported)
int *pi;
#define POINTER(X) p ## X;
int x = *POINTER(^i);
   )cpp",
 
-R"cpp(// Forward class declaration
+  R"cpp(// Forward class declaration
 class $decl[[Foo]];
 class $def[[Foo]] {};
 F^oo* foo();
   )cpp",
 
-R"cpp(// Function declaration
+  R"cpp(// Function declaration
 void $decl[[foo]]();
 void g() { f^oo(); }
 void $def[[foo]]() {}
   )cpp",
 
-R"cpp(
+  R"cpp(
 #define FF(name) class name##_Test {};
 [[FF]](my);
 void f() { my^_Test a; }
   )cpp",
 
-R"cpp(
+  R"cpp(
  #define FF() class [[Test]] {};
  FF();
  

[clang] [clang-tools-extra] [clang] Compute accurate begin location for CallExpr with explicit object parameter (PR #117841)

2024-11-28 Thread Nathan Ridge via cfe-commits

https://github.com/HighCommander4 updated 
https://github.com/llvm/llvm-project/pull/117841

>From 3e5e55fa72c04996dfde1304662e9def6a1ef726 Mon Sep 17 00:00:00 2001
From: Nathan Ridge 
Date: Fri, 29 Nov 2024 00:08:40 -0500
Subject: [PATCH] [clang] Compute accurate begin location for CallExpr with
 explicit object parameter

The explicit object parameter is written before the callee expression,
so the begin location should come from the explicit object parameter.
---
 clang-tools-extra/clangd/unittests/XRefsTests.cpp | 10 ++
 clang/lib/AST/Expr.cpp|  8 
 clang/lib/Sema/SemaOverload.cpp   |  2 +-
 clang/test/AST/ast-dump-cxx2b-deducing-this.cpp   |  4 ++--
 4 files changed, 21 insertions(+), 3 deletions(-)

diff --git a/clang-tools-extra/clangd/unittests/XRefsTests.cpp 
b/clang-tools-extra/clangd/unittests/XRefsTests.cpp
index d393c72974d447..7d824d659ad2ce 100644
--- a/clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ b/clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -1019,6 +1019,15 @@ TEST(LocateSymbol, All) {
   void *Value;
   void *getPointer() const { return Info::get^Pointer(Value); }
 };
+  )cpp",
+  R"cpp(// Deducing this
+struct S {
+  int bar(this S&);
+};
+void foo() {
+  S [[waldo]];
+  int x = wa^ldo.bar();
+}
 )cpp"};
   for (const char *Test : Tests) {
 Annotations T(Test);
@@ -1035,6 +1044,7 @@ TEST(LocateSymbol, All) {
 TU.Code = std::string(T.code());
 
 TU.ExtraArgs.push_back("-xobjective-c++");
+TU.ExtraArgs.push_back("-std=c++23");
 
 auto AST = TU.build();
 auto Results = locateSymbolAt(AST, T.point());
diff --git a/clang/lib/AST/Expr.cpp b/clang/lib/AST/Expr.cpp
index a4fb4d5a1f2ec4..5a6738196d2890 100644
--- a/clang/lib/AST/Expr.cpp
+++ b/clang/lib/AST/Expr.cpp
@@ -1639,11 +1639,19 @@ SourceLocation CallExpr::getBeginLoc() const {
   if (const auto *OCE = dyn_cast(this))
 return OCE->getBeginLoc();
 
+  if (const auto *Method =
+  dyn_cast_if_present(getCalleeDecl());
+  Method && Method->isExplicitObjectMemberFunction()) {
+assert(getNumArgs() > 0 && getArg(0));
+return getArg(0)->getBeginLoc();
+  }
+
   SourceLocation begin = getCallee()->getBeginLoc();
   if (begin.isInvalid() && getNumArgs() > 0 && getArg(0))
 begin = getArg(0)->getBeginLoc();
   return begin;
 }
+
 SourceLocation CallExpr::getEndLoc() const {
   if (const auto *OCE = dyn_cast(this))
 return OCE->getEndLoc();
diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 4c9e37bd286dee..e4bf9aa521224b 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -15565,7 +15565,7 @@ ExprResult Sema::BuildCallToMemberFunction(Scope *S, 
Expr *MemExprE,
 // Build the actual expression node.
 ExprResult FnExpr =
 CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr,
-  HadMultipleCandidates, MemExpr->getBeginLoc());
+  HadMultipleCandidates, MemExpr->getExprLoc());
 if (FnExpr.isInvalid())
   return ExprError();
 
diff --git a/clang/test/AST/ast-dump-cxx2b-deducing-this.cpp 
b/clang/test/AST/ast-dump-cxx2b-deducing-this.cpp
index 04cff07376885a..1b385e0fc33319 100644
--- a/clang/test/AST/ast-dump-cxx2b-deducing-this.cpp
+++ b/clang/test/AST/ast-dump-cxx2b-deducing-this.cpp
@@ -9,7 +9,7 @@ int main() {
   S s;
   int x = s.f();
   // CHECK: CallExpr 0x{{[^ ]*}}  'int
-  // CHECK-NEXT: |-ImplicitCastExpr 0x{{[^ ]*}}  'int (*)(S &)' 

-  // CHECK-NEXT: | `-DeclRefExpr 0x{{[^ ]*}}  'int (S &)' lvalue 
CXXMethod 0x{{[^ ]*}} 'f' 'int (S &)'
+  // CHECK-NEXT: |-ImplicitCastExpr 0x{{[^ ]*}}  'int (*)(S &)' 

+  // CHECK-NEXT: | `-DeclRefExpr 0x{{[^ ]*}}  'int (S &)' lvalue 
CXXMethod 0x{{[^ ]*}} 'f' 'int (S &)'
 }
 }

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


[clang] [clang-tools-extra] [clang] Compute accurate begin location for CallExpr with explicit object parameter (PR #117841)

2024-11-28 Thread Nathan Ridge via cfe-commits

HighCommander4 wrote:

(Removed extraneous formatting changes)

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


[clang] 9b5b3ed - [clang-format][doc] Fix formatting, etc.

2024-11-28 Thread Owen Pan via cfe-commits

Author: Owen Pan
Date: 2024-11-28T22:00:23-08:00
New Revision: 9b5b3edd64e56af02295c0365269177443d4a64d

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

LOG: [clang-format][doc] Fix formatting, etc.

Added: 


Modified: 
clang/docs/ClangFormatStyleOptions.rst
clang/include/clang/Format/Format.h
clang/include/clang/Tooling/Inclusions/IncludeStyle.h

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index dc34094b5053a9..4be448171699ca 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -3759,9 +3759,9 @@ the configuration (without a prefix: ``Auto``).
   lists.
 
   Important 
diff erences:
-  - No spaces inside the braced list.
-  - No line break before the closing brace.
-  - Indentation with the continuation indent, not with the block indent.
+  * No spaces inside the braced list.
+  * No line break before the closing brace.
+  * Indentation with the continuation indent, not with the block indent.
 
   Fundamentally, C++11 braced lists are formatted exactly like function
   calls would be formatted in their place. If the braced list follows a name
@@ -4104,10 +4104,10 @@ the configuration (without a prefix: ``Auto``).
   When guessing whether a #include is the "main" include (to assign
   category 0, see above), use this regex of allowed suffixes to the header
   stem. A partial match is done, so that:
-  - "" means "arbitrary suffix"
-  - "$" means "no suffix"
+  * ``""`` means "arbitrary suffix"
+  * ``"$"`` means "no suffix"
 
-  For example, if configured to "(_test)?$", then a header a.h would be seen
+  For example, if configured to ``"(_test)?$"``, then a header a.h would be 
seen
   as the "main" include in both a.cc and a_test.cc.
 
 .. _IncludeIsMainSourceRegex:
@@ -5313,21 +5313,21 @@ the configuration (without a prefix: ``Auto``).
 
 **QualifierOrder** (``List of Strings``) :versionbadge:`clang-format 14` 
:ref:`¶ `
   The order in which the qualifiers appear.
-  Order is an array that can contain any of the following:
+  The order is an array that can contain any of the following:
 
-* const
-* inline
-* static
-* friend
-* constexpr
-* volatile
-* restrict
-* type
+* ``const``
+* ``inline``
+* ``static``
+* ``friend``
+* ``constexpr``
+* ``volatile``
+* ``restrict``
+* ``type``
 
 
   .. note::
 
-   It **must** contain ``type``.
+   It must contain ``type``.
 
   Items to the left of ``type`` will be placed to the left of the type and
   aligned in the order supplied. Items to the right of ``type`` will be
@@ -6645,12 +6645,11 @@ the configuration (without a prefix: ``Auto``).
 .. _StatementMacros:
 
 **StatementMacros** (``List of Strings``) :versionbadge:`clang-format 8` 
:ref:`¶ `
-  A vector of macros that should be interpreted as complete
-  statements.
+  A vector of macros that should be interpreted as complete statements.
 
-  Typical macros are expressions, and require a semi-colon to be
-  added; sometimes this is not the case, and this allows to make
-  clang-format aware of such cases.
+  Typical macros are expressions and require a semicolon to be added.
+  Sometimes this is not the case, and this allows to make clang-format aware
+  of such cases.
 
   For example: Q_UNUSED
 

diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 056fad2cc0ff8c..6383934afa2c40 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -2506,9 +2506,9 @@ struct FormatStyle {
   /// lists.
   ///
   /// Important 
diff erences:
-  /// - No spaces inside the braced list.
-  /// - No line break before the closing brace.
-  /// - Indentation with the continuation indent, not with the block indent.
+  /// * No spaces inside the braced list.
+  /// * No line break before the closing brace.
+  /// * Indentation with the continuation indent, not with the block indent.
   ///
   /// Fundamentally, C++11 braced lists are formatted exactly like function
   /// calls would be formatted in their place. If the braced list follows a 
name
@@ -3742,19 +3742,19 @@ struct FormatStyle {
   QualifierAlignmentStyle QualifierAlignment;
 
   /// The order in which the qualifiers appear.
-  /// Order is an array that can contain any of the following:
+  /// The order is an array that can contain any of the following:
   ///
-  ///   * const
-  ///   * inline
-  ///   * static
-  ///   * friend
-  ///   * constexpr
-  ///   * volatile
-  ///   * restrict
-  ///   * type
+  ///   * ``const``
+  ///   * ``inline``
+  ///   * ``static``
+  ///   * ``friend``
+  ///   * ``constexpr``
+  ///   * ``volatile``
+  ///   * ``restrict``
+  ///   * 

[clang] 18760ce - [Clang][AST] Fix PackIndexingExpr AST printout (#117947)

2024-11-28 Thread via cfe-commits

Author: AlexErofeev
Date: 2024-11-29T14:04:25+08:00
New Revision: 18760ce0fd811140fe6cb9a01b766d73bb50bf4d

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

LOG: [Clang][AST] Fix PackIndexingExpr AST printout (#117947)

Fixes #116486 
Also added a test

Added: 
clang/test/AST/ast-print-packindexingexpr.cpp

Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/AST/StmtPrinter.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 601a233b81904f..758a08e6309360 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -771,6 +771,7 @@ Bug Fixes to AST Handling
   and ``relatedalso`` comment commands.
 - Clang now uses the location of the begin of the member expression for 
``CallExpr``
   involving deduced ``this``. (#GH116928)
+- Fixed printout of AST that uses pack indexing expression. (#GH116486)
 
 Miscellaneous Bug Fixes
 ^^^

diff  --git a/clang/lib/AST/StmtPrinter.cpp b/clang/lib/AST/StmtPrinter.cpp
index c8677d11b64e8d..7507c9d14327a0 100644
--- a/clang/lib/AST/StmtPrinter.cpp
+++ b/clang/lib/AST/StmtPrinter.cpp
@@ -2514,7 +2514,10 @@ void StmtPrinter::VisitSizeOfPackExpr(SizeOfPackExpr *E) 
{
 }
 
 void StmtPrinter::VisitPackIndexingExpr(PackIndexingExpr *E) {
-  OS << E->getPackIdExpression() << "...[" << E->getIndexExpr() << "]";
+  PrintExpr(E->getPackIdExpression());
+  OS << "...[";
+  PrintExpr(E->getIndexExpr());
+  OS << "]";
 }
 
 void StmtPrinter::VisitSubstNonTypeTemplateParmPackExpr(

diff  --git a/clang/test/AST/ast-print-packindexingexpr.cpp 
b/clang/test/AST/ast-print-packindexingexpr.cpp
new file mode 100644
index 00..157abeb99436a2
--- /dev/null
+++ b/clang/test/AST/ast-print-packindexingexpr.cpp
@@ -0,0 +1,9 @@
+// RUN: %clang_cc1 -ast-print -std=c++2c %s | FileCheck %s
+
+template 
+auto foo(T ...params) {
+  return params...[N];
+}
+
+// CHECK: template  auto foo(T ...params) {
+// CHECK-NEXT: return params...[N];



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


[clang] [Clang][AST] Fix PackIndexingExpr AST printout (PR #117947)

2024-11-28 Thread Younan Zhang via cfe-commits

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

Thanks

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


[clang] [Clang][AST] Fix PackIndexingExpr AST printout (PR #117947)

2024-11-28 Thread via cfe-commits

github-actions[bot] wrote:



@AlexErofeev Congratulations on having your first Pull Request (PR) merged into 
the LLVM Project!

Your changes will be combined with recent changes from other authors, then 
tested by our [build bots](https://lab.llvm.org/buildbot/). If there is a 
problem with a build, you may receive a report in an email or a comment on this 
PR.

Please check whether problems have been caused by your change specifically, as 
the builds can include changes from many authors. It is not uncommon for your 
change to be included in a build that fails due to someone else's changes, or 
infrastructure issues.

How to do this, and the rest of the post-merge process, is covered in detail 
[here](https://llvm.org/docs/MyFirstTypoFix.html#myfirsttypofix-issues-after-landing-your-pr).

If your change does cause a problem, it may be reverted, or you can revert it 
yourself. This is a normal part of [LLVM 
development](https://llvm.org/docs/DeveloperPolicy.html#patch-reversion-policy).
 You can fix your changes and open a new PR to merge them again.

If you don't get any reports, no action is required from you. Your changes are 
working as expected, well done!


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


[clang] BreakBeforeTemplateClose (PR #118046)

2024-11-28 Thread via cfe-commits

https://github.com/leijurv updated 
https://github.com/llvm/llvm-project/pull/118046

>From b9886635c250fe765bf35c6b0e785f55b0749d52 Mon Sep 17 00:00:00 2001
From: Leijurv 
Date: Thu, 28 Nov 2024 21:44:50 -0600
Subject: [PATCH 1/5] BreakBeforeTemplateClose

---
 clang/docs/ClangFormatStyleOptions.rst | 23 ++
 clang/include/clang/Format/Format.h|  4 
 clang/lib/Format/ContinuationIndenter.cpp  | 22 +
 clang/lib/Format/Format.cpp|  2 ++
 clang/unittests/Format/ConfigParseTest.cpp |  1 +
 clang/unittests/Format/FormatTest.cpp  | 21 
 6 files changed, 73 insertions(+)

diff --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index dc34094b5053a9..b40507b289049d 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -3416,6 +3416,29 @@ the configuration (without a prefix: ``Auto``).
 
 
 
+
+.. _BreakBeforeTemplateClose:
+
+**BreakBeforeTemplateClose** (``Boolean``) :ref:`¶ `
+  If ``true``, a line break will be placed before the ``>`` in a multiline 
template declaration.
+
+  .. code-block:: c++
+
+ true:
+ template <
+ typename Foo,
+ typename Bar,
+ typename Baz
+ >
+
+ false:
+ template <
+ typename Foo,
+ typename Bar,
+ typename Baz>
+
+
+
 .. _BreakBeforeTernaryOperators:
 
 **BreakBeforeTernaryOperators** (``Boolean``) :versionbadge:`clang-format 3.7` 
:ref:`¶ `
diff --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 056fad2cc0ff8c..a8478060828072 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -2248,6 +2248,9 @@ struct FormatStyle {
   /// \version 16
   BreakBeforeInlineASMColonStyle BreakBeforeInlineASMColon;
 
+  /// If ``true``, a line break will be placed before the ``>`` in a multiline 
template declaration.
+  bool BreakBeforeTemplateClose;
+
   /// If ``true``, ternary operators will be placed after line breaks.
   /// \code
   ///true:
@@ -5184,6 +5187,7 @@ struct FormatStyle {
BreakBeforeBraces == R.BreakBeforeBraces &&
BreakBeforeConceptDeclarations == R.BreakBeforeConceptDeclarations 
&&
BreakBeforeInlineASMColon == R.BreakBeforeInlineASMColon &&
+   BreakBeforeTemplateClose == R.BreakBeforeTemplateClose &&
BreakBeforeTernaryOperators == R.BreakBeforeTernaryOperators &&
BreakBinaryOperations == R.BreakBinaryOperations &&
BreakConstructorInitializers == R.BreakConstructorInitializers &&
diff --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index aed86c1fb99551..5887e9cef9011d 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -382,10 +382,28 @@ bool ContinuationIndenter::canBreak(const LineState 
&State) {
   return !State.NoLineBreak && !CurrentState.NoLineBreak;
 }
 
+bool isMatchingBraceOnSameLine(const FormatToken* Token) {
+  if (!Token->MatchingParen) {
+return false;
+  }
+  const FormatToken* Matching = Token->MatchingParen;
+  const FormatToken* Current = Token;
+  while (Current && Current != Matching) {
+if (Current->NewlinesBefore > 0) {
+  return false;
+}
+Current = Current->Previous;
+  }
+  return true;
+}
+
 bool ContinuationIndenter::mustBreak(const LineState &State) {
   const FormatToken &Current = *State.NextToken;
   const FormatToken &Previous = *Current.Previous;
   const auto &CurrentState = State.Stack.back();
+  if (Current.ClosesTemplateDeclaration && Style.BreakBeforeTemplateClose) {
+return !isMatchingBraceOnSameLine(State.NextToken);
+  }
   if (Style.BraceWrapping.BeforeLambdaBody && Current.CanBreakBefore &&
   Current.is(TT_LambdaLBrace) && Previous.isNot(TT_LineComment)) {
 auto LambdaBodyLength = getLengthToMatchingParen(Current, State.Stack);
@@ -1279,6 +1297,10 @@ unsigned ContinuationIndenter::getNewLineColumn(const 
LineState &State) {
   FormatToken &Current = *State.NextToken;
   const auto &CurrentState = State.Stack.back();
 
+  if (Current.ClosesTemplateDeclaration && Style.BreakBeforeTemplateClose) {
+return 0;
+  }
+
   if (CurrentState.IsCSharpGenericTypeConstraint &&
   Current.isNot(TT_CSharpGenericTypeConstraint)) {
 return CurrentState.ColonPos + 2;
diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index ee52972ce66f4a..a957129bbcf440 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -1000,6 +1000,8 @@ template <> struct MappingTraits {
 IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
 IO.mapOptional("BreakBeforeInlineASMColon",
Style.BreakBeforeInlineASMColon);
+IO.mapOptional("BreakBeforeTemplateClose",
+   Style.BreakBeforeTemplateClose);
 IO.mapOptional("BreakBeforeTernaryO

[clang] [llvm] [RISCV] Add Qualcomm uC Xqcisls (Scaled Load Store) extension (PR #117987)

2024-11-28 Thread Craig Topper via cfe-commits

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

LGTM

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


[clang] [Clang][AST] Fix PackIndexingExpr AST printout (PR #117947)

2024-11-28 Thread Younan Zhang via cfe-commits

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


[clang] [Clang] Don't add top-level const qualifiers to captured function types (PR #118050)

2024-11-28 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Younan Zhang (zyn0217)


Changes

This aligns with the logic in `TreeTransform::RebuildQualifiedType()` where we 
refrain from adding const qualifiers to function types. Previously, we seemed 
to overlook this edge case when copy-capturing a variable that is of function 
type within a const-qualified lambda.

This issue also reveals other related problems as in incorrect type printout 
and a suspicious implementation in DeduceTemplateArguments. I decide to leave 
them in follow-up work.

Fixes #84961


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


3 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+1) 
- (modified) clang/lib/Sema/SemaExpr.cpp (+9-2) 
- (modified) clang/test/SemaCXX/lambda-capture-type-deduction.cpp (+14) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 8bd06fadfdc984..553856f3060bc1 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -712,6 +712,7 @@ Bug Fixes to C++ Support
 - Name independent data members were not correctly initialized from default 
member initializers. (#GH114069)
 - Fixed expression transformation for ``[[assume(...)]]``, allowing using pack 
indexing expressions within the
   assumption if they also occur inside of a dependent lambda. (#GH114787)
+- Lambdas now capture function types without considering top-level const 
qualifiers. (#GH84961)
 - Clang now uses valid deduced type locations when diagnosing functions with 
trailing return type
   missing placeholder return type. (#GH78694)
 
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 6c7472ce92703b..04b713a91dedfa 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -18479,7 +18479,10 @@ static bool 
isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI,
 // are mutable in the sense that user can change their value - they are
 // private instances of the captured declarations.
 const Capture &Cap = CSI->getCapture(Var);
-if (Cap.isCopyCapture() &&
+// C++ [dcl.fct]p7:
+//   [When] adding cv-qualifications on top of the function type [...] the
+//   cv-qualifiers are ignored.
+if (Cap.isCopyCapture() && !DeclRefType->isFunctionType() &&
 !(isa(CSI) &&
   !cast(CSI)->lambdaCaptureShouldBeConst()) &&
 !(isa(CSI) &&
@@ -18789,7 +18792,11 @@ static bool captureInLambda(LambdaScopeInfo *LSI, 
ValueDecl *Var,
 //   parameter-declaration-clause is not followed by mutable.
 DeclRefType = CaptureType.getNonReferenceType();
 bool Const = LSI->lambdaCaptureShouldBeConst();
-if (Const && !CaptureType->isReferenceType())
+// C++ [dcl.fct]p7:
+//   [When] adding cv-qualifications on top of the function type [...] the
+//   cv-qualifiers are ignored.
+if (Const && !CaptureType->isReferenceType() &&
+!DeclRefType->isFunctionType())
   DeclRefType.addConst();
   }
 
diff --git a/clang/test/SemaCXX/lambda-capture-type-deduction.cpp 
b/clang/test/SemaCXX/lambda-capture-type-deduction.cpp
index a86f3018989927..ba7ab34f943be1 100644
--- a/clang/test/SemaCXX/lambda-capture-type-deduction.cpp
+++ b/clang/test/SemaCXX/lambda-capture-type-deduction.cpp
@@ -319,3 +319,17 @@ constexpr void foo() {
 }
 
 } // namespace GH47400
+
+namespace GH84961 {
+
+template  void g(const T &t) {}
+
+template  void f(const T &t) {
+  [t] { g(t); }();
+}
+
+void h() {
+  f(h);
+}
+
+} // namespace GH84961

``




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


[clang] [Clang] Don't add top-level const qualifiers to captured function types (PR #118050)

2024-11-28 Thread Younan Zhang via cfe-commits

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


[clang] [analyzer] Modernize, improve and promote chroot checker (PR #117791)

2024-11-28 Thread Balazs Benics via cfe-commits

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


[clang] e034c4e - [analyzer] Modernize, improve and promote chroot checker (#117791)

2024-11-28 Thread via cfe-commits

Author: vabridgers
Date: 2024-11-29T08:23:08+01:00
New Revision: e034c4ef7b52635bb9cc78b6d3f97a4af5002f92

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

LOG: [analyzer] Modernize, improve and promote chroot checker (#117791)

This change modernizes, improves and promotes the chroot checker from
alpha to the Unix family of checkers. This checker covers the POS05
recommendations for use of chroot.

The improvements included modeling of a success or failure from chroot
and not falsely reporting a warning along an error path. This was made
possible through modernizing the checker to be flow sensitive.

-

Co-authored-by: einvbri 
Co-authored-by: Balazs Benics 

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/docs/analyzer/checkers.rst
clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
clang/lib/StaticAnalyzer/Checkers/ChrootChecker.cpp
clang/test/Analysis/analyzer-enabled-checkers.c
clang/test/Analysis/chroot.c
clang/test/Analysis/show-checker-list.c
clang/test/Analysis/std-c-library-functions-arg-enabled-checkers.c

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 758a08e6309360..102ffb56fec35f 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -1024,6 +1024,16 @@ Moved checkers
   original checkers were implemented only using AST matching and make more
   sense as a single clang-tidy check.
 
+- The checker ``alpha.unix.Chroot`` was modernized, improved and moved to
+  ``unix.Chroot``. Testing was done on open source projects that use chroot(),
+  and false issues addressed in the improvements based on real use cases. Open
+  source projects used for testing include nsjail, lxroot, dive and ruri.
+  This checker conforms to SEI Cert C recommendation `POS05-C. Limit access to
+  files by creating a jail
+  
`_.
+  Fixes (#GH34697).
+  (#GH117791) 
[Documentation](https://clang.llvm.org/docs/analyzer/checkers.html#unix-chroot-c).
+
 .. _release-notes-sanitizers:
 
 Sanitizers

diff  --git a/clang/docs/analyzer/checkers.rst 
b/clang/docs/analyzer/checkers.rst
index 401d8dcb4e7f02..cbbdc6345c116b 100644
--- a/clang/docs/analyzer/checkers.rst
+++ b/clang/docs/analyzer/checkers.rst
@@ -1750,6 +1750,37 @@ Critical section handling functions modeled by this 
checker:
}
  }
 
+.. _unix-Chroot:
+
+unix.Chroot (C)
+"""
+Check improper use of chroot described by SEI Cert C recommendation `POS05-C.
+Limit access to files by creating a jail
+`_.
+The checker finds usage patterns where ``chdir("/")`` is not called immediately
+after a call to ``chroot(path)``.
+
+.. code-block:: c
+
+ void f();
+
+ void test_bad() {
+   chroot("/usr/local");
+   f(); // warn: no call of chdir("/") immediately after chroot
+ }
+
+  void test_bad_path() {
+chroot("/usr/local");
+chdir("/usr"); // warn: no call of chdir("/") immediately after chroot
+f();
+  }
+
+ void test_good() {
+   chroot("/usr/local");
+   chdir("/"); // no warning
+   f();
+ }
+
 .. _unix-Errno:
 
 unix.Errno (C)
@@ -3298,21 +3329,6 @@ SEI CERT checkers which tries to find errors based on 
their `C coding rules ,
   HelpText<"Check for proper usage of vfork">,
   Documentation;
 
-} // end "unix"
-
-let ParentPackage = UnixAlpha in {
-
 def ChrootChecker : Checker<"Chroot">,
   HelpText<"Check improper use of chroot">,
   Documentation;
 
+} // end "unix"
+
+let ParentPackage = UnixAlpha in {
+
 def PthreadLockChecker : Checker<"PthreadLock">,
   HelpText<"Simple lock -> unlock checker">,
   Dependencies<[PthreadLockBase]>,

diff  --git a/clang/lib/StaticAnalyzer/Checkers/ChrootChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/ChrootChecker.cpp
index 3a0a01c23de03e..99fc0a953ef178 100644
--- a/clang/lib/StaticAnalyzer/Checkers/ChrootChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/ChrootChecker.cpp
@@ -7,9 +7,13 @@
 
//===--===//
 //
 //  This file defines chroot checker, which checks improper use of chroot.
+//  This is described by the SEI Cert C rule POS05-C.
+//  The checker is a warning not a hard failure since it only checks for a
+//  recommended rule.
 //
 
//===--===//
 
+#include "clang/AST/ASTContext.h"
 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
@@ -25,94 +29,128 @@ using namespace clang;
 using namespace ento;
 
 namespace 

[clang] [llvm] [InstCombine] Fold `X Pred C2 ? X BOp C1 : C2 BOp C1` to `min/max(X, C2) BOp C1` (PR #116888)

2024-11-28 Thread Yingwei Zheng via cfe-commits


@@ -1898,6 +1882,56 @@ static Instruction *foldSelectICmpEq(SelectInst &SI, 
ICmpInst *ICI,
   return nullptr;
 }
 
+/// Fold `X Pred C2 ? X BOp C1 : C2 BOp C1` to `min/max(X, C2) BOp C1`.
+/// This allows for better canonicalization.
+static Value *foldSelectWithConstOpToBinOp(ICmpInst *Cmp, Value *TrueVal,
+   Value *FalseVal,
+   IRBuilderBase &Builder) {
+  BinaryOperator *BOp;
+  Constant *C1, *C2, *C3;
+  Value *X;
+  ICmpInst::Predicate Predicate;
+
+  if (!match(Cmp, m_ICmp(Predicate, m_Value(X), m_Constant(C1
+return nullptr;
+
+  if (!ICmpInst::isRelational(Predicate))
+return nullptr;
+
+  if (match(TrueVal, m_Constant())) {
+std::swap(FalseVal, TrueVal);
+Predicate = ICmpInst::getInversePredicate(Predicate);
+  }
+
+  if (!match(TrueVal, m_BinOp(BOp)) || !match(FalseVal, m_Constant(C3)))
+return nullptr;
+
+  if (!match(BOp, m_OneUse(m_BinOp(m_Specific(X), m_Constant(C2)
+return nullptr;
+
+  Value *RHS;
+  SelectPatternFlavor SPF;
+  unsigned Opcode = BOp->getOpcode();
+  const DataLayout Layout = BOp->getDataLayout();

dtcxzyw wrote:

```suggestion
  const DataLayout &Layout = BOp->getDataLayout();
```


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


[clang] Fix generation of wasm binaries while running clang-repl in browser (PR #117978)

2024-11-28 Thread Anutosh Bhat via cfe-commits

https://github.com/anutosh491 created 
https://github.com/llvm/llvm-project/pull/117978

None

>From 987f77db9d45dee264c60f434652131438784f6f Mon Sep 17 00:00:00 2001
From: anutosh491 
Date: Thu, 28 Nov 2024 14:02:00 +0530
Subject: [PATCH] Fix generation of wasm binaries while running clang-repl in
 browser

---
 clang/lib/Interpreter/CMakeLists.txt  |  2 +
 clang/lib/Interpreter/Interpreter.cpp |  1 +
 clang/lib/Interpreter/Wasm.cpp| 57 ---
 3 files changed, 45 insertions(+), 15 deletions(-)

diff --git a/clang/lib/Interpreter/CMakeLists.txt 
b/clang/lib/Interpreter/CMakeLists.txt
index df7ea82e0dada5..bf70cdfbee01e1 100644
--- a/clang/lib/Interpreter/CMakeLists.txt
+++ b/clang/lib/Interpreter/CMakeLists.txt
@@ -16,6 +16,7 @@ set(LLVM_LINK_COMPONENTS
 if (EMSCRIPTEN AND "lld" IN_LIST LLVM_ENABLE_PROJECTS)
   set(WASM_SRC Wasm.cpp)
   set(WASM_LINK lldWasm)
+  set(COMMON_LINK lldCommon)
 endif()
 
 add_clang_library(clangInterpreter
@@ -47,6 +48,7 @@ add_clang_library(clangInterpreter
   clangSema
   clangSerialization
   ${WASM_LINK}
+  ${COMMON_LINK}
   )
 
 if ((MINGW OR CYGWIN) AND BUILD_SHARED_LIBS)
diff --git a/clang/lib/Interpreter/Interpreter.cpp 
b/clang/lib/Interpreter/Interpreter.cpp
index 5dc67f6375098f..887b494ff98f19 100644
--- a/clang/lib/Interpreter/Interpreter.cpp
+++ b/clang/lib/Interpreter/Interpreter.cpp
@@ -201,6 +201,7 @@ IncrementalCompilerBuilder::CreateCpp() {
   Argv.push_back("-target");
   Argv.push_back("wasm32-unknown-emscripten");
   Argv.push_back("-shared");
+  Argv.push_back("-fvisibility=default");
 #endif
   Argv.insert(Argv.end(), UserArgs.begin(), UserArgs.end());
 
diff --git a/clang/lib/Interpreter/Wasm.cpp b/clang/lib/Interpreter/Wasm.cpp
index 79efbaa03982d0..0fd6ad509c2938 100644
--- a/clang/lib/Interpreter/Wasm.cpp
+++ b/clang/lib/Interpreter/Wasm.cpp
@@ -23,6 +23,31 @@
 #include 
 
 namespace lld {
+enum Flavor {
+  Invalid,
+  Gnu, // -flavor gnu
+  MinGW,   // -flavor gnu MinGW
+  WinLink, // -flavor link
+  Darwin,  // -flavor darwin
+  Wasm,// -flavor wasm
+};
+
+using Driver = bool (*)(llvm::ArrayRef, llvm::raw_ostream &,
+llvm::raw_ostream &, bool, bool);
+
+struct DriverDef {
+  Flavor f;
+  Driver d;
+};
+
+struct Result {
+int retCode;
+bool canRunAgain;
+};
+
+Result lldMain(llvm::ArrayRef args, llvm::raw_ostream &stdoutOS,
+llvm::raw_ostream &stderrOS, llvm::ArrayRef 
drivers);
+
 namespace wasm {
 bool link(llvm::ArrayRef args, llvm::raw_ostream &stdoutOS,
   llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput);
@@ -51,45 +76,47 @@ llvm::Error 
WasmIncrementalExecutor::addModule(PartialTranslationUnit &PTU) {
   llvm::TargetMachine *TargetMachine = Target->createTargetMachine(
   PTU.TheModule->getTargetTriple(), "", "", TO, llvm::Reloc::Model::PIC_);
   PTU.TheModule->setDataLayout(TargetMachine->createDataLayout());
-  std::string OutputFileName = PTU.TheModule->getName().str() + ".wasm";
+  std::string ObjectFileName = PTU.TheModule->getName().str() + ".o";  // For 
the wasm object
+  std::string BinaryFileName = PTU.TheModule->getName().str() + ".wasm";  // 
For the wasm binary
 
   std::error_code Error;
-  llvm::raw_fd_ostream OutputFile(llvm::StringRef(OutputFileName), Error);
+  llvm::raw_fd_ostream ObjectFileOutput(llvm::StringRef(ObjectFileName), 
Error);
 
   llvm::legacy::PassManager PM;
-  if (TargetMachine->addPassesToEmitFile(PM, OutputFile, nullptr,
+  if (TargetMachine->addPassesToEmitFile(PM, ObjectFileOutput, nullptr,
  llvm::CodeGenFileType::ObjectFile)) {
 return llvm::make_error(
 "Wasm backend cannot produce object.", llvm::inconvertibleErrorCode());
   }
 
   if (!PM.run(*PTU.TheModule)) {
-
 return llvm::make_error("Failed to emit Wasm object.",
llvm::inconvertibleErrorCode());
   }
 
-  OutputFile.close();
+  ObjectFileOutput.close();
 
   std::vector LinkerArgs = {"wasm-ld",
   "-shared",
   "--import-memory",
-  "--no-entry",
-  "--export-all",
   "--experimental-pic",
   "--stack-first",
   "--allow-undefined",
-  OutputFileName.c_str(),
+  ObjectFileName.c_str(),
   "-o",
-  OutputFileName.c_str()};
-  int Result =
-  lld::wasm::link(LinkerArgs, llvm::outs(), llvm::errs(), false, false);
-  if (!Result)
+  BinaryFileName.c_str()};
+
+  const lld::DriverDef WasmDriver = {lld::Flavor::Wasm, &lld::wasm::link};
+  std::vector WasmDriverA

[clang] [clang] Add a lifetime_capture_by testcase for temporary capturing object. (PR #117733)

2024-11-28 Thread Utkarsh Saxena via cfe-commits

usx95 wrote:

>  We could potentially limit the suppression to cases where the destructor is 
> trivial, but that might not be worth the added complexity.
I agree that might not be worth the complexity. Let's revisit if we have 
practical false positives.

Thanks for the tests. LGTM.

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


[clang-tools-extra] [clangd] Support symbolTags for document symbol (PR #113669)

2024-11-28 Thread via cfe-commits

chouzz wrote:



Hi, @travkin79 that sounds great. I tried to build clangd from [my github 
action](https://github.com/chouzz/clangd/actions/workflows/autobuild.yaml), but 
I failed, maybe @HighCommander4 could help point out how to build clangd via 
github actions with specify branch?

> It seems, there is one failing test in the CI pipeline. Could you try fixing 
> it?

I will check.
 

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


[clang] 0604d13 - [Clang] Add [[clang::no_specializations]] (#101469)

2024-11-28 Thread via cfe-commits

Author: Nikolas Klauser
Date: 2024-11-28T10:13:18+01:00
New Revision: 0604d13790b20f6b385507bb63c62aa87162da9b

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

LOG: [Clang] Add [[clang::no_specializations]] (#101469)

This can be used to inform users when a template should not be
specialized. For example, this is the case for the standard type traits
(except for `common_type` and `common_reference`, which have more
complicated rules).

Added: 
clang/test/SemaCXX/attr-no-specializations.cpp

Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/Attr.td
clang/include/clang/Basic/AttrDocs.td
clang/include/clang/Basic/DiagnosticGroups.td
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/SemaDeclAttr.cpp
clang/lib/Sema/SemaTemplate.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 70227a6248afad..2ecd19bdc39448 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -473,6 +473,11 @@ Attribute Changes in Clang
 - The ``hybrid_patchable`` attribute is now supported on ARM64EC targets. It 
can be used to specify
   that a function requires an additional x86-64 thunk, which may be patched at 
runtime.
 
+- The attribute ``[[clang::no_specializations]]`` has been added to warn
+  users that a specific template shouldn't be specialized. This is useful for
+  e.g. standard library type traits, where adding a specialization results in
+  undefined behaviour.
+
 - ``[[clang::lifetimebound]]`` is now explicitly disallowed on explicit object 
member functions
   where they were previously silently ignored.
 

diff  --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index b055cbd769bb50..425b72d4729f13 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -103,6 +103,9 @@ def NonParmVar : SubsetSubjecthasLocalStorage()}],
 "variables with non-local storage">;
+def VarTmpl : SubsetSubjectgetDescribedVarTemplate()}],
+"variable templates">;
+
 def NonBitField : SubsetSubjectisBitField()}],
 "non-bit-field non-static data members">;
@@ -3428,6 +3431,15 @@ def DiagnoseIf : InheritableAttr {
   let Documentation = [DiagnoseIfDocs];
 }
 
+def NoSpecializations : InheritableAttr {
+  let Spellings = [Clang<"no_specializations", /*AllowInC*/0>];
+  let Args = [StringArgument<"Message", 1>];
+  let Subjects = SubjectList<[ClassTmpl, FunctionTmpl, VarTmpl]>;
+  let Documentation = [NoSpecializationsDocs];
+  let MeaningfulToClassTemplateDefinition = 1;
+  let TemplateDependent = 1;
+}
+
 def ArcWeakrefUnavailable : InheritableAttr {
   let Spellings = [Clang<"objc_arc_weak_reference_unavailable">];
   let Subjects = SubjectList<[ObjCInterface], ErrorDiag>;

diff  --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index aafd4449e47004..9617687ac69caf 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -1155,6 +1155,15 @@ Query for this feature with 
``__has_attribute(diagnose_if)``.
   }];
 }
 
+def NoSpecializationsDocs : Documentation {
+  let Category = DocCatDecl;
+  let Content = [{
+``[[clang::no_specializations]]`` can be applied to function, class, or 
variable
+templates which should not be explicitly specialized by users. This is 
primarily
+used to diagnose user specializations of standard library type traits.
+  }];
+}
+
 def PassObjectSizeDocs : Documentation {
   let Category = DocCatVariable; // Technically it's a parameter doc, but eh.
   let Heading = "pass_object_size, pass_dynamic_object_size";

diff  --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index df9bf94b5d0398..8f3c4872e67608 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -1589,4 +1589,3 @@ def ExplicitSpecializationStorageClass : 
DiagGroup<"explicit-specialization-stor
 
 // A warning for options that enable a feature that is not yet complete
 def ExperimentalOption : DiagGroup<"experimental-option">;
-

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index a6c5c5806c33f2..316374f92b7daf 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -5445,6 +5445,10 @@ def note_dependent_function_template_spec_discard_reason 
: Note<
   "candidate ignored: %select{not a function template|"
   "not a member of the enclosing %select{class template|"
   "namespace; did you mean to explicitly qualify the specialization?}1}0">;
+def warn_

[clang] [Clang] Add [[clang::no_specializations]] (PR #101469)

2024-11-28 Thread Nikolas Klauser via cfe-commits

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


[clang] [clang] Improve the lifetime_capture_by diagnostic on the constructor. (PR #117792)

2024-11-28 Thread Haojian Wu via cfe-commits

https://github.com/hokein updated 
https://github.com/llvm/llvm-project/pull/117792

>From edd8e7354c4ff96446d32830f4cd5e6c3c333a84 Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Tue, 26 Nov 2024 21:42:45 +0100
Subject: [PATCH 1/2] [clang] Improve the lifetime_capture_by diagnostic on the
 constructor.

---
 clang/lib/Sema/CheckExprLifetime.cpp  | 11 +++
 clang/lib/Sema/SemaChecking.cpp   |  6 ++
 .../warn-lifetime-analysis-capture-by.cpp | 19 +++
 3 files changed, 36 insertions(+)

diff --git a/clang/lib/Sema/CheckExprLifetime.cpp 
b/clang/lib/Sema/CheckExprLifetime.cpp
index 6cdd4dc629e50a..c4fa73127410b5 100644
--- a/clang/lib/Sema/CheckExprLifetime.cpp
+++ b/clang/lib/Sema/CheckExprLifetime.cpp
@@ -535,6 +535,9 @@ static void visitFunctionCallArguments(IndirectLocalPath 
&Path, Expr *Call,
 
   bool EnableGSLAnalysis = !Callee->getASTContext().getDiagnostics().isIgnored(
   diag::warn_dangling_lifetime_pointer, SourceLocation());
+  bool EnableDanglingCapture =
+  !Callee->getASTContext().getDiagnostics().isIgnored(
+  diag::warn_dangling_reference_captured, SourceLocation());
   Expr *ObjectArg = nullptr;
   if (isa(Call) && Callee->isCXXInstanceMember()) {
 ObjectArg = Args[0];
@@ -623,6 +626,14 @@ static void visitFunctionCallArguments(IndirectLocalPath 
&Path, Expr *Call,
 }
 if (CheckCoroCall || Callee->getParamDecl(I)->hasAttr())
   VisitLifetimeBoundArg(Callee->getParamDecl(I), Arg);
+else if (const auto *CaptureAttr =
+ Callee->getParamDecl(I)->getAttr();
+ EnableDanglingCapture && CaptureAttr &&
+ isa(Callee) &&
+ llvm::any_of(CaptureAttr->params(), [](int ArgIdx) {
+   return ArgIdx == LifetimeCaptureByAttr::THIS;
+ }))
+  VisitLifetimeBoundArg(Callee->getParamDecl(I), Arg);
 else if (EnableGSLAnalysis && I == 0) {
   // Perform GSL analysis for the first argument
   if (shouldTrackFirstArgument(Callee)) {
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index a49605e4867651..1605523097a6b1 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -3240,8 +3240,14 @@ void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool 
IsMemberFunction,
  unsigned ArgIdx) {
 if (!Attr)
   return;
+
 Expr *Captured = const_cast(GetArgAt(ArgIdx));
 for (int CapturingParamIdx : Attr->params()) {
+  // lifetime_capture_by(this) case is handled in the lifetimebound expr
+  // initialization codepath.
+  if (CapturingParamIdx == LifetimeCaptureByAttr::THIS &&
+  isa(FD))
+continue;
   Expr *Capturing = const_cast(GetArgAt(CapturingParamIdx));
   CapturingEntity CE{Capturing};
   // Ensure that 'Captured' outlives the 'Capturing' entity.
diff --git a/clang/test/Sema/warn-lifetime-analysis-capture-by.cpp 
b/clang/test/Sema/warn-lifetime-analysis-capture-by.cpp
index 4d562bac1e305b..77523210e50203 100644
--- a/clang/test/Sema/warn-lifetime-analysis-capture-by.cpp
+++ b/clang/test/Sema/warn-lifetime-analysis-capture-by.cpp
@@ -411,3 +411,22 @@ void use() {
 }
 } // namespace with_span
 } // namespace inferred_capture_by
+
+namespace on_constructor {
+struct T {
+  T(const int& t [[clang::lifetime_capture_by(this)]]);
+};
+struct T2 {
+  T2(const int& t [[clang::lifetime_capture_by(x)]], int& x);
+};
+int foo(const T& t);
+
+void test() {
+  auto x = foo(T(1)); // OK. no diagnosic
+  T(1); // OK. no diagnostic
+  T t(1); // expected-warning {{temporary whose address is used}}
+
+  int a;
+  T2(1, a); // expected-warning {{object whose reference is captured by}}
+}
+} // namespace on_constructor

>From da5e551cc486880896ebfbe8b6e7e5e51de71f8b Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Thu, 28 Nov 2024 10:12:40 +0100
Subject: [PATCH 2/2] Address comments

---
 clang/lib/Sema/CheckExprLifetime.cpp  | 19 ++-
 .../warn-lifetime-analysis-capture-by.cpp |  2 ++
 2 files changed, 16 insertions(+), 5 deletions(-)

diff --git a/clang/lib/Sema/CheckExprLifetime.cpp 
b/clang/lib/Sema/CheckExprLifetime.cpp
index c4fa73127410b5..607b7daf878e17 100644
--- a/clang/lib/Sema/CheckExprLifetime.cpp
+++ b/clang/lib/Sema/CheckExprLifetime.cpp
@@ -535,9 +535,6 @@ static void visitFunctionCallArguments(IndirectLocalPath 
&Path, Expr *Call,
 
   bool EnableGSLAnalysis = !Callee->getASTContext().getDiagnostics().isIgnored(
   diag::warn_dangling_lifetime_pointer, SourceLocation());
-  bool EnableDanglingCapture =
-  !Callee->getASTContext().getDiagnostics().isIgnored(
-  diag::warn_dangling_reference_captured, SourceLocation());
   Expr *ObjectArg = nullptr;
   if (isa(Call) && Callee->isCXXInstanceMember()) {
 ObjectArg = Args[0];
@@ -628,11 +625,23 @@ static void visitFunctionCallArguments(IndirectLocalPath 
&Path, Expr *Call,
   VisitLifetimeBoundArg(Cal

[clang] [clang] Check specialization for annotation (PR #117315)

2024-11-28 Thread Utkarsh Saxena via cfe-commits


@@ -253,9 +253,12 @@ static void 
visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
   LocalVisitor Visit);
 
 template  static bool isRecordWithAttr(QualType Type) {
-  if (auto *RD = Type->getAsCXXRecordDecl())
-return RD->hasAttr();
-  return false;
+  auto *RD = Type->getAsCXXRecordDecl();
+  if (!RD)
+return false;
+  if (auto *CTSD = dyn_cast(RD))
+RD = CTSD->getSpecializedTemplate()->getTemplatedDecl();

usx95 wrote:

Moved to Sema.h.

It seems hard to find a test for it though.

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


[clang] [clang] Improve the lifetime_capture_by diagnostic on the constructor. (PR #117792)

2024-11-28 Thread Haojian Wu via cfe-commits


@@ -535,6 +535,9 @@ static void visitFunctionCallArguments(IndirectLocalPath 
&Path, Expr *Call,
 
   bool EnableGSLAnalysis = !Callee->getASTContext().getDiagnostics().isIgnored(
   diag::warn_dangling_lifetime_pointer, SourceLocation());
+  bool EnableDanglingCapture =
+  !Callee->getASTContext().getDiagnostics().isIgnored(
+  diag::warn_dangling_reference_captured, SourceLocation());

hokein wrote:

Done. I added some comments to clarify the behavior.

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


[clang] [clang] Improve the lifetime_capture_by diagnostic on the constructor. (PR #117792)

2024-11-28 Thread Haojian Wu via cfe-commits

https://github.com/hokein updated 
https://github.com/llvm/llvm-project/pull/117792

>From edd8e7354c4ff96446d32830f4cd5e6c3c333a84 Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Tue, 26 Nov 2024 21:42:45 +0100
Subject: [PATCH 1/2] [clang] Improve the lifetime_capture_by diagnostic on the
 constructor.

---
 clang/lib/Sema/CheckExprLifetime.cpp  | 11 +++
 clang/lib/Sema/SemaChecking.cpp   |  6 ++
 .../warn-lifetime-analysis-capture-by.cpp | 19 +++
 3 files changed, 36 insertions(+)

diff --git a/clang/lib/Sema/CheckExprLifetime.cpp 
b/clang/lib/Sema/CheckExprLifetime.cpp
index 6cdd4dc629e50a..c4fa73127410b5 100644
--- a/clang/lib/Sema/CheckExprLifetime.cpp
+++ b/clang/lib/Sema/CheckExprLifetime.cpp
@@ -535,6 +535,9 @@ static void visitFunctionCallArguments(IndirectLocalPath 
&Path, Expr *Call,
 
   bool EnableGSLAnalysis = !Callee->getASTContext().getDiagnostics().isIgnored(
   diag::warn_dangling_lifetime_pointer, SourceLocation());
+  bool EnableDanglingCapture =
+  !Callee->getASTContext().getDiagnostics().isIgnored(
+  diag::warn_dangling_reference_captured, SourceLocation());
   Expr *ObjectArg = nullptr;
   if (isa(Call) && Callee->isCXXInstanceMember()) {
 ObjectArg = Args[0];
@@ -623,6 +626,14 @@ static void visitFunctionCallArguments(IndirectLocalPath 
&Path, Expr *Call,
 }
 if (CheckCoroCall || Callee->getParamDecl(I)->hasAttr())
   VisitLifetimeBoundArg(Callee->getParamDecl(I), Arg);
+else if (const auto *CaptureAttr =
+ Callee->getParamDecl(I)->getAttr();
+ EnableDanglingCapture && CaptureAttr &&
+ isa(Callee) &&
+ llvm::any_of(CaptureAttr->params(), [](int ArgIdx) {
+   return ArgIdx == LifetimeCaptureByAttr::THIS;
+ }))
+  VisitLifetimeBoundArg(Callee->getParamDecl(I), Arg);
 else if (EnableGSLAnalysis && I == 0) {
   // Perform GSL analysis for the first argument
   if (shouldTrackFirstArgument(Callee)) {
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index a49605e4867651..1605523097a6b1 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -3240,8 +3240,14 @@ void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool 
IsMemberFunction,
  unsigned ArgIdx) {
 if (!Attr)
   return;
+
 Expr *Captured = const_cast(GetArgAt(ArgIdx));
 for (int CapturingParamIdx : Attr->params()) {
+  // lifetime_capture_by(this) case is handled in the lifetimebound expr
+  // initialization codepath.
+  if (CapturingParamIdx == LifetimeCaptureByAttr::THIS &&
+  isa(FD))
+continue;
   Expr *Capturing = const_cast(GetArgAt(CapturingParamIdx));
   CapturingEntity CE{Capturing};
   // Ensure that 'Captured' outlives the 'Capturing' entity.
diff --git a/clang/test/Sema/warn-lifetime-analysis-capture-by.cpp 
b/clang/test/Sema/warn-lifetime-analysis-capture-by.cpp
index 4d562bac1e305b..77523210e50203 100644
--- a/clang/test/Sema/warn-lifetime-analysis-capture-by.cpp
+++ b/clang/test/Sema/warn-lifetime-analysis-capture-by.cpp
@@ -411,3 +411,22 @@ void use() {
 }
 } // namespace with_span
 } // namespace inferred_capture_by
+
+namespace on_constructor {
+struct T {
+  T(const int& t [[clang::lifetime_capture_by(this)]]);
+};
+struct T2 {
+  T2(const int& t [[clang::lifetime_capture_by(x)]], int& x);
+};
+int foo(const T& t);
+
+void test() {
+  auto x = foo(T(1)); // OK. no diagnosic
+  T(1); // OK. no diagnostic
+  T t(1); // expected-warning {{temporary whose address is used}}
+
+  int a;
+  T2(1, a); // expected-warning {{object whose reference is captured by}}
+}
+} // namespace on_constructor

>From 48487a5b1f9b87c295ce1d6df7d0fc60a7db6695 Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Thu, 28 Nov 2024 10:12:40 +0100
Subject: [PATCH 2/2] Address comments

---
 clang/lib/Sema/CheckExprLifetime.cpp  | 19 ++-
 .../warn-lifetime-analysis-capture-by.cpp |  7 +++
 2 files changed, 21 insertions(+), 5 deletions(-)

diff --git a/clang/lib/Sema/CheckExprLifetime.cpp 
b/clang/lib/Sema/CheckExprLifetime.cpp
index c4fa73127410b5..607b7daf878e17 100644
--- a/clang/lib/Sema/CheckExprLifetime.cpp
+++ b/clang/lib/Sema/CheckExprLifetime.cpp
@@ -535,9 +535,6 @@ static void visitFunctionCallArguments(IndirectLocalPath 
&Path, Expr *Call,
 
   bool EnableGSLAnalysis = !Callee->getASTContext().getDiagnostics().isIgnored(
   diag::warn_dangling_lifetime_pointer, SourceLocation());
-  bool EnableDanglingCapture =
-  !Callee->getASTContext().getDiagnostics().isIgnored(
-  diag::warn_dangling_reference_captured, SourceLocation());
   Expr *ObjectArg = nullptr;
   if (isa(Call) && Callee->isCXXInstanceMember()) {
 ObjectArg = Args[0];
@@ -628,11 +625,23 @@ static void visitFunctionCallArguments(IndirectLocalPath 
&Path, Expr *Call,
   VisitLifetimeBoundAr

[clang] [clang] Improve the lifetime_capture_by diagnostic on the constructor. (PR #117792)

2024-11-28 Thread Haojian Wu via cfe-commits


@@ -411,3 +411,22 @@ void use() {
 }
 } // namespace with_span
 } // namespace inferred_capture_by
+
+namespace on_constructor {
+struct T {
+  T(const int& t [[clang::lifetime_capture_by(this)]]);
+};
+struct T2 {
+  T2(const int& t [[clang::lifetime_capture_by(x)]], int& x);
+};
+int foo(const T& t);

hokein wrote:

Done.

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


[clang] [clang] Add a lifetime_capture_by testcase for temporary capturing object. (PR #117733)

2024-11-28 Thread Haojian Wu via cfe-commits

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


[clang] 2c242b9 - [clang] Add a lifetime_capture_by testcase for temporary capturing object. (#117733)

2024-11-28 Thread via cfe-commits

Author: Haojian Wu
Date: 2024-11-28T10:17:41+01:00
New Revision: 2c242b98c608021e6768f0369498f5b8b5144d34

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

LOG: [clang] Add a lifetime_capture_by testcase for temporary capturing object. 
(#117733)

Add a test case to indicate this is an expected behavior.

Added: 


Modified: 
clang/test/Sema/warn-lifetime-analysis-capture-by.cpp

Removed: 




diff  --git a/clang/test/Sema/warn-lifetime-analysis-capture-by.cpp 
b/clang/test/Sema/warn-lifetime-analysis-capture-by.cpp
index 4d562bac1e305b..e867296d6d8ea7 100644
--- a/clang/test/Sema/warn-lifetime-analysis-capture-by.cpp
+++ b/clang/test/Sema/warn-lifetime-analysis-capture-by.cpp
@@ -143,6 +143,20 @@ void use() {
 }
 } // namespace this_is_captured
 
+namespace temporary_capturing_object {
+struct S {
+  void add(const int& x [[clang::lifetime_capture_by(this)]]);
+};
+
+void test() {
+  // We still give an warning even the capturing object is a temoprary.
+  // It is possible that the capturing object uses the captured object in its
+  // destructor.
+  S().add(1); // expected-warning {{object whose reference is captured}}
+  S{}.add(1); // expected-warning {{object whose reference is captured}}
+}
+} // namespace ignore_temporary_class_object
+
 // 
 // Capture by Global and Unknown.
 // 



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


[clang] [clang] Move warning about memset/memcpy to NonTriviallyCopyable type… (PR #117387)

2024-11-28 Thread via cfe-commits


@@ -0,0 +1,27 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -std=c++11 -Wnontrivial-memcall %s
+
+extern "C" void *memcpy(void *s1, const void *s2, unsigned n);
+
+class TriviallyCopyable {};
+class NonTriviallyCopyable { NonTriviallyCopyable(const 
NonTriviallyCopyable&);};
+struct Incomplete;
+
+void test_memcpy(TriviallyCopyable* tc0, TriviallyCopyable* tc1,
+ NonTriviallyCopyable *ntc0, NonTriviallyCopyable *ntc1,
+ Incomplete *i0, Incomplete *i1) {
+  // OK
+  memcpy(tc0, tc1, sizeof(*tc0));
+
+  // OK
+  memcpy(i0, i1, 10);
+
+  // expected-warning@+2{{first argument in call to 'memcpy' is a pointer to 
non-trivially copyable type 'NonTriviallyCopyable'}}
+  // expected-note@+1{{explicitly cast the pointer to silence this warning}}
+  memcpy(ntc0, ntc1, sizeof(*ntc0));
+
+  // ~ OK
+  memcpy((void*)ntc0, ntc1, sizeof(*ntc0));
+
+  // OK
+  memcpy((void*)ntc0, (void*)ntc1, sizeof(*ntc0));
+}

zmodem wrote:

But it looks to me that clang/test/SemaCXX/warn-memaccess.cpp also only covers 
-Wnontrivial-memcall, i.e. it's just checking calls to 
bzero/memset/memmove/memcpy. Can you just change the flag there?

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


[clang] [Clang][AST] Fix MS Mangle concept uneval context template instantiation crash (PR #117845)

2024-11-28 Thread via cfe-commits

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

The fix LGTM. I do wonder if the test should live in CodeGen/ instead, but I 
don't have a strong feeling about this (AST/ already seems to have some codegen 
tests).

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


[clang] [clang] Check specialization for annotation (PR #117315)

2024-11-28 Thread Haojian Wu via cfe-commits


@@ -1763,6 +1763,18 @@ class Sema final : public SemaBase {
   /// Add [[gsl::Pointer]] attributes for std:: types.
   void inferGslPointerAttribute(TypedefNameDecl *TD);
 
+  template  static bool isRecordWithAttr(QualType Type) {

hokein wrote:

I'd avoid expose this function if possible (as it seems only be used in 
`CheckExprLifetime.cpp` and `isPointerLikeType`). How about?

- we just keep the `isPointerLikeType` declaration in Sema.h
- define `isPointerLikeType` in `CheckExprLifetime.cpp`
- the `isRecordWithAttr` can still be in `CheckExprLifetime.cpp`.

I think it is fine as `CheckExprLifetime.cpp` is a part of Sema library.

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


[clang] [analyzer] Modernize, improve and promote chroot checker (PR #117791)

2024-11-28 Thread via cfe-commits

vabridgers wrote:

@steakhal , I believe all comments are now resolved. Thank you for the 
thoughtful and detailed comments, look forward to concluding this in the best 
way possible. Thank you!

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


[clang] [clang] Check specialization for annotation (PR #117315)

2024-11-28 Thread Utkarsh Saxena via cfe-commits

https://github.com/usx95 updated 
https://github.com/llvm/llvm-project/pull/117315

>From e30ae8a6e0c1df8e33c2add6502342cb269c1cfd Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Fri, 22 Nov 2024 11:02:49 +
Subject: [PATCH 1/4] [clang] Check specialization for annotation

---
 clang/lib/Sema/CheckExprLifetime.cpp | 9 ++---
 1 file changed, 6 insertions(+), 3 deletions(-)

diff --git a/clang/lib/Sema/CheckExprLifetime.cpp 
b/clang/lib/Sema/CheckExprLifetime.cpp
index 8886e5e307ddf8..64dc4794b6235a 100644
--- a/clang/lib/Sema/CheckExprLifetime.cpp
+++ b/clang/lib/Sema/CheckExprLifetime.cpp
@@ -253,9 +253,12 @@ static void 
visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
   LocalVisitor Visit);
 
 template  static bool isRecordWithAttr(QualType Type) {
-  if (auto *RD = Type->getAsCXXRecordDecl())
-return RD->hasAttr();
-  return false;
+  auto *RD = Type->getAsCXXRecordDecl();
+  if (!RD)
+return false;
+  if (auto *CTSD = dyn_cast(RD))
+RD = CTSD->getSpecializedTemplate()->getTemplatedDecl();
+  return RD->hasAttr();
 }
 
 // Decl::isInStdNamespace will return false for iterators in some STL

>From db163394b70054694734c269f5fd61ef438eda3b Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Thu, 28 Nov 2024 09:01:25 +
Subject: [PATCH 2/4] move to Sema.h

---
 clang/include/clang/Sema/Sema.h  | 12 
 clang/lib/Sema/CheckExprLifetime.cpp | 45 ++--
 clang/lib/Sema/SemaAttr.cpp  |  5 
 3 files changed, 33 insertions(+), 29 deletions(-)

diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 6ea6c67447b6f0..9029d54e90f028 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -1760,6 +1760,18 @@ class Sema final : public SemaBase {
   /// Add [[gsl::Pointer]] attributes for std:: types.
   void inferGslPointerAttribute(TypedefNameDecl *TD);
 
+  template  static bool isRecordWithAttr(QualType Type) {
+auto *RD = Type->getAsCXXRecordDecl();
+if (!RD)
+  return false;
+if (auto *CTSD = dyn_cast(RD))
+  RD = CTSD->getSpecializedTemplate()->getTemplatedDecl();
+return RD->hasAttr();
+  }
+
+  /// 
+  static bool isPointerLikeType(QualType Type);
+
   LifetimeCaptureByAttr *ParseLifetimeCaptureByAttr(const ParsedAttr &AL,
 StringRef ParamName);
   // Processes the argument 'X' in [[clang::lifetime_capture_by(X)]]. Since 'X'
diff --git a/clang/lib/Sema/CheckExprLifetime.cpp 
b/clang/lib/Sema/CheckExprLifetime.cpp
index 64dc4794b6235a..e18651d8e12ab9 100644
--- a/clang/lib/Sema/CheckExprLifetime.cpp
+++ b/clang/lib/Sema/CheckExprLifetime.cpp
@@ -252,15 +252,6 @@ static void 
visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
   Expr *Init, ReferenceKind RK,
   LocalVisitor Visit);
 
-template  static bool isRecordWithAttr(QualType Type) {
-  auto *RD = Type->getAsCXXRecordDecl();
-  if (!RD)
-return false;
-  if (auto *CTSD = dyn_cast(RD))
-RD = CTSD->getSpecializedTemplate()->getTemplatedDecl();
-  return RD->hasAttr();
-}
-
 // Decl::isInStdNamespace will return false for iterators in some STL
 // implementations due to them being defined in a namespace outside of the std
 // namespace.
@@ -279,11 +270,6 @@ static bool isInStlNamespace(const Decl *D) {
   return DC->isStdNamespace();
 }
 
-static bool isPointerLikeType(QualType Type) {
-  return isRecordWithAttr(Type) || Type->isPointerType() ||
- Type->isNullPtrType();
-}
-
 // Returns true if the given Record decl is a form of `GSLOwner`
 // type, e.g. std::vector, std::optional.
 static bool isContainerOfPointer(const RecordDecl *Container) {
@@ -293,7 +279,7 @@ static bool isContainerOfPointer(const RecordDecl 
*Container) {
   return false;
 const auto &TAs = CTSD->getTemplateArgs();
 return TAs.size() > 0 && TAs[0].getKind() == TemplateArgument::Type &&
-   isPointerLikeType(TAs[0].getAsType());
+   Sema::isPointerLikeType(TAs[0].getAsType());
   }
   return false;
 }
@@ -306,7 +292,7 @@ static bool isContainerOfOwner(const RecordDecl *Container) 
{
 return false;
   const auto &TAs = CTSD->getTemplateArgs();
   return TAs.size() > 0 && TAs[0].getKind() == TemplateArgument::Type &&
- isRecordWithAttr(TAs[0].getAsType());
+ Sema::isRecordWithAttr(TAs[0].getAsType());
 }
 
 // Returns true if the given Record is `std::initializer_list`.
@@ -317,23 +303,24 @@ static bool isStdInitializerListOfPointer(const 
RecordDecl *RD) {
 return isInStlNamespace(RD) && RD->getIdentifier() &&
RD->getName() == "initializer_list" && TAs.size() > 0 &&
TAs[0].getKind() == TemplateArgument::Type &&
-   isPointerLikeType(TAs[0].getAsType());
+   Sema::isPointerLikeType(TAs[0].getAsType());
   }
 

[clang] [clang] Check specialization for annotation (PR #117315)

2024-11-28 Thread Utkarsh Saxena via cfe-commits

https://github.com/usx95 updated 
https://github.com/llvm/llvm-project/pull/117315

>From e30ae8a6e0c1df8e33c2add6502342cb269c1cfd Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Fri, 22 Nov 2024 11:02:49 +
Subject: [PATCH 1/5] [clang] Check specialization for annotation

---
 clang/lib/Sema/CheckExprLifetime.cpp | 9 ++---
 1 file changed, 6 insertions(+), 3 deletions(-)

diff --git a/clang/lib/Sema/CheckExprLifetime.cpp 
b/clang/lib/Sema/CheckExprLifetime.cpp
index 8886e5e307ddf8..64dc4794b6235a 100644
--- a/clang/lib/Sema/CheckExprLifetime.cpp
+++ b/clang/lib/Sema/CheckExprLifetime.cpp
@@ -253,9 +253,12 @@ static void 
visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
   LocalVisitor Visit);
 
 template  static bool isRecordWithAttr(QualType Type) {
-  if (auto *RD = Type->getAsCXXRecordDecl())
-return RD->hasAttr();
-  return false;
+  auto *RD = Type->getAsCXXRecordDecl();
+  if (!RD)
+return false;
+  if (auto *CTSD = dyn_cast(RD))
+RD = CTSD->getSpecializedTemplate()->getTemplatedDecl();
+  return RD->hasAttr();
 }
 
 // Decl::isInStdNamespace will return false for iterators in some STL

>From db163394b70054694734c269f5fd61ef438eda3b Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Thu, 28 Nov 2024 09:01:25 +
Subject: [PATCH 2/5] move to Sema.h

---
 clang/include/clang/Sema/Sema.h  | 12 
 clang/lib/Sema/CheckExprLifetime.cpp | 45 ++--
 clang/lib/Sema/SemaAttr.cpp  |  5 
 3 files changed, 33 insertions(+), 29 deletions(-)

diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 6ea6c67447b6f0..9029d54e90f028 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -1760,6 +1760,18 @@ class Sema final : public SemaBase {
   /// Add [[gsl::Pointer]] attributes for std:: types.
   void inferGslPointerAttribute(TypedefNameDecl *TD);
 
+  template  static bool isRecordWithAttr(QualType Type) {
+auto *RD = Type->getAsCXXRecordDecl();
+if (!RD)
+  return false;
+if (auto *CTSD = dyn_cast(RD))
+  RD = CTSD->getSpecializedTemplate()->getTemplatedDecl();
+return RD->hasAttr();
+  }
+
+  /// 
+  static bool isPointerLikeType(QualType Type);
+
   LifetimeCaptureByAttr *ParseLifetimeCaptureByAttr(const ParsedAttr &AL,
 StringRef ParamName);
   // Processes the argument 'X' in [[clang::lifetime_capture_by(X)]]. Since 'X'
diff --git a/clang/lib/Sema/CheckExprLifetime.cpp 
b/clang/lib/Sema/CheckExprLifetime.cpp
index 64dc4794b6235a..e18651d8e12ab9 100644
--- a/clang/lib/Sema/CheckExprLifetime.cpp
+++ b/clang/lib/Sema/CheckExprLifetime.cpp
@@ -252,15 +252,6 @@ static void 
visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
   Expr *Init, ReferenceKind RK,
   LocalVisitor Visit);
 
-template  static bool isRecordWithAttr(QualType Type) {
-  auto *RD = Type->getAsCXXRecordDecl();
-  if (!RD)
-return false;
-  if (auto *CTSD = dyn_cast(RD))
-RD = CTSD->getSpecializedTemplate()->getTemplatedDecl();
-  return RD->hasAttr();
-}
-
 // Decl::isInStdNamespace will return false for iterators in some STL
 // implementations due to them being defined in a namespace outside of the std
 // namespace.
@@ -279,11 +270,6 @@ static bool isInStlNamespace(const Decl *D) {
   return DC->isStdNamespace();
 }
 
-static bool isPointerLikeType(QualType Type) {
-  return isRecordWithAttr(Type) || Type->isPointerType() ||
- Type->isNullPtrType();
-}
-
 // Returns true if the given Record decl is a form of `GSLOwner`
 // type, e.g. std::vector, std::optional.
 static bool isContainerOfPointer(const RecordDecl *Container) {
@@ -293,7 +279,7 @@ static bool isContainerOfPointer(const RecordDecl 
*Container) {
   return false;
 const auto &TAs = CTSD->getTemplateArgs();
 return TAs.size() > 0 && TAs[0].getKind() == TemplateArgument::Type &&
-   isPointerLikeType(TAs[0].getAsType());
+   Sema::isPointerLikeType(TAs[0].getAsType());
   }
   return false;
 }
@@ -306,7 +292,7 @@ static bool isContainerOfOwner(const RecordDecl *Container) 
{
 return false;
   const auto &TAs = CTSD->getTemplateArgs();
   return TAs.size() > 0 && TAs[0].getKind() == TemplateArgument::Type &&
- isRecordWithAttr(TAs[0].getAsType());
+ Sema::isRecordWithAttr(TAs[0].getAsType());
 }
 
 // Returns true if the given Record is `std::initializer_list`.
@@ -317,23 +303,24 @@ static bool isStdInitializerListOfPointer(const 
RecordDecl *RD) {
 return isInStlNamespace(RD) && RD->getIdentifier() &&
RD->getName() == "initializer_list" && TAs.size() > 0 &&
TAs[0].getKind() == TemplateArgument::Type &&
-   isPointerLikeType(TAs[0].getAsType());
+   Sema::isPointerLikeType(TAs[0].getAsType());
   }
 

[clang] [clang] Format bitfield width diagnostics with thousands-separators (PR #117763)

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


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

>From 07b326b59bf9a8e385840a590c5162b9d1914650 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Tue, 26 Nov 2024 19:26:32 +0100
Subject: [PATCH 1/2] [clang] Format bitfield width diagnostics with
 thousands-separators

---
 .../clang/Basic/DiagnosticSemaKinds.td|  2 +-
 clang/lib/Sema/SemaDecl.cpp   | 27 ++-
 clang/test/SemaCXX/bitfield-layout.cpp|  4 +--
 3 files changed, 24 insertions(+), 9 deletions(-)

diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 6ff24c2bc8faad..5ab0885c8414fd 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -6400,7 +6400,7 @@ def err_incorrect_number_of_vector_initializers : Error<
 // Used by C++ which allows bit-fields that are wider than the type.
 def warn_bitfield_width_exceeds_type_width: Warning<
   "width of bit-field %0 (%1 bits) exceeds the width of its type; value will "
-  "be truncated to %2 bit%s2">, InGroup;
+  "be truncated to %2 bits">, InGroup;
 def err_bitfield_too_wide : Error<
   "%select{bit-field %1|anonymous bit-field}0 is too wide (%2 bits)">;
 def warn_bitfield_too_small_for_enum : Warning<
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 74b0e5ad23bd48..7378edc1c5cecb 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -18307,16 +18307,22 @@ ExprResult Sema::VerifyBitField(SourceLocation 
FieldLoc,
   if (Value.isSigned() && Value.isNegative()) {
 if (FieldName)
   return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
-   << FieldName << toString(Value, 10);
+ << FieldName
+ << toString(Value, 10, Value.isSigned(),
+ /*formatAsCLiteral=*/false, /*UpperCase=*/true,
+ /*InsertSeparators=*/true);
 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
-  << toString(Value, 10);
+   << toString(Value, 10, Value.isSigned(), /*formatAsCLiteral=*/false,
+   /*UpperCase=*/true, /*InsertSeparators=*/true);
   }
 
   // The size of the bit-field must not exceed our maximum permitted object
   // size.
   if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
 return Diag(FieldLoc, diag::err_bitfield_too_wide)
-   << !FieldName << FieldName << toString(Value, 10);
+   << !FieldName << FieldName
+   << toString(Value, 10, Value.isSigned(), /*formatAsCLiteral=*/false,
+   /*UpperCase=*/true, /*InsertSeparators=*/true);
   }
 
   if (!FieldTy->isDependentType()) {
@@ -18335,7 +18341,10 @@ ExprResult Sema::VerifyBitField(SourceLocation 
FieldLoc,
   unsigned DiagWidth =
   CStdConstraintViolation ? TypeWidth : TypeStorageSize;
   return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
- << (bool)FieldName << FieldName << toString(Value, 10)
+ << (bool)FieldName << FieldName
+ << toString(Value, 10, Value.isSigned(),
+ /*formatAsCLiteral=*/false, /*UpperCase=*/true,
+ /*InsertSeparators=*/true)
  << !CStdConstraintViolation << DiagWidth;
 }
 
@@ -18343,9 +18352,15 @@ ExprResult Sema::VerifyBitField(SourceLocation 
FieldLoc,
 // specified bits as value bits: that's all integral types other than
 // 'bool'.
 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
+  llvm::APInt TypeWidthAP(sizeof(TypeWidth) * 8, TypeWidth,
+  /*IsSigned=*/false);
   Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
-  << FieldName << toString(Value, 10)
-  << (unsigned)TypeWidth;
+  << FieldName
+  << toString(Value, 10, Value.isSigned(), /*formatAsCLiteral=*/false,
+  /*UpperCase=*/true, /*InsertSeparators=*/true)
+  << toString(TypeWidthAP, 10, /*Signed=*/false,
+  /*formatAsCLiteral=*/false, /*UpperCase=*/true,
+  /*InsertSeparators=*/true);
 }
   }
 
diff --git a/clang/test/SemaCXX/bitfield-layout.cpp 
b/clang/test/SemaCXX/bitfield-layout.cpp
index 7efd1d38c682f5..951a4f72de1566 100644
--- a/clang/test/SemaCXX/bitfield-layout.cpp
+++ b/clang/test/SemaCXX/bitfield-layout.cpp
@@ -35,14 +35,14 @@ CHECK_SIZE(Test4, 8);
 CHECK_ALIGN(Test4, 8);
 
 struct Test5 {
-  char c : 0x10001; // expected-warning {{width of bit-field 'c' 
(4294967297 bits) exceeds the width of its type; value will be truncated to 8 
bits}}
+  char c : 0x10001; // expected-warning {{width of bit-field 'c' 
(4'294'967'297 bits) exceeds the width of its type; value will be truncated to 
8 bits}}
 };
 // Size and a

[clang] [analyzer][NFC] Cleanup BranchNodeBuilder (PR #117898)

2024-11-28 Thread Gábor Horváth via cfe-commits

https://github.com/Xazax-hun approved this pull request.

LGTM! Did you run it over a couple of open source projects to check if there is 
any difference in the diagnostics?

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


[clang] [clang] Check specialization for annotation (PR #117315)

2024-11-28 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 89b08c8ee7b5184f8cfb0d356f2762173fb87d42 
a847f8bf8d02edb0b9615856713ec122cee1e927 --extensions h,cpp -- 
clang/include/clang/Sema/Sema.h clang/lib/Sema/CheckExprLifetime.cpp 
clang/lib/Sema/SemaAttr.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Sema/CheckExprLifetime.cpp 
b/clang/lib/Sema/CheckExprLifetime.cpp
index f522c46c6c..2970f1fa0c 100644
--- a/clang/lib/Sema/CheckExprLifetime.cpp
+++ b/clang/lib/Sema/CheckExprLifetime.cpp
@@ -336,8 +336,7 @@ static bool shouldTrackImplicitObjectArg(const 
CXXMethodDecl *Callee) {
 return false;
   if (!isRecordWithAttr(
   Callee->getFunctionObjectParameterType()) &&
-  !isRecordWithAttr(
-  Callee->getFunctionObjectParameterType()))
+  !isRecordWithAttr(Callee->getFunctionObjectParameterType()))
 return false;
   if (Sema::isPointerLikeType(Callee->getReturnType())) {
 if (!Callee->getIdentifier())

``




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


[clang] [Clang][AArch64]Refactor typespec handling in SveEmitter.cpp (PR #117717)

2024-11-28 Thread via cfe-commits

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


[clang] [clang-repl] Fix generation of wasm binaries while running clang-repl in browser (PR #117978)

2024-11-28 Thread Anutosh Bhat via cfe-commits

https://github.com/anutosh491 updated 
https://github.com/llvm/llvm-project/pull/117978

>From 987f77db9d45dee264c60f434652131438784f6f Mon Sep 17 00:00:00 2001
From: anutosh491 
Date: Thu, 28 Nov 2024 14:02:00 +0530
Subject: [PATCH 1/2] Fix generation of wasm binaries while running clang-repl
 in browser

---
 clang/lib/Interpreter/CMakeLists.txt  |  2 +
 clang/lib/Interpreter/Interpreter.cpp |  1 +
 clang/lib/Interpreter/Wasm.cpp| 57 ---
 3 files changed, 45 insertions(+), 15 deletions(-)

diff --git a/clang/lib/Interpreter/CMakeLists.txt 
b/clang/lib/Interpreter/CMakeLists.txt
index df7ea82e0dada5..bf70cdfbee01e1 100644
--- a/clang/lib/Interpreter/CMakeLists.txt
+++ b/clang/lib/Interpreter/CMakeLists.txt
@@ -16,6 +16,7 @@ set(LLVM_LINK_COMPONENTS
 if (EMSCRIPTEN AND "lld" IN_LIST LLVM_ENABLE_PROJECTS)
   set(WASM_SRC Wasm.cpp)
   set(WASM_LINK lldWasm)
+  set(COMMON_LINK lldCommon)
 endif()
 
 add_clang_library(clangInterpreter
@@ -47,6 +48,7 @@ add_clang_library(clangInterpreter
   clangSema
   clangSerialization
   ${WASM_LINK}
+  ${COMMON_LINK}
   )
 
 if ((MINGW OR CYGWIN) AND BUILD_SHARED_LIBS)
diff --git a/clang/lib/Interpreter/Interpreter.cpp 
b/clang/lib/Interpreter/Interpreter.cpp
index 5dc67f6375098f..887b494ff98f19 100644
--- a/clang/lib/Interpreter/Interpreter.cpp
+++ b/clang/lib/Interpreter/Interpreter.cpp
@@ -201,6 +201,7 @@ IncrementalCompilerBuilder::CreateCpp() {
   Argv.push_back("-target");
   Argv.push_back("wasm32-unknown-emscripten");
   Argv.push_back("-shared");
+  Argv.push_back("-fvisibility=default");
 #endif
   Argv.insert(Argv.end(), UserArgs.begin(), UserArgs.end());
 
diff --git a/clang/lib/Interpreter/Wasm.cpp b/clang/lib/Interpreter/Wasm.cpp
index 79efbaa03982d0..0fd6ad509c2938 100644
--- a/clang/lib/Interpreter/Wasm.cpp
+++ b/clang/lib/Interpreter/Wasm.cpp
@@ -23,6 +23,31 @@
 #include 
 
 namespace lld {
+enum Flavor {
+  Invalid,
+  Gnu, // -flavor gnu
+  MinGW,   // -flavor gnu MinGW
+  WinLink, // -flavor link
+  Darwin,  // -flavor darwin
+  Wasm,// -flavor wasm
+};
+
+using Driver = bool (*)(llvm::ArrayRef, llvm::raw_ostream &,
+llvm::raw_ostream &, bool, bool);
+
+struct DriverDef {
+  Flavor f;
+  Driver d;
+};
+
+struct Result {
+int retCode;
+bool canRunAgain;
+};
+
+Result lldMain(llvm::ArrayRef args, llvm::raw_ostream &stdoutOS,
+llvm::raw_ostream &stderrOS, llvm::ArrayRef 
drivers);
+
 namespace wasm {
 bool link(llvm::ArrayRef args, llvm::raw_ostream &stdoutOS,
   llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput);
@@ -51,45 +76,47 @@ llvm::Error 
WasmIncrementalExecutor::addModule(PartialTranslationUnit &PTU) {
   llvm::TargetMachine *TargetMachine = Target->createTargetMachine(
   PTU.TheModule->getTargetTriple(), "", "", TO, llvm::Reloc::Model::PIC_);
   PTU.TheModule->setDataLayout(TargetMachine->createDataLayout());
-  std::string OutputFileName = PTU.TheModule->getName().str() + ".wasm";
+  std::string ObjectFileName = PTU.TheModule->getName().str() + ".o";  // For 
the wasm object
+  std::string BinaryFileName = PTU.TheModule->getName().str() + ".wasm";  // 
For the wasm binary
 
   std::error_code Error;
-  llvm::raw_fd_ostream OutputFile(llvm::StringRef(OutputFileName), Error);
+  llvm::raw_fd_ostream ObjectFileOutput(llvm::StringRef(ObjectFileName), 
Error);
 
   llvm::legacy::PassManager PM;
-  if (TargetMachine->addPassesToEmitFile(PM, OutputFile, nullptr,
+  if (TargetMachine->addPassesToEmitFile(PM, ObjectFileOutput, nullptr,
  llvm::CodeGenFileType::ObjectFile)) {
 return llvm::make_error(
 "Wasm backend cannot produce object.", llvm::inconvertibleErrorCode());
   }
 
   if (!PM.run(*PTU.TheModule)) {
-
 return llvm::make_error("Failed to emit Wasm object.",
llvm::inconvertibleErrorCode());
   }
 
-  OutputFile.close();
+  ObjectFileOutput.close();
 
   std::vector LinkerArgs = {"wasm-ld",
   "-shared",
   "--import-memory",
-  "--no-entry",
-  "--export-all",
   "--experimental-pic",
   "--stack-first",
   "--allow-undefined",
-  OutputFileName.c_str(),
+  ObjectFileName.c_str(),
   "-o",
-  OutputFileName.c_str()};
-  int Result =
-  lld::wasm::link(LinkerArgs, llvm::outs(), llvm::errs(), false, false);
-  if (!Result)
+  BinaryFileName.c_str()};
+
+  const lld::DriverDef WasmDriver = {lld::Flavor::Wasm, &lld::wasm::link};
+  std::vector WasmDriverArg

[clang] [clang-repl] Fix generation of wasm binaries while running clang-repl in browser (PR #117978)

2024-11-28 Thread Anutosh Bhat via cfe-commits

https://github.com/anutosh491 updated 
https://github.com/llvm/llvm-project/pull/117978

>From 987f77db9d45dee264c60f434652131438784f6f Mon Sep 17 00:00:00 2001
From: anutosh491 
Date: Thu, 28 Nov 2024 14:02:00 +0530
Subject: [PATCH 1/2] Fix generation of wasm binaries while running clang-repl
 in browser

---
 clang/lib/Interpreter/CMakeLists.txt  |  2 +
 clang/lib/Interpreter/Interpreter.cpp |  1 +
 clang/lib/Interpreter/Wasm.cpp| 57 ---
 3 files changed, 45 insertions(+), 15 deletions(-)

diff --git a/clang/lib/Interpreter/CMakeLists.txt 
b/clang/lib/Interpreter/CMakeLists.txt
index df7ea82e0dada5..bf70cdfbee01e1 100644
--- a/clang/lib/Interpreter/CMakeLists.txt
+++ b/clang/lib/Interpreter/CMakeLists.txt
@@ -16,6 +16,7 @@ set(LLVM_LINK_COMPONENTS
 if (EMSCRIPTEN AND "lld" IN_LIST LLVM_ENABLE_PROJECTS)
   set(WASM_SRC Wasm.cpp)
   set(WASM_LINK lldWasm)
+  set(COMMON_LINK lldCommon)
 endif()
 
 add_clang_library(clangInterpreter
@@ -47,6 +48,7 @@ add_clang_library(clangInterpreter
   clangSema
   clangSerialization
   ${WASM_LINK}
+  ${COMMON_LINK}
   )
 
 if ((MINGW OR CYGWIN) AND BUILD_SHARED_LIBS)
diff --git a/clang/lib/Interpreter/Interpreter.cpp 
b/clang/lib/Interpreter/Interpreter.cpp
index 5dc67f6375098f..887b494ff98f19 100644
--- a/clang/lib/Interpreter/Interpreter.cpp
+++ b/clang/lib/Interpreter/Interpreter.cpp
@@ -201,6 +201,7 @@ IncrementalCompilerBuilder::CreateCpp() {
   Argv.push_back("-target");
   Argv.push_back("wasm32-unknown-emscripten");
   Argv.push_back("-shared");
+  Argv.push_back("-fvisibility=default");
 #endif
   Argv.insert(Argv.end(), UserArgs.begin(), UserArgs.end());
 
diff --git a/clang/lib/Interpreter/Wasm.cpp b/clang/lib/Interpreter/Wasm.cpp
index 79efbaa03982d0..0fd6ad509c2938 100644
--- a/clang/lib/Interpreter/Wasm.cpp
+++ b/clang/lib/Interpreter/Wasm.cpp
@@ -23,6 +23,31 @@
 #include 
 
 namespace lld {
+enum Flavor {
+  Invalid,
+  Gnu, // -flavor gnu
+  MinGW,   // -flavor gnu MinGW
+  WinLink, // -flavor link
+  Darwin,  // -flavor darwin
+  Wasm,// -flavor wasm
+};
+
+using Driver = bool (*)(llvm::ArrayRef, llvm::raw_ostream &,
+llvm::raw_ostream &, bool, bool);
+
+struct DriverDef {
+  Flavor f;
+  Driver d;
+};
+
+struct Result {
+int retCode;
+bool canRunAgain;
+};
+
+Result lldMain(llvm::ArrayRef args, llvm::raw_ostream &stdoutOS,
+llvm::raw_ostream &stderrOS, llvm::ArrayRef 
drivers);
+
 namespace wasm {
 bool link(llvm::ArrayRef args, llvm::raw_ostream &stdoutOS,
   llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput);
@@ -51,45 +76,47 @@ llvm::Error 
WasmIncrementalExecutor::addModule(PartialTranslationUnit &PTU) {
   llvm::TargetMachine *TargetMachine = Target->createTargetMachine(
   PTU.TheModule->getTargetTriple(), "", "", TO, llvm::Reloc::Model::PIC_);
   PTU.TheModule->setDataLayout(TargetMachine->createDataLayout());
-  std::string OutputFileName = PTU.TheModule->getName().str() + ".wasm";
+  std::string ObjectFileName = PTU.TheModule->getName().str() + ".o";  // For 
the wasm object
+  std::string BinaryFileName = PTU.TheModule->getName().str() + ".wasm";  // 
For the wasm binary
 
   std::error_code Error;
-  llvm::raw_fd_ostream OutputFile(llvm::StringRef(OutputFileName), Error);
+  llvm::raw_fd_ostream ObjectFileOutput(llvm::StringRef(ObjectFileName), 
Error);
 
   llvm::legacy::PassManager PM;
-  if (TargetMachine->addPassesToEmitFile(PM, OutputFile, nullptr,
+  if (TargetMachine->addPassesToEmitFile(PM, ObjectFileOutput, nullptr,
  llvm::CodeGenFileType::ObjectFile)) {
 return llvm::make_error(
 "Wasm backend cannot produce object.", llvm::inconvertibleErrorCode());
   }
 
   if (!PM.run(*PTU.TheModule)) {
-
 return llvm::make_error("Failed to emit Wasm object.",
llvm::inconvertibleErrorCode());
   }
 
-  OutputFile.close();
+  ObjectFileOutput.close();
 
   std::vector LinkerArgs = {"wasm-ld",
   "-shared",
   "--import-memory",
-  "--no-entry",
-  "--export-all",
   "--experimental-pic",
   "--stack-first",
   "--allow-undefined",
-  OutputFileName.c_str(),
+  ObjectFileName.c_str(),
   "-o",
-  OutputFileName.c_str()};
-  int Result =
-  lld::wasm::link(LinkerArgs, llvm::outs(), llvm::errs(), false, false);
-  if (!Result)
+  BinaryFileName.c_str()};
+
+  const lld::DriverDef WasmDriver = {lld::Flavor::Wasm, &lld::wasm::link};
+  std::vector WasmDriverArg

[clang] [clang-repl] Fix generation of wasm binaries while running clang-repl in browser (PR #117978)

2024-11-28 Thread Anutosh Bhat via cfe-commits

https://github.com/anutosh491 updated 
https://github.com/llvm/llvm-project/pull/117978

>From 987f77db9d45dee264c60f434652131438784f6f Mon Sep 17 00:00:00 2001
From: anutosh491 
Date: Thu, 28 Nov 2024 14:02:00 +0530
Subject: [PATCH 1/2] Fix generation of wasm binaries while running clang-repl
 in browser

---
 clang/lib/Interpreter/CMakeLists.txt  |  2 +
 clang/lib/Interpreter/Interpreter.cpp |  1 +
 clang/lib/Interpreter/Wasm.cpp| 57 ---
 3 files changed, 45 insertions(+), 15 deletions(-)

diff --git a/clang/lib/Interpreter/CMakeLists.txt 
b/clang/lib/Interpreter/CMakeLists.txt
index df7ea82e0dada5..bf70cdfbee01e1 100644
--- a/clang/lib/Interpreter/CMakeLists.txt
+++ b/clang/lib/Interpreter/CMakeLists.txt
@@ -16,6 +16,7 @@ set(LLVM_LINK_COMPONENTS
 if (EMSCRIPTEN AND "lld" IN_LIST LLVM_ENABLE_PROJECTS)
   set(WASM_SRC Wasm.cpp)
   set(WASM_LINK lldWasm)
+  set(COMMON_LINK lldCommon)
 endif()
 
 add_clang_library(clangInterpreter
@@ -47,6 +48,7 @@ add_clang_library(clangInterpreter
   clangSema
   clangSerialization
   ${WASM_LINK}
+  ${COMMON_LINK}
   )
 
 if ((MINGW OR CYGWIN) AND BUILD_SHARED_LIBS)
diff --git a/clang/lib/Interpreter/Interpreter.cpp 
b/clang/lib/Interpreter/Interpreter.cpp
index 5dc67f6375098f..887b494ff98f19 100644
--- a/clang/lib/Interpreter/Interpreter.cpp
+++ b/clang/lib/Interpreter/Interpreter.cpp
@@ -201,6 +201,7 @@ IncrementalCompilerBuilder::CreateCpp() {
   Argv.push_back("-target");
   Argv.push_back("wasm32-unknown-emscripten");
   Argv.push_back("-shared");
+  Argv.push_back("-fvisibility=default");
 #endif
   Argv.insert(Argv.end(), UserArgs.begin(), UserArgs.end());
 
diff --git a/clang/lib/Interpreter/Wasm.cpp b/clang/lib/Interpreter/Wasm.cpp
index 79efbaa03982d0..0fd6ad509c2938 100644
--- a/clang/lib/Interpreter/Wasm.cpp
+++ b/clang/lib/Interpreter/Wasm.cpp
@@ -23,6 +23,31 @@
 #include 
 
 namespace lld {
+enum Flavor {
+  Invalid,
+  Gnu, // -flavor gnu
+  MinGW,   // -flavor gnu MinGW
+  WinLink, // -flavor link
+  Darwin,  // -flavor darwin
+  Wasm,// -flavor wasm
+};
+
+using Driver = bool (*)(llvm::ArrayRef, llvm::raw_ostream &,
+llvm::raw_ostream &, bool, bool);
+
+struct DriverDef {
+  Flavor f;
+  Driver d;
+};
+
+struct Result {
+int retCode;
+bool canRunAgain;
+};
+
+Result lldMain(llvm::ArrayRef args, llvm::raw_ostream &stdoutOS,
+llvm::raw_ostream &stderrOS, llvm::ArrayRef 
drivers);
+
 namespace wasm {
 bool link(llvm::ArrayRef args, llvm::raw_ostream &stdoutOS,
   llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput);
@@ -51,45 +76,47 @@ llvm::Error 
WasmIncrementalExecutor::addModule(PartialTranslationUnit &PTU) {
   llvm::TargetMachine *TargetMachine = Target->createTargetMachine(
   PTU.TheModule->getTargetTriple(), "", "", TO, llvm::Reloc::Model::PIC_);
   PTU.TheModule->setDataLayout(TargetMachine->createDataLayout());
-  std::string OutputFileName = PTU.TheModule->getName().str() + ".wasm";
+  std::string ObjectFileName = PTU.TheModule->getName().str() + ".o";  // For 
the wasm object
+  std::string BinaryFileName = PTU.TheModule->getName().str() + ".wasm";  // 
For the wasm binary
 
   std::error_code Error;
-  llvm::raw_fd_ostream OutputFile(llvm::StringRef(OutputFileName), Error);
+  llvm::raw_fd_ostream ObjectFileOutput(llvm::StringRef(ObjectFileName), 
Error);
 
   llvm::legacy::PassManager PM;
-  if (TargetMachine->addPassesToEmitFile(PM, OutputFile, nullptr,
+  if (TargetMachine->addPassesToEmitFile(PM, ObjectFileOutput, nullptr,
  llvm::CodeGenFileType::ObjectFile)) {
 return llvm::make_error(
 "Wasm backend cannot produce object.", llvm::inconvertibleErrorCode());
   }
 
   if (!PM.run(*PTU.TheModule)) {
-
 return llvm::make_error("Failed to emit Wasm object.",
llvm::inconvertibleErrorCode());
   }
 
-  OutputFile.close();
+  ObjectFileOutput.close();
 
   std::vector LinkerArgs = {"wasm-ld",
   "-shared",
   "--import-memory",
-  "--no-entry",
-  "--export-all",
   "--experimental-pic",
   "--stack-first",
   "--allow-undefined",
-  OutputFileName.c_str(),
+  ObjectFileName.c_str(),
   "-o",
-  OutputFileName.c_str()};
-  int Result =
-  lld::wasm::link(LinkerArgs, llvm::outs(), llvm::errs(), false, false);
-  if (!Result)
+  BinaryFileName.c_str()};
+
+  const lld::DriverDef WasmDriver = {lld::Flavor::Wasm, &lld::wasm::link};
+  std::vector WasmDriverArg

[clang] 6e720df - [clang] Improve the lifetime_capture_by diagnostic on the constructor. (#117792)

2024-11-28 Thread via cfe-commits

Author: Haojian Wu
Date: 2024-11-28T12:35:15+01:00
New Revision: 6e720df1ae23c715aefc36476ab46284a96e9371

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

LOG: [clang] Improve the lifetime_capture_by diagnostic on the constructor. 
(#117792)

With this change, the lifetime_capture_by code path will not handle the
constructor decl to avoid bogus diagnostics (see the testcase).

Instead, we reuse the lifetimebound code as the
lifetime_capture_by(this) has the same semantic as lifetimebound in
constructor. The downside is that the lifetimebound diagnostic is reused
for the capture case (I think it is not a big issue).


Fixes #117680

Added: 


Modified: 
clang/include/clang/Basic/AttrDocs.td
clang/lib/Sema/CheckExprLifetime.cpp
clang/lib/Sema/SemaChecking.cpp
clang/test/Sema/warn-lifetime-analysis-capture-by.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index 9617687ac69caf..5de39be4805600 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -3985,6 +3985,8 @@ The capturing entity ``X`` can be one of the following:
   std::set s;
 };
 
+  Note: When applied to a constructor parameter, 
`[[clang::lifetime_capture_by(this)]]` is just an alias of 
`[[clang::lifetimebound]]`.
+
 - `global`, `unknown`.
 
   .. code-block:: c++

diff  --git a/clang/lib/Sema/CheckExprLifetime.cpp 
b/clang/lib/Sema/CheckExprLifetime.cpp
index 6cdd4dc629e50a..607b7daf878e17 100644
--- a/clang/lib/Sema/CheckExprLifetime.cpp
+++ b/clang/lib/Sema/CheckExprLifetime.cpp
@@ -623,6 +623,26 @@ static void visitFunctionCallArguments(IndirectLocalPath 
&Path, Expr *Call,
 }
 if (CheckCoroCall || Callee->getParamDecl(I)->hasAttr())
   VisitLifetimeBoundArg(Callee->getParamDecl(I), Arg);
+else if (const auto *CaptureAttr =
+ Callee->getParamDecl(I)->getAttr();
+ CaptureAttr && isa(Callee) &&
+ llvm::any_of(CaptureAttr->params(), [](int ArgIdx) {
+   return ArgIdx == LifetimeCaptureByAttr::THIS;
+ }))
+  // `lifetime_capture_by(this)` in a class constructor has the same
+  // semantics as `lifetimebound`:
+  //
+  // struct Foo {
+  //   const int& a;
+  //   // Equivalent to Foo(const int& t [[clang::lifetimebound]])
+  //   Foo(const int& t [[clang::lifetime_capture_by(this)]]) : a(t) {}
+  // };
+  //
+  // In the implementation, `lifetime_capture_by` is treated as an alias 
for
+  // `lifetimebound` and shares the same code path. This implies the 
emitted
+  // diagnostics will be emitted under `-Wdangling`, not
+  // `-Wdangling-capture`.
+  VisitLifetimeBoundArg(Callee->getParamDecl(I), Arg);
 else if (EnableGSLAnalysis && I == 0) {
   // Perform GSL analysis for the first argument
   if (shouldTrackFirstArgument(Callee)) {

diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index e071e2b7f33500..a248a6b53b0d06 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -3240,8 +3240,14 @@ void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool 
IsMemberFunction,
  unsigned ArgIdx) {
 if (!Attr)
   return;
+
 Expr *Captured = const_cast(GetArgAt(ArgIdx));
 for (int CapturingParamIdx : Attr->params()) {
+  // lifetime_capture_by(this) case is handled in the lifetimebound expr
+  // initialization codepath.
+  if (CapturingParamIdx == LifetimeCaptureByAttr::THIS &&
+  isa(FD))
+continue;
   Expr *Capturing = const_cast(GetArgAt(CapturingParamIdx));
   CapturingEntity CE{Capturing};
   // Ensure that 'Captured' outlives the 'Capturing' entity.

diff  --git a/clang/test/Sema/warn-lifetime-analysis-capture-by.cpp 
b/clang/test/Sema/warn-lifetime-analysis-capture-by.cpp
index e867296d6d8ea7..12b933e63edd7b 100644
--- a/clang/test/Sema/warn-lifetime-analysis-capture-by.cpp
+++ b/clang/test/Sema/warn-lifetime-analysis-capture-by.cpp
@@ -425,3 +425,29 @@ void use() {
 }
 } // namespace with_span
 } // namespace inferred_capture_by
+
+namespace on_constructor {
+struct T {
+  T(const int& t [[clang::lifetime_capture_by(this)]]);
+};
+struct T2 {
+  T2(const int& t [[clang::lifetime_capture_by(x)]], int& x);
+};
+struct T3 {
+  T3(const T& t [[clang::lifetime_capture_by(this)]]);
+};
+
+int foo(const T& t);
+int bar(const T& t[[clang::lifetimebound]]);
+
+void test() {
+  auto x = foo(T(1)); // OK. no diagnosic
+  T(1); // OK. no diagnostic
+  T t(1); // expected-warning {{temporary whose address is used}}
+  auto y = bar(T(1)); // expected-warning {{temporary whose address is used}}
+  T3 t3(T(1)); // expe

[clang] [clang] Improve the lifetime_capture_by diagnostic on the constructor. (PR #117792)

2024-11-28 Thread Haojian Wu via cfe-commits

https://github.com/hokein closed 
https://github.com/llvm/llvm-project/pull/117792
___
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][use-internal-linkage]fix false positives for global overloaded operator new and operator delete (PR #117945)

2024-11-28 Thread Julian Schmidt via cfe-commits


@@ -85,3 +85,13 @@ void func_with_body() {}
 void func_without_body();
 void func_without_body();
 }
+
+// gh117489 start
+namespace std {
+using size_t = decltype(sizeof(int));
+}
+void * operator new(std::size_t);
+void * operator new[](std::size_t);
+void operator delete(void*);
+void operator delete[](void*);
+// gh117489 end

5chmidti wrote:

In the previous PR, you constrained the matcher to require that a body is 
available, so this test would pass, even without the change in this PR.
*Unless* you have checked that this was broken before, because the implicitly 
generated operators are considered to be the body of these declarations. 
Though, adding the body would mean there is less confusion/need for a comment.

Please also mark the delete functions `noexcept`

https://github.com/llvm/llvm-project/pull/117945
___
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][use-internal-linkage]fix false positives for global overloaded operator new and operator delete (PR #117945)

2024-11-28 Thread Julian Schmidt via cfe-commits


@@ -43,7 +43,7 @@ void test(void) {
 }
 
 extern void g3(int); // expected-note{{previous declaration is here}}
-static void g3(int x) { } // expected-error{{static declaration of 'g3' 
follows non-static declaration}}
+static void g3(int x) { } // expected-error{{static declaration of 'g3' }}

5chmidti wrote:

What's the reason for this change?

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


[clang] [clang] Check specialization for annotation (PR #117315)

2024-11-28 Thread Utkarsh Saxena via cfe-commits

https://github.com/usx95 updated 
https://github.com/llvm/llvm-project/pull/117315

>From e30ae8a6e0c1df8e33c2add6502342cb269c1cfd Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Fri, 22 Nov 2024 11:02:49 +
Subject: [PATCH 1/8] [clang] Check specialization for annotation

---
 clang/lib/Sema/CheckExprLifetime.cpp | 9 ++---
 1 file changed, 6 insertions(+), 3 deletions(-)

diff --git a/clang/lib/Sema/CheckExprLifetime.cpp 
b/clang/lib/Sema/CheckExprLifetime.cpp
index 8886e5e307ddf8..64dc4794b6235a 100644
--- a/clang/lib/Sema/CheckExprLifetime.cpp
+++ b/clang/lib/Sema/CheckExprLifetime.cpp
@@ -253,9 +253,12 @@ static void 
visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
   LocalVisitor Visit);
 
 template  static bool isRecordWithAttr(QualType Type) {
-  if (auto *RD = Type->getAsCXXRecordDecl())
-return RD->hasAttr();
-  return false;
+  auto *RD = Type->getAsCXXRecordDecl();
+  if (!RD)
+return false;
+  if (auto *CTSD = dyn_cast(RD))
+RD = CTSD->getSpecializedTemplate()->getTemplatedDecl();
+  return RD->hasAttr();
 }
 
 // Decl::isInStdNamespace will return false for iterators in some STL

>From db163394b70054694734c269f5fd61ef438eda3b Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Thu, 28 Nov 2024 09:01:25 +
Subject: [PATCH 2/8] move to Sema.h

---
 clang/include/clang/Sema/Sema.h  | 12 
 clang/lib/Sema/CheckExprLifetime.cpp | 45 ++--
 clang/lib/Sema/SemaAttr.cpp  |  5 
 3 files changed, 33 insertions(+), 29 deletions(-)

diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 6ea6c67447b6f0..9029d54e90f028 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -1760,6 +1760,18 @@ class Sema final : public SemaBase {
   /// Add [[gsl::Pointer]] attributes for std:: types.
   void inferGslPointerAttribute(TypedefNameDecl *TD);
 
+  template  static bool isRecordWithAttr(QualType Type) {
+auto *RD = Type->getAsCXXRecordDecl();
+if (!RD)
+  return false;
+if (auto *CTSD = dyn_cast(RD))
+  RD = CTSD->getSpecializedTemplate()->getTemplatedDecl();
+return RD->hasAttr();
+  }
+
+  /// 
+  static bool isPointerLikeType(QualType Type);
+
   LifetimeCaptureByAttr *ParseLifetimeCaptureByAttr(const ParsedAttr &AL,
 StringRef ParamName);
   // Processes the argument 'X' in [[clang::lifetime_capture_by(X)]]. Since 'X'
diff --git a/clang/lib/Sema/CheckExprLifetime.cpp 
b/clang/lib/Sema/CheckExprLifetime.cpp
index 64dc4794b6235a..e18651d8e12ab9 100644
--- a/clang/lib/Sema/CheckExprLifetime.cpp
+++ b/clang/lib/Sema/CheckExprLifetime.cpp
@@ -252,15 +252,6 @@ static void 
visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
   Expr *Init, ReferenceKind RK,
   LocalVisitor Visit);
 
-template  static bool isRecordWithAttr(QualType Type) {
-  auto *RD = Type->getAsCXXRecordDecl();
-  if (!RD)
-return false;
-  if (auto *CTSD = dyn_cast(RD))
-RD = CTSD->getSpecializedTemplate()->getTemplatedDecl();
-  return RD->hasAttr();
-}
-
 // Decl::isInStdNamespace will return false for iterators in some STL
 // implementations due to them being defined in a namespace outside of the std
 // namespace.
@@ -279,11 +270,6 @@ static bool isInStlNamespace(const Decl *D) {
   return DC->isStdNamespace();
 }
 
-static bool isPointerLikeType(QualType Type) {
-  return isRecordWithAttr(Type) || Type->isPointerType() ||
- Type->isNullPtrType();
-}
-
 // Returns true if the given Record decl is a form of `GSLOwner`
 // type, e.g. std::vector, std::optional.
 static bool isContainerOfPointer(const RecordDecl *Container) {
@@ -293,7 +279,7 @@ static bool isContainerOfPointer(const RecordDecl 
*Container) {
   return false;
 const auto &TAs = CTSD->getTemplateArgs();
 return TAs.size() > 0 && TAs[0].getKind() == TemplateArgument::Type &&
-   isPointerLikeType(TAs[0].getAsType());
+   Sema::isPointerLikeType(TAs[0].getAsType());
   }
   return false;
 }
@@ -306,7 +292,7 @@ static bool isContainerOfOwner(const RecordDecl *Container) 
{
 return false;
   const auto &TAs = CTSD->getTemplateArgs();
   return TAs.size() > 0 && TAs[0].getKind() == TemplateArgument::Type &&
- isRecordWithAttr(TAs[0].getAsType());
+ Sema::isRecordWithAttr(TAs[0].getAsType());
 }
 
 // Returns true if the given Record is `std::initializer_list`.
@@ -317,23 +303,24 @@ static bool isStdInitializerListOfPointer(const 
RecordDecl *RD) {
 return isInStlNamespace(RD) && RD->getIdentifier() &&
RD->getName() == "initializer_list" && TAs.size() > 0 &&
TAs[0].getKind() == TemplateArgument::Type &&
-   isPointerLikeType(TAs[0].getAsType());
+   Sema::isPointerLikeType(TAs[0].getAsType());
   }
 

[clang] [llvm] [AArch64] Implement intrinsics for F1CVTL/F2CVTL and BF1CVTL/BF2CVTL (PR #116959)

2024-11-28 Thread via cfe-commits

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

Thank you Spencer!
LGTM!

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


[clang] [clang] Check specialization for annotation (PR #117315)

2024-11-28 Thread Utkarsh Saxena via cfe-commits


@@ -1763,6 +1763,8 @@ class Sema final : public SemaBase {
   /// Add [[gsl::Pointer]] attributes for std:: types.
   void inferGslPointerAttribute(TypedefNameDecl *TD);
 
+  static bool isPointerLikeType(QualType QT);

usx95 wrote:

Added comments. Also moved to CheckExprLifetime.h.
I guess that is better to avoid wrong usages.

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


[clang] [compiler-rt] [llvm] [SystemZ] Add support for half (fp16) (PR #109164)

2024-11-28 Thread Ulrich Weigand via cfe-commits


@@ -1883,6 +1931,10 @@ void SystemZInstrInfo::getLoadStoreOpcodes(const 
TargetRegisterClass *RC,
   } else if (RC == &SystemZ::FP128BitRegClass) {
 LoadOpcode = SystemZ::LX;
 StoreOpcode = SystemZ::STX;
+  } else if (RC == &SystemZ::FP16BitRegClass ||
+ RC == &SystemZ::VR16BitRegClass) {
+LoadOpcode = SystemZ::VL16;

uweigand wrote:

What I meant is that `VL16` is defined as having a `v16hb` return value
```
def VL16 : UnaryAliasVRX;
```
and `v16hb` is defined to live in `VR16` - *not* `FP16`:
```
def v16hb   : TypedReg;
```

So it seems to me forcing a `FP16` register into the instruction, even if it 
might seem to do what we want, is not really allowed and might e.g. trigger 
strict MI checking failures ...


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


[clang] [clang] Check specialization for annotation (PR #117315)

2024-11-28 Thread Haojian Wu via cfe-commits

hokein wrote:

The PR description needs to update as well.

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


[clang] [clang] Check specialization for annotation (PR #117315)

2024-11-28 Thread Haojian Wu via cfe-commits

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


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


[clang] [clang] Check specialization for annotation (PR #117315)

2024-11-28 Thread Haojian Wu via cfe-commits


@@ -1763,6 +1763,8 @@ class Sema final : public SemaBase {
   /// Add [[gsl::Pointer]] attributes for std:: types.
   void inferGslPointerAttribute(TypedefNameDecl *TD);
 
+  static bool isPointerLikeType(QualType QT);

hokein wrote:

nit: please add some comments for this API. I think it is worth clarifying that 
it is only used for the lifetime analysis (to avoid misuse).

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


[clang] [clang] Check specialization for annotation (PR #117315)

2024-11-28 Thread Utkarsh Saxena via cfe-commits

https://github.com/usx95 updated 
https://github.com/llvm/llvm-project/pull/117315

>From e30ae8a6e0c1df8e33c2add6502342cb269c1cfd Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Fri, 22 Nov 2024 11:02:49 +
Subject: [PATCH 1/7] [clang] Check specialization for annotation

---
 clang/lib/Sema/CheckExprLifetime.cpp | 9 ++---
 1 file changed, 6 insertions(+), 3 deletions(-)

diff --git a/clang/lib/Sema/CheckExprLifetime.cpp 
b/clang/lib/Sema/CheckExprLifetime.cpp
index 8886e5e307ddf8..64dc4794b6235a 100644
--- a/clang/lib/Sema/CheckExprLifetime.cpp
+++ b/clang/lib/Sema/CheckExprLifetime.cpp
@@ -253,9 +253,12 @@ static void 
visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
   LocalVisitor Visit);
 
 template  static bool isRecordWithAttr(QualType Type) {
-  if (auto *RD = Type->getAsCXXRecordDecl())
-return RD->hasAttr();
-  return false;
+  auto *RD = Type->getAsCXXRecordDecl();
+  if (!RD)
+return false;
+  if (auto *CTSD = dyn_cast(RD))
+RD = CTSD->getSpecializedTemplate()->getTemplatedDecl();
+  return RD->hasAttr();
 }
 
 // Decl::isInStdNamespace will return false for iterators in some STL

>From db163394b70054694734c269f5fd61ef438eda3b Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Thu, 28 Nov 2024 09:01:25 +
Subject: [PATCH 2/7] move to Sema.h

---
 clang/include/clang/Sema/Sema.h  | 12 
 clang/lib/Sema/CheckExprLifetime.cpp | 45 ++--
 clang/lib/Sema/SemaAttr.cpp  |  5 
 3 files changed, 33 insertions(+), 29 deletions(-)

diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 6ea6c67447b6f0..9029d54e90f028 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -1760,6 +1760,18 @@ class Sema final : public SemaBase {
   /// Add [[gsl::Pointer]] attributes for std:: types.
   void inferGslPointerAttribute(TypedefNameDecl *TD);
 
+  template  static bool isRecordWithAttr(QualType Type) {
+auto *RD = Type->getAsCXXRecordDecl();
+if (!RD)
+  return false;
+if (auto *CTSD = dyn_cast(RD))
+  RD = CTSD->getSpecializedTemplate()->getTemplatedDecl();
+return RD->hasAttr();
+  }
+
+  /// 
+  static bool isPointerLikeType(QualType Type);
+
   LifetimeCaptureByAttr *ParseLifetimeCaptureByAttr(const ParsedAttr &AL,
 StringRef ParamName);
   // Processes the argument 'X' in [[clang::lifetime_capture_by(X)]]. Since 'X'
diff --git a/clang/lib/Sema/CheckExprLifetime.cpp 
b/clang/lib/Sema/CheckExprLifetime.cpp
index 64dc4794b6235a..e18651d8e12ab9 100644
--- a/clang/lib/Sema/CheckExprLifetime.cpp
+++ b/clang/lib/Sema/CheckExprLifetime.cpp
@@ -252,15 +252,6 @@ static void 
visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
   Expr *Init, ReferenceKind RK,
   LocalVisitor Visit);
 
-template  static bool isRecordWithAttr(QualType Type) {
-  auto *RD = Type->getAsCXXRecordDecl();
-  if (!RD)
-return false;
-  if (auto *CTSD = dyn_cast(RD))
-RD = CTSD->getSpecializedTemplate()->getTemplatedDecl();
-  return RD->hasAttr();
-}
-
 // Decl::isInStdNamespace will return false for iterators in some STL
 // implementations due to them being defined in a namespace outside of the std
 // namespace.
@@ -279,11 +270,6 @@ static bool isInStlNamespace(const Decl *D) {
   return DC->isStdNamespace();
 }
 
-static bool isPointerLikeType(QualType Type) {
-  return isRecordWithAttr(Type) || Type->isPointerType() ||
- Type->isNullPtrType();
-}
-
 // Returns true if the given Record decl is a form of `GSLOwner`
 // type, e.g. std::vector, std::optional.
 static bool isContainerOfPointer(const RecordDecl *Container) {
@@ -293,7 +279,7 @@ static bool isContainerOfPointer(const RecordDecl 
*Container) {
   return false;
 const auto &TAs = CTSD->getTemplateArgs();
 return TAs.size() > 0 && TAs[0].getKind() == TemplateArgument::Type &&
-   isPointerLikeType(TAs[0].getAsType());
+   Sema::isPointerLikeType(TAs[0].getAsType());
   }
   return false;
 }
@@ -306,7 +292,7 @@ static bool isContainerOfOwner(const RecordDecl *Container) 
{
 return false;
   const auto &TAs = CTSD->getTemplateArgs();
   return TAs.size() > 0 && TAs[0].getKind() == TemplateArgument::Type &&
- isRecordWithAttr(TAs[0].getAsType());
+ Sema::isRecordWithAttr(TAs[0].getAsType());
 }
 
 // Returns true if the given Record is `std::initializer_list`.
@@ -317,23 +303,24 @@ static bool isStdInitializerListOfPointer(const 
RecordDecl *RD) {
 return isInStlNamespace(RD) && RD->getIdentifier() &&
RD->getName() == "initializer_list" && TAs.size() > 0 &&
TAs[0].getKind() == TemplateArgument::Type &&
-   isPointerLikeType(TAs[0].getAsType());
+   Sema::isPointerLikeType(TAs[0].getAsType());
   }
 

[clang] [llvm] [llvm][opt][Transforms][SPIR-V] Enable `InferAddressSpaces` for SPIR-V (PR #110897)

2024-11-28 Thread Alex Voicu via cfe-commits


@@ -0,0 +1,29 @@
+; NOTE: Assertions have been autogenerated by utils/update_test_checks.py

AlexVlx wrote:

Done.

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


[clang] [clang] Add a common definition of isPointerLikeType for lifetime analysis (PR #117315)

2024-11-28 Thread Utkarsh Saxena via cfe-commits

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


[clang] [clang] Add a common definition of isPointerLikeType for lifetime analysis (PR #117315)

2024-11-28 Thread Utkarsh Saxena via cfe-commits

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


[clang] [llvm] [RISCV] Add stack clash protection (PR #117612)

2024-11-28 Thread Raphael Moreira Zinsly via cfe-commits

https://github.com/rzinsly updated 
https://github.com/llvm/llvm-project/pull/117612

>From f6bb44ca2242623399eb0ea946f38399fed3807c Mon Sep 17 00:00:00 2001
From: Raphael Moreira Zinsly 
Date: Tue, 26 Nov 2024 16:40:37 -0300
Subject: [PATCH 1/3] [NFC][RISCV] Remove CFIIndex argument from
 RISCVFrameLowering::allocateStack

Calculates CFIIndex inside RISCVFrameLowering::allocateStack instead of
sending it by argument.
---
 llvm/lib/Target/RISCV/RISCVFrameLowering.cpp | 23 +---
 llvm/lib/Target/RISCV/RISCVFrameLowering.h   |  3 ++-
 2 files changed, 12 insertions(+), 14 deletions(-)

diff --git a/llvm/lib/Target/RISCV/RISCVFrameLowering.cpp 
b/llvm/lib/Target/RISCV/RISCVFrameLowering.cpp
index 1ff435b76ad68a..e2c9baa1b7b1f6 100644
--- a/llvm/lib/Target/RISCV/RISCVFrameLowering.cpp
+++ b/llvm/lib/Target/RISCV/RISCVFrameLowering.cpp
@@ -612,8 +612,9 @@ static MCCFIInstruction createDefCFAOffset(const 
TargetRegisterInfo &TRI,
 
 void RISCVFrameLowering::allocateStack(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MBBI,
-   StackOffset Offset, bool EmitCFI,
-   unsigned CFIIndex) const {
+   MachineFunction &MF, StackOffset Offset,
+   uint64_t RealStackSize,
+   bool EmitCFI) const {
   DebugLoc DL;
   const RISCVRegisterInfo *RI = STI.getRegisterInfo();
   const RISCVInstrInfo *TII = STI.getInstrInfo();
@@ -622,7 +623,9 @@ void RISCVFrameLowering::allocateStack(MachineBasicBlock 
&MBB,
 getStackAlign());
 
   if (EmitCFI) {
-// Emit ".cfi_def_cfa_offset StackSize"
+// Emit ".cfi_def_cfa_offset RealStackSize"
+unsigned CFIIndex = MF.addFrameInst(
+   MCCFIInstruction::cfiDefCfaOffset(nullptr, RealStackSize));
 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
 .addCFIIndex(CFIIndex)
 .setMIFlag(MachineInstr::FrameSetup);
@@ -745,10 +748,8 @@ void RISCVFrameLowering::emitPrologue(MachineFunction &MF,
 
   if (StackSize != 0) {
 // Allocate space on the stack if necessary.
-unsigned CFIIndex = MF.addFrameInst(
-MCCFIInstruction::cfiDefCfaOffset(nullptr, RealStackSize));
-allocateStack(MBB, MBBI, StackOffset::getFixed(-StackSize),
- /*EmitCFI=*/ true, CFIIndex);
+allocateStack(MBB, MBBI, MF, StackOffset::getFixed(-StackSize),
+ RealStackSize, /*EmitCFI=*/ true);
   }
 
   // The frame pointer is callee-saved, and code has been generated for us to
@@ -790,12 +791,8 @@ void RISCVFrameLowering::emitPrologue(MachineFunction &MF,
 assert(SecondSPAdjustAmount > 0 &&
"SecondSPAdjustAmount should be greater than zero");
 
-// If we are using a frame-pointer, and thus emitted ".cfi_def_cfa fp, 0",
-// don't emit an sp-based .cfi_def_cfa_offset
-unsigned CFIIndex = MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(
-nullptr, getStackSizeWithRVVPadding(MF)));
-allocateStack(MBB, MBBI, StackOffset::getFixed(-SecondSPAdjustAmount),
-  !hasFP(MF), CFIIndex);
+allocateStack(MBB, MBBI, MF, StackOffset::getFixed(-SecondSPAdjustAmount),
+  getStackSizeWithRVVPadding(MF), !hasFP(MF));
   }
 
   if (RVVStackSize) {
diff --git a/llvm/lib/Target/RISCV/RISCVFrameLowering.h 
b/llvm/lib/Target/RISCV/RISCVFrameLowering.h
index 9aff4dc9e4089a..8c2e3f0f3e5638 100644
--- a/llvm/lib/Target/RISCV/RISCVFrameLowering.h
+++ b/llvm/lib/Target/RISCV/RISCVFrameLowering.h
@@ -79,7 +79,8 @@ class RISCVFrameLowering : public TargetFrameLowering {
   }
 
   void allocateStack(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
- StackOffset Offset, bool EmitCFI, unsigned CFIIndex) 
const;
+ MachineFunction &MF, StackOffset Offset,
+ uint64_t RealStackSize, bool EmitCFI) const;
 
 protected:
   const RISCVSubtarget &STI;

>From 6a09d85096bdf08d0dfce5c1cb8b2cb22ec25eba Mon Sep 17 00:00:00 2001
From: Raphael Moreira Zinsly 
Date: Mon, 25 Nov 2024 14:51:35 -0300
Subject: [PATCH 2/3] [RISCV] Add initial stack clash protection

Enable `-fstack-clash-protection` for RISCV and stack probe for function
prologues.
We probe the stack by creating an unrolled loop that allocates and probe
the stack in ProbeSize chunks, this is not ideal if the loop has many
iterations.
---
 clang/lib/Driver/ToolChains/Clang.cpp |  3 +-
 llvm/lib/Target/RISCV/RISCVFrameLowering.cpp  | 90 +++
 llvm/lib/Target/RISCV/RISCVFrameLowering.h|  5 +-
 llvm/lib/Target/RISCV/RISCVISelLowering.cpp   | 22 +
 llvm/lib/Target/RISCV/RISCVISelLowering.h |  5 ++
 .../Target/RISCV/RISCVMachineFunctionInfo.cpp | 30 +++
 .../Target/RISCV/RISCVMachineFunctionInfo.h   |  7 +-
 llvm/lib/Target/RISCV/RISCVTargetMachine.cpp  |  4 +-
 .../RISCV/stack-clash-prologue-

[clang] [llvm] [RISCV] Add stack clash protection (PR #117612)

2024-11-28 Thread Raphael Moreira Zinsly via cfe-commits


@@ -610,22 +610,134 @@ static MCCFIInstruction createDefCFAOffset(const 
TargetRegisterInfo &TRI,
 Comment.str());
 }
 
+// Allocate stack space and probe it if necessary.
 void RISCVFrameLowering::allocateStack(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MBBI,
-   StackOffset Offset, bool EmitCFI,
-   unsigned CFIIndex) const {
+   MachineFunction &MF, uint64_t Offset,
+   uint64_t RealStackSize, bool EmitCFI,
+   bool NeedProbe,
+   uint64_t ProbeSize) const {
   DebugLoc DL;
   const RISCVRegisterInfo *RI = STI.getRegisterInfo();
   const RISCVInstrInfo *TII = STI.getInstrInfo();
 
-  RI->adjustReg(MBB, MBBI, DL, SPReg, SPReg, Offset, MachineInstr::FrameSetup,
+  // Simply allocate the stack if it's not big enough to require a probe.
+  if (!NeedProbe || Offset <= ProbeSize) {
+RI->adjustReg(MBB, MBBI, DL, SPReg, SPReg, StackOffset::getFixed(-Offset),
+  MachineInstr::FrameSetup, getStackAlign());
+
+if (EmitCFI) {
+  // Emit ".cfi_def_cfa_offset RealStackSize"
+  unsigned CFIIndex = MF.addFrameInst(
+  MCCFIInstruction::cfiDefCfaOffset(nullptr, RealStackSize));
+  BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
+  .addCFIIndex(CFIIndex)
+  .setMIFlag(MachineInstr::FrameSetup);
+}
+
+return;
+  }
+
+  // Unroll the probe loop depending on the number of iterations.
+  if (Offset < ProbeSize * 5) {
+uint64_t CurrentOffset = 0;
+bool IsRV64 = STI.is64Bit();
+while (CurrentOffset + ProbeSize <= Offset) {
+  RI->adjustReg(MBB, MBBI, DL, SPReg, SPReg,
+StackOffset::getFixed(-ProbeSize), 
MachineInstr::FrameSetup,
+getStackAlign());
+  // s[d|w] zero, 0(sp)
+  BuildMI(MBB, MBBI, DL, TII->get(IsRV64 ? RISCV::SD : RISCV::SW))
+  .addReg(RISCV::X0)
+  .addReg(SPReg)
+  .addImm(0)
+  .setMIFlags(MachineInstr::FrameSetup);
+
+  CurrentOffset += ProbeSize;
+  if (EmitCFI) {
+// Emit ".cfi_def_cfa_offset CurrentOffset"
+unsigned CFIIndex = MF.addFrameInst(
+MCCFIInstruction::cfiDefCfaOffset(nullptr, CurrentOffset));
+BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
+.addCFIIndex(CFIIndex)
+.setMIFlag(MachineInstr::FrameSetup);
+  }
+}
+
+uint64_t Residual = Offset - CurrentOffset;
+if (Residual) {
+  RI->adjustReg(MBB, MBBI, DL, SPReg, SPReg,
+StackOffset::getFixed(-Residual), MachineInstr::FrameSetup,
+getStackAlign());
+  if (EmitCFI) {
+// Emit ".cfi_def_cfa_offset Offset"
+unsigned CFIIndex =
+MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, 
Offset));
+BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
+.addCFIIndex(CFIIndex)
+.setMIFlag(MachineInstr::FrameSetup);
+  }
+}
+
+return;
+  }
+
+  // Emit a variable-length allocation probing loop.
+  uint64_t RoundedSize = (Offset / ProbeSize) * ProbeSize;
+  uint64_t Residual = Offset - RoundedSize;
+
+  Register TargetReg = RISCV::X6;
+  // SUB TargetReg, SP, RoundedSize
+  RI->adjustReg(MBB, MBBI, DL, TargetReg, SPReg,
+StackOffset::getFixed(-RoundedSize), MachineInstr::FrameSetup,
 getStackAlign());
 
   if (EmitCFI) {
-// Emit ".cfi_def_cfa_offset StackSize"
+// Set the CFA register to TargetReg.
+unsigned Reg = STI.getRegisterInfo()->getDwarfRegNum(TargetReg, true);
+unsigned CFIIndex =
+MF.addFrameInst(MCCFIInstruction::cfiDefCfa(nullptr, Reg, 
RoundedSize));
 BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
 .addCFIIndex(CFIIndex)
-.setMIFlag(MachineInstr::FrameSetup);
+.setMIFlags(MachineInstr::FrameSetup);
+  }
+
+  // It will be expanded to a probe loop in `inlineStackProbe`.
+  BuildMI(MBB, MBBI, DL, TII->get(RISCV::PROBED_STACKALLOC))
+  .addReg(SPReg)
+  .addReg(TargetReg);
+
+  if (EmitCFI) {
+// Set the CFA register back to SP.
+unsigned Reg = STI.getRegisterInfo()->getDwarfRegNum(SPReg, true);
+unsigned CFIIndex =
+MF.addFrameInst(MCCFIInstruction::createDefCfaRegister(nullptr, Reg));
+BuildMI(MBB, MBBI, DL, TII->get(TargetOpcode::CFI_INSTRUCTION))
+.addCFIIndex(CFIIndex)
+.setMIFlags(MachineInstr::FrameSetup);
+  }
+
+  if (Residual) {
+RI->adjustReg(MBB, MBBI, DL, SPReg, SPReg, 
StackOffset::getFixed(-Residual),
+  MachineInstr::FrameSetup, getStackAlign());
+if (Residual > ProbeSize) {
+  // s[d|w] zero, 0(sp)
+  bool IsRV64 = STI.hasFeature(

[clang] [clang] Add a common definition of isPointerLikeType for lifetime analysis (PR #117315)

2024-11-28 Thread Haojian Wu via cfe-commits


@@ -1763,6 +1763,8 @@ class Sema final : public SemaBase {
   /// Add [[gsl::Pointer]] attributes for std:: types.
   void inferGslPointerAttribute(TypedefNameDecl *TD);
 
+  static bool isPointerLikeType(QualType QT);

hokein wrote:

Oh, nice! Moving to `checkExprLifetime.h` makes more sense.

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


[clang] [clang] Add a common definition of isPointerLikeType for lifetime analysis (PR #117315)

2024-11-28 Thread Haojian Wu via cfe-commits

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


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


[clang] [analyzer][NFC] Cleanup BranchNodeBuilder (PR #117898)

2024-11-28 Thread Donát Nagy via cfe-commits

NagyDonat wrote:

I didn't run an analysis yet, because I was convinced about the correctness of 
this change based on an understanding of the source code (and the fact that the 
lit tests pass). However, I started a test run now to double-check this. I'll 
merge this commit if it reveals no discrepancies.

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


[clang] [llvm] Codegen changes for strict modifier with grainsize/num_tasks of taskloop construct (PR #117196)

2024-11-28 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder 
`openmp-offload-libc-amdgpu-runtime` running on `omp-vega20-1` while building 
`clang,llvm` at step 7 "Add check check-offload".

Full details are available at: 
https://lab.llvm.org/buildbot/#/builders/73/builds/9286


Here is the relevant piece of the build log for the reference

```
Step 7 (Add check check-offload) failure: test (failure)
 TEST 'libomptarget :: amdgcn-amd-amdhsa :: 
offloading/thread_state_1.c' FAILED 
Exit Code: 2

Command Output (stdout):
--
# RUN: at line 1
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/./bin/clang 
-fopenmp-I 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.src/offload/test 
-I 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/openmp/runtime/src
 -L 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload
 -L /home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/./lib -L 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/openmp/runtime/src
  -nogpulib 
-Wl,-rpath,/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload
 
-Wl,-rpath,/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/openmp/runtime/src
 
-Wl,-rpath,/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/./lib
  -fopenmp-targets=amdgcn-amd-amdhsa 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.src/offload/test/offloading/thread_state_1.c
 -o 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload/test/amdgcn-amd-amdhsa/offloading/Output/thread_state_1.c.tmp
 -Xoffload-linker -lc -Xoffload-linker -lm 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/./lib/libomptarget.devicertl.a
 && 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload/test/amdgcn-amd-amdhsa/offloading/Output/thread_state_1.c.tmp
 | 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/./bin/FileCheck
 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.src/offload/test/offloading/thread_state_1.c
# executed command: 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/./bin/clang 
-fopenmp -I 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.src/offload/test 
-I 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/openmp/runtime/src
 -L 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload
 -L /home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/./lib -L 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/openmp/runtime/src
 -nogpulib 
-Wl,-rpath,/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload
 
-Wl,-rpath,/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/openmp/runtime/src
 
-Wl,-rpath,/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/./lib
 -fopenmp-targets=amdgcn-amd-amdhsa 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.src/offload/test/offloading/thread_state_1.c
 -o 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload/test/amdgcn-amd-amdhsa/offloading/Output/thread_state_1.c.tmp
 -Xoffload-linker -lc -Xoffload-linker -lm 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/./lib/libomptarget.devicertl.a
# executed command: 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload/test/amdgcn-amd-amdhsa/offloading/Output/thread_state_1.c.tmp
# executed command: 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/./bin/FileCheck
 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.src/offload/test/offloading/thread_state_1.c
# RUN: at line 2
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/./bin/clang 
-fopenmp-I 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.src/offload/test 
-I 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/openmp/runtime/src
 -L 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload
 -L /home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/./lib -L 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/openmp/runtime/src
  -nogpulib 
-Wl,-rpath,/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/offload
 
-Wl,-rpath,/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/runtimes/runtimes-bins/openmp/runtime/src
 
-Wl,-rpath,/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/

[clang] [llvm] Codegen changes for strict modifier with grainsize/num_tasks of taskloop construct (PR #117196)

2024-11-28 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder 
`libc-x86_64-debian-fullbuild-dbg-asan` running on 
`libc-x86_64-debian-fullbuild` while building `clang,llvm` at step 4 "annotate".

Full details are available at: 
https://lab.llvm.org/buildbot/#/builders/171/builds/11252


Here is the relevant piece of the build log for the reference

```
Step 4 (annotate) failure: 'python 
../llvm-zorg/zorg/buildbot/builders/annotated/libc-linux.py ...' (failure)
...
[==] Running 4 tests from 1 test suite.
[ RUN  ] LlvmLibcHashTest.SanityCheck
[   OK ] LlvmLibcHashTest.SanityCheck (16 ms)
[ RUN  ] LlvmLibcHashTest.Avalanche
[   OK ] LlvmLibcHashTest.Avalanche (2144 ms)
[ RUN  ] LlvmLibcHashTest.UniformLSB
[   OK ] LlvmLibcHashTest.UniformLSB (202 ms)
[ RUN  ] LlvmLibcHashTest.UniformMSB
[   OK ] LlvmLibcHashTest.UniformMSB (135 us)
Ran 4 tests.  PASS: 4  FAIL: 0
command timed out: 1200 seconds without output running [b'python', 
b'../llvm-zorg/zorg/buildbot/builders/annotated/libc-linux.py', b'--debug', 
b'--asan'], attempting to kill
process killed by signal 9
program finished with exit code -1
elapsedTime=1259.659335
Step 8 (libc-unit-tests) failure: libc-unit-tests (failure)
...
[ RUN  ] LlvmLibcStrtoint32Test.InvalidBase
[   OK ] LlvmLibcStrtoint32Test.InvalidBase (51 us)
[ RUN  ] LlvmLibcStrtoint32Test.CleanBaseTenDecode
[   OK ] LlvmLibcStrtoint32Test.CleanBaseTenDecode (122 us)
[ RUN  ] LlvmLibcStrtoint32Test.MessyBaseTenDecode
[   OK ] LlvmLibcStrtoint32Test.MessyBaseTenDecode (65 us)
[ RUN  ] LlvmLibcStrtoint32Test.DecodeInOtherBases
[   OK ] LlvmLibcStrtoint32Test.DecodeInOtherBases (462 ms)
[ RUN  ] LlvmLibcStrtoint32Test.CleanBaseSixteenDecode
[   OK ] LlvmLibcStrtoint32Test.CleanBaseSixteenDecode (111 us)
[ RUN  ] LlvmLibcStrtoint32Test.MessyBaseSixteenDecode
[   OK ] LlvmLibcStrtoint32Test.MessyBaseSixteenDecode (75 us)
[ RUN  ] LlvmLibcStrtoint32Test.AutomaticBaseSelection
[   OK ] LlvmLibcStrtoint32Test.AutomaticBaseSelection (28 us)
[ RUN  ] LlvmLibcStrtouint32Test.InvalidBase
[   OK ] LlvmLibcStrtouint32Test.InvalidBase (43 us)
[ RUN  ] LlvmLibcStrtouint32Test.CleanBaseTenDecode
[   OK ] LlvmLibcStrtouint32Test.CleanBaseTenDecode (52 us)
[ RUN  ] LlvmLibcStrtouint32Test.MessyBaseTenDecode
[   OK ] LlvmLibcStrtouint32Test.MessyBaseTenDecode (74 us)
[ RUN  ] LlvmLibcStrtouint32Test.DecodeInOtherBases
[   OK ] LlvmLibcStrtouint32Test.DecodeInOtherBases (227 ms)
[ RUN  ] LlvmLibcStrtouint32Test.CleanBaseSixteenDecode
[   OK ] LlvmLibcStrtouint32Test.CleanBaseSixteenDecode (71 us)
[ RUN  ] LlvmLibcStrtouint32Test.MessyBaseSixteenDecode
[   OK ] LlvmLibcStrtouint32Test.MessyBaseSixteenDecode (43 us)
[ RUN  ] LlvmLibcStrtouint32Test.AutomaticBaseSelection
[   OK ] LlvmLibcStrtouint32Test.AutomaticBaseSelection (9 us)
Ran 14 tests.  PASS: 14  FAIL: 0
[1096/1098] Running unit test libc.test.src.time.nanosleep_test.__unit__
[==] Running 1 test from 1 test suite.
[ RUN  ] LlvmLibcNanosleep.SmokeTest
[   OK ] LlvmLibcNanosleep.SmokeTest (132 us)
Ran 1 tests.  PASS: 1  FAIL: 0
[1097/1098] Running unit test libc.test.src.__support.hash_test.__unit__
[==] Running 4 tests from 1 test suite.
[ RUN  ] LlvmLibcHashTest.SanityCheck
[   OK ] LlvmLibcHashTest.SanityCheck (16 ms)
[ RUN  ] LlvmLibcHashTest.Avalanche
[   OK ] LlvmLibcHashTest.Avalanche (2144 ms)
[ RUN  ] LlvmLibcHashTest.UniformLSB
[   OK ] LlvmLibcHashTest.UniformLSB (202 ms)
[ RUN  ] LlvmLibcHashTest.UniformMSB
[   OK ] LlvmLibcHashTest.UniformMSB (135 us)
Ran 4 tests.  PASS: 4  FAIL: 0

command timed out: 1200 seconds without output running [b'python', 
b'../llvm-zorg/zorg/buildbot/builders/annotated/libc-linux.py', b'--debug', 
b'--asan'], attempting to kill
process killed by signal 9
program finished with exit code -1
elapsedTime=1259.659335

```



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


[clang] [clang] Check specialization for annotation (PR #117315)

2024-11-28 Thread Utkarsh Saxena via cfe-commits

https://github.com/usx95 updated 
https://github.com/llvm/llvm-project/pull/117315

>From e30ae8a6e0c1df8e33c2add6502342cb269c1cfd Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Fri, 22 Nov 2024 11:02:49 +
Subject: [PATCH 1/3] [clang] Check specialization for annotation

---
 clang/lib/Sema/CheckExprLifetime.cpp | 9 ++---
 1 file changed, 6 insertions(+), 3 deletions(-)

diff --git a/clang/lib/Sema/CheckExprLifetime.cpp 
b/clang/lib/Sema/CheckExprLifetime.cpp
index 8886e5e307ddf8..64dc4794b6235a 100644
--- a/clang/lib/Sema/CheckExprLifetime.cpp
+++ b/clang/lib/Sema/CheckExprLifetime.cpp
@@ -253,9 +253,12 @@ static void 
visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
   LocalVisitor Visit);
 
 template  static bool isRecordWithAttr(QualType Type) {
-  if (auto *RD = Type->getAsCXXRecordDecl())
-return RD->hasAttr();
-  return false;
+  auto *RD = Type->getAsCXXRecordDecl();
+  if (!RD)
+return false;
+  if (auto *CTSD = dyn_cast(RD))
+RD = CTSD->getSpecializedTemplate()->getTemplatedDecl();
+  return RD->hasAttr();
 }
 
 // Decl::isInStdNamespace will return false for iterators in some STL

>From db163394b70054694734c269f5fd61ef438eda3b Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Thu, 28 Nov 2024 09:01:25 +
Subject: [PATCH 2/3] move to Sema.h

---
 clang/include/clang/Sema/Sema.h  | 12 
 clang/lib/Sema/CheckExprLifetime.cpp | 45 ++--
 clang/lib/Sema/SemaAttr.cpp  |  5 
 3 files changed, 33 insertions(+), 29 deletions(-)

diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 6ea6c67447b6f0..9029d54e90f028 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -1760,6 +1760,18 @@ class Sema final : public SemaBase {
   /// Add [[gsl::Pointer]] attributes for std:: types.
   void inferGslPointerAttribute(TypedefNameDecl *TD);
 
+  template  static bool isRecordWithAttr(QualType Type) {
+auto *RD = Type->getAsCXXRecordDecl();
+if (!RD)
+  return false;
+if (auto *CTSD = dyn_cast(RD))
+  RD = CTSD->getSpecializedTemplate()->getTemplatedDecl();
+return RD->hasAttr();
+  }
+
+  /// 
+  static bool isPointerLikeType(QualType Type);
+
   LifetimeCaptureByAttr *ParseLifetimeCaptureByAttr(const ParsedAttr &AL,
 StringRef ParamName);
   // Processes the argument 'X' in [[clang::lifetime_capture_by(X)]]. Since 'X'
diff --git a/clang/lib/Sema/CheckExprLifetime.cpp 
b/clang/lib/Sema/CheckExprLifetime.cpp
index 64dc4794b6235a..e18651d8e12ab9 100644
--- a/clang/lib/Sema/CheckExprLifetime.cpp
+++ b/clang/lib/Sema/CheckExprLifetime.cpp
@@ -252,15 +252,6 @@ static void 
visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
   Expr *Init, ReferenceKind RK,
   LocalVisitor Visit);
 
-template  static bool isRecordWithAttr(QualType Type) {
-  auto *RD = Type->getAsCXXRecordDecl();
-  if (!RD)
-return false;
-  if (auto *CTSD = dyn_cast(RD))
-RD = CTSD->getSpecializedTemplate()->getTemplatedDecl();
-  return RD->hasAttr();
-}
-
 // Decl::isInStdNamespace will return false for iterators in some STL
 // implementations due to them being defined in a namespace outside of the std
 // namespace.
@@ -279,11 +270,6 @@ static bool isInStlNamespace(const Decl *D) {
   return DC->isStdNamespace();
 }
 
-static bool isPointerLikeType(QualType Type) {
-  return isRecordWithAttr(Type) || Type->isPointerType() ||
- Type->isNullPtrType();
-}
-
 // Returns true if the given Record decl is a form of `GSLOwner`
 // type, e.g. std::vector, std::optional.
 static bool isContainerOfPointer(const RecordDecl *Container) {
@@ -293,7 +279,7 @@ static bool isContainerOfPointer(const RecordDecl 
*Container) {
   return false;
 const auto &TAs = CTSD->getTemplateArgs();
 return TAs.size() > 0 && TAs[0].getKind() == TemplateArgument::Type &&
-   isPointerLikeType(TAs[0].getAsType());
+   Sema::isPointerLikeType(TAs[0].getAsType());
   }
   return false;
 }
@@ -306,7 +292,7 @@ static bool isContainerOfOwner(const RecordDecl *Container) 
{
 return false;
   const auto &TAs = CTSD->getTemplateArgs();
   return TAs.size() > 0 && TAs[0].getKind() == TemplateArgument::Type &&
- isRecordWithAttr(TAs[0].getAsType());
+ Sema::isRecordWithAttr(TAs[0].getAsType());
 }
 
 // Returns true if the given Record is `std::initializer_list`.
@@ -317,23 +303,24 @@ static bool isStdInitializerListOfPointer(const 
RecordDecl *RD) {
 return isInStlNamespace(RD) && RD->getIdentifier() &&
RD->getName() == "initializer_list" && TAs.size() > 0 &&
TAs[0].getKind() == TemplateArgument::Type &&
-   isPointerLikeType(TAs[0].getAsType());
+   Sema::isPointerLikeType(TAs[0].getAsType());
   }
 

[clang] [clang] Improve the lifetime_capture_by diagnostic on the constructor. (PR #117792)

2024-11-28 Thread Haojian Wu via cfe-commits

https://github.com/hokein updated 
https://github.com/llvm/llvm-project/pull/117792

>From edd8e7354c4ff96446d32830f4cd5e6c3c333a84 Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Tue, 26 Nov 2024 21:42:45 +0100
Subject: [PATCH 1/3] [clang] Improve the lifetime_capture_by diagnostic on the
 constructor.

---
 clang/lib/Sema/CheckExprLifetime.cpp  | 11 +++
 clang/lib/Sema/SemaChecking.cpp   |  6 ++
 .../warn-lifetime-analysis-capture-by.cpp | 19 +++
 3 files changed, 36 insertions(+)

diff --git a/clang/lib/Sema/CheckExprLifetime.cpp 
b/clang/lib/Sema/CheckExprLifetime.cpp
index 6cdd4dc629e50a..c4fa73127410b5 100644
--- a/clang/lib/Sema/CheckExprLifetime.cpp
+++ b/clang/lib/Sema/CheckExprLifetime.cpp
@@ -535,6 +535,9 @@ static void visitFunctionCallArguments(IndirectLocalPath 
&Path, Expr *Call,
 
   bool EnableGSLAnalysis = !Callee->getASTContext().getDiagnostics().isIgnored(
   diag::warn_dangling_lifetime_pointer, SourceLocation());
+  bool EnableDanglingCapture =
+  !Callee->getASTContext().getDiagnostics().isIgnored(
+  diag::warn_dangling_reference_captured, SourceLocation());
   Expr *ObjectArg = nullptr;
   if (isa(Call) && Callee->isCXXInstanceMember()) {
 ObjectArg = Args[0];
@@ -623,6 +626,14 @@ static void visitFunctionCallArguments(IndirectLocalPath 
&Path, Expr *Call,
 }
 if (CheckCoroCall || Callee->getParamDecl(I)->hasAttr())
   VisitLifetimeBoundArg(Callee->getParamDecl(I), Arg);
+else if (const auto *CaptureAttr =
+ Callee->getParamDecl(I)->getAttr();
+ EnableDanglingCapture && CaptureAttr &&
+ isa(Callee) &&
+ llvm::any_of(CaptureAttr->params(), [](int ArgIdx) {
+   return ArgIdx == LifetimeCaptureByAttr::THIS;
+ }))
+  VisitLifetimeBoundArg(Callee->getParamDecl(I), Arg);
 else if (EnableGSLAnalysis && I == 0) {
   // Perform GSL analysis for the first argument
   if (shouldTrackFirstArgument(Callee)) {
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index a49605e4867651..1605523097a6b1 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -3240,8 +3240,14 @@ void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool 
IsMemberFunction,
  unsigned ArgIdx) {
 if (!Attr)
   return;
+
 Expr *Captured = const_cast(GetArgAt(ArgIdx));
 for (int CapturingParamIdx : Attr->params()) {
+  // lifetime_capture_by(this) case is handled in the lifetimebound expr
+  // initialization codepath.
+  if (CapturingParamIdx == LifetimeCaptureByAttr::THIS &&
+  isa(FD))
+continue;
   Expr *Capturing = const_cast(GetArgAt(CapturingParamIdx));
   CapturingEntity CE{Capturing};
   // Ensure that 'Captured' outlives the 'Capturing' entity.
diff --git a/clang/test/Sema/warn-lifetime-analysis-capture-by.cpp 
b/clang/test/Sema/warn-lifetime-analysis-capture-by.cpp
index 4d562bac1e305b..77523210e50203 100644
--- a/clang/test/Sema/warn-lifetime-analysis-capture-by.cpp
+++ b/clang/test/Sema/warn-lifetime-analysis-capture-by.cpp
@@ -411,3 +411,22 @@ void use() {
 }
 } // namespace with_span
 } // namespace inferred_capture_by
+
+namespace on_constructor {
+struct T {
+  T(const int& t [[clang::lifetime_capture_by(this)]]);
+};
+struct T2 {
+  T2(const int& t [[clang::lifetime_capture_by(x)]], int& x);
+};
+int foo(const T& t);
+
+void test() {
+  auto x = foo(T(1)); // OK. no diagnosic
+  T(1); // OK. no diagnostic
+  T t(1); // expected-warning {{temporary whose address is used}}
+
+  int a;
+  T2(1, a); // expected-warning {{object whose reference is captured by}}
+}
+} // namespace on_constructor

>From 48487a5b1f9b87c295ce1d6df7d0fc60a7db6695 Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Thu, 28 Nov 2024 10:12:40 +0100
Subject: [PATCH 2/3] Address comments

---
 clang/lib/Sema/CheckExprLifetime.cpp  | 19 ++-
 .../warn-lifetime-analysis-capture-by.cpp |  7 +++
 2 files changed, 21 insertions(+), 5 deletions(-)

diff --git a/clang/lib/Sema/CheckExprLifetime.cpp 
b/clang/lib/Sema/CheckExprLifetime.cpp
index c4fa73127410b5..607b7daf878e17 100644
--- a/clang/lib/Sema/CheckExprLifetime.cpp
+++ b/clang/lib/Sema/CheckExprLifetime.cpp
@@ -535,9 +535,6 @@ static void visitFunctionCallArguments(IndirectLocalPath 
&Path, Expr *Call,
 
   bool EnableGSLAnalysis = !Callee->getASTContext().getDiagnostics().isIgnored(
   diag::warn_dangling_lifetime_pointer, SourceLocation());
-  bool EnableDanglingCapture =
-  !Callee->getASTContext().getDiagnostics().isIgnored(
-  diag::warn_dangling_reference_captured, SourceLocation());
   Expr *ObjectArg = nullptr;
   if (isa(Call) && Callee->isCXXInstanceMember()) {
 ObjectArg = Args[0];
@@ -628,11 +625,23 @@ static void visitFunctionCallArguments(IndirectLocalPath 
&Path, Expr *Call,
   VisitLifetimeBoundAr

[clang] [clang] Improve the lifetime_capture_by diagnostic on the constructor. (PR #117792)

2024-11-28 Thread Haojian Wu via cfe-commits


@@ -623,6 +623,26 @@ static void visitFunctionCallArguments(IndirectLocalPath 
&Path, Expr *Call,
 }
 if (CheckCoroCall || Callee->getParamDecl(I)->hasAttr())
   VisitLifetimeBoundArg(Callee->getParamDecl(I), Arg);
+else if (const auto *CaptureAttr =
+ Callee->getParamDecl(I)->getAttr();
+ CaptureAttr && isa(Callee) &&
+ llvm::any_of(CaptureAttr->params(), [](int ArgIdx) {
+   return ArgIdx == LifetimeCaptureByAttr::THIS;
+ }))
+  // `lifetime_capture_by(this)` in a class constructor has the same
+  // semantics as `lifetimebound`:
+  //
+  // struct Foo {
+  //   const int& a;
+  //   // Equivalent to Foo(const int& t [[clang::lifetimebound]])
+  //   Foo(const int& t [[clang::lifetime_capture_by(this)]]) : a(t) {}
+  // };
+  //
+  // In the implementation, `lifetime_capture_by` is treated as an alias 
for
+  // `lifetimebound` and shares the same code path. This implies the 
emitted
+  // diagnostics will be emitted under `-Wdangling`, not
+  // `-Wdangling-capture`.
+  VisitLifetimeBoundArg(Callee->getParamDecl(I), Arg);

hokein wrote:

Done.

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


[clang] [llvm] [AArch64] Implement intrinsics for F1CVTL/F2CVTL and BF1CVTL/BF2CVTL (PR #116959)

2024-11-28 Thread via cfe-commits

https://github.com/SpencerAbson updated 
https://github.com/llvm/llvm-project/pull/116959

>From 296492155525985942e1a0fc56b6f0db34e8a7a4 Mon Sep 17 00:00:00 2001
From: Spencer Abson 
Date: Wed, 20 Nov 2024 10:57:49 +
Subject: [PATCH 1/7] [AArch64] Add intrinsics for F1CVTL/F2CVTL and
 BF1CVTL/BF2CVTL

---
 clang/include/clang/Basic/TargetBuiltins.h|  1 +
 clang/include/clang/Basic/arm_sme.td  |  7 ++
 clang/include/clang/Basic/arm_sve_sme_incl.td |  2 +
 clang/lib/CodeGen/CGBuiltin.cpp   |  4 +
 .../fp8-intrinsics/acle_sme2_fp8_cvt.c| 81 +++
 clang/utils/TableGen/SveEmitter.cpp   |  6 ++
 llvm/include/llvm/IR/IntrinsicsAArch64.td | 17 
 .../Target/AArch64/AArch64ISelDAGToDAG.cpp| 34 
 llvm/lib/Target/AArch64/SMEInstrFormats.td|  2 +-
 .../AArch64/sme2-fp8-intrinsics-cvt.ll| 48 +++
 10 files changed, 201 insertions(+), 1 deletion(-)
 create mode 100644 
clang/test/CodeGen/AArch64/fp8-intrinsics/acle_sme2_fp8_cvt.c
 create mode 100644 llvm/test/CodeGen/AArch64/sme2-fp8-intrinsics-cvt.ll

diff --git a/clang/include/clang/Basic/TargetBuiltins.h 
b/clang/include/clang/Basic/TargetBuiltins.h
index 89ebf5758a5b55..a14fd2c4b224d8 100644
--- a/clang/include/clang/Basic/TargetBuiltins.h
+++ b/clang/include/clang/Basic/TargetBuiltins.h
@@ -336,6 +336,7 @@ namespace clang {
 bool isTupleSet() const { return Flags & IsTupleSet; }
 bool isReadZA() const { return Flags & IsReadZA; }
 bool isWriteZA() const { return Flags & IsWriteZA; }
+bool setsFPMR() const { return Flags & SetsFPMR; }
 bool isReductionQV() const { return Flags & IsReductionQV; }
 uint64_t getBits() const { return Flags; }
 bool isFlagSet(uint64_t Flag) const { return Flags & Flag; }
diff --git a/clang/include/clang/Basic/arm_sme.td 
b/clang/include/clang/Basic/arm_sme.td
index 0f689e82bdb742..8e7e4395411c6c 100644
--- a/clang/include/clang/Basic/arm_sme.td
+++ b/clang/include/clang/Basic/arm_sme.td
@@ -824,4 +824,11 @@ let SMETargetGuard = "sme-lutv2" in {
   def SVLUTI4_ZT_X4 : SInst<"svluti4_zt_{d}_x4", "4i2.u", "cUc", MergeNone, 
"aarch64_sme_luti4_zt_x4", [IsStreaming, IsInZT0], [ImmCheck<0, ImmCheck0_0>]>;
 }
 
+let SMETargetGuard = "sme2,fp8" in {
+  // Convert from half-precision/BFloat16 to deinterleaved FP8 multi-vector
+  def SVF1CVTL: Inst<"svcvtl1_f16[_mf8]_x2_fpm",  "2~n", "h", MergeNone, 
"aarch64_sme_fp8_f1cvtl_x2",  [IsStreaming, IsOverloadNone, SetsFPMR], []>;
+  def SVF1CVTL_BF : Inst<"svcvtl1_bf16[_mf8]_x2_fpm", "2~n", "b", MergeNone, 
"aarch64_sme_fp8_bf1cvtl_x2", [IsStreaming, IsOverloadNone, SetsFPMR], []>;
+  def SVF2CVTL: Inst<"svcvtl2_f16[_mf8]_x2_fpm",  "2~n", "h", MergeNone, 
"aarch64_sme_fp8_f2cvtl_x2",  [IsStreaming, IsOverloadNone, SetsFPMR], []>;
+  def SVF2CVTL_BF : Inst<"svcvtl2_bf16[_mf8]_x2_fpm", "2~n", "b", MergeNone, 
"aarch64_sme_fp8_bf2cvtl_x2", [IsStreaming, IsOverloadNone, SetsFPMR], []>;
+}
 } // let SVETargetGuard = InvalidMode
diff --git a/clang/include/clang/Basic/arm_sve_sme_incl.td 
b/clang/include/clang/Basic/arm_sve_sme_incl.td
index 50911fb63e818e..7fdf732e506a2e 100644
--- a/clang/include/clang/Basic/arm_sve_sme_incl.td
+++ b/clang/include/clang/Basic/arm_sve_sme_incl.td
@@ -103,6 +103,7 @@ include "arm_immcheck_incl.td"
 // M: svfloat32_t
 // N: svfloat64_t
 // $: svbfloat16_t
+// ~: svmfloat8_t
 
 // J: Prefetch type (sv_prfop)
 
@@ -235,6 +236,7 @@ def IsInOutZA   : 
FlagType<0x2000>;
 def IsInZT0 : FlagType<0x4000>;
 def IsOutZT0: FlagType<0x8000>;
 def IsInOutZT0  : FlagType<0x1>;
+def SetsFPMR: FlagType<0x2>;
 
 defvar InvalidMode = "";
 
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 0916e14f182ddd..568ba0ade6422f 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -11182,6 +11182,10 @@ Value 
*CodeGenFunction::EmitAArch64SMEBuiltinExpr(unsigned BuiltinID,
BuiltinID == SME::BI__builtin_sme_svstr_za)
 return EmitSMELdrStr(TypeFlags, Ops, Builtin->LLVMIntrinsic);
 
+  // Emit set FPMR for intrinsics that require it
+  if (TypeFlags.setsFPMR())
+Builder.CreateCall(CGM.getIntrinsic(Intrinsic::aarch64_set_fpmr),
+   Ops.pop_back_val());
   // Handle builtins which require their multi-vector operands to be swapped
   swapCommutativeSMEOperands(BuiltinID, Ops);
 
diff --git a/clang/test/CodeGen/AArch64/fp8-intrinsics/acle_sme2_fp8_cvt.c 
b/clang/test/CodeGen/AArch64/fp8-intrinsics/acle_sme2_fp8_cvt.c
new file mode 100644
index 00..da2a505a897996
--- /dev/null
+++ b/clang/test/CodeGen/AArch64/fp8-intrinsics/acle_sme2_fp8_cvt.c
@@ -0,0 +1,81 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+
+// REQUIRES: aarch64-registered-target
+
+// RUN: %clang_cc1 -trip

[clang] [Clang][AArch64]Refactor typespec handling in SveEmitter.cpp (PR #117717)

2024-11-28 Thread Sander de Smalen via cfe-commits


@@ -423,131 +434,143 @@ const std::array 
SVEEmitter::Reinterprets =
 // Type implementation
 
//===--===//
 
-std::string SVEType::builtin_str() const {
-  std::string S;
-  if (isVoid())
+std::string SVEType::builtinBaseType() const {
+  switch (Kind) {
+  case TypeKind::Void:
 return "v";
-
-  if (isScalarPredicate())
-return "b";
-
-  if (isSvcount())
+  case TypeKind::Svcount:
 return "Qa";
-
-  if (isVoidPointer())
-S += "v";
-  else if (!isFloatingPoint())
+  case TypeKind::BFloat16:
+assert(ElementBitwidth == 16 && "Invalid BFloat16!");
+return "y";
+  case TypeKind::MFloat8:
+assert(ElementBitwidth == 8 && "Invalid MFloat8!");
+return "c";
+  case TypeKind::Float:
 switch (ElementBitwidth) {
-case 1: S += "b"; break;
-case 8: S += "c"; break;
-case 16: S += "s"; break;
-case 32: S += "i"; break;
-case 64: S += "Wi"; break;
-case 128: S += "LLLi"; break;
-default: llvm_unreachable("Unhandled case!");
+case 16:
+  return "h";
+case 32:
+  return "f";
+case 64:
+  return "d";
+default:
+  llvm_unreachable("Unhandled float width!");
 }
-  else if (isFloat())
+  case TypeKind::Predicate:
+if (isScalar())
+  return "b";
+[[fallthrough]];
+  // SInt/UInt, PredicatePattern, PrefetchOp.
+  default:
 switch (ElementBitwidth) {
-case 16: S += "h"; break;
-case 32: S += "f"; break;
-case 64: S += "d"; break;
-default: llvm_unreachable("Unhandled case!");
+case 1:
+  return "b";
+case 8:
+  return "c";
+case 16:
+  return "s";
+case 32:
+  return "i";
+case 64:
+  return "Wi";
+case 128:
+  return "LLLi";
+default:
+  llvm_unreachable("Unhandled bitwidth!");
 }
-  else if (isBFloat()) {
-assert(ElementBitwidth == 16 && "Not a valid BFloat.");
-S += "y";
-  } else if (isMFloat()) {
-assert(ElementBitwidth == 8 && "Not a valid MFloat.");
-S += "m";
   }
+}
 
-  if (!isFloatingPoint()) {
-if ((isChar() || isPointer()) && !isVoidPointer()) {
-  // Make chars and typed pointers explicitly signed.
-  if (Signed)
-S = "S" + S;
-  else if (!Signed)
-S = "U" + S;
-} else if (!isVoidPointer() && !Signed) {
-  S = "U" + S;
-}
-  }
+std::string SVEType::builtin_str() const {
 
-  // Constant indices are "int", but have the "constant expression" modifier.
-  if (isImmediate()) {
-assert(!isFloat() && "fp immediates are not supported");
-S = "I" + S;
-  }
+  std::string Prefix;
 
-  if (isScalar()) {
-if (Constant) S += "C";
-if (Pointer) S += "*";
-return S;
+  if (isScalableVector())
+Prefix = "q" + llvm::utostr(getNumElements() * NumVectors);
+  else if (isFixedLengthVector())
+Prefix = "V" + llvm::utostr(getNumElements() * NumVectors);
+  else if (isImmediate()) {
+assert(!isFloatingPoint() && "fp immediates are not supported");
+Prefix = "I";
   }
 
-  if (isFixedLengthVector())
-return "V" + utostr(getNumElements() * NumVectors) + S;
-  return "q" + utostr(getNumElements() * NumVectors) + S;
+  // Make chars and integer pointers explicitly signed.
+  if ((ElementBitwidth == 8 || isPointer()) && isSignedInteger())

sdesmalen-arm wrote:

This code just makes the decision that chars are by default signed.

The reason that predicates are described having an element type is to 
distinguish between for example `_b` and `_b8`, but that's only for their 
representation in arm_sve.h. For the builtin descriptions in e.g. 
`arm_sve_builtins.inc` they should use `q16b`, which represent a ``, because `q16Sc` represents ``.

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


[clang] [Clang][AArch64]Refactor typespec handling in SveEmitter.cpp (PR #117717)

2024-11-28 Thread Sander de Smalen via cfe-commits


@@ -431,133 +434,130 @@ const std::array 
SVEEmitter::Reinterprets =
 // Type implementation
 
//===--===//
 
-std::string SVEType::builtin_str() const {
-  std::string OutStr;
-
-  if (isScalarPredicate())
-return "b";
-
-  if (isSvcount())
+std::string SVEType::builtinBaseType() const {
+  switch (Kind) {
+  case TypeKind::Void:
+return "v";
+  case TypeKind::Svcount:
 return "Qa";
-
-  if (isVoid()) {
-OutStr += "v";
-if (!isPointer())
-  return OutStr;
-  } else if (isFloat()) {
+  case TypeKind::BFloat16:
+assert(ElementBitwidth == 16 && "Invalid BFloat16!");
+return "y";
+  case TypeKind::MFloat8:
+assert(ElementBitwidth == 8 && "Invalid MFloat8!");
+return "c";
+  case TypeKind::Float:
 switch (ElementBitwidth) {
 case 16:
-  OutStr += "h";
-  break;
+  return "h";
 case 32:
-  OutStr += "f";
-  break;
+  return "f";
 case 64:
-  OutStr += "d";
-  break;
+  return "d";
 default:
-  llvm_unreachable("Unhandled float type!");
+  llvm_unreachable("Unhandled float width!");
 }
-  } else if (isBFloat()) {
-assert(ElementBitwidth == 16 && "Not a valid BFloat.");
-OutStr += "y";
-  } else if (isMFloat()) {
-assert(ElementBitwidth == 8 && "Not a valid MFloat.");
-OutStr += "m";
-  } else {
+  case TypeKind::Predicate:
+if (isScalar())
+  return "b";
+[[fallthrough]];
+  // SInt/UInt, PredicatePattern, PrefetchOp.
+  default:

sdesmalen-arm wrote:

They have the size of an `int`, so that would be the string `"i"`.

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


[clang] [clang] Remove unused lambda capture. (PR #117988)

2024-11-28 Thread Alexandros Lamprineas via cfe-commits

https://github.com/labrinea created 
https://github.com/llvm/llvm-project/pull/117988

Fixes regression in sanitizer buildbots caused by #116257.

>From 27de3fb4c80f909cd58ee4d579665fd6d8fdaf8d Mon Sep 17 00:00:00 2001
From: Alexandros Lamprineas 
Date: Thu, 28 Nov 2024 10:24:42 +
Subject: [PATCH] [clang] Remove unused lambda capture.

Fixes regression in sanitizer buildbots caused by #116257.
---
 clang/lib/Basic/Targets/X86.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/Basic/Targets/X86.cpp b/clang/lib/Basic/Targets/X86.cpp
index 38714d0e7d3c51..8c31bbe0567416 100644
--- a/clang/lib/Basic/Targets/X86.cpp
+++ b/clang/lib/Basic/Targets/X86.cpp
@@ -1365,7 +1365,7 @@ static llvm::X86::ProcessorFeatures getFeature(StringRef 
Name) {
 }
 
 unsigned X86TargetInfo::getFMVPriority(ArrayRef Features) const {
-  auto getPriority = [this](StringRef Feature) -> unsigned {
+  auto getPriority = [](StringRef Feature) -> unsigned {
 // Valid CPUs have a 'key feature' that compares just better than its key
 // feature.
 using namespace llvm::X86;

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


[clang] b869f1b - [clang] Remove unused lambda capture (NFC)

2024-11-28 Thread Jie Fu via cfe-commits

Author: Jie Fu
Date: 2024-11-28T18:25:30+08:00
New Revision: b869f1bd4fc96fd1d2038720bd1ca84788d71370

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

LOG: [clang] Remove unused lambda capture (NFC)

/llvm-project/clang/lib/Basic/Targets/X86.cpp:1368:23:
error: lambda capture 'this' is not used [-Werror,-Wunused-lambda-capture]
  auto getPriority = [this](StringRef Feature) -> unsigned {
  ^~~~
1 error generated.

Added: 


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

Removed: 




diff  --git a/clang/lib/Basic/Targets/X86.cpp b/clang/lib/Basic/Targets/X86.cpp
index 38714d0e7d3c51..8c31bbe0567416 100644
--- a/clang/lib/Basic/Targets/X86.cpp
+++ b/clang/lib/Basic/Targets/X86.cpp
@@ -1365,7 +1365,7 @@ static llvm::X86::ProcessorFeatures getFeature(StringRef 
Name) {
 }
 
 unsigned X86TargetInfo::getFMVPriority(ArrayRef Features) const {
-  auto getPriority = [this](StringRef Feature) -> unsigned {
+  auto getPriority = [](StringRef Feature) -> unsigned {
 // Valid CPUs have a 'key feature' that compares just better than its key
 // feature.
 using namespace llvm::X86;



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


[clang] [clang] Remove unused lambda capture. (PR #117988)

2024-11-28 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Alexandros Lamprineas (labrinea)


Changes

Fixes regression in sanitizer buildbots caused by #116257.

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


1 Files Affected:

- (modified) clang/lib/Basic/Targets/X86.cpp (+1-1) 


``diff
diff --git a/clang/lib/Basic/Targets/X86.cpp b/clang/lib/Basic/Targets/X86.cpp
index 38714d0e7d3c51..8c31bbe0567416 100644
--- a/clang/lib/Basic/Targets/X86.cpp
+++ b/clang/lib/Basic/Targets/X86.cpp
@@ -1365,7 +1365,7 @@ static llvm::X86::ProcessorFeatures getFeature(StringRef 
Name) {
 }
 
 unsigned X86TargetInfo::getFMVPriority(ArrayRef Features) const {
-  auto getPriority = [this](StringRef Feature) -> unsigned {
+  auto getPriority = [](StringRef Feature) -> unsigned {
 // Valid CPUs have a 'key feature' that compares just better than its key
 // feature.
 using namespace llvm::X86;

``




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


[clang] [analyzer] Modernize, improve and promote chroot checker (PR #117791)

2024-11-28 Thread via cfe-commits

https://github.com/vabridgers updated 
https://github.com/llvm/llvm-project/pull/117791

>From ed174c8b52880d4f89415eb3a72da13f355438d7 Mon Sep 17 00:00:00 2001
From: einvbri 
Date: Mon, 25 Nov 2024 10:31:57 +0100
Subject: [PATCH 1/5] [analyzer] Modernize, improve and promote chroot checker

This change modernizes, improves and promotes the chroot checker from
alpha to the Unix family of checkers. This checker covers the POS05
recommendations for use of chroot.

The improvements included modeling of a success or failure from chroot
and not falsely reporting a warning along an error path. This was made
possible through modernizing the checker to be flow sensitive.
---
 clang/docs/ReleaseNotes.rst   |   3 +
 clang/docs/analyzer/checkers.rst  |  30 ++--
 .../clang/StaticAnalyzer/Checkers/Checkers.td |   8 +-
 .../StaticAnalyzer/Checkers/ChrootChecker.cpp | 149 ++
 .../test/Analysis/analyzer-enabled-checkers.c |   1 +
 clang/test/Analysis/chroot.c  |  36 -
 clang/test/Analysis/show-checker-list.c   |   9 --
 ...c-library-functions-arg-enabled-checkers.c |   1 +
 8 files changed, 174 insertions(+), 63 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 6c40e48e2f49b3..292a41e127bfd0 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -985,6 +985,9 @@ Moved checkers
   original checkers were implemented only using AST matching and make more
   sense as a single clang-tidy check.
 
+- The checker ``alpha.unix.Chroot`` was modernized, improved and moved from
+  alpha to a main Unix family checker.
+
 .. _release-notes-sanitizers:
 
 Sanitizers
diff --git a/clang/docs/analyzer/checkers.rst b/clang/docs/analyzer/checkers.rst
index f34b25cd04bd18..5149faa50f72cf 100644
--- a/clang/docs/analyzer/checkers.rst
+++ b/clang/docs/analyzer/checkers.rst
@@ -1750,6 +1750,21 @@ Critical section handling functions modeled by this 
checker:
}
  }
 
+.. _unix-Chroot:
+
+unix.Chroot (C)
+"
+Check improper use of chroot.
+
+.. code-block:: c
+
+ void f();
+
+ void test() {
+   chroot("/usr/local");
+   f(); // warn: no call of chdir("/") immediately after chroot
+ }
+
 .. _unix-Errno:
 
 unix.Errno (C)
@@ -3275,21 +3290,6 @@ SEI CERT checkers which tries to find errors based on 
their `C coding rules ,
   HelpText<"Check for proper usage of vfork">,
   Documentation;
 
-} // end "unix"
-
-let ParentPackage = UnixAlpha in {
-
 def ChrootChecker : Checker<"Chroot">,
   HelpText<"Check improper use of chroot">,
   Documentation;
 
+} // end "unix"
+
+let ParentPackage = UnixAlpha in {
+
 def PthreadLockChecker : Checker<"PthreadLock">,
   HelpText<"Simple lock -> unlock checker">,
   Dependencies<[PthreadLockBase]>,
diff --git a/clang/lib/StaticAnalyzer/Checkers/ChrootChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/ChrootChecker.cpp
index 3a0a01c23de03e..d957ce9ed2ffc7 100644
--- a/clang/lib/StaticAnalyzer/Checkers/ChrootChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/ChrootChecker.cpp
@@ -10,6 +10,8 @@
 //
 
//===--===//
 
+#include "clang/AST/ASTContext.h"
+#include "clang/Basic/TargetInfo.h"
 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
 #include "clang/StaticAnalyzer/Core/Checker.h"
@@ -24,21 +26,30 @@
 using namespace clang;
 using namespace ento;
 
-namespace {
-
 // enum value that represent the jail state
-enum Kind { NO_CHROOT, ROOT_CHANGED, JAIL_ENTERED };
+enum ChrootKind { NO_CHROOT, ROOT_CHANGED, ROOT_CHANGE_FAILED, JAIL_ENTERED };
 
-bool isRootChanged(intptr_t k) { return k == ROOT_CHANGED; }
-//bool isJailEntered(intptr_t k) { return k == JAIL_ENTERED; }
+// Track chroot state changes for success, failure, state change
+// and "jail"
+REGISTER_TRAIT_WITH_PROGRAMSTATE(ChrootState, ChrootKind)
+
+// Track the call expression to chroot for accurate
+// warning messages
+REGISTER_TRAIT_WITH_PROGRAMSTATE(ChrootCall, const Expr *)
+
+namespace {
 
 // This checker checks improper use of chroot.
-// The state transition:
+// The state transitions
+//
+//  -> ROOT_CHANGE_FAILED
+//  |
 // NO_CHROOT ---chroot(path)--> ROOT_CHANGED ---chdir(/) --> JAIL_ENTERED
 //  |   |
 // ROOT_CHANGED<--chdir(..)--  JAIL_ENTERED<--chdir(..)--
 //  |   |
 //  bug<--foo()--  JAIL_ENTERED<--foo()--
+//
 class ChrootChecker : public Checker {
   // This bug refers to possibly break out of a chroot() jail.
   const BugType BT_BreakJail{this, "Break out of jail"};
@@ -49,20 +60,17 @@ class ChrootChecker : public Checker {
 public:
   ChrootChecker() {}
 
-  static void *getTag() {
-static int x;
-return &x;
-  }
-
   bool eval

[clang] [analyzer] Modernize, improve and promote chroot checker (PR #117791)

2024-11-28 Thread via cfe-commits


@@ -104,15 +146,35 @@ void ChrootChecker::evalChdir(const CallEvent &Call, 
CheckerContext &C) const {
 R = R->StripCasts();
 if (const StringRegion* StrRegion= dyn_cast(R)) {
   const StringLiteral* Str = StrRegion->getStringLiteral();
-  if (Str->getString() == "/")
-state = Mgr.addGDM(state, ChrootChecker::getTag(),
-   (void*) JAIL_ENTERED);
+  if (Str->getString() == "/") {
+state = state->set(JAIL_ENTERED);
+  }
 }
   }
 
   C.addTransition(state);
 }
 
+const ExplodedNode *ChrootChecker::getAcquisitionSite(const ExplodedNode *N,
+  CheckerContext &C) {
+  ProgramStateRef State = N->getState();
+  // When bug type is resource leak, exploded node N may not have state info
+  // for leaked file descriptor, but predecessor should have it.
+  if (!State->get())
+N = N->getFirstPred();

vabridgers wrote:

I've created a new approach using a visitor.

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


[clang] [analyzer] Modernize, improve and promote chroot checker (PR #117791)

2024-11-28 Thread via cfe-commits


@@ -104,15 +146,35 @@ void ChrootChecker::evalChdir(const CallEvent &Call, 
CheckerContext &C) const {
 R = R->StripCasts();
 if (const StringRegion* StrRegion= dyn_cast(R)) {
   const StringLiteral* Str = StrRegion->getStringLiteral();
-  if (Str->getString() == "/")
-state = Mgr.addGDM(state, ChrootChecker::getTag(),
-   (void*) JAIL_ENTERED);
+  if (Str->getString() == "/") {
+state = state->set(JAIL_ENTERED);
+  }
 }
   }
 
   C.addTransition(state);
 }
 
+const ExplodedNode *ChrootChecker::getAcquisitionSite(const ExplodedNode *N,
+  CheckerContext &C) {
+  ProgramStateRef State = N->getState();
+  // When bug type is resource leak, exploded node N may not have state info
+  // for leaked file descriptor, but predecessor should have it.
+  if (!State->get())
+N = N->getFirstPred();
+
+  const ExplodedNode *Pred = N;
+  while (N) {
+State = N->getState();
+if (!State->get())
+  return Pred;
+Pred = N;
+N = N->getFirstPred();
+  }

vabridgers wrote:

I had to move this graph walk to the visitor since I needed to find the node 
where chroot was found. I experimented with avoiding this graph walk, but could 
not find a way. I found the approach I'm using in the current Stream Checker 
for the same reasons I'm using it, which is to get the location info for the 
chroot instance and chdir instance for bug reporting. See StreamChecker.cpp, 
method reportLeaks which uses getAcquisitionSite. That approach usage also uses 
a visitor.

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


[clang] [clang] Add a lifetime_capture_by testcase for temporary capturing object. (PR #117733)

2024-11-28 Thread Utkarsh Saxena via cfe-commits

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


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


[clang] [clang-repl] Fix generation of wasm binaries while running clang-repl in browser (PR #117978)

2024-11-28 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 332719561000dcac94384234ace1fa959362ad8e 
987f77db9d45dee264c60f434652131438784f6f --extensions cpp -- 
clang/lib/Interpreter/Interpreter.cpp clang/lib/Interpreter/Wasm.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Interpreter/Wasm.cpp b/clang/lib/Interpreter/Wasm.cpp
index 0fd6ad509c..4c9149663e 100644
--- a/clang/lib/Interpreter/Wasm.cpp
+++ b/clang/lib/Interpreter/Wasm.cpp
@@ -41,12 +41,12 @@ struct DriverDef {
 };
 
 struct Result {
-int retCode;
-bool canRunAgain;
+  int retCode;
+  bool canRunAgain;
 };
 
 Result lldMain(llvm::ArrayRef args, llvm::raw_ostream &stdoutOS,
-llvm::raw_ostream &stderrOS, llvm::ArrayRef 
drivers);
+   llvm::raw_ostream &stderrOS, llvm::ArrayRef drivers);
 
 namespace wasm {
 bool link(llvm::ArrayRef args, llvm::raw_ostream &stdoutOS,
@@ -76,8 +76,10 @@ llvm::Error 
WasmIncrementalExecutor::addModule(PartialTranslationUnit &PTU) {
   llvm::TargetMachine *TargetMachine = Target->createTargetMachine(
   PTU.TheModule->getTargetTriple(), "", "", TO, llvm::Reloc::Model::PIC_);
   PTU.TheModule->setDataLayout(TargetMachine->createDataLayout());
-  std::string ObjectFileName = PTU.TheModule->getName().str() + ".o";  // For 
the wasm object
-  std::string BinaryFileName = PTU.TheModule->getName().str() + ".wasm";  // 
For the wasm binary
+  std::string ObjectFileName =
+  PTU.TheModule->getName().str() + ".o"; // For the wasm object
+  std::string BinaryFileName =
+  PTU.TheModule->getName().str() + ".wasm"; // For the wasm binary
 
   std::error_code Error;
   llvm::raw_fd_ostream ObjectFileOutput(llvm::StringRef(ObjectFileName), 
Error);
@@ -109,7 +111,8 @@ llvm::Error 
WasmIncrementalExecutor::addModule(PartialTranslationUnit &PTU) {
   const lld::DriverDef WasmDriver = {lld::Flavor::Wasm, &lld::wasm::link};
   std::vector WasmDriverArgs;
   WasmDriverArgs.push_back(WasmDriver);
-  lld::Result Result = lld::lldMain(LinkerArgs, llvm::outs(), llvm::errs(), 
WasmDriverArgs);
+  lld::Result Result =
+  lld::lldMain(LinkerArgs, llvm::outs(), llvm::errs(), WasmDriverArgs);
 
   if (Result.retCode != 0)
 return llvm::make_error(

``




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


[clang] 76e6c8d - Codegen changes for strict modifier with grainsize/num_tasks of taskloop construct (#117196)

2024-11-28 Thread via cfe-commits

Author: CHANDRA GHALE
Date: 2024-11-28T14:18:59+05:30
New Revision: 76e6c8d3fc3dc097a3bd96e8959f73a809493976

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

LOG: Codegen changes for strict modifier with grainsize/num_tasks of taskloop 
construct (#117196)

Initial parsing/sema for 'strict' modifier with 'num_tasks' and
‘grainsize’ clause is present in these commits
[grainsize_parsing](https://github.com/llvm/llvm-project/commit/ab9eac762c35068e77f57795e660d06f578c9614)
and
[num_tasks_parsing](https://github.com/llvm/llvm-project/commit/56c166017055595a9f26933e85bfd89e30c528d0#diff-4184486638e85284c3a2c961a81e7752231022daf97e411007c13a6732b50db9R6545)
. However, this implementation appears incomplete as it lacks code
generation support. A runtime patch was introduced in this runtime
commit
[runtime_patch](https://github.com/llvm/llvm-project/commit/540007b42701b5ac9adba076824bfd648a265413#diff-5e95f9319910d6965d09c301359dbe6b23f3eef5ce4d262ef2c2d2137875b5c4R374)
, which adds a new API, _kmpc_taskloop_5, to accommodate the strict
modifier. 
In this patch I have added codegen support. When the strict modifier is
present alongside the grainsize or num_tasks clauses of taskloop
construct, the code now emits a call to _kmpc_taskloop_5, which includes
an additional parameter of type i32 with the value 1 to indicate the
strict modifier. If the strict modifier is not present, it falls back to
the existing _kmpc_taskloop API call.

-

Co-authored-by: Chandra Ghale 

Added: 
clang/test/OpenMP/taskloop_strictmodifier_codegen.cpp

Modified: 
clang/lib/CodeGen/CGOpenMPRuntime.cpp
clang/lib/CodeGen/CGOpenMPRuntime.h
clang/lib/CodeGen/CGStmtOpenMP.cpp
llvm/include/llvm/Frontend/OpenMP/OMPKinds.def

Removed: 




diff  --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index cc389974e04081..6a5860242035b2 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -4666,7 +4666,7 @@ void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction 
&CGF, SourceLocation Loc,
CGF.getContext().VoidPtrTy);
   }
   enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
-  llvm::Value *TaskArgs[] = {
+  llvm::SmallVector TaskArgs{
   UpLoc,
   ThreadID,
   Result.NewTask,
@@ -4683,12 +4683,18 @@ void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction 
&CGF, SourceLocation Loc,
   Data.Schedule.getPointer()
   ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
   /*isSigned=*/false)
-  : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
-  Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
- Result.TaskDupFn, CGF.VoidPtrTy)
-   : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
+  : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0)};
+  if (Data.HasModifier)
+TaskArgs.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 1));
+
+  TaskArgs.push_back(Result.TaskDupFn
+ ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
+   Result.TaskDupFn, CGF.VoidPtrTy)
+ : llvm::ConstantPointerNull::get(CGF.VoidPtrTy));
   CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
-  CGM.getModule(), OMPRTL___kmpc_taskloop),
+  CGM.getModule(), Data.HasModifier
+   ? OMPRTL___kmpc_taskloop_5
+   : OMPRTL___kmpc_taskloop),
   TaskArgs);
 }
 

diff  --git a/clang/lib/CodeGen/CGOpenMPRuntime.h 
b/clang/lib/CodeGen/CGOpenMPRuntime.h
index 5e7715743afb58..56d502d92806eb 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.h
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.h
@@ -122,6 +122,7 @@ struct OMPTaskDataTy final {
   bool IsReductionWithTaskMod = false;
   bool IsWorksharingReduction = false;
   bool HasNowaitClause = false;
+  bool HasModifier = false;
 };
 
 /// Class intended to support codegen of all kind of the reduction clauses.

diff  --git a/clang/lib/CodeGen/CGStmtOpenMP.cpp 
b/clang/lib/CodeGen/CGStmtOpenMP.cpp
index 390516fea38498..6cb37b20b7aeee 100644
--- a/clang/lib/CodeGen/CGStmtOpenMP.cpp
+++ b/clang/lib/CodeGen/CGStmtOpenMP.cpp
@@ -7831,10 +7831,14 @@ void 
CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) {
 // grainsize clause
 Data.Schedule.setInt(/*IntVal=*/false);
 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize()));
+Data.HasModifier =
+(Clause->getModifier() == OMPC_GRAINSIZE_strict) ? true : false;
   } else if (const auto *Clause = S.getSingleClause()) {
 

[clang] [clang-repl] Fix generation of wasm binaries while running clang-repl in browser (PR #117978)

2024-11-28 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Anutosh Bhat (anutosh491)


Changes



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


3 Files Affected:

- (modified) clang/lib/Interpreter/CMakeLists.txt (+2) 
- (modified) clang/lib/Interpreter/Interpreter.cpp (+1) 
- (modified) clang/lib/Interpreter/Wasm.cpp (+42-15) 


``diff
diff --git a/clang/lib/Interpreter/CMakeLists.txt 
b/clang/lib/Interpreter/CMakeLists.txt
index df7ea82e0dada5..bf70cdfbee01e1 100644
--- a/clang/lib/Interpreter/CMakeLists.txt
+++ b/clang/lib/Interpreter/CMakeLists.txt
@@ -16,6 +16,7 @@ set(LLVM_LINK_COMPONENTS
 if (EMSCRIPTEN AND "lld" IN_LIST LLVM_ENABLE_PROJECTS)
   set(WASM_SRC Wasm.cpp)
   set(WASM_LINK lldWasm)
+  set(COMMON_LINK lldCommon)
 endif()
 
 add_clang_library(clangInterpreter
@@ -47,6 +48,7 @@ add_clang_library(clangInterpreter
   clangSema
   clangSerialization
   ${WASM_LINK}
+  ${COMMON_LINK}
   )
 
 if ((MINGW OR CYGWIN) AND BUILD_SHARED_LIBS)
diff --git a/clang/lib/Interpreter/Interpreter.cpp 
b/clang/lib/Interpreter/Interpreter.cpp
index 5dc67f6375098f..887b494ff98f19 100644
--- a/clang/lib/Interpreter/Interpreter.cpp
+++ b/clang/lib/Interpreter/Interpreter.cpp
@@ -201,6 +201,7 @@ IncrementalCompilerBuilder::CreateCpp() {
   Argv.push_back("-target");
   Argv.push_back("wasm32-unknown-emscripten");
   Argv.push_back("-shared");
+  Argv.push_back("-fvisibility=default");
 #endif
   Argv.insert(Argv.end(), UserArgs.begin(), UserArgs.end());
 
diff --git a/clang/lib/Interpreter/Wasm.cpp b/clang/lib/Interpreter/Wasm.cpp
index 79efbaa03982d0..0fd6ad509c2938 100644
--- a/clang/lib/Interpreter/Wasm.cpp
+++ b/clang/lib/Interpreter/Wasm.cpp
@@ -23,6 +23,31 @@
 #include 
 
 namespace lld {
+enum Flavor {
+  Invalid,
+  Gnu, // -flavor gnu
+  MinGW,   // -flavor gnu MinGW
+  WinLink, // -flavor link
+  Darwin,  // -flavor darwin
+  Wasm,// -flavor wasm
+};
+
+using Driver = bool (*)(llvm::ArrayRef, llvm::raw_ostream &,
+llvm::raw_ostream &, bool, bool);
+
+struct DriverDef {
+  Flavor f;
+  Driver d;
+};
+
+struct Result {
+int retCode;
+bool canRunAgain;
+};
+
+Result lldMain(llvm::ArrayRef args, llvm::raw_ostream &stdoutOS,
+llvm::raw_ostream &stderrOS, llvm::ArrayRef 
drivers);
+
 namespace wasm {
 bool link(llvm::ArrayRef args, llvm::raw_ostream &stdoutOS,
   llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput);
@@ -51,45 +76,47 @@ llvm::Error 
WasmIncrementalExecutor::addModule(PartialTranslationUnit &PTU) {
   llvm::TargetMachine *TargetMachine = Target->createTargetMachine(
   PTU.TheModule->getTargetTriple(), "", "", TO, llvm::Reloc::Model::PIC_);
   PTU.TheModule->setDataLayout(TargetMachine->createDataLayout());
-  std::string OutputFileName = PTU.TheModule->getName().str() + ".wasm";
+  std::string ObjectFileName = PTU.TheModule->getName().str() + ".o";  // For 
the wasm object
+  std::string BinaryFileName = PTU.TheModule->getName().str() + ".wasm";  // 
For the wasm binary
 
   std::error_code Error;
-  llvm::raw_fd_ostream OutputFile(llvm::StringRef(OutputFileName), Error);
+  llvm::raw_fd_ostream ObjectFileOutput(llvm::StringRef(ObjectFileName), 
Error);
 
   llvm::legacy::PassManager PM;
-  if (TargetMachine->addPassesToEmitFile(PM, OutputFile, nullptr,
+  if (TargetMachine->addPassesToEmitFile(PM, ObjectFileOutput, nullptr,
  llvm::CodeGenFileType::ObjectFile)) {
 return llvm::make_error(
 "Wasm backend cannot produce object.", llvm::inconvertibleErrorCode());
   }
 
   if (!PM.run(*PTU.TheModule)) {
-
 return llvm::make_error("Failed to emit Wasm object.",
llvm::inconvertibleErrorCode());
   }
 
-  OutputFile.close();
+  ObjectFileOutput.close();
 
   std::vector LinkerArgs = {"wasm-ld",
   "-shared",
   "--import-memory",
-  "--no-entry",
-  "--export-all",
   "--experimental-pic",
   "--stack-first",
   "--allow-undefined",
-  OutputFileName.c_str(),
+  ObjectFileName.c_str(),
   "-o",
-  OutputFileName.c_str()};
-  int Result =
-  lld::wasm::link(LinkerArgs, llvm::outs(), llvm::errs(), false, false);
-  if (!Result)
+  BinaryFileName.c_str()};
+
+  const lld::DriverDef WasmDriver = {lld::Flavor::Wasm, &lld::wasm::link};
+  std::vector WasmDriverArgs;
+  WasmDriverArgs.push_back(WasmDriver);
+  lld::Result Result = lld::lldMain(LinkerArgs, llvm::outs(), llvm::errs(), 
WasmDriverArgs);
+
+  if (Result.retCod

[clang] [llvm] Codegen changes for strict modifier with grainsize/num_tasks of taskloop construct (PR #117196)

2024-11-28 Thread CHANDRA GHALE via cfe-commits

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


[clang] [clang-repl] Fix generation of wasm binaries while running clang-repl in browser (PR #117978)

2024-11-28 Thread Anutosh Bhat via cfe-commits

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


  1   2   3   4   >