[clang] [llvm] [RISCV][VCIX] Add vcix_state to GNU inline assembly register set (PR #106914)

2024-09-11 Thread Michal Terepeta via cfe-commits


@@ -44,7 +44,7 @@ ArrayRef RISCVTargetInfo::getGCCRegNames() 
const {
   "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31",
 
   // CSRs
-  "fflags", "frm", "vtype", "vl", "vxsat", "vxrm"
+  "fflags", "frm", "vtype", "vl", "vxsat", "vxrm", "sf_vcix_state"

michalt wrote:

Should we stay with the `sf_` prefix then? Or is there some simple workaround? 

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


[clang] [llvm] [RISCV][VCIX] Add vcix_state to GNU inline assembly register set (PR #106914)

2024-09-11 Thread Jessica Clarke via cfe-commits


@@ -44,7 +44,7 @@ ArrayRef RISCVTargetInfo::getGCCRegNames() 
const {
   "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31",
 
   // CSRs
-  "fflags", "frm", "vtype", "vl", "vxsat", "vxrm"
+  "fflags", "frm", "vtype", "vl", "vxsat", "vxrm", "sf_vcix_state"

jrtc27 wrote:

What do you mean by "This is a machine instruction name [...] it can't 
recognize"? That's the name it's given in TableGen.

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


[clang-tools-extra] [clang-tidy] Create bugprone-bit-cast-pointers check (PR #108083)

2024-09-11 Thread Carlos Galvez via cfe-commits

carlosgalvezp wrote:

Perhaps we can start with only pointer-to-pointer, yes. The original intention 
was to forbid that:

https://www.open-std.org/jtc1/sc22/WG21/docs/papers/2016/p0476r0.html#det

```cpp


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


[clang-tools-extra] [clang-tidy] Create bugprone-bit-cast-pointers check (PR #108083)

2024-09-11 Thread Carlos Galvez via cfe-commits

carlosgalvezp wrote:

Perhaps we can start with pointer-to-pointer only, yes. Pointer-int conversions 
are still implementation-defined, but I guess it's less of a problem than UB.

The original paper only checked that both inputs are not pointers:

```cpp
  !(is_pointer_v &&
is_pointer_v) &&
```

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


[clang] [llvm] [RISCV][VCIX] Add vcix_state to GNU inline assembly register set (PR #106914)

2024-09-11 Thread Brandon Wu via cfe-commits


@@ -44,7 +44,7 @@ ArrayRef RISCVTargetInfo::getGCCRegNames() 
const {
   "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31",
 
   // CSRs
-  "fflags", "frm", "vtype", "vl", "vxsat", "vxrm"
+  "fflags", "frm", "vtype", "vl", "vxsat", "vxrm", "sf_vcix_state"

4vtomat wrote:

```
#include 
#include 


int foo(__rvv_uint64m1_t vreg) {

  auto vl = __riscv_vsetvl_e64m1(1);

  // This VCIX instruction gets scheduled after the asm block below.
  __riscv_sf_vc_iv_se_u64m1(0, 0, vreg, 0, vl);

  asm volatile(
  R"(
vsetivli zero, 2, e64, m1, ta, ma
sf.vc.vv 0x3, 0x0, %[vreg], %[vreg];
  )"
  : "=r"(vl)
  : [vreg]"vr"(vreg)
  : "memory", "vl", "sf_vcix_state");

  return 0;
}
```
Use the code above as an example, it compiles to the llvm:
```
  define dso_local noundef signext i32 @_Z3foou16__rvv_uint64m1_t( %vreg) local_unnamed_addr #0 {
  entry:
%0 = tail call i64 @llvm.riscv.vsetvli.i64(i64 1, i64 3, i64 0)
tail call void @llvm.riscv.sf.vc.iv.se.i64.nxv1i64.i64.i64(i64 0, i64 0, 
 %vreg, i64 0, i64 %0)
%1 = tail call i64 asm sideeffect "\0Avsetivli zero, 2, e64, m1, 
ta, ma\0Asf.vc.vv 0x3, 0x0, $1, $1;\0A  ", 
"=r,^vr,~{memory},~{vl},~{sf_vcix_state}"( %vreg)
ret i32 0
  }
```

if we change `sf_vcix_state` to `sf.vcix_state`, the code doesn't work as 
expected, the instruction is still reordered, so I doubt that the name here is 
the defining name of the register in `RISCVRegisterInfo.td` rather than the 
actually name of the register.


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


[clang-tools-extra] [clang-tidy] Create bugprone-bit-cast-pointers check (PR #108083)

2024-09-11 Thread Carlos Galvez via cfe-commits

https://github.com/carlosgalvezp updated 
https://github.com/llvm/llvm-project/pull/108083

>From c4d85703ee004522746df940f7b08cabaa0f4eca Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Carlos=20G=C3=A1lvez?= 
Date: Tue, 10 Sep 2024 13:46:51 +
Subject: [PATCH] [clang-tidy] Create bugprone-bit-cast-pointers check

To detect unsafe use of bit_cast. Otherwise, bit_cast bypasses all
checks done by compilers and linters.

Fixes #106987
---
 .../bugprone/BitCastPointersCheck.cpp | 32 +++
 .../bugprone/BitCastPointersCheck.h   | 34 
 .../bugprone/BugproneTidyModule.cpp   |  3 ++
 .../clang-tidy/bugprone/CMakeLists.txt|  1 +
 clang-tools-extra/docs/ReleaseNotes.rst   |  6 +++
 .../checks/bugprone/bit-cast-pointers.rst | 40 +++
 .../checkers/bugprone/bit-cast-pointers.cpp   | 34 
 7 files changed, 150 insertions(+)
 create mode 100644 
clang-tools-extra/clang-tidy/bugprone/BitCastPointersCheck.cpp
 create mode 100644 clang-tools-extra/clang-tidy/bugprone/BitCastPointersCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/bugprone/bit-cast-pointers.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/bit-cast-pointers.cpp

diff --git a/clang-tools-extra/clang-tidy/bugprone/BitCastPointersCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/BitCastPointersCheck.cpp
new file mode 100644
index 00..30c026fba150a5
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/bugprone/BitCastPointersCheck.cpp
@@ -0,0 +1,32 @@
+//===--- BitCastPointersCheck.cpp - clang-tidy 
===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "BitCastPointersCheck.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+void BitCastPointersCheck::registerMatchers(MatchFinder *Finder) {
+  auto IsPointerType = refersToType(qualType(isAnyPointer()));
+  Finder->addMatcher(callExpr(callee(functionDecl(allOf(
+  hasName("::std::bit_cast"),
+  hasTemplateArgument(0, IsPointerType),
+  hasTemplateArgument(1, IsPointerType)
+ .bind("x"),
+ this);
+}
+
+void BitCastPointersCheck::check(const MatchFinder::MatchResult &Result) {
+  if (const auto *MatchedDecl = Result.Nodes.getNodeAs("x"))
+diag(MatchedDecl->getBeginLoc(),
+ "do not use std::bit_cast on pointers; use it on values instead");
+}
+
+} // namespace clang::tidy::bugprone
diff --git a/clang-tools-extra/clang-tidy/bugprone/BitCastPointersCheck.h 
b/clang-tools-extra/clang-tidy/bugprone/BitCastPointersCheck.h
new file mode 100644
index 00..d7c23c187dae34
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/bugprone/BitCastPointersCheck.h
@@ -0,0 +1,34 @@
+//===--- BitCastPointersCheck.h - clang-tidy *- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_BITCASTPOINTERSCHECK_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_BITCASTPOINTERSCHECK_H
+
+#include "../ClangTidyCheck.h"
+
+namespace clang::tidy::bugprone {
+
+/// Warns about usage of ``std::bit_cast`` when the input and output types are
+/// pointers.
+///
+/// For the user-facing documentation see:
+/// 
http://clang.llvm.org/extra/clang-tidy/checks/bugprone/bit-cast-pointers.html
+class BitCastPointersCheck : public ClangTidyCheck {
+public:
+  BitCastPointersCheck(StringRef Name, ClangTidyContext *Context)
+  : ClangTidyCheck(Name, Context) {}
+  void registerMatchers(ast_matchers::MatchFinder *Finder) override;
+  void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
+  bool isLanguageVersionSupported(const LangOptions &LangOpts) const override {
+return LangOpts.CPlusPlus20;
+  }
+};
+
+} // namespace clang::tidy::bugprone
+
+#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_BITCASTPOINTERSCHECK_H
diff --git a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp 
b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
index 689eb92a3d8d17..931624224d784b 100644
--- a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
@@ -14,6 +14,7 @@
 #include "AssertSideEffectCheck.h"
 #include "AssignmentInIfConditionCheck.h"
 #include "Bad

[clang] [llvm] [RISCV][VCIX] Add vcix_state to GNU inline assembly register set (PR #106914)

2024-09-11 Thread Brandon Wu via cfe-commits


@@ -44,7 +44,7 @@ ArrayRef RISCVTargetInfo::getGCCRegNames() 
const {
   "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31",
 
   // CSRs
-  "fflags", "frm", "vtype", "vl", "vxsat", "vxrm"
+  "fflags", "frm", "vtype", "vl", "vxsat", "vxrm", "sf_vcix_state"

4vtomat wrote:

I think here is the root cause: 
https://github.com/llvm/llvm-project/blob/1e3a24d2e4eb63c17b962161ae6588d1b2c178f8/llvm/include/llvm/CodeGen/TargetRegisterInfo.h#L1106
Maybe we should overwrite this function for RISCV?
What do you think @jrtc27 @kito-cheng ?

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


[clang] [llvm] [RISCV][VCIX] Add vcix_state to GNU inline assembly register set (PR #106914)

2024-09-11 Thread Brandon Wu via cfe-commits

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


[clang] [llvm] [RISCV][VCIX] Add vcix_state to GNU inline assembly register set (PR #106914)

2024-09-11 Thread Brandon Wu via cfe-commits

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


[clang] 34cab2e - [Driver][test] Remove useless LoongArch test checks in mcmodel.c

2024-09-11 Thread Weining Lu via cfe-commits

Author: Weining Lu
Date: 2024-09-11T16:10:38+08:00
New Revision: 34cab2ed82a63ecf3d0ebf790def6d21bd4b87af

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

LOG: [Driver][test] Remove useless LoongArch test checks in mcmodel.c

Added: 


Modified: 
clang/test/Driver/mcmodel.c

Removed: 




diff  --git a/clang/test/Driver/mcmodel.c b/clang/test/Driver/mcmodel.c
index 9681c32579d71e..c6c8b5433d23be 100644
--- a/clang/test/Driver/mcmodel.c
+++ b/clang/test/Driver/mcmodel.c
@@ -43,5 +43,4 @@
 // AARCH64-PIC-LARGE: error: invalid argument '-mcmodel=large' only allowed 
with '-fno-pic'
 // ERR-AARCH64_32: error: unsupported argument 'small' to option '-mcmodel=' 
for target 'aarch64_32-unknown-linux'
 
-// ERR-LOONGARCH64-PLT-LARGE: error: invalid argument '-mcmodel=large' not 
allowed with '-fplt'
 // ERR-LOONGARCH64-PLT-EXTREME: error: invalid argument '-mcmodel=extreme' not 
allowed with '-fplt'



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


[clang] [clang-tools-extra] [clangd] Collect comments from function definitions into the index (PR #67802)

2024-09-11 Thread Christian Kandeler via cfe-commits

ckandeler wrote:

> I wrote a libAST unit test to demonstrate the bug, and filed #108145 about 
> it. Hopefully folks more familiar with that code can suggest an appropriate 
> fix there.

Awesome, thanks.

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


[clang] [clang-tools-extra] [clangd] Collect comments from function definitions into the index (PR #67802)

2024-09-11 Thread Christian Kandeler via cfe-commits


@@ -1477,6 +1477,26 @@ TEST_F(SymbolCollectorTest, Documentation) {
 forCodeCompletion(false;
 }
 
+TEST_F(SymbolCollectorTest, DocumentationInMain) {

ckandeler wrote:

Hm, do we really want to specify a behavior there? My thinking was that the 
comment should be at either the declaration or the definition and otherwise one 
of them gets chosen at random, depending on the parse order. I suppose one 
could also cook up some elaborated merging scheme, but that seems like overkill.

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


[clang-tools-extra] [clang-tidy] Add user-defined functions to `bugprone-unsafe-functions` check (PR #106350)

2024-09-11 Thread via cfe-commits

https://github.com/Discookie updated 
https://github.com/llvm/llvm-project/pull/106350

>From c4e05bdb36e270cbf0557f38fad7c04edf011905 Mon Sep 17 00:00:00 2001
From: Viktor 
Date: Wed, 28 Aug 2024 08:47:20 +
Subject: [PATCH 1/8] [clang-tidy] Add user-defined functions to
 bugprone-unsafe-functions check

---
 .../bugprone/UnsafeFunctionsCheck.cpp | 225 +++---
 .../bugprone/UnsafeFunctionsCheck.h   |  12 +
 .../checks/bugprone/unsafe-functions.rst  |  49 
 .../bugprone/unsafe-functions-custom.c|  38 +++
 .../checkers/bugprone/unsafe-functions.c  |   6 +
 5 files changed, 295 insertions(+), 35 deletions(-)
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/unsafe-functions-custom.c

diff --git a/clang-tools-extra/clang-tidy/bugprone/UnsafeFunctionsCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/UnsafeFunctionsCheck.cpp
index ea7eaa0b0ff811..05c2063402b080 100644
--- a/clang-tools-extra/clang-tidy/bugprone/UnsafeFunctionsCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/UnsafeFunctionsCheck.cpp
@@ -7,6 +7,8 @@
 
//===--===//
 
 #include "UnsafeFunctionsCheck.h"
+#include "../utils/Matchers.h"
+#include "../utils/OptionsUtils.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/Lex/PPCallbacks.h"
@@ -18,6 +20,12 @@ using namespace llvm;
 
 namespace clang::tidy::bugprone {
 
+static constexpr llvm::StringLiteral OptionNameCustomNormalFunctions =
+"CustomNormalFunctions";
+static constexpr llvm::StringLiteral OptionNameCustomAnnexKFunctions =
+"CustomAnnexKFunctions";
+static constexpr llvm::StringLiteral OptionNameReportDefaultFunctions =
+"ReportDefaultFunctions";
 static constexpr llvm::StringLiteral OptionNameReportMoreUnsafeFunctions =
 "ReportMoreUnsafeFunctions";
 
@@ -26,6 +34,10 @@ static constexpr llvm::StringLiteral 
FunctionNamesWithAnnexKReplacementId =
 static constexpr llvm::StringLiteral FunctionNamesId = "FunctionsNames";
 static constexpr llvm::StringLiteral AdditionalFunctionNamesId =
 "AdditionalFunctionsNames";
+static constexpr llvm::StringLiteral CustomFunctionNamesId =
+"CustomFunctionNames";
+static constexpr llvm::StringLiteral CustomAnnexKFunctionNamesId =
+"CustomAnnexKFunctionNames";
 static constexpr llvm::StringLiteral DeclRefId = "DRE";
 
 static std::optional
@@ -127,57 +139,155 @@ static bool isAnnexKAvailable(std::optional 
&CacheVar, Preprocessor *PP,
   return CacheVar.value();
 }
 
+static std::vector
+ParseCheckedFunctions(StringRef Option, StringRef OptionName,
+  ClangTidyContext *Context) {
+  std::vector Functions = utils::options::parseStringList(Option);
+  std::vector Result;
+  Result.reserve(Functions.size());
+
+  for (StringRef Function : Functions) {
+if (Function.empty()) {
+  continue;
+}
+
+auto [Name, Rest] = Function.split(',');
+auto [Replacement, Reason] = Rest.split(',');
+
+if (Name.trim().empty()) {
+  Context->configurationDiag("invalid configuration value for option '%0'; 
"
+ "expected the name of an unsafe function")
+  << OptionName;
+}
+
+if (Replacement.trim().empty()) {
+  Context->configurationDiag(
+  "invalid configuration value '%0' for option '%1'; "
+  "expected a replacement function name")
+  << Name.trim() << OptionName;
+}
+
+Result.push_back({Name.trim().str(), llvm::Regex(Name.trim()),
+  Replacement.trim().str(), Reason.trim().str()});
+  }
+
+  return Result;
+}
+
+static std::string SerializeCheckedFunctions(
+const std::vector &Functions) {
+  std::vector Result;
+  Result.reserve(Functions.size());
+
+  for (const auto &Entry : Functions) {
+if (Entry.Reason.empty())
+  Result.push_back(Entry.Name + "," + Entry.Replacement);
+else
+  Result.push_back(Entry.Name + "," + Entry.Replacement + "," +
+   Entry.Reason);
+  }
+
+  return llvm::join(Result, ";");
+}
+
 UnsafeFunctionsCheck::UnsafeFunctionsCheck(StringRef Name,
ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
+  CustomNormalFunctions(ParseCheckedFunctions(
+  Options.get(OptionNameCustomNormalFunctions, ""),
+  OptionNameCustomNormalFunctions, Context)),
+  CustomAnnexKFunctions(ParseCheckedFunctions(
+  Options.get(OptionNameCustomAnnexKFunctions, ""),
+  OptionNameCustomAnnexKFunctions, Context)),
+  ReportDefaultFunctions(
+  Options.get(OptionNameReportDefaultFunctions, true)),
   ReportMoreUnsafeFunctions(
   Options.get(OptionNameReportMoreUnsafeFunctions, true)) {}
 
 void UnsafeFunctionsCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, OptionNameCustomNormalFunctions,
+SerializeChecke

[clang] [WebKit Static Analyzer] Treat WTFReportBacktrace as a trivial function. (PR #108167)

2024-09-11 Thread Ryosuke Niwa via cfe-commits

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

Treat WTFReportBacktrace, which prints out the backtrace, as trivial.

>From ad40cdfa22ccbbea7f8b67bf0f3ac1cc0ce1a46c Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa 
Date: Wed, 11 Sep 2024 01:24:27 -0700
Subject: [PATCH] [WebKit Static Analyzer] Treat WTFReportBacktrace as a
 trivial function.

Treat WTFReportBacktrace, which prints out the backtrace, as trivial.
---
 clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp | 1 +
 clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.cpp  | 3 +++
 2 files changed, 4 insertions(+)

diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
index 49bbff1942167b..2b9b7883c978ba 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
@@ -397,6 +397,7 @@ class TrivialFunctionAnalysisVisitor
   return true;
 
 if (Name == "WTFCrashWithInfo" || Name == "WTFBreakpointTrap" ||
+Name == "WTFReportBacktrace" ||
 Name == "WTFCrashWithSecurityImplication" || Name == "WTFCrash" ||
 Name == "WTFReportAssertionFailure" || Name == "isMainThread" ||
 Name == "isMainThreadOrGCThread" || Name == "isMainRunLoop" ||
diff --git a/clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.cpp 
b/clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.cpp
index a98c6eb9c84d97..424ebd349e955a 100644
--- a/clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.cpp
+++ b/clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.cpp
@@ -6,6 +6,7 @@
 void WTFBreakpointTrap();
 void WTFCrashWithInfo(int, const char*, const char*, int);
 void WTFReportAssertionFailure(const char* file, int line, const char* 
function, const char* assertion);
+void WTFReportBacktrace(void);
 
 void WTFCrash(void);
 void WTFCrashWithSecurityImplication(void);
@@ -334,6 +335,7 @@ class RefCounted {
   }
   unsigned trivial60() { return ObjectWithNonTrivialDestructor { 5 }.value(); }
   unsigned trivial61() { return DerivedNumber('7').value(); }
+  void trivial62() { WTFReportBacktrace(); }
 
   static RefCounted& singleton() {
 static RefCounted s_RefCounted;
@@ -506,6 +508,7 @@ class UnrelatedClass {
 getFieldTrivial().trivial59(); // no-warning
 getFieldTrivial().trivial60(); // no-warning
 getFieldTrivial().trivial61(); // no-warning
+getFieldTrivial().trivial62(); // no-warning
 
 RefCounted::singleton().trivial18(); // no-warning
 RefCounted::singleton().someFunction(); // no-warning

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


[clang] [WebKit Static Analyzer] Treat WTFReportBacktrace as a trivial function. (PR #108167)

2024-09-11 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Ryosuke Niwa (rniwa)


Changes

Treat WTFReportBacktrace, which prints out the backtrace, as trivial.

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


2 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp 
(+1) 
- (modified) clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.cpp (+3) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
index 49bbff1942167b..2b9b7883c978ba 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
@@ -397,6 +397,7 @@ class TrivialFunctionAnalysisVisitor
   return true;
 
 if (Name == "WTFCrashWithInfo" || Name == "WTFBreakpointTrap" ||
+Name == "WTFReportBacktrace" ||
 Name == "WTFCrashWithSecurityImplication" || Name == "WTFCrash" ||
 Name == "WTFReportAssertionFailure" || Name == "isMainThread" ||
 Name == "isMainThreadOrGCThread" || Name == "isMainRunLoop" ||
diff --git a/clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.cpp 
b/clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.cpp
index a98c6eb9c84d97..424ebd349e955a 100644
--- a/clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.cpp
+++ b/clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.cpp
@@ -6,6 +6,7 @@
 void WTFBreakpointTrap();
 void WTFCrashWithInfo(int, const char*, const char*, int);
 void WTFReportAssertionFailure(const char* file, int line, const char* 
function, const char* assertion);
+void WTFReportBacktrace(void);
 
 void WTFCrash(void);
 void WTFCrashWithSecurityImplication(void);
@@ -334,6 +335,7 @@ class RefCounted {
   }
   unsigned trivial60() { return ObjectWithNonTrivialDestructor { 5 }.value(); }
   unsigned trivial61() { return DerivedNumber('7').value(); }
+  void trivial62() { WTFReportBacktrace(); }
 
   static RefCounted& singleton() {
 static RefCounted s_RefCounted;
@@ -506,6 +508,7 @@ class UnrelatedClass {
 getFieldTrivial().trivial59(); // no-warning
 getFieldTrivial().trivial60(); // no-warning
 getFieldTrivial().trivial61(); // no-warning
+getFieldTrivial().trivial62(); // no-warning
 
 RefCounted::singleton().trivial18(); // no-warning
 RefCounted::singleton().someFunction(); // no-warning

``




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


[clang] [llvm] [SPIR-V] Add SPIR-V structurizer (PR #107408)

2024-09-11 Thread Vyacheslav Levytskyy via cfe-commits
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= 
Message-ID:
In-Reply-To: 



@@ -744,79 +744,139 @@ static void insertSpirvDecorations(MachineFunction &MF, 
MachineIRBuilder MIB) {
 MI->eraseFromParent();
 }
 
-// Find basic blocks of the switch and replace registers in spv_switch() by its
-// MBB equivalent.
-static void processSwitches(MachineFunction &MF, SPIRVGlobalRegistry *GR,
-MachineIRBuilder MIB) {
-  DenseMap BB2MBB;
-  SmallVector>>
-  Switches;
+// LLVM allows the switches to use registers as cases, while SPIR-V required
+// those to be immediate values. This function replaces such operands with the
+// equivalent immediate constant.
+static void processSwitchesConstants(MachineFunction &MF,
+ SPIRVGlobalRegistry *GR,
+ MachineIRBuilder MIB) {
+  MachineRegisterInfo &MRI = MF.getRegInfo();
   for (MachineBasicBlock &MBB : MF) {
-MachineRegisterInfo &MRI = MF.getRegInfo();
-BB2MBB[MBB.getBasicBlock()] = &MBB;
 for (MachineInstr &MI : MBB) {
   if (!isSpvIntrinsic(MI, Intrinsic::spv_switch))
 continue;
-  // Calls to spv_switch intrinsics representing IR switches.
-  SmallVector NewOps;
-  for (unsigned i = 2; i < MI.getNumOperands(); ++i) {
+
+  SmallVector NewOperands;
+  NewOperands.push_back(MI.getOperand(0)); // Opcode
+  NewOperands.push_back(MI.getOperand(1)); // Condition
+  NewOperands.push_back(MI.getOperand(2)); // Default
+  for (unsigned i = 3; i < MI.getNumOperands(); i += 2) {
 Register Reg = MI.getOperand(i).getReg();
-if (i % 2 == 1) {
-  MachineInstr *ConstInstr = getDefInstrMaybeConstant(Reg, &MRI);
-  NewOps.push_back(ConstInstr);
-} else {
-  MachineInstr *BuildMBB = MRI.getVRegDef(Reg);
-  assert(BuildMBB &&
- BuildMBB->getOpcode() == TargetOpcode::G_BLOCK_ADDR &&
- BuildMBB->getOperand(1).isBlockAddress() &&
- BuildMBB->getOperand(1).getBlockAddress());
-  NewOps.push_back(BuildMBB);
-}
+MachineInstr *ConstInstr = getDefInstrMaybeConstant(Reg, &MRI);
+NewOperands.push_back(
+MachineOperand::CreateCImm(ConstInstr->getOperand(1).getCImm()));
+
+NewOperands.push_back(MI.getOperand(i + 1));
   }
-  Switches.push_back(std::make_pair(&MI, NewOps));
+
+  assert(MI.getNumOperands() == NewOperands.size());
+  while (MI.getNumOperands() > 0)
+MI.removeOperand(0);
+  for (auto &MO : NewOperands)
+MI.addOperand(MO);
 }
   }
+}
 
+// Some instructions are used during CodeGen but should never be emitted.
+// Cleaning up those.
+static void cleanupHelperInstructions(MachineFunction &MF) {
   SmallPtrSet ToEraseMI;
+  for (MachineBasicBlock &MBB : MF) {
+for (MachineInstr &MI : MBB) {
+  if (isSpvIntrinsic(MI, Intrinsic::spv_track_constant) ||
+  MI.getOpcode() == TargetOpcode::G_BRINDIRECT)
+ToEraseMI.insert(&MI);
+}
+  }
+
+  for (MachineInstr *MI : ToEraseMI)
+MI->eraseFromParent();
+}
+
+// Find all usages of G_BLOCK_ADDR in our intrinsics and replace those
+// operands/registers by the actual MBB it references.
+static void processBlockAddr(MachineFunction &MF, SPIRVGlobalRegistry *GR,
+ MachineIRBuilder MIB) {
+  // Gather the reverse-mapping BB -> MBB.
+  DenseMap BB2MBB;
+  for (MachineBasicBlock &MBB : MF)
+BB2MBB[MBB.getBasicBlock()] = &MBB;
+
+  // Gather instructions requiring patching. For now, only those can use
+  // G_BLOCK_ADDR.
+  SmallVector InstructionsToPatch;
+  for (MachineBasicBlock &MBB : MF) {
+for (MachineInstr &MI : MBB) {
+  if (isSpvIntrinsic(MI, Intrinsic::spv_switch) ||
+  isSpvIntrinsic(MI, Intrinsic::spv_loop_merge) ||
+  isSpvIntrinsic(MI, Intrinsic::spv_selection_merge))
+InstructionsToPatch.push_back(&MI);
+}
+  }
+
+  // For each instruction to fix, we replace all the G_BLOCK_ADDR operands by
+  // the actual MBB it references. Once those references updated, we can 
cleanup
+  // remaining G_BLOCK_ADDR references.
   SmallPtrSet ClearAddressTaken;
-  for (auto &SwIt : Switches) {
-MachineInstr &MI = *SwIt.first;
-MachineBasicBlock *MBB = MI.getParent();
-SmallVector &Ins = SwIt.second;
+  SmallPtrSet ToEraseMI;
+  MachineRegisterInfo &MRI = MF.getRegInfo();
+  for (MachineInstr *MI : InstructionsToPatch) {
 SmallVector NewOps;
-for (unsigned i = 0; i < Ins.size(); ++i) {
-  if (Ins[i]->getOpcode() == TargetOpcode::G_BLOCK_ADDR) {
-BasicBlock *CaseBB =
-Ins[i]->getOperand(1).getBlockAddress()->getBasicBlock();
-auto It

[clang] [llvm] [SPIR-V] Add SPIR-V structurizer (PR #107408)

2024-09-11 Thread Vyacheslav Levytskyy via cfe-commits
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= 
Message-ID:
In-Reply-To: 


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


[clang] Set dllimport on Objective C ivar offsets (PR #107604)

2024-09-11 Thread David Chisnall via cfe-commits

davidchisnall wrote:

LGTM, do you need someone else to commit it for you?

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


[clang-tools-extra] [clang-tidy] Add user-defined functions to `bugprone-unsafe-functions` check (PR #106350)

2024-09-11 Thread via cfe-commits

https://github.com/Discookie updated 
https://github.com/llvm/llvm-project/pull/106350

>From c4e05bdb36e270cbf0557f38fad7c04edf011905 Mon Sep 17 00:00:00 2001
From: Viktor 
Date: Wed, 28 Aug 2024 08:47:20 +
Subject: [PATCH 1/9] [clang-tidy] Add user-defined functions to
 bugprone-unsafe-functions check

---
 .../bugprone/UnsafeFunctionsCheck.cpp | 225 +++---
 .../bugprone/UnsafeFunctionsCheck.h   |  12 +
 .../checks/bugprone/unsafe-functions.rst  |  49 
 .../bugprone/unsafe-functions-custom.c|  38 +++
 .../checkers/bugprone/unsafe-functions.c  |   6 +
 5 files changed, 295 insertions(+), 35 deletions(-)
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/unsafe-functions-custom.c

diff --git a/clang-tools-extra/clang-tidy/bugprone/UnsafeFunctionsCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/UnsafeFunctionsCheck.cpp
index ea7eaa0b0ff811..05c2063402b080 100644
--- a/clang-tools-extra/clang-tidy/bugprone/UnsafeFunctionsCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/UnsafeFunctionsCheck.cpp
@@ -7,6 +7,8 @@
 
//===--===//
 
 #include "UnsafeFunctionsCheck.h"
+#include "../utils/Matchers.h"
+#include "../utils/OptionsUtils.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/Lex/PPCallbacks.h"
@@ -18,6 +20,12 @@ using namespace llvm;
 
 namespace clang::tidy::bugprone {
 
+static constexpr llvm::StringLiteral OptionNameCustomNormalFunctions =
+"CustomNormalFunctions";
+static constexpr llvm::StringLiteral OptionNameCustomAnnexKFunctions =
+"CustomAnnexKFunctions";
+static constexpr llvm::StringLiteral OptionNameReportDefaultFunctions =
+"ReportDefaultFunctions";
 static constexpr llvm::StringLiteral OptionNameReportMoreUnsafeFunctions =
 "ReportMoreUnsafeFunctions";
 
@@ -26,6 +34,10 @@ static constexpr llvm::StringLiteral 
FunctionNamesWithAnnexKReplacementId =
 static constexpr llvm::StringLiteral FunctionNamesId = "FunctionsNames";
 static constexpr llvm::StringLiteral AdditionalFunctionNamesId =
 "AdditionalFunctionsNames";
+static constexpr llvm::StringLiteral CustomFunctionNamesId =
+"CustomFunctionNames";
+static constexpr llvm::StringLiteral CustomAnnexKFunctionNamesId =
+"CustomAnnexKFunctionNames";
 static constexpr llvm::StringLiteral DeclRefId = "DRE";
 
 static std::optional
@@ -127,57 +139,155 @@ static bool isAnnexKAvailable(std::optional 
&CacheVar, Preprocessor *PP,
   return CacheVar.value();
 }
 
+static std::vector
+ParseCheckedFunctions(StringRef Option, StringRef OptionName,
+  ClangTidyContext *Context) {
+  std::vector Functions = utils::options::parseStringList(Option);
+  std::vector Result;
+  Result.reserve(Functions.size());
+
+  for (StringRef Function : Functions) {
+if (Function.empty()) {
+  continue;
+}
+
+auto [Name, Rest] = Function.split(',');
+auto [Replacement, Reason] = Rest.split(',');
+
+if (Name.trim().empty()) {
+  Context->configurationDiag("invalid configuration value for option '%0'; 
"
+ "expected the name of an unsafe function")
+  << OptionName;
+}
+
+if (Replacement.trim().empty()) {
+  Context->configurationDiag(
+  "invalid configuration value '%0' for option '%1'; "
+  "expected a replacement function name")
+  << Name.trim() << OptionName;
+}
+
+Result.push_back({Name.trim().str(), llvm::Regex(Name.trim()),
+  Replacement.trim().str(), Reason.trim().str()});
+  }
+
+  return Result;
+}
+
+static std::string SerializeCheckedFunctions(
+const std::vector &Functions) {
+  std::vector Result;
+  Result.reserve(Functions.size());
+
+  for (const auto &Entry : Functions) {
+if (Entry.Reason.empty())
+  Result.push_back(Entry.Name + "," + Entry.Replacement);
+else
+  Result.push_back(Entry.Name + "," + Entry.Replacement + "," +
+   Entry.Reason);
+  }
+
+  return llvm::join(Result, ";");
+}
+
 UnsafeFunctionsCheck::UnsafeFunctionsCheck(StringRef Name,
ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
+  CustomNormalFunctions(ParseCheckedFunctions(
+  Options.get(OptionNameCustomNormalFunctions, ""),
+  OptionNameCustomNormalFunctions, Context)),
+  CustomAnnexKFunctions(ParseCheckedFunctions(
+  Options.get(OptionNameCustomAnnexKFunctions, ""),
+  OptionNameCustomAnnexKFunctions, Context)),
+  ReportDefaultFunctions(
+  Options.get(OptionNameReportDefaultFunctions, true)),
   ReportMoreUnsafeFunctions(
   Options.get(OptionNameReportMoreUnsafeFunctions, true)) {}
 
 void UnsafeFunctionsCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, OptionNameCustomNormalFunctions,
+SerializeChecke

[clang] [llvm] [SPIRV][RFC] Rework / extend support for memory scopes (PR #106429)

2024-09-11 Thread Vyacheslav Levytskyy via cfe-commits

VyacheslavLevytskyy wrote:

Thank you @AlexVlx for answering some of my questions. It was exactly my point 
in the comment that clang is not the only available FE and SPIRV BE should 
remain agnostic towards vendors, frameworks, etc., so it's nice to be on the 
same page wrt. vendor-specific choice of terminology (the use of "singlethread" 
is justified, but "all_svm_devices" is not) and/or the choice of default values 
(the System scope in the role of a stricter default is a reasonable 
justification). SPIRV BE needs to accommodate any flavor of SPIR-V Compute with 
equal hospitality, so, continuing your metaphor, that train still waits on the 
platform, it's just a matter of will and considerate manner of changes.

Just a couple of comments:

> Perhaps a better solution is to add an option that controls this behaviour / 
> the default, that the BE can consume and act accordingly?

It doesn't seem necessary to get one more command line arg to cover this, it 
doesn't help more than setting an explicit scope in a (highly hypothetical) 
customer's code.

> I believe the current string based design was put in place to give full 
> freedom to targets, so relying strictly on integer values for scopes is 
> legacy/less preferred.

I don't agree. Existing implementation gives the same level of freedom to 
targets, using string values in the same way. However, we don't expect a target 
to change string names of scopes between getMemScope() calls, so there is no 
justification to use strings in every call instead of accounting for string 
names just once. I'd vote to keep the current approach as more performant.

Talking about the best way to move forward, I don't see any contention points. 
I'd be glad to hear from you at the SPIR-V BE discussion group where it should 
be possible to talk this out faster/easier, or just here, both will do. 
Probably topics comprise just (1) the default value, (2) how to spell the word 
"all_svm_devices" properly to remain agnostic wrt. vendors (would it be 
"system"? "crossdevice"? anything else?), and (3) no reason behind 
getSyncScopeNames() asking string scope names on each call to getMemScope() 
instead of integers as now (i.e., if we indeed need to change the default, it 
looks a reasonable decision to integrate it with the existing code).

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


[clang] [lldb] [llvm] Test branch1 (PR #108178)

2024-09-11 Thread via cfe-commits

github-actions[bot] wrote:



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

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

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

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

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

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

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

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


[clang] [lldb] [llvm] Test branch1 (PR #108178)

2024-09-11 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang

@llvm/pr-subscribers-llvm-binary-utilities

Author: None (Lakshmi-Surekha)


Changes



---

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


129 Files Affected:

- (modified) clang/lib/CodeGen/CGObjCMac.cpp (+5-1) 
- (modified) lldb/CMakeLists.txt (+4) 
- (added) lldb/NOTICE.TXT (+7) 
- (modified) lldb/cmake/modules/LLDBConfig.cmake (+1-1) 
- (modified) lldb/include/lldb/Core/Module.h (+3) 
- (modified) lldb/include/lldb/Core/ModuleSpec.h (+21-2) 
- (modified) lldb/include/lldb/Host/HostGetOpt.h (+1-1) 
- (modified) lldb/include/lldb/Host/HostInfo.h (+3) 
- (modified) lldb/include/lldb/Host/HostInfoBase.h (+1-1) 
- (modified) lldb/include/lldb/Host/XML.h (+5) 
- (added) lldb/include/lldb/Host/aix/AbstractSocket.h (+25) 
- (added) lldb/include/lldb/Host/aix/Host.h (+22) 
- (added) lldb/include/lldb/Host/aix/HostInfoAIX.h (+42) 
- (added) lldb/include/lldb/Host/aix/Ptrace.h (+62) 
- (added) lldb/include/lldb/Host/aix/Support.h (+29) 
- (added) lldb/include/lldb/Host/aix/Uio.h (+23) 
- (modified) lldb/include/lldb/Host/common/GetOptInc.h (+3-3) 
- (modified) lldb/include/lldb/Symbol/ObjectFile.h (+5) 
- (modified) lldb/include/lldb/Target/ABI.h (+6) 
- (modified) lldb/include/lldb/Target/DynamicLoader.h (+6) 
- (modified) lldb/include/lldb/Target/Process.h (+14) 
- (modified) lldb/include/lldb/Target/RegisterContextUnwind.h (+4) 
- (modified) lldb/include/lldb/Target/ThreadPlanCallFunction.h (+6) 
- (modified) lldb/include/lldb/Utility/StringExtractorGDBRemote.h (+1) 
- (modified) lldb/include/lldb/lldb-private-enumerations.h (+1) 
- (modified) lldb/source/API/CMakeLists.txt (+108) 
- (modified) lldb/source/API/SBBreakpoint.cpp (+3-3) 
- (modified) lldb/source/API/SBBreakpointLocation.cpp (+3-3) 
- (modified) lldb/source/API/SBBreakpointName.cpp (+2-2) 
- (modified) lldb/source/Core/DynamicLoader.cpp (+10) 
- (modified) lldb/source/Core/Mangled.cpp (+2) 
- (modified) lldb/source/Core/Module.cpp (+12) 
- (modified) lldb/source/Core/Section.cpp (+4) 
- (modified) lldb/source/Expression/DWARFExpression.cpp (+5-5) 
- (modified) lldb/source/Host/CMakeLists.txt (+13) 
- (added) lldb/source/Host/aix/AbstractSocket.cpp (+21) 
- (added) lldb/source/Host/aix/Host.cpp (+304) 
- (added) lldb/source/Host/aix/HostInfoAIX.cpp (+215) 
- (added) lldb/source/Host/aix/Support.cpp (+44) 
- (modified) lldb/source/Host/common/GetOptInc.cpp (+1-1) 
- (modified) lldb/source/Host/common/Host.cpp (+174-6) 
- (added) lldb/source/Host/common/LICENSE.aix-netbsd.txt (+125) 
- (modified) lldb/source/Host/common/XML.cpp (+3) 
- (modified) lldb/source/Host/posix/ConnectionFileDescriptorPosix.cpp (+2) 
- (modified) lldb/source/Host/posix/FileSystemPosix.cpp (+2) 
- (modified) lldb/source/Host/posix/MainLoopPosix.cpp (+17) 
- (modified) lldb/source/Host/posix/ProcessLauncherPosixFork.cpp (+5) 
- (modified) lldb/source/Initialization/CMakeLists.txt (+1-1) 
- (modified) lldb/source/Initialization/SystemInitializerCommon.cpp (+2-2) 
- (modified) lldb/source/Plugins/ABI/PowerPC/ABISysV_ppc64.cpp (+130-1) 
- (modified) lldb/source/Plugins/ABI/PowerPC/ABISysV_ppc64.h (+6) 
- (added) lldb/source/Plugins/DynamicLoader/AIX-DYLD/CMakeLists.txt (+11) 
- (added) lldb/source/Plugins/DynamicLoader/AIX-DYLD/DynamicLoaderAIXDYLD.cpp 
(+272) 
- (added) lldb/source/Plugins/DynamicLoader/AIX-DYLD/DynamicLoaderAIXDYLD.h 
(+55) 
- (modified) lldb/source/Plugins/DynamicLoader/CMakeLists.txt (+1) 
- (modified) 
lldb/source/Plugins/DynamicLoader/Darwin-Kernel/DynamicLoaderDarwinKernel.cpp 
(+2-2) 
- (modified) 
lldb/source/Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderDarwin.cpp (+1-1) 
- (modified) lldb/source/Plugins/Instruction/PPC64/EmulateInstructionPPC64.cpp 
(+193-3) 
- (modified) lldb/source/Plugins/Instruction/PPC64/EmulateInstructionPPC64.h 
(+14) 
- (modified) 
lldb/source/Plugins/InstrumentationRuntime/MainThreadChecker/InstrumentationRuntimeMainThreadChecker.cpp
 (+1-1) 
- (modified) 
lldb/source/Plugins/InstrumentationRuntime/TSan/InstrumentationRuntimeTSan.cpp 
(+7-7) 
- (modified) 
lldb/source/Plugins/InstrumentationRuntime/UBSan/InstrumentationRuntimeUBSan.cpp
 (+1-1) 
- (modified) lldb/source/Plugins/JITLoader/GDB/JITLoaderGDB.cpp (+4) 
- (modified) lldb/source/Plugins/Language/ObjC/Cocoa.cpp (+2) 
- (modified) lldb/source/Plugins/MemoryHistory/asan/MemoryHistoryASan.cpp 
(+1-1) 
- (modified) 
lldb/source/Plugins/ObjectContainer/BSD-Archive/ObjectContainerBSDArchive.cpp 
(+1-1) 
- (added) lldb/source/Plugins/ObjectContainer/Big-Archive/CMakeLists.txt (+10) 
- (added) 
lldb/source/Plugins/ObjectContainer/Big-Archive/ObjectContainerBigArchive.cpp 
(+522) 
- (added) 
lldb/source/Plugins/ObjectContainer/Big-Archive/ObjectContainerBigArchive.h 
(+177) 
- (modified) lldb/source/Plugins/ObjectContainer/CMakeLists.txt (+1) 
- (modified) lldb/source/Plugins/ObjectFile/CMakeLists.txt (+1) 
- (modified) lldb/source/Plugins/ObjectFile/Mach-O

[clang] [lldb] [llvm] Test branch1 (PR #108178)

2024-09-11 Thread via cfe-commits

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


[clang] [lldb] [llvm] Test branch1 (PR #108178)

2024-09-11 Thread via cfe-commits

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


[clang] [lldb] [llvm] Test branch1 (PR #108178)

2024-09-11 Thread via cfe-commits

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


[clang] [TBAA] Emit "omnipotent char" for intrinsics with type cast (PR #107793)

2024-09-11 Thread Matt Arsenault via cfe-commits

arsenm wrote:

> Hi, @paulwalker-arm, ACLE allows users to do instruction-level development, 
> but mixing intrinsic and regular C code may break some of the rules set by 
> the compiler. 

The rules are still there. You can always use a union or copy to avoid 
violating the rules. I don't think it makes sense to special case any 
intrinsics 


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


[clang] [alpha.webkit.UncountedCallArgsChecker] Allow protector functions in Objective-C++ (PR #108184)

2024-09-11 Thread Ryosuke Niwa via cfe-commits

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

This PR fixes the bug that WebKit checkers didn't recognize the return value of 
an Objective-C++ selector which returns Ref or RefPtr to be safe.

>From c8cd18baa5b285262905ad0d8c49ba102993ef1e Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa 
Date: Wed, 11 Sep 2024 03:14:31 -0700
Subject: [PATCH] [alpha.webkit.UncountedCallArgsChecker] Allow protector
 functions in Objective-C++

This PR fixes the bug that WebKit checkers didn't recognize the return value of
an Objective-C++ selector which returns Ref or RefPtr to be safe.
---
 .../Checkers/WebKit/PtrTypesSemantics.cpp | 11 
 .../Checkers/WebKit/PtrTypesSemantics.h   |  5 
 .../WebKit/UncountedCallArgsChecker.cpp   |  3 +--
 .../Checkers/WebKit/uncounted-obj-arg.mm  | 26 +++
 4 files changed, 43 insertions(+), 2 deletions(-)
 create mode 100644 clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.mm

diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
index 49bbff1942167b..5a484d0546e95f 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
@@ -143,6 +143,17 @@ bool isReturnValueRefCounted(const clang::FunctionDecl *F) 
{
   return false;
 }
 
+std::optional isUncounted(const clang::QualType T)
+{
+  if (auto *Subst = dyn_cast(T)) {
+if (auto *Decl = Subst->getAssociatedDecl()) {
+  if (isRefType(safeGetName(Decl)))
+return false;
+}
+  }
+  return isUncounted(T->getAsCXXRecordDecl());
+}
+
 std::optional isUncounted(const CXXRecordDecl* Class)
 {
   // Keep isRefCounted first as it's cheaper.
diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h
index ec1db1cc335807..2932e62ad06e4b 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h
@@ -20,6 +20,7 @@ class CXXMethodDecl;
 class CXXRecordDecl;
 class Decl;
 class FunctionDecl;
+class QualType;
 class Stmt;
 class Type;
 
@@ -42,6 +43,10 @@ std::optional isRefCountable(const 
clang::CXXRecordDecl* Class);
 /// \returns true if \p Class is ref-counted, false if not.
 bool isRefCounted(const clang::CXXRecordDecl *Class);
 
+/// \returns true if \p Class is ref-countable AND not ref-counted, false if
+/// not, std::nullopt if inconclusive.
+std::optional isUncounted(const clang::QualType T);
+
 /// \returns true if \p Class is ref-countable AND not ref-counted, false if
 /// not, std::nullopt if inconclusive.
 std::optional isUncounted(const clang::CXXRecordDecl* Class);
diff --git 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp
index 704c082a4d1d63..81c2434ce64775 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp
@@ -87,8 +87,7 @@ class UncountedCallArgsChecker
 }
 auto *E = MemberCallExpr->getImplicitObjectArgument();
 QualType ArgType = MemberCallExpr->getObjectType();
-std::optional IsUncounted =
-isUncounted(ArgType->getAsCXXRecordDecl());
+std::optional IsUncounted = isUncounted(ArgType);
 if (IsUncounted && *IsUncounted && !isPtrOriginSafe(E))
   reportBugOnThis(E);
   }
diff --git a/clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.mm 
b/clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.mm
new file mode 100644
index 00..db0c5b19eec5bb
--- /dev/null
+++ b/clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.mm
@@ -0,0 +1,26 @@
+// RUN: %clang_analyze_cc1 
-analyzer-checker=alpha.webkit.UncountedCallArgsChecker -verify %s
+// expected-no-diagnostics
+
+#import "mock-types.h"
+#import "mock-system-header.h"
+#import "../../Inputs/system-header-simulator-for-objc-dealloc.h"
+
+@interface Foo : NSObject
+
+@property (nonatomic, readonly) RefPtr countable;
+
+- (void)execute;
+- (RefPtr)_protectedRefCountable;
+@end
+
+@implementation Foo
+
+- (void)execute {
+  self._protectedRefCountable->method();
+}
+
+- (RefPtr)_protectedRefCountable {
+  return _countable;
+}
+
+@end

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


[clang] [alpha.webkit.UncountedCallArgsChecker] Allow protector functions in Objective-C++ (PR #108184)

2024-09-11 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Ryosuke Niwa (rniwa)


Changes

This PR fixes the bug that WebKit checkers didn't recognize the return value of 
an Objective-C++ selector which returns Ref or RefPtr to be safe.

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


4 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp 
(+11) 
- (modified) clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h (+5) 
- (modified) 
clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp (+1-2) 
- (added) clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.mm (+26) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
index 49bbff1942167b..5a484d0546e95f 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
@@ -143,6 +143,17 @@ bool isReturnValueRefCounted(const clang::FunctionDecl *F) 
{
   return false;
 }
 
+std::optional isUncounted(const clang::QualType T)
+{
+  if (auto *Subst = dyn_cast(T)) {
+if (auto *Decl = Subst->getAssociatedDecl()) {
+  if (isRefType(safeGetName(Decl)))
+return false;
+}
+  }
+  return isUncounted(T->getAsCXXRecordDecl());
+}
+
 std::optional isUncounted(const CXXRecordDecl* Class)
 {
   // Keep isRefCounted first as it's cheaper.
diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h
index ec1db1cc335807..2932e62ad06e4b 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h
@@ -20,6 +20,7 @@ class CXXMethodDecl;
 class CXXRecordDecl;
 class Decl;
 class FunctionDecl;
+class QualType;
 class Stmt;
 class Type;
 
@@ -42,6 +43,10 @@ std::optional isRefCountable(const 
clang::CXXRecordDecl* Class);
 /// \returns true if \p Class is ref-counted, false if not.
 bool isRefCounted(const clang::CXXRecordDecl *Class);
 
+/// \returns true if \p Class is ref-countable AND not ref-counted, false if
+/// not, std::nullopt if inconclusive.
+std::optional isUncounted(const clang::QualType T);
+
 /// \returns true if \p Class is ref-countable AND not ref-counted, false if
 /// not, std::nullopt if inconclusive.
 std::optional isUncounted(const clang::CXXRecordDecl* Class);
diff --git 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp
index 704c082a4d1d63..81c2434ce64775 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp
@@ -87,8 +87,7 @@ class UncountedCallArgsChecker
 }
 auto *E = MemberCallExpr->getImplicitObjectArgument();
 QualType ArgType = MemberCallExpr->getObjectType();
-std::optional IsUncounted =
-isUncounted(ArgType->getAsCXXRecordDecl());
+std::optional IsUncounted = isUncounted(ArgType);
 if (IsUncounted && *IsUncounted && !isPtrOriginSafe(E))
   reportBugOnThis(E);
   }
diff --git a/clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.mm 
b/clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.mm
new file mode 100644
index 00..db0c5b19eec5bb
--- /dev/null
+++ b/clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.mm
@@ -0,0 +1,26 @@
+// RUN: %clang_analyze_cc1 
-analyzer-checker=alpha.webkit.UncountedCallArgsChecker -verify %s
+// expected-no-diagnostics
+
+#import "mock-types.h"
+#import "mock-system-header.h"
+#import "../../Inputs/system-header-simulator-for-objc-dealloc.h"
+
+@interface Foo : NSObject
+
+@property (nonatomic, readonly) RefPtr countable;
+
+- (void)execute;
+- (RefPtr)_protectedRefCountable;
+@end
+
+@implementation Foo
+
+- (void)execute {
+  self._protectedRefCountable->method();
+}
+
+- (RefPtr)_protectedRefCountable {
+  return _countable;
+}
+
+@end

``




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


[clang] [alpha.webkit.UncountedCallArgsChecker] Allow protector functions in Objective-C++ (PR #108184)

2024-09-11 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 34cab2ed82a63ecf3d0ebf790def6d21bd4b87af 
c8cd18baa5b285262905ad0d8c49ba102993ef1e --extensions h,cpp -- 
clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp 
clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h 
clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
index 5a484d0546..25aaa5c5fd 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
@@ -143,8 +143,7 @@ bool isReturnValueRefCounted(const clang::FunctionDecl *F) {
   return false;
 }
 
-std::optional isUncounted(const clang::QualType T)
-{
+std::optional isUncounted(const clang::QualType T) {
   if (auto *Subst = dyn_cast(T)) {
 if (auto *Decl = Subst->getAssociatedDecl()) {
   if (isRefType(safeGetName(Decl)))

``




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


[clang] [llvm] [SPIR-V] Add SPIR-V structurizer (PR #107408)

2024-09-11 Thread Nathan Gauër via cfe-commits


@@ -744,79 +744,139 @@ static void insertSpirvDecorations(MachineFunction &MF, 
MachineIRBuilder MIB) {
 MI->eraseFromParent();
 }
 
-// Find basic blocks of the switch and replace registers in spv_switch() by its
-// MBB equivalent.
-static void processSwitches(MachineFunction &MF, SPIRVGlobalRegistry *GR,
-MachineIRBuilder MIB) {
-  DenseMap BB2MBB;
-  SmallVector>>
-  Switches;
+// LLVM allows the switches to use registers as cases, while SPIR-V required
+// those to be immediate values. This function replaces such operands with the
+// equivalent immediate constant.
+static void processSwitchesConstants(MachineFunction &MF,
+ SPIRVGlobalRegistry *GR,
+ MachineIRBuilder MIB) {
+  MachineRegisterInfo &MRI = MF.getRegInfo();
   for (MachineBasicBlock &MBB : MF) {
-MachineRegisterInfo &MRI = MF.getRegInfo();
-BB2MBB[MBB.getBasicBlock()] = &MBB;
 for (MachineInstr &MI : MBB) {
   if (!isSpvIntrinsic(MI, Intrinsic::spv_switch))
 continue;
-  // Calls to spv_switch intrinsics representing IR switches.
-  SmallVector NewOps;
-  for (unsigned i = 2; i < MI.getNumOperands(); ++i) {
+
+  SmallVector NewOperands;
+  NewOperands.push_back(MI.getOperand(0)); // Opcode
+  NewOperands.push_back(MI.getOperand(1)); // Condition
+  NewOperands.push_back(MI.getOperand(2)); // Default
+  for (unsigned i = 3; i < MI.getNumOperands(); i += 2) {
 Register Reg = MI.getOperand(i).getReg();
-if (i % 2 == 1) {
-  MachineInstr *ConstInstr = getDefInstrMaybeConstant(Reg, &MRI);
-  NewOps.push_back(ConstInstr);
-} else {
-  MachineInstr *BuildMBB = MRI.getVRegDef(Reg);
-  assert(BuildMBB &&
- BuildMBB->getOpcode() == TargetOpcode::G_BLOCK_ADDR &&
- BuildMBB->getOperand(1).isBlockAddress() &&
- BuildMBB->getOperand(1).getBlockAddress());
-  NewOps.push_back(BuildMBB);
-}
+MachineInstr *ConstInstr = getDefInstrMaybeConstant(Reg, &MRI);
+NewOperands.push_back(
+MachineOperand::CreateCImm(ConstInstr->getOperand(1).getCImm()));
+
+NewOperands.push_back(MI.getOperand(i + 1));
   }
-  Switches.push_back(std::make_pair(&MI, NewOps));
+
+  assert(MI.getNumOperands() == NewOperands.size());
+  while (MI.getNumOperands() > 0)
+MI.removeOperand(0);
+  for (auto &MO : NewOperands)
+MI.addOperand(MO);
 }
   }
+}
 
+// Some instructions are used during CodeGen but should never be emitted.
+// Cleaning up those.
+static void cleanupHelperInstructions(MachineFunction &MF) {
   SmallPtrSet ToEraseMI;
+  for (MachineBasicBlock &MBB : MF) {
+for (MachineInstr &MI : MBB) {
+  if (isSpvIntrinsic(MI, Intrinsic::spv_track_constant) ||
+  MI.getOpcode() == TargetOpcode::G_BRINDIRECT)
+ToEraseMI.insert(&MI);
+}
+  }
+
+  for (MachineInstr *MI : ToEraseMI)
+MI->eraseFromParent();
+}
+
+// Find all usages of G_BLOCK_ADDR in our intrinsics and replace those
+// operands/registers by the actual MBB it references.
+static void processBlockAddr(MachineFunction &MF, SPIRVGlobalRegistry *GR,
+ MachineIRBuilder MIB) {
+  // Gather the reverse-mapping BB -> MBB.
+  DenseMap BB2MBB;
+  for (MachineBasicBlock &MBB : MF)
+BB2MBB[MBB.getBasicBlock()] = &MBB;
+
+  // Gather instructions requiring patching. For now, only those can use
+  // G_BLOCK_ADDR.
+  SmallVector InstructionsToPatch;
+  for (MachineBasicBlock &MBB : MF) {
+for (MachineInstr &MI : MBB) {
+  if (isSpvIntrinsic(MI, Intrinsic::spv_switch) ||
+  isSpvIntrinsic(MI, Intrinsic::spv_loop_merge) ||
+  isSpvIntrinsic(MI, Intrinsic::spv_selection_merge))
+InstructionsToPatch.push_back(&MI);
+}
+  }
+
+  // For each instruction to fix, we replace all the G_BLOCK_ADDR operands by
+  // the actual MBB it references. Once those references updated, we can 
cleanup
+  // remaining G_BLOCK_ADDR references.
   SmallPtrSet ClearAddressTaken;
-  for (auto &SwIt : Switches) {
-MachineInstr &MI = *SwIt.first;
-MachineBasicBlock *MBB = MI.getParent();
-SmallVector &Ins = SwIt.second;
+  SmallPtrSet ToEraseMI;
+  MachineRegisterInfo &MRI = MF.getRegInfo();
+  for (MachineInstr *MI : InstructionsToPatch) {
 SmallVector NewOps;
-for (unsigned i = 0; i < Ins.size(); ++i) {
-  if (Ins[i]->getOpcode() == TargetOpcode::G_BLOCK_ADDR) {
-BasicBlock *CaseBB =
-Ins[i]->getOperand(1).getBlockAddress()->getBasicBlock();
-auto It = BB2MBB.find(CaseBB);
-if (It == BB2MBB.end())
-  report_fatal_error("cannot find a machine basic block by a basic "
- "block in a switch statement");
-MachineBasicBlock *Succ = It->second;
-ClearAddressTaken.insert(Succ);
-Ne

[clang] [llvm] [SPIR-V] Add SPIR-V structurizer (PR #107408)

2024-09-11 Thread Vyacheslav Levytskyy via cfe-commits
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= 
Message-ID:
In-Reply-To: 


VyacheslavLevytskyy wrote:

I didn't dive deeply into the subject, but I'd be eager to assist in a somewhat 
indirect manner. I've tried the PR locally to check this with SYCL and machine 
verifier (expensive checks: on). The former luckily didn't notice any changes, 
but the latter gives some insights. Probably I see one potential issue to 
address with respect to the validity of code between passes, namely after SPIRV 
pre legalizer.

37 of 63 test cases in the 'structurizer' folder are failing when running with 
'llc -verify-machineinstrs', and it looks like the repeat offender is "Virtual 
register defs don't dominate all uses", like in

```
  ...
  %45:iid(s32) = ASSIGN_TYPE %59:iid(s32), %56:type(s64)
  %95:iid(s32) = nsw G_ADD %96:iid, %97:iid
  %96:iid(s32) = GET_ID %45:iid(s32)
  %97:iid(s32) = GET_ID %26:iid(s32)
  %47:iid(s32) = nsw ASSIGN_TYPE %95:iid(s32), %56:type(s64)
  G_STORE %47:iid(s32), %5:pid(p0) :: (store (s32) into %ir.i)
  G_BR %bb.9
  ...

*** Bad machine code: Virtual register defs don't dominate all uses. ***
- function:main
- v. register: %97
```

No existing tests with '-verify-machineinstrs' start to fail, so I guess there 
are no problems with code modifications wrt. the general/existing branching 
logic, but rather with the new use case introduced by the PR/added instructions.

Another weird thing is that llvm specifically build with expensive checks on is 
now hangs (or maybe hits a very long timeout, I haven't yet a patience to 
check) while running our test suite, so I'm not quite sure if this PR introduce 
new issues for Machine Verifier in general, in the part of existing test cases 
where we haven't yet inserted '-verify-machineinstrs'.

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


[clang] [llvm] [DLCov 3/5] Implement DebugLoc origin-tracking (PR #107369)

2024-09-11 Thread Stephen Tozer via cfe-commits

SLTozer wrote:

> @SLTozer What's in patches 4 and 5...? I keep putting off looking at this 
> stack, as I've been waiting for the whole series to appear (perhaps 
> incorrectly)...

Patches 4 and 5 are less consequential, but I'll open them up - patch 4 is 
adding origin-tracking support to the IRBuilder, so that we properly track the 
origin of DebugLocs that have been assigned by the IRBuilder (rather than 
exclusively seeing the IRBuilder as the origin), and patch 5 updates 
`getMergedLocations` in the same way.

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


[clang] [clang-tools-extra] Fix OOM in FormatDiagnostic (PR #108187)

2024-09-11 Thread Vakhurin Sergei via cfe-commits

https://github.com/igelbox created 
https://github.com/llvm/llvm-project/pull/108187

Resolves: #70930 (and probably latest comments from #251)
by fixing racing for the shared `DiagStorage` value which caused messing with 
args inside the storage and then formatting the following message with 
`getArgSInt(1)` == 2:
```
def err_module_odr_violation_function : Error<
  "%q0 has different definitions in different modules; "
  "%select{definition in module '%2'|defined here}1 "
  "first difference is "
```
which causes `HandleSelectModifier` to go beyond the `ArgumentLen` so the 
recursive call to `FormatDiagnostic` was made with `DiagStr` > `DiagEnd` that 
leads to infinite `while (DiagStr != DiagEnd)`.

**The Main Idea:**
Reuse the existing `DiagStorageAllocator` logic to make all 
`DiagnosticBuilder`s having independent states.
Also, encapsulating the rest of state (e.g. ID and Loc) into 
`DiagnosticBuilder`.

**TODO (or not todo):**
- [ ] add a test (I have no idea how to turn a whole bunch of my proprietary 
code which leads `clangd` to OOM into a small public example.. probably I must 
try using 
[this](https://github.com/llvm/llvm-project/issues/70930#issuecomment-2209872975)
 instead)
- [ ] figure `Diag.CurDiagID != diag::fatal_too_many_errors` out
- [ ] ? get rid of `DiagStorageAllocator` at all and make `DiagnosticBuilder` 
having they own `DiagnosticStorage` coz it seems pretty small so should fit the 
stack for short-living `DiagnosticBuilder` instances

>From f26c4f33c838f173cd330a18b66eb94ffa7fcc87 Mon Sep 17 00:00:00 2001
From: Sergei 
Date: Tue, 10 Sep 2024 16:19:05 +
Subject: [PATCH] fix quick OOM in FormatDiagnostic

---
 .../ClangTidyDiagnosticConsumer.cpp   |   2 -
 clang/include/clang/Basic/Diagnostic.h| 269 ++
 clang/include/clang/Basic/DiagnosticIDs.h |   7 +-
 clang/include/clang/Basic/PartialDiagnostic.h |   5 +-
 clang/include/clang/Sema/Sema.h   |   6 +-
 clang/lib/Basic/Diagnostic.cpp|  86 +++---
 clang/lib/Basic/DiagnosticIDs.cpp |  22 +-
 clang/lib/Basic/SourceManager.cpp |  23 +-
 clang/lib/Frontend/Rewrite/FixItRewriter.cpp  |   4 +-
 clang/lib/Frontend/TextDiagnosticPrinter.cpp  |   2 +-
 clang/lib/Sema/Sema.cpp   |  19 +-
 clang/lib/Sema/SemaBase.cpp   |   2 +-
 clang/lib/Serialization/ASTReader.cpp |  15 +-
 clang/unittests/Basic/DiagnosticTest.cpp  |   4 -
 clang/unittests/Driver/DXCModeTest.cpp|   5 -
 15 files changed, 174 insertions(+), 297 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp 
b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
index 200bb87a5ac3cb..4c75b422701148 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
@@ -380,7 +380,6 @@ void ClangTidyDiagnosticConsumer::HandleDiagnostic(
 ++Context.Stats.ErrorsIgnoredNOLINT;
 // Ignored a warning, should ignore related notes as well
 LastErrorWasIgnored = true;
-Context.DiagEngine->Clear();
 for (const auto &Error : SuppressionErrors)
   Context.diag(Error);
 return;
@@ -457,7 +456,6 @@ void ClangTidyDiagnosticConsumer::HandleDiagnostic(
   if (Info.hasSourceManager())
 checkFilters(Info.getLocation(), Info.getSourceManager());
 
-  Context.DiagEngine->Clear();
   for (const auto &Error : SuppressionErrors)
 Context.diag(Error);
 }
diff --git a/clang/include/clang/Basic/Diagnostic.h 
b/clang/include/clang/Basic/Diagnostic.h
index 0c7836c2ea569c..1eecab4f6e49a2 100644
--- a/clang/include/clang/Basic/Diagnostic.h
+++ b/clang/include/clang/Basic/Diagnostic.h
@@ -183,6 +183,41 @@ struct DiagnosticStorage {
   DiagnosticStorage() = default;
 };
 
+/// An allocator for DiagnosticStorage objects, which uses a small cache to
+/// objects, used to reduce malloc()/free() traffic for partial diagnostics.
+class DiagStorageAllocator {
+  static const unsigned NumCached = 16;
+  DiagnosticStorage Cached[NumCached];
+  DiagnosticStorage *FreeList[NumCached];
+  unsigned NumFreeListEntries;
+
+public:
+  DiagStorageAllocator();
+  ~DiagStorageAllocator();
+
+  /// Allocate new storage.
+  DiagnosticStorage *Allocate() {
+if (NumFreeListEntries == 0)
+  return new DiagnosticStorage;
+
+DiagnosticStorage *Result = FreeList[--NumFreeListEntries];
+Result->NumDiagArgs = 0;
+Result->DiagRanges.clear();
+Result->FixItHints.clear();
+return Result;
+  }
+
+  /// Free the given storage object.
+  void Deallocate(DiagnosticStorage *S) {
+if (S >= Cached && S <= Cached + NumCached) {
+  FreeList[NumFreeListEntries++] = S;
+  return;
+}
+
+delete S;
+  }
+};
+
 /// Concrete class used by the front-end to report problems and issues.
 ///
 /// This massages the diagnostics (e.g. handling things like "report warnings
@@ -520,27 +555,6 @@ class DiagnosticsEngine : public 
Ref

[clang] [clang-tools-extra] Fix OOM in FormatDiagnostic (PR #108187)

2024-09-11 Thread via cfe-commits

github-actions[bot] wrote:



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

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

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

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

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

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

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

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


[clang] [clang-tools-extra] Fix OOM in FormatDiagnostic (PR #108187)

2024-09-11 Thread Vakhurin Sergei via cfe-commits


@@ -571,8 +571,7 @@ DiagnosticIDs::getDiagnosticSeverity(unsigned DiagID, 
SourceLocation Loc,
   }
 
   // If explicitly requested, map fatal errors to errors.
-  if (Result == diag::Severity::Fatal &&
-  Diag.CurDiagID != diag::fatal_too_many_errors && Diag.FatalsAsError)

igelbox wrote:

I'm not sure why do we checked for `Diag.CurDiagID != 
diag::fatal_too_many_errors` here.
Moreover even without this piece of code unit-tests succeed.

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


[clang] [clang-tools-extra] Fix OOM in FormatDiagnostic (PR #108187)

2024-09-11 Thread Vakhurin Sergei via cfe-commits


@@ -1333,13 +1263,7 @@ class DiagnosticBuilder : public StreamingDiagnostic {
 public:
   /// Copy constructor.  When copied, this "takes" the diagnostic info from the
   /// input and neuters it.
-  DiagnosticBuilder(const DiagnosticBuilder &D) : StreamingDiagnostic() {
-DiagObj = D.DiagObj;
-DiagStorage = D.DiagStorage;

igelbox wrote:

Well well, `DiagStorage` might be allocated via `DiagStorageAllocator` so this 
looked like a potential memory manager mess. Now, I fixed this (see cpp).

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


[clang] [clang-tools-extra] Fix OOM in FormatDiagnostic (PR #108187)

2024-09-11 Thread Vakhurin Sergei via cfe-commits


@@ -538,24 +511,51 @@ bool DiagnosticsEngine::EmitCurrentDiagnostic(bool Force) 
{
 Emitted = (DiagLevel != DiagnosticIDs::Ignored);
 if (Emitted) {
   // Emit the diagnostic regardless of suppression level.
-  Diags->EmitDiag(*this, DiagLevel);
+  Diags->EmitDiag(*this, DB, DiagLevel);
 }
   } else {
 // Process the diagnostic, sending the accumulated information to the
 // DiagnosticConsumer.
-Emitted = ProcessDiag();
+Emitted = ProcessDiag(DB);
   }
 
-  // Clear out the current diagnostic object.
-  Clear();
+  return Emitted;
+}
 
-  // If there was a delayed diagnostic, emit it now.
-  if (!Force && DelayedDiagID)
-ReportDelayed();
+DiagnosticBuilder::DiagnosticBuilder(DiagnosticsEngine *diagObj,
+ SourceLocation CurDiagLoc,
+ unsigned CurDiagID)
+: StreamingDiagnostic(diagObj->DiagAllocator), DiagObj(diagObj),
+  CurDiagLoc(CurDiagLoc), CurDiagID(CurDiagID), IsActive(true) {
+  assert(diagObj && "DiagnosticBuilder requires a valid DiagnosticsEngine!");
+}
 
-  return Emitted;
+DiagnosticBuilder::DiagnosticBuilder(const DiagnosticBuilder &D)
+: StreamingDiagnostic() {
+  CurDiagLoc = D.CurDiagLoc;
+  CurDiagID = D.CurDiagID;
+  FlagValue = D.FlagValue;
+  DiagObj = D.DiagObj;
+  DiagStorage = D.DiagStorage;
+  D.DiagStorage = nullptr;

igelbox wrote:

Prevent potential memory manager mess if it was allocated by 
`DiagStorageAllocator`

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


[clang] [clang-tools-extra] Fix OOM in FormatDiagnostic (PR #108187)

2024-09-11 Thread Vakhurin Sergei via cfe-commits

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


[clang] [clang-tools-extra] Fix OOM in FormatDiagnostic (PR #108187)

2024-09-11 Thread Vakhurin Sergei via cfe-commits

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


[clang] [clang-tools-extra] Fix OOM in FormatDiagnostic (PR #108187)

2024-09-11 Thread Vakhurin Sergei via cfe-commits

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


[clang] [clang-scan-deps] Infer the target from the executable name (PR #108189)

2024-09-11 Thread Martin Storsjö via cfe-commits

https://github.com/mstorsjo created 
https://github.com/llvm/llvm-project/pull/108189

This allows clang-scan-deps to work correctly when using cross compilers with 
names like -clang.

From 1c7a8ffac3681ce8d662732c9489629d7d83d092 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Martin=20Storsj=C3=B6?= 
Date: Wed, 11 Sep 2024 11:48:07 +0300
Subject: [PATCH] [clang-scan-deps] Infer the target from the executable name

This allows clang-scan-deps to work correctly when using cross
compilers with names like -clang.
---
 clang/test/ClangScanDeps/implicit-target.c| 31 +++
 clang/tools/clang-scan-deps/ClangScanDeps.cpp |  5 +++
 2 files changed, 36 insertions(+)
 create mode 100644 clang/test/ClangScanDeps/implicit-target.c

diff --git a/clang/test/ClangScanDeps/implicit-target.c 
b/clang/test/ClangScanDeps/implicit-target.c
new file mode 100644
index 00..cf757f937331a6
--- /dev/null
+++ b/clang/test/ClangScanDeps/implicit-target.c
@@ -0,0 +1,31 @@
+// Check that we can detect an implicit target when clang is invoked as
+// clang. Using an implicit triple requires that the target actually
+// is available, too.
+// REQUIRES: x86-registered-target
+
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: sed -e "s|DIR|%/t|g" %t/cdb.json.in > %t/cdb.json
+
+// Check that we can deduce this both when using a compilation database, and 
when using
+// a literal command line.
+
+// RUN: clang-scan-deps -format experimental-full -compilation-database 
%t/cdb.json | FileCheck %s
+
+// RUN: clang-scan-deps -format experimental-full -- x86_64-w64-mingw32-clang 
%t/source.c -o %t/source.o | FileCheck %s
+
+// CHECK: "-triple",
+// CHECK-NEXT: "x86_64-w64-windows-gnu",
+
+
+//--- cdb.json.in
+[
+  {
+"directory": "DIR"
+"command": "x86_64-w64-mingw32-clang -c DIR/source.c -o DIR/source.o"
+"file": "DIR/source.c"
+  },
+]
+
+//--- source.c
+void func(void) {}
diff --git a/clang/tools/clang-scan-deps/ClangScanDeps.cpp 
b/clang/tools/clang-scan-deps/ClangScanDeps.cpp
index a8f6150dd3493d..cd6dd2620152a6 100644
--- a/clang/tools/clang-scan-deps/ClangScanDeps.cpp
+++ b/clang/tools/clang-scan-deps/ClangScanDeps.cpp
@@ -15,6 +15,7 @@
 #include "clang/Tooling/DependencyScanning/DependencyScanningTool.h"
 #include "clang/Tooling/DependencyScanning/DependencyScanningWorker.h"
 #include "clang/Tooling/JSONCompilationDatabase.h"
+#include "clang/Tooling/Tooling.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/Twine.h"
 #include "llvm/Support/CommandLine.h"
@@ -24,6 +25,7 @@
 #include "llvm/Support/LLVMDriver.h"
 #include "llvm/Support/Program.h"
 #include "llvm/Support/Signals.h"
+#include "llvm/Support/TargetSelect.h"
 #include "llvm/Support/ThreadPool.h"
 #include "llvm/Support/Threading.h"
 #include "llvm/Support/Timer.h"
@@ -795,6 +797,7 @@ getCompilationDatabase(int argc, char **argv, std::string 
&ErrorMessage) {
 }
 
 int clang_scan_deps_main(int argc, char **argv, const llvm::ToolContext &) {
+  llvm::InitializeAllTargetInfos();
   std::string ErrorMessage;
   std::unique_ptr Compilations =
   getCompilationDatabase(argc, argv, ErrorMessage);
@@ -810,6 +813,8 @@ int clang_scan_deps_main(int argc, char **argv, const 
llvm::ToolContext &) {
   Compilations = expandResponseFiles(std::move(Compilations),
  llvm::vfs::getRealFileSystem());
 
+  Compilations = inferTargetAndDriverMode(std::move(Compilations));
+
   // The command options are rewritten to run Clang in preprocessor only mode.
   auto AdjustingCompilations =
   std::make_unique(

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


[clang] [clang-scan-deps] Infer the target from the executable name (PR #108189)

2024-09-11 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Martin Storsjö (mstorsjo)


Changes

This allows clang-scan-deps to work correctly when using cross compilers with 
names like -clang.

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


2 Files Affected:

- (added) clang/test/ClangScanDeps/implicit-target.c (+31) 
- (modified) clang/tools/clang-scan-deps/ClangScanDeps.cpp (+5) 


``diff
diff --git a/clang/test/ClangScanDeps/implicit-target.c 
b/clang/test/ClangScanDeps/implicit-target.c
new file mode 100644
index 00..cf757f937331a6
--- /dev/null
+++ b/clang/test/ClangScanDeps/implicit-target.c
@@ -0,0 +1,31 @@
+// Check that we can detect an implicit target when clang is invoked as
+// clang. Using an implicit triple requires that the target actually
+// is available, too.
+// REQUIRES: x86-registered-target
+
+// RUN: rm -rf %t
+// RUN: split-file %s %t
+// RUN: sed -e "s|DIR|%/t|g" %t/cdb.json.in > %t/cdb.json
+
+// Check that we can deduce this both when using a compilation database, and 
when using
+// a literal command line.
+
+// RUN: clang-scan-deps -format experimental-full -compilation-database 
%t/cdb.json | FileCheck %s
+
+// RUN: clang-scan-deps -format experimental-full -- x86_64-w64-mingw32-clang 
%t/source.c -o %t/source.o | FileCheck %s
+
+// CHECK: "-triple",
+// CHECK-NEXT: "x86_64-w64-windows-gnu",
+
+
+//--- cdb.json.in
+[
+  {
+"directory": "DIR"
+"command": "x86_64-w64-mingw32-clang -c DIR/source.c -o DIR/source.o"
+"file": "DIR/source.c"
+  },
+]
+
+//--- source.c
+void func(void) {}
diff --git a/clang/tools/clang-scan-deps/ClangScanDeps.cpp 
b/clang/tools/clang-scan-deps/ClangScanDeps.cpp
index a8f6150dd3493d..cd6dd2620152a6 100644
--- a/clang/tools/clang-scan-deps/ClangScanDeps.cpp
+++ b/clang/tools/clang-scan-deps/ClangScanDeps.cpp
@@ -15,6 +15,7 @@
 #include "clang/Tooling/DependencyScanning/DependencyScanningTool.h"
 #include "clang/Tooling/DependencyScanning/DependencyScanningWorker.h"
 #include "clang/Tooling/JSONCompilationDatabase.h"
+#include "clang/Tooling/Tooling.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/Twine.h"
 #include "llvm/Support/CommandLine.h"
@@ -24,6 +25,7 @@
 #include "llvm/Support/LLVMDriver.h"
 #include "llvm/Support/Program.h"
 #include "llvm/Support/Signals.h"
+#include "llvm/Support/TargetSelect.h"
 #include "llvm/Support/ThreadPool.h"
 #include "llvm/Support/Threading.h"
 #include "llvm/Support/Timer.h"
@@ -795,6 +797,7 @@ getCompilationDatabase(int argc, char **argv, std::string 
&ErrorMessage) {
 }
 
 int clang_scan_deps_main(int argc, char **argv, const llvm::ToolContext &) {
+  llvm::InitializeAllTargetInfos();
   std::string ErrorMessage;
   std::unique_ptr Compilations =
   getCompilationDatabase(argc, argv, ErrorMessage);
@@ -810,6 +813,8 @@ int clang_scan_deps_main(int argc, char **argv, const 
llvm::ToolContext &) {
   Compilations = expandResponseFiles(std::move(Compilations),
  llvm::vfs::getRealFileSystem());
 
+  Compilations = inferTargetAndDriverMode(std::move(Compilations));
+
   // The command options are rewritten to run Clang in preprocessor only mode.
   auto AdjustingCompilations =
   std::make_unique(

``




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


[clang] [llvm] [SPIR-V] Add SPIR-V structurizer (PR #107408)

2024-09-11 Thread Vyacheslav Levytskyy via cfe-commits
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= 
Message-ID:
In-Reply-To: 



@@ -744,79 +744,139 @@ static void insertSpirvDecorations(MachineFunction &MF, 
MachineIRBuilder MIB) {
 MI->eraseFromParent();
 }
 
-// Find basic blocks of the switch and replace registers in spv_switch() by its
-// MBB equivalent.
-static void processSwitches(MachineFunction &MF, SPIRVGlobalRegistry *GR,
-MachineIRBuilder MIB) {
-  DenseMap BB2MBB;
-  SmallVector>>
-  Switches;
+// LLVM allows the switches to use registers as cases, while SPIR-V required
+// those to be immediate values. This function replaces such operands with the
+// equivalent immediate constant.
+static void processSwitchesConstants(MachineFunction &MF,
+ SPIRVGlobalRegistry *GR,
+ MachineIRBuilder MIB) {
+  MachineRegisterInfo &MRI = MF.getRegInfo();
   for (MachineBasicBlock &MBB : MF) {
-MachineRegisterInfo &MRI = MF.getRegInfo();
-BB2MBB[MBB.getBasicBlock()] = &MBB;
 for (MachineInstr &MI : MBB) {
   if (!isSpvIntrinsic(MI, Intrinsic::spv_switch))
 continue;
-  // Calls to spv_switch intrinsics representing IR switches.
-  SmallVector NewOps;
-  for (unsigned i = 2; i < MI.getNumOperands(); ++i) {
+
+  SmallVector NewOperands;
+  NewOperands.push_back(MI.getOperand(0)); // Opcode
+  NewOperands.push_back(MI.getOperand(1)); // Condition
+  NewOperands.push_back(MI.getOperand(2)); // Default
+  for (unsigned i = 3; i < MI.getNumOperands(); i += 2) {
 Register Reg = MI.getOperand(i).getReg();
-if (i % 2 == 1) {
-  MachineInstr *ConstInstr = getDefInstrMaybeConstant(Reg, &MRI);
-  NewOps.push_back(ConstInstr);
-} else {
-  MachineInstr *BuildMBB = MRI.getVRegDef(Reg);
-  assert(BuildMBB &&
- BuildMBB->getOpcode() == TargetOpcode::G_BLOCK_ADDR &&
- BuildMBB->getOperand(1).isBlockAddress() &&
- BuildMBB->getOperand(1).getBlockAddress());
-  NewOps.push_back(BuildMBB);
-}
+MachineInstr *ConstInstr = getDefInstrMaybeConstant(Reg, &MRI);
+NewOperands.push_back(
+MachineOperand::CreateCImm(ConstInstr->getOperand(1).getCImm()));
+
+NewOperands.push_back(MI.getOperand(i + 1));
   }
-  Switches.push_back(std::make_pair(&MI, NewOps));
+
+  assert(MI.getNumOperands() == NewOperands.size());
+  while (MI.getNumOperands() > 0)
+MI.removeOperand(0);
+  for (auto &MO : NewOperands)
+MI.addOperand(MO);
 }
   }
+}
 
+// Some instructions are used during CodeGen but should never be emitted.
+// Cleaning up those.
+static void cleanupHelperInstructions(MachineFunction &MF) {
   SmallPtrSet ToEraseMI;
+  for (MachineBasicBlock &MBB : MF) {
+for (MachineInstr &MI : MBB) {
+  if (isSpvIntrinsic(MI, Intrinsic::spv_track_constant) ||
+  MI.getOpcode() == TargetOpcode::G_BRINDIRECT)
+ToEraseMI.insert(&MI);
+}
+  }
+
+  for (MachineInstr *MI : ToEraseMI)
+MI->eraseFromParent();
+}
+
+// Find all usages of G_BLOCK_ADDR in our intrinsics and replace those
+// operands/registers by the actual MBB it references.
+static void processBlockAddr(MachineFunction &MF, SPIRVGlobalRegistry *GR,
+ MachineIRBuilder MIB) {
+  // Gather the reverse-mapping BB -> MBB.
+  DenseMap BB2MBB;
+  for (MachineBasicBlock &MBB : MF)
+BB2MBB[MBB.getBasicBlock()] = &MBB;
+
+  // Gather instructions requiring patching. For now, only those can use
+  // G_BLOCK_ADDR.
+  SmallVector InstructionsToPatch;
+  for (MachineBasicBlock &MBB : MF) {
+for (MachineInstr &MI : MBB) {
+  if (isSpvIntrinsic(MI, Intrinsic::spv_switch) ||
+  isSpvIntrinsic(MI, Intrinsic::spv_loop_merge) ||
+  isSpvIntrinsic(MI, Intrinsic::spv_selection_merge))
+InstructionsToPatch.push_back(&MI);
+}
+  }
+
+  // For each instruction to fix, we replace all the G_BLOCK_ADDR operands by
+  // the actual MBB it references. Once those references updated, we can 
cleanup
+  // remaining G_BLOCK_ADDR references.
   SmallPtrSet ClearAddressTaken;
-  for (auto &SwIt : Switches) {
-MachineInstr &MI = *SwIt.first;
-MachineBasicBlock *MBB = MI.getParent();
-SmallVector &Ins = SwIt.second;
+  SmallPtrSet ToEraseMI;
+  MachineRegisterInfo &MRI = MF.getRegInfo();
+  for (MachineInstr *MI : InstructionsToPatch) {
 SmallVector NewOps;
-for (unsigned i = 0; i < Ins.size(); ++i) {
-  if (Ins[i]->getOpcode() == TargetOpcode::G_BLOCK_ADDR) {
-BasicBlock *CaseBB =
-Ins[i]->getOperand(1).getBlockAddress()->getBasicBlock();
-auto It

[clang] [llvm] [SPIR-V] Add SPIR-V structurizer (PR #107408)

2024-09-11 Thread Vyacheslav Levytskyy via cfe-commits
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= 
Message-ID:
In-Reply-To: 


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


[clang] [llvm] [SPIR-V] Add SPIR-V structurizer (PR #107408)

2024-09-11 Thread Vyacheslav Levytskyy via cfe-commits
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= 
Message-ID:
In-Reply-To: 


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


[clang] [llvm] [SPIRV][RFC] Rework / extend support for memory scopes (PR #106429)

2024-09-11 Thread Matt Arsenault via cfe-commits


@@ -766,8 +766,19 @@ static void EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr 
*Expr, Address Dest,
   // LLVM atomic instructions always have synch scope. If clang atomic
   // expression has no scope operand, use default LLVM synch scope.
   if (!ScopeModel) {
+llvm::SyncScope::ID SS;
+if (CGF.getLangOpts().OpenCL)
+  // OpenCL approach is: "The functions that do not have memory_scope
+  // argument have the same semantics as the corresponding functions with
+  // the memory_scope argument set to memory_scope_device." See ref.:
+  // 
https://registry.khronos.org/OpenCL/specs/3.0-unified/html/OpenCL_C.html#atomic-functions
+  SS = CGF.getTargetHooks().getLLVMSyncScopeID(CGF.getLangOpts(),
+   SyncScope::OpenCLDevice,
+   Order, 
CGF.getLLVMContext());
+else
+  SS = CGF.getLLVMContext().getOrInsertSyncScopeID("");

arsenm wrote:

Don't need to query this, this can just be llvm::SyncScope::System

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


[clang] [llvm] [SPIRV][RFC] Rework / extend support for memory scopes (PR #106429)

2024-09-11 Thread Matt Arsenault via cfe-commits


@@ -58,7 +58,35 @@ class SPIRVTargetCodeGenInfo : public 
CommonSPIRTargetCodeGenInfo {
   SPIRVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
   : CommonSPIRTargetCodeGenInfo(std::make_unique(CGT)) {}
   void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
+  llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts,
+ SyncScope Scope,
+ llvm::AtomicOrdering Ordering,
+ llvm::LLVMContext &Ctx) const 
override;
 };
+
+inline StringRef mapClangSyncScopeToLLVM(SyncScope Scope) {
+  switch (Scope) {
+  case SyncScope::HIPSingleThread:
+  case SyncScope::SingleScope:
+return "singlethread";
+  case SyncScope::HIPWavefront:
+  case SyncScope::OpenCLSubGroup:
+  case SyncScope::WavefrontScope:
+return "subgroup";
+  case SyncScope::HIPWorkgroup:
+  case SyncScope::OpenCLWorkGroup:
+  case SyncScope::WorkgroupScope:
+return "workgroup";
+  case SyncScope::HIPAgent:
+  case SyncScope::OpenCLDevice:
+  case SyncScope::DeviceScope:
+return "device";
+  case SyncScope::SystemScope:
+  case SyncScope::HIPSystem:
+  case SyncScope::OpenCLAllSVMDevices:
+return "all_svm_devices";

arsenm wrote:

On the naming point, this preferably would use the names directly from the 
SPIRV spec

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


[clang] [llvm] [SPIRV][RFC] Rework / extend support for memory scopes (PR #106429)

2024-09-11 Thread Matt Arsenault via cfe-commits


@@ -251,6 +251,24 @@ SPIRV::MemorySemantics::MemorySemantics 
getMemSemantics(AtomicOrdering Ord) {
   llvm_unreachable(nullptr);
 }
 
+SPIRV::Scope::Scope getMemScope(const LLVMContext &Ctx, SyncScope::ID ID) {
+  SmallVector SSNs;
+  Ctx.getSyncScopeNames(SSNs);
+
+  StringRef MemScope = SSNs[ID];
+  if (MemScope.empty() || MemScope == "all_svm_devices")

arsenm wrote:

Just avoid all_svm_devices altogether? It's the same as the default / ""

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


[clang] [llvm] [SPIR-V] Add SPIR-V structurizer (PR #107408)

2024-09-11 Thread Vyacheslav Levytskyy via cfe-commits
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= ,
Nathan =?utf-8?q?Gauër?= 
Message-ID:
In-Reply-To: 


VyacheslavLevytskyy wrote:

To be absolutely sure I've just cleanly rebuilt llvm with 
`-DLLVM_ENABLE_EXPENSIVE_CHECKS=ON` and I can confirm that our test suite is 
hanging/hitting a timeout now. It's slightly more worrying than 'llc 
-verify-machineinstrs' fails.

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


[clang] e50131a - [clang] Diagnose dangling issues for the "Container" case. (#107213)

2024-09-11 Thread via cfe-commits

Author: Haojian Wu
Date: 2024-09-11T13:20:59+02:00
New Revision: e50131aa068f74daa70d4135c92020aadae3af33

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

LOG: [clang] Diagnose dangling issues for the "Container" case. 
(#107213)

This pull request enhances the GSL lifetime analysis to detect
situations where a dangling `Container` object is
constructed:

```cpp
std::vector bad = {std::string()}; // dangling
```

The assignment case is not yet supported, but they will be addressed in
a follow-up.

Fixes #100526 (excluding the `push_back` case).

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/AttrDocs.td
clang/lib/Sema/CheckExprLifetime.cpp
clang/test/Sema/warn-lifetime-analysis-nocfg.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 250821a9f9c45c..59ccdf1e15cd81 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -298,6 +298,8 @@ Improvements to Clang's diagnostics
 
 - Clang now warns for u8 character literals used in C23 with 
``-Wpre-c23-compat`` instead of ``-Wpre-c++17-compat``.
 
+- Clang now diagnoses cases where a dangling ``GSLOwner`` object 
is constructed, e.g. ``std::vector v = {std::string()};`` 
(#GH100526).
+
 Improvements to Clang's time-trace
 --
 

diff  --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index 546e5100b79dd9..9f72456d2da678 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -6690,6 +6690,20 @@ When the Owner's lifetime ends, it will consider the 
Pointer to be dangling.
 P.getInt(); // P is dangling
   }
 
+If a template class is annotated with ``[[gsl::Owner]]``, and the first
+instantiated template argument is a pointer type (raw pointer, or 
``[[gsl::Pointer]]``),
+the analysis will consider the instantiated class as a container of the 
pointer.
+When constructing such an object from a GSL owner object, the analysis will
+assume that the container holds a pointer to the owner object. Consequently,
+when the owner object is destroyed, the pointer will be considered dangling.
+
+.. code-block:: c++
+
+   int f() {
+ std::vector v = {std::string()}; // v holds a dangling 
pointer.
+ std::optional o = std::string(); // o holds a dangling 
pointer.
+   }
+
 }];
 }
 

diff  --git a/clang/lib/Sema/CheckExprLifetime.cpp 
b/clang/lib/Sema/CheckExprLifetime.cpp
index f1507ebb9a5068..c8e703036c132c 100644
--- a/clang/lib/Sema/CheckExprLifetime.cpp
+++ b/clang/lib/Sema/CheckExprLifetime.cpp
@@ -267,6 +267,26 @@ static bool isInStlNamespace(const Decl *D) {
   return DC->isStdNamespace();
 }
 
+// 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) {
+  if (const auto *CTSD =
+  dyn_cast_if_present(Container)) {
+if (!CTSD->hasAttr()) // Container must be a GSL owner type.
+  return false;
+const auto &TAs = CTSD->getTemplateArgs();
+return TAs.size() > 0 && TAs[0].getKind() == TemplateArgument::Type &&
+   (isRecordWithAttr(TAs[0].getAsType()) ||
+TAs[0].getAsType()->isPointerType());
+  }
+  return false;
+}
+
+static bool isGSLOwner(QualType T) {
+  return isRecordWithAttr(T) &&
+ !isContainerOfPointer(T->getAsRecordDecl());
+}
+
 static bool shouldTrackImplicitObjectArg(const CXXMethodDecl *Callee) {
   if (auto *Conv = dyn_cast_or_null(Callee))
 if (isRecordWithAttr(Conv->getConversionType()))
@@ -275,7 +295,7 @@ static bool shouldTrackImplicitObjectArg(const 
CXXMethodDecl *Callee) {
 return false;
   if (!isRecordWithAttr(
   Callee->getFunctionObjectParameterType()) &&
-  !isRecordWithAttr(Callee->getFunctionObjectParameterType()))
+  !isGSLOwner(Callee->getFunctionObjectParameterType()))
 return false;
   if (Callee->getReturnType()->isPointerType() ||
   isRecordWithAttr(Callee->getReturnType())) {
@@ -413,7 +433,7 @@ static void visitFunctionCallArguments(IndirectLocalPath 
&Path, Expr *Call,
 // Once we initialized a value with a non gsl-owner reference, it can no
 // longer dangle.
 if (ReturnType->isReferenceType() &&
-!isRecordWithAttr(ReturnType->getPointeeType())) {
+!isGSLOwner(ReturnType->getPointeeType())) {
   for (const IndirectLocalPathEntry &PE : llvm::reverse(Path)) {
 if (PE.Kind == IndirectLocalPathEntry::GslReferenceInit ||
 PE.Kind == IndirectLocalPathEntry::LifetimeBoundCall)
@@ -468,12 +488,17 @@ static void visitFunctionCallArguments(IndirectLocalPath 
&Path, Expr *Call,
 if (CheckCoroCall || Callee->getParamDecl(I)->hasAttr())
 

[clang] [clang] Diagnose dangling issues for the "Container" case. (PR #107213)

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

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


[clang] [Clang][Parser] Build up QualifiedTemplateName for typo correction (PR #108148)

2024-09-11 Thread via cfe-commits

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

I think it makes sense but
 - I'd like @mizvekov to get a change to look at it
 - Even if I think the change is fairly low risk, I'm not sure a 
crash-on-invalid is critical enough to backport (we are at ~1 week of the 
release)
 
I added more people for additional feedback

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


[clang] Set dllimport on Objective C ivar offsets (PR #107604)

2024-09-11 Thread Frederik Carlier via cfe-commits

qmfrederik wrote:

@davidchisnall Yes, I don't have merge permissions on this repo; so I'd need 
someone to merge it for me :-)

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


[clang] [llvm] [SPIR-V] Add SPIR-V structurizer (PR #107408)

2024-09-11 Thread Vyacheslav Levytskyy via cfe-commits
Nathan =?utf-8?q?Gau=C3=ABr?= ,
Nathan =?utf-8?q?Gau=C3=ABr?= ,
Nathan =?utf-8?q?Gau=C3=ABr?= ,
Nathan =?utf-8?q?Gau=C3=ABr?= ,
Nathan =?utf-8?q?Gau=C3=ABr?= ,
Nathan =?utf-8?q?Gau=C3=ABr?= ,
Nathan =?utf-8?q?Gau=C3=ABr?= ,
Nathan =?utf-8?q?Gau=C3=ABr?= ,
Nathan =?utf-8?q?Gau=C3=ABr?= ,
Nathan =?utf-8?q?Gau=C3=ABr?= 
Message-ID:
In-Reply-To: 


VyacheslavLevytskyy wrote:

The culprit is `test/CodeGen/SPIRV/structurizer/cf.do.continue.ll`.

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


[clang] Set dllimport on Objective C ivar offsets (PR #107604)

2024-09-11 Thread David Chisnall via cfe-commits

https://github.com/davidchisnall updated 
https://github.com/llvm/llvm-project/pull/107604

>From 5fa137ce295b369b3d652e9538a4f3c13e592ad3 Mon Sep 17 00:00:00 2001
From: Frederik Carlier 
Date: Fri, 6 Sep 2024 11:54:59 +
Subject: [PATCH 1/2] Set dllimport on Objective C ivar offsets

This commit ensures that offsets for instance variables are marked with 
`dllimport` if the interface to which they belong have this attribute.
---
 clang/lib/CodeGen/CGObjCGNU.cpp | 11 +--
 clang/test/CodeGenObjC/dllstorage.m |  4 ++--
 2 files changed, 11 insertions(+), 4 deletions(-)

diff --git a/clang/lib/CodeGen/CGObjCGNU.cpp b/clang/lib/CodeGen/CGObjCGNU.cpp
index adc7cdbfded880..6280e9465ecba6 100644
--- a/clang/lib/CodeGen/CGObjCGNU.cpp
+++ b/clang/lib/CodeGen/CGObjCGNU.cpp
@@ -1699,11 +1699,18 @@ class CGObjCGNUstep2 : public CGObjCGNUstep {
   llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
   const ObjCInterfaceDecl *Interface,
   const ObjCIvarDecl *Ivar) override {
-const std::string Name = 
GetIVarOffsetVariableName(Ivar->getContainingInterface(), Ivar);
+const ObjCInterfaceDecl *ContainingInterface =
+Ivar->getContainingInterface();
+const std::string Name =
+GetIVarOffsetVariableName(ContainingInterface, Ivar);
 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
-if (!IvarOffsetPointer)
+if (!IvarOffsetPointer) {
   IvarOffsetPointer = new llvm::GlobalVariable(TheModule, IntTy, false,
   llvm::GlobalValue::ExternalLinkage, nullptr, Name);
+  if (Ivar->getAccessControl() != ObjCIvarDecl::Private &&
+  Ivar->getAccessControl() != ObjCIvarDecl::Package)
+CGM.setGVProperties(IvarOffsetPointer, ContainingInterface);
+}
 CharUnits Align = CGM.getIntAlign();
 llvm::Value *Offset =
 CGF.Builder.CreateAlignedLoad(IntTy, IvarOffsetPointer, Align);
diff --git a/clang/test/CodeGenObjC/dllstorage.m 
b/clang/test/CodeGenObjC/dllstorage.m
index c94f4c9b5804d0..a6c591b2d79302 100644
--- a/clang/test/CodeGenObjC/dllstorage.m
+++ b/clang/test/CodeGenObjC/dllstorage.m
@@ -112,7 +112,7 @@ @interface M : I {
 // CHECK-IR-DAG: @"OBJC_IVAR_$_M._ivar" = external dllimport global i32
 
 // CHECK-NF-DAG: @"$_OBJC_REF_CLASS_M" = external dllimport global ptr
-// CHECK-NF-DAG: @"__objc_ivar_offset_M._ivar.@" = external global i32
+// CHECK-NF-DAG: @"__objc_ivar_offset_M._ivar.@" = external dllimport global 
i32
 
 __declspec(dllexport)
 __attribute__((__objc_exception__))
@@ -151,7 +151,7 @@ id f(Q *q) {
 
 // CHECK-IR-DAG: @"OBJC_IVAR_$_M._ivar" = external dllimport global i32
 
-// CHECK-NF-DAG: @"__objc_ivar_offset_M._ivar.@" = external global i32
+// CHECK-NF-DAG: @"__objc_ivar_offset_M._ivar.@" = external dllimport global 
i32
 
 int g(void) {
   @autoreleasepool {

>From 93abb9bbc785d9ed6e86c0f1cfb22bc7982da252 Mon Sep 17 00:00:00 2001
From: Frederik Carlier 
Date: Sat, 7 Sep 2024 03:00:46 -0700
Subject: [PATCH 2/2] Add tests to ensure unmarked instance variables are
 considered protected

---
 clang/test/SemaObjC/ivar-access-tests.m | 10 ++
 1 file changed, 10 insertions(+)

diff --git a/clang/test/SemaObjC/ivar-access-tests.m 
b/clang/test/SemaObjC/ivar-access-tests.m
index cd7e09d406adaa..6060dea5ab0f0e 100644
--- a/clang/test/SemaObjC/ivar-access-tests.m
+++ b/clang/test/SemaObjC/ivar-access-tests.m
@@ -2,6 +2,8 @@
 
 @interface MySuperClass
 {
+  int unmarked;
+
 @private
   int private;
 
@@ -17,6 +19,7 @@ @implementation MySuperClass
 - (void) test {
 int access;
 MySuperClass *s = 0;
+access = s->unmarked;
 access = s->private;   
 access = s->protected;
 }
@@ -30,9 +33,11 @@ @implementation MyClass
 - (void) test {
 int access;
 MySuperClass *s = 0;
+access = s->unmarked;
 access = s->private; // expected-error {{instance variable 'private' is 
private}}
 access = s->protected;
 MyClass *m=0;
+access = m->unmarked;
 access = m->private; // expected-error {{instance variable 'private' is 
private}}
 access = m->protected;
 }
@@ -46,9 +51,11 @@ @implementation Deeper
 - (void) test {
 int access;
 MySuperClass *s = 0;
+access = s->unmarked;
 access = s->private; // expected-error {{instance variable 'private' is 
private}}
 access = s->protected;
 MyClass *m=0;
+access = m->unmarked;
 access = m->private; // expected-error {{instance variable 'private' is 
private}}
 access = m->protected;
 }
@@ -61,9 +68,11 @@ @implementation Unrelated
 - (void) test {
 int access;
 MySuperClass *s = 0;
+access = s->unmarked; // expected-error {{instance variable 'unmarked' is 
protected}}
 access = s->private; // expected-error {{instance variable 'private' is 
private}}
 access = s->protected; // expected-error {{instance variable 'protected' 
is protected}}
 MyClass *m=0;
+access = m->unmarked; // expected-error {{instanc

[clang] 7c25ae8 - Set dllimport on Objective C ivar offsets (#107604)

2024-09-11 Thread via cfe-commits

Author: Frederik Carlier
Date: 2024-09-11T12:38:00+01:00
New Revision: 7c25ae87f7378f38aa49a92b9cf8092deb95a1f4

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

LOG: Set dllimport on Objective C ivar offsets (#107604)

Ensures that offsets for instance variables are marked with `dllimport`
if the interface to which they belong has this attribute.

Added: 


Modified: 
clang/lib/CodeGen/CGObjCGNU.cpp
clang/test/CodeGenObjC/dllstorage.m
clang/test/SemaObjC/ivar-access-tests.m

Removed: 




diff  --git a/clang/lib/CodeGen/CGObjCGNU.cpp b/clang/lib/CodeGen/CGObjCGNU.cpp
index adc7cdbfded880..6280e9465ecba6 100644
--- a/clang/lib/CodeGen/CGObjCGNU.cpp
+++ b/clang/lib/CodeGen/CGObjCGNU.cpp
@@ -1699,11 +1699,18 @@ class CGObjCGNUstep2 : public CGObjCGNUstep {
   llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
   const ObjCInterfaceDecl *Interface,
   const ObjCIvarDecl *Ivar) override {
-const std::string Name = 
GetIVarOffsetVariableName(Ivar->getContainingInterface(), Ivar);
+const ObjCInterfaceDecl *ContainingInterface =
+Ivar->getContainingInterface();
+const std::string Name =
+GetIVarOffsetVariableName(ContainingInterface, Ivar);
 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
-if (!IvarOffsetPointer)
+if (!IvarOffsetPointer) {
   IvarOffsetPointer = new llvm::GlobalVariable(TheModule, IntTy, false,
   llvm::GlobalValue::ExternalLinkage, nullptr, Name);
+  if (Ivar->getAccessControl() != ObjCIvarDecl::Private &&
+  Ivar->getAccessControl() != ObjCIvarDecl::Package)
+CGM.setGVProperties(IvarOffsetPointer, ContainingInterface);
+}
 CharUnits Align = CGM.getIntAlign();
 llvm::Value *Offset =
 CGF.Builder.CreateAlignedLoad(IntTy, IvarOffsetPointer, Align);

diff  --git a/clang/test/CodeGenObjC/dllstorage.m 
b/clang/test/CodeGenObjC/dllstorage.m
index c94f4c9b5804d0..a6c591b2d79302 100644
--- a/clang/test/CodeGenObjC/dllstorage.m
+++ b/clang/test/CodeGenObjC/dllstorage.m
@@ -112,7 +112,7 @@ @interface M : I {
 // CHECK-IR-DAG: @"OBJC_IVAR_$_M._ivar" = external dllimport global i32
 
 // CHECK-NF-DAG: @"$_OBJC_REF_CLASS_M" = external dllimport global ptr
-// CHECK-NF-DAG: @"__objc_ivar_offset_M._ivar.@" = external global i32
+// CHECK-NF-DAG: @"__objc_ivar_offset_M._ivar.@" = external dllimport global 
i32
 
 __declspec(dllexport)
 __attribute__((__objc_exception__))
@@ -151,7 +151,7 @@ id f(Q *q) {
 
 // CHECK-IR-DAG: @"OBJC_IVAR_$_M._ivar" = external dllimport global i32
 
-// CHECK-NF-DAG: @"__objc_ivar_offset_M._ivar.@" = external global i32
+// CHECK-NF-DAG: @"__objc_ivar_offset_M._ivar.@" = external dllimport global 
i32
 
 int g(void) {
   @autoreleasepool {

diff  --git a/clang/test/SemaObjC/ivar-access-tests.m 
b/clang/test/SemaObjC/ivar-access-tests.m
index cd7e09d406adaa..6060dea5ab0f0e 100644
--- a/clang/test/SemaObjC/ivar-access-tests.m
+++ b/clang/test/SemaObjC/ivar-access-tests.m
@@ -2,6 +2,8 @@
 
 @interface MySuperClass
 {
+  int unmarked;
+
 @private
   int private;
 
@@ -17,6 +19,7 @@ @implementation MySuperClass
 - (void) test {
 int access;
 MySuperClass *s = 0;
+access = s->unmarked;
 access = s->private;   
 access = s->protected;
 }
@@ -30,9 +33,11 @@ @implementation MyClass
 - (void) test {
 int access;
 MySuperClass *s = 0;
+access = s->unmarked;
 access = s->private; // expected-error {{instance variable 'private' is 
private}}
 access = s->protected;
 MyClass *m=0;
+access = m->unmarked;
 access = m->private; // expected-error {{instance variable 'private' is 
private}}
 access = m->protected;
 }
@@ -46,9 +51,11 @@ @implementation Deeper
 - (void) test {
 int access;
 MySuperClass *s = 0;
+access = s->unmarked;
 access = s->private; // expected-error {{instance variable 'private' is 
private}}
 access = s->protected;
 MyClass *m=0;
+access = m->unmarked;
 access = m->private; // expected-error {{instance variable 'private' is 
private}}
 access = m->protected;
 }
@@ -61,9 +68,11 @@ @implementation Unrelated
 - (void) test {
 int access;
 MySuperClass *s = 0;
+access = s->unmarked; // expected-error {{instance variable 'unmarked' is 
protected}}
 access = s->private; // expected-error {{instance variable 'private' is 
private}}
 access = s->protected; // expected-error {{instance variable 'protected' 
is protected}}
 MyClass *m=0;
+access = m->unmarked; // expected-error {{instance variable 'unmarked' is 
protected}}
 access = m->private; // expected-error {{instance variable 'private' is 
private}}
 access = m->protected; // expected-error {{in

[clang] Set dllimport on Objective C ivar offsets (PR #107604)

2024-09-11 Thread David Chisnall via cfe-commits

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


[clang] [clang][TableGen] Change ASTTableGen to use const Record pointers (PR #108193)

2024-09-11 Thread Rahul Joshi via cfe-commits

https://github.com/jurahul created 
https://github.com/llvm/llvm-project/pull/108193

Change ASTTableGen to use const Record pointers.

>From 2e365455982c5cd7405beace6807c0b72b2e06d3 Mon Sep 17 00:00:00 2001
From: Rahul Joshi 
Date: Wed, 11 Sep 2024 04:38:23 -0700
Subject: [PATCH] [clang][TableGen] Change ASTTableGen to use const Record
 pointers

---
 clang/utils/TableGen/ASTTableGen.cpp | 19 ++
 clang/utils/TableGen/ASTTableGen.h   | 37 ++--
 2 files changed, 27 insertions(+), 29 deletions(-)

diff --git a/clang/utils/TableGen/ASTTableGen.cpp 
b/clang/utils/TableGen/ASTTableGen.cpp
index 54288ff6a03be3..47344777e9311a 100644
--- a/clang/utils/TableGen/ASTTableGen.cpp
+++ b/clang/utils/TableGen/ASTTableGen.cpp
@@ -31,7 +31,8 @@ llvm::StringRef clang::tblgen::HasProperties::getName() const 
{
   }
 }
 
-static StringRef removeExpectedNodeNameSuffix(Record *node, StringRef suffix) {
+static StringRef removeExpectedNodeNameSuffix(const Record *node,
+  StringRef suffix) {
   StringRef nodeName = node->getName();
   if (!nodeName.ends_with(suffix)) {
 PrintFatalError(node->getLoc(),
@@ -105,8 +106,7 @@ static void visitASTNodeRecursive(ASTNode node, ASTNode 
base,
   }
 }
 
-static void visitHierarchy(RecordKeeper &records,
-   StringRef nodeClassName,
+static void visitHierarchy(const RecordKeeper &records, StringRef 
nodeClassName,
ASTNodeHierarchyVisitor visit) {
   // Check for the node class, just as a basic correctness check.
   if (!records.getClass(nodeClassName)) {
@@ -114,13 +114,10 @@ static void visitHierarchy(RecordKeeper &records,
   + nodeClassName);
   }
 
-  // Find all the nodes in the hierarchy.
-  auto nodes = records.getAllDerivedDefinitions(nodeClassName);
-
-  // Derive the child map.
+  // Derive the child map for all nodes in the hierarchy.
   ChildMap hierarchy;
   ASTNode root;
-  for (ASTNode node : nodes) {
+  for (ASTNode node : records.getAllDerivedDefinitions(nodeClassName)) {
 if (auto base = node.getBase())
   hierarchy.insert(std::make_pair(base, node));
 else if (root)
@@ -136,8 +133,8 @@ static void visitHierarchy(RecordKeeper &records,
   visitASTNodeRecursive(root, ASTNode(), hierarchy, visit);
 }
 
-void clang::tblgen::visitASTNodeHierarchyImpl(RecordKeeper &records,
-  StringRef nodeClassName,
-  ASTNodeHierarchyVisitor visit) {
+void clang::tblgen::visitASTNodeHierarchyImpl(
+const RecordKeeper &records, StringRef nodeClassName,
+ASTNodeHierarchyVisitor visit) {
   visitHierarchy(records, nodeClassName, visit);
 }
diff --git a/clang/utils/TableGen/ASTTableGen.h 
b/clang/utils/TableGen/ASTTableGen.h
index 41f78a6a3bbcdd..143d779a8a64f8 100644
--- a/clang/utils/TableGen/ASTTableGen.h
+++ b/clang/utils/TableGen/ASTTableGen.h
@@ -87,18 +87,18 @@ namespace clang {
 namespace tblgen {
 
 class WrappedRecord {
-  llvm::Record *Record;
+  const llvm::Record *Record;
 
 protected:
-  WrappedRecord(llvm::Record *record = nullptr) : Record(record) {}
+  WrappedRecord(const llvm::Record *record = nullptr) : Record(record) {}
 
-  llvm::Record *get() const {
+  const llvm::Record *get() const {
 assert(Record && "accessing null record");
 return Record;
   }
 
 public:
-  llvm::Record *getRecord() const { return Record; }
+  const llvm::Record *getRecord() const { return Record; }
 
   explicit operator bool() const { return Record != nullptr; }
 
@@ -144,7 +144,7 @@ class HasProperties : public WrappedRecord {
 public:
   static constexpr llvm::StringRef ClassName = HasPropertiesClassName;
 
-  HasProperties(llvm::Record *record = nullptr) : WrappedRecord(record) {}
+  HasProperties(const llvm::Record *record = nullptr) : WrappedRecord(record) 
{}
 
   llvm::StringRef getName() const;
 
@@ -157,7 +157,7 @@ class HasProperties : public WrappedRecord {
 /// in one of Clang's AST hierarchies.
 class ASTNode : public HasProperties {
 public:
-  ASTNode(llvm::Record *record = nullptr) : HasProperties(record) {}
+  ASTNode(const llvm::Record *record = nullptr) : HasProperties(record) {}
 
   llvm::StringRef getName() const {
 return get()->getName();
@@ -180,7 +180,7 @@ class ASTNode : public HasProperties {
 
 class DeclNode : public ASTNode {
 public:
-  DeclNode(llvm::Record *record = nullptr) : ASTNode(record) {}
+  DeclNode(const llvm::Record *record = nullptr) : ASTNode(record) {}
 
   llvm::StringRef getId() const;
   std::string getClassName() const;
@@ -202,7 +202,7 @@ class DeclNode : public ASTNode {
 
 class TypeNode : public ASTNode {
 public:
-  TypeNode(llvm::Record *record = nullptr) : ASTNode(record) {}
+  TypeNode(const llvm::Record *record = nullptr) : ASTNode(record) {}
 
   llvm::StringRef getId() const;
   llvm::StringRef getClassName() const;
@@ -224,7 +224,7 @@ class TypeNode : public ASTNode {
 
 

[clang] [clang][TableGen] Change ASTTableGen to use const Record pointers (PR #108193)

2024-09-11 Thread Rahul Joshi via cfe-commits

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


[clang] [clang-format] Fix regressions in BAS_AlwaysBreak (PR #107506)

2024-09-11 Thread via cfe-commits

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


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


[clang] [clang-tools-extra] Fix OOM in FormatDiagnostic (PR #108187)

2024-09-11 Thread Vakhurin Sergei via cfe-commits

https://github.com/igelbox updated 
https://github.com/llvm/llvm-project/pull/108187

>From aee4cf70dedaa3c8b7b6508238e01f92d60c631c Mon Sep 17 00:00:00 2001
From: Sergei 
Date: Tue, 10 Sep 2024 16:19:05 +
Subject: [PATCH] fix quick OOM in FormatDiagnostic

---
 .../ClangTidyDiagnosticConsumer.cpp   |   2 -
 clang/include/clang/Basic/Diagnostic.h| 269 ++
 clang/include/clang/Basic/DiagnosticIDs.h |   7 +-
 clang/include/clang/Basic/PartialDiagnostic.h |   5 +-
 clang/include/clang/Sema/Sema.h   |   6 +-
 clang/lib/Basic/Diagnostic.cpp|  86 +++---
 clang/lib/Basic/DiagnosticIDs.cpp |  22 +-
 clang/lib/Basic/SourceManager.cpp |  23 +-
 clang/lib/Frontend/Rewrite/FixItRewriter.cpp  |   4 +-
 clang/lib/Frontend/TextDiagnosticPrinter.cpp  |   2 +-
 clang/lib/Sema/Sema.cpp   |  19 +-
 clang/lib/Sema/SemaBase.cpp   |   2 +-
 clang/lib/Serialization/ASTReader.cpp |  15 +-
 clang/unittests/Basic/DiagnosticTest.cpp  |   4 -
 clang/unittests/Driver/DXCModeTest.cpp|   5 -
 15 files changed, 174 insertions(+), 297 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp 
b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
index 200bb87a5ac3cb..4c75b422701148 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
@@ -380,7 +380,6 @@ void ClangTidyDiagnosticConsumer::HandleDiagnostic(
 ++Context.Stats.ErrorsIgnoredNOLINT;
 // Ignored a warning, should ignore related notes as well
 LastErrorWasIgnored = true;
-Context.DiagEngine->Clear();
 for (const auto &Error : SuppressionErrors)
   Context.diag(Error);
 return;
@@ -457,7 +456,6 @@ void ClangTidyDiagnosticConsumer::HandleDiagnostic(
   if (Info.hasSourceManager())
 checkFilters(Info.getLocation(), Info.getSourceManager());
 
-  Context.DiagEngine->Clear();
   for (const auto &Error : SuppressionErrors)
 Context.diag(Error);
 }
diff --git a/clang/include/clang/Basic/Diagnostic.h 
b/clang/include/clang/Basic/Diagnostic.h
index 0c7836c2ea569c..1eecab4f6e49a2 100644
--- a/clang/include/clang/Basic/Diagnostic.h
+++ b/clang/include/clang/Basic/Diagnostic.h
@@ -183,6 +183,41 @@ struct DiagnosticStorage {
   DiagnosticStorage() = default;
 };
 
+/// An allocator for DiagnosticStorage objects, which uses a small cache to
+/// objects, used to reduce malloc()/free() traffic for partial diagnostics.
+class DiagStorageAllocator {
+  static const unsigned NumCached = 16;
+  DiagnosticStorage Cached[NumCached];
+  DiagnosticStorage *FreeList[NumCached];
+  unsigned NumFreeListEntries;
+
+public:
+  DiagStorageAllocator();
+  ~DiagStorageAllocator();
+
+  /// Allocate new storage.
+  DiagnosticStorage *Allocate() {
+if (NumFreeListEntries == 0)
+  return new DiagnosticStorage;
+
+DiagnosticStorage *Result = FreeList[--NumFreeListEntries];
+Result->NumDiagArgs = 0;
+Result->DiagRanges.clear();
+Result->FixItHints.clear();
+return Result;
+  }
+
+  /// Free the given storage object.
+  void Deallocate(DiagnosticStorage *S) {
+if (S >= Cached && S <= Cached + NumCached) {
+  FreeList[NumFreeListEntries++] = S;
+  return;
+}
+
+delete S;
+  }
+};
+
 /// Concrete class used by the front-end to report problems and issues.
 ///
 /// This massages the diagnostics (e.g. handling things like "report warnings
@@ -520,27 +555,6 @@ class DiagnosticsEngine : public 
RefCountedBase {
   void *ArgToStringCookie = nullptr;
   ArgToStringFnTy ArgToStringFn;
 
-  /// ID of the "delayed" diagnostic, which is a (typically
-  /// fatal) diagnostic that had to be delayed because it was found
-  /// while emitting another diagnostic.
-  unsigned DelayedDiagID;
-
-  /// First string argument for the delayed diagnostic.
-  std::string DelayedDiagArg1;
-
-  /// Second string argument for the delayed diagnostic.
-  std::string DelayedDiagArg2;
-
-  /// Third string argument for the delayed diagnostic.
-  std::string DelayedDiagArg3;
-
-  /// Optional flag value.
-  ///
-  /// Some flags accept values, for instance: -Wframe-larger-than= and
-  /// -Rpass=. The content of this string is emitted after the flag name
-  /// and '='.
-  std::string FlagValue;
-
 public:
   explicit DiagnosticsEngine(IntrusiveRefCntPtr Diags,
  IntrusiveRefCntPtr DiagOpts,
@@ -945,50 +959,11 @@ class DiagnosticsEngine : public 
RefCountedBase {
 
   void Report(const StoredDiagnostic &storedDiag);
 
-  /// Determine whethere there is already a diagnostic in flight.
-  bool isDiagnosticInFlight() const {
-return CurDiagID != std::numeric_limits::max();
-  }
-
-  /// Set the "delayed" diagnostic that will be emitted once
-  /// the current diagnostic completes.
-  ///
-  ///  If a diagnostic is already in-flight but the front end must
-  ///  report a

[clang] [clang][TableGen] Migrate Builtins emitter to use const RecordKeeper (PR #108195)

2024-09-11 Thread Rahul Joshi via cfe-commits

https://github.com/jurahul created 
https://github.com/llvm/llvm-project/pull/108195

Migrate Builtins emitter to use const RecordKeeper.


>From 903b02c1656c5bacfa0d97da83584876fa1f2999 Mon Sep 17 00:00:00 2001
From: Rahul Joshi 
Date: Wed, 11 Sep 2024 04:51:40 -0700
Subject: [PATCH] [clang][TableGen] Migrate Builtins emitter to use const
 RecordKeeper

---
 clang/utils/TableGen/ClangBuiltinsEmitter.cpp | 2 +-
 clang/utils/TableGen/TableGenBackends.h   | 3 ++-
 2 files changed, 3 insertions(+), 2 deletions(-)

diff --git a/clang/utils/TableGen/ClangBuiltinsEmitter.cpp 
b/clang/utils/TableGen/ClangBuiltinsEmitter.cpp
index 94f12a08164fdc..4ae7600a392b8f 100644
--- a/clang/utils/TableGen/ClangBuiltinsEmitter.cpp
+++ b/clang/utils/TableGen/ClangBuiltinsEmitter.cpp
@@ -345,7 +345,7 @@ void EmitBuiltin(llvm::raw_ostream &OS, const Record 
*Builtin) {
 }
 } // namespace
 
-void clang::EmitClangBuiltins(llvm::RecordKeeper &Records,
+void clang::EmitClangBuiltins(const llvm::RecordKeeper &Records,
   llvm::raw_ostream &OS) {
   emitSourceFileHeader("List of builtins that Clang recognizes", OS);
 
diff --git a/clang/utils/TableGen/TableGenBackends.h 
b/clang/utils/TableGen/TableGenBackends.h
index 3a424c9c91fe71..35cc04d6ef31f4 100644
--- a/clang/utils/TableGen/TableGenBackends.h
+++ b/clang/utils/TableGen/TableGenBackends.h
@@ -73,7 +73,8 @@ void EmitClangAttrNodeTraverse(llvm::RecordKeeper &Records,
llvm::raw_ostream &OS);
 void EmitClangAttrDocTable(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
 
-void EmitClangBuiltins(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
+void EmitClangBuiltins(const llvm::RecordKeeper &Records,
+   llvm::raw_ostream &OS);
 
 void EmitClangDiagsDefs(llvm::RecordKeeper &Records, llvm::raw_ostream &OS,
 const std::string &Component);

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


[clang] [clang] Do not substitute parameter pack while retaining the pack expansion (PR #108197)

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

https://github.com/usx95 created 
https://github.com/llvm/llvm-project/pull/108197

Consider when Input[I] is a VarDecl with parameter pack. We would have already 
expanded the pack before the code change in the loop`for (unsigned I = 0; I != 
*NumExpansions; ++I) {`.

Now in `if (RetainExpansion) {`, without this change, we continue to substitute 
the pack in the pattern even when we do not have meaningful 
`ArgumentPackSubstitutionIndex` set. 

This leads to use of an invalid pack substitution index in 
`TemplateInstantiator::TransformFunctionParmPackRefExpr` containing 
`TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];`

This change set `ArgumentPackSubstitutionIndex` to `-1` while retaining 
expansion to instruct `TransformFunctionParmPackRefExpr` to build 
`FunctionParmPackExpr` instead of substituting the param pack.

---

There are other instances of `RetainExpansion` and IIUC, they should also unset 
the `ArgumentPackSubstitutionIndex`. It would be great if someone can verify my 
understanding. If this is correct then we could instead have a 
`ArgumentPackSubstitutionIndexRAII` as part of 
`ForgetPartiallySubstitutedPackRAII`.


Fixes https://github.com/llvm/llvm-project/issues/63819

>From 5901d82ea0543074853b963f7dc9106a6fe3bcee Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Wed, 11 Sep 2024 11:33:45 +
Subject: [PATCH 1/2] [clang] Do not expand pack while retaining expansion

---
 clang/lib/Sema/TreeTransform.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index 0daf620b4123e4..a40673b04764da 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -4361,7 +4361,7 @@ bool TreeTransform::TransformExprs(Expr *const 
*Inputs,
   // forgetting the partially-substituted parameter pack.
   if (RetainExpansion) {
 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
-
+Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
 ExprResult Out = getDerived().TransformExpr(Pattern);
 if (Out.isInvalid())
   return true;

>From 97fbf34c3edd09348fb48b4dc66f1d854516e8ef Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Wed, 11 Sep 2024 11:59:58 +
Subject: [PATCH 2/2] Add comment

---
 clang/lib/Sema/TreeTransform.h | 1 +
 1 file changed, 1 insertion(+)

diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index a40673b04764da..0de43d2127b12f 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -4361,6 +4361,7 @@ bool TreeTransform::TransformExprs(Expr *const 
*Inputs,
   // forgetting the partially-substituted parameter pack.
   if (RetainExpansion) {
 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
+// Simple transform producing another pack expansion.
 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
 ExprResult Out = getDerived().TransformExpr(Pattern);
 if (Out.isInvalid())

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


[clang] [clang] Do not substitute parameter pack while retaining the pack expansion (PR #108197)

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

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

>From 5901d82ea0543074853b963f7dc9106a6fe3bcee Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Wed, 11 Sep 2024 11:33:45 +
Subject: [PATCH 1/2] [clang] Do not expand pack while retaining expansion

---
 clang/lib/Sema/TreeTransform.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index 0daf620b4123e4..a40673b04764da 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -4361,7 +4361,7 @@ bool TreeTransform::TransformExprs(Expr *const 
*Inputs,
   // forgetting the partially-substituted parameter pack.
   if (RetainExpansion) {
 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
-
+Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
 ExprResult Out = getDerived().TransformExpr(Pattern);
 if (Out.isInvalid())
   return true;

>From 97fbf34c3edd09348fb48b4dc66f1d854516e8ef Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Wed, 11 Sep 2024 11:59:58 +
Subject: [PATCH 2/2] Add comment

---
 clang/lib/Sema/TreeTransform.h | 1 +
 1 file changed, 1 insertion(+)

diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index a40673b04764da..0de43d2127b12f 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -4361,6 +4361,7 @@ bool TreeTransform::TransformExprs(Expr *const 
*Inputs,
   // forgetting the partially-substituted parameter pack.
   if (RetainExpansion) {
 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
+// Simple transform producing another pack expansion.
 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
 ExprResult Out = getDerived().TransformExpr(Pattern);
 if (Out.isInvalid())

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


[clang] [clang] Do not substitute parameter pack while retaining the pack expansion (PR #108197)

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

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


[clang] [clang] Do not substitute parameter pack while retaining the pack expansion (PR #108197)

2024-09-11 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Utkarsh Saxena (usx95)


Changes

Consider when Input[I] is a VarDecl with parameter pack. We would have already 
expanded the pack before the code change in the loop`for (unsigned I = 0; I != 
*NumExpansions; ++I) {`.

Now in `if (RetainExpansion) {`, without this change, we continue to substitute 
the pack in the pattern even when we do not have meaningful 
`ArgumentPackSubstitutionIndex` set. 

This leads to use of an invalid pack substitution index in 
`TemplateInstantiator::TransformFunctionParmPackRefExpr` containing 
`TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];`

This change set `ArgumentPackSubstitutionIndex` to `-1` while retaining 
expansion to instruct `TransformFunctionParmPackRefExpr` to build 
`FunctionParmPackExpr` instead of substituting the param pack.

---

There are other instances of `RetainExpansion` and IIUC, they should also unset 
the `ArgumentPackSubstitutionIndex`. It would be great if someone can verify my 
understanding. If this is correct then we could instead have a 
`ArgumentPackSubstitutionIndexRAII` as part of 
`ForgetPartiallySubstitutedPackRAII`.


Fixes https://github.com/llvm/llvm-project/issues/63819
Fixes https://github.com/llvm/llvm-project/issues/107560

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


1 Files Affected:

- (modified) clang/lib/Sema/TreeTransform.h (+2-1) 


``diff
diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index 0daf620b4123e4..0de43d2127b12f 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -4361,7 +4361,8 @@ bool TreeTransform::TransformExprs(Expr *const 
*Inputs,
   // forgetting the partially-substituted parameter pack.
   if (RetainExpansion) {
 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
-
+// Simple transform producing another pack expansion.
+Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
 ExprResult Out = getDerived().TransformExpr(Pattern);
 if (Out.isInvalid())
   return true;

``




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


[clang] [clang] Do not substitute parameter pack while retaining the pack expansion (PR #108197)

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

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


[clang] [clang][TableGen] Change comment command emitter to const RecordKeeper (PR #108199)

2024-09-11 Thread Rahul Joshi via cfe-commits

https://github.com/jurahul created 
https://github.com/llvm/llvm-project/pull/108199

Change comment command emitter to const RecordKeeper.

>From 5e344e11844fc50ef231c8f8937f5251e76a1150 Mon Sep 17 00:00:00 2001
From: Rahul Joshi 
Date: Wed, 11 Sep 2024 04:59:50 -0700
Subject: [PATCH] [clang][TableGen] Change comment command emitter to const
 RecordKeeper

---
 .../TableGen/ClangCommentCommandInfoEmitter.cpp| 14 +++---
 clang/utils/TableGen/TableGenBackends.h|  4 ++--
 2 files changed, 9 insertions(+), 9 deletions(-)

diff --git a/clang/utils/TableGen/ClangCommentCommandInfoEmitter.cpp 
b/clang/utils/TableGen/ClangCommentCommandInfoEmitter.cpp
index aee7d38786a51c..1a2503dcf660cf 100644
--- a/clang/utils/TableGen/ClangCommentCommandInfoEmitter.cpp
+++ b/clang/utils/TableGen/ClangCommentCommandInfoEmitter.cpp
@@ -20,16 +20,16 @@
 
 using namespace llvm;
 
-void clang::EmitClangCommentCommandInfo(RecordKeeper &Records,
+void clang::EmitClangCommentCommandInfo(const RecordKeeper &Records,
 raw_ostream &OS) {
   emitSourceFileHeader("A list of commands useable in documentation comments",
OS, Records);
 
   OS << "namespace {\n"
 "const CommandInfo Commands[] = {\n";
-  std::vector Tags = Records.getAllDerivedDefinitions("Command");
+  ArrayRef Tags = Records.getAllDerivedDefinitions("Command");
   for (size_t i = 0, e = Tags.size(); i != e; ++i) {
-Record &Tag = *Tags[i];
+const Record &Tag = *Tags[i];
 OS << "  { "
<< "\"" << Tag.getValueAsString("Name") << "\", "
<< "\"" << Tag.getValueAsString("EndCommandName") << "\", " << i << ", "
@@ -62,7 +62,7 @@ void clang::EmitClangCommentCommandInfo(RecordKeeper &Records,
 
   std::vector Matches;
   for (size_t i = 0, e = Tags.size(); i != e; ++i) {
-Record &Tag = *Tags[i];
+const Record &Tag = *Tags[i];
 std::string Name = std::string(Tag.getValueAsString("Name"));
 std::string Return;
 raw_string_ostream(Return) << "return &Commands[" << i << "];";
@@ -112,7 +112,7 @@ static std::string MangleName(StringRef Str) {
   return Mangled;
 }
 
-void clang::EmitClangCommentCommandList(RecordKeeper &Records,
+void clang::EmitClangCommentCommandList(const RecordKeeper &Records,
 raw_ostream &OS) {
   emitSourceFileHeader("A list of commands useable in documentation comments",
OS, Records);
@@ -121,9 +121,9 @@ void clang::EmitClangCommentCommandList(RecordKeeper 
&Records,
  << "#  define COMMENT_COMMAND(NAME)\n"
  << "#endif\n";
 
-  std::vector Tags = Records.getAllDerivedDefinitions("Command");
+  ArrayRef Tags = Records.getAllDerivedDefinitions("Command");
   for (size_t i = 0, e = Tags.size(); i != e; ++i) {
-Record &Tag = *Tags[i];
+const Record &Tag = *Tags[i];
 std::string MangledName = MangleName(Tag.getValueAsString("Name"));
 
 OS << "COMMENT_COMMAND(" << MangledName << ")\n";
diff --git a/clang/utils/TableGen/TableGenBackends.h 
b/clang/utils/TableGen/TableGenBackends.h
index 3a424c9c91fe71..2ead14045329bd 100644
--- a/clang/utils/TableGen/TableGenBackends.h
+++ b/clang/utils/TableGen/TableGenBackends.h
@@ -90,9 +90,9 @@ void EmitClangCommentHTMLTagsProperties(llvm::RecordKeeper 
&Records,
 void EmitClangCommentHTMLNamedCharacterReferences(llvm::RecordKeeper &Records,
   llvm::raw_ostream &OS);
 
-void EmitClangCommentCommandInfo(llvm::RecordKeeper &Records,
+void EmitClangCommentCommandInfo(const llvm::RecordKeeper &Records,
  llvm::raw_ostream &OS);
-void EmitClangCommentCommandList(llvm::RecordKeeper &Records,
+void EmitClangCommentCommandList(const llvm::RecordKeeper &Records,
  llvm::raw_ostream &OS);
 void EmitClangOpcodes(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
 

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


[clang] [clang][TableGen] Change HTML Emitter to use const RecordKeeper (PR #108201)

2024-09-11 Thread Rahul Joshi via cfe-commits

https://github.com/jurahul created 
https://github.com/llvm/llvm-project/pull/108201

None

>From 2e0b2207c6cff650edee1db9da00ef6734366cd2 Mon Sep 17 00:00:00 2001
From: Rahul Joshi 
Date: Wed, 11 Sep 2024 05:05:26 -0700
Subject: [PATCH] [clang][TableGen] Change HTML Emitter to use const
 RecordKeeper

---
 ...CommentHTMLNamedCharacterReferenceEmitter.cpp | 16 ++--
 clang/utils/TableGen/TableGenBackends.h  |  4 ++--
 2 files changed, 8 insertions(+), 12 deletions(-)

diff --git 
a/clang/utils/TableGen/ClangCommentHTMLNamedCharacterReferenceEmitter.cpp 
b/clang/utils/TableGen/ClangCommentHTMLNamedCharacterReferenceEmitter.cpp
index f1cd9af0519d1b..bd75b3f6b652a1 100644
--- a/clang/utils/TableGen/ClangCommentHTMLNamedCharacterReferenceEmitter.cpp
+++ b/clang/utils/TableGen/ClangCommentHTMLNamedCharacterReferenceEmitter.cpp
@@ -46,21 +46,17 @@ static bool translateCodePointToUTF8(unsigned CodePoint,
   return true;
 }
 
-void clang::EmitClangCommentHTMLNamedCharacterReferences(RecordKeeper &Records,
- raw_ostream &OS) {
-  std::vector Tags = Records.getAllDerivedDefinitions("NCR");
+void clang::EmitClangCommentHTMLNamedCharacterReferences(
+const RecordKeeper &Records, raw_ostream &OS) {
   std::vector NameToUTF8;
   SmallString<32> CLiteral;
-  for (std::vector::iterator I = Tags.begin(), E = Tags.end();
-   I != E; ++I) {
-Record &Tag = **I;
-std::string Spelling = std::string(Tag.getValueAsString("Spelling"));
-uint64_t CodePoint = Tag.getValueAsInt("CodePoint");
+  for (const Record *Tag : Records.getAllDerivedDefinitions("NCR")) {
+std::string Spelling = std::string(Tag->getValueAsString("Spelling"));
+uint64_t CodePoint = Tag->getValueAsInt("CodePoint");
 CLiteral.clear();
 CLiteral.append("return ");
 if (!translateCodePointToUTF8(CodePoint, CLiteral)) {
-  SrcMgr.PrintMessage(Tag.getLoc().front(),
-  SourceMgr::DK_Error,
+  SrcMgr.PrintMessage(Tag->getLoc().front(), SourceMgr::DK_Error,
   Twine("invalid code point"));
   continue;
 }
diff --git a/clang/utils/TableGen/TableGenBackends.h 
b/clang/utils/TableGen/TableGenBackends.h
index 3a424c9c91fe71..5dc9fbd3586ec7 100644
--- a/clang/utils/TableGen/TableGenBackends.h
+++ b/clang/utils/TableGen/TableGenBackends.h
@@ -87,8 +87,8 @@ void EmitClangCommentHTMLTags(llvm::RecordKeeper &Records,
   llvm::raw_ostream &OS);
 void EmitClangCommentHTMLTagsProperties(llvm::RecordKeeper &Records,
 llvm::raw_ostream &OS);
-void EmitClangCommentHTMLNamedCharacterReferences(llvm::RecordKeeper &Records,
-  llvm::raw_ostream &OS);
+void EmitClangCommentHTMLNamedCharacterReferences(
+const llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
 
 void EmitClangCommentCommandInfo(llvm::RecordKeeper &Records,
  llvm::raw_ostream &OS);

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


[clang] [clang][TableGen] Change HTML Tags emitter to use const RecordKeeper (PR #108202)

2024-09-11 Thread Rahul Joshi via cfe-commits

https://github.com/jurahul created 
https://github.com/llvm/llvm-project/pull/108202

None

>From fa77d999f72a5faff0cbab7f4609eab7910dc3d8 Mon Sep 17 00:00:00 2001
From: Rahul Joshi 
Date: Wed, 11 Sep 2024 05:09:13 -0700
Subject: [PATCH] [clang][TableGen] Change HTML Tags emitter to use const
 RecordKeeper

---
 .../utils/TableGen/ClangCommentHTMLTagsEmitter.cpp  | 13 +++--
 clang/utils/TableGen/TableGenBackends.h |  4 ++--
 2 files changed, 9 insertions(+), 8 deletions(-)

diff --git a/clang/utils/TableGen/ClangCommentHTMLTagsEmitter.cpp 
b/clang/utils/TableGen/ClangCommentHTMLTagsEmitter.cpp
index 3dc1098753e0bf..a457315bc62c5c 100644
--- a/clang/utils/TableGen/ClangCommentHTMLTagsEmitter.cpp
+++ b/clang/utils/TableGen/ClangCommentHTMLTagsEmitter.cpp
@@ -19,10 +19,11 @@
 
 using namespace llvm;
 
-void clang::EmitClangCommentHTMLTags(RecordKeeper &Records, raw_ostream &OS) {
-  std::vector Tags = Records.getAllDerivedDefinitions("Tag");
+void clang::EmitClangCommentHTMLTags(const RecordKeeper &Records,
+ raw_ostream &OS) {
+  ArrayRef Tags = Records.getAllDerivedDefinitions("Tag");
   std::vector Matches;
-  for (Record *Tag : Tags) {
+  for (const Record *Tag : Tags) {
 Matches.emplace_back(std::string(Tag->getValueAsString("Spelling")),
  "return true;");
   }
@@ -35,12 +36,12 @@ void clang::EmitClangCommentHTMLTags(RecordKeeper &Records, 
raw_ostream &OS) {
  << "}\n\n";
 }
 
-void clang::EmitClangCommentHTMLTagsProperties(RecordKeeper &Records,
+void clang::EmitClangCommentHTMLTagsProperties(const RecordKeeper &Records,
raw_ostream &OS) {
-  std::vector Tags = Records.getAllDerivedDefinitions("Tag");
+  ArrayRef Tags = Records.getAllDerivedDefinitions("Tag");
   std::vector MatchesEndTagOptional;
   std::vector MatchesEndTagForbidden;
-  for (Record *Tag : Tags) {
+  for (const Record *Tag : Tags) {
 std::string Spelling = std::string(Tag->getValueAsString("Spelling"));
 StringMatcher::StringPair Match(Spelling, "return true;");
 if (Tag->getValueAsBit("EndTagOptional"))
diff --git a/clang/utils/TableGen/TableGenBackends.h 
b/clang/utils/TableGen/TableGenBackends.h
index 3a424c9c91fe71..a3e01952f99289 100644
--- a/clang/utils/TableGen/TableGenBackends.h
+++ b/clang/utils/TableGen/TableGenBackends.h
@@ -83,9 +83,9 @@ void EmitClangDiagsIndexName(llvm::RecordKeeper &Records,
 
 void EmitClangSACheckers(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
 
-void EmitClangCommentHTMLTags(llvm::RecordKeeper &Records,
+void EmitClangCommentHTMLTags(const llvm::RecordKeeper &Records,
   llvm::raw_ostream &OS);
-void EmitClangCommentHTMLTagsProperties(llvm::RecordKeeper &Records,
+void EmitClangCommentHTMLTagsProperties(const llvm::RecordKeeper &Records,
 llvm::raw_ostream &OS);
 void EmitClangCommentHTMLNamedCharacterReferences(llvm::RecordKeeper &Records,
   llvm::raw_ostream &OS);

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


[clang] [clang][TableGen] Change DataCollector to use const RecordKeeper (PR #108203)

2024-09-11 Thread Rahul Joshi via cfe-commits

https://github.com/jurahul created 
https://github.com/llvm/llvm-project/pull/108203

None

>From 3f98162db22fffbeb5d4c140e83c502aef049f9c Mon Sep 17 00:00:00 2001
From: Rahul Joshi 
Date: Wed, 11 Sep 2024 05:11:29 -0700
Subject: [PATCH] [clang][TableGen] Change DataCollector to use const
 RecordKeeper

---
 clang/utils/TableGen/ClangDataCollectorsEmitter.cpp | 2 +-
 clang/utils/TableGen/TableGenBackends.h | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/clang/utils/TableGen/ClangDataCollectorsEmitter.cpp 
b/clang/utils/TableGen/ClangDataCollectorsEmitter.cpp
index 45082935c1f794..dae6710d752358 100644
--- a/clang/utils/TableGen/ClangDataCollectorsEmitter.cpp
+++ b/clang/utils/TableGen/ClangDataCollectorsEmitter.cpp
@@ -4,7 +4,7 @@
 
 using namespace llvm;
 
-void clang::EmitClangDataCollectors(RecordKeeper &RK, raw_ostream &OS) {
+void clang::EmitClangDataCollectors(const RecordKeeper &RK, raw_ostream &OS) {
   const auto &Defs = RK.getClasses();
   for (const auto &Entry : Defs) {
 Record &R = *Entry.second;
diff --git a/clang/utils/TableGen/TableGenBackends.h 
b/clang/utils/TableGen/TableGenBackends.h
index 3a424c9c91fe71..6e5508c6f68a5c 100644
--- a/clang/utils/TableGen/TableGenBackends.h
+++ b/clang/utils/TableGen/TableGenBackends.h
@@ -151,7 +151,7 @@ void EmitClangOpenCLBuiltinHeader(llvm::RecordKeeper 
&Records,
 void EmitClangOpenCLBuiltinTests(llvm::RecordKeeper &Records,
  llvm::raw_ostream &OS);
 
-void EmitClangDataCollectors(llvm::RecordKeeper &Records,
+void EmitClangDataCollectors(const llvm::RecordKeeper &Records,
  llvm::raw_ostream &OS);
 
 void EmitTestPragmaAttributeSupportedAttributes(llvm::RecordKeeper &Records,

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


[clang] [clang] Detect dangling assignment for "Container" case. (PR #108205)

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

https://github.com/hokein created 
https://github.com/llvm/llvm-project/pull/108205

This is a follow up of https://github.com/llvm/llvm-project/pull/107213, 
supporting the assignment case.

With this patch, clang now diagnoses cases where a dangling 
`container` is assigned, e.g.

```
void test() {
   std::vector v;
   v = {std::string()}; // dangling
}
```

Fixes #100526

>From 041b36967842cf4cb8942e4cbfe729d8987f1a0c Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Wed, 11 Sep 2024 13:27:28 +0200
Subject: [PATCH] [clang] Detect dangling assignment for "Container"
 case.

---
 clang/docs/ReleaseNotes.rst  |  2 ++
 clang/lib/Sema/CheckExprLifetime.cpp |  3 ++-
 clang/test/Sema/warn-lifetime-analysis-nocfg.cpp | 10 --
 3 files changed, 12 insertions(+), 3 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 59ccdf1e15cd81..43f0d6eb4f2edc 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -300,6 +300,8 @@ Improvements to Clang's diagnostics
 
 - Clang now diagnoses cases where a dangling ``GSLOwner`` object 
is constructed, e.g. ``std::vector v = {std::string()};`` 
(#GH100526).
 
+- Clang now diagnoses cases where a dangling ``GSLOwner`` object 
is assigned, e.g. ``v = {std::string()};`` (#GH100526).
+
 Improvements to Clang's time-trace
 --
 
diff --git a/clang/lib/Sema/CheckExprLifetime.cpp 
b/clang/lib/Sema/CheckExprLifetime.cpp
index c8e703036c132c..6fc1d4d0aae259 100644
--- a/clang/lib/Sema/CheckExprLifetime.cpp
+++ b/clang/lib/Sema/CheckExprLifetime.cpp
@@ -982,7 +982,8 @@ static bool shouldRunGSLAssignmentAnalysis(const Sema 
&SemaRef,
   diag::warn_dangling_lifetime_pointer_assignment, SourceLocation());
   return (EnableGSLAssignmentWarnings &&
   (isRecordWithAttr(Entity.LHS->getType()) ||
-   isAssignmentOperatorLifetimeBound(Entity.AssignmentOperator)));
+   isAssignmentOperatorLifetimeBound(Entity.AssignmentOperator) ||
+   isContainerOfPointer(Entity.LHS->getType()->getAsRecordDecl(;
 }
 
 static void checkExprLifetimeImpl(Sema &SemaRef,
diff --git a/clang/test/Sema/warn-lifetime-analysis-nocfg.cpp 
b/clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
index 234e06f069074b..d744140800f595 100644
--- a/clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
+++ b/clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
@@ -601,17 +601,23 @@ void test() {
   std::optional o4 = std::optional(s); 
 
   // FIXME: should work for assignment cases
-  v1 = {std::string()};
-  o1 = std::string();
+  v1 = {std::string()}; // expected-warning {{object backing the pointer}}
+  o1 = std::string(); // expected-warning {{object backing the pointer}}
 
   // no warning on copying pointers.
   std::vector n1 = {std::string_view()};
+  n1 = {std::string_view()};
   std::optional n2 = {std::string_view()};
+  n2 = {std::string_view()};
   std::optional n3 = std::string_view();
+  n3 = std::string_view();
   std::optional n4 = std::make_optional(std::string_view());
+  n4 = std::make_optional(std::string_view());
   const char* b = "";
   std::optional n5 = std::make_optional(b);
+  n5 = std::make_optional(b);
   std::optional n6 = std::make_optional("test");
+  n6 = std::make_optional("test");
 }
 
 std::vector test2(int i) {

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


[clang] [clang][bytecode] Check for Pointer dereference in EvaluationResult (PR #108207)

2024-09-11 Thread Timm Baeder via cfe-commits

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

We will deref<>() it later, so this is the right check.

>From 7f27917b46e254bacc7214ef40d6a61f0db0e92f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Wed, 11 Sep 2024 14:16:58 +0200
Subject: [PATCH] [clang][bytecode] Check for Pointer dereference in
 EvaluationResult

We will deref<>() it later, so this is the right check.
---
 clang/lib/AST/ByteCode/EvaluationResult.cpp  |  4 ++--
 clang/test/AST/ByteCode/initializer_list.cpp | 20 ++--
 2 files changed, 20 insertions(+), 4 deletions(-)

diff --git a/clang/lib/AST/ByteCode/EvaluationResult.cpp 
b/clang/lib/AST/ByteCode/EvaluationResult.cpp
index bdebd19af9f940..627d4b2f65be9d 100644
--- a/clang/lib/AST/ByteCode/EvaluationResult.cpp
+++ b/clang/lib/AST/ByteCode/EvaluationResult.cpp
@@ -178,8 +178,8 @@ bool EvaluationResult::checkFullyInitialized(InterpState &S,
 static void collectBlocks(const Pointer &Ptr,
   llvm::SetVector &Blocks) {
   auto isUsefulPtr = [](const Pointer &P) -> bool {
-return P.isLive() && !P.isZero() && !P.isDummy() &&
-   !P.isUnknownSizeArray() && !P.isOnePastEnd() && P.isBlockPointer();
+return P.isLive() && !P.isZero() && !P.isDummy() && P.isDereferencable() &&
+   !P.isUnknownSizeArray() && !P.isOnePastEnd();
   };
 
   if (!isUsefulPtr(Ptr))
diff --git a/clang/test/AST/ByteCode/initializer_list.cpp 
b/clang/test/AST/ByteCode/initializer_list.cpp
index 4e3b8dc9120167..f882e4ff1b1247 100644
--- a/clang/test/AST/ByteCode/initializer_list.cpp
+++ b/clang/test/AST/ByteCode/initializer_list.cpp
@@ -1,8 +1,6 @@
 // RUN: %clang_cc1 -fexperimental-new-constant-interpreter -fms-extensions 
-std=c++20 -verify=expected,both %s
 // RUN: %clang_cc1 -std=c++20 -fms-extensions -verify=ref,both %s
 
-// both-no-diagnostics
-
 namespace std {
   typedef decltype(sizeof(int)) size_t;
   template 
@@ -53,3 +51,21 @@ constexpr int foo() {
 }
 
 static_assert(foo() == 0);
+
+
+namespace rdar13395022 {
+  struct MoveOnly { // both-note {{candidate}}
+MoveOnly(MoveOnly&&); // both-note 2{{copy constructor is implicitly 
deleted because}} both-note {{candidate}}
+  };
+
+  void test(MoveOnly mo) {
+auto &&list1 = {mo}; // both-error {{call to implicitly-deleted copy 
constructor}} both-note {{in initialization of temporary of type 
'std::initializer_list}}
+MoveOnly (&&list2)[1] = {mo}; // both-error {{call to implicitly-deleted 
copy constructor}} both-note {{in initialization of temporary of type 
'MoveOnly[1]'}}
+std::initializer_list &&list3 = {};
+MoveOnly (&&list4)[1] = {}; // both-error {{no matching constructor}}
+// both-note@-1 {{in implicit initialization of array element 0 with 
omitted initializer}}
+// both-note@-2 {{in initialization of temporary of type 'MoveOnly[1]' 
created to list-initialize this reference}}
+  }
+}
+
+

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


[clang] [clang][bytecode] Check for Pointer dereference in EvaluationResult (PR #108207)

2024-09-11 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Timm Baeder (tbaederr)


Changes

We will deref<>() it later, so this is the right check.

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


2 Files Affected:

- (modified) clang/lib/AST/ByteCode/EvaluationResult.cpp (+2-2) 
- (modified) clang/test/AST/ByteCode/initializer_list.cpp (+18-2) 


``diff
diff --git a/clang/lib/AST/ByteCode/EvaluationResult.cpp 
b/clang/lib/AST/ByteCode/EvaluationResult.cpp
index bdebd19af9f940..627d4b2f65be9d 100644
--- a/clang/lib/AST/ByteCode/EvaluationResult.cpp
+++ b/clang/lib/AST/ByteCode/EvaluationResult.cpp
@@ -178,8 +178,8 @@ bool EvaluationResult::checkFullyInitialized(InterpState &S,
 static void collectBlocks(const Pointer &Ptr,
   llvm::SetVector &Blocks) {
   auto isUsefulPtr = [](const Pointer &P) -> bool {
-return P.isLive() && !P.isZero() && !P.isDummy() &&
-   !P.isUnknownSizeArray() && !P.isOnePastEnd() && P.isBlockPointer();
+return P.isLive() && !P.isZero() && !P.isDummy() && P.isDereferencable() &&
+   !P.isUnknownSizeArray() && !P.isOnePastEnd();
   };
 
   if (!isUsefulPtr(Ptr))
diff --git a/clang/test/AST/ByteCode/initializer_list.cpp 
b/clang/test/AST/ByteCode/initializer_list.cpp
index 4e3b8dc9120167..f882e4ff1b1247 100644
--- a/clang/test/AST/ByteCode/initializer_list.cpp
+++ b/clang/test/AST/ByteCode/initializer_list.cpp
@@ -1,8 +1,6 @@
 // RUN: %clang_cc1 -fexperimental-new-constant-interpreter -fms-extensions 
-std=c++20 -verify=expected,both %s
 // RUN: %clang_cc1 -std=c++20 -fms-extensions -verify=ref,both %s
 
-// both-no-diagnostics
-
 namespace std {
   typedef decltype(sizeof(int)) size_t;
   template 
@@ -53,3 +51,21 @@ constexpr int foo() {
 }
 
 static_assert(foo() == 0);
+
+
+namespace rdar13395022 {
+  struct MoveOnly { // both-note {{candidate}}
+MoveOnly(MoveOnly&&); // both-note 2{{copy constructor is implicitly 
deleted because}} both-note {{candidate}}
+  };
+
+  void test(MoveOnly mo) {
+auto &&list1 = {mo}; // both-error {{call to implicitly-deleted copy 
constructor}} both-note {{in initialization of temporary of type 
'std::initializer_list}}
+MoveOnly (&&list2)[1] = {mo}; // both-error {{call to implicitly-deleted 
copy constructor}} both-note {{in initialization of temporary of type 
'MoveOnly[1]'}}
+std::initializer_list &&list3 = {};
+MoveOnly (&&list4)[1] = {}; // both-error {{no matching constructor}}
+// both-note@-1 {{in implicit initialization of array element 0 with 
omitted initializer}}
+// both-note@-2 {{in initialization of temporary of type 'MoveOnly[1]' 
created to list-initialize this reference}}
+  }
+}
+
+

``




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


[clang] [clang] Detect dangling assignment for "Container" case. (PR #108205)

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


@@ -601,17 +601,23 @@ void test() {
   std::optional o4 = std::optional(s); 
 
   // FIXME: should work for assignment cases

usx95 wrote:

nit: remove fixme.

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


[clang] [clang] Detect dangling assignment for "Container" case. (PR #108205)

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

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


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


[clang] [clang] Detect dangling assignment for "Container" case. (PR #108205)

2024-09-11 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Haojian Wu (hokein)


Changes

This is a follow up of https://github.com/llvm/llvm-project/pull/107213, 
supporting the assignment case.

With this patch, clang now diagnoses cases where a dangling 
`container` is assigned, e.g.

```
void test() {
   std::vector v;
   v = {std::string()}; // dangling
}
```

Fixes #100526

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


3 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+2) 
- (modified) clang/lib/Sema/CheckExprLifetime.cpp (+2-1) 
- (modified) clang/test/Sema/warn-lifetime-analysis-nocfg.cpp (+8-2) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 59ccdf1e15cd81..43f0d6eb4f2edc 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -300,6 +300,8 @@ Improvements to Clang's diagnostics
 
 - Clang now diagnoses cases where a dangling ``GSLOwner`` object 
is constructed, e.g. ``std::vector v = {std::string()};`` 
(#GH100526).
 
+- Clang now diagnoses cases where a dangling ``GSLOwner`` object 
is assigned, e.g. ``v = {std::string()};`` (#GH100526).
+
 Improvements to Clang's time-trace
 --
 
diff --git a/clang/lib/Sema/CheckExprLifetime.cpp 
b/clang/lib/Sema/CheckExprLifetime.cpp
index c8e703036c132c..6fc1d4d0aae259 100644
--- a/clang/lib/Sema/CheckExprLifetime.cpp
+++ b/clang/lib/Sema/CheckExprLifetime.cpp
@@ -982,7 +982,8 @@ static bool shouldRunGSLAssignmentAnalysis(const Sema 
&SemaRef,
   diag::warn_dangling_lifetime_pointer_assignment, SourceLocation());
   return (EnableGSLAssignmentWarnings &&
   (isRecordWithAttr(Entity.LHS->getType()) ||
-   isAssignmentOperatorLifetimeBound(Entity.AssignmentOperator)));
+   isAssignmentOperatorLifetimeBound(Entity.AssignmentOperator) ||
+   isContainerOfPointer(Entity.LHS->getType()->getAsRecordDecl(;
 }
 
 static void checkExprLifetimeImpl(Sema &SemaRef,
diff --git a/clang/test/Sema/warn-lifetime-analysis-nocfg.cpp 
b/clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
index 234e06f069074b..d744140800f595 100644
--- a/clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
+++ b/clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
@@ -601,17 +601,23 @@ void test() {
   std::optional o4 = std::optional(s); 
 
   // FIXME: should work for assignment cases
-  v1 = {std::string()};
-  o1 = std::string();
+  v1 = {std::string()}; // expected-warning {{object backing the pointer}}
+  o1 = std::string(); // expected-warning {{object backing the pointer}}
 
   // no warning on copying pointers.
   std::vector n1 = {std::string_view()};
+  n1 = {std::string_view()};
   std::optional n2 = {std::string_view()};
+  n2 = {std::string_view()};
   std::optional n3 = std::string_view();
+  n3 = std::string_view();
   std::optional n4 = std::make_optional(std::string_view());
+  n4 = std::make_optional(std::string_view());
   const char* b = "";
   std::optional n5 = std::make_optional(b);
+  n5 = std::make_optional(b);
   std::optional n6 = std::make_optional("test");
+  n6 = std::make_optional("test");
 }
 
 std::vector test2(int i) {

``




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


[clang] [clangl[TableGen] Change Diagnostic Emitter to use const RecordKeeper (PR #108209)

2024-09-11 Thread Rahul Joshi via cfe-commits

https://github.com/jurahul created 
https://github.com/llvm/llvm-project/pull/108209

None

>From 34a33e2b31ef10ecad91197dcae67164f5163ace Mon Sep 17 00:00:00 2001
From: Rahul Joshi 
Date: Wed, 11 Sep 2024 05:28:22 -0700
Subject: [PATCH] [clangl[TableGen] Change Diagnostic Emitter to use const
 RecordKeeper

---
 .../TableGen/ClangDiagnosticsEmitter.cpp  | 98 ++-
 clang/utils/TableGen/TableGenBackends.h   | 12 ++-
 2 files changed, 59 insertions(+), 51 deletions(-)

diff --git a/clang/utils/TableGen/ClangDiagnosticsEmitter.cpp 
b/clang/utils/TableGen/ClangDiagnosticsEmitter.cpp
index 6ca24a8c74b2ff..773668caa75747 100644
--- a/clang/utils/TableGen/ClangDiagnosticsEmitter.cpp
+++ b/clang/utils/TableGen/ClangDiagnosticsEmitter.cpp
@@ -39,12 +39,13 @@ using namespace llvm;
 
 namespace {
 class DiagGroupParentMap {
-  RecordKeeper &Records;
-  std::map > Mapping;
+  const RecordKeeper &Records;
+  std::map> Mapping;
+
 public:
-  DiagGroupParentMap(RecordKeeper &records) : Records(records) {
-std::vector DiagGroups
-  = Records.getAllDerivedDefinitions("DiagGroup");
+  DiagGroupParentMap(const RecordKeeper &records) : Records(records) {
+ArrayRef DiagGroups =
+Records.getAllDerivedDefinitions("DiagGroup");
 for (unsigned i = 0, e = DiagGroups.size(); i != e; ++i) {
   std::vector SubGroups =
 DiagGroups[i]->getValueAsListOfDefs("SubGroups");
@@ -53,7 +54,7 @@ class DiagGroupParentMap {
 }
   }
 
-  const std::vector &getParents(const Record *Group) {
+  const std::vector &getParents(const Record *Group) {
 return Mapping[Group];
   }
 };
@@ -68,7 +69,8 @@ getCategoryFromDiagGroup(const Record *Group,
 
   // The diag group may the subgroup of one or more other diagnostic groups,
   // check these for a category as well.
-  const std::vector &Parents = DiagGroupParents.getParents(Group);
+  const std::vector &Parents =
+  DiagGroupParents.getParents(Group);
   for (unsigned i = 0, e = Parents.size(); i != e; ++i) {
 CatName = getCategoryFromDiagGroup(Parents[i], DiagGroupParents);
 if (!CatName.empty()) return CatName;
@@ -94,19 +96,19 @@ static std::string getDiagnosticCategory(const Record *R,
 
 namespace {
   class DiagCategoryIDMap {
-RecordKeeper &Records;
+const RecordKeeper &Records;
 StringMap CategoryIDs;
 std::vector CategoryStrings;
   public:
-DiagCategoryIDMap(RecordKeeper &records) : Records(records) {
+DiagCategoryIDMap(const RecordKeeper &records) : Records(records) {
   DiagGroupParentMap ParentInfo(Records);
 
   // The zero'th category is "".
   CategoryStrings.push_back("");
   CategoryIDs[""] = 0;
 
-  std::vector Diags =
-  Records.getAllDerivedDefinitions("Diagnostic");
+  ArrayRef Diags =
+  Records.getAllDerivedDefinitions("Diagnostic");
   for (unsigned i = 0, e = Diags.size(); i != e; ++i) {
 std::string Category = getDiagnosticCategory(Diags[i], ParentInfo);
 if (Category.empty()) continue;  // Skip diags with no category.
@@ -153,8 +155,8 @@ static bool diagGroupBeforeByName(const Record *LHS, const 
Record *RHS) {
 
 /// Invert the 1-[0/1] mapping of diags to group into a one to many
 /// mapping of groups to diags in the group.
-static void groupDiagnostics(const std::vector &Diags,
- const std::vector &DiagGroups,
+static void groupDiagnostics(ArrayRef Diags,
+ ArrayRef DiagGroups,
  std::map &DiagsInGroup) {
 
   for (unsigned i = 0, e = Diags.size(); i != e; ++i) {
@@ -172,7 +174,7 @@ static void groupDiagnostics(const std::vector 
&Diags,
   // Add all DiagGroup's to the DiagsInGroup list to make sure we pick up empty
   // groups (these are warnings that GCC supports that clang never produces).
   for (unsigned i = 0, e = DiagGroups.size(); i != e; ++i) {
-Record *Group = DiagGroups[i];
+const Record *Group = DiagGroups[i];
 GroupInfo &GI =
 DiagsInGroup[std::string(Group->getValueAsString("GroupName"))];
 GI.GroupName = Group->getName();
@@ -255,20 +257,18 @@ class InferPedantic {
   GMap;
 
   DiagGroupParentMap &DiagGroupParents;
-  const std::vector &Diags;
-  const std::vector DiagGroups;
+  ArrayRef Diags;
+  const std::vector DiagGroups;
   std::map &DiagsInGroup;
   llvm::DenseSet DiagsSet;
   GMap GroupCount;
 public:
   InferPedantic(DiagGroupParentMap &DiagGroupParents,
-const std::vector &Diags,
-const std::vector &DiagGroups,
+ArrayRef Diags,
+ArrayRef DiagGroups,
 std::map &DiagsInGroup)
-  : DiagGroupParents(DiagGroupParents),
-  Diags(Diags),
-  DiagGroups(DiagGroups),
-  DiagsInGroup(DiagsInGroup) {}
+  : DiagGroupParents(DiagGroupParents), Diags(Diags),
+DiagGroups(DiagGroups), DiagsInGroup(DiagsInGroup) {}
 
   /// Compute the set of diagnostics and groups that are immediately
   /// in -Wpedantic

[clang-tools-extra] [Docs][clang-query] disclose Windows linetab bug on clang-query tab auto-complete (PR #107956)

2024-09-11 Thread Aaron Ballman via cfe-commits

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

LGTM!

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


[clang] Don't emit int TBAA metadata on more complex FP math libcalls. (PR #107598)

2024-09-11 Thread Matt Arsenault via cfe-commits


@@ -699,9 +699,20 @@ static RValue emitLibraryCall(CodeGenFunction &CGF, const 
FunctionDecl *FD,
 bool ConstWithoutErrnoAndExceptions =
 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID);
 // Restrict to target with errno, for example, MacOS doesn't set errno.
-// TODO: Support builtin function with complex type returned, eg: cacosh
+bool CallWithPointerArgsOrPointerReturnType = false;
+if (Call.isScalar() && Call.getScalarVal()) {
+  if (CallBase *CB = dyn_cast(Call.getScalarVal())) {
+for (Value *A : CB->args())
+  if (A->getType()->isPointerTy())
+CallWithPointerArgsOrPointerReturnType = true;

arsenm wrote:

Should probably be looking at the source signature, not the IR? 

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


[clang] Don't emit int TBAA metadata on more complex FP math libcalls. (PR #107598)

2024-09-11 Thread Matt Arsenault via cfe-commits


@@ -699,9 +699,20 @@ static RValue emitLibraryCall(CodeGenFunction &CGF, const 
FunctionDecl *FD,
 bool ConstWithoutErrnoAndExceptions =
 Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID);
 // Restrict to target with errno, for example, MacOS doesn't set errno.
-// TODO: Support builtin function with complex type returned, eg: cacosh
+bool CallWithPointerArgsOrPointerReturnType = false;
+if (Call.isScalar() && Call.getScalarVal()) {
+  if (CallBase *CB = dyn_cast(Call.getScalarVal())) {
+for (Value *A : CB->args())
+  if (A->getType()->isPointerTy())
+CallWithPointerArgsOrPointerReturnType = true;
+CallWithPointerArgsOrPointerReturnType =
+CallWithPointerArgsOrPointerReturnType ||
+CB->getFunctionType()->getReturnType()->isPointerTy();
+  }
+}

arsenm wrote:

Turn this into a predicate function 

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


[clang-tools-extra] 80fcab8 - [Docs][clang-query] disclose Windows linetab bug on clang-query tab auto-complete (#107956)

2024-09-11 Thread via cfe-commits

Author: MichelleCDjunaidi
Date: 2024-09-11T08:32:01-04:00
New Revision: 80fcab8c26129a98f01ce4f8d9cc90f3653bf693

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

LOG: [Docs][clang-query] disclose Windows linetab bug on clang-query tab 
auto-complete (#107956)

As per
https://github.com/llvm/llvm-project/pull/106672/#issuecomment-2325577815
and https://github.com/llvm/llvm-project/issues/107377, the
documentation should be updated to note that the current bug on Windows
involving ``LineEditor`` causing Tab key related features to not work.

Fixes #107377

Added: 


Modified: 
clang-tools-extra/docs/clang-tidy/Contributing.rst

Removed: 




diff  --git a/clang-tools-extra/docs/clang-tidy/Contributing.rst 
b/clang-tools-extra/docs/clang-tidy/Contributing.rst
index d5303418b859b2..ff8b05ff263c14 100644
--- a/clang-tools-extra/docs/clang-tidy/Contributing.rst
+++ b/clang-tools-extra/docs/clang-tidy/Contributing.rst
@@ -344,18 +344,20 @@ matching expressions to simplify your matcher.
   clang-query> let c1 cxxRecordDecl()
   clang-query> match c1
 
-Alternatively, pressing the tab key after a previous matcher's open 
parentheses would also 
-show which matchers can be chained with the previous matcher, though some 
matchers that work 
-may not be listed.
-
-Just like breaking up a huge function into smaller chunks with 
intention-revealing names 
-can help you understand a complex algorithm, breaking up a matcher into 
smaller matchers 
-with intention-revealing names can help you understand a complicated matcher.  
-
-Once you have a working clang-query matcher, the C++ API matchers will be the 
same or similar 
-to your interactively constructed matcher (there can be cases where they 
diff er slightly). 
-You can use local variables to preserve your intention-revealing names that 
you applied 
-to nested matchers.
+Alternatively, pressing the tab key after a previous matcher's open 
parentheses 
+would also show which matchers can be chained with the previous matcher, 
+though some matchers that work may not be listed. Note that tab completion 
+does not currently work on Windows.
+
+Just like breaking up a huge function into smaller chunks with 
+intention-revealing names can help you understand a complex algorithm, 
breaking 
+up a matcher into smaller matchers with intention-revealing names can help 
+you understand a complicated matcher.  
+
+Once you have a working :program:`clang-query` matcher, the C++ API matchers 
+will be the same or similar to your interactively constructed matcher (there 
+can be cases where they 
diff er slightly). You can use local variables to preserve 
+your intention-revealing names that you applied to nested matchers.
 
 Creating private matchers
 ^



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


[clang-tools-extra] [Docs][clang-query] disclose Windows linetab bug on clang-query tab auto-complete (PR #107956)

2024-09-11 Thread Aaron Ballman via cfe-commits

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


[clang-tools-extra] [Docs][clang-query] disclose Windows linetab bug on clang-query tab auto-complete (PR #107956)

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

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder `clangd-ubuntu-tsan` 
running on `clangd-ubuntu-clang` while building `clang-tools-extra` at step 2 
"checkout".

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


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

```
Step 2 (checkout) failure: update (failure)
git version 2.17.1
fatal: unable to access 'https://github.com/llvm/llvm-project.git/': Could not 
resolve host: github.com
fatal: unable to access 'https://github.com/llvm/llvm-project.git/': Could not 
resolve host: github.com

```



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


[clang] [clang][TableGen] Change Opcode Emitter to use const RecordKeeper (PR #108211)

2024-09-11 Thread Rahul Joshi via cfe-commits

https://github.com/jurahul created 
https://github.com/llvm/llvm-project/pull/108211

None

>From 49650f70c36c37747da6d73865ebcb7b7a94da2f Mon Sep 17 00:00:00 2001
From: Rahul Joshi 
Date: Wed, 11 Sep 2024 05:33:50 -0700
Subject: [PATCH] [clang][TableGen] Change Opcode Emitter to use const
 RecordKeeper

---
 clang/utils/TableGen/ClangOpcodesEmitter.cpp | 6 +++---
 clang/utils/TableGen/TableGenBackends.h  | 2 +-
 2 files changed, 4 insertions(+), 4 deletions(-)

diff --git a/clang/utils/TableGen/ClangOpcodesEmitter.cpp 
b/clang/utils/TableGen/ClangOpcodesEmitter.cpp
index 120e1e2efa32b4..7e426d59359a87 100644
--- a/clang/utils/TableGen/ClangOpcodesEmitter.cpp
+++ b/clang/utils/TableGen/ClangOpcodesEmitter.cpp
@@ -20,11 +20,11 @@ using namespace llvm;
 
 namespace {
 class ClangOpcodesEmitter {
-  RecordKeeper &Records;
+  const RecordKeeper &Records;
   unsigned NumTypes;
 
 public:
-  ClangOpcodesEmitter(RecordKeeper &R)
+  ClangOpcodesEmitter(const RecordKeeper &R)
   : Records(R), NumTypes(Records.getAllDerivedDefinitions("Type").size()) 
{}
 
   void run(raw_ostream &OS);
@@ -404,6 +404,6 @@ void ClangOpcodesEmitter::PrintTypes(raw_ostream &OS,
   OS << ">";
 }
 
-void clang::EmitClangOpcodes(RecordKeeper &Records, raw_ostream &OS) {
+void clang::EmitClangOpcodes(const RecordKeeper &Records, raw_ostream &OS) {
   ClangOpcodesEmitter(Records).run(OS);
 }
diff --git a/clang/utils/TableGen/TableGenBackends.h 
b/clang/utils/TableGen/TableGenBackends.h
index 3a424c9c91fe71..5050b764b09fb8 100644
--- a/clang/utils/TableGen/TableGenBackends.h
+++ b/clang/utils/TableGen/TableGenBackends.h
@@ -94,7 +94,7 @@ void EmitClangCommentCommandInfo(llvm::RecordKeeper &Records,
  llvm::raw_ostream &OS);
 void EmitClangCommentCommandList(llvm::RecordKeeper &Records,
  llvm::raw_ostream &OS);
-void EmitClangOpcodes(llvm::RecordKeeper &Records, llvm::raw_ostream &OS);
+void EmitClangOpcodes(const llvm::RecordKeeper &Records, llvm::raw_ostream 
&OS);
 
 void EmitClangSyntaxNodeList(llvm::RecordKeeper &Records,
  llvm::raw_ostream &OS);

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


[clang] [clang][TableGen] Change OpenCL emitter to use const RecordKeeper (PR #108213)

2024-09-11 Thread Rahul Joshi via cfe-commits

https://github.com/jurahul created 
https://github.com/llvm/llvm-project/pull/108213

None

>From b70f6ccab04237caf4e956deee4893dc13557088 Mon Sep 17 00:00:00 2001
From: Rahul Joshi 
Date: Wed, 11 Sep 2024 05:40:16 -0700
Subject: [PATCH] [clang][TableGen] Change OpenCL emitter to use const
 RecordKeeper

---
 .../TableGen/ClangOpenCLBuiltinEmitter.cpp| 46 ++-
 clang/utils/TableGen/TableGenBackends.h   |  6 +--
 2 files changed, 28 insertions(+), 24 deletions(-)

diff --git a/clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp 
b/clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp
index 74c3a856ab6937..d68dcc472a7bdb 100644
--- a/clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp
+++ b/clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp
@@ -87,7 +87,7 @@ struct BuiltinTableEntries {
 //
 class BuiltinNameEmitter {
 public:
-  BuiltinNameEmitter(RecordKeeper &Records, raw_ostream &OS)
+  BuiltinNameEmitter(const RecordKeeper &Records, raw_ostream &OS)
   : Records(Records), OS(OS) {}
 
   // Entrypoint to generate the functions and structures for checking
@@ -100,7 +100,7 @@ class BuiltinNameEmitter {
 
   // Contains OpenCL builtin functions and related information, stored as
   // Record instances. They are coming from the associated TableGen file.
-  RecordKeeper &Records;
+  const RecordKeeper &Records;
 
   // The output file.
   raw_ostream &OS;
@@ -113,7 +113,7 @@ class BuiltinNameEmitter {
   // \param Output (out) String containing the enums to emit in the output 
file.
   // \param List (out) List containing the extracted Types, except the Types in
   //TypesSeen.
-  void ExtractEnumTypes(std::vector &Types,
+  void ExtractEnumTypes(ArrayRef Types,
 StringMap &TypesSeen, std::string &Output,
 std::vector &List);
 
@@ -237,7 +237,7 @@ class BuiltinNameEmitter {
 /// Base class for emitting a file (e.g. header or test) from OpenCLBuiltins.td
 class OpenCLBuiltinFileEmitterBase {
 public:
-  OpenCLBuiltinFileEmitterBase(RecordKeeper &Records, raw_ostream &OS)
+  OpenCLBuiltinFileEmitterBase(const RecordKeeper &Records, raw_ostream &OS)
   : Records(Records), OS(OS) {}
   virtual ~OpenCLBuiltinFileEmitterBase() = default;
 
@@ -305,7 +305,7 @@ class OpenCLBuiltinFileEmitterBase {
 
   // Contains OpenCL builtin functions and related information, stored as
   // Record instances. They are coming from the associated TableGen file.
-  RecordKeeper &Records;
+  const RecordKeeper &Records;
 
   // The output file.
   raw_ostream &OS;
@@ -316,7 +316,7 @@ class OpenCLBuiltinFileEmitterBase {
 // builtin function described in the .td input.
 class OpenCLBuiltinTestEmitter : public OpenCLBuiltinFileEmitterBase {
 public:
-  OpenCLBuiltinTestEmitter(RecordKeeper &Records, raw_ostream &OS)
+  OpenCLBuiltinTestEmitter(const RecordKeeper &Records, raw_ostream &OS)
   : OpenCLBuiltinFileEmitterBase(Records, OS) {}
 
   // Entrypoint to generate the functions for testing all OpenCL builtin
@@ -329,7 +329,7 @@ class OpenCLBuiltinTestEmitter : public 
OpenCLBuiltinFileEmitterBase {
 // prototype for each builtin function described in the .td input.
 class OpenCLBuiltinHeaderEmitter : public OpenCLBuiltinFileEmitterBase {
 public:
-  OpenCLBuiltinHeaderEmitter(RecordKeeper &Records, raw_ostream &OS)
+  OpenCLBuiltinHeaderEmitter(const RecordKeeper &Records, raw_ostream &OS)
   : OpenCLBuiltinFileEmitterBase(Records, OS) {}
 
   // Entrypoint to generate the header.
@@ -362,7 +362,7 @@ void BuiltinNameEmitter::Emit() {
   EmitQualTypeFinder();
 }
 
-void BuiltinNameEmitter::ExtractEnumTypes(std::vector &Types,
+void BuiltinNameEmitter::ExtractEnumTypes(ArrayRef Types,
   StringMap &TypesSeen,
   std::string &Output,
   std::vector &List) {
@@ -392,11 +392,11 @@ void BuiltinNameEmitter::EmitDeclarations() {
   // Extract generic types and non-generic types separately, to keep
   // gentypes at the end of the enum which simplifies the special handling
   // for gentypes in SemaLookup.
-  std::vector GenTypes =
+  ArrayRef GenTypes =
   Records.getAllDerivedDefinitions("GenericType");
   ExtractEnumTypes(GenTypes, TypesSeen, GenTypeEnums, GenTypeList);
 
-  std::vector Types = Records.getAllDerivedDefinitions("Type");
+  ArrayRef Types = Records.getAllDerivedDefinitions("Type");
   ExtractEnumTypes(Types, TypesSeen, TypeEnums, TypeList);
 
   OS << TypeEnums;
@@ -499,7 +499,7 @@ static void VerifySignature(const std::vector 
&Signature,
 
 void BuiltinNameEmitter::GetOverloads() {
   // Populate the TypeMap.
-  std::vector Types = Records.getAllDerivedDefinitions("Type");
+  ArrayRef Types = Records.getAllDerivedDefinitions("Type");
   unsigned I = 0;
   for (const auto &T : Types) {
 TypeMap.insert(std::make_pair(T, I++));
@@ -507,7 +507,8 @@ void BuiltinNameEmitter::GetOverloads() {
 
   // Populate the

[clang] [llvm] [SystemZ][z/OS] Update autoconversion functions to improve support for UTF-8 (PR #98652)

2024-09-11 Thread Abhina Sree via cfe-commits

https://github.com/abhina-sree updated 
https://github.com/llvm/llvm-project/pull/98652

>From e7be53314994b9a051ba2ff99dfd029937ebcc07 Mon Sep 17 00:00:00 2001
From: Abhina Sreeskantharajan 
Date: Fri, 12 Jul 2024 11:17:24 -0400
Subject: [PATCH 1/3] update autoconversion functionality to fix error: source
 file is not valid UTF-8

---
 clang/include/clang/Basic/FileEntry.h   |  9 ++
 clang/lib/Basic/SourceManager.cpp   | 25 
 llvm/include/llvm/Support/AutoConvert.h |  7 +
 llvm/lib/Support/AutoConvert.cpp| 40 -
 llvm/lib/Support/MemoryBuffer.cpp   | 16 --
 llvm/lib/Support/VirtualFileSystem.cpp  |  2 +-
 6 files changed, 95 insertions(+), 4 deletions(-)

diff --git a/clang/include/clang/Basic/FileEntry.h 
b/clang/include/clang/Basic/FileEntry.h
index 68d4bf60930037..1fe6c3617582ce 100644
--- a/clang/include/clang/Basic/FileEntry.h
+++ b/clang/include/clang/Basic/FileEntry.h
@@ -70,6 +70,11 @@ class FileEntryRef {
   const FileEntry &getFileEntry() const {
 return *getBaseMapEntry().second->V.get();
   }
+#ifdef __MVS__
+  FileEntry &getFileEntry() {
+return *getBaseMapEntry().second->V.get();
+  }
+#endif
   DirectoryEntryRef getDir() const { return ME->second->Dir; }
 
   inline off_t getSize() const;
@@ -323,6 +328,10 @@ class FileEntry {
 
   StringRef tryGetRealPathName() const { return RealPathName; }
   off_t getSize() const { return Size; }
+#ifdef __MVS__
+  // Size may increase due to potential z/OS EBCDIC -> UTF-8 conversion.
+  void setSize(off_t NewSize) { Size = NewSize; }
+#endif
   unsigned getUID() const { return UID; }
   const llvm::sys::fs::UniqueID &getUniqueID() const { return UniqueID; }
   time_t getModificationTime() const { return ModTime; }
diff --git a/clang/lib/Basic/SourceManager.cpp 
b/clang/lib/Basic/SourceManager.cpp
index d6ec26af80aadd..44b56a352dfc4e 100644
--- a/clang/lib/Basic/SourceManager.cpp
+++ b/clang/lib/Basic/SourceManager.cpp
@@ -24,6 +24,7 @@
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/StringSwitch.h"
 #include "llvm/Support/Allocator.h"
+#include "llvm/Support/AutoConvert.h"
 #include "llvm/Support/Capacity.h"
 #include "llvm/Support/Compiler.h"
 #include "llvm/Support/Endian.h"
@@ -166,8 +167,15 @@ ContentCache::getBufferOrNone(DiagnosticsEngine &Diag, 
FileManager &FM,
   // Unless this is a named pipe (in which case we can handle a mismatch),
   // check that the file's size is the same as in the file entry (which may
   // have come from a stat cache).
+#ifndef __MVS__
   if (!ContentsEntry->isNamedPipe() &&
   Buffer->getBufferSize() != (size_t)ContentsEntry->getSize()) {
+#else
+  // The buffer will always be larger than the file size on z/OS in the 
presence
+  // of characters outside the base character set.
+  if (!ContentsEntry->isNamedPipe() &&
+  Buffer->getBufferSize() < (size_t)ContentsEntry->getSize()) {
+#endif
 if (Diag.isDiagnosticInFlight())
   Diag.SetDelayedDiagnostic(diag::err_file_modified,
 ContentsEntry->getName());
@@ -617,6 +625,23 @@ FileID SourceManager::createFileIDImpl(ContentCache &File, 
StringRef Filename,
 return FileID::get(LoadedID);
   }
   unsigned FileSize = File.getSize();
+#ifdef __MVS__
+  llvm::ErrorOr NeedConversion =
+  llvm::needConversion(Filename.str().c_str());
+  if (NeedConversion && *NeedConversion) {
+// Buffer size may increase due to potential z/OS EBCDIC to UTF-8
+// conversion.
+if (std::optional Buffer =
+File.getBufferOrNone(Diag, getFileManager())) {
+  unsigned BufSize = Buffer->getBufferSize();
+  if (BufSize > FileSize) {
+if (File.ContentsEntry.has_value())
+  File.ContentsEntry->getFileEntry().setSize(BufSize);
+FileSize = BufSize;
+  }
+}
+  }
+#endif
   if (!(NextLocalOffset + FileSize + 1 > NextLocalOffset &&
 NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset)) {
 Diag.Report(IncludePos, diag::err_sloc_space_too_large);
diff --git a/llvm/include/llvm/Support/AutoConvert.h 
b/llvm/include/llvm/Support/AutoConvert.h
index 6f45c4683f7775..a9b3e0357589bc 100644
--- a/llvm/include/llvm/Support/AutoConvert.h
+++ b/llvm/include/llvm/Support/AutoConvert.h
@@ -17,6 +17,7 @@
 #ifdef __MVS__
 #include <_Ccsid.h>
 #ifdef __cplusplus
+#include "llvm/Support/ErrorOr.h"
 #include 
 #endif // __cplusplus
 
@@ -52,6 +53,12 @@ std::error_code restorezOSStdHandleAutoConversion(int FD);
 /// \brief Set the tag information for a file descriptor.
 std::error_code setzOSFileTag(int FD, int CCSID, bool Text);
 
+// Get the the tag ccsid for a file name or a file descriptor.
+ErrorOr<__ccsid_t> getFileTag(const char *FileName, const int FD = -1);
+
+// Query the file tag to determine if it needs conversion to UTF-8 codepage.
+ErrorOr needConversion(const char *FileName, const int FD = -1);
+
 } // namespace llvm
 #endif // __cplusplus
 
diff --git a/llvm/lib/Support/AutoConvert.cpp b/llvm/lib/S

[clang] [clang] Do not substitute parameter pack while retaining the pack expansion (PR #108197)

2024-09-11 Thread Ilya Biryukov via cfe-commits

https://github.com/ilya-biryukov commented:

Sorry for not looking closer yet, but could we get a test case?
It would make it much easier to review this change.

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


[clang] [Clang][Parser] Build up QualifiedTemplateName for typo correction (PR #108148)

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

zyn0217 wrote:

> Even if I think the change is fairly low risk, I'm not sure a 
> crash-on-invalid is critical enough to backport (we are at ~1 week of the 
> release)

I understand the point, but my thought is that we'd want as less regressions as 
possible; OTOH, the crash-on-invalid could also affect clangd, when the user 
happens to be typing something invalid.

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


[clang] [llvm] [DLCov 4/5] Track coverage and origins through IRBuilder (PR #108214)

2024-09-11 Thread Stephen Tozer via cfe-commits

https://github.com/SLTozer created 
https://github.com/llvm/llvm-project/pull/108214

This is part of a series of patches that tries to improve DILocation bug 
detection in Debugify; see below for more details. This patch modifies the 
IRBuilder to pass coverage and origin data through the IRBuilder, tracking the 
initial DebugLoc set in the IRBuilder (via `setCurrentDebugLocation`) as well 
as the point where we attach that DebugLoc to an inserted instruction. An 
important part of this patch is that it stores a DebugLoc directly in the 
IRBuilder instead of storing a DILocation metadata, meaning that coverage 
information is propagated through it. It also means that in the resulting 
Debugify report, we see two origin stack traces for the bug: that of the 
original DebugLoc, and the stack trace where we set this for the newly inserted 
instruction. The usefulness of this is that for any given bug, either of these 
could be relevant; the error could result from bad DebugLocs on existing 
instructions being propagated, in which case the original DebugLoc is what we 
care about, or it could result from the IRBuilder not having the correct 
DebugLoc set for it.

There are few places in the compiler where this sort of extension is necessary 
- the IRBuilder is a specific case where we propagate DebugLocs between 
instructions in an indirect way, using DILocation internally, which is used 
frequently enough for this modification to be worthwhile. The only other cases 
I've seen so far, which will be covered in the next patch, are the functions 
for merging DILocations.



This series of patches adds a "DebugLoc coverage tracking" feature, that 
inserts conditionally-compiled tracking information into DebugLocs (and by 
extension, to Instructions), which is used by Debugify to provide more accurate 
and detailed coverage reports. When enabled, this features tracks whether and 
why we have intentionally dropped a DebugLoc, allowing Debugify to ignore false 
positives. An optional additional feature allows also storing a stack trace of 
the point where a DebugLoc was unintentionally dropped/not generated, which is 
used to make fixing detected errors significantly easier. The goal of these 
features is to provide useful tools for developers to fix existing DebugLoc 
errors and allow reliable detection of regressions by either manual inspection 
or an automated script. 

Previous: https://github.com/llvm/llvm-project/pull/107369

>From e45d7e68a371a09ea766c4accf8edc6c030fd7fd Mon Sep 17 00:00:00 2001
From: Stephen Tozer 
Date: Wed, 4 Sep 2024 12:09:50 +0100
Subject: [PATCH 1/4] Add CMake option to enable expensive line number origin
 tracking

---
 llvm/CMakeLists.txt|  4 
 llvm/cmake/modules/HandleLLVMOptions.cmake | 12 
 llvm/docs/CMake.rst| 11 +++
 llvm/include/llvm/Config/config.h.cmake|  4 
 4 files changed, 31 insertions(+)

diff --git a/llvm/CMakeLists.txt b/llvm/CMakeLists.txt
index 12618966c4adfd..3e2e90f5adad2e 100644
--- a/llvm/CMakeLists.txt
+++ b/llvm/CMakeLists.txt
@@ -524,6 +524,10 @@ endif()
 
 option(LLVM_ENABLE_CRASH_DUMPS "Turn on memory dumps on crashes. Currently 
only implemented on Windows." OFF)
 
+set(LLVM_ENABLE_DEBUGLOC_COVERAGE_TRACKING "DISABLED" CACHE STRING
+  "Enhance debugify's line number coverage tracking; enabling this is 
abi-breaking. Can be DISABLED, COVERAGE, or COVERAGE_AND_ORIGIN.")
+set_property(CACHE LLVM_ENABLE_DEBUGLOC_COVERAGE_TRACKING PROPERTY STRINGS 
DISABLED COVERAGE COVERAGE_AND_ORIGIN)
+
 set(WINDOWS_PREFER_FORWARD_SLASH_DEFAULT OFF)
 if (MINGW)
   # Cygwin doesn't identify itself as Windows, and thus gets path::Style::posix
diff --git a/llvm/cmake/modules/HandleLLVMOptions.cmake 
b/llvm/cmake/modules/HandleLLVMOptions.cmake
index 5ca580fbb59c59..a4b11c149da9de 100644
--- a/llvm/cmake/modules/HandleLLVMOptions.cmake
+++ b/llvm/cmake/modules/HandleLLVMOptions.cmake
@@ -196,6 +196,18 @@ else()
   message(FATAL_ERROR "Unknown value for LLVM_ABI_BREAKING_CHECKS: 
\"${LLVM_ABI_BREAKING_CHECKS}\"!")
 endif()
 
+string(TOUPPER "${LLVM_ENABLE_DEBUGLOC_COVERAGE_TRACKING}" 
uppercase_LLVM_ENABLE_DEBUGLOC_COVERAGE_TRACKING)
+
+if( uppercase_LLVM_ENABLE_DEBUGLOC_COVERAGE_TRACKING STREQUAL "COVERAGE" )
+  set( ENABLE_DEBUGLOC_COVERAGE_TRACKING 1 )
+elseif( uppercase_LLVM_ENABLE_DEBUGLOC_COVERAGE_TRACKING STREQUAL 
"COVERAGE_AND_ORIGIN" )
+  message(FATAL_ERROR "\"COVERAGE_AND_ORIGIN\" setting for 
LLVM_ENABLE_DEBUGLOC_COVERAGE_TRACKING currently unimplemented.")
+elseif( uppercase_LLVM_ENABLE_DEBUGLOC_COVERAGE_TRACKING STREQUAL "DISABLED" 
OR NOT DEFINED LLVM_ENABLE_DEBUGLOC_COVERAGE_TRACKING )
+  # The DISABLED setting is default and requires no additional defines.
+else()
+  message(FATAL_ERROR "Unknown value for 
LLVM_ENABLE_DEBUGLOC_COVERAGE_TRACKING: 
\"${LLVM_ENABLE_DEBUGLOC_COVERAGE_TRACKING}\"!")
+endif()
+
 if( LLVM_REVERSE_ITERATION )
   set( LLVM_ENABLE_REVERSE_ITE

[clang] [llvm] [DLCov 4/5] Track coverage and origins through IRBuilder (PR #108214)

2024-09-11 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-debuginfo

Author: Stephen Tozer (SLTozer)


Changes

This is part of a series of patches that tries to improve DILocation bug 
detection in Debugify; see below for more details. This patch modifies the 
IRBuilder to pass coverage and origin data through the IRBuilder, tracking the 
initial DebugLoc set in the IRBuilder (via `setCurrentDebugLocation`) as well 
as the point where we attach that DebugLoc to an inserted instruction. An 
important part of this patch is that it stores a DebugLoc directly in the 
IRBuilder instead of storing a DILocation metadata, meaning that coverage 
information is propagated through it. It also means that in the resulting 
Debugify report, we see two origin stack traces for the bug: that of the 
original DebugLoc, and the stack trace where we set this for the newly inserted 
instruction. The usefulness of this is that for any given bug, either of these 
could be relevant; the error could result from bad DebugLocs on existing 
instructions being propagated, in which case the original DebugLoc is what we 
care about, or it could result from the IRBuilder not having the correct 
DebugLoc set for it.

There are few places in the compiler where this sort of extension is necessary 
- the IRBuilder is a specific case where we propagate DebugLocs between 
instructions in an indirect way, using DILocation internally, which is used 
frequently enough for this modification to be worthwhile. The only other cases 
I've seen so far, which will be covered in the next patch, are the functions 
for merging DILocations.



This series of patches adds a "DebugLoc coverage tracking" feature, that 
inserts conditionally-compiled tracking information into DebugLocs (and by 
extension, to Instructions), which is used by Debugify to provide more accurate 
and detailed coverage reports. When enabled, this features tracks whether and 
why we have intentionally dropped a DebugLoc, allowing Debugify to ignore false 
positives. An optional additional feature allows also storing a stack trace of 
the point where a DebugLoc was unintentionally dropped/not generated, which is 
used to make fixing detected errors significantly easier. The goal of these 
features is to provide useful tools for developers to fix existing DebugLoc 
errors and allow reliable detection of regressions by either manual inspection 
or an automated script. 

Previous: https://github.com/llvm/llvm-project/pull/107369

---

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


20 Files Affected:

- (modified) clang/lib/CodeGen/BackendUtil.cpp (+16) 
- (modified) llvm/CMakeLists.txt (+4) 
- (modified) llvm/cmake/modules/HandleLLVMOptions.cmake (+13) 
- (modified) llvm/docs/CMake.rst (+11) 
- (modified) llvm/include/llvm/Config/config.h.cmake (+8) 
- (modified) llvm/include/llvm/IR/DebugLoc.h (+113-1) 
- (modified) llvm/include/llvm/IR/IRBuilder.h (+27-4) 
- (modified) llvm/include/llvm/Support/Signals.h (+40) 
- (modified) llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp (+5) 
- (modified) llvm/lib/CodeGen/BranchFolding.cpp (+1-1) 
- (modified) llvm/lib/CodeGen/BranchFolding.h (+8-4) 
- (modified) llvm/lib/IR/DebugInfo.cpp (+2-2) 
- (modified) llvm/lib/IR/DebugLoc.cpp (+36) 
- (modified) llvm/lib/IR/IRBuilder.cpp (+6-12) 
- (modified) llvm/lib/IR/Instruction.cpp (+4-2) 
- (modified) llvm/lib/Support/Signals.cpp (+116) 
- (modified) llvm/lib/Support/Unix/Signals.inc (+15) 
- (modified) llvm/lib/Support/Windows/Signals.inc (+5) 
- (modified) llvm/lib/Transforms/Utils/Debugify.cpp (+79-17) 
- (modified) llvm/utils/llvm-original-di-preservation.py (+13-9) 


``diff
diff --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index e765bbf637a661..20653daff7d4ae 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -911,6 +911,22 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
   Debugify.setOrigDIVerifyBugsReportFilePath(
   CodeGenOpts.DIBugsReportFilePath);
 Debugify.registerCallbacks(PIC, MAM);
+
+#if ENABLE_DEBUGLOC_COVERAGE_TRACKING
+// If we're using debug location coverage tracking, mark all the
+// instructions coming out of the frontend without a DebugLoc as being
+// intentional line-zero locations, to prevent both those instructions and
+// new instructions that inherit their location from being treated as
+// incorrectly empty locations.
+for (Function &F : *TheModule) {
+  if (!F.getSubprogram())
+continue;
+  for (BasicBlock &BB : F)
+for (Instruction &I : BB)
+  if (!I.getDebugLoc())
+I.setDebugLoc(DebugLoc::getLineZero());
+}
+#endif
   }
   // Attempt to load pass plugins and register their callbacks with PB.
   for (auto &PluginFN : CodeGenOpts.PassPlugins) {
diff --git a/llvm/CMakeLists.txt b/llvm/CMakeLists.txt
index 12618966c4adfd..3e2e90f5ad

[clang] [clang][transformer] Make `describe()` terser for `NamedDecl`s. (PR #108215)

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

https://github.com/legrosbuffle created 
https://github.com/llvm/llvm-project/pull/108215

Right now `describe()`ing a `FunctionDecl` dups the whole code of the function. 
Dump only its name.

>From 42f1e67d2186fd90b8fc08206b33e077912039a1 Mon Sep 17 00:00:00 2001
From: Clement Courbet 
Date: Wed, 11 Sep 2024 12:35:14 +
Subject: [PATCH] [clang][transformer] Make `describe()` terser for
 `NamedDecl`s.

Right now `describe()`ing a `FunctionDecl` dups the whole code of the
function. Dump only its name.
---
 clang/lib/Tooling/Transformer/Stencil.cpp |  8 +++-
 clang/unittests/Tooling/StencilTest.cpp   | 22 ++
 2 files changed, 29 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Tooling/Transformer/Stencil.cpp 
b/clang/lib/Tooling/Transformer/Stencil.cpp
index bc4fa6e36057c1..223fb5a7689751 100644
--- a/clang/lib/Tooling/Transformer/Stencil.cpp
+++ b/clang/lib/Tooling/Transformer/Stencil.cpp
@@ -50,7 +50,13 @@ static Error printNode(StringRef Id, const 
MatchFinder::MatchResult &Match,
   auto NodeOrErr = getNode(Match.Nodes, Id);
   if (auto Err = NodeOrErr.takeError())
 return Err;
-  NodeOrErr->print(Os, PrintingPolicy(Match.Context->getLangOpts()));
+  const PrintingPolicy PP(Match.Context->getLangOpts());
+  if (const auto *ND = NodeOrErr->get()) {
+// For NamedDecls, we can do a better job than printing the whole thing.
+ND->getNameForDiagnostic(Os, PP, false);
+  } else {
+NodeOrErr->print(Os, PP);
+  }
   *Result += Output;
   return Error::success();
 }
diff --git a/clang/unittests/Tooling/StencilTest.cpp 
b/clang/unittests/Tooling/StencilTest.cpp
index 26257cf2ca3a5f..445912a53e8b62 100644
--- a/clang/unittests/Tooling/StencilTest.cpp
+++ b/clang/unittests/Tooling/StencilTest.cpp
@@ -565,6 +565,28 @@ TEST_F(StencilTest, DescribeAnonNamespaceType) {
HasValue(std::string(Expected)));
 }
 
+TEST_F(StencilTest, DescribeFunction) {
+  std::string Snippet = "int F(); F();";
+  std::string Expected = "F";
+  auto StmtMatch = matchStmt(Snippet, 
callExpr(callee(namedDecl().bind("fn";
+  ASSERT_TRUE(StmtMatch);
+  EXPECT_THAT_EXPECTED(describe("fn")->eval(StmtMatch->Result),
+   HasValue(std::string(Expected)));
+}
+
+TEST_F(StencilTest, DescribeImplicitOperator) {
+  std::string Snippet = "struct Tag {}; [](Tag){};";
+  std::string Expected = "operator()";
+  auto StmtMatch = matchStmt(
+  Snippet,
+  stmt(hasDescendant(
+  cxxMethodDecl(hasParameter(0, hasType(namedDecl(hasName("Tag")
+  .bind("fn";
+  ASSERT_TRUE(StmtMatch);
+  EXPECT_THAT_EXPECTED(describe("fn")->eval(StmtMatch->Result),
+   HasValue(std::string(Expected)));
+}
+
 TEST_F(StencilTest, RunOp) {
   StringRef Id = "id";
   auto SimpleFn = [Id](const MatchResult &R) {

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


[clang] [clang][TableGene] Change OptionDoc Emitter to use const RecordKeeper (PR #108216)

2024-09-11 Thread Rahul Joshi via cfe-commits

https://github.com/jurahul created 
https://github.com/llvm/llvm-project/pull/108216

None

>From f45b440523b4d1043f42b969246900c24025871a Mon Sep 17 00:00:00 2001
From: Rahul Joshi 
Date: Wed, 11 Sep 2024 05:51:13 -0700
Subject: [PATCH] [clang][TableGene] Change OptionDoc Emitter to use const
 RecordKeeper

---
 .../utils/TableGen/ClangOptionDocEmitter.cpp  | 46 +--
 clang/utils/TableGen/TableGenBackends.h   |  2 +-
 2 files changed, 24 insertions(+), 24 deletions(-)

diff --git a/clang/utils/TableGen/ClangOptionDocEmitter.cpp 
b/clang/utils/TableGen/ClangOptionDocEmitter.cpp
index 86835611b84218..8c32f0218e761b 100644
--- a/clang/utils/TableGen/ClangOptionDocEmitter.cpp
+++ b/clang/utils/TableGen/ClangOptionDocEmitter.cpp
@@ -24,8 +24,8 @@ using namespace llvm;
 
 namespace {
 struct DocumentedOption {
-  Record *Option;
-  std::vector Aliases;
+  const Record *Option;
+  std::vector Aliases;
 };
 struct DocumentedGroup;
 struct Documentation {
@@ -37,7 +37,7 @@ struct Documentation {
   }
 };
 struct DocumentedGroup : Documentation {
-  Record *Group;
+  const Record *Group;
 };
 
 static bool hasFlag(const Record *Option, StringRef OptionFlag,
@@ -63,25 +63,25 @@ static bool isOptionVisible(const Record *Option, const 
Record *DocInfo) {
 }
 
 // Reorganize the records into a suitable form for emitting documentation.
-Documentation extractDocumentation(RecordKeeper &Records,
+Documentation extractDocumentation(const RecordKeeper &Records,
const Record *DocInfo) {
   Documentation Result;
 
   // Build the tree of groups. The root in the tree is the fake option group
   // (Record*)nullptr, which contains all top-level groups and options.
-  std::map > OptionsInGroup;
-  std::map > GroupsInGroup;
-  std::map > Aliases;
+  std::map> OptionsInGroup;
+  std::map> GroupsInGroup;
+  std::map> Aliases;
 
-  std::map OptionsByName;
-  for (Record *R : Records.getAllDerivedDefinitions("Option"))
+  std::map OptionsByName;
+  for (const Record *R : Records.getAllDerivedDefinitions("Option"))
 OptionsByName[std::string(R->getValueAsString("Name"))] = R;
 
-  auto Flatten = [](Record *R) {
+  auto Flatten = [](const Record *R) {
 return R->getValue("DocFlatten") && R->getValueAsBit("DocFlatten");
   };
 
-  auto SkipFlattened = [&](Record *R) -> Record* {
+  auto SkipFlattened = [&](const Record *R) -> const Record * {
 while (R && Flatten(R)) {
   auto *G = dyn_cast(R->getValueInit("Group"));
   if (!G)
@@ -91,17 +91,17 @@ Documentation extractDocumentation(RecordKeeper &Records,
 return R;
   };
 
-  for (Record *R : Records.getAllDerivedDefinitions("OptionGroup")) {
+  for (const Record *R : Records.getAllDerivedDefinitions("OptionGroup")) {
 if (Flatten(R))
   continue;
 
-Record *Group = nullptr;
+const Record *Group = nullptr;
 if (auto *G = dyn_cast(R->getValueInit("Group")))
   Group = SkipFlattened(G->getDef());
 GroupsInGroup[Group].push_back(R);
   }
 
-  for (Record *R : Records.getAllDerivedDefinitions("Option")) {
+  for (const Record *R : Records.getAllDerivedDefinitions("Option")) {
 if (auto *A = dyn_cast(R->getValueInit("Alias"))) {
   Aliases[A->getDef()].push_back(R);
   continue;
@@ -120,33 +120,33 @@ Documentation extractDocumentation(RecordKeeper &Records,
   }
 }
 
-Record *Group = nullptr;
+const Record *Group = nullptr;
 if (auto *G = dyn_cast(R->getValueInit("Group")))
   Group = SkipFlattened(G->getDef());
 OptionsInGroup[Group].push_back(R);
   }
 
-  auto CompareByName = [](Record *A, Record *B) {
+  auto CompareByName = [](const Record *A, const Record *B) {
 return A->getValueAsString("Name") < B->getValueAsString("Name");
   };
 
-  auto CompareByLocation = [](Record *A, Record *B) {
+  auto CompareByLocation = [](const Record *A, const Record *B) {
 return A->getLoc()[0].getPointer() < B->getLoc()[0].getPointer();
   };
 
-  auto DocumentationForOption = [&](Record *R) -> DocumentedOption {
+  auto DocumentationForOption = [&](const Record *R) -> DocumentedOption {
 auto &A = Aliases[R];
 llvm::sort(A, CompareByName);
 return {R, std::move(A)};
   };
 
-  std::function DocumentationForGroup =
-  [&](Record *R) -> Documentation {
+  std::function DocumentationForGroup =
+  [&](const Record *R) -> Documentation {
 Documentation D;
 
 auto &Groups = GroupsInGroup[R];
 llvm::sort(Groups, CompareByLocation);
-for (Record *G : Groups) {
+for (const Record *G : Groups) {
   D.Groups.emplace_back();
   D.Groups.back().Group = G;
   Documentation &Base = D.Groups.back();
@@ -157,7 +157,7 @@ Documentation extractDocumentation(RecordKeeper &Records,
 
 auto &Options = OptionsInGroup[R];
 llvm::sort(Options, CompareByName);
-for (Record *O : Options)
+for (const Record *O : Options)
   if (isOptionVisible(O, DocInfo))
 D.Options.push_back(DocumentationForOptio

[clang] [clang][TableGen] Migrate clang-tblgen to use const RecordKeeper (PR #107533)

2024-09-11 Thread Rahul Joshi via cfe-commits

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


[clang] [clang][transformer] Make `describe()` terser for `NamedDecl`s. (PR #108215)

2024-09-11 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Clement Courbet (legrosbuffle)


Changes

Right now `describe()`ing a `FunctionDecl` dups the whole code of the function. 
Dump only its name.

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


2 Files Affected:

- (modified) clang/lib/Tooling/Transformer/Stencil.cpp (+7-1) 
- (modified) clang/unittests/Tooling/StencilTest.cpp (+22) 


``diff
diff --git a/clang/lib/Tooling/Transformer/Stencil.cpp 
b/clang/lib/Tooling/Transformer/Stencil.cpp
index bc4fa6e36057c1..223fb5a7689751 100644
--- a/clang/lib/Tooling/Transformer/Stencil.cpp
+++ b/clang/lib/Tooling/Transformer/Stencil.cpp
@@ -50,7 +50,13 @@ static Error printNode(StringRef Id, const 
MatchFinder::MatchResult &Match,
   auto NodeOrErr = getNode(Match.Nodes, Id);
   if (auto Err = NodeOrErr.takeError())
 return Err;
-  NodeOrErr->print(Os, PrintingPolicy(Match.Context->getLangOpts()));
+  const PrintingPolicy PP(Match.Context->getLangOpts());
+  if (const auto *ND = NodeOrErr->get()) {
+// For NamedDecls, we can do a better job than printing the whole thing.
+ND->getNameForDiagnostic(Os, PP, false);
+  } else {
+NodeOrErr->print(Os, PP);
+  }
   *Result += Output;
   return Error::success();
 }
diff --git a/clang/unittests/Tooling/StencilTest.cpp 
b/clang/unittests/Tooling/StencilTest.cpp
index 26257cf2ca3a5f..445912a53e8b62 100644
--- a/clang/unittests/Tooling/StencilTest.cpp
+++ b/clang/unittests/Tooling/StencilTest.cpp
@@ -565,6 +565,28 @@ TEST_F(StencilTest, DescribeAnonNamespaceType) {
HasValue(std::string(Expected)));
 }
 
+TEST_F(StencilTest, DescribeFunction) {
+  std::string Snippet = "int F(); F();";
+  std::string Expected = "F";
+  auto StmtMatch = matchStmt(Snippet, 
callExpr(callee(namedDecl().bind("fn";
+  ASSERT_TRUE(StmtMatch);
+  EXPECT_THAT_EXPECTED(describe("fn")->eval(StmtMatch->Result),
+   HasValue(std::string(Expected)));
+}
+
+TEST_F(StencilTest, DescribeImplicitOperator) {
+  std::string Snippet = "struct Tag {}; [](Tag){};";
+  std::string Expected = "operator()";
+  auto StmtMatch = matchStmt(
+  Snippet,
+  stmt(hasDescendant(
+  cxxMethodDecl(hasParameter(0, hasType(namedDecl(hasName("Tag")
+  .bind("fn";
+  ASSERT_TRUE(StmtMatch);
+  EXPECT_THAT_EXPECTED(describe("fn")->eval(StmtMatch->Result),
+   HasValue(std::string(Expected)));
+}
+
 TEST_F(StencilTest, RunOp) {
   StringRef Id = "id";
   auto SimpleFn = [Id](const MatchResult &R) {

``




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


[clang] [clang][TableGen] Change ASTTableGen to use const Record pointers (PR #108193)

2024-09-11 Thread Rahul Joshi via cfe-commits

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


[clang] [clang][TableGen] Change ASTTableGen to use const Record pointers (PR #108193)

2024-09-11 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Rahul Joshi (jurahul)


Changes

Change ASTTableGen to use const Record pointers.

This is a part of effort to have better const correctness in TableGen backends:

https://discourse.llvm.org/t/psa-planned-changes-to-tablegen-getallderiveddefinitions-api-potential-downstream-breakages/81089

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


2 Files Affected:

- (modified) clang/utils/TableGen/ASTTableGen.cpp (+8-11) 
- (modified) clang/utils/TableGen/ASTTableGen.h (+19-18) 


``diff
diff --git a/clang/utils/TableGen/ASTTableGen.cpp 
b/clang/utils/TableGen/ASTTableGen.cpp
index 54288ff6a03be3..47344777e9311a 100644
--- a/clang/utils/TableGen/ASTTableGen.cpp
+++ b/clang/utils/TableGen/ASTTableGen.cpp
@@ -31,7 +31,8 @@ llvm::StringRef clang::tblgen::HasProperties::getName() const 
{
   }
 }
 
-static StringRef removeExpectedNodeNameSuffix(Record *node, StringRef suffix) {
+static StringRef removeExpectedNodeNameSuffix(const Record *node,
+  StringRef suffix) {
   StringRef nodeName = node->getName();
   if (!nodeName.ends_with(suffix)) {
 PrintFatalError(node->getLoc(),
@@ -105,8 +106,7 @@ static void visitASTNodeRecursive(ASTNode node, ASTNode 
base,
   }
 }
 
-static void visitHierarchy(RecordKeeper &records,
-   StringRef nodeClassName,
+static void visitHierarchy(const RecordKeeper &records, StringRef 
nodeClassName,
ASTNodeHierarchyVisitor visit) {
   // Check for the node class, just as a basic correctness check.
   if (!records.getClass(nodeClassName)) {
@@ -114,13 +114,10 @@ static void visitHierarchy(RecordKeeper &records,
   + nodeClassName);
   }
 
-  // Find all the nodes in the hierarchy.
-  auto nodes = records.getAllDerivedDefinitions(nodeClassName);
-
-  // Derive the child map.
+  // Derive the child map for all nodes in the hierarchy.
   ChildMap hierarchy;
   ASTNode root;
-  for (ASTNode node : nodes) {
+  for (ASTNode node : records.getAllDerivedDefinitions(nodeClassName)) {
 if (auto base = node.getBase())
   hierarchy.insert(std::make_pair(base, node));
 else if (root)
@@ -136,8 +133,8 @@ static void visitHierarchy(RecordKeeper &records,
   visitASTNodeRecursive(root, ASTNode(), hierarchy, visit);
 }
 
-void clang::tblgen::visitASTNodeHierarchyImpl(RecordKeeper &records,
-  StringRef nodeClassName,
-  ASTNodeHierarchyVisitor visit) {
+void clang::tblgen::visitASTNodeHierarchyImpl(
+const RecordKeeper &records, StringRef nodeClassName,
+ASTNodeHierarchyVisitor visit) {
   visitHierarchy(records, nodeClassName, visit);
 }
diff --git a/clang/utils/TableGen/ASTTableGen.h 
b/clang/utils/TableGen/ASTTableGen.h
index 41f78a6a3bbcdd..143d779a8a64f8 100644
--- a/clang/utils/TableGen/ASTTableGen.h
+++ b/clang/utils/TableGen/ASTTableGen.h
@@ -87,18 +87,18 @@ namespace clang {
 namespace tblgen {
 
 class WrappedRecord {
-  llvm::Record *Record;
+  const llvm::Record *Record;
 
 protected:
-  WrappedRecord(llvm::Record *record = nullptr) : Record(record) {}
+  WrappedRecord(const llvm::Record *record = nullptr) : Record(record) {}
 
-  llvm::Record *get() const {
+  const llvm::Record *get() const {
 assert(Record && "accessing null record");
 return Record;
   }
 
 public:
-  llvm::Record *getRecord() const { return Record; }
+  const llvm::Record *getRecord() const { return Record; }
 
   explicit operator bool() const { return Record != nullptr; }
 
@@ -144,7 +144,7 @@ class HasProperties : public WrappedRecord {
 public:
   static constexpr llvm::StringRef ClassName = HasPropertiesClassName;
 
-  HasProperties(llvm::Record *record = nullptr) : WrappedRecord(record) {}
+  HasProperties(const llvm::Record *record = nullptr) : WrappedRecord(record) 
{}
 
   llvm::StringRef getName() const;
 
@@ -157,7 +157,7 @@ class HasProperties : public WrappedRecord {
 /// in one of Clang's AST hierarchies.
 class ASTNode : public HasProperties {
 public:
-  ASTNode(llvm::Record *record = nullptr) : HasProperties(record) {}
+  ASTNode(const llvm::Record *record = nullptr) : HasProperties(record) {}
 
   llvm::StringRef getName() const {
 return get()->getName();
@@ -180,7 +180,7 @@ class ASTNode : public HasProperties {
 
 class DeclNode : public ASTNode {
 public:
-  DeclNode(llvm::Record *record = nullptr) : ASTNode(record) {}
+  DeclNode(const llvm::Record *record = nullptr) : ASTNode(record) {}
 
   llvm::StringRef getId() const;
   std::string getClassName() const;
@@ -202,7 +202,7 @@ class DeclNode : public ASTNode {
 
 class TypeNode : public ASTNode {
 public:
-  TypeNode(llvm::Record *record = nullptr) : ASTNode(record) {}
+  TypeNode(const llvm::Record *record = nullptr) : ASTNode(record) {}
 
   llvm::StringRef getId() const;
   llvm::StringRef getClassName() const;
@@ -224,7 +224,7 @@ cla

[clang] [clang][TableGen] Change ASTTableGen to use const Record pointers (PR #108193)

2024-09-11 Thread Rahul Joshi via cfe-commits

jurahul wrote:

@AaronBallman I am adding you as a reviewer, but if there is someone else who 
can help review these, please let me know.

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


[clang] [clang-tools-extra] [libc] [libc][c11] implement ctime (PR #107285)

2024-09-11 Thread Зишан Мирза via cfe-commits


@@ -3062,6 +3062,10 @@ libc/src/time/asctime.cpp
 libc/src/time/asctime.h
 libc/src/time/asctime_r.cpp
 libc/src/time/asctime_r.h
+libc/src/time/ctime.cpp
+libc/src/time/ctime.h
+libc/src/time/ctime_r.cpp
+libc/src/time/ctime_r.h

zimirza wrote:

I forgot to delete those. I had created another issue for that. I will delete 
them now.

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


[clang] [llvm] [DLCov 3/5] Implement DebugLoc origin-tracking (PR #107369)

2024-09-11 Thread Stephen Tozer via cfe-commits

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


  1   2   3   4   5   6   >