[clang] [llvm] [AMDGPU] Adding the amdgpu-num-work-groups function attribute (PR #79035)
https://github.com/jwanggit86 edited https://github.com/llvm/llvm-project/pull/79035 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [AMDGPU] Adding the amdgpu-num-work-groups function attribute (PR #79035)
@@ -137,6 +137,12 @@ Removed Compiler Flags Attribute Changes in Clang -- +- Introduced a new function attribute ``__attribute__((amdgpu_max_num_work_groups(x, y, z)))`` or jwanggit86 wrote: In the case of flat workgroup size, the LLVM attribute is called `amdgpu-flat-work-group-size`, but the metadata is `.max_flat_workgroup_size`. I suppose we can copy that and change the metadata from `.max_num_work_groups_x` to `.max_num_workgoups_x` and so on. Do you want the LLVM attribute to be changed from `amdgpu-max-num-work-groups` to `amdgpu-max-num-workgroups` as well? Note that in the file `AMDGPUUsage.rst` the word `work-group` with a hyphen is used a lot. https://github.com/llvm/llvm-project/pull/79035 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] a331937 - [MC] Move CompressDebugSections/RelaxELFRelocations from TargetOptions/MCAsmInfo to MCTargetOptions
Author: Fangrui Song Date: 2024-03-06T23:19:59-08:00 New Revision: a3319371970b599ef65ef1567c440fbdc3a330f4 URL: https://github.com/llvm/llvm-project/commit/a3319371970b599ef65ef1567c440fbdc3a330f4 DIFF: https://github.com/llvm/llvm-project/commit/a3319371970b599ef65ef1567c440fbdc3a330f4.diff LOG: [MC] Move CompressDebugSections/RelaxELFRelocations from TargetOptions/MCAsmInfo to MCTargetOptions The convention is for such MC-specific options to reside in MCTargetOptions. However, CompressDebugSections/RelaxELFRelocations do not follow the convention: `CompressDebugSections` is defined in both TargetOptions and MCAsmInfo and there is forwarding complexity. Move the option to MCTargetOptions and hereby simplify the code. Rename the misleading RelaxELFRelocations to X86RelaxRelocations. llvm-mc -relax-relocations and llc -x86-relax-relocations can now be unified. Added: Modified: clang/lib/CodeGen/BackendUtil.cpp clang/tools/driver/cc1as_main.cpp lld/test/ELF/weak-undef-got-pie.s llvm/include/llvm/CodeGen/CommandFlags.h llvm/include/llvm/MC/MCAsmInfo.h llvm/include/llvm/MC/MCContext.h llvm/include/llvm/MC/MCTargetOptions.h llvm/include/llvm/MC/MCTargetOptionsCommandFlags.h llvm/include/llvm/Target/TargetOptions.h llvm/lib/CodeGen/CommandFlags.cpp llvm/lib/CodeGen/LLVMTargetMachine.cpp llvm/lib/LTO/LTO.cpp llvm/lib/MC/ELFObjectWriter.cpp llvm/lib/MC/MCTargetOptionsCommandFlags.cpp llvm/lib/Target/X86/MCTargetDesc/X86ELFObjectWriter.cpp llvm/lib/Target/X86/X86MCInstLower.cpp llvm/test/ExecutionEngine/JITLink/AArch64/ELF_minimal.s llvm/test/ExecutionEngine/JITLink/AArch64/ELF_relocations.s llvm/test/ExecutionEngine/JITLink/x86-64/COFF_small_pic_relocations.s llvm/test/ExecutionEngine/JITLink/x86-64/ELF_common_var.s llvm/test/MC/ELF/got-relaxed-i386.s llvm/test/MC/ELF/relocation-386.s llvm/test/MC/X86/gotpcrelx.s llvm/tools/gold/gold-plugin.cpp llvm/tools/llvm-mc/llvm-mc.cpp Removed: diff --git a/clang/lib/CodeGen/BackendUtil.cpp b/clang/lib/CodeGen/BackendUtil.cpp index 056f790d41853d..7310e3817c79a1 100644 --- a/clang/lib/CodeGen/BackendUtil.cpp +++ b/clang/lib/CodeGen/BackendUtil.cpp @@ -356,8 +356,6 @@ static bool initTargetOptions(DiagnosticsEngine , llvm::TargetMachine::parseBinutilsVersion(CodeGenOpts.BinutilsVersion); Options.UseInitArray = CodeGenOpts.UseInitArray; Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS; - Options.CompressDebugSections = CodeGenOpts.getCompressDebugSections(); - Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations; // Set EABI version. Options.EABIVersion = TargetOpts.EABIVersion; @@ -460,6 +458,9 @@ static bool initTargetOptions(DiagnosticsEngine , Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose; Options.MCOptions.Dwarf64 = CodeGenOpts.Dwarf64; Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments; + Options.MCOptions.X86RelaxRelocations = CodeGenOpts.RelaxELFRelocations; + Options.MCOptions.CompressDebugSections = + CodeGenOpts.getCompressDebugSections(); Options.MCOptions.ABIName = TargetOpts.ABI; for (const auto : HSOpts.UserEntries) if (!Entry.IsFramework && diff --git a/clang/tools/driver/cc1as_main.cpp b/clang/tools/driver/cc1as_main.cpp index a55e06500d9d92..5498c3f9d4a20d 100644 --- a/clang/tools/driver/cc1as_main.cpp +++ b/clang/tools/driver/cc1as_main.cpp @@ -428,6 +428,8 @@ static bool ExecuteAssemblerImpl(AssemblerInvocation , MCTargetOptions MCOptions; MCOptions.EmitDwarfUnwind = Opts.EmitDwarfUnwind; MCOptions.EmitCompactUnwindNonCanonical = Opts.EmitCompactUnwindNonCanonical; + MCOptions.X86RelaxRelocations = Opts.RelaxELFRelocations; + MCOptions.CompressDebugSections = Opts.CompressDebugSections; MCOptions.AsSecureLogFile = Opts.AsSecureLogFile; std::unique_ptr MAI( @@ -436,9 +438,7 @@ static bool ExecuteAssemblerImpl(AssemblerInvocation , // Ensure MCAsmInfo initialization occurs before any use, otherwise sections // may be created with a combination of default and explicit settings. - MAI->setCompressDebugSections(Opts.CompressDebugSections); - MAI->setRelaxELFRelocations(Opts.RelaxELFRelocations); bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj; if (Opts.OutputPath.empty()) diff --git a/lld/test/ELF/weak-undef-got-pie.s b/lld/test/ELF/weak-undef-got-pie.s index c695ecdbafb12e..2301400f4e0b19 100644 --- a/lld/test/ELF/weak-undef-got-pie.s +++ b/lld/test/ELF/weak-undef-got-pie.s @@ -1,7 +1,7 @@ # REQUIRES: x86 # RUN: llvm-mc -filetype=obj -triple=x86_64 %p/Inputs/dummy-shared.s -o %t1.o # RUN: ld.lld %t1.o -shared -o %t1.so -# RUN: llvm-mc -filetype=obj -relax-relocations=false -triple=x86_64 %s -o %t.o +# RUN: llvm-mc -filetype=obj -x86-relax-relocations=false -triple=x86_64 %s -o %t.o # RUN:
[clang] [llvm] [AMDGPU] Adding the amdgpu-num-work-groups function attribute (PR #79035)
@@ -137,6 +137,12 @@ Removed Compiler Flags Attribute Changes in Clang -- +- Introduced a new function attribute ``__attribute__((amdgpu_max_num_work_groups(x, y, z)))`` or arsenm wrote: The backend facing parts seem more consistently to be workgroup. e.g in the HSA metadata, we have .workgroup_size_hint, .reqd_workgroup_size. As horrible as it is, maybe it's best to keep it this way for the clang attribute, and rename all the backend bits to be "workgroup"? https://github.com/llvm/llvm-project/pull/79035 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [AMDGPU] Adding the amdgpu-num-work-groups function attribute (PR #79035)
@@ -137,6 +137,12 @@ Removed Compiler Flags Attribute Changes in Clang -- +- Introduced a new function attribute ``__attribute__((amdgpu_max_num_work_groups(x, y, z)))`` or arsenm wrote: Ugh. The ISA manuals usually use "workgroup". read_work_group_size came from OpenCL. We made up amdgpu_flat_work_group_size https://github.com/llvm/llvm-project/pull/79035 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [C++20][Coroutines] Lambda-coroutine with operator new in promise_type (PR #84193)
@@ -6898,10 +6898,18 @@ class Sema final { BinaryOperatorKind Operator); ActOnCXXThis - Parse 'this' pointer. - ExprResult ActOnCXXThis(SourceLocation loc); + /// + /// \param SkipLambdaCaptureCheck Whether to skip the 'this' check for a + /// lambda because 'this' is the lambda's 'this'-pointer. + ExprResult ActOnCXXThis(SourceLocation loc, + bool SkipLambdaCaptureCheck = false); ChuanqiXu9 wrote: If there is any problem with the promise_type with a constructor, let's make it in other patches. https://github.com/llvm/llvm-project/pull/84193 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [C++20][Coroutines] Lambda-coroutine with operator new in promise_type (PR #84193)
https://github.com/ChuanqiXu9 approved this pull request. LGTM with the adding the comments. https://github.com/llvm/llvm-project/pull/84193 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [C++20][Coroutines] Lambda-coroutine with operator new in promise_type (PR #84193)
https://github.com/Endilll commented: `Sema.h` changes look good. https://github.com/llvm/llvm-project/pull/84193 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [C++20][Coroutines] Lambda-coroutine with operator new in promise_type (PR #84193)
@@ -6898,10 +6898,18 @@ class Sema final { BinaryOperatorKind Operator); ActOnCXXThis - Parse 'this' pointer. - ExprResult ActOnCXXThis(SourceLocation loc); + /// + /// \param SkipLambdaCaptureCheck Whether to skip the 'this' check for a + /// lambda because 'this' is the lambda's 'this'-pointer. + ExprResult ActOnCXXThis(SourceLocation loc, + bool SkipLambdaCaptureCheck = false); ChuanqiXu9 wrote: Excellent. Good. I suggest you to update this to the inline comments. https://github.com/llvm/llvm-project/pull/84193 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Turn 'counted_by' into a type attribute and parse it into 'CountAttributedType' (PR #78000)
Endilll wrote: Can you resolve merge conflicts, so that I can review changes to `Sema.h`? https://github.com/llvm/llvm-project/pull/78000 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [C++20][Coroutines] Lambda-coroutine with operator new in promise_type (PR #84193)
@@ -1434,13 +1434,18 @@ ExprResult Sema::ActOnCXXThis(SourceLocation Loc) { return Diag(Loc, diag::err_invalid_this_use) << 0; } - return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false); + return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false, + SkipLambdaCaptureCheck); } -Expr *Sema::BuildCXXThisExpr(SourceLocation Loc, QualType Type, - bool IsImplicit) { +Expr *Sema::BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit, + bool SkipLambdaCaptureCheck) { auto *This = CXXThisExpr::Create(Context, Loc, Type, IsImplicit); - MarkThisReferenced(This); + + if (!SkipLambdaCaptureCheck) { andreasfertig wrote: See above, because in this case nothing is captured. https://github.com/llvm/llvm-project/pull/84193 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [C++20][Coroutines] Lambda-coroutine with operator new in promise_type (PR #84193)
@@ -0,0 +1,54 @@ +// RUN: %clang_cc1 -fsyntax-only -verify -I%S/Inputs -std=c++20 %s + +// expected-no-diagnostics + +#include "std-coroutine.h" + +using size_t = decltype(sizeof(0)); + +struct Generator { + struct promise_type { +int _val{}; + +Generator get_return_object() noexcept +{ + return {}; +} + +std::suspend_never initial_suspend() noexcept +{ + return {}; +} + +std::suspend_always final_suspend() noexcept +{ + return {}; +} + +void return_void() noexcept {} +void unhandled_exception() noexcept {} + +template +static void* +operator new(size_t size, + This&, + TheRest&&...) noexcept +{ +return nullptr; +} + +static void operator delete(void*, size_t) +{ +} + }; +}; + +int main() +{ + auto lamb = []() -> Generator { andreasfertig wrote: Sure. See my answer above, maybe that helps to understand that we aren't talking about a captured `this`, this time. https://github.com/llvm/llvm-project/pull/84193 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][C++23] Implement P1774R8: Portable assumptions (PR #81014)
https://github.com/Endilll commented: `Sema.h` changes look good. https://github.com/llvm/llvm-project/pull/81014 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [C++20][Coroutines] Lambda-coroutine with operator new in promise_type (PR #84193)
@@ -6898,10 +6898,18 @@ class Sema final { BinaryOperatorKind Operator); ActOnCXXThis - Parse 'this' pointer. - ExprResult ActOnCXXThis(SourceLocation loc); + /// + /// \param SkipLambdaCaptureCheck Whether to skip the 'this' check for a + /// lambda because 'this' is the lambda's 'this'-pointer. + ExprResult ActOnCXXThis(SourceLocation loc, + bool SkipLambdaCaptureCheck = false); andreasfertig wrote: Sure, have a look at this code (https://cppinsights.io/s/3212c7be) ``` class Test { int a; public: Test(int x) : a{x} { int other{}; auto l1 = [=] { return a + 2 + other; }; } }; ``` The lambda `l1` has _two_ things that we refer to as `this`-pointer. It's very own, as every non-static member function has. Used to access `other` like `this->other` inside the lambdas body. That `this`-pointer isn't captured. Hence, no check. Then the captured `this`-pointer from the enclosing scope of `Test`. In C++ Insights called `__this`. While being used it looks like `this->__this->a`. The check is in place for the latter. For the use case of calling `operator new` in the case of a coroutine, we are talking about the first one, which isn't captured. While writing about this, I haven't checked whether a `promise_type` with a constructor worked before or does so now. I can check that maybe tomorrow. https://github.com/llvm/llvm-project/pull/84193 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Upstream visionOS Availability & DarwinSDKInfo APIs (PR #84279)
https://github.com/cyndyishida updated https://github.com/llvm/llvm-project/pull/84279 >From 777edd2803f87308a6eb4119aacca792a8c62672 Mon Sep 17 00:00:00 2001 From: Cyndy Ishida Date: Wed, 6 Mar 2024 20:29:30 -0800 Subject: [PATCH 1/2] [clang] Support availability annotations for visionOS Admittently a bit awkward, `visionos` is the correct and accepted spelling for annotating availability for xros target triples. This patch detects errors and handles cases when `xros` is mistakenly passed. --- clang/include/clang/Basic/Attr.td | 8 clang/lib/Parse/ParseDecl.cpp | 5 ++- clang/lib/Parse/ParseExpr.cpp | 3 +- .../test/CodeGen/attr-availability-visionos.c | 10 + clang/test/Sema/attr-availability-visionos.c | 39 +++ 5 files changed, 63 insertions(+), 2 deletions(-) create mode 100644 clang/test/CodeGen/attr-availability-visionos.c create mode 100644 clang/test/Sema/attr-availability-visionos.c diff --git a/clang/include/clang/Basic/Attr.td b/clang/include/clang/Basic/Attr.td index fa191c7378dba4..ebb616fbe253fc 100644 --- a/clang/include/clang/Basic/Attr.td +++ b/clang/include/clang/Basic/Attr.td @@ -983,6 +983,8 @@ def Availability : InheritableAttr { .Case("watchos_app_extension", "watchOS (App Extension)") .Case("maccatalyst", "macCatalyst") .Case("maccatalyst_app_extension", "macCatalyst (App Extension)") + .Case("xros", "visionOS") + .Case("xros_app_extension", "visionOS (App Extension)") .Case("swift", "Swift") .Case("shadermodel", "HLSL ShaderModel") .Case("ohos", "OpenHarmony OS") @@ -1000,6 +1002,8 @@ static llvm::StringRef getPlatformNameSourceSpelling(llvm::StringRef Platform) { .Case("watchos_app_extension", "watchOSApplicationExtension") .Case("maccatalyst", "macCatalyst") .Case("maccatalyst_app_extension", "macCatalystApplicationExtension") + .Case("xros", "visionOS") + .Case("xros_app_extension", "visionOSApplicationExtension") .Case("zos", "z/OS") .Case("shadermodel", "ShaderModel") .Default(Platform); @@ -1016,6 +1020,10 @@ static llvm::StringRef canonicalizePlatformName(llvm::StringRef Platform) { .Case("watchOSApplicationExtension", "watchos_app_extension") .Case("macCatalyst", "maccatalyst") .Case("macCatalystApplicationExtension", "maccatalyst_app_extension") + .Case("visionOS", "xros") + .Case("visionOSApplicationExtension", "xros_app_extension") + .Case("visionos", "xros") + .Case("visionos_app_extension", "xros_app_extension") .Case("ShaderModel", "shadermodel") .Default(Platform); } }]; diff --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp index 81f1c711269445..ee377b70964a28 100644 --- a/clang/lib/Parse/ParseDecl.cpp +++ b/clang/lib/Parse/ParseDecl.cpp @@ -1234,8 +1234,11 @@ void Parser::ParseAvailabilityAttribute( } IdentifierLoc *Platform = ParseIdentifierLoc(); if (const IdentifierInfo *const Ident = Platform->Ident) { +// Disallow xrOS for availability attributes. +if (Ident->getName().contains("xrOS") || Ident->getName().contains("xros")) + Diag(Platform->Loc, diag::warn_availability_unknown_platform) << Ident; // Canonicalize platform name from "macosx" to "macos". -if (Ident->getName() == "macosx") +else if (Ident->getName() == "macosx") Platform->Ident = PP.getIdentifierInfo("macos"); // Canonicalize platform name from "macosx_app_extension" to // "macos_app_extension". diff --git a/clang/lib/Parse/ParseExpr.cpp b/clang/lib/Parse/ParseExpr.cpp index 4bf954b5cc4db5..1f07eddb0fb378 100644 --- a/clang/lib/Parse/ParseExpr.cpp +++ b/clang/lib/Parse/ParseExpr.cpp @@ -3863,7 +3863,8 @@ std::optional Parser::ParseAvailabilitySpec() { StringRef Platform = AvailabilityAttr::canonicalizePlatformName(GivenPlatform); -if (AvailabilityAttr::getPrettyPlatformName(Platform).empty()) { +if (AvailabilityAttr::getPrettyPlatformName(Platform).empty() || +(GivenPlatform.contains("xros") || GivenPlatform.contains("xrOS"))) { Diag(PlatformIdentifier->Loc, diag::err_avail_query_unrecognized_platform_name) << GivenPlatform; diff --git a/clang/test/CodeGen/attr-availability-visionos.c b/clang/test/CodeGen/attr-availability-visionos.c new file mode 100644 index 00..09b98fb4a7d5e3 --- /dev/null +++ b/clang/test/CodeGen/attr-availability-visionos.c @@ -0,0 +1,10 @@ +// RUN: %clang_cc1 -triple arm64-apple-xros1 -emit-llvm -o - %s 2>&1 | FileCheck %s + +__attribute__((availability(visionOS, introduced=1.1))) +void introduced_1_1(); + +void use() { + if (__builtin_available(visionOS 1.2, *)) +introduced_1_1(); + // CHECK: call i32
[clang] [alpha.webkit.UncountedLocalVarsChecker] Allow uncounted object references within trivial statements (PR #82229)
https://github.com/rniwa updated https://github.com/llvm/llvm-project/pull/82229 >From 234e301ab2721ddb2f4b43589785015a7d0aa304 Mon Sep 17 00:00:00 2001 From: Ryosuke Niwa Date: Mon, 19 Feb 2024 01:07:13 -0800 Subject: [PATCH 1/9] [alpha.webkit.UncountedLocalVarsChecker] Allow uncounted object references within trivial statements This PR makes alpha.webkit.UncountedLocalVarsChecker ignore raw references and pointers to a ref counted type which appears within "trival" statements. To do this, this PR extends TrivialFunctionAnalysis so that it can also analyze "triviality" of statements as well as that of functions Each Visit* function is now augmented with withCachedResult, which is responsible for looking up and updating the cache for each Visit* functions. As this PR dramatically improves the false positive rate of the checker, it also deletes the code to ignore raw pointers and references within if and for statements. --- .../Checkers/WebKit/PtrTypesSemantics.cpp | 222 -- .../Checkers/WebKit/PtrTypesSemantics.h | 21 +- .../WebKit/UncountedLocalVarsChecker.cpp | 69 +++--- .../Analysis/Checkers/WebKit/mock-types.h | 2 + .../Checkers/WebKit/uncounted-local-vars.cpp | 92 +++- 5 files changed, 285 insertions(+), 121 deletions(-) diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp index 01b191ab0eeaf4..6c9a8aedb38a4c 100644 --- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp @@ -245,18 +245,41 @@ class TrivialFunctionAnalysisVisitor // Returns false if at least one child is non-trivial. bool VisitChildren(const Stmt *S) { -for (const Stmt *Child : S->children()) { - if (Child && !Visit(Child)) +return withCachedResult(S, [&]() { + for (const Stmt *Child : S->children()) { +if (Child && !Visit(Child)) + return false; + } + return true; +}); + } + + bool VisitSubExpr(const Expr *Parent, const Expr *E) { +return withCachedResult(Parent, [&]() { + if (!Visit(E)) return false; -} + return true; +}); + } -return true; + template + bool withCachedResult(const StmtType *S, CheckFunction Function) { +// Insert false to the cache first to avoid infinite recursion. +auto [It, IsNew] = StatementCache.insert(std::make_pair(S, false)); +if (!IsNew) + return It->second; +bool Result = Function(); +It->second = Result; +return Result; } public: - using CacheTy = TrivialFunctionAnalysis::CacheTy; + using FunctionCacheTy = TrivialFunctionAnalysis::FunctionCacheTy; + using StatementCacheTy = TrivialFunctionAnalysis::StatementCacheTy; - TrivialFunctionAnalysisVisitor(CacheTy ) : Cache(Cache) {} + TrivialFunctionAnalysisVisitor(FunctionCacheTy , + StatementCacheTy ) + : FunctionCache(FunctionCache), StatementCache(StatementCache) {} bool VisitStmt(const Stmt *S) { // All statements are non-trivial unless overriden later. @@ -272,13 +295,21 @@ class TrivialFunctionAnalysisVisitor bool VisitReturnStmt(const ReturnStmt *RS) { // A return statement is allowed as long as the return value is trivial. -if (auto *RV = RS->getRetValue()) - return Visit(RV); -return true; +return withCachedResult(RS, [&]() { + if (auto *RV = RS->getRetValue()) +return Visit(RV); + return true; +}); + } + + bool VisitCXXForRangeStmt(const CXXForRangeStmt *FS) { +return VisitChildren(FS); } bool VisitDeclStmt(const DeclStmt *DS) { return VisitChildren(DS); } bool VisitDoStmt(const DoStmt *DS) { return VisitChildren(DS); } + bool VisitForStmt(const ForStmt *FS) { return VisitChildren(FS); } + bool VisitWhileStmt(const WhileStmt *WS) { return VisitChildren(WS); } bool VisitIfStmt(const IfStmt *IS) { return VisitChildren(IS); } bool VisitSwitchStmt(const SwitchStmt *SS) { return VisitChildren(SS); } bool VisitCaseStmt(const CaseStmt *CS) { return VisitChildren(CS); } @@ -286,17 +317,26 @@ class TrivialFunctionAnalysisVisitor bool VisitUnaryOperator(const UnaryOperator *UO) { // Operator '*' and '!' are allowed as long as the operand is trivial. -if (UO->getOpcode() == UO_Deref || UO->getOpcode() == UO_AddrOf || -UO->getOpcode() == UO_LNot) - return Visit(UO->getSubExpr()); - -// Other operators are non-trivial. -return false; +return withCachedResult(UO, [&]() { + auto op = UO->getOpcode(); + if (op == UO_Deref || op == UO_AddrOf || op == UO_LNot) +return Visit(UO->getSubExpr()); + if (UO->isIncrementOp() || UO->isDecrementOp()) { +if (auto *RefExpr = dyn_cast(UO->getSubExpr())) { + if (auto *Decl = dyn_cast(RefExpr->getDecl())) +return Decl->isLocalVarDeclOrParm() && +
[clang] [alpha.webkit.UncountedLocalVarsChecker] Allow uncounted object references within trivial statements (PR #82229)
@@ -305,19 +337,21 @@ class TrivialFunctionAnalysisVisitor } bool VisitDeclRefExpr(const DeclRefExpr *DRE) { -if (auto *decl = DRE->getDecl()) { - if (isa(decl)) -return true; - if (isa(decl)) -return true; - if (auto *VD = dyn_cast(decl)) { -if (VD->hasConstantInitialization() && VD->getEvaluatedValue()) +return WithCachedResult(DRE, [&]() { + if (auto *decl = DRE->getDecl()) { +if (isa(decl)) return true; -auto *Init = VD->getInit(); -return !Init || Visit(Init); +if (isa(decl)) + return true; +if (auto *VD = dyn_cast(decl)) { + if (VD->hasConstantInitialization() && VD->getEvaluatedValue()) +return true; + auto *Init = VD->getInit(); + return !Init || Visit(Init); rniwa wrote: Oh, that is a very good point. I guess we can just always `return true` for `DeclRefExpr`. https://github.com/llvm/llvm-project/pull/82229 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Upstream visionOS Availability & DarwinSDKInfo APIs (PR #84279)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Cyndy Ishida (cyndyishida) Changes Admittedly a bit awkward, `visionos` is the correct and accepted spelling for annotating availability for xrOS target triples. This patch detects errors and handles cases when `xros` is mistakenly passed. In addition, add APIs for introduced/deprecated/obsoleted versioning in DarwinSDKInfo mappings. --- Full diff: https://github.com/llvm/llvm-project/pull/84279.diff 6 Files Affected: - (modified) clang/include/clang/Basic/Attr.td (+8) - (modified) clang/include/clang/Basic/DarwinSDKInfo.h (+24) - (modified) clang/lib/Parse/ParseDecl.cpp (+4-1) - (modified) clang/lib/Parse/ParseExpr.cpp (+2-1) - (added) clang/test/Sema/attr-availability-visionos.c (+39) - (modified) clang/unittests/Basic/DarwinSDKInfoTest.cpp (+10) ``diff diff --git a/clang/include/clang/Basic/Attr.td b/clang/include/clang/Basic/Attr.td index fa191c7378dba4..ebb616fbe253fc 100644 --- a/clang/include/clang/Basic/Attr.td +++ b/clang/include/clang/Basic/Attr.td @@ -983,6 +983,8 @@ def Availability : InheritableAttr { .Case("watchos_app_extension", "watchOS (App Extension)") .Case("maccatalyst", "macCatalyst") .Case("maccatalyst_app_extension", "macCatalyst (App Extension)") + .Case("xros", "visionOS") + .Case("xros_app_extension", "visionOS (App Extension)") .Case("swift", "Swift") .Case("shadermodel", "HLSL ShaderModel") .Case("ohos", "OpenHarmony OS") @@ -1000,6 +1002,8 @@ static llvm::StringRef getPlatformNameSourceSpelling(llvm::StringRef Platform) { .Case("watchos_app_extension", "watchOSApplicationExtension") .Case("maccatalyst", "macCatalyst") .Case("maccatalyst_app_extension", "macCatalystApplicationExtension") + .Case("xros", "visionOS") + .Case("xros_app_extension", "visionOSApplicationExtension") .Case("zos", "z/OS") .Case("shadermodel", "ShaderModel") .Default(Platform); @@ -1016,6 +1020,10 @@ static llvm::StringRef canonicalizePlatformName(llvm::StringRef Platform) { .Case("watchOSApplicationExtension", "watchos_app_extension") .Case("macCatalyst", "maccatalyst") .Case("macCatalystApplicationExtension", "maccatalyst_app_extension") + .Case("visionOS", "xros") + .Case("visionOSApplicationExtension", "xros_app_extension") + .Case("visionos", "xros") + .Case("visionos_app_extension", "xros_app_extension") .Case("ShaderModel", "shadermodel") .Default(Platform); } }]; diff --git a/clang/include/clang/Basic/DarwinSDKInfo.h b/clang/include/clang/Basic/DarwinSDKInfo.h index dedfbd934a7b63..db20b968a898ea 100644 --- a/clang/include/clang/Basic/DarwinSDKInfo.h +++ b/clang/include/clang/Basic/DarwinSDKInfo.h @@ -105,6 +105,30 @@ class DarwinSDKInfo { map(const VersionTuple , const VersionTuple , std::optional MaximumValue) const; +/// Remap the 'introduced' availability version. +/// If None is returned, the 'unavailable' availability should be used +/// instead. +std::optional +mapIntroducedAvailabilityVersion(const VersionTuple ) const { + // API_TO_BE_DEPRECATED is 10. + if (Key.getMajor() == 10) +return VersionTuple(10); + // Use None for maximum to force unavailable behavior for + return map(Key, MinimumValue, std::nullopt); +} + +/// Remap the 'deprecated' and 'obsoleted' availability version. +/// If None is returned for 'obsoleted', the 'unavailable' availability +/// should be used instead. If None is returned for 'deprecated', the +/// 'deprecated' version should be dropped. +std::optional +mapDeprecatedObsoletedAvailabilityVersion(const VersionTuple ) const { + // API_TO_BE_DEPRECATED is 10. + if (Key.getMajor() == 10) +return VersionTuple(10); + return map(Key, MinimumValue, MaximumValue); +} + static std::optional parseJSON(const llvm::json::Object , VersionTuple MaximumDeploymentTarget); diff --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp index 81f1c711269445..ee377b70964a28 100644 --- a/clang/lib/Parse/ParseDecl.cpp +++ b/clang/lib/Parse/ParseDecl.cpp @@ -1234,8 +1234,11 @@ void Parser::ParseAvailabilityAttribute( } IdentifierLoc *Platform = ParseIdentifierLoc(); if (const IdentifierInfo *const Ident = Platform->Ident) { +// Disallow xrOS for availability attributes. +if (Ident->getName().contains("xrOS") || Ident->getName().contains("xros")) + Diag(Platform->Loc, diag::warn_availability_unknown_platform) << Ident; // Canonicalize platform name from "macosx" to "macos". -if (Ident->getName() == "macosx") +else if (Ident->getName() == "macosx")
[clang] [clang] Upstream visionOS Availability & DarwinSDKInfo APIs (PR #84279)
https://github.com/cyndyishida created https://github.com/llvm/llvm-project/pull/84279 Admittedly a bit awkward, `visionos` is the correct and accepted spelling for annotating availability for xrOS target triples. This patch detects errors and handles cases when `xros` is mistakenly passed. In addition, add APIs for introduced/deprecated/obsoleted versioning in DarwinSDKInfo mappings. >From 64ff809b6325c9b6d4f957c9bbc2d9ffc83eaa15 Mon Sep 17 00:00:00 2001 From: Cyndy Ishida Date: Wed, 6 Mar 2024 20:29:30 -0800 Subject: [PATCH 1/2] [clang] Support availability annotations for visionOS Admittently a bit awkward, `visionos` is the correct and accepted spelling for annotating availability for xros target triples. This patch detects errors and handles cases when `xros` is mistakenly passed. --- clang/include/clang/Basic/Attr.td| 8 clang/lib/Parse/ParseDecl.cpp| 5 ++- clang/lib/Parse/ParseExpr.cpp| 3 +- clang/test/Sema/attr-availability-visionos.c | 39 4 files changed, 53 insertions(+), 2 deletions(-) create mode 100644 clang/test/Sema/attr-availability-visionos.c diff --git a/clang/include/clang/Basic/Attr.td b/clang/include/clang/Basic/Attr.td index fa191c7378dba4..ebb616fbe253fc 100644 --- a/clang/include/clang/Basic/Attr.td +++ b/clang/include/clang/Basic/Attr.td @@ -983,6 +983,8 @@ def Availability : InheritableAttr { .Case("watchos_app_extension", "watchOS (App Extension)") .Case("maccatalyst", "macCatalyst") .Case("maccatalyst_app_extension", "macCatalyst (App Extension)") + .Case("xros", "visionOS") + .Case("xros_app_extension", "visionOS (App Extension)") .Case("swift", "Swift") .Case("shadermodel", "HLSL ShaderModel") .Case("ohos", "OpenHarmony OS") @@ -1000,6 +1002,8 @@ static llvm::StringRef getPlatformNameSourceSpelling(llvm::StringRef Platform) { .Case("watchos_app_extension", "watchOSApplicationExtension") .Case("maccatalyst", "macCatalyst") .Case("maccatalyst_app_extension", "macCatalystApplicationExtension") + .Case("xros", "visionOS") + .Case("xros_app_extension", "visionOSApplicationExtension") .Case("zos", "z/OS") .Case("shadermodel", "ShaderModel") .Default(Platform); @@ -1016,6 +1020,10 @@ static llvm::StringRef canonicalizePlatformName(llvm::StringRef Platform) { .Case("watchOSApplicationExtension", "watchos_app_extension") .Case("macCatalyst", "maccatalyst") .Case("macCatalystApplicationExtension", "maccatalyst_app_extension") + .Case("visionOS", "xros") + .Case("visionOSApplicationExtension", "xros_app_extension") + .Case("visionos", "xros") + .Case("visionos_app_extension", "xros_app_extension") .Case("ShaderModel", "shadermodel") .Default(Platform); } }]; diff --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp index 81f1c711269445..ee377b70964a28 100644 --- a/clang/lib/Parse/ParseDecl.cpp +++ b/clang/lib/Parse/ParseDecl.cpp @@ -1234,8 +1234,11 @@ void Parser::ParseAvailabilityAttribute( } IdentifierLoc *Platform = ParseIdentifierLoc(); if (const IdentifierInfo *const Ident = Platform->Ident) { +// Disallow xrOS for availability attributes. +if (Ident->getName().contains("xrOS") || Ident->getName().contains("xros")) + Diag(Platform->Loc, diag::warn_availability_unknown_platform) << Ident; // Canonicalize platform name from "macosx" to "macos". -if (Ident->getName() == "macosx") +else if (Ident->getName() == "macosx") Platform->Ident = PP.getIdentifierInfo("macos"); // Canonicalize platform name from "macosx_app_extension" to // "macos_app_extension". diff --git a/clang/lib/Parse/ParseExpr.cpp b/clang/lib/Parse/ParseExpr.cpp index 4bf954b5cc4db5..1f07eddb0fb378 100644 --- a/clang/lib/Parse/ParseExpr.cpp +++ b/clang/lib/Parse/ParseExpr.cpp @@ -3863,7 +3863,8 @@ std::optional Parser::ParseAvailabilitySpec() { StringRef Platform = AvailabilityAttr::canonicalizePlatformName(GivenPlatform); -if (AvailabilityAttr::getPrettyPlatformName(Platform).empty()) { +if (AvailabilityAttr::getPrettyPlatformName(Platform).empty() || +(GivenPlatform.contains("xros") || GivenPlatform.contains("xrOS"))) { Diag(PlatformIdentifier->Loc, diag::err_avail_query_unrecognized_platform_name) << GivenPlatform; diff --git a/clang/test/Sema/attr-availability-visionos.c b/clang/test/Sema/attr-availability-visionos.c new file mode 100644 index 00..2c388c5d529073 --- /dev/null +++ b/clang/test/Sema/attr-availability-visionos.c @@ -0,0 +1,39 @@ +// RUN: %clang_cc1 -triple arm64-apple-xros1 -fapplication-extension -verify=visionos %s 2>&1 +
[clang] [C++20][Coroutines] Lambda-coroutine with operator new in promise_type (PR #84193)
@@ -1434,13 +1434,18 @@ ExprResult Sema::ActOnCXXThis(SourceLocation Loc) { return Diag(Loc, diag::err_invalid_this_use) << 0; } - return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false); + return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false, + SkipLambdaCaptureCheck); } -Expr *Sema::BuildCXXThisExpr(SourceLocation Loc, QualType Type, - bool IsImplicit) { +Expr *Sema::BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit, + bool SkipLambdaCaptureCheck) { auto *This = CXXThisExpr::Create(Context, Loc, Type, IsImplicit); - MarkThisReferenced(This); + + if (!SkipLambdaCaptureCheck) { shafik wrote: Can we provide a standard reference for this code that justifies why we skip this check here? https://github.com/llvm/llvm-project/pull/84193 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [C++20][Coroutines] Lambda-coroutine with operator new in promise_type (PR #84193)
@@ -0,0 +1,54 @@ +// RUN: %clang_cc1 -fsyntax-only -verify -I%S/Inputs -std=c++20 %s + +// expected-no-diagnostics + +#include "std-coroutine.h" + +using size_t = decltype(sizeof(0)); + +struct Generator { + struct promise_type { +int _val{}; + +Generator get_return_object() noexcept +{ + return {}; +} + +std::suspend_never initial_suspend() noexcept +{ + return {}; +} + +std::suspend_always final_suspend() noexcept +{ + return {}; +} + +void return_void() noexcept {} +void unhandled_exception() noexcept {} + +template +static void* +operator new(size_t size, + This&, + TheRest&&...) noexcept +{ +return nullptr; +} + +static void operator delete(void*, size_t) +{ +} + }; +}; + +int main() +{ + auto lamb = []() -> Generator { shafik wrote: What should happen if the lambda has a capture? Is it allowed? https://github.com/llvm/llvm-project/pull/84193 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Add some CodeGen tests for CWG 4xx issues (PR #83715)
https://github.com/shafik commented: Late review but LGTM https://github.com/llvm/llvm-project/pull/83715 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [RISCV][Clang] Added builtin support for experimental Zimop extension (PR #79971)
jrtc27 wrote: Surely we should instead be defining intrinsics with actual names for the operations we know about? What's the actual use case for needing an arbitrary unnamed one? https://github.com/llvm/llvm-project/pull/79971 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [RISCV][Clang] Added builtin support for experimental Zimop extension (PR #79971)
https://github.com/wangpc-pp commented: The code is OK I think. One question: how will these builtins be used? Are their semantics bound to specific extensions that extend MOPs? https://github.com/llvm/llvm-project/pull/79971 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [X86] Add Support for X86 TLSDESC Relocations (PR #83136)
@@ -0,0 +1,165 @@ +; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py UTC_ARGS: --version 4 +; RUN: llc < %s -mtriple=i686-unknown-unknown --relocation-model=pic -enable-tlsdesc | FileCheck %s --check-prefix=X86 +; RUN: llc < %s -mtriple=x86_64-pc-linux-gnux32 --relocation-model=pic -enable-tlsdesc | FileCheck %s --check-prefix=X32 +; RUN: llc < %s -mtriple=x86_64-unknown-unknown --relocation-model=pic -enable-tlsdesc | FileCheck %s --check-prefix=X64 + +@x = thread_local global i32 0, align 4 +@y = internal thread_local global i32 0, align 4 phoebewang wrote: Added in `f5`. > The ideal thing is probably not to use `_TLS_MODULE_BASE_` when its result is > used only once in the function I think it is demonstrated by `f3`? https://github.com/llvm/llvm-project/pull/83136 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [X86] Add Support for X86 TLSDESC Relocations (PR #83136)
https://github.com/phoebewang updated https://github.com/llvm/llvm-project/pull/83136 >From cdc9ee6c322af0ceed162f3f714bcd0a22e020c3 Mon Sep 17 00:00:00 2001 From: Phoebe Wang Date: Tue, 27 Feb 2024 22:16:38 +0800 Subject: [PATCH 1/7] [X86] Add Support for X86 TLSDESC Relocations --- clang/lib/Driver/ToolChains/CommonArgs.cpp| 3 +- clang/test/Driver/tls-dialect.c | 2 +- .../lib/Target/X86/MCTargetDesc/X86BaseInfo.h | 14 ++ llvm/lib/Target/X86/X86AsmPrinter.cpp | 2 + llvm/lib/Target/X86/X86ISelLowering.cpp | 98 +++ llvm/lib/Target/X86/X86MCInstLower.cpp| 30 +++- llvm/test/CodeGen/X86/tls-desc.ll | 165 ++ 7 files changed, 273 insertions(+), 41 deletions(-) create mode 100644 llvm/test/CodeGen/X86/tls-desc.ll diff --git a/clang/lib/Driver/ToolChains/CommonArgs.cpp b/clang/lib/Driver/ToolChains/CommonArgs.cpp index faceee85a2f8dc..c66e3ee12e50c4 100644 --- a/clang/lib/Driver/ToolChains/CommonArgs.cpp +++ b/clang/lib/Driver/ToolChains/CommonArgs.cpp @@ -740,7 +740,8 @@ bool tools::isTLSDESCEnabled(const ToolChain , SupportedArgument = V == "desc" || V == "trad"; EnableTLSDESC = V == "desc"; } else if (Triple.isX86()) { -SupportedArgument = V == "gnu"; +SupportedArgument = V == "gnu" || V == "gnu2"; +EnableTLSDESC = V == "gnu2"; } else { Unsupported = true; } diff --git a/clang/test/Driver/tls-dialect.c b/clang/test/Driver/tls-dialect.c index f73915b28ec2a3..a808dd81531ce7 100644 --- a/clang/test/Driver/tls-dialect.c +++ b/clang/test/Driver/tls-dialect.c @@ -2,6 +2,7 @@ // RUN: %clang -### --target=riscv64-linux -mtls-dialect=trad %s 2>&1 | FileCheck --check-prefix=NODESC %s // RUN: %clang -### --target=riscv64-linux %s 2>&1 | FileCheck --check-prefix=NODESC %s // RUN: %clang -### --target=x86_64-linux -mtls-dialect=gnu %s 2>&1 | FileCheck --check-prefix=NODESC %s +// RUN: %clang -### --target=x86_64-linux -mtls-dialect=gnu2 %s 2>&1 | FileCheck --check-prefix=DESC %s /// Android supports TLSDESC by default on RISC-V /// TLSDESC is not on by default in Linux, even on RISC-V, and is covered above @@ -18,7 +19,6 @@ /// Unsupported argument // RUN: not %clang -### --target=riscv64-linux -mtls-dialect=gnu2 %s 2>&1 | FileCheck --check-prefix=UNSUPPORTED-ARG %s -// RUN: not %clang -### --target=x86_64-linux -mtls-dialect=gnu2 %s 2>&1 | FileCheck --check-prefix=UNSUPPORTED-ARG %s // DESC: "-cc1" {{.*}}"-enable-tlsdesc" // NODESC-NOT: "-enable-tlsdesc" diff --git a/llvm/lib/Target/X86/MCTargetDesc/X86BaseInfo.h b/llvm/lib/Target/X86/MCTargetDesc/X86BaseInfo.h index 4442b80861b61a..1877550f8c40bb 100644 --- a/llvm/lib/Target/X86/MCTargetDesc/X86BaseInfo.h +++ b/llvm/lib/Target/X86/MCTargetDesc/X86BaseInfo.h @@ -431,6 +431,20 @@ enum TOF { /// See 'ELF Handling for Thread-Local Storage' for more details. ///SYMBOL_LABEL @TLSLDM MO_TLSLDM, + /// MO_TLSCALL - On a symbol operand this indicates that the immediate is + /// the index of the TLS descriptor function for the symbol. Used in both + /// the IA32 and x86-64 local dynamic TLS access model. + /// See 'RFC-TLSDESC-x86' for more details. + ///SYMBOL_LABEL @TLSCALL + MO_TLSCALL, + /// MO_TLSDESC - On a symbol operand this indicates that the immediate is + /// the index of the TLS descriptor argument for the symbol. When this + /// argument is passed to a call getting from index@TLSCALL, the function will + /// return the offset for the symbol. Used in both the IA32 and x86-64 local + /// dynamic TLS access model. + /// See 'RFC-TLSDESC-x86' for more details. + ///SYMBOL_LABEL @TLSDESC + MO_TLSDESC, /// MO_GOTTPOFF - On a symbol operand this indicates that the immediate is /// the offset of the GOT entry with the thread-pointer offset for the /// symbol. Used in the x86-64 initial exec TLS access model. diff --git a/llvm/lib/Target/X86/X86AsmPrinter.cpp b/llvm/lib/Target/X86/X86AsmPrinter.cpp index 3395a13545e454..d8e111db1cec42 100644 --- a/llvm/lib/Target/X86/X86AsmPrinter.cpp +++ b/llvm/lib/Target/X86/X86AsmPrinter.cpp @@ -271,6 +271,8 @@ void X86AsmPrinter::PrintSymbolOperand(const MachineOperand , case X86II::MO_TLSGD: O << "@TLSGD"; break; case X86II::MO_TLSLD: O << "@TLSLD"; break; case X86II::MO_TLSLDM:O << "@TLSLDM";break; + case X86II::MO_TLSDESC: O << "@TLSDESC"; break; + case X86II::MO_TLSCALL: O << "@TLSCALL"; break; case X86II::MO_GOTTPOFF: O << "@GOTTPOFF"; break; case X86II::MO_INDNTPOFF: O << "@INDNTPOFF"; break; case X86II::MO_TPOFF: O << "@TPOFF"; break; diff --git a/llvm/lib/Target/X86/X86ISelLowering.cpp b/llvm/lib/Target/X86/X86ISelLowering.cpp index a86f13135173b0..88314bcf510e9a 100644 --- a/llvm/lib/Target/X86/X86ISelLowering.cpp +++ b/llvm/lib/Target/X86/X86ISelLowering.cpp @@ -18515,17 +18515,17 @@ X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG ) const {
[clang] [clang] Validate ABI tag attributes (PR #84272)
LocalSpook wrote: @erichkeane @AaronBallman https://github.com/llvm/llvm-project/pull/84272 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [X86] Add Support for X86 TLSDESC Relocations (PR #83136)
phoebewang wrote: > I assume that's what you're doing in the place I asked for a comment is > trying to avoid redundantly generating TLSDESC accesses for > _TLS_MODULE_BASE_. I see that we don't generate multiple accesses for > _TLS_MODULE_BASE_ in the test cases, but I thought that was only safe to do > when an earlier access dominates a later access. > > Is my understanding here correct, or is there an interaction with > > https://github.com/llvm/llvm-project/blob/04a271ebe4c2421f34a4fbf34c328df9f111/llvm/lib/Target/X86/X86InstrInfo.cpp#L10245 > > ? Yes, you are correct. I think SelectionDAG takes care of it. I checked it locally, it will generate two pairs of `_TLS_MODULE_BASE_` in `if ... else ...` branches respectively and one `_TLS_MODULE_BASE_` otherwise. I admit I didn't know the code here when adding it to GetTLSADDR. But I think not to create the nodes at the beginning is slightly better than to remove it later if they have the same output. Not to mention dominator iteration is expensive. https://github.com/llvm/llvm-project/pull/83136 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [X86] Finely handle target of __builtin_ia32_cmp[p|s][s|d] from avx into sse/sse2/avx (PR #84136)
FreddyLeaf wrote: > > > Still not understand. Shouldn't the target feature of the caller be > > > passed to the intrinsic when checking the argument of the intrinsic? > > > > > > The target features passing from option can be passed to Semachecking. It's > > special for attribute_target, which is handled in `handleTargetAttr`, which > > is after Sema::CheckBuiltinFunctionCall. > > Then why not move the call `handleTargetAttr` before > `Sema::CheckBuiltinFunctionCall`? Mainly because all Sema::CheckBuiltinFunctionCall before doesn't dependent on target feature, right? We don't have any other builtins have different range limit of same const parameter. But clang::CodegenFunction has the information of the whole function, which I think is a more reasonable place to do the check. https://github.com/llvm/llvm-project/pull/84136 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [X86] Finely handle target of __builtin_ia32_cmp[p|s][s|d] from avx into sse/sse2/avx (PR #84136)
KanRobert wrote: > > Still not understand. Shouldn't the target feature of the caller be passed > > to the intrinsic when checking the argument of the intrinsic? > > The target features passing from option can be passed to Semachecking. It's > special for attribute_target, which is handled in `handleTargetAttr`, which > is after Sema::CheckBuiltinFunctionCall. Then why not move the call `handleTargetAttr` before `Sema::CheckBuiltinFunctionCall`? https://github.com/llvm/llvm-project/pull/84136 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [alpha.webkit.UncountedLocalVarsChecker] Allow uncounted object references within trivial statements (PR #82229)
https://github.com/haoNoQ approved this pull request. LGTM! I think we have to look at the `DeclRefExpr` case more closely - something seems fishy about it, but also this isn't this patch's fault. https://github.com/llvm/llvm-project/pull/82229 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [alpha.webkit.UncountedLocalVarsChecker] Allow uncounted object references within trivial statements (PR #82229)
@@ -305,19 +337,21 @@ class TrivialFunctionAnalysisVisitor } bool VisitDeclRefExpr(const DeclRefExpr *DRE) { -if (auto *decl = DRE->getDecl()) { - if (isa(decl)) -return true; - if (isa(decl)) -return true; - if (auto *VD = dyn_cast(decl)) { -if (VD->hasConstantInitialization() && VD->getEvaluatedValue()) +return WithCachedResult(DRE, [&]() { + if (auto *decl = DRE->getDecl()) { +if (isa(decl)) return true; -auto *Init = VD->getInit(); -return !Init || Visit(Init); +if (isa(decl)) + return true; +if (auto *VD = dyn_cast(decl)) { + if (VD->hasConstantInitialization() && VD->getEvaluatedValue()) +return true; + auto *Init = VD->getInit(); + return !Init || Visit(Init); haoNoQ wrote: > Actually, we need to cache the results for `VisitDeclRefExpr` as well to > avoid infinite recursion. Wait, hmmm, this looks unusual. Why are we visiting the initializer whenever the variable is *accessed*? Isn't it sufficient to visit the initializer whenever the object is *initialized*? The initializer isn't evaluated at use site and it doesn't necessarily represent the contents of the variable anymore. Why do we care what the variable contained "initially"? It's good that we aren't doing it *every* time the variable is used (so we can treat it as an unrelated problem for another patch) but we probably weren't doing it at the right time in the first place. https://github.com/llvm/llvm-project/pull/82229 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [alpha.webkit.UncountedLocalVarsChecker] Allow uncounted object references within trivial statements (PR #82229)
https://github.com/haoNoQ edited https://github.com/llvm/llvm-project/pull/82229 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Validate ABI tag attributes (PR #84272)
https://github.com/LocalSpook edited https://github.com/llvm/llvm-project/pull/84272 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Validate ABI tag attributes (PR #84272)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Виктор Чернякин (LocalSpook) Changes This PR adds checks to make sure the ABI tag given in `[[gnu::abi_tag("")]]` attribute is valid. Example errors: ```text stdin:1:16: error: ABI tag cannot be empty 1 | [[gnu::abi_tag("")]] void f(); |^~ ``` ```text stdin:1:17: error: character '9' is not allowed at the start of an ABI tag 1 | [[gnu::abi_tag("99")]] void f(); | ^ ``` ```text stdin:1:18: error: character 'Ж' is not allowed in ABI tags 1 | [[gnu::abi_tag("AЖ")]] void f(); | ^ ``` The Itanium ABI specification says that an ABI tag can be any identifier, but this PR rejects tags with non-ASCII characters because I couldn't figure out a nice way of validating them. The code that validates identifiers (and supports Unicode, extensions like `$` in identifers, etc.) is private in Lexer, and special-casing `abi_tag` there seems incorrect to me. Eventually I decided to do the checks in `handleAbiTagAttr()` in Sema. I'm new here, so I could just be missing something. Fixes #83462. Relevant section of the Itanium ABI specification: https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangle.abi-tag --- I don't have commit permissions, so someone will have to commit for me. I'd like the author tag to be `Victor Chernyakin chernyakin.victor.j@outlook.com` (https://llvm.org/docs/DeveloperPolicy.html#obtaining-commit-access told me to say this). --- Full diff: https://github.com/llvm/llvm-project/pull/84272.diff 3 Files Affected: - (modified) clang/include/clang/Basic/DiagnosticSemaKinds.td (+4) - (modified) clang/lib/Sema/SemaDeclAttr.cpp (+30-1) - (added) clang/test/Sema/attr-abi-tag.cpp (+9) ``diff diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td index b007ff7d8ccf0f..18b8332ea7d329 100644 --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -5890,6 +5890,10 @@ def err_definition_of_explicitly_defaulted_member : Error< def err_redefinition_extern_inline : Error< "redefinition of a 'extern inline' function %0 is not supported in " "%select{C99 mode|C++}1">; +def err_empty_abi_tag : Error< + "ABI tag cannot be empty">; +def err_invalid_char_in_abi_tag : Error< + "character '%0' is not allowed %select{at the start of an ABI tag|in ABI tags}1">; def warn_attr_abi_tag_namespace : Warning< "'abi_tag' attribute on %select{non-inline|anonymous}0 namespace ignored">, InGroup; diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp index 397b5db0dc0669..b7423de07835f0 100644 --- a/clang/lib/Sema/SemaDeclAttr.cpp +++ b/clang/lib/Sema/SemaDeclAttr.cpp @@ -44,6 +44,7 @@ #include "llvm/ADT/StringExtras.h" #include "llvm/IR/Assumptions.h" #include "llvm/MC/MCSectionMachO.h" +#include "llvm/Support/ConvertUTF.h" #include "llvm/Support/Error.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/raw_ostream.h" @@ -7425,11 +7426,39 @@ static void handleMSConstexprAttr(Sema , Decl *D, const ParsedAttr ) { D->addAttr(::new (S.Context) MSConstexprAttr(S.Context, AL)); } +static bool checkValidAbiTag(Sema , const Expr *Exp, StringRef Tag) { + if (Tag.empty()) { +S.Diag(Exp->getExprLoc(), diag::err_empty_abi_tag) << Exp->getSourceRange(); +return false; + } + + for (size_t I = 0; I < Tag.size(); ++I) { +if (!isAsciiIdentifierContinue(Tag[I])) { + S.Diag(Exp->getBeginLoc().getLocWithOffset(1 + I), + diag::err_invalid_char_in_abi_tag) + << Tag.substr(I, llvm::getNumBytesForUTF8(Tag[I])) + << /*not allowed at all*/ 1; + return false; +} + } + + if (!isAsciiIdentifierStart(Tag[0])) { +S.Diag(Exp->getBeginLoc().getLocWithOffset(1), + diag::err_invalid_char_in_abi_tag) +<< Tag.substr(0, llvm::getNumBytesForUTF8(Tag[0])) +<< /*not allowed at the start*/ 0; +return false; + } + + return true; +} + static void handleAbiTagAttr(Sema , Decl *D, const ParsedAttr ) { SmallVector Tags; for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) { StringRef Tag; -if (!S.checkStringLiteralArgumentAttr(AL, I, Tag)) +if (!S.checkStringLiteralArgumentAttr(AL, I, Tag) || +!checkValidAbiTag(S, AL.getArgAsExpr(I), Tag)) return; Tags.push_back(Tag); } diff --git a/clang/test/Sema/attr-abi-tag.cpp b/clang/test/Sema/attr-abi-tag.cpp new file mode 100644 index 00..b4f3aade2027bd --- /dev/null +++ b/clang/test/Sema/attr-abi-tag.cpp @@ -0,0 +1,9 @@ +// RUN: %clang_cc1 -verify -fsyntax-only %s + +[[gnu::abi_tag("")]]void f1(); // expected-error {{ABI tag cannot be empty}} +[[gnu::abi_tag("9A")]] void f2(); // expected-error {{character '9' is not allowed at the start of an ABI tag}} +[[gnu::abi_tag("0")]] void f3(); // expected-error {{character '0' is not
[clang] [clang] Validate ABI tag attributes (PR #84272)
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/84272 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Validate ABI tag attributes (PR #84272)
https://github.com/LocalSpook created https://github.com/llvm/llvm-project/pull/84272 This PR adds checks to make sure the ABI tag given in `[[gnu::abi_tag("")]]` attribute is valid. Example errors: ```text :1:16: error: ABI tag cannot be empty 1 | [[gnu::abi_tag("")]] void f(); |^~ ``` ```text :1:17: error: character '9' is not allowed at the start of an ABI tag 1 | [[gnu::abi_tag("99")]] void f(); | ^ ``` ```text :1:18: error: character 'Ж' is not allowed in ABI tags 1 | [[gnu::abi_tag("AЖ")]] void f(); | ^ ``` The Itanium ABI specification says that an ABI tag can be any identifier, but this PR rejects tags with non-ASCII characters because I couldn't figure out a nice way of validating them. The code that validates identifiers (and supports Unicode, extensions like `$` in identifers, etc.) is private in Lexer, and special-casing `abi_tag` there seems incorrect to me. Eventually I decided to do the checks in `handleAbiTagAttr()` in Sema. I'm new here, so I could just be missing something. Fixes #83462. Relevant section of the Itanium ABI specification: https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangle.abi-tag --- I don't have commit permissions, so someone will have to commit for me. I'd like the author tag to be `Victor Chernyakin ` (https://llvm.org/docs/DeveloperPolicy.html#obtaining-commit-access told me to say this). From 944de3307437ae3fedfea0e46bca3ccd839f20fc Mon Sep 17 00:00:00 2001 From: Victor Chernyakin Date: Wed, 6 Mar 2024 04:38:42 -0800 Subject: [PATCH] [clang] Validate ABI tag attributes Before, ABI tags were not validated at all, which could lead to invalid manglings: [[gnu::abi_tag("")]]void f() -> _Z1fB0v [[gnu::abi_tag("999")]] void f() -> _Z1fB3999v [[gnu::abi_tag("-")]] void f() -> _Z1fB1-v Fixes #83462. --- .../clang/Basic/DiagnosticSemaKinds.td| 4 +++ clang/lib/Sema/SemaDeclAttr.cpp | 31 ++- clang/test/Sema/attr-abi-tag.cpp | 9 ++ 3 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 clang/test/Sema/attr-abi-tag.cpp diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td index b007ff7d8ccf0f..18b8332ea7d329 100644 --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -5890,6 +5890,10 @@ def err_definition_of_explicitly_defaulted_member : Error< def err_redefinition_extern_inline : Error< "redefinition of a 'extern inline' function %0 is not supported in " "%select{C99 mode|C++}1">; +def err_empty_abi_tag : Error< + "ABI tag cannot be empty">; +def err_invalid_char_in_abi_tag : Error< + "character '%0' is not allowed %select{at the start of an ABI tag|in ABI tags}1">; def warn_attr_abi_tag_namespace : Warning< "'abi_tag' attribute on %select{non-inline|anonymous}0 namespace ignored">, InGroup; diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp index 397b5db0dc0669..b7423de07835f0 100644 --- a/clang/lib/Sema/SemaDeclAttr.cpp +++ b/clang/lib/Sema/SemaDeclAttr.cpp @@ -44,6 +44,7 @@ #include "llvm/ADT/StringExtras.h" #include "llvm/IR/Assumptions.h" #include "llvm/MC/MCSectionMachO.h" +#include "llvm/Support/ConvertUTF.h" #include "llvm/Support/Error.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/raw_ostream.h" @@ -7425,11 +7426,39 @@ static void handleMSConstexprAttr(Sema , Decl *D, const ParsedAttr ) { D->addAttr(::new (S.Context) MSConstexprAttr(S.Context, AL)); } +static bool checkValidAbiTag(Sema , const Expr *Exp, StringRef Tag) { + if (Tag.empty()) { +S.Diag(Exp->getExprLoc(), diag::err_empty_abi_tag) << Exp->getSourceRange(); +return false; + } + + for (size_t I = 0; I < Tag.size(); ++I) { +if (!isAsciiIdentifierContinue(Tag[I])) { + S.Diag(Exp->getBeginLoc().getLocWithOffset(1 + I), + diag::err_invalid_char_in_abi_tag) + << Tag.substr(I, llvm::getNumBytesForUTF8(Tag[I])) + << /*not allowed at all*/ 1; + return false; +} + } + + if (!isAsciiIdentifierStart(Tag[0])) { +S.Diag(Exp->getBeginLoc().getLocWithOffset(1), + diag::err_invalid_char_in_abi_tag) +<< Tag.substr(0, llvm::getNumBytesForUTF8(Tag[0])) +<< /*not allowed at the start*/ 0; +return false; + } + + return true; +} + static void handleAbiTagAttr(Sema , Decl *D, const ParsedAttr ) { SmallVector Tags; for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) { StringRef Tag; -if (!S.checkStringLiteralArgumentAttr(AL, I, Tag)) +if (!S.checkStringLiteralArgumentAttr(AL, I, Tag) || +!checkValidAbiTag(S, AL.getArgAsExpr(I), Tag)) return; Tags.push_back(Tag); } diff --git a/clang/test/Sema/attr-abi-tag.cpp b/clang/test/Sema/attr-abi-tag.cpp new file mode 100644 index 00..b4f3aade2027bd ---
[clang] [X86] Finely handle target of __builtin_ia32_cmp[p|s][s|d] from avx into sse/sse2/avx (PR #84136)
FreddyLeaf wrote: > Still not understand. Shouldn't the target feature of the caller be passed to > the intrinsic when checking the argument of the intrinsic? The target features passing from option can be passed to Semachecking. It's special for attribute_target, which is handled in `handleTargetAttr`, which is after Sema::CheckBuiltinFunctionCall. https://github.com/llvm/llvm-project/pull/84136 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [X86] Finely handle target of __builtin_ia32_cmp[p|s][s|d] from avx into sse/sse2/avx (PR #84136)
KanRobert wrote: Still not understand. Shouldn't the target feature of the caller be passed to the intrinsic when checking the argument of the intrinsic? https://github.com/llvm/llvm-project/pull/84136 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [C++20][Coroutines] Lambda-coroutine with operator new in promise_type (PR #84193)
@@ -6898,10 +6898,18 @@ class Sema final { BinaryOperatorKind Operator); ActOnCXXThis - Parse 'this' pointer. - ExprResult ActOnCXXThis(SourceLocation loc); + /// + /// \param SkipLambdaCaptureCheck Whether to skip the 'this' check for a + /// lambda because 'this' is the lambda's 'this'-pointer. + ExprResult ActOnCXXThis(SourceLocation loc, + bool SkipLambdaCaptureCheck = false); ChuanqiXu9 wrote: Can we provide more rationale for skipping lambda's capture check here? For example, in what cases and for what reasons, we want to skip the check. I am still confused for that. https://github.com/llvm/llvm-project/pull/84193 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][Sema] Skip the RequiresExprBodyDecls for lambda dependencies (PR #83997)
https://github.com/zyn0217 closed https://github.com/llvm/llvm-project/pull/83997 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 9fe5aa3 - [clang][Sema] Skip the RequiresExprBodyDecls for lambda dependencies (#83997)
Author: Younan Zhang Date: 2024-03-07T09:49:02+08:00 New Revision: 9fe5aa31eccff49632e40bcdad6e64fc00190889 URL: https://github.com/llvm/llvm-project/commit/9fe5aa31eccff49632e40bcdad6e64fc00190889 DIFF: https://github.com/llvm/llvm-project/commit/9fe5aa31eccff49632e40bcdad6e64fc00190889.diff LOG: [clang][Sema] Skip the RequiresExprBodyDecls for lambda dependencies (#83997) The dependency of a lambda inside of a `RequiresExprBodyDecl` was previously affected by its parent, e.g., `ClassTemplateSpecializationDecl`. This made the lambda always dependent regardless of the template arguments we had, which caused some crashes on the constraint evaluation later. This fixes https://github.com/llvm/llvm-project/issues/56556, fixes https://github.com/llvm/llvm-project/issues/82849 and a case demonstrated by https://github.com/llvm/llvm-project/issues/49570#issuecomment-1664966972. Added: Modified: clang/docs/ReleaseNotes.rst clang/lib/Sema/TreeTransform.h clang/test/SemaTemplate/concepts-lambda.cpp Removed: diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index 942820a5268576..8300a8484585ae 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -319,6 +319,8 @@ Bug Fixes to C++ Support Fixes (#GH80630) - Fix a crash when an explicit template argument list is used with a name for which lookup finds a non-template function and a dependent using declarator. +- Fixed an issue where the ``RequiresExprBody`` was involved in the lambda dependency + calculation. (#GH56556), (#GH82849). - Fix a bug where overload resolution falsely reported an ambiguity when it was comparing a member-function against a non member function or a member-function with an explicit object parameter against a member function with no explicit object parameter diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h index 7389a48fe56fcc..409aee73d960eb 100644 --- a/clang/lib/Sema/TreeTransform.h +++ b/clang/lib/Sema/TreeTransform.h @@ -13649,10 +13649,29 @@ TreeTransform::TransformLambdaExpr(LambdaExpr *E) { // use evaluation contexts to distinguish the function parameter case. CXXRecordDecl::LambdaDependencyKind DependencyKind = CXXRecordDecl::LDK_Unknown; + DeclContext *DC = getSema().CurContext; + // A RequiresExprBodyDecl is not interesting for dependencies. + // For the following case, + // + // template + // concept C = requires { [] {}; }; + // + // template + // struct Widget; + // + // template + // struct Widget {}; + // + // While we are substituting Widget, the parent of DC would be + // the template specialization itself. Thus, the lambda expression + // will be deemed as dependent even if there are no dependent template + // arguments. + // (A ClassTemplateSpecializationDecl is always a dependent context.) + while (DC->getDeclKind() == Decl::Kind::RequiresExprBody) +DC = DC->getParent(); if ((getSema().isUnevaluatedContext() || getSema().isConstantEvaluatedContext()) && - (getSema().CurContext->isFileContext() || - !getSema().CurContext->getParent()->isDependentContext())) + (DC->isFileContext() || !DC->getParent()->isDependentContext())) DependencyKind = CXXRecordDecl::LDK_NeverDependent; CXXRecordDecl *OldClass = E->getLambdaClass(); diff --git a/clang/test/SemaTemplate/concepts-lambda.cpp b/clang/test/SemaTemplate/concepts-lambda.cpp index 0b7580f91043c7..fac790d09f9cf2 100644 --- a/clang/test/SemaTemplate/concepts-lambda.cpp +++ b/clang/test/SemaTemplate/concepts-lambda.cpp @@ -90,6 +90,64 @@ struct Foo { static_assert(ConstructibleWithN); +namespace GH56556 { + +template +inline constexpr It declare (); + +template typename Template> +concept D = requires { + { [] (Template &) {}(declare()) }; +}; + +template +struct B {}; + +template +struct Adapter; + +template T> +struct Adapter {}; + +template struct Adapter>; + +} // namespace GH56556 + +namespace GH82849 { + +template +concept C = requires(T t) { + requires requires (T u) { +[](V) { + return requires(V v) { +[](V w) {}(v); + }; +}(t); + }; +}; + +template +struct Widget; + +template +struct Widget { + static F create(F from) { +return from; + } +}; + +template +bool foo() { + return C; +} + +void bar() { + // https://github.com/llvm/llvm-project/issues/49570#issuecomment-1664966972 + Widget::create(0); +} + +} // namespace GH82849 + } // GH60642 reported an assert being hit, make sure we don't assert. ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][Sema] Skip the RequiresExprBodyDecls for lambda dependencies (PR #83997)
https://github.com/zyn0217 updated https://github.com/llvm/llvm-project/pull/83997 >From 69414d7352b170f6fcff22c6f5dfa91cc76b0b58 Mon Sep 17 00:00:00 2001 From: Younan Zhang Date: Tue, 5 Mar 2024 19:56:59 +0800 Subject: [PATCH 1/3] gh56556 --- clang/lib/Sema/TreeTransform.h | 6 -- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h index 7389a48fe56fcc..c96ffcb97a7591 100644 --- a/clang/lib/Sema/TreeTransform.h +++ b/clang/lib/Sema/TreeTransform.h @@ -13649,10 +13649,12 @@ TreeTransform::TransformLambdaExpr(LambdaExpr *E) { // use evaluation contexts to distinguish the function parameter case. CXXRecordDecl::LambdaDependencyKind DependencyKind = CXXRecordDecl::LDK_Unknown; + DeclContext *DC = getSema().CurContext; + if (DC->getDeclKind() == Decl::Kind::RequiresExprBody) +DC = DC->getParent(); if ((getSema().isUnevaluatedContext() || getSema().isConstantEvaluatedContext()) && - (getSema().CurContext->isFileContext() || - !getSema().CurContext->getParent()->isDependentContext())) + (DC->isFileContext() || !DC->getParent()->isDependentContext())) DependencyKind = CXXRecordDecl::LDK_NeverDependent; CXXRecordDecl *OldClass = E->getLambdaClass(); >From b905083e5d5186ad08ac3d553be3e8f47dabc1b6 Mon Sep 17 00:00:00 2001 From: Younan Zhang Date: Wed, 6 Mar 2024 13:46:43 +0800 Subject: [PATCH 2/3] Tests & release notes --- clang/docs/ReleaseNotes.rst | 2 + clang/lib/Sema/TreeTransform.h | 17 +++ clang/test/SemaTemplate/concepts-lambda.cpp | 52 + 3 files changed, 71 insertions(+) diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index d4e6bcf661da1a..141099fb68a200 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -302,6 +302,8 @@ Bug Fixes to C++ Support our attention by an attempt to fix in (#GH77703). Fixes (#GH83385). - Fix evaluation of some immediate calls in default arguments. Fixes (#GH80630) +- Fixed an issue where the ``RequiresExprBody`` was involved in the lambda dependency + calculation. (#GH56556), (#GH82849). Bug Fixes to AST Handling ^ diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h index c96ffcb97a7591..84348e13567e71 100644 --- a/clang/lib/Sema/TreeTransform.h +++ b/clang/lib/Sema/TreeTransform.h @@ -13650,6 +13650,23 @@ TreeTransform::TransformLambdaExpr(LambdaExpr *E) { CXXRecordDecl::LambdaDependencyKind DependencyKind = CXXRecordDecl::LDK_Unknown; DeclContext *DC = getSema().CurContext; + // A RequiresExprBodyDecl is not interesting for dependencies. + // For the following case, + // + // template + // concept C = requires { [] {}; }; + // + // template + // struct Widget; + // + // template + // struct Widget {}; + // + // While we are here in substitution for Widget, the parent of DC would be + // the template specialization itself. Thus, the lambda expression + // will be deemed as dependent even if we have non-dependent template + // arguments. + // (A ClassTemplateSpecializationDecl is always a dependent context.) if (DC->getDeclKind() == Decl::Kind::RequiresExprBody) DC = DC->getParent(); if ((getSema().isUnevaluatedContext() || diff --git a/clang/test/SemaTemplate/concepts-lambda.cpp b/clang/test/SemaTemplate/concepts-lambda.cpp index 0b7580f91043c7..ef04cad4eef98b 100644 --- a/clang/test/SemaTemplate/concepts-lambda.cpp +++ b/clang/test/SemaTemplate/concepts-lambda.cpp @@ -90,6 +90,58 @@ struct Foo { static_assert(ConstructibleWithN); +namespace GH56556 { + +template +inline constexpr It declare (); + +template typename Template> +concept D = requires { + { [] (Template &) {}(declare()) }; +}; + +template +struct B {}; + +template +struct Adapter; + +template T> +struct Adapter {}; + +template struct Adapter>; + +} // namespace GH56556 + +namespace GH82849 { + +template +concept C = requires(T t) { + [](T) {}(t); +}; + +template +struct Widget; + +template +struct Widget { + static F create(F from) { +return from; + } +}; + +template +bool foo() { + return C; +} + +void bar() { + // https://github.com/llvm/llvm-project/issues/49570#issuecomment-1664966972 + Widget::create(0); +} + +} // namespace GH82849 + } // GH60642 reported an assert being hit, make sure we don't assert. >From 6b36f74b6aede38766674c99a803c86becacd01d Mon Sep 17 00:00:00 2001 From: Younan Zhang Date: Wed, 6 Mar 2024 18:56:53 +0800 Subject: [PATCH 3/3] Address Corentin's comments --- clang/lib/Sema/TreeTransform.h | 6 +++--- clang/test/SemaTemplate/concepts-lambda.cpp | 8 +++- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h index 84348e13567e71..409aee73d960eb 100644 --- a/clang/lib/Sema/TreeTransform.h +++
[clang] [X86] Finely handle target of __builtin_ia32_cmp[p|s][s|d] from avx into sse/sse2/avx (PR #84136)
@@ -2613,6 +2614,24 @@ void CGBuilderInserter::InsertHelper( // called function. void CodeGenFunction::checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl) { + // SemaCheking cannot handle below x86 builtins because they have different + // parameter ranges with different TargetAttribute of caller. FreddyLeaf wrote: Updated in description. https://github.com/llvm/llvm-project/pull/84136 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [X86] Finely handle target of __builtin_ia32_cmp[p|s][s|d] from avx into sse/sse2/avx (PR #84136)
https://github.com/FreddyLeaf edited https://github.com/llvm/llvm-project/pull/84136 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [alpha.webkit.UncountedLocalVarsChecker] Allow uncounted object references within trivial statements (PR #82229)
@@ -189,18 +202,16 @@ class UncountedLocalVarsChecker dyn_cast_or_null(Ref->getFoundDecl())) { const auto *MaybeGuardianArgType = MaybeGuardian->getType().getTypePtr(); - if (!MaybeGuardianArgType) -return; - const CXXRecordDecl *const MaybeGuardianArgCXXRecord = - MaybeGuardianArgType->getAsCXXRecordDecl(); - if (!MaybeGuardianArgCXXRecord) -return; - - if (MaybeGuardian->isLocalVarDecl() && - (isRefCounted(MaybeGuardianArgCXXRecord) || - isRefcountedStringsHack(MaybeGuardian)) && - isGuardedScopeEmbeddedInGuardianScope(V, MaybeGuardian)) { -return; + if (MaybeGuardianArgType) { +const CXXRecordDecl *const MaybeGuardianArgCXXRecord = +MaybeGuardianArgType->getAsCXXRecordDecl(); +if (MaybeGuardianArgCXXRecord) { + if (MaybeGuardian->isLocalVarDecl() && + (isRefCounted(MaybeGuardianArgCXXRecord) || + isRefcountedStringsHack(MaybeGuardian)) && + isGuardedScopeEmbeddedInGuardianScope(V, MaybeGuardian)) +return; +} haoNoQ wrote: Oh right ok! https://github.com/llvm/llvm-project/pull/82229 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [X86] Finely handle target of __builtin_ia32_cmp[p|s][s|d] from avx into sse/sse2/avx (PR #84136)
@@ -4745,6 +4745,127 @@ static __inline__ __m128d __DEFAULT_FN_ATTRS _mm_castsi128_pd(__m128i __a) { return (__m128d)__a; } +/// Compares each of the corresponding double-precision values of two +///128-bit vectors of [2 x double], using the operation specified by the +///immediate integer operand. +/// +///Returns a [2 x double] vector consisting of two doubles corresponding to +///the two comparison results: zero if the comparison is false, and all 1's +///if the comparison is true. +/// +/// \headerfile +/// +/// \code +/// __m128d _mm_cmp_pd(__m128d a, __m128d b, const int c); +/// \endcode +/// +/// This intrinsic corresponds to the (V)CMPPD instruction. +/// +/// \param a +///A 128-bit vector of [2 x double]. +/// \param b +///A 128-bit vector of [2 x double]. +/// \param c +///An immediate integer operand, with bits [4:0] specifying which comparison FreddyLeaf wrote: Refined in 51eda069c797c91fd3072f347e1dd4a20ab53702 https://github.com/llvm/llvm-project/pull/84136 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [X86] Finely handle target of __builtin_ia32_cmp[p|s][s|d] from avx into sse/sse2/avx (PR #84136)
@@ -2940,6 +2940,134 @@ _mm_movemask_ps(__m128 __a) return __builtin_ia32_movmskps((__v4sf)__a); } +/* Compare */ +#define _CMP_EQ_OQ0x00 /* Equal (ordered, non-signaling) */ +#define _CMP_LT_OS0x01 /* Less-than (ordered, signaling) */ +#define _CMP_LE_OS0x02 /* Less-than-or-equal (ordered, signaling) */ +#define _CMP_UNORD_Q 0x03 /* Unordered (non-signaling) */ +#define _CMP_NEQ_UQ 0x04 /* Not-equal (unordered, non-signaling) */ +#define _CMP_NLT_US 0x05 /* Not-less-than (unordered, signaling) */ +#define _CMP_NLE_US 0x06 /* Not-less-than-or-equal (unordered, signaling) */ +#define _CMP_ORD_Q0x07 /* Ordered (non-signaling) */ + +/// Compares each of the corresponding values of two 128-bit vectors of +///[4 x float], using the operation specified by the immediate integer +///operand. +/// +///Returns a [4 x float] vector consisting of four floats corresponding to +///the four comparison results: zero if the comparison is false, and all 1's +///if the comparison is true. +/// +/// \headerfile +/// +/// \code +/// __m128 _mm_cmp_ps(__m128 a, __m128 b, const int c); +/// \endcode +/// +/// This intrinsic corresponds to the (V)CMPPS instruction. +/// +/// \param a +///A 128-bit vector of [4 x float]. +/// \param b +///A 128-bit vector of [4 x float]. +/// \param c +///An immediate integer operand, with bits [4:0] specifying which comparison +///operation to use: \n +///(Note that without avx enabled, only bits [2:0] are supported) \n +///0x00: Equal (ordered, non-signaling) \n +///0x01: Less-than (ordered, signaling) \n +///0x02: Less-than-or-equal (ordered, signaling) \n +///0x03: Unordered (non-signaling) \n +///0x04: Not-equal (unordered, non-signaling) \n +///0x05: Not-less-than (unordered, signaling) \n +///0x06: Not-less-than-or-equal (unordered, signaling) \n +///0x07: Ordered (non-signaling) \n +///0x08: Equal (unordered, non-signaling) \n +///0x09: Not-greater-than-or-equal (unordered, signaling) \n +///0x0A: Not-greater-than (unordered, signaling) \n +///0x0B: False (ordered, non-signaling) \n +///0x0C: Not-equal (ordered, non-signaling) \n +///0x0D: Greater-than-or-equal (ordered, signaling) \n +///0x0E: Greater-than (ordered, signaling) \n +///0x0F: True (unordered, non-signaling) \n +///0x10: Equal (ordered, signaling) \n +///0x11: Less-than (ordered, non-signaling) \n +///0x12: Less-than-or-equal (ordered, non-signaling) \n +///0x13: Unordered (signaling) \n +///0x14: Not-equal (unordered, signaling) \n +///0x15: Not-less-than (unordered, non-signaling) \n +///0x16: Not-less-than-or-equal (unordered, non-signaling) \n +///0x17: Ordered (signaling) \n +///0x18: Equal (unordered, signaling) \n +///0x19: Not-greater-than-or-equal (unordered, non-signaling) \n +///0x1A: Not-greater-than (unordered, non-signaling) \n +///0x1B: False (ordered, signaling) \n +///0x1C: Not-equal (ordered, signaling) \n +///0x1D: Greater-than-or-equal (ordered, non-signaling) \n +///0x1E: Greater-than (ordered, non-signaling) \n +///0x1F: True (unordered, signaling) FreddyLeaf wrote: Refined in 51eda069c797c91fd3072f347e1dd4a20ab53702 https://github.com/llvm/llvm-project/pull/84136 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [X86] Finely handle target of __builtin_ia32_cmp[p|s][s|d] from avx into sse/sse2/avx (PR #84136)
https://github.com/FreddyLeaf updated https://github.com/llvm/llvm-project/pull/84136 >From 2ba698b222fa1dc963d21850d5931562aa65533d Mon Sep 17 00:00:00 2001 From: Freddy Ye Date: Tue, 26 Sep 2023 16:44:01 +0800 Subject: [PATCH 1/5] [X86] Change target of __builtin_ia32_cmp[p|s][s|d] from avx into sse/sse2 --- clang/include/clang/Basic/BuiltinsX86.def | 8 +- clang/lib/Headers/avxintrin.h | 247 -- clang/lib/Headers/emmintrin.h | 121 + clang/lib/Headers/xmmintrin.h | 128 + clang/test/CodeGen/X86/avx-builtins.c | 96 --- .../test/CodeGen/X86/cmp-avx-builtins-error.c | 22 ++ clang/test/CodeGen/X86/sse-builtins.c | 54 clang/test/CodeGen/X86/sse2-builtins.c| 54 clang/test/CodeGen/target-features-error-2.c | 4 +- 9 files changed, 385 insertions(+), 349 deletions(-) create mode 100644 clang/test/CodeGen/X86/cmp-avx-builtins-error.c diff --git a/clang/include/clang/Basic/BuiltinsX86.def b/clang/include/clang/Basic/BuiltinsX86.def index 207cde0414b54e..eafcc219c10966 100644 --- a/clang/include/clang/Basic/BuiltinsX86.def +++ b/clang/include/clang/Basic/BuiltinsX86.def @@ -226,6 +226,8 @@ TARGET_BUILTIN(__builtin_ia32_minps, "V4fV4fV4f", "ncV:128:", "sse") TARGET_BUILTIN(__builtin_ia32_maxps, "V4fV4fV4f", "ncV:128:", "sse") TARGET_BUILTIN(__builtin_ia32_minss, "V4fV4fV4f", "ncV:128:", "sse") TARGET_BUILTIN(__builtin_ia32_maxss, "V4fV4fV4f", "ncV:128:", "sse") +TARGET_BUILTIN(__builtin_ia32_cmpps, "V4fV4fV4fIc", "ncV:128:", "sse") +TARGET_BUILTIN(__builtin_ia32_cmpss, "V4fV4fV4fIc", "ncV:128:", "sse") TARGET_BUILTIN(__builtin_ia32_cmpeqpd, "V2dV2dV2d", "ncV:128:", "sse2") TARGET_BUILTIN(__builtin_ia32_cmpltpd, "V2dV2dV2d", "ncV:128:", "sse2") @@ -243,6 +245,8 @@ TARGET_BUILTIN(__builtin_ia32_cmpneqsd, "V2dV2dV2d", "ncV:128:", "sse2") TARGET_BUILTIN(__builtin_ia32_cmpnltsd, "V2dV2dV2d", "ncV:128:", "sse2") TARGET_BUILTIN(__builtin_ia32_cmpnlesd, "V2dV2dV2d", "ncV:128:", "sse2") TARGET_BUILTIN(__builtin_ia32_cmpordsd, "V2dV2dV2d", "ncV:128:", "sse2") +TARGET_BUILTIN(__builtin_ia32_cmpsd, "V2dV2dV2dIc", "ncV:128:", "sse2") +TARGET_BUILTIN(__builtin_ia32_cmppd, "V2dV2dV2dIc", "ncV:128:", "sse2") TARGET_BUILTIN(__builtin_ia32_minpd, "V2dV2dV2d", "ncV:128:", "sse2") TARGET_BUILTIN(__builtin_ia32_maxpd, "V2dV2dV2d", "ncV:128:", "sse2") TARGET_BUILTIN(__builtin_ia32_minsd, "V2dV2dV2d", "ncV:128:", "sse2") @@ -462,12 +466,8 @@ TARGET_BUILTIN(__builtin_ia32_blendvps256, "V8fV8fV8fV8f", "ncV:256:", "avx") TARGET_BUILTIN(__builtin_ia32_shufpd256, "V4dV4dV4dIi", "ncV:256:", "avx") TARGET_BUILTIN(__builtin_ia32_shufps256, "V8fV8fV8fIi", "ncV:256:", "avx") TARGET_BUILTIN(__builtin_ia32_dpps256, "V8fV8fV8fIc", "ncV:256:", "avx") -TARGET_BUILTIN(__builtin_ia32_cmppd, "V2dV2dV2dIc", "ncV:128:", "avx") TARGET_BUILTIN(__builtin_ia32_cmppd256, "V4dV4dV4dIc", "ncV:256:", "avx") -TARGET_BUILTIN(__builtin_ia32_cmpps, "V4fV4fV4fIc", "ncV:128:", "avx") TARGET_BUILTIN(__builtin_ia32_cmpps256, "V8fV8fV8fIc", "ncV:256:", "avx") -TARGET_BUILTIN(__builtin_ia32_cmpsd, "V2dV2dV2dIc", "ncV:128:", "avx") -TARGET_BUILTIN(__builtin_ia32_cmpss, "V4fV4fV4fIc", "ncV:128:", "avx") TARGET_BUILTIN(__builtin_ia32_vextractf128_pd256, "V2dV4dIi", "ncV:256:", "avx") TARGET_BUILTIN(__builtin_ia32_vextractf128_ps256, "V4fV8fIi", "ncV:256:", "avx") TARGET_BUILTIN(__builtin_ia32_vextractf128_si256, "V4iV8iIi", "ncV:256:", "avx") diff --git a/clang/lib/Headers/avxintrin.h b/clang/lib/Headers/avxintrin.h index f116d8bc3a94c7..d6192518ea24ba 100644 --- a/clang/lib/Headers/avxintrin.h +++ b/clang/lib/Headers/avxintrin.h @@ -1573,15 +1573,6 @@ _mm256_blendv_ps(__m256 __a, __m256 __b, __m256 __c) ((__m256d)__builtin_ia32_shufpd256((__v4df)(__m256d)(a), \ (__v4df)(__m256d)(b), (int)(mask))) -/* Compare */ -#define _CMP_EQ_OQ0x00 /* Equal (ordered, non-signaling) */ -#define _CMP_LT_OS0x01 /* Less-than (ordered, signaling) */ -#define _CMP_LE_OS0x02 /* Less-than-or-equal (ordered, signaling) */ -#define _CMP_UNORD_Q 0x03 /* Unordered (non-signaling) */ -#define _CMP_NEQ_UQ 0x04 /* Not-equal (unordered, non-signaling) */ -#define _CMP_NLT_US 0x05 /* Not-less-than (unordered, signaling) */ -#define _CMP_NLE_US 0x06 /* Not-less-than-or-equal (unordered, signaling) */ -#define _CMP_ORD_Q0x07 /* Ordered (non-signaling) */ #define _CMP_EQ_UQ0x08 /* Equal (unordered, non-signaling) */ #define _CMP_NGE_US 0x09 /* Not-greater-than-or-equal (unordered, signaling) */ #define _CMP_NGT_US 0x0a /* Not-greater-than (unordered, signaling) */ @@ -1607,126 +1598,6 @@ _mm256_blendv_ps(__m256 __a, __m256 __b, __m256 __c) #define _CMP_GT_OQ0x1e /* Greater-than (ordered, non-signaling) */ #define _CMP_TRUE_US 0x1f /* True (unordered, signaling) */ -/// Compares each of the corresponding double-precision values of two -///
[clang-tools-extra] [clang-tidy] bugprone-assert-side-effect can detect side effect from non-const reference parameters (PR #84095)
https://github.com/HerrCai0907 closed https://github.com/llvm/llvm-project/pull/84095 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] 84842f4 - [clang-tidy] bugprone-assert-side-effect can detect side effect from non-const reference parameters (#84095)
Author: Congcong Cai Date: 2024-03-07T09:39:29+08:00 New Revision: 84842f4b3ba175d744c03d40baa8e371522615e8 URL: https://github.com/llvm/llvm-project/commit/84842f4b3ba175d744c03d40baa8e371522615e8 DIFF: https://github.com/llvm/llvm-project/commit/84842f4b3ba175d744c03d40baa8e371522615e8.diff LOG: [clang-tidy] bugprone-assert-side-effect can detect side effect from non-const reference parameters (#84095) Fixes: #84092 Added: Modified: clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp clang-tools-extra/docs/ReleaseNotes.rst clang-tools-extra/test/clang-tidy/checkers/bugprone/assert-side-effect.cpp Removed: diff --git a/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp index 43bedd4f73ef44..c650aae4fa03c0 100644 --- a/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp @@ -60,16 +60,26 @@ AST_MATCHER_P2(Expr, hasSideEffect, bool, CheckFunctionCalls, } if (const auto *CExpr = dyn_cast(E)) { -bool Result = CheckFunctionCalls; +if (!CheckFunctionCalls) + return false; if (const auto *FuncDecl = CExpr->getDirectCallee()) { if (FuncDecl->getDeclName().isIdentifier() && IgnoredFunctionsMatcher.matches(*FuncDecl, Finder, Builder)) // exceptions come here -Result = false; - else if (const auto *MethodDecl = dyn_cast(FuncDecl)) -Result &= !MethodDecl->isConst(); +return false; + for (size_t I = 0; I < FuncDecl->getNumParams(); I++) { +const ParmVarDecl *P = FuncDecl->getParamDecl(I); +const Expr *ArgExpr = +I < CExpr->getNumArgs() ? CExpr->getArg(I) : nullptr; +const QualType PT = P->getType().getCanonicalType(); +if (ArgExpr && !ArgExpr->isXValue() && PT->isReferenceType() && +!PT.getNonReferenceType().isConstQualified()) + return true; + } + if (const auto *MethodDecl = dyn_cast(FuncDecl)) +return !MethodDecl->isConst(); } -return Result; +return true; } return isa(E) || isa(E) || isa(E); diff --git a/clang-tools-extra/docs/ReleaseNotes.rst b/clang-tools-extra/docs/ReleaseNotes.rst index 1b839a35c3ed65..d98c4ff9a75044 100644 --- a/clang-tools-extra/docs/ReleaseNotes.rst +++ b/clang-tools-extra/docs/ReleaseNotes.rst @@ -128,6 +128,10 @@ New check aliases Changes in existing checks ^^ +- Improved :doc:`bugprone-assert-side-effect + ` check by detecting side + effect from calling a method with non-const reference parameters. + - Improved :doc:`bugprone-non-zero-enum-to-bool-conversion ` check by eliminating false positives resulting from direct usage of bitwise operators diff --git a/clang-tools-extra/test/clang-tidy/checkers/bugprone/assert-side-effect.cpp b/clang-tools-extra/test/clang-tidy/checkers/bugprone/assert-side-effect.cpp index c11638aa823aae..5cdc1afb3d9099 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/bugprone/assert-side-effect.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/bugprone/assert-side-effect.cpp @@ -108,3 +108,27 @@ int main() { return 0; } + +namespace parameter_anaylysis { + +struct S { + bool value(int) const; + bool leftValueRef(int &) const; + bool constRef(int const &) const; + bool rightValueRef(int &&) const; +}; + +void foo() { + S s{}; + int i = 0; + assert(s.value(0)); + assert(s.value(i)); + assert(s.leftValueRef(i)); + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: side effect in assert() condition discarded in release builds + assert(s.constRef(0)); + assert(s.constRef(i)); + assert(s.rightValueRef(0)); + assert(s.rightValueRef(static_cast(i))); +} + +} // namespace parameter_anaylysis ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] bugprone-assert-side-effect can detect side effect from non-const reference parameters (PR #84095)
https://github.com/HerrCai0907 updated https://github.com/llvm/llvm-project/pull/84095 >From 160add4d95f34608a3d423482ad50fb45f6db522 Mon Sep 17 00:00:00 2001 From: Congcong Cai Date: Wed, 6 Mar 2024 06:55:30 +0800 Subject: [PATCH 1/4] [clang-tidy][NFC]refactor AssertSideEffectCheck logic --- .../clang-tidy/bugprone/AssertSideEffectCheck.cpp | 11 ++- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp index 43bedd4f73ef44..25ca42bfd1bede 100644 --- a/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp @@ -60,16 +60,17 @@ AST_MATCHER_P2(Expr, hasSideEffect, bool, CheckFunctionCalls, } if (const auto *CExpr = dyn_cast(E)) { -bool Result = CheckFunctionCalls; +if (!CheckFunctionCalls) + return false; if (const auto *FuncDecl = CExpr->getDirectCallee()) { if (FuncDecl->getDeclName().isIdentifier() && IgnoredFunctionsMatcher.matches(*FuncDecl, Finder, Builder)) // exceptions come here -Result = false; - else if (const auto *MethodDecl = dyn_cast(FuncDecl)) -Result &= !MethodDecl->isConst(); +return false; + if (const auto *MethodDecl = dyn_cast(FuncDecl)) +return !MethodDecl->isConst(); } -return Result; +return true; } return isa(E) || isa(E) || isa(E); >From ce40ee88c708c8dcce8e5b2b9a1d000465e80c24 Mon Sep 17 00:00:00 2001 From: Congcong Cai Date: Wed, 6 Mar 2024 07:44:15 +0800 Subject: [PATCH 2/4] [clang-tidy] bugprone-assert-side-effect can detect side effect from non-const reference parameters Fixes: #84092 --- .../bugprone/AssertSideEffectCheck.cpp| 11 + clang-tools-extra/docs/ReleaseNotes.rst | 4 .../checkers/bugprone/assert-side-effect.cpp | 24 +++ 3 files changed, 39 insertions(+) diff --git a/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp index 25ca42bfd1bede..2111047b9dff7a 100644 --- a/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp +++ b/clang-tools-extra/clang-tidy/bugprone/AssertSideEffectCheck.cpp @@ -13,6 +13,7 @@ #include "clang/ASTMatchers/ASTMatchFinder.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Lex/Lexer.h" +#include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/Casting.h" @@ -67,6 +68,16 @@ AST_MATCHER_P2(Expr, hasSideEffect, bool, CheckFunctionCalls, IgnoredFunctionsMatcher.matches(*FuncDecl, Finder, Builder)) // exceptions come here return false; + for (size_t I = 0; I < FuncDecl->getNumParams(); I++) { +const ParmVarDecl *P = FuncDecl->getParamDecl(I); +const Expr *ArgExpr = +I < CExpr->getNumArgs() ? CExpr->getArg(I) : nullptr; +QualType PT = P->getType().getCanonicalType(); +if (PT->isReferenceType() && +!PT.getNonReferenceType().isConstQualified() && ArgExpr && +!ArgExpr->isXValue()) + return true; + } if (const auto *MethodDecl = dyn_cast(FuncDecl)) return !MethodDecl->isConst(); } diff --git a/clang-tools-extra/docs/ReleaseNotes.rst b/clang-tools-extra/docs/ReleaseNotes.rst index 0d2467210fc664..0d4d5ddb5c8763 100644 --- a/clang-tools-extra/docs/ReleaseNotes.rst +++ b/clang-tools-extra/docs/ReleaseNotes.rst @@ -122,6 +122,10 @@ New check aliases Changes in existing checks ^^ +- Improved :doc:`bugprone-assert-side-effect + ` check by detection side + effect from method call with non-const reference parameters. + - Improved :doc:`bugprone-non-zero-enum-to-bool-conversion ` check by eliminating false positives resulting from direct usage of bitwise operators diff --git a/clang-tools-extra/test/clang-tidy/checkers/bugprone/assert-side-effect.cpp b/clang-tools-extra/test/clang-tidy/checkers/bugprone/assert-side-effect.cpp index c11638aa823aae..5cdc1afb3d9099 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/bugprone/assert-side-effect.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/bugprone/assert-side-effect.cpp @@ -108,3 +108,27 @@ int main() { return 0; } + +namespace parameter_anaylysis { + +struct S { + bool value(int) const; + bool leftValueRef(int &) const; + bool constRef(int const &) const; + bool rightValueRef(int &&) const; +}; + +void foo() { + S s{}; + int i = 0; + assert(s.value(0)); + assert(s.value(i)); + assert(s.leftValueRef(i)); + // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: side effect in assert() condition discarded in release builds + assert(s.constRef(0)); + assert(s.constRef(i)); +
[clang] Turn 'counted_by' into a type attribute and parse it into 'CountAttributedType' (PR #78000)
https://github.com/rapidsna updated https://github.com/llvm/llvm-project/pull/78000 >From c39871ed2ec642ab00360f2c3a18fba7c915f82d Mon Sep 17 00:00:00 2001 From: Yeoul Na Date: Mon, 18 Dec 2023 10:58:16 +0900 Subject: [PATCH 1/8] [BoundsSafety] Introduce CountAttributedType CountAttributedType is a sugar type to represent a type with a 'counted_by' attribute and the likes, which provides bounds information to the underlying type. The type contains an the argument of attribute as an expression. Additionally, the type holds metadata about declarations referenced by the expression in order to make it easier for Sema to access declarations on which the type depends. This also adjusts the CountedBy attribute definition and implements parsing CountAttributedType. __bdos and array-checks sanitizer use CountAttributedType instead of hasAttr. Implements special lookup for counted_by argument in structs. Adjust test/Sema/attr-counted-by.c to match the default diags generated by the expression parser. --- clang/include/clang/AST/ASTContext.h | 7 + clang/include/clang/AST/PropertiesBase.td | 1 + clang/include/clang/AST/RecursiveASTVisitor.h | 9 + clang/include/clang/AST/Type.h| 152 +++ clang/include/clang/AST/TypeLoc.h | 26 +++ clang/include/clang/AST/TypeProperties.td | 19 ++ clang/include/clang/Basic/Attr.td | 7 +- .../clang/Basic/DiagnosticSemaKinds.td| 14 +- clang/include/clang/Basic/TypeNodes.td| 2 + clang/include/clang/Parse/Parser.h| 5 + clang/include/clang/Sema/Sema.h | 16 +- .../clang/Serialization/ASTRecordReader.h | 2 + .../clang/Serialization/ASTRecordWriter.h | 5 + .../clang/Serialization/TypeBitCodes.def | 2 +- clang/lib/AST/ASTContext.cpp | 55 ++ clang/lib/AST/ASTImporter.cpp | 22 +++ clang/lib/AST/ASTStructuralEquivalence.cpp| 7 + clang/lib/AST/ItaniumMangle.cpp | 1 + clang/lib/AST/Type.cpp| 65 +++ clang/lib/AST/TypeLoc.cpp | 4 + clang/lib/AST/TypePrinter.cpp | 30 +++ clang/lib/CodeGen/CGBuiltin.cpp | 6 +- clang/lib/CodeGen/CGDebugInfo.cpp | 1 + clang/lib/CodeGen/CGExpr.cpp | 37 +--- clang/lib/CodeGen/CodeGenFunction.cpp | 1 + clang/lib/Parse/ParseDecl.cpp | 90 + clang/lib/Sema/SemaDecl.cpp | 6 - clang/lib/Sema/SemaDeclAttr.cpp | 183 -- clang/lib/Sema/SemaExpr.cpp | 25 ++- clang/lib/Sema/SemaType.cpp | 12 ++ clang/lib/Sema/TreeTransform.h| 7 + clang/lib/Serialization/ASTReader.cpp | 8 + clang/lib/Serialization/ASTWriter.cpp | 4 + clang/test/Sema/attr-counted-by.c | 20 +- clang/tools/libclang/CIndex.cpp | 4 + 35 files changed, 692 insertions(+), 163 deletions(-) diff --git a/clang/include/clang/AST/ASTContext.h b/clang/include/clang/AST/ASTContext.h index 12ce9af1e53f63..08795af245c06b 100644 --- a/clang/include/clang/AST/ASTContext.h +++ b/clang/include/clang/AST/ASTContext.h @@ -250,6 +250,8 @@ class ASTContext : public RefCountedBase { DependentBitIntTypes; llvm::FoldingSet BTFTagAttributedTypes; + mutable llvm::FoldingSet CountAttributedTypes; + mutable llvm::FoldingSet QualifiedTemplateNames; mutable llvm::FoldingSet DependentTemplateNames; mutable llvm::FoldingSet @@ -1341,6 +1343,11 @@ class ASTContext : public RefCountedBase { return CanQualType::CreateUnsafe(getPointerType((QualType) T)); } + QualType + getCountAttributedType(QualType T, Expr *CountExpr, bool CountInBytes, + bool OrNull, + ArrayRef DependentDecls) const; + /// Return the uniqued reference to a type adjusted from the original /// type to a new type. QualType getAdjustedType(QualType Orig, QualType New) const; diff --git a/clang/include/clang/AST/PropertiesBase.td b/clang/include/clang/AST/PropertiesBase.td index 0270c086d06b6a..6df1d93a7ba2eb 100644 --- a/clang/include/clang/AST/PropertiesBase.td +++ b/clang/include/clang/AST/PropertiesBase.td @@ -143,6 +143,7 @@ def UInt32 : CountPropertyType<"uint32_t">; def UInt64 : CountPropertyType<"uint64_t">; def UnaryTypeTransformKind : EnumPropertyType<"UnaryTransformType::UTTKind">; def VectorKind : EnumPropertyType<"VectorKind">; +def TypeCoupledDeclRefInfo : PropertyType; def ExceptionSpecInfo : PropertyType<"FunctionProtoType::ExceptionSpecInfo"> { let BufferElementTypes = [ QualType ]; diff --git a/clang/include/clang/AST/RecursiveASTVisitor.h b/clang/include/clang/AST/RecursiveASTVisitor.h index 9da5206a21c34c..b058e0435912eb 100644 --- a/clang/include/clang/AST/RecursiveASTVisitor.h +++
[clang] Turn 'counted_by' into a type attribute and parse it into 'CountAttributedType' (PR #78000)
rapidsna wrote: @AaronBallman thanks for the review! I addressed your comments. https://github.com/llvm/llvm-project/pull/78000 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [X86] Finely handle target of __builtin_ia32_cmp[p|s][s|d] from avx into sse/sse2/avx (PR #84136)
@@ -34,6 +34,60 @@ __m128 test_mm_andnot_ps(__m128 A, __m128 B) { return _mm_andnot_ps(A, B); } +__m128 test_mm_cmp_ps_eq_oq(__m128 a, __m128 b) { + // CHECK-LABEL: test_mm_cmp_ps_eq_oq + // CHECK: fcmp oeq <4 x float> %{{.*}}, %{{.*}} + return _mm_cmp_ps(a, b, _CMP_EQ_OQ); FreddyLeaf wrote: Oh the remaining 24 are already there. So I only moved the first 8 from avx to sse/sse2. which is expected. https://github.com/llvm/llvm-project/pull/84136 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Turn 'counted_by' into a type attribute and parse it into 'CountAttributedType' (PR #78000)
@@ -2000,6 +2001,21 @@ class alignas(TypeAlignment) Type : public ExtQualsTypeCommonBase { unsigned NumExpansions; }; + class CountAttributedTypeBitfields { +friend class CountAttributedType; + +LLVM_PREFERRED_TYPE(TypeBitfields) +unsigned : NumTypeBits; + +/// The limit is 15. rapidsna wrote: Thanks! I added `static_assert` and removed the comment. https://github.com/llvm/llvm-project/pull/78000 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Turn 'counted_by' into a type attribute and parse it into 'CountAttributedType' (PR #78000)
@@ -1117,6 +1117,32 @@ class ObjCInterfaceTypeLoc : public ConcreteTypeLoc { +public: + TypeLoc getInnerLoc() const { return this->getInnerTypeLoc(); } + QualType getInnerType() const { return this->getTypePtr()->desugar(); } + void initializeLocal(ASTContext , SourceLocation Loc) { +// nothing to do + } + unsigned getLocalDataAlignment() const { return 1; } + unsigned getLocalDataSize() const { return 0; } rapidsna wrote: I think you're right. I just removed them. https://github.com/llvm/llvm-project/pull/78000 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Turn 'counted_by' into a type attribute and parse it into 'CountAttributedType' (PR #78000)
@@ -4259,7 +4240,7 @@ LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E, if (const auto *ME = dyn_cast(Array); ME && ME->isFlexibleArrayMemberLike(getContext(), StrictFlexArraysLevel) && - ME->getMemberDecl()->hasAttr()) { + ME->getMemberDecl()->getType()->getAs()) { rapidsna wrote: `ME->getMemberDecl()->getType()` might be wrapped in another sugar type, so `isa` might not work in that case. To deal with that, I just added `isCountAttributedType()`. https://github.com/llvm/llvm-project/pull/78000 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Turn 'counted_by' into a type attribute and parse it into 'CountAttributedType' (PR #78000)
@@ -13233,6 +13262,32 @@ static QualType getCommonSugarTypeNode(ASTContext , const Type *X, return QualType(); return Ctx.getUsingType(CD, Ctx.getQualifiedType(Underlying)); } + case Type::CountAttributed: { +const auto *DX = cast(X), + *DY = cast(Y); +if (DX->isCountInBytes() != DY->isCountInBytes()) + return QualType(); +if (DX->isOrNull() != DY->isOrNull()) + return QualType(); +const auto CEX = DX->getCountExpr(); +const auto CEY = DY->getCountExpr(); +const auto CDX = DX->getCoupledDecls(); rapidsna wrote: Done! https://github.com/llvm/llvm-project/pull/78000 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Turn 'counted_by' into a type attribute and parse it into 'CountAttributedType' (PR #78000)
@@ -7239,6 +7239,13 @@ QualType TreeTransform::TransformAttributedType(TypeLocBuilder , }); } +template +QualType TreeTransform::TransformCountAttributedType( +TypeLocBuilder , CountAttributedTypeLoc TL) { + // TODO + llvm_unreachable("Unexpected TreeTransform for CountAttributedType"); rapidsna wrote: @AaronBallman thanks for letting me know. I just implemented `TransformCountAttributedType`. I'll see if I can fine a test case to exercise this. https://github.com/llvm/llvm-project/pull/78000 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][analyzer] Fix StreamChecker `ftell` and `fgetpos` at indeterminate file position. (PR #84191)
@@ -880,6 +883,24 @@ void StreamChecker::preReadWrite(const FnDescription *Desc, } } +void StreamChecker::preWrite(const FnDescription *Desc, const CallEvent , benshi001 wrote: Why we need a separated `preWrite` ? The original `preReadWrite` also works. https://github.com/llvm/llvm-project/pull/84191 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [X86] Finely handle target of __builtin_ia32_cmp[p|s][s|d] from avx into sse/sse2/avx (PR #84136)
@@ -2613,6 +2614,24 @@ void CGBuilderInserter::InsertHelper( // called function. void CodeGenFunction::checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl) { + // SemaCheking cannot handle below x86 builtins because they have different + // parameter ranges with different TargetAttribute of caller. KanRobert wrote: I see. They corresponds to different instructions. https://github.com/llvm/llvm-project/pull/84136 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [alpha.webkit.UncountedLocalVarsChecker] Allow uncounted object references within trivial statements (PR #82229)
https://github.com/rniwa updated https://github.com/llvm/llvm-project/pull/82229 >From 234e301ab2721ddb2f4b43589785015a7d0aa304 Mon Sep 17 00:00:00 2001 From: Ryosuke Niwa Date: Mon, 19 Feb 2024 01:07:13 -0800 Subject: [PATCH 1/8] [alpha.webkit.UncountedLocalVarsChecker] Allow uncounted object references within trivial statements This PR makes alpha.webkit.UncountedLocalVarsChecker ignore raw references and pointers to a ref counted type which appears within "trival" statements. To do this, this PR extends TrivialFunctionAnalysis so that it can also analyze "triviality" of statements as well as that of functions Each Visit* function is now augmented with withCachedResult, which is responsible for looking up and updating the cache for each Visit* functions. As this PR dramatically improves the false positive rate of the checker, it also deletes the code to ignore raw pointers and references within if and for statements. --- .../Checkers/WebKit/PtrTypesSemantics.cpp | 222 -- .../Checkers/WebKit/PtrTypesSemantics.h | 21 +- .../WebKit/UncountedLocalVarsChecker.cpp | 69 +++--- .../Analysis/Checkers/WebKit/mock-types.h | 2 + .../Checkers/WebKit/uncounted-local-vars.cpp | 92 +++- 5 files changed, 285 insertions(+), 121 deletions(-) diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp index 01b191ab0eeaf4..6c9a8aedb38a4c 100644 --- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp @@ -245,18 +245,41 @@ class TrivialFunctionAnalysisVisitor // Returns false if at least one child is non-trivial. bool VisitChildren(const Stmt *S) { -for (const Stmt *Child : S->children()) { - if (Child && !Visit(Child)) +return withCachedResult(S, [&]() { + for (const Stmt *Child : S->children()) { +if (Child && !Visit(Child)) + return false; + } + return true; +}); + } + + bool VisitSubExpr(const Expr *Parent, const Expr *E) { +return withCachedResult(Parent, [&]() { + if (!Visit(E)) return false; -} + return true; +}); + } -return true; + template + bool withCachedResult(const StmtType *S, CheckFunction Function) { +// Insert false to the cache first to avoid infinite recursion. +auto [It, IsNew] = StatementCache.insert(std::make_pair(S, false)); +if (!IsNew) + return It->second; +bool Result = Function(); +It->second = Result; +return Result; } public: - using CacheTy = TrivialFunctionAnalysis::CacheTy; + using FunctionCacheTy = TrivialFunctionAnalysis::FunctionCacheTy; + using StatementCacheTy = TrivialFunctionAnalysis::StatementCacheTy; - TrivialFunctionAnalysisVisitor(CacheTy ) : Cache(Cache) {} + TrivialFunctionAnalysisVisitor(FunctionCacheTy , + StatementCacheTy ) + : FunctionCache(FunctionCache), StatementCache(StatementCache) {} bool VisitStmt(const Stmt *S) { // All statements are non-trivial unless overriden later. @@ -272,13 +295,21 @@ class TrivialFunctionAnalysisVisitor bool VisitReturnStmt(const ReturnStmt *RS) { // A return statement is allowed as long as the return value is trivial. -if (auto *RV = RS->getRetValue()) - return Visit(RV); -return true; +return withCachedResult(RS, [&]() { + if (auto *RV = RS->getRetValue()) +return Visit(RV); + return true; +}); + } + + bool VisitCXXForRangeStmt(const CXXForRangeStmt *FS) { +return VisitChildren(FS); } bool VisitDeclStmt(const DeclStmt *DS) { return VisitChildren(DS); } bool VisitDoStmt(const DoStmt *DS) { return VisitChildren(DS); } + bool VisitForStmt(const ForStmt *FS) { return VisitChildren(FS); } + bool VisitWhileStmt(const WhileStmt *WS) { return VisitChildren(WS); } bool VisitIfStmt(const IfStmt *IS) { return VisitChildren(IS); } bool VisitSwitchStmt(const SwitchStmt *SS) { return VisitChildren(SS); } bool VisitCaseStmt(const CaseStmt *CS) { return VisitChildren(CS); } @@ -286,17 +317,26 @@ class TrivialFunctionAnalysisVisitor bool VisitUnaryOperator(const UnaryOperator *UO) { // Operator '*' and '!' are allowed as long as the operand is trivial. -if (UO->getOpcode() == UO_Deref || UO->getOpcode() == UO_AddrOf || -UO->getOpcode() == UO_LNot) - return Visit(UO->getSubExpr()); - -// Other operators are non-trivial. -return false; +return withCachedResult(UO, [&]() { + auto op = UO->getOpcode(); + if (op == UO_Deref || op == UO_AddrOf || op == UO_LNot) +return Visit(UO->getSubExpr()); + if (UO->isIncrementOp() || UO->isDecrementOp()) { +if (auto *RefExpr = dyn_cast(UO->getSubExpr())) { + if (auto *Decl = dyn_cast(RefExpr->getDecl())) +return Decl->isLocalVarDeclOrParm() && +
[clang] [Clang] Update value for __cpp_implicit_move (#84216) (PR #84228)
frederick-vs-ja wrote: [This page](https://clang.llvm.org/cxx_status.html) still refers to [P2266R1](https://wg21.link/p2266r1) but the approved revision is [P2266R3](https://wg21.link/p2266r3). Should we fix the citation in this PR or another? https://github.com/llvm/llvm-project/pull/84228 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Turn 'counted_by' into a type attribute and parse it into 'CountAttributedType' (PR #78000)
https://github.com/rapidsna updated https://github.com/llvm/llvm-project/pull/78000 >From c39871ed2ec642ab00360f2c3a18fba7c915f82d Mon Sep 17 00:00:00 2001 From: Yeoul Na Date: Mon, 18 Dec 2023 10:58:16 +0900 Subject: [PATCH 1/7] [BoundsSafety] Introduce CountAttributedType CountAttributedType is a sugar type to represent a type with a 'counted_by' attribute and the likes, which provides bounds information to the underlying type. The type contains an the argument of attribute as an expression. Additionally, the type holds metadata about declarations referenced by the expression in order to make it easier for Sema to access declarations on which the type depends. This also adjusts the CountedBy attribute definition and implements parsing CountAttributedType. __bdos and array-checks sanitizer use CountAttributedType instead of hasAttr. Implements special lookup for counted_by argument in structs. Adjust test/Sema/attr-counted-by.c to match the default diags generated by the expression parser. --- clang/include/clang/AST/ASTContext.h | 7 + clang/include/clang/AST/PropertiesBase.td | 1 + clang/include/clang/AST/RecursiveASTVisitor.h | 9 + clang/include/clang/AST/Type.h| 152 +++ clang/include/clang/AST/TypeLoc.h | 26 +++ clang/include/clang/AST/TypeProperties.td | 19 ++ clang/include/clang/Basic/Attr.td | 7 +- .../clang/Basic/DiagnosticSemaKinds.td| 14 +- clang/include/clang/Basic/TypeNodes.td| 2 + clang/include/clang/Parse/Parser.h| 5 + clang/include/clang/Sema/Sema.h | 16 +- .../clang/Serialization/ASTRecordReader.h | 2 + .../clang/Serialization/ASTRecordWriter.h | 5 + .../clang/Serialization/TypeBitCodes.def | 2 +- clang/lib/AST/ASTContext.cpp | 55 ++ clang/lib/AST/ASTImporter.cpp | 22 +++ clang/lib/AST/ASTStructuralEquivalence.cpp| 7 + clang/lib/AST/ItaniumMangle.cpp | 1 + clang/lib/AST/Type.cpp| 65 +++ clang/lib/AST/TypeLoc.cpp | 4 + clang/lib/AST/TypePrinter.cpp | 30 +++ clang/lib/CodeGen/CGBuiltin.cpp | 6 +- clang/lib/CodeGen/CGDebugInfo.cpp | 1 + clang/lib/CodeGen/CGExpr.cpp | 37 +--- clang/lib/CodeGen/CodeGenFunction.cpp | 1 + clang/lib/Parse/ParseDecl.cpp | 90 + clang/lib/Sema/SemaDecl.cpp | 6 - clang/lib/Sema/SemaDeclAttr.cpp | 183 -- clang/lib/Sema/SemaExpr.cpp | 25 ++- clang/lib/Sema/SemaType.cpp | 12 ++ clang/lib/Sema/TreeTransform.h| 7 + clang/lib/Serialization/ASTReader.cpp | 8 + clang/lib/Serialization/ASTWriter.cpp | 4 + clang/test/Sema/attr-counted-by.c | 20 +- clang/tools/libclang/CIndex.cpp | 4 + 35 files changed, 692 insertions(+), 163 deletions(-) diff --git a/clang/include/clang/AST/ASTContext.h b/clang/include/clang/AST/ASTContext.h index 12ce9af1e53f63..08795af245c06b 100644 --- a/clang/include/clang/AST/ASTContext.h +++ b/clang/include/clang/AST/ASTContext.h @@ -250,6 +250,8 @@ class ASTContext : public RefCountedBase { DependentBitIntTypes; llvm::FoldingSet BTFTagAttributedTypes; + mutable llvm::FoldingSet CountAttributedTypes; + mutable llvm::FoldingSet QualifiedTemplateNames; mutable llvm::FoldingSet DependentTemplateNames; mutable llvm::FoldingSet @@ -1341,6 +1343,11 @@ class ASTContext : public RefCountedBase { return CanQualType::CreateUnsafe(getPointerType((QualType) T)); } + QualType + getCountAttributedType(QualType T, Expr *CountExpr, bool CountInBytes, + bool OrNull, + ArrayRef DependentDecls) const; + /// Return the uniqued reference to a type adjusted from the original /// type to a new type. QualType getAdjustedType(QualType Orig, QualType New) const; diff --git a/clang/include/clang/AST/PropertiesBase.td b/clang/include/clang/AST/PropertiesBase.td index 0270c086d06b6a..6df1d93a7ba2eb 100644 --- a/clang/include/clang/AST/PropertiesBase.td +++ b/clang/include/clang/AST/PropertiesBase.td @@ -143,6 +143,7 @@ def UInt32 : CountPropertyType<"uint32_t">; def UInt64 : CountPropertyType<"uint64_t">; def UnaryTypeTransformKind : EnumPropertyType<"UnaryTransformType::UTTKind">; def VectorKind : EnumPropertyType<"VectorKind">; +def TypeCoupledDeclRefInfo : PropertyType; def ExceptionSpecInfo : PropertyType<"FunctionProtoType::ExceptionSpecInfo"> { let BufferElementTypes = [ QualType ]; diff --git a/clang/include/clang/AST/RecursiveASTVisitor.h b/clang/include/clang/AST/RecursiveASTVisitor.h index 9da5206a21c34c..b058e0435912eb 100644 --- a/clang/include/clang/AST/RecursiveASTVisitor.h +++
[clang] [alpha.webkit.UncountedLocalVarsChecker] Allow uncounted object references within trivial statements (PR #82229)
rniwa wrote: Actually, we need to cache the results for `VisitDeclRefExpr` as well to avoid infinite recursion. https://github.com/llvm/llvm-project/pull/82229 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [X86] Finely handle target of __builtin_ia32_cmp[p|s][s|d] from avx into sse/sse2/avx (PR #84136)
@@ -2613,6 +2614,24 @@ void CGBuilderInserter::InsertHelper( // called function. void CodeGenFunction::checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl) { + // SemaCheking cannot handle below x86 builtins because they have different + // parameter ranges with different TargetAttribute of caller. FreddyLeaf wrote: because SDM defined so? https://github.com/llvm/llvm-project/pull/84136 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][C++23] Implement P1774R8: Portable assumptions (PR #81014)
Sirraide wrote: > Change __attribute__((assume)) (and [[clang::assume]] if we care enough about > that one) to be synonyms for [[assume]]. Actually, I think we could do that immediately because OpenMP’s `assume` isn’t valid as a statement attribute anyway iirc. I’d still deprecate all spellings other than `[[omp::assume]]` on functions, though—unless there is some problem with that that I’m missing. https://github.com/llvm/llvm-project/pull/81014 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [X86] Finely handle target of __builtin_ia32_cmp[p|s][s|d] from avx into sse/sse2/avx (PR #84136)
@@ -2613,6 +2614,24 @@ void CGBuilderInserter::InsertHelper( // called function. void CodeGenFunction::checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl) { + // SemaCheking cannot handle below x86 builtins because they have different + // parameter ranges with different TargetAttribute of caller. KanRobert wrote: This is the behavior. But why? https://github.com/llvm/llvm-project/pull/84136 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][OpenMP] throw compilation error instead of crash in Stmt::OMPScopeDirectiveClass case (#77535) (PR #84135)
https://github.com/Puellaquae updated https://github.com/llvm/llvm-project/pull/84135 >From a2c88b0b615875d625b49e596886a0f5b32cf159 Mon Sep 17 00:00:00 2001 From: Puellaquae Date: Wed, 6 Mar 2024 05:22:08 + Subject: [PATCH 1/3] [Clang][OpenMP] throw compilation error instead of crash in Stmt::OMPScopeDirectiveClass case (#77535) --- clang/lib/CodeGen/CGStmt.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/clang/lib/CodeGen/CGStmt.cpp b/clang/lib/CodeGen/CGStmt.cpp index d0a3a716ad75e1..698986a3e49dd0 100644 --- a/clang/lib/CodeGen/CGStmt.cpp +++ b/clang/lib/CodeGen/CGStmt.cpp @@ -414,7 +414,8 @@ void CodeGenFunction::EmitStmt(const Stmt *S, ArrayRef Attrs) { CGM.ErrorUnsupported(S, "OpenMP dispatch directive"); break; case Stmt::OMPScopeDirectiveClass: -llvm_unreachable("scope not supported with FE outlining"); +CGM.ErrorUnsupported(S, "scope with FE outlining"); +break; case Stmt::OMPMaskedDirectiveClass: EmitOMPMaskedDirective(cast(*S)); break; >From 52e4f0b996085b289d1550af06760e273c390996 Mon Sep 17 00:00:00 2001 From: Puellaquae Date: Wed, 6 Mar 2024 08:05:52 + Subject: [PATCH 2/3] [Clang][OpenMP] add test for Stmt::OMPScopeDirectiveClass support error --- clang/test/OpenMP/error_unsupport_feature.c | 8 1 file changed, 8 insertions(+) create mode 100644 clang/test/OpenMP/error_unsupport_feature.c diff --git a/clang/test/OpenMP/error_unsupport_feature.c b/clang/test/OpenMP/error_unsupport_feature.c new file mode 100644 index 00..a100300752db91 --- /dev/null +++ b/clang/test/OpenMP/error_unsupport_feature.c @@ -0,0 +1,8 @@ +// RUN: %clang_cc1 -emit-obj -verify -fopenmp %s + +int main () { + int r = 0; +#pragma omp scope reduction(+:r) // expected-error {{cannot compile this scope with FE outlining yet}} + r++; + return r; +} >From 7f3ac8e792d5070369bc008e3dc0e470d34c6974 Mon Sep 17 00:00:00 2001 From: Puellaquae Date: Thu, 7 Mar 2024 00:59:39 + Subject: [PATCH 3/3] [Test] use emit-llvm in test --- clang/test/OpenMP/error_unsupport_feature.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clang/test/OpenMP/error_unsupport_feature.c b/clang/test/OpenMP/error_unsupport_feature.c index a100300752db91..611a8b4639c44e 100644 --- a/clang/test/OpenMP/error_unsupport_feature.c +++ b/clang/test/OpenMP/error_unsupport_feature.c @@ -1,4 +1,4 @@ -// RUN: %clang_cc1 -emit-obj -verify -fopenmp %s +// RUN: %clang_cc1 -emit-llvm -verify -fopenmp %s int main () { int r = 0; ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][Sema] Skip the RequiresExprBodyDecls for lambda dependencies (PR #83997)
https://github.com/yuxuanchen1997 approved this pull request. Thank you so much! This looks good. https://github.com/llvm/llvm-project/pull/83997 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][StaticAnalyzer] Adding getentropy to CStringChecker. (PR #83675)
https://github.com/devnexen updated https://github.com/llvm/llvm-project/pull/83675 >From 1b2fec2c9a41be4ad216d7032189f561eed3f751 Mon Sep 17 00:00:00 2001 From: David Carlier Date: Sat, 2 Mar 2024 14:56:15 + Subject: [PATCH 1/2] [clang][StaticAnalyzer] Adding getentropy to CStringChecker. since it went way beyond just openbsd, adding basic check for possible misusage. --- .../Checkers/CStringChecker.cpp | 43 +++ 1 file changed, 43 insertions(+) diff --git a/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp index 59be236ca1c769..cea99fad3e8436 100644 --- a/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp @@ -165,6 +165,7 @@ class CStringChecker : public Checker< eval::Call, {{CDM::CLibrary, {"explicit_bzero"}, 2}, ::evalBzero}, {{CDM::CLibrary, {"sprintf"}, 2}, ::evalSprintf}, {{CDM::CLibrary, {"snprintf"}, 2}, ::evalSnprintf}, + {{CDM::CLibrary, {"getentropy"}, 2}, ::evalGetentropy}, }; // These require a bit of special handling. @@ -219,6 +220,7 @@ class CStringChecker : public Checker< eval::Call, void evalSnprintf(CheckerContext , const CallEvent ) const; void evalSprintfCommon(CheckerContext , const CallEvent , bool IsBounded, bool IsBuiltin) const; + void evalGetentropy(CheckerContext , const CallEvent ) const; // Utility methods std::pair @@ -2515,6 +2517,47 @@ void CStringChecker::evalSprintfCommon(CheckerContext , const CallEvent , C.addTransition(State); } +void CStringChecker::evalGetentropy(CheckerContext , +const CallEvent ) const { + DestinationArgExpr Buffer = {{Call.getArgExpr(0), 0}}; + SizeArgExpr Size = {{Call.getArgExpr(1), 1}}; + ProgramStateRef State = C.getState(); + constexpr int BufferMaxSize = 256; + + SVal SizeVal = C.getSVal(Size.Expression); + QualType SizeTy = Size.Expression->getType(); + + ProgramStateRef StateZeroSize, StateNonZeroSize; + std::tie(StateZeroSize, StateNonZeroSize) = + assumeZero(C, State, SizeVal, SizeTy); + + SVal Buff = C.getSVal(Buffer.Expression); + State = checkNonNull(C, StateNonZeroSize, Buffer, Buff); + if (!State) +return; + + State = CheckBufferAccess(C, State, Buffer, Size, AccessKind::write); + if (!State) +return; + + auto SizeLoc = SizeVal.getAs(); + auto size = SizeLoc->getValue().getExtValue(); + + if (size > BufferMaxSize) { +ErrorMessage Message; +llvm::raw_svector_ostream Os(Message); +Os << " destination buffer size is greater than " << BufferMaxSize; +emitOutOfBoundsBug(C, StateNonZeroSize, Buffer.Expression, Message); +return; + } + + State = invalidateDestinationBufferBySize(C, State, Buffer.Expression, +C.getSVal(Buffer.Expression), +SizeVal, SizeTy); + + C.addTransition(State); +} + //===--===// // The driver method, and other Checker callbacks. //===--===// >From 4c626fa147aade7725e04dc633b53aefcd1347b0 Mon Sep 17 00:00:00 2001 From: David Carlier Date: Wed, 6 Mar 2024 17:38:25 + Subject: [PATCH 2/2] few fixes and tests additions --- .../Checkers/CStringChecker.cpp | 51 +++ clang/test/Analysis/bstring.c | 39 ++ 2 files changed, 70 insertions(+), 20 deletions(-) diff --git a/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp index cea99fad3e8436..4d0492bcaf159e 100644 --- a/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp +++ b/clang/lib/StaticAnalyzer/Checkers/CStringChecker.cpp @@ -165,7 +165,8 @@ class CStringChecker : public Checker< eval::Call, {{CDM::CLibrary, {"explicit_bzero"}, 2}, ::evalBzero}, {{CDM::CLibrary, {"sprintf"}, 2}, ::evalSprintf}, {{CDM::CLibrary, {"snprintf"}, 2}, ::evalSnprintf}, - {{CDM::CLibrary, {"getentropy"}, 2}, ::evalGetentropy}, + {{CDM::CLibrary, {"getentropy"}, 2}, + std::bind(::evalGetentropy, _1, _2, _3, CK_Regular)}, }; // These require a bit of special handling. @@ -220,7 +221,7 @@ class CStringChecker : public Checker< eval::Call, void evalSnprintf(CheckerContext , const CallEvent ) const; void evalSprintfCommon(CheckerContext , const CallEvent , bool IsBounded, bool IsBuiltin) const; - void evalGetentropy(CheckerContext , const CallEvent ) const; + void evalGetentropy(CheckerContext , const CallEvent , CharKind CK) const; // Utility methods std::pair @@ -2518,11 +2519,13 @@ void CStringChecker::evalSprintfCommon(CheckerContext , const CallEvent , } void CStringChecker::evalGetentropy(CheckerContext , -
[clang] [X86] Finely handle target of __builtin_ia32_cmp[p|s][s|d] from avx into sse/sse2/avx (PR #84136)
@@ -34,6 +34,60 @@ __m128 test_mm_andnot_ps(__m128 A, __m128 B) { return _mm_andnot_ps(A, B); } +__m128 test_mm_cmp_ps_eq_oq(__m128 a, __m128 b) { + // CHECK-LABEL: test_mm_cmp_ps_eq_oq + // CHECK: fcmp oeq <4 x float> %{{.*}}, %{{.*}} + return _mm_cmp_ps(a, b, _CMP_EQ_OQ); FreddyLeaf wrote: These condition codes are [0,7], so they won't throw errors. What about adding 8 more tests to avx-builtins.c with condition codes of [8,15]? https://github.com/llvm/llvm-project/pull/84136 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][C++23] Implement P1774R8: Portable assumptions (PR #81014)
https://github.com/Sirraide updated https://github.com/llvm/llvm-project/pull/81014 >From 5ba669011752b6ea6e6fe5f6141c4af66ca7ccbf Mon Sep 17 00:00:00 2001 From: Sirraide Date: Wed, 7 Feb 2024 17:25:10 +0100 Subject: [PATCH 01/22] [Clang] Parsing and Sema for C++23's `assume` attribute --- clang/include/clang/Basic/Attr.td | 9 clang/include/clang/Basic/DiagnosticGroups.td | 4 +- .../clang/Basic/DiagnosticParseKinds.td | 3 ++ .../clang/Basic/DiagnosticSemaKinds.td| 7 +++ clang/include/clang/Parse/Parser.h| 7 +++ clang/lib/Parse/ParseDeclCXX.cpp | 54 ++- clang/lib/Parse/ParseExpr.cpp | 13 + clang/lib/Sema/SemaStmtAttr.cpp | 34 clang/test/Parser/cxx23-assume.cpp| 27 ++ 9 files changed, 156 insertions(+), 2 deletions(-) create mode 100644 clang/test/Parser/cxx23-assume.cpp diff --git a/clang/include/clang/Basic/Attr.td b/clang/include/clang/Basic/Attr.td index b2d5309e142c1a..2804ff1aea005f 100644 --- a/clang/include/clang/Basic/Attr.td +++ b/clang/include/clang/Basic/Attr.td @@ -1564,6 +1564,15 @@ def Unlikely : StmtAttr { } def : MutualExclusions<[Likely, Unlikely]>; +def Assume : StmtAttr { + let Spellings = [CXX11<"", "assume", 202302>]; + let Subjects = SubjectList<[NullStmt], ErrorDiag, "empty statements">; + // The standard only allows a conditional-expression here, but we ought + // to get better results by handling that in Sema. + let Args = [ExprArgument<"Assumption">]; + let Documentation = [AssumptionDocs]; +} + def NoMerge : DeclOrStmtAttr { let Spellings = [Clang<"nomerge">]; let Documentation = [NoMergeDocs]; diff --git a/clang/include/clang/Basic/DiagnosticGroups.td b/clang/include/clang/Basic/DiagnosticGroups.td index 6765721ae7002c..192b081404a827 100644 --- a/clang/include/clang/Basic/DiagnosticGroups.td +++ b/clang/include/clang/Basic/DiagnosticGroups.td @@ -1124,9 +1124,11 @@ def NonGCC : DiagGroup<"non-gcc", def CXX14Attrs : DiagGroup<"c++14-attribute-extensions">; def CXX17Attrs : DiagGroup<"c++17-attribute-extensions">; def CXX20Attrs : DiagGroup<"c++20-attribute-extensions">; +def CXX23Attrs : DiagGroup<"c++23-attribute-extensions">; def FutureAttrs : DiagGroup<"future-attribute-extensions", [CXX14Attrs, CXX17Attrs, -CXX20Attrs]>; +CXX20Attrs, +CXX23Attrs]>; def CXX23AttrsOnLambda : DiagGroup<"c++23-lambda-attributes">; diff --git a/clang/include/clang/Basic/DiagnosticParseKinds.td b/clang/include/clang/Basic/DiagnosticParseKinds.td index a30ab27566ec3e..9ecfdab3617e05 100644 --- a/clang/include/clang/Basic/DiagnosticParseKinds.td +++ b/clang/include/clang/Basic/DiagnosticParseKinds.td @@ -783,6 +783,9 @@ def err_ms_property_expected_comma_or_rparen : Error< def err_ms_property_initializer : Error< "property declaration cannot have a default member initializer">; +def err_assume_attr_expects_cond_expr : Error< + "use of this expression in an 'assume' attribute requires parentheses">; + def warn_cxx20_compat_explicit_bool : Warning< "this expression will be parsed as explicit(bool) in C++20">, InGroup, DefaultIgnore; diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td index b4dc4feee8e63a..847168af288622 100644 --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -9083,6 +9083,8 @@ def ext_cxx17_attr : Extension< "use of the %0 attribute is a C++17 extension">, InGroup; def ext_cxx20_attr : Extension< "use of the %0 attribute is a C++20 extension">, InGroup; +def ext_cxx23_attr : Extension< + "use of the %0 attribute is a C++23 extension">, InGroup; def warn_unused_comparison : Warning< "%select{equality|inequality|relational|three-way}0 comparison result unused">, @@ -10149,6 +10151,11 @@ def err_fallthrough_attr_outside_switch : Error< def err_fallthrough_attr_invalid_placement : Error< "fallthrough annotation does not directly precede switch label">; +def err_assume_attr_args : Error< + "attribute 'assume' requires a single expression argument">; +def err_assume_attr_wrong_target : Error< + "'assume' attribute is only allowed on empty statements">; + def warn_unreachable_default : Warning< "default label in switch which covers all enumeration values">, InGroup, DefaultIgnore; diff --git a/clang/include/clang/Parse/Parser.h b/clang/include/clang/Parse/Parser.h index da18cf88edcc92..0f982dbb67b41c 100644 --- a/clang/include/clang/Parse/Parser.h +++ b/clang/include/clang/Parse/Parser.h @@ -1801,6 +1801,7 @@ class Parser : public CodeCompletionHandler { ExprResult
[clang] [Clang][OpenMP] throw compilation error instead of crash in Stmt::OMPScopeDirectiveClass case (#77535) (PR #84135)
@@ -0,0 +1,8 @@ +// RUN: %clang_cc1 -emit-obj -verify -fopenmp %s shiltian wrote: You can use `-emit-llvm` instead. https://github.com/llvm/llvm-project/pull/84135 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][OpenMP] throw compilation error instead of crash in Stmt::OMPScopeDirectiveClass case (#77535) (PR #84135)
@@ -0,0 +1,8 @@ +// RUN: %clang_cc1 -emit-obj -verify -fopenmp %s Puellaquae wrote: during testing, I found it can't produce this error without `-emit-obj` https://github.com/llvm/llvm-project/pull/84135 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][C++23] Implement P1774R8: Portable assumptions (PR #81014)
Sirraide wrote: I’ve implemented what we’ve decided on as a result of the RFC and also renamed the attribute to `CXXAssumeAttr` and the OpenMP one to `OMPAssumeAttr` so we don’t confuse the two. > > But it sounds like my idea doesn't have legs because of OpenMP > > specification requirements. I'm fine with (3) as an approach then. > > I think a hybrid approach between (3) and what you’re suggesting might make > sense: > > 1. Introduce `[[omp::assume]]` for OpenMP (if that isn’t already a thing) > 2. Deprecate `[[clang::assume]]` and `__attribute__((assume))`, telling > people to use `[[omp::assume]]` or `[[assume]]` instead, depending on where > we encounter the attribute, and maybe, eventually > 3. Change `__attribute__((assume))` (and `[[clang::assume]]` if we care > enough about that one) to be synonyms for `[[assume]]`. @AaronBallman, @erichkeane Thoughts on this? https://github.com/llvm/llvm-project/pull/81014 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][C++23] Implement P1774R8: Portable assumptions (PR #81014)
Sirraide wrote: It requests a review automatically if one of the files has a code owner, interesting. https://github.com/llvm/llvm-project/pull/81014 ___ 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 bugprone-suspicious-stringview-data-usage check (PR #83716)
@@ -0,0 +1,100 @@ +//===--- SuspiciousStringviewDataUsageCheck.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 "SuspiciousStringviewDataUsageCheck.h" +#include "../utils/Matchers.h" +#include "../utils/OptionsUtils.h" +#include "clang/AST/ASTContext.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::bugprone { + +SuspiciousStringviewDataUsageCheck::SuspiciousStringviewDataUsageCheck( +StringRef Name, ClangTidyContext *Context) +: ClangTidyCheck(Name, Context), + StringViewTypes(utils::options::parseStringList(Options.get( + "StringViewTypes", "::std::basic_string_view;::llvm::StringRef"))), + AllowedCallees( + utils::options::parseStringList(Options.get("AllowedCallees", ""))) {} + +void SuspiciousStringviewDataUsageCheck::storeOptions( +ClangTidyOptions::OptionMap ) { + Options.store(Opts, "StringViewTypes", +utils::options::serializeStringList(StringViewTypes)); + Options.store(Opts, "AllowedCallees", +utils::options::serializeStringList(AllowedCallees)); +} + +bool SuspiciousStringviewDataUsageCheck::isLanguageVersionSupported( +const LangOptions ) const { + return LangOpts.CPlusPlus; +} + +std::optional +SuspiciousStringviewDataUsageCheck::getCheckTraversalKind() const { + return TK_AsIs; +} + +void SuspiciousStringviewDataUsageCheck::registerMatchers(MatchFinder *Finder) { + + auto AncestorCall = anyOf( + cxxConstructExpr(), callExpr(unless(cxxOperatorCallExpr())), lambdaExpr(), + initListExpr( + hasType(qualType(hasCanonicalType(hasDeclaration(recordDecl())); + + auto DataMethod = + cxxMethodDecl(hasName("data"), +ofClass(matchers::matchesAnyListedName(StringViewTypes))); + + auto DataWithSelfCall = + cxxMemberCallExpr(on(ignoringParenImpCasts(expr().bind("self"))), +callee(DataMethod)) + .bind("data-call"); + auto SizeCall = cxxMemberCallExpr( + callee(cxxMethodDecl(hasAnyName("size", "length"))), + on(ignoringParenImpCasts( + matchers::isStatementIdenticalToBoundNode("self"; + + Finder->addMatcher( + cxxMemberCallExpr( + on(ignoringParenImpCasts(expr().bind("self"))), callee(DataMethod), + expr().bind("data-call"), + hasParent(expr(anyOf( + invocation( + expr().bind("call"), unless(cxxOperatorCallExpr()), 5chmidti wrote: Ah, okay. https://github.com/llvm/llvm-project/pull/83716 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][C++23] Implement P1774R8: Portable assumptions (PR #81014)
https://github.com/Sirraide updated https://github.com/llvm/llvm-project/pull/81014 >From 5ba669011752b6ea6e6fe5f6141c4af66ca7ccbf Mon Sep 17 00:00:00 2001 From: Sirraide Date: Wed, 7 Feb 2024 17:25:10 +0100 Subject: [PATCH 01/21] [Clang] Parsing and Sema for C++23's `assume` attribute --- clang/include/clang/Basic/Attr.td | 9 clang/include/clang/Basic/DiagnosticGroups.td | 4 +- .../clang/Basic/DiagnosticParseKinds.td | 3 ++ .../clang/Basic/DiagnosticSemaKinds.td| 7 +++ clang/include/clang/Parse/Parser.h| 7 +++ clang/lib/Parse/ParseDeclCXX.cpp | 54 ++- clang/lib/Parse/ParseExpr.cpp | 13 + clang/lib/Sema/SemaStmtAttr.cpp | 34 clang/test/Parser/cxx23-assume.cpp| 27 ++ 9 files changed, 156 insertions(+), 2 deletions(-) create mode 100644 clang/test/Parser/cxx23-assume.cpp diff --git a/clang/include/clang/Basic/Attr.td b/clang/include/clang/Basic/Attr.td index b2d5309e142c1a..2804ff1aea005f 100644 --- a/clang/include/clang/Basic/Attr.td +++ b/clang/include/clang/Basic/Attr.td @@ -1564,6 +1564,15 @@ def Unlikely : StmtAttr { } def : MutualExclusions<[Likely, Unlikely]>; +def Assume : StmtAttr { + let Spellings = [CXX11<"", "assume", 202302>]; + let Subjects = SubjectList<[NullStmt], ErrorDiag, "empty statements">; + // The standard only allows a conditional-expression here, but we ought + // to get better results by handling that in Sema. + let Args = [ExprArgument<"Assumption">]; + let Documentation = [AssumptionDocs]; +} + def NoMerge : DeclOrStmtAttr { let Spellings = [Clang<"nomerge">]; let Documentation = [NoMergeDocs]; diff --git a/clang/include/clang/Basic/DiagnosticGroups.td b/clang/include/clang/Basic/DiagnosticGroups.td index 6765721ae7002c..192b081404a827 100644 --- a/clang/include/clang/Basic/DiagnosticGroups.td +++ b/clang/include/clang/Basic/DiagnosticGroups.td @@ -1124,9 +1124,11 @@ def NonGCC : DiagGroup<"non-gcc", def CXX14Attrs : DiagGroup<"c++14-attribute-extensions">; def CXX17Attrs : DiagGroup<"c++17-attribute-extensions">; def CXX20Attrs : DiagGroup<"c++20-attribute-extensions">; +def CXX23Attrs : DiagGroup<"c++23-attribute-extensions">; def FutureAttrs : DiagGroup<"future-attribute-extensions", [CXX14Attrs, CXX17Attrs, -CXX20Attrs]>; +CXX20Attrs, +CXX23Attrs]>; def CXX23AttrsOnLambda : DiagGroup<"c++23-lambda-attributes">; diff --git a/clang/include/clang/Basic/DiagnosticParseKinds.td b/clang/include/clang/Basic/DiagnosticParseKinds.td index a30ab27566ec3e..9ecfdab3617e05 100644 --- a/clang/include/clang/Basic/DiagnosticParseKinds.td +++ b/clang/include/clang/Basic/DiagnosticParseKinds.td @@ -783,6 +783,9 @@ def err_ms_property_expected_comma_or_rparen : Error< def err_ms_property_initializer : Error< "property declaration cannot have a default member initializer">; +def err_assume_attr_expects_cond_expr : Error< + "use of this expression in an 'assume' attribute requires parentheses">; + def warn_cxx20_compat_explicit_bool : Warning< "this expression will be parsed as explicit(bool) in C++20">, InGroup, DefaultIgnore; diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td index b4dc4feee8e63a..847168af288622 100644 --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -9083,6 +9083,8 @@ def ext_cxx17_attr : Extension< "use of the %0 attribute is a C++17 extension">, InGroup; def ext_cxx20_attr : Extension< "use of the %0 attribute is a C++20 extension">, InGroup; +def ext_cxx23_attr : Extension< + "use of the %0 attribute is a C++23 extension">, InGroup; def warn_unused_comparison : Warning< "%select{equality|inequality|relational|three-way}0 comparison result unused">, @@ -10149,6 +10151,11 @@ def err_fallthrough_attr_outside_switch : Error< def err_fallthrough_attr_invalid_placement : Error< "fallthrough annotation does not directly precede switch label">; +def err_assume_attr_args : Error< + "attribute 'assume' requires a single expression argument">; +def err_assume_attr_wrong_target : Error< + "'assume' attribute is only allowed on empty statements">; + def warn_unreachable_default : Warning< "default label in switch which covers all enumeration values">, InGroup, DefaultIgnore; diff --git a/clang/include/clang/Parse/Parser.h b/clang/include/clang/Parse/Parser.h index da18cf88edcc92..0f982dbb67b41c 100644 --- a/clang/include/clang/Parse/Parser.h +++ b/clang/include/clang/Parse/Parser.h @@ -1801,6 +1801,7 @@ class Parser : public CodeCompletionHandler { ExprResult
[clang] [llvm] [Clang] CGCoroutine: Skip moving parameters if the allocation decision is false (PR #81195)
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 dcd08daed5fb9928fedb09c2a84d1e9d2ab59630 1e03c2ec24c7bc6a303266a7023a56d6449a46e5 -- clang/lib/CodeGen/CGCoroutine.cpp clang/test/CodeGenCoroutines/coro-gro.cpp clang/test/CodeGenCoroutines/coro-params.cpp llvm/lib/Transforms/Coroutines/CoroElide.cpp `` View the diff from clang-format here. ``diff diff --git a/llvm/lib/Transforms/Coroutines/CoroElide.cpp b/llvm/lib/Transforms/Coroutines/CoroElide.cpp index 51c155767c..3b0766031a 100644 --- a/llvm/lib/Transforms/Coroutines/CoroElide.cpp +++ b/llvm/lib/Transforms/Coroutines/CoroElide.cpp @@ -52,10 +52,9 @@ struct Lowerer : coro::LowererBase { AAResults ); bool shouldElide(Function *F, DominatorTree ) const; void collectPostSplitCoroIds(Function *F); - bool processCoroId(Function , CoroIdInst *, AAResults , DominatorTree , - OptimizationRemarkEmitter ); - bool hasEscapePath(Function , - const CoroBeginInst *, + bool processCoroId(Function , CoroIdInst *, AAResults , + DominatorTree , OptimizationRemarkEmitter ); + bool hasEscapePath(Function , const CoroBeginInst *, const SmallPtrSetImpl &) const; }; @@ -79,7 +78,8 @@ struct StackAliases { return It != Stores.end() && It->second.size() == 1; } - const SmallPtrSetImpl& getLoadsByStore(const StoreInst *Store) const { + const SmallPtrSetImpl & + getLoadsByStore(const StoreInst *Store) const { const static SmallPtrSet EmptyStores; auto Ptr = Store->getPointerOperand(); if (Loads.contains(Ptr)) { @@ -89,7 +89,8 @@ struct StackAliases { return EmptyStores; } - const SmallPtrSetImpl& getStoresByLoad(const LoadInst *Load) const { + const SmallPtrSetImpl & + getStoresByLoad(const LoadInst *Load) const { const static SmallPtrSet EmptyLoads; auto Ptr = Load->getPointerOperand(); if (Stores.contains(Ptr)) { @@ -108,8 +109,7 @@ private: // Go through the list of coro.subfn.addr intrinsics and replace them with the // provided constant. template -static void replaceWithConstant(Constant *Value, -Range ) { +static void replaceWithConstant(Constant *Value, Range ) { if (Users.empty()) return; @@ -233,10 +233,8 @@ void Lowerer::elideHeapAllocations(Function *F, uint64_t FrameSize, removeTailCallAttribute(Frame, AA); } -bool Lowerer::hasEscapePath( -Function , -const CoroBeginInst *CB, -const SmallPtrSetImpl ) const { +bool Lowerer::hasEscapePath(Function , const CoroBeginInst *CB, +const SmallPtrSetImpl ) const { const auto = DestroyAddr.find(CB); assert(It != DestroyAddr.end()); @@ -261,8 +259,7 @@ bool Lowerer::hasEscapePath( if (isa(U)) continue; -if (auto *SI = dyn_cast(U); -SI && SI->getPointerOperand() == U) { +if (auto *SI = dyn_cast(U); SI && SI->getPointerOperand() == U) { for (const auto *Load : SA.getLoadsByStore(SI)) { AliasUsers.insert(Load); } @@ -364,7 +361,7 @@ bool Lowerer::shouldElide(Function *F, DominatorTree ) const { } SmallPtrSet CoroBeginsToTest; - for (const auto& Class : CoroBeginClasses) { + for (const auto : CoroBeginClasses) { if (Class.isLeader()) { CoroBeginsToTest.insert(Class.getData()); } @@ -394,8 +391,7 @@ bool Lowerer::shouldElide(Function *F, DominatorTree ) const { return DT.dominates(DA, TI->getTerminator()); }); }) || -!hasEscapePath(*F, CB, Terminators)) -{ +!hasEscapePath(*F, CB, Terminators)) { ReferencedCoroBegins.insert(CB); } else { llvm::dbgs() << "not referenced\n"; @@ -407,8 +403,7 @@ bool Lowerer::shouldElide(Function *F, DominatorTree ) const { // perform heap elision. llvm::dbgs() << "DestroyAddr: " << DestroyAddr.size() << " ReferencedCoroBegins: " << ReferencedCoroBegins.size() - << " CoroBeginsToTest: " << CoroBeginsToTest.size() - << "\n"; + << " CoroBeginsToTest: " << CoroBeginsToTest.size() << "\n"; return ReferencedCoroBegins.size() == CoroBeginsToTest.size(); } @@ -437,10 +432,9 @@ void Lowerer::collectPostSplitCoroIds(Function *F) { } } -static void findReachableCoroSubFnForValue( -llvm::Value *V, -const StackAliases , -SmallSet ) { +static void findReachableCoroSubFnForValue(llvm::Value *V, + const StackAliases , + SmallSet ) { if (auto *CSFI = dyn_cast(V)) { Res.insert(CSFI); @@ -472,7 +466,8 @@ bool Lowerer::processCoroId(Function , CoroIdInst *CoroId, AAResults ,
[clang-tools-extra] [clang-tidy] Add bugprone-suspicious-stringview-data-usage check (PR #83716)
@@ -0,0 +1,100 @@ +//===--- SuspiciousStringviewDataUsageCheck.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 "SuspiciousStringviewDataUsageCheck.h" +#include "../utils/Matchers.h" +#include "../utils/OptionsUtils.h" +#include "clang/AST/ASTContext.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::bugprone { + +SuspiciousStringviewDataUsageCheck::SuspiciousStringviewDataUsageCheck( +StringRef Name, ClangTidyContext *Context) +: ClangTidyCheck(Name, Context), + StringViewTypes(utils::options::parseStringList(Options.get( + "StringViewTypes", "::std::basic_string_view;::llvm::StringRef"))), + AllowedCallees( + utils::options::parseStringList(Options.get("AllowedCallees", ""))) {} + +void SuspiciousStringviewDataUsageCheck::storeOptions( +ClangTidyOptions::OptionMap ) { + Options.store(Opts, "StringViewTypes", +utils::options::serializeStringList(StringViewTypes)); + Options.store(Opts, "AllowedCallees", +utils::options::serializeStringList(AllowedCallees)); +} + +bool SuspiciousStringviewDataUsageCheck::isLanguageVersionSupported( +const LangOptions ) const { + return LangOpts.CPlusPlus; +} + +std::optional +SuspiciousStringviewDataUsageCheck::getCheckTraversalKind() const { + return TK_AsIs; +} 5chmidti wrote: I don't mind either way, this was just a consistency thing https://github.com/llvm/llvm-project/pull/83716 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [Clang] CGCoroutine: Skip moving parameters if the allocation decision is false (PR #81195)
https://github.com/yuxuanchen1997 updated https://github.com/llvm/llvm-project/pull/81195 >From 1e03c2ec24c7bc6a303266a7023a56d6449a46e5 Mon Sep 17 00:00:00 2001 From: Yuxuan Chen Date: Wed, 7 Feb 2024 16:05:42 -0800 Subject: [PATCH] Skip moving parameters if the allocation decision is false --- clang/lib/CodeGen/CGCoroutine.cpp| 120 --- clang/test/CodeGenCoroutines/coro-gro.cpp| 6 +- clang/test/CodeGenCoroutines/coro-params.cpp | 48 +++-- llvm/lib/Transforms/Coroutines/CoroElide.cpp | 211 --- 4 files changed, 311 insertions(+), 74 deletions(-) diff --git a/clang/lib/CodeGen/CGCoroutine.cpp b/clang/lib/CodeGen/CGCoroutine.cpp index 888d30bfb3e1d6..b2933650367c12 100644 --- a/clang/lib/CodeGen/CGCoroutine.cpp +++ b/clang/lib/CodeGen/CGCoroutine.cpp @@ -389,25 +389,12 @@ namespace { ParamReferenceReplacerRAII(CodeGenFunction::DeclMapTy ) : LocalDeclMap(LocalDeclMap) {} -void addCopy(DeclStmt const *PM) { - // Figure out what param it refers to. - - assert(PM->isSingleDecl()); - VarDecl const*VD = static_cast(PM->getSingleDecl()); - Expr const *InitExpr = VD->getInit(); - GetParamRef Visitor; - Visitor.Visit(const_cast(InitExpr)); - assert(Visitor.Expr); - DeclRefExpr *DREOrig = Visitor.Expr; - auto *PD = DREOrig->getDecl(); - - auto it = LocalDeclMap.find(PD); - assert(it != LocalDeclMap.end() && "parameter is not found"); - SavedLocals.insert({ PD, it->second }); - - auto copyIt = LocalDeclMap.find(VD); - assert(copyIt != LocalDeclMap.end() && "parameter copy is not found"); - it->second = copyIt->getSecond(); +void substAddress(ValueDecl *D, Address Addr) { + auto it = LocalDeclMap.find(D); + assert(it != LocalDeclMap.end() && "original decl is not found"); + SavedLocals.insert({D, it->second}); + + it->second = Addr; } ~ParamReferenceReplacerRAII() { @@ -629,6 +616,63 @@ struct GetReturnObjectManager { Builder.CreateStore(Builder.getTrue(), GroActiveFlag); } }; + +static ValueDecl *getOriginalParamDeclForParamMove(VarDecl const *VD) { + Expr const *InitExpr = VD->getInit(); + GetParamRef Visitor; + Visitor.Visit(const_cast(InitExpr)); + assert(Visitor.Expr); + return Visitor.Expr->getDecl(); +} + +struct ParamMoveManager { + ParamMoveManager(CodeGenFunction , + llvm::ArrayRef ParamMoves) + : CGF(CGF), ParamMovesVarDecls() { +ParamMovesVarDecls.reserve(ParamMoves.size()); +for (auto *S : ParamMoves) { + auto *PMStmt = cast(S); + assert(PMStmt->isSingleDecl()); + auto *ParamMoveVD = static_cast(PMStmt->getSingleDecl()); + ParamMovesVarDecls.push_back(ParamMoveVD); +} + } + + // Because we wrap param moves in the coro.alloc block. It's not always + // necessary to run the corresponding cleanups in the branches. + // We would need to know when to (conditionally) clean them up. + void EmitMovesWithCleanup(Address PMCleanupActiveFlag) { +// Create parameter copies. We do it before creating a promise, since an +// evolution of coroutine TS may allow promise constructor to observe +// parameter copies. +for (auto *VD : ParamMovesVarDecls) { + auto Emission = CGF.EmitAutoVarAlloca(*VD); + CGF.EmitAutoVarInit(Emission); + auto OldTop = CGF.EHStack.stable_begin(); + CGF.EmitAutoVarCleanups(Emission); + auto Top = CGF.EHStack.stable_begin(); + + for (auto I = CGF.EHStack.find(Top), E = CGF.EHStack.find(OldTop); I != E; + I++) { +if (auto *Cleanup = dyn_cast(&*I)) { + assert(!Cleanup->hasActiveFlag() && + "cleanup already has active flag?"); + Cleanup->setActiveFlag(PMCleanupActiveFlag); + Cleanup->setTestFlagInEHCleanup(); + Cleanup->setTestFlagInNormalCleanup(); +} + } +} + } + + llvm::ArrayRef GetParamMovesVarDecls() { +return ParamMovesVarDecls; + } + +private: + CodeGenFunction + SmallVector ParamMovesVarDecls; +}; } // namespace static void emitBodyAndFallthrough(CodeGenFunction , @@ -648,6 +692,8 @@ void CodeGenFunction::EmitCoroutineBody(const CoroutineBodyStmt ) { auto *EntryBB = Builder.GetInsertBlock(); auto *AllocBB = createBasicBlock("coro.alloc"); auto *InitBB = createBasicBlock("coro.init"); + auto *ParamMoveBB = createBasicBlock("coro.param.move"); + auto *AfterParamMoveBB = createBasicBlock("coro.after.param.move"); auto *FinalBB = createBasicBlock("coro.final"); auto *RetBB = createBasicBlock("coro.ret"); @@ -664,6 +710,9 @@ void CodeGenFunction::EmitCoroutineBody(const CoroutineBodyStmt ) { auto *CoroAlloc = Builder.CreateCall( CGM.getIntrinsic(llvm::Intrinsic::coro_alloc), {CoroId}); + auto PMCleanupActiveFlag = CreateTempAlloca( + Builder.getInt1Ty(), CharUnits::One(), "param.move.cleanup.active"); + Builder.CreateStore(CoroAlloc, PMCleanupActiveFlag);
[clang] Revert "[clang-repl] Pass triple to IncrementalCompilerBuilder as explicit argument" (PR #84261)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Stefan Gränitz (weliveindetail) Changes Reverts llvm/llvm-project#84174 due too sanitizer memory leak detection --- Full diff: https://github.com/llvm/llvm-project/pull/84261.diff 4 Files Affected: - (modified) clang/include/clang/Interpreter/Interpreter.h (+1-4) - (modified) clang/lib/Interpreter/Interpreter.cpp (+5-7) - (modified) clang/unittests/Interpreter/CMakeLists.txt (-1) - (removed) clang/unittests/Interpreter/IncrementalCompilerBuilderTest.cpp (-35) ``diff diff --git a/clang/include/clang/Interpreter/Interpreter.h b/clang/include/clang/Interpreter/Interpreter.h index c8f932e95c4798..292fa566ae7037 100644 --- a/clang/include/clang/Interpreter/Interpreter.h +++ b/clang/include/clang/Interpreter/Interpreter.h @@ -48,8 +48,6 @@ class IncrementalCompilerBuilder { UserArgs = Args; } - void SetTargetTriple(std::string TT) { TargetTriple = TT; } - // General C++ llvm::Expected> CreateCpp(); @@ -64,12 +62,11 @@ class IncrementalCompilerBuilder { private: static llvm::Expected> - create(std::string TT, std::vector ); + create(std::vector ); llvm::Expected> createCuda(bool device); std::vector UserArgs; - std::optional TargetTriple; llvm::StringRef OffloadArch; llvm::StringRef CudaSDKPath; diff --git a/clang/lib/Interpreter/Interpreter.cpp b/clang/lib/Interpreter/Interpreter.cpp index 37696b28976428..9f97a3c6b0be9e 100644 --- a/clang/lib/Interpreter/Interpreter.cpp +++ b/clang/lib/Interpreter/Interpreter.cpp @@ -132,8 +132,7 @@ CreateCI(const llvm::opt::ArgStringList ) { } // anonymous namespace llvm::Expected> -IncrementalCompilerBuilder::create(std::string TT, - std::vector ) { +IncrementalCompilerBuilder::create(std::vector ) { // If we don't know ClangArgv0 or the address of main() at this point, try // to guess it anyway (it's possible on some platforms). @@ -163,7 +162,8 @@ IncrementalCompilerBuilder::create(std::string TT, TextDiagnosticBuffer *DiagsBuffer = new TextDiagnosticBuffer; DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagsBuffer); - driver::Driver Driver(/*MainBinaryName=*/ClangArgv[0], TT, Diags); + driver::Driver Driver(/*MainBinaryName=*/ClangArgv[0], +llvm::sys::getProcessTriple(), Diags); Driver.setCheckInputsExist(false); // the input comes from mem buffers llvm::ArrayRef RF = llvm::ArrayRef(ClangArgv); std::unique_ptr Compilation(Driver.BuildCompilation(RF)); @@ -185,8 +185,7 @@ IncrementalCompilerBuilder::CreateCpp() { Argv.push_back("-xc++"); Argv.insert(Argv.end(), UserArgs.begin(), UserArgs.end()); - std::string TT = TargetTriple ? *TargetTriple : llvm::sys::getProcessTriple(); - return IncrementalCompilerBuilder::create(TT, Argv); + return IncrementalCompilerBuilder::create(Argv); } llvm::Expected> @@ -214,8 +213,7 @@ IncrementalCompilerBuilder::createCuda(bool device) { Argv.insert(Argv.end(), UserArgs.begin(), UserArgs.end()); - std::string TT = TargetTriple ? *TargetTriple : llvm::sys::getProcessTriple(); - return IncrementalCompilerBuilder::create(TT, Argv); + return IncrementalCompilerBuilder::create(Argv); } llvm::Expected> diff --git a/clang/unittests/Interpreter/CMakeLists.txt b/clang/unittests/Interpreter/CMakeLists.txt index 0ddedb283e07d1..712641afb976dd 100644 --- a/clang/unittests/Interpreter/CMakeLists.txt +++ b/clang/unittests/Interpreter/CMakeLists.txt @@ -7,7 +7,6 @@ set(LLVM_LINK_COMPONENTS ) add_clang_unittest(ClangReplInterpreterTests - IncrementalCompilerBuilderTest.cpp IncrementalProcessingTest.cpp InterpreterTest.cpp CodeCompletionTest.cpp diff --git a/clang/unittests/Interpreter/IncrementalCompilerBuilderTest.cpp b/clang/unittests/Interpreter/IncrementalCompilerBuilderTest.cpp deleted file mode 100644 index 1cc0223465c8fa..00 --- a/clang/unittests/Interpreter/IncrementalCompilerBuilderTest.cpp +++ /dev/null @@ -1,35 +0,0 @@ -//=== unittests/Interpreter/IncrementalCompilerBuilderTest.cpp ===// -// -// 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 "clang/Basic/TargetOptions.h" -#include "clang/Frontend/CompilerInstance.h" -#include "clang/Interpreter/Interpreter.h" -#include "llvm/Support/Error.h" -#include "gtest/gtest.h" - -using namespace llvm; -using namespace clang; - -namespace { - -TEST(IncrementalCompilerBuilder, SetCompilerArgs) { - std::vector ClangArgv = {"-Xclang", "-ast-dump-all"}; - auto CB = clang::IncrementalCompilerBuilder(); - CB.SetCompilerArgs(ClangArgv); - auto CI = cantFail(CB.CreateCpp()); - EXPECT_TRUE(CI->getFrontendOpts().ASTDumpAll); -} - -TEST(IncrementalCompilerBuilder, SetTargetTriple) { -
[clang] Revert "[clang-repl] Pass triple to IncrementalCompilerBuilder as explicit argument" (PR #84261)
https://github.com/weliveindetail closed https://github.com/llvm/llvm-project/pull/84261 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 6a39a71 - Revert "[clang-repl] Pass triple to IncrementalCompilerBuilder as explicit argument" (#84261)
Author: Stefan Gränitz Date: 2024-03-07T01:01:07+01:00 New Revision: 6a39a714423ba5675b9e211a80c1dae1ff0e6eac URL: https://github.com/llvm/llvm-project/commit/6a39a714423ba5675b9e211a80c1dae1ff0e6eac DIFF: https://github.com/llvm/llvm-project/commit/6a39a714423ba5675b9e211a80c1dae1ff0e6eac.diff LOG: Revert "[clang-repl] Pass triple to IncrementalCompilerBuilder as explicit argument" (#84261) Reverts llvm/llvm-project#84174 due too sanitizer memory leak detection Added: Modified: clang/include/clang/Interpreter/Interpreter.h clang/lib/Interpreter/Interpreter.cpp clang/unittests/Interpreter/CMakeLists.txt Removed: clang/unittests/Interpreter/IncrementalCompilerBuilderTest.cpp diff --git a/clang/include/clang/Interpreter/Interpreter.h b/clang/include/clang/Interpreter/Interpreter.h index c8f932e95c4798..292fa566ae7037 100644 --- a/clang/include/clang/Interpreter/Interpreter.h +++ b/clang/include/clang/Interpreter/Interpreter.h @@ -48,8 +48,6 @@ class IncrementalCompilerBuilder { UserArgs = Args; } - void SetTargetTriple(std::string TT) { TargetTriple = TT; } - // General C++ llvm::Expected> CreateCpp(); @@ -64,12 +62,11 @@ class IncrementalCompilerBuilder { private: static llvm::Expected> - create(std::string TT, std::vector ); + create(std::vector ); llvm::Expected> createCuda(bool device); std::vector UserArgs; - std::optional TargetTriple; llvm::StringRef OffloadArch; llvm::StringRef CudaSDKPath; diff --git a/clang/lib/Interpreter/Interpreter.cpp b/clang/lib/Interpreter/Interpreter.cpp index 37696b28976428..9f97a3c6b0be9e 100644 --- a/clang/lib/Interpreter/Interpreter.cpp +++ b/clang/lib/Interpreter/Interpreter.cpp @@ -132,8 +132,7 @@ CreateCI(const llvm::opt::ArgStringList ) { } // anonymous namespace llvm::Expected> -IncrementalCompilerBuilder::create(std::string TT, - std::vector ) { +IncrementalCompilerBuilder::create(std::vector ) { // If we don't know ClangArgv0 or the address of main() at this point, try // to guess it anyway (it's possible on some platforms). @@ -163,7 +162,8 @@ IncrementalCompilerBuilder::create(std::string TT, TextDiagnosticBuffer *DiagsBuffer = new TextDiagnosticBuffer; DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagsBuffer); - driver::Driver Driver(/*MainBinaryName=*/ClangArgv[0], TT, Diags); + driver::Driver Driver(/*MainBinaryName=*/ClangArgv[0], +llvm::sys::getProcessTriple(), Diags); Driver.setCheckInputsExist(false); // the input comes from mem buffers llvm::ArrayRef RF = llvm::ArrayRef(ClangArgv); std::unique_ptr Compilation(Driver.BuildCompilation(RF)); @@ -185,8 +185,7 @@ IncrementalCompilerBuilder::CreateCpp() { Argv.push_back("-xc++"); Argv.insert(Argv.end(), UserArgs.begin(), UserArgs.end()); - std::string TT = TargetTriple ? *TargetTriple : llvm::sys::getProcessTriple(); - return IncrementalCompilerBuilder::create(TT, Argv); + return IncrementalCompilerBuilder::create(Argv); } llvm::Expected> @@ -214,8 +213,7 @@ IncrementalCompilerBuilder::createCuda(bool device) { Argv.insert(Argv.end(), UserArgs.begin(), UserArgs.end()); - std::string TT = TargetTriple ? *TargetTriple : llvm::sys::getProcessTriple(); - return IncrementalCompilerBuilder::create(TT, Argv); + return IncrementalCompilerBuilder::create(Argv); } llvm::Expected> diff --git a/clang/unittests/Interpreter/CMakeLists.txt b/clang/unittests/Interpreter/CMakeLists.txt index 0ddedb283e07d1..712641afb976dd 100644 --- a/clang/unittests/Interpreter/CMakeLists.txt +++ b/clang/unittests/Interpreter/CMakeLists.txt @@ -7,7 +7,6 @@ set(LLVM_LINK_COMPONENTS ) add_clang_unittest(ClangReplInterpreterTests - IncrementalCompilerBuilderTest.cpp IncrementalProcessingTest.cpp InterpreterTest.cpp CodeCompletionTest.cpp diff --git a/clang/unittests/Interpreter/IncrementalCompilerBuilderTest.cpp b/clang/unittests/Interpreter/IncrementalCompilerBuilderTest.cpp deleted file mode 100644 index 1cc0223465c8fa..00 --- a/clang/unittests/Interpreter/IncrementalCompilerBuilderTest.cpp +++ /dev/null @@ -1,35 +0,0 @@ -//=== unittests/Interpreter/IncrementalCompilerBuilderTest.cpp ===// -// -// 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 "clang/Basic/TargetOptions.h" -#include "clang/Frontend/CompilerInstance.h" -#include "clang/Interpreter/Interpreter.h" -#include "llvm/Support/Error.h" -#include "gtest/gtest.h" - -using namespace llvm; -using namespace clang; - -namespace { - -TEST(IncrementalCompilerBuilder, SetCompilerArgs) { - std::vector ClangArgv =
[clang] Revert "[clang-repl] Pass triple to IncrementalCompilerBuilder as explicit argument" (PR #84261)
https://github.com/weliveindetail created https://github.com/llvm/llvm-project/pull/84261 Reverts llvm/llvm-project#84174 due too sanitizer memory leak detection From efe6097aad69aba7d2421880305198bf09226db6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20Gr=C3=A4nitz?= Date: Thu, 7 Mar 2024 01:00:03 +0100 Subject: [PATCH] =?UTF-8?q?Revert=20"[clang-repl]=20Expose=20setter=20for?= =?UTF-8?q?=20triple=20in=20IncrementalCompilerBuilder=20(=E2=80=A6"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit 6494f9bb8ac1e6f7526b72ee07f71527b8e66066. --- clang/include/clang/Interpreter/Interpreter.h | 5 +-- clang/lib/Interpreter/Interpreter.cpp | 12 +++ clang/unittests/Interpreter/CMakeLists.txt| 1 - .../IncrementalCompilerBuilderTest.cpp| 35 --- 4 files changed, 6 insertions(+), 47 deletions(-) delete mode 100644 clang/unittests/Interpreter/IncrementalCompilerBuilderTest.cpp diff --git a/clang/include/clang/Interpreter/Interpreter.h b/clang/include/clang/Interpreter/Interpreter.h index c8f932e95c4798..292fa566ae7037 100644 --- a/clang/include/clang/Interpreter/Interpreter.h +++ b/clang/include/clang/Interpreter/Interpreter.h @@ -48,8 +48,6 @@ class IncrementalCompilerBuilder { UserArgs = Args; } - void SetTargetTriple(std::string TT) { TargetTriple = TT; } - // General C++ llvm::Expected> CreateCpp(); @@ -64,12 +62,11 @@ class IncrementalCompilerBuilder { private: static llvm::Expected> - create(std::string TT, std::vector ); + create(std::vector ); llvm::Expected> createCuda(bool device); std::vector UserArgs; - std::optional TargetTriple; llvm::StringRef OffloadArch; llvm::StringRef CudaSDKPath; diff --git a/clang/lib/Interpreter/Interpreter.cpp b/clang/lib/Interpreter/Interpreter.cpp index 37696b28976428..9f97a3c6b0be9e 100644 --- a/clang/lib/Interpreter/Interpreter.cpp +++ b/clang/lib/Interpreter/Interpreter.cpp @@ -132,8 +132,7 @@ CreateCI(const llvm::opt::ArgStringList ) { } // anonymous namespace llvm::Expected> -IncrementalCompilerBuilder::create(std::string TT, - std::vector ) { +IncrementalCompilerBuilder::create(std::vector ) { // If we don't know ClangArgv0 or the address of main() at this point, try // to guess it anyway (it's possible on some platforms). @@ -163,7 +162,8 @@ IncrementalCompilerBuilder::create(std::string TT, TextDiagnosticBuffer *DiagsBuffer = new TextDiagnosticBuffer; DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagsBuffer); - driver::Driver Driver(/*MainBinaryName=*/ClangArgv[0], TT, Diags); + driver::Driver Driver(/*MainBinaryName=*/ClangArgv[0], +llvm::sys::getProcessTriple(), Diags); Driver.setCheckInputsExist(false); // the input comes from mem buffers llvm::ArrayRef RF = llvm::ArrayRef(ClangArgv); std::unique_ptr Compilation(Driver.BuildCompilation(RF)); @@ -185,8 +185,7 @@ IncrementalCompilerBuilder::CreateCpp() { Argv.push_back("-xc++"); Argv.insert(Argv.end(), UserArgs.begin(), UserArgs.end()); - std::string TT = TargetTriple ? *TargetTriple : llvm::sys::getProcessTriple(); - return IncrementalCompilerBuilder::create(TT, Argv); + return IncrementalCompilerBuilder::create(Argv); } llvm::Expected> @@ -214,8 +213,7 @@ IncrementalCompilerBuilder::createCuda(bool device) { Argv.insert(Argv.end(), UserArgs.begin(), UserArgs.end()); - std::string TT = TargetTriple ? *TargetTriple : llvm::sys::getProcessTriple(); - return IncrementalCompilerBuilder::create(TT, Argv); + return IncrementalCompilerBuilder::create(Argv); } llvm::Expected> diff --git a/clang/unittests/Interpreter/CMakeLists.txt b/clang/unittests/Interpreter/CMakeLists.txt index 0ddedb283e07d1..712641afb976dd 100644 --- a/clang/unittests/Interpreter/CMakeLists.txt +++ b/clang/unittests/Interpreter/CMakeLists.txt @@ -7,7 +7,6 @@ set(LLVM_LINK_COMPONENTS ) add_clang_unittest(ClangReplInterpreterTests - IncrementalCompilerBuilderTest.cpp IncrementalProcessingTest.cpp InterpreterTest.cpp CodeCompletionTest.cpp diff --git a/clang/unittests/Interpreter/IncrementalCompilerBuilderTest.cpp b/clang/unittests/Interpreter/IncrementalCompilerBuilderTest.cpp deleted file mode 100644 index 1cc0223465c8fa..00 --- a/clang/unittests/Interpreter/IncrementalCompilerBuilderTest.cpp +++ /dev/null @@ -1,35 +0,0 @@ -//=== unittests/Interpreter/IncrementalCompilerBuilderTest.cpp ===// -// -// 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 "clang/Basic/TargetOptions.h" -#include "clang/Frontend/CompilerInstance.h" -#include "clang/Interpreter/Interpreter.h" -#include
[clang] [clang-repl] Pass triple to IncrementalCompilerBuilder as explicit argument (PR #84174)
weliveindetail wrote: Interesting, thanks for reporting! It's this code: ``` llvm::MemoryBuffer *MB = llvm::MemoryBuffer::getMemBuffer("").release(); Clang->getPreprocessorOpts().addRemappedFile("<<< inputs >>>", MB); ``` Apparently, it is related to releasing the MemBuffer and passing the raw pointer to `addRemappedFile()`, but I don't see why this fails here and not in any of the existing tests. Let me revert and investigate tomorrow. https://github.com/llvm/llvm-project/pull/84174 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] bugprone-assert-side-effect can detect side effect from non-const reference parameters (PR #84095)
@@ -60,16 +60,27 @@ AST_MATCHER_P2(Expr, hasSideEffect, bool, CheckFunctionCalls, } if (const auto *CExpr = dyn_cast(E)) { -bool Result = CheckFunctionCalls; +if (!CheckFunctionCalls) + return false; if (const auto *FuncDecl = CExpr->getDirectCallee()) { if (FuncDecl->getDeclName().isIdentifier() && IgnoredFunctionsMatcher.matches(*FuncDecl, Finder, Builder)) // exceptions come here -Result = false; - else if (const auto *MethodDecl = dyn_cast(FuncDecl)) -Result &= !MethodDecl->isConst(); +return false; + for (size_t I = 0; I < FuncDecl->getNumParams(); I++) { +const ParmVarDecl *P = FuncDecl->getParamDecl(I); +const Expr *ArgExpr = +I < CExpr->getNumArgs() ? CExpr->getArg(I) : nullptr; +QualType PT = P->getType().getCanonicalType(); 5chmidti wrote: `const QualType` https://github.com/llvm/llvm-project/pull/84095 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] bugprone-assert-side-effect can detect side effect from non-const reference parameters (PR #84095)
https://github.com/5chmidti edited https://github.com/llvm/llvm-project/pull/84095 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] bugprone-assert-side-effect can detect side effect from non-const reference parameters (PR #84095)
@@ -122,6 +122,10 @@ New check aliases Changes in existing checks ^^ +- Improved :doc:`bugprone-assert-side-effect + ` check by detection side 5chmidti wrote: `... detecting side effects from calling a method ...` https://github.com/llvm/llvm-project/pull/84095 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] bugprone-assert-side-effect can detect side effect from non-const reference parameters (PR #84095)
https://github.com/5chmidti approved this pull request. LGTM https://github.com/llvm/llvm-project/pull/84095 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Update value for __cpp_implicit_move (#84216) (PR #84228)
https://github.com/aniplcc updated https://github.com/llvm/llvm-project/pull/84228 >From 5de5eacdbd0ddf91f060edb003414b576365f2e0 Mon Sep 17 00:00:00 2001 From: aniplcc Date: Thu, 7 Mar 2024 01:39:30 +0530 Subject: [PATCH] [Clang] Update value for __cpp_implicit_move (#84216) --- clang/lib/Frontend/InitPreprocessor.cpp | 2 +- clang/test/Lexer/cxx-features.cpp | 2 +- clang/test/SemaCXX/cxx2b-p2266-disable-with-msvc-compat.cpp | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/clang/lib/Frontend/InitPreprocessor.cpp b/clang/lib/Frontend/InitPreprocessor.cpp index 9b979d810fa127..48ad92063bd461 100644 --- a/clang/lib/Frontend/InitPreprocessor.cpp +++ b/clang/lib/Frontend/InitPreprocessor.cpp @@ -736,7 +736,7 @@ static void InitializeCPlusPlusFeatureTestMacros(const LangOptions , } // C++23 features. if (LangOpts.CPlusPlus23) { -Builder.defineMacro("__cpp_implicit_move", "202011L"); +Builder.defineMacro("__cpp_implicit_move", "202207L"); Builder.defineMacro("__cpp_size_t_suffix", "202011L"); Builder.defineMacro("__cpp_if_consteval", "202106L"); Builder.defineMacro("__cpp_multidimensional_subscript", "202211L"); diff --git a/clang/test/Lexer/cxx-features.cpp b/clang/test/Lexer/cxx-features.cpp index 2650a3a82252ba..9496746c6fd663 100644 --- a/clang/test/Lexer/cxx-features.cpp +++ b/clang/test/Lexer/cxx-features.cpp @@ -45,7 +45,7 @@ #endif -#if check(implicit_move, 0, 0, 0, 0, 0, 202011, 202011) +#if check(implicit_move, 0, 0, 0, 0, 0, 202207, 202207) #error "wrong value for __cpp_implicit_move" #endif diff --git a/clang/test/SemaCXX/cxx2b-p2266-disable-with-msvc-compat.cpp b/clang/test/SemaCXX/cxx2b-p2266-disable-with-msvc-compat.cpp index d40491834d3988..9323dea24bd75b 100644 --- a/clang/test/SemaCXX/cxx2b-p2266-disable-with-msvc-compat.cpp +++ b/clang/test/SemaCXX/cxx2b-p2266-disable-with-msvc-compat.cpp @@ -9,7 +9,7 @@ #if __INCLUDE_LEVEL__ == 0 -#if __cpluscplus > 202002L && __cpp_implicit_move < 202011L +#if __cpluscplus > 202002L && __cpp_implicit_move < 202207L #error "__cpp_implicit_move not defined correctly" #endif ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][CUDA] Disable float128 diagnostics for device compilation (PR #83918)
https://github.com/Artem-B approved this pull request. https://github.com/llvm/llvm-project/pull/83918 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][NFC] Remove '--' separator in the linker wrapper usage (PR #84253)
llvmbot wrote: @llvm/pr-subscribers-clang @llvm/pr-subscribers-clang-driver @llvm/pr-subscribers-backend-amdgpu Author: Joseph Huber (jhuber6) Changes Summary: The very first version of the `clang-linker-wrapper` used `--` as a separator for the host and device arguments. I moved away from this towards a commandline parsing implementation years ago but never got around to officially removing this. --- Patch is 25.12 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/84253.diff 8 Files Affected: - (modified) clang/lib/Driver/ToolChains/Clang.cpp (-1) - (modified) clang/test/Driver/amdgpu-openmp-toolchain.c (+1-1) - (modified) clang/test/Driver/linker-wrapper-image.c (+9-9) - (modified) clang/test/Driver/linker-wrapper-libs.c (+7-7) - (modified) clang/test/Driver/linker-wrapper.c (+20-20) - (modified) clang/test/Driver/openmp-offload-gpu.c (+1-1) - (modified) clang/test/Driver/openmp-offload-infer.c (+1-1) - (modified) clang/tools/clang-linker-wrapper/LinkerWrapperOpts.td (-4) ``diff diff --git a/clang/lib/Driver/ToolChains/Clang.cpp b/clang/lib/Driver/ToolChains/Clang.cpp index 858d20fbfac015..6f75bf56cf7251 100644 --- a/clang/lib/Driver/ToolChains/Clang.cpp +++ b/clang/lib/Driver/ToolChains/Clang.cpp @@ -8886,7 +8886,6 @@ void LinkerWrapper::ConstructJob(Compilation , const JobAction , // Add the linker arguments to be forwarded by the wrapper. CmdArgs.push_back(Args.MakeArgString(Twine("--linker-path=") + LinkCommand->getExecutable())); - CmdArgs.push_back("--"); for (const char *LinkArg : LinkCommand->getArguments()) CmdArgs.push_back(LinkArg); diff --git a/clang/test/Driver/amdgpu-openmp-toolchain.c b/clang/test/Driver/amdgpu-openmp-toolchain.c index 4975e2f8a52399..849afb871ddbfc 100644 --- a/clang/test/Driver/amdgpu-openmp-toolchain.c +++ b/clang/test/Driver/amdgpu-openmp-toolchain.c @@ -11,7 +11,7 @@ // CHECK: "-cc1" "-triple" "x86_64-unknown-linux-gnu"{{.*}}"-emit-llvm-bc"{{.*}}"-x" "c" // CHECK: "-cc1" "-triple" "amdgcn-amd-amdhsa" "-aux-triple" "x86_64-unknown-linux-gnu"{{.*}}"-target-cpu" "gfx906"{{.*}}"-fcuda-is-device"{{.*}} // CHECK: "-cc1" "-triple" "x86_64-unknown-linux-gnu"{{.*}}"-emit-obj" -// CHECK: clang-linker-wrapper{{.*}}"--"{{.*}} "-o" "a.out" +// CHECK: clang-linker-wrapper{{.*}} "-o" "a.out" // RUN: %clang -ccc-print-phases --target=x86_64-unknown-linux-gnu -fopenmp -fopenmp-targets=amdgcn-amd-amdhsa -Xopenmp-target=amdgcn-amd-amdhsa -march=gfx906 %s 2>&1 \ // RUN: | FileCheck --check-prefix=CHECK-PHASES %s diff --git a/clang/test/Driver/linker-wrapper-image.c b/clang/test/Driver/linker-wrapper-image.c index 08f860f6cab0de..75475264135224 100644 --- a/clang/test/Driver/linker-wrapper-image.c +++ b/clang/test/Driver/linker-wrapper-image.c @@ -8,11 +8,11 @@ // RUN: %clang -cc1 %s -triple x86_64-unknown-linux-gnu -emit-obj -o %t.o \ // RUN: -fembed-offload-object=%t.out // RUN: clang-linker-wrapper --print-wrapped-module --dry-run --host-triple=x86_64-unknown-linux-gnu \ -// RUN: --linker-path=/usr/bin/ld -- %t.o -o a.out 2>&1 | FileCheck %s --check-prefixes=OPENMP,OPENMP-ELF +// RUN: --linker-path=/usr/bin/ld %t.o -o a.out 2>&1 | FileCheck %s --check-prefixes=OPENMP,OPENMP-ELF // RUN: clang-linker-wrapper --print-wrapped-module --dry-run -r --host-triple=x86_64-unknown-linux-gnu \ -// RUN: --linker-path=/usr/bin/ld -- %t.o -o a.out 2>&1 | FileCheck %s --check-prefixes=OPENMP-ELF,OPENMP-REL +// RUN: --linker-path=/usr/bin/ld %t.o -o a.out 2>&1 | FileCheck %s --check-prefixes=OPENMP-ELF,OPENMP-REL // RUN: clang-linker-wrapper --print-wrapped-module --dry-run --host-triple=x86_64-unknown-windows-gnu \ -// RUN: --linker-path=/usr/bin/ld -- %t.o -o a.out 2>&1 | FileCheck %s --check-prefixes=OPENMP,OPENMP-COFF +// RUN: --linker-path=/usr/bin/ld %t.o -o a.out 2>&1 | FileCheck %s --check-prefixes=OPENMP,OPENMP-COFF // OPENMP-ELF: @__start_omp_offloading_entries = external hidden constant [0 x %struct.__tgt_offload_entry] // OPENMP-ELF-NEXT: @__stop_omp_offloading_entries = external hidden constant [0 x %struct.__tgt_offload_entry] @@ -45,11 +45,11 @@ // RUN: %clang -cc1 %s -triple x86_64-unknown-linux-gnu -emit-obj -o %t.o \ // RUN: -fembed-offload-object=%t.out // RUN: clang-linker-wrapper --print-wrapped-module --dry-run --host-triple=x86_64-unknown-linux-gnu \ -// RUN: --linker-path=/usr/bin/ld -- %t.o -o a.out 2>&1 | FileCheck %s --check-prefixes=CUDA,CUDA-ELF +// RUN: --linker-path=/usr/bin/ld %t.o -o a.out 2>&1 | FileCheck %s --check-prefixes=CUDA,CUDA-ELF // RUN: clang-linker-wrapper --print-wrapped-module --dry-run -r --host-triple=x86_64-unknown-linux-gnu \ -// RUN: --linker-path=/usr/bin/ld -- %t.o -o a.out 2>&1 | FileCheck %s --check-prefixes=CUDA,CUDA-ELF +// RUN: --linker-path=/usr/bin/ld %t.o -o a.out 2>&1 | FileCheck %s --check-prefixes=CUDA,CUDA-ELF // RUN:
[clang] [clang][CodeGen] Allow memcpy replace with trivial auto var init (PR #84230)
antoniofrighetto wrote: I think manually checking if `TrivialAutoVarInit` is set (to `Pattern`?) may be a better fix, as there was only [one codepath](https://github.com/llvm/llvm-project/blob/main/clang/lib/CodeGen/CGDecl.cpp#L1972-L1974) in which we were not checking this. https://github.com/llvm/llvm-project/pull/84230 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][NFC] Remove '--' separator in the linker wrapper usage (PR #84253)
https://github.com/jhuber6 created https://github.com/llvm/llvm-project/pull/84253 Summary: The very first version of the `clang-linker-wrapper` used `--` as a separator for the host and device arguments. I moved away from this towards a commandline parsing implementation years ago but never got around to officially removing this. >From 6e5b672d9a1e1cbf57c5edd34dce90b1cd4d6b45 Mon Sep 17 00:00:00 2001 From: Joseph Huber Date: Wed, 6 Mar 2024 16:55:01 -0600 Subject: [PATCH] [Clang][NFC] Remove '--' separator in the linker wrapper usage Summary: The very first version of the `clang-linker-wrapper` used `--` as a separator for the host and device arguments. I moved away from this towards a commandline parsing implementation years ago but never got around to officially removing this. --- clang/lib/Driver/ToolChains/Clang.cpp | 1 - clang/test/Driver/amdgpu-openmp-toolchain.c | 2 +- clang/test/Driver/linker-wrapper-image.c | 18 - clang/test/Driver/linker-wrapper-libs.c | 14 +++ clang/test/Driver/linker-wrapper.c| 40 +-- clang/test/Driver/openmp-offload-gpu.c| 2 +- clang/test/Driver/openmp-offload-infer.c | 2 +- .../clang-linker-wrapper/LinkerWrapperOpts.td | 4 -- 8 files changed, 39 insertions(+), 44 deletions(-) diff --git a/clang/lib/Driver/ToolChains/Clang.cpp b/clang/lib/Driver/ToolChains/Clang.cpp index 858d20fbfac015..6f75bf56cf7251 100644 --- a/clang/lib/Driver/ToolChains/Clang.cpp +++ b/clang/lib/Driver/ToolChains/Clang.cpp @@ -8886,7 +8886,6 @@ void LinkerWrapper::ConstructJob(Compilation , const JobAction , // Add the linker arguments to be forwarded by the wrapper. CmdArgs.push_back(Args.MakeArgString(Twine("--linker-path=") + LinkCommand->getExecutable())); - CmdArgs.push_back("--"); for (const char *LinkArg : LinkCommand->getArguments()) CmdArgs.push_back(LinkArg); diff --git a/clang/test/Driver/amdgpu-openmp-toolchain.c b/clang/test/Driver/amdgpu-openmp-toolchain.c index 4975e2f8a52399..849afb871ddbfc 100644 --- a/clang/test/Driver/amdgpu-openmp-toolchain.c +++ b/clang/test/Driver/amdgpu-openmp-toolchain.c @@ -11,7 +11,7 @@ // CHECK: "-cc1" "-triple" "x86_64-unknown-linux-gnu"{{.*}}"-emit-llvm-bc"{{.*}}"-x" "c" // CHECK: "-cc1" "-triple" "amdgcn-amd-amdhsa" "-aux-triple" "x86_64-unknown-linux-gnu"{{.*}}"-target-cpu" "gfx906"{{.*}}"-fcuda-is-device"{{.*}} // CHECK: "-cc1" "-triple" "x86_64-unknown-linux-gnu"{{.*}}"-emit-obj" -// CHECK: clang-linker-wrapper{{.*}}"--"{{.*}} "-o" "a.out" +// CHECK: clang-linker-wrapper{{.*}} "-o" "a.out" // RUN: %clang -ccc-print-phases --target=x86_64-unknown-linux-gnu -fopenmp -fopenmp-targets=amdgcn-amd-amdhsa -Xopenmp-target=amdgcn-amd-amdhsa -march=gfx906 %s 2>&1 \ // RUN: | FileCheck --check-prefix=CHECK-PHASES %s diff --git a/clang/test/Driver/linker-wrapper-image.c b/clang/test/Driver/linker-wrapper-image.c index 08f860f6cab0de..75475264135224 100644 --- a/clang/test/Driver/linker-wrapper-image.c +++ b/clang/test/Driver/linker-wrapper-image.c @@ -8,11 +8,11 @@ // RUN: %clang -cc1 %s -triple x86_64-unknown-linux-gnu -emit-obj -o %t.o \ // RUN: -fembed-offload-object=%t.out // RUN: clang-linker-wrapper --print-wrapped-module --dry-run --host-triple=x86_64-unknown-linux-gnu \ -// RUN: --linker-path=/usr/bin/ld -- %t.o -o a.out 2>&1 | FileCheck %s --check-prefixes=OPENMP,OPENMP-ELF +// RUN: --linker-path=/usr/bin/ld %t.o -o a.out 2>&1 | FileCheck %s --check-prefixes=OPENMP,OPENMP-ELF // RUN: clang-linker-wrapper --print-wrapped-module --dry-run -r --host-triple=x86_64-unknown-linux-gnu \ -// RUN: --linker-path=/usr/bin/ld -- %t.o -o a.out 2>&1 | FileCheck %s --check-prefixes=OPENMP-ELF,OPENMP-REL +// RUN: --linker-path=/usr/bin/ld %t.o -o a.out 2>&1 | FileCheck %s --check-prefixes=OPENMP-ELF,OPENMP-REL // RUN: clang-linker-wrapper --print-wrapped-module --dry-run --host-triple=x86_64-unknown-windows-gnu \ -// RUN: --linker-path=/usr/bin/ld -- %t.o -o a.out 2>&1 | FileCheck %s --check-prefixes=OPENMP,OPENMP-COFF +// RUN: --linker-path=/usr/bin/ld %t.o -o a.out 2>&1 | FileCheck %s --check-prefixes=OPENMP,OPENMP-COFF // OPENMP-ELF: @__start_omp_offloading_entries = external hidden constant [0 x %struct.__tgt_offload_entry] // OPENMP-ELF-NEXT: @__stop_omp_offloading_entries = external hidden constant [0 x %struct.__tgt_offload_entry] @@ -45,11 +45,11 @@ // RUN: %clang -cc1 %s -triple x86_64-unknown-linux-gnu -emit-obj -o %t.o \ // RUN: -fembed-offload-object=%t.out // RUN: clang-linker-wrapper --print-wrapped-module --dry-run --host-triple=x86_64-unknown-linux-gnu \ -// RUN: --linker-path=/usr/bin/ld -- %t.o -o a.out 2>&1 | FileCheck %s --check-prefixes=CUDA,CUDA-ELF +// RUN: --linker-path=/usr/bin/ld %t.o -o a.out 2>&1 | FileCheck %s --check-prefixes=CUDA,CUDA-ELF // RUN: clang-linker-wrapper --print-wrapped-module --dry-run -r
[clang] [clang][CodeGen] Allow memcpy replace with trivial auto var init (PR #84230)
https://github.com/antoniofrighetto edited https://github.com/llvm/llvm-project/pull/84230 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Revert "[clang] Avoid memcopy for small structure with padding under … (PR #84230)
https://github.com/antoniofrighetto updated https://github.com/llvm/llvm-project/pull/84230 >From 91ca7b2e5c98a7caa8a97f05f57e84f68d861fa3 Mon Sep 17 00:00:00 2001 From: Antonio Frighetto Date: Wed, 6 Mar 2024 23:49:40 +0100 Subject: [PATCH] [clang][CodeGen] Allow memcpy replace with trivial auto var init Fixes: https://github.com/llvm/llvm-project/issues/84178. --- clang/lib/CodeGen/CGDecl.cpp | 43 ++- clang/test/CodeGen/aapcs-align.cpp| 4 +-- clang/test/CodeGen/aapcs64-align.cpp | 8 ++--- clang/test/CodeGen/attr-counted-by.c | 26 -- clang/test/CodeGenCXX/auto-var-init.cpp | 6 ++-- clang/test/CodeGenOpenCL/amdgpu-printf.cl | 9 + clang/test/OpenMP/bug54082.c | 4 +-- 7 files changed, 43 insertions(+), 57 deletions(-) diff --git a/clang/lib/CodeGen/CGDecl.cpp b/clang/lib/CodeGen/CGDecl.cpp index bbe14ef4c17244..aa9997b87ecfa7 100644 --- a/clang/lib/CodeGen/CGDecl.cpp +++ b/clang/lib/CodeGen/CGDecl.cpp @@ -1241,27 +1241,38 @@ static void emitStoresForConstant(CodeGenModule , const VarDecl , return; } - // If the initializer is small, use a handful of stores. + // If the initializer is small or trivialAutoVarInit is set, use a handful of + // stores. + bool IsTrivialAutoVarInitPattern = + CGM.getContext().getLangOpts().getTrivialAutoVarInit() == + LangOptions::TrivialAutoVarInitKind::Pattern; if (shouldSplitConstantStore(CGM, ConstantSize)) { if (auto *STy = dyn_cast(Ty)) { - const llvm::StructLayout *Layout = - CGM.getDataLayout().getStructLayout(STy); - for (unsigned i = 0; i != constant->getNumOperands(); i++) { -CharUnits CurOff = CharUnits::fromQuantity(Layout->getElementOffset(i)); -Address EltPtr = Builder.CreateConstInBoundsByteGEP( -Loc.withElementType(CGM.Int8Ty), CurOff); -emitStoresForConstant(CGM, D, EltPtr, isVolatile, Builder, - constant->getAggregateElement(i), IsAutoInit); + if (STy == Loc.getElementType() || + (STy != Loc.getElementType() && IsTrivialAutoVarInitPattern)) { +const llvm::StructLayout *Layout = +CGM.getDataLayout().getStructLayout(STy); +for (unsigned i = 0; i != constant->getNumOperands(); i++) { + CharUnits CurOff = + CharUnits::fromQuantity(Layout->getElementOffset(i)); + Address EltPtr = Builder.CreateConstInBoundsByteGEP( + Loc.withElementType(CGM.Int8Ty), CurOff); + emitStoresForConstant(CGM, D, EltPtr, isVolatile, Builder, +constant->getAggregateElement(i), IsAutoInit); +} +return; } - return; } else if (auto *ATy = dyn_cast(Ty)) { - for (unsigned i = 0; i != ATy->getNumElements(); i++) { -Address EltPtr = Builder.CreateConstGEP( -Loc.withElementType(ATy->getElementType()), i); -emitStoresForConstant(CGM, D, EltPtr, isVolatile, Builder, - constant->getAggregateElement(i), IsAutoInit); + if (ATy == Loc.getElementType() || + (ATy != Loc.getElementType() && IsTrivialAutoVarInitPattern)) { +for (unsigned i = 0; i != ATy->getNumElements(); i++) { + Address EltPtr = Builder.CreateConstGEP( + Loc.withElementType(ATy->getElementType()), i); + emitStoresForConstant(CGM, D, EltPtr, isVolatile, Builder, +constant->getAggregateElement(i), IsAutoInit); +} +return; } - return; } } diff --git a/clang/test/CodeGen/aapcs-align.cpp b/clang/test/CodeGen/aapcs-align.cpp index 2886a32974b066..4f393d9e6b7f32 100644 --- a/clang/test/CodeGen/aapcs-align.cpp +++ b/clang/test/CodeGen/aapcs-align.cpp @@ -134,8 +134,8 @@ void g6() { f6m(1, 2, 3, 4, 5, s); } // CHECK: define{{.*}} void @g6 -// CHECK: call void @f6(i32 noundef 1, [4 x i32] [i32 6, i32 7, i32 0, i32 0]) -// CHECK: call void @f6m(i32 noundef 1, i32 noundef 2, i32 noundef 3, i32 noundef 4, i32 noundef 5, [4 x i32] [i32 6, i32 7, i32 0, i32 0]) +// CHECK: call void @f6(i32 noundef 1, [4 x i32] [i32 6, i32 7, i32 0, i32 undef]) +// CHECK: call void @f6m(i32 noundef 1, i32 noundef 2, i32 noundef 3, i32 noundef 4, i32 noundef 5, [4 x i32] [i32 6, i32 7, i32 0, i32 undef]) // CHECK: declare void @f6(i32 noundef, [4 x i32]) // CHECK: declare void @f6m(i32 noundef, i32 noundef, i32 noundef, i32 noundef, i32 noundef, [4 x i32]) } diff --git a/clang/test/CodeGen/aapcs64-align.cpp b/clang/test/CodeGen/aapcs64-align.cpp index 759413cbc4b56f..de231f2123b975 100644 --- a/clang/test/CodeGen/aapcs64-align.cpp +++ b/clang/test/CodeGen/aapcs64-align.cpp @@ -75,8 +75,8 @@ void g4() { f4m(1, 2, 3, 4, 5, s); } // CHECK: define{{.*}} void @g4() -// CHECK: call void @f4(i32 noundef 1, [2 x i64] %{{.*}}) -// CHECK: void @f4m(i32 noundef 1, i32 noundef 2, i32 noundef 3, i32 noundef 4,
[clang-tools-extra] [clang-tidy] Fix handling --driver-mode= (PR #66553)
@@ -550,9 +555,91 @@ static llvm::IntrusiveRefCntPtr createBaseFS() { return BaseFS; } +static void recreateOptionsParserIfNeeded( +llvm::Expected , +llvm::ArrayRef Args, +const ClangTidyOptions ) { + + auto DoubleDashIt = std::find(Args.begin(), Args.end(), StringRef("--")); + + // Exit if we don't have any compiler arguments + if (DoubleDashIt == Args.end() || Args.empty() || + Args.back() == StringRef("--")) +return; + + auto IsDriverMode = [](StringRef Argument) { +return Argument.startswith("--driver-mode="); + }; + + // Exit if --driver-mode= is explicitly passed in compiler arguments + if (Args.end() != + std::find_if(std::next(DoubleDashIt), Args.end(), IsDriverMode)) +return; + + std::vector CommandArguments(std::next(DoubleDashIt), +Args.end()); + + // Add clang-tool as program name if not added + if (CommandArguments.empty() || + llvm::StringRef(CommandArguments.front()).startswith("-")) +CommandArguments.insert(CommandArguments.begin(), "clang-tool"); + + // Apply --extra-arg and --extra-arg-before to compiler arguments + CommandArguments = + OptionsParser->getArgumentsAdjuster()(CommandArguments, ""); + + // Apply ExtraArgsBefore from clang-tidy config to compiler arguments + if (EffectiveOptions.ExtraArgsBefore) +CommandArguments = tooling::getInsertArgumentAdjuster( +*EffectiveOptions.ExtraArgsBefore, +tooling::ArgumentInsertPosition::BEGIN)(CommandArguments, ""); + + // Apply ExtraArgs from clang-tidy config to compiler arguments + if (EffectiveOptions.ExtraArgs) +CommandArguments = tooling::getInsertArgumentAdjuster( +*EffectiveOptions.ExtraArgs, +tooling::ArgumentInsertPosition::END)(CommandArguments, ""); + + // Check if now we have --driver-mode= + auto DriverModeIt = std::find_if(CommandArguments.begin(), + CommandArguments.end(), IsDriverMode); + if (DriverModeIt == CommandArguments.end()) { +// Try to detect and add --driver-mode= +std::string ExeName = CommandArguments.front(); 5chmidti wrote: `const std::string` https://github.com/llvm/llvm-project/pull/66553 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits