[libclc] 25c0554 - [libclc] Move conversion builtins to the CLC library (#124727)
Author: Fraser Cormack Date: 2025-02-12T08:55:02Z New Revision: 25c055416643f3291dfaa8136cb3a17b00656779 URL: https://github.com/llvm/llvm-project/commit/25c055416643f3291dfaa8136cb3a17b00656779 DIFF: https://github.com/llvm/llvm-project/commit/25c055416643f3291dfaa8136cb3a17b00656779.diff LOG: [libclc] Move conversion builtins to the CLC library (#124727) This commit moves the implementations of conversion builtins to the CLC library. It keeps the dichotomy of regular vs. clspv implementations of the conversions. However, for the sake of a consistent interface all CLC conversion routines are built, even the ones that clspv opts out of in the user-facing OpenCL layer. It simultaneously updates the python script to use f-strings for formatting. Added: libclc/clc/include/clc/clc_convert.h libclc/clc/include/clc/float/definitions.h Modified: libclc/CMakeLists.txt libclc/generic/include/clc/convert.h libclc/generic/lib/gen_convert.py Removed: libclc/generic/include/clc/float/definitions.h diff --git a/libclc/CMakeLists.txt b/libclc/CMakeLists.txt index 2978fadc2c29f..c88ea9700d100 100644 --- a/libclc/CMakeLists.txt +++ b/libclc/CMakeLists.txt @@ -247,11 +247,27 @@ add_custom_target( "generate_convert.cl" DEPENDS convert.cl ) set_target_properties( "generate_convert.cl" PROPERTIES FOLDER "libclc/Sourcegenning" ) add_custom_command( - OUTPUT clspv-convert.cl - COMMAND ${Python3_EXECUTABLE} ${script_loc} --clspv > clspv-convert.cl + OUTPUT clc-convert.cl + COMMAND ${Python3_EXECUTABLE} ${script_loc} --clc > clc-convert.cl DEPENDS ${script_loc} ) -add_custom_target( "clspv-generate_convert.cl" DEPENDS clspv-convert.cl ) -set_target_properties( "clspv-generate_convert.cl" PROPERTIES FOLDER "libclc/Sourcegenning" ) +add_custom_target( "clc-generate_convert.cl" DEPENDS clc-convert.cl ) +set_target_properties( "clc-generate_convert.cl" PROPERTIES FOLDER "libclc/Sourcegenning" ) + +if ( clspv-- IN_LIST LIBCLC_TARGETS_TO_BUILD OR clspv64-- IN_LIST LIBCLC_TARGETS_TO_BUILD ) + add_custom_command( +OUTPUT clspv-convert.cl +COMMAND ${Python3_EXECUTABLE} ${script_loc} --clspv > clspv-convert.cl +DEPENDS ${script_loc} ) + add_custom_target( "clspv-generate_convert.cl" DEPENDS clspv-convert.cl ) + set_target_properties( "clspv-generate_convert.cl" PROPERTIES FOLDER "libclc/Sourcegenning" ) + + add_custom_command( +OUTPUT clc-clspv-convert.cl +COMMAND ${Python3_EXECUTABLE} ${script_loc} --clc --clspv > clc-clspv-convert.cl +DEPENDS ${script_loc} ) + add_custom_target( "clc-clspv-generate_convert.cl" DEPENDS clc-clspv-convert.cl ) + set_target_properties( "clc-clspv-generate_convert.cl" PROPERTIES FOLDER "libclc/Sourcegenning" ) +endif() enable_testing() @@ -289,6 +305,12 @@ foreach( t ${LIBCLC_TARGETS_TO_BUILD} ) set( clc_lib_files ) set( clc_dirs ${dirs} generic ) + if( ARCH STREQUAL clspv OR ARCH STREQUAL clspv64 ) +set( clc_gen_files clc-clspv-convert.cl ) + else() +set( clc_gen_files clc-convert.cl ) + endif() + libclc_configure_lib_source( clc_lib_files CLC_INTERNAL @@ -372,6 +394,7 @@ foreach( t ${LIBCLC_TARGETS_TO_BUILD} ) COMPILE_FLAGS ${clc_build_flags} OPT_FLAGS ${opt_flags} LIB_FILES ${clc_lib_files} + GEN_FILES ${clc_gen_files} ) list( APPEND build_flags diff --git a/libclc/clc/include/clc/clc_convert.h b/libclc/clc/include/clc/clc_convert.h new file mode 100644 index 0..20bbd57540b30 --- /dev/null +++ b/libclc/clc/include/clc/clc_convert.h @@ -0,0 +1,98 @@ +#ifndef __CLC_CLC_CONVERT_H__ +#define __CLC_CLC_CONVERT_H__ + +#define _CLC_CONVERT_DECL(FROM_TYPE, TO_TYPE, SUFFIX) \ + _CLC_OVERLOAD _CLC_DECL TO_TYPE __clc_convert_##TO_TYPE##SUFFIX(FROM_TYPE x); + +#define _CLC_VECTOR_CONVERT_DECL(FROM_TYPE, TO_TYPE, SUFFIX) \ + _CLC_CONVERT_DECL(FROM_TYPE, TO_TYPE, SUFFIX) \ + _CLC_CONVERT_DECL(FROM_TYPE##2, TO_TYPE##2, SUFFIX) \ + _CLC_CONVERT_DECL(FROM_TYPE##3, TO_TYPE##3, SUFFIX) \ + _CLC_CONVERT_DECL(FROM_TYPE##4, TO_TYPE##4, SUFFIX) \ + _CLC_CONVERT_DECL(FROM_TYPE##8, TO_TYPE##8, SUFFIX) \ + _CLC_CONVERT_DECL(FROM_TYPE##16, TO_TYPE##16, SUFFIX) + +#define _CLC_VECTOR_CONVERT_FROM1(FROM_TYPE, SUFFIX) \ + _CLC_VECTOR_CONVERT_DECL(FROM_TYPE, char, SUFFIX) \ + _CLC_VECTOR_CONVERT_DECL(FROM_TYPE, uchar, SUFFIX) \ + _CLC_VECTOR_CONVERT_DECL(FROM_TYPE, int, SUFFIX) \ + _CLC_VECTOR_CONVERT_DECL(FROM_TYPE, uint, SUFFIX) \ + _CLC_VECTOR_CONVERT_DECL(FROM_TYPE, short, SUFFIX) \ + _CLC_VECTOR_CONVERT_DECL(FROM_TYPE, usho
[clang] [clang][perf-training] Support excluding LLVM build from PGO training (PR #126876)
https://github.com/petrhosek created https://github.com/llvm/llvm-project/pull/126876 Using LLVM build itself for PGO training is convenient and a great starting point but it also has several issues: * LLVM build implicitly depends on tools other than CMake and C/C++ compiler and if those tools aren't available in PATH, the build will fail. * LLVM build also requires standard headers and libraries which may not always be available in the default location requiring an explicit sysroot. * Building a single configuration (-DCMAKE_BUILD_TYPE=Release) only exercises the -O3 pipeline and can pesimize other configurations. * Building for the host target doesn't exercise all other targets. * Since LLVMSupport is a static library, this doesn't exercise the linker (beyond what the CMake itself does). Rather than using LLVM build, ideally we would provide a more minimal, purpose built corpus. While we're working on building such a corpus, provide a CMake option that lets vendors disable the use LLVM build for PGO training. >From 7297d3bf62624f57579d7a1facf7cac36fc75dd4 Mon Sep 17 00:00:00 2001 From: Petr Hosek Date: Tue, 11 Feb 2025 08:28:05 + Subject: [PATCH] [clang][perf-training] Support excluding LLVM build from PGO training Using LLVM build itself for PGO training is convenient and a great starting point but it also has several issues: * LLVM build implicitly depends on tools other than CMake and C/C++ compiler and if those tools aren't available in PATH, the build will fail. * LLVM build also requires standard headers and libraries which may not always be available in the default location requiring an explicit sysroot. * Building a single configuration (-DCMAKE_BUILD_TYPE=Release) only exercises the -O3 pipeline and can pesimize other configurations. * Building for the host target doesn't exercise all other targets. * Since LLVMSupport is a static library, this doesn't exercise the linker (beyond what the CMake itself does). Rather than using LLVM build, ideally we would provide a more minimal, purpose built corpus. While we're working on building such a corpus, provide a CMake option that lets vendors disable the use LLVM build for PGO training. --- clang/utils/perf-training/CMakeLists.txt | 6 ++ clang/utils/perf-training/lit.cfg | 3 +++ clang/utils/perf-training/lit.site.cfg.in | 1 + 3 files changed, 10 insertions(+) diff --git a/clang/utils/perf-training/CMakeLists.txt b/clang/utils/perf-training/CMakeLists.txt index 4aed086563ee9..0c1cdd9a1fb60 100644 --- a/clang/utils/perf-training/CMakeLists.txt +++ b/clang/utils/perf-training/CMakeLists.txt @@ -6,6 +6,12 @@ set(CLANG_PGO_TRAINING_DATA "${CMAKE_CURRENT_SOURCE_DIR}" CACHE PATH set(CLANG_PGO_TRAINING_DATA_SOURCE_DIR OFF CACHE STRING "Path to source directory containing cmake project with source files to use for generating pgo data") set(CLANG_PGO_TRAINING_DEPS "" CACHE STRING "Extra dependencies needed to build the PGO training data.") +option(CLANG_PGO_TRAINING_USE_LLVM_BUILD "Use LLVM build for generating PGO data" ON) + +llvm_canonicalize_cmake_booleans( + CLANG_PGO_TRAINING_USE_LLVM +) + if(LLVM_BUILD_INSTRUMENTED) configure_lit_site_cfg( ${CMAKE_CURRENT_SOURCE_DIR}/lit.site.cfg.in diff --git a/clang/utils/perf-training/lit.cfg b/clang/utils/perf-training/lit.cfg index adefc7893ac44..3f6089b7139a7 100644 --- a/clang/utils/perf-training/lit.cfg +++ b/clang/utils/perf-training/lit.cfg @@ -27,6 +27,9 @@ config.clang = lit.util.which('clang', config.clang_tools_dir).replace('\\', '/' config.name = 'Clang Perf Training' config.suffixes = ['.c', '.cc', '.cpp', '.m', '.mm', '.cu', '.ll', '.cl', '.s', '.S', '.modulemap', '.test'] +if not config.use_llvm_build: +config.excludes = ['llvm-support'] + cc1_wrapper = '%s %s/perf-helper.py cc1' % (config.python_exe, config.perf_helper_dir) use_lit_shell = os.environ.get("LIT_USE_INTERNAL_SHELL") diff --git a/clang/utils/perf-training/lit.site.cfg.in b/clang/utils/perf-training/lit.site.cfg.in index 9d279d552919a..da81ec21a28a6 100644 --- a/clang/utils/perf-training/lit.site.cfg.in +++ b/clang/utils/perf-training/lit.site.cfg.in @@ -11,6 +11,7 @@ config.python_exe = "@Python3_EXECUTABLE@" config.cmake_exe = "@CMAKE_COMMAND@" config.llvm_src_dir ="@CMAKE_SOURCE_DIR@" config.cmake_generator ="@CMAKE_GENERATOR@" +config.use_llvm_build = @CLANG_PGO_TRAINING_USE_LLVM_BUILD@ # Let the main config do the real work. lit_config.load_config(config, "@CLANG_SOURCE_DIR@/utils/perf-training/lit.cfg") ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][bytecode] Fix operator new source expression (PR #126870)
https://github.com/tbaederr closed https://github.com/llvm/llvm-project/pull/126870 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 20506a0 - [clang][bytecode] Fix operator new source expression (#126870)
Author: Timm Baeder Date: 2025-02-12T10:05:49+01:00 New Revision: 20506a0a15f9c4a7dc1cd0b4fa2dec8449074ab8 URL: https://github.com/llvm/llvm-project/commit/20506a0a15f9c4a7dc1cd0b4fa2dec8449074ab8 DIFF: https://github.com/llvm/llvm-project/commit/20506a0a15f9c4a7dc1cd0b4fa2dec8449074ab8.diff LOG: [clang][bytecode] Fix operator new source expression (#126870) ... for composite element types. Looks like I forgot this in e6030d389571b3f1b0f0c5a35b7fa45937ed0f6c Added: Modified: clang/lib/AST/ByteCode/InterpBuiltin.cpp clang/test/AST/ByteCode/new-delete.cpp Removed: diff --git a/clang/lib/AST/ByteCode/InterpBuiltin.cpp b/clang/lib/AST/ByteCode/InterpBuiltin.cpp index 0e586725b5869..55ac41736344d 100644 --- a/clang/lib/AST/ByteCode/InterpBuiltin.cpp +++ b/clang/lib/AST/ByteCode/InterpBuiltin.cpp @@ -1683,7 +1683,7 @@ static bool interp__builtin_operator_new(InterpState &S, CodePtr OpPC, assert(!ElemT); // Structs etc. const Descriptor *Desc = S.P.createDescriptor( - Call, ElemType.getTypePtr(), Descriptor::InlineDescMD, + NewCall, ElemType.getTypePtr(), Descriptor::InlineDescMD, /*IsConst=*/false, /*IsTemporary=*/false, /*IsMutable=*/false, /*Init=*/nullptr); diff --git a/clang/test/AST/ByteCode/new-delete.cpp b/clang/test/AST/ByteCode/new-delete.cpp index e60ff894c9715..31f066b37858d 100644 --- a/clang/test/AST/ByteCode/new-delete.cpp +++ b/clang/test/AST/ByteCode/new-delete.cpp @@ -840,10 +840,17 @@ template struct SS { constexpr SS(unsigned long long N) : data(nullptr){ -data = alloc.allocate(N); // #call +data = alloc.allocate(N); for(std::size_t i = 0; i < N; i ++) -std::construct_at(data + i, i); // #construct_call +std::construct_at(data + i, i); } + +constexpr SS() +: data(nullptr){ +data = alloc.allocate(1); +std::construct_at(data); +} + constexpr T operator[](std::size_t i) const { return data[i]; } @@ -855,6 +862,7 @@ struct SS { T* data; }; constexpr unsigned short ssmall = SS(100)[42]; +constexpr auto Ss = SS()[0]; ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [NFC] Delete useless call. (PR #126875)
https://github.com/schittir converted_to_draft https://github.com/llvm/llvm-project/pull/126875 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][perf-training] Support excluding LLVM build from PGO training (PR #126876)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Petr Hosek (petrhosek) Changes Using LLVM build itself for PGO training is convenient and a great starting point but it also has several issues: * LLVM build implicitly depends on tools other than CMake and C/C++ compiler and if those tools aren't available in PATH, the build will fail. * LLVM build also requires standard headers and libraries which may not always be available in the default location requiring an explicit sysroot. * Building a single configuration (-DCMAKE_BUILD_TYPE=Release) only exercises the -O3 pipeline and can pesimize other configurations. * Building for the host target doesn't exercise all other targets. * Since LLVMSupport is a static library, this doesn't exercise the linker (beyond what the CMake itself does). Rather than using LLVM build, ideally we would provide a more minimal, purpose built corpus. While we're working on building such a corpus, provide a CMake option that lets vendors disable the use LLVM build for PGO training. --- Full diff: https://github.com/llvm/llvm-project/pull/126876.diff 3 Files Affected: - (modified) clang/utils/perf-training/CMakeLists.txt (+6) - (modified) clang/utils/perf-training/lit.cfg (+3) - (modified) clang/utils/perf-training/lit.site.cfg.in (+1) ``diff diff --git a/clang/utils/perf-training/CMakeLists.txt b/clang/utils/perf-training/CMakeLists.txt index 4aed086563ee9..0c1cdd9a1fb60 100644 --- a/clang/utils/perf-training/CMakeLists.txt +++ b/clang/utils/perf-training/CMakeLists.txt @@ -6,6 +6,12 @@ set(CLANG_PGO_TRAINING_DATA "${CMAKE_CURRENT_SOURCE_DIR}" CACHE PATH set(CLANG_PGO_TRAINING_DATA_SOURCE_DIR OFF CACHE STRING "Path to source directory containing cmake project with source files to use for generating pgo data") set(CLANG_PGO_TRAINING_DEPS "" CACHE STRING "Extra dependencies needed to build the PGO training data.") +option(CLANG_PGO_TRAINING_USE_LLVM_BUILD "Use LLVM build for generating PGO data" ON) + +llvm_canonicalize_cmake_booleans( + CLANG_PGO_TRAINING_USE_LLVM +) + if(LLVM_BUILD_INSTRUMENTED) configure_lit_site_cfg( ${CMAKE_CURRENT_SOURCE_DIR}/lit.site.cfg.in diff --git a/clang/utils/perf-training/lit.cfg b/clang/utils/perf-training/lit.cfg index adefc7893ac44..3f6089b7139a7 100644 --- a/clang/utils/perf-training/lit.cfg +++ b/clang/utils/perf-training/lit.cfg @@ -27,6 +27,9 @@ config.clang = lit.util.which('clang', config.clang_tools_dir).replace('\\', '/' config.name = 'Clang Perf Training' config.suffixes = ['.c', '.cc', '.cpp', '.m', '.mm', '.cu', '.ll', '.cl', '.s', '.S', '.modulemap', '.test'] +if not config.use_llvm_build: +config.excludes = ['llvm-support'] + cc1_wrapper = '%s %s/perf-helper.py cc1' % (config.python_exe, config.perf_helper_dir) use_lit_shell = os.environ.get("LIT_USE_INTERNAL_SHELL") diff --git a/clang/utils/perf-training/lit.site.cfg.in b/clang/utils/perf-training/lit.site.cfg.in index 9d279d552919a..da81ec21a28a6 100644 --- a/clang/utils/perf-training/lit.site.cfg.in +++ b/clang/utils/perf-training/lit.site.cfg.in @@ -11,6 +11,7 @@ config.python_exe = "@Python3_EXECUTABLE@" config.cmake_exe = "@CMAKE_COMMAND@" config.llvm_src_dir ="@CMAKE_SOURCE_DIR@" config.cmake_generator ="@CMAKE_GENERATOR@" +config.use_llvm_build = @CLANG_PGO_TRAINING_USE_LLVM_BUILD@ # Let the main config do the real work. lit_config.load_config(config, "@CLANG_SOURCE_DIR@/utils/perf-training/lit.cfg") `` https://github.com/llvm/llvm-project/pull/126876 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][perf-training] Support excluding LLVM build from PGO training (PR #126876)
petrhosek wrote: @tstellar We're trying to build a more minimal corpus that would address the issues I listed with @ilovepi. In the meantime, it'd be helpful to have this option since the current implementation actually breaks on our builders (which don't have host toolchain and sysroot installed). https://github.com/llvm/llvm-project/pull/126876 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [NFC] Delete useless call. (PR #126875)
https://github.com/schittir closed https://github.com/llvm/llvm-project/pull/126875 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [llvm:ir] Add support for constant data exceeding 4GiB (PR #126481)
@@ -644,7 +644,7 @@ class ConstantDataSequential : public ConstantData { Type *getElementType() const; /// Return the number of elements in the array or vector. - unsigned getNumElements() const; + uint64_t getNumElements() const; pzzp wrote: Should I add these test to regression tests? but it is really large https://github.com/llvm/llvm-project/pull/126481 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] Add option assume-at-least-one-iteration (PR #125494)
https://github.com/NagyDonat closed https://github.com/llvm/llvm-project/pull/125494 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] edbc1fb - [analyzer] Add option assume-at-least-one-iteration (#125494)
Author: Donát Nagy Date: 2025-02-12T11:56:02+01:00 New Revision: edbc1fb228acd7746d91cd72d476c063704504b8 URL: https://github.com/llvm/llvm-project/commit/edbc1fb228acd7746d91cd72d476c063704504b8 DIFF: https://github.com/llvm/llvm-project/commit/edbc1fb228acd7746d91cd72d476c063704504b8.diff LOG: [analyzer] Add option assume-at-least-one-iteration (#125494) This commit adds the new analyzer option `assume-at-least-one-iteration`, which is `false` by default, but can be set to `true` to ensure that the analyzer always assumes at least one iteration in loops. In some situations this "loop is skipped" execution path is an important corner case that may evade the notice of the developer and hide significant bugs -- however, there are also many situations where it's guaranteed that at least one iteration will happen (e.g. some data structure is always nonempty), but the analyzer cannot realize this and will produce false positives when it assumes that the loop is skipped. This commit refactors some logic around the implementation of the new feature, but the only functional change is introducing the new analyzer option. If the new option is left in its default state (false), then the analysis is functionally equivalent to an analysis done with a version before this commit. Added: Modified: clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def clang/lib/StaticAnalyzer/Core/ExprEngine.cpp clang/test/Analysis/analyzer-config.c clang/test/Analysis/loop-assumptions.c Removed: diff --git a/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def b/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def index 34bb7a809162b..a9b8d0753673b 100644 --- a/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def +++ b/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def @@ -294,6 +294,16 @@ ANALYZER_OPTION( bool, ShouldUnrollLoops, "unroll-loops", "Whether the analysis should try to unroll loops with known bounds.", false) +ANALYZER_OPTION( +bool, ShouldAssumeAtLeastOneIteration, "assume-at-least-one-iteration", +"Whether the analyzer should always assume at least one iteration in " +"loops where the loop condition is opaque (i.e. the analyzer cannot " +"determine if it's true or false). Setting this to true eliminates some " +"false positives (where e.g. a structure is nonempty, but the analyzer " +"does not notice this); but it also eliminates some true positives (e.g. " +"cases where a structure can be empty and this causes buggy behavior).", +false) + ANALYZER_OPTION( bool, ShouldDisplayNotesAsEvents, "notes-as-events", "Whether the bug reporter should transparently treat extra note diagnostic " diff --git a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp index e3ec7c57571c8..c799687ccb44f 100644 --- a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp +++ b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp @@ -2813,13 +2813,24 @@ void ExprEngine::processBranch( if (StTrue && StFalse) assert(!isa(Condition)); +// We want to ensure consistent behavior between `eagerly-assume=false`, +// when the state split is always performed by the `assumeCondition()` +// call within this function and `eagerly-assume=true` (the default), when +// some conditions (comparison operators, unary negation) can trigger a +// state split before this callback. There are some contrived corner cases +// that behave diff erently with and without `eagerly-assume`, but I don't +// know about an example that could plausibly appear in "real" code. +bool BothFeasible = +(StTrue && StFalse) || +didEagerlyAssumeBifurcateAt(PrevState, dyn_cast(Condition)); + if (StTrue) { - // If we are processing a loop condition where two iterations have - // already been completed and the false branch is also feasible, then - // don't assume a third iteration because it is a redundant execution - // path (unlikely to be diff erent from earlier loop exits) and can cause - // false positives if e.g. the loop iterates over a two-element structure - // with an opaque condition. + // In a loop, if both branches are feasible (i.e. the analyzer doesn't + // understand the loop condition) and two iterations have already been + // completed, then don't assume a third iteration because it is a + // redundant execution path (unlikely to be diff erent from earlier loop + // exits) and can cause false positives if e.g. the loop iterates over a + // two-element structure with an opaque condition. // // The iteration count "2" is hardcoded because it's the natural limit: // * the fact that the programmer wrote a loop (and not just an `if`) @@ -2830,10 +2841,7 @@ void ExprEngine::processBranch(
[clang] [clang][Sema] Fix type of an statement expression ending with an atomic type (PR #119711)
https://github.com/alejandro-alvarez-sonarsource updated https://github.com/llvm/llvm-project/pull/119711 From d398fa13c2fa141954c79ca68a59c6ac506b393f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20=C3=81lvarez=20Ayll=C3=B3n?= Date: Wed, 11 Dec 2024 15:43:58 +0100 Subject: [PATCH 1/5] Add regression test --- clang/test/Sema/gh106576.c | 16 1 file changed, 16 insertions(+) create mode 100644 clang/test/Sema/gh106576.c diff --git a/clang/test/Sema/gh106576.c b/clang/test/Sema/gh106576.c new file mode 100644 index 0..792977dea1413 --- /dev/null +++ b/clang/test/Sema/gh106576.c @@ -0,0 +1,16 @@ +// RUN: %clang_cc1 -fsyntax-only -verify %s + +typedef _Atomic char atomic_char; + +typedef _Atomic char atomic_char; + +atomic_char counter; + +char load_plus_one(void) { + return ({counter;}) + 1; // no crash +} + +char type_of_stmt_expr(void) { + typeof(({counter;})) y = ""; // expected-error-re {{incompatible pointer to integer conversion initializing 'typeof (({{{.*}}}))' (aka 'char') with an expression of type 'char[1]'}} + return y; +} From 296aa35fe32449067c69d2b40031af0dd6822a07 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20=C3=81lvarez=20Ayll=C3=B3n?= Date: Thu, 12 Dec 2024 15:08:56 +0100 Subject: [PATCH 2/5] Tentative fix --- clang/lib/Sema/SemaExpr.cpp | 13 +++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index 20bf6f7f6f28f..165447efb345c 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -15861,10 +15861,19 @@ ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) return Cast->getSubExpr(); + auto Ty = E->getType().getUnqualifiedType(); + + // If the type is an atomic, the statement type is the underlying type. + if (const AtomicType *AT = Ty->getAs()) { +Ty = AT->getValueType().getUnqualifiedType(); +return ImplicitCastExpr::Create(Context, Ty, CK_AtomicToNonAtomic, E, +/*base path*/ nullptr, VK_PRValue, +FPOptionsOverride()); + } + // FIXME: Provide a better location for the initialization. return PerformCopyInitialization( - InitializedEntity::InitializeStmtExprResult( - E->getBeginLoc(), E->getType().getUnqualifiedType()), + InitializedEntity::InitializeStmtExprResult(E->getBeginLoc(), Ty), SourceLocation(), E); } From d13e1090c641314aae8eef50f1b0fb5c0ec67e39 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20=C3=81lvarez=20Ayll=C3=B3n?= Date: Thu, 12 Dec 2024 15:30:07 +0100 Subject: [PATCH 3/5] Use PerformImplicitConversion --- clang/lib/Sema/SemaExpr.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index 165447efb345c..45ae97807c203 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -15866,9 +15866,7 @@ ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { // If the type is an atomic, the statement type is the underlying type. if (const AtomicType *AT = Ty->getAs()) { Ty = AT->getValueType().getUnqualifiedType(); -return ImplicitCastExpr::Create(Context, Ty, CK_AtomicToNonAtomic, E, -/*base path*/ nullptr, VK_PRValue, -FPOptionsOverride()); +return PerformImplicitConversion(E, Ty, AssignmentAction::Casting); } // FIXME: Provide a better location for the initialization. From 02d8385cc0f824ff0436a7b0a42d16555e5ee0c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20=C3=81lvarez=20Ayll=C3=B3n?= Date: Wed, 18 Dec 2024 09:19:51 +0100 Subject: [PATCH 4/5] Add release note --- clang/docs/ReleaseNotes.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index 408b2800f9e79..24420d9dd49d5 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -853,6 +853,7 @@ Bug Fixes to AST Handling - Clang now uses the location of the begin of the member expression for ``CallExpr`` involving deduced ``this``. (#GH116928) - Fixed printout of AST that uses pack indexing expression. (#GH116486) +- Fixed type deduction of an statement expression (a GCC extension) ending with an atomic type. (#GH106576) Miscellaneous Bug Fixes ^^^ From 46a2b3b9aab3f3778c15e3f021241bcf612e3be6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20=C3=81lvarez=20Ayll=C3=B3n?= Date: Wed, 12 Feb 2025 11:22:03 +0100 Subject: [PATCH 5/5] Fix by using getAtomicUnqualifiedType --- clang/lib/Sema/SemaExpr.cpp | 11 ++- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index c564949cb2e47..0cdbca4f6723b 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -1594
[clang] [llvm] [llvm:ir] Add support for constant data exceeding 4GiB (PR #126481)
@@ -644,7 +644,7 @@ class ConstantDataSequential : public ConstantData { Type *getElementType() const; /// Return the number of elements in the array or vector. - unsigned getNumElements() const; + uint64_t getNumElements() const; pzzp wrote: ok, I update `getElementAsInteger` and `getElementAsFloat`, it seems that these two are used in codegen. I test it with this script's generation ```bash #!/bin/bash cat << EOF target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128" target triple = "x86_64-unknown-linux-gnu" EOF # generate @ARR = global [1073741825 x i32] [...], align 16 for (( i = 0; i<1024; i++)); do ARR_1K+="i32 $((RANDOM % 97)), " done for (( i = 0; i<1024; i++)); do ARR_1M+="$ARR_1K" done echo -n "@ARR = global [$((1024 * 1024 * 1024 + 1)) x i32] [" for (( i = 0; i<$((1024)); i++)); do echo -n "$ARR_1M" done echo -n 'i32 233], align 16' cat << EOF !llvm.module.flags = !{!0, !1, !2, !3} !0 = !{i32 1, !"wchar_size", i32 4} !1 = !{i32 8, !"PIC Level", i32 2} !2 = !{i32 7, !"PIE Level", i32 2} !3 = !{i32 7, !"uwtable", i32 2} EOF ``` I checked that the result is ok. The last number in result asm is `233` and the size is `4294967300` https://github.com/llvm/llvm-project/pull/126481 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][Sema] Fix initialization of `NonTypeTemplateParmDecl`... (PR #121768)
Alejandro =?utf-8?q?Álvarez_Ayllón?=, Alejandro =?utf-8?q?Álvarez_Ayllón?=, Alejandro =?utf-8?q?Álvarez_Ayllón?=, Alejandro =?utf-8?q?Álvarez_Ayllón?=, Alejandro =?utf-8?q?Álvarez_Ayllón?=, Alejandro =?utf-8?q?Álvarez_Ayllón?Message-ID: In-Reply-To: @@ -786,12 +786,16 @@ NonTypeTemplateParmDecl *NonTypeTemplateParmDecl::Create( QualType T, bool ParameterPack, TypeSourceInfo *TInfo) { AutoType *AT = C.getLangOpts().CPlusPlus20 ? T->getContainedAutoType() : nullptr; - return new (C, DC, - additionalSizeToAlloc, -Expr *>(0, -AT && AT->isConstrained() ? 1 : 0)) - NonTypeTemplateParmDecl(DC, StartLoc, IdLoc, D, P, Id, T, ParameterPack, - TInfo); + bool const HasConstraint = AT && AT->isConstrained(); zyn0217 wrote: We prefer `const bool` afaik https://github.com/llvm/llvm-project/pull/121768 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][Sema] Fix initialization of `NonTypeTemplateParmDecl`... (PR #121768)
Alejandro =?utf-8?q?=C3=81lvarez_Ayll=C3=B3n?=, Alejandro =?utf-8?q?=C3=81lvarez_Ayll=C3=B3n?=, Alejandro =?utf-8?q?=C3=81lvarez_Ayll=C3=B3n?=, Alejandro =?utf-8?q?=C3=81lvarez_Ayll=C3=B3n?=, Alejandro =?utf-8?q?=C3=81lvarez_Ayll=C3=B3n?=, Alejandro =?utf-8?q?=C3=81lvarez_Ayll=C3=B3n?= Message-ID: In-Reply-To: https://github.com/zyn0217 approved this pull request. LGTM modulo a nit https://github.com/llvm/llvm-project/pull/121768 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][Sema] Fix initialization of `NonTypeTemplateParmDecl`... (PR #121768)
Alejandro =?utf-8?q?Álvarez_Ayllón?=, Alejandro =?utf-8?q?Álvarez_Ayllón?=, Alejandro =?utf-8?q?Álvarez_Ayllón?=, Alejandro =?utf-8?q?Álvarez_Ayllón?=, Alejandro =?utf-8?q?Álvarez_Ayllón?=, Alejandro =?utf-8?q?Álvarez_Ayllón?Message-ID: In-Reply-To: https://github.com/zyn0217 edited https://github.com/llvm/llvm-project/pull/121768 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][Sema] Add diagnostic note for reference of function-like macros requiring without parentheses (PR #123495)
https://github.com/StarOne01 updated https://github.com/llvm/llvm-project/pull/123495 >From ea6c9ca9cffbf4327fc7bab85e37e2a3c2c0f0cd Mon Sep 17 00:00:00 2001 From: Prashanth Date: Sun, 19 Jan 2025 07:28:24 +0530 Subject: [PATCH 01/12] [clang][Sema] Add diagnostic note for function-like macros requiring parentheses --- clang/include/clang/Basic/DiagnosticSemaKinds.td | 2 ++ clang/lib/Sema/SemaExpr.cpp | 15 ++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td index bcae9e9f30093..d9c8fcc66acf2 100644 --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -5961,6 +5961,8 @@ def err_fold_expression_limit_exceeded: Error< "instantiating fold expression with %0 arguments exceeded expression nesting " "limit of %1">, DefaultFatal, NoSFINAE; +def note_function_like_macro_requires_parens : Note< + "'%0' exists, but as a function-like macro; perhaps, did you forget the parentheses?">; def err_unexpected_typedef : Error< "unexpected type name %0: expected expression">; def err_unexpected_namespace : Error< diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index 3cd4010740d19..dff03ac31ef2a 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -2522,6 +2522,19 @@ bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, DC = DC->getLookupParent(); } + // Check whether a similar function-like macro exists and suggest it + if (IdentifierInfo *II = Name.getAsIdentifierInfo()) { +if (II->hasMacroDefinition()) { + MacroInfo *MI = PP.getMacroInfo(II); + if (MI && MI->isFunctionLike()) { +Diag( R.getNameLoc() ,diag::err_undeclared_var_use) << II->getName(); +Diag(MI->getDefinitionLoc(), diag::note_function_like_macro_requires_parens) +<< II->getName(); +return true; + } +} + } + // We didn't find anything, so try to correct for a typo. TypoCorrection Corrected; if (S && Out) { @@ -2632,7 +2645,7 @@ bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, << SS.getRange(); return true; } - + // Give up, we can't recover. Diag(R.getNameLoc(), diagnostic) << Name; return true; >From c274178a0ce3a510eaaa9390b277b860bcc5a2a9 Mon Sep 17 00:00:00 2001 From: Prashanth Date: Sun, 19 Jan 2025 08:30:39 +0530 Subject: [PATCH 02/12] [clang][Tests] Modify tests for function-like macros according to the new behavior and Format the changes --- clang/include/clang/Basic/DiagnosticSemaKinds.td| 5 +++-- clang/lib/Sema/SemaExpr.cpp | 7 --- clang/test/Preprocessor/macro_with_initializer_list.cpp | 6 -- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td index d9c8fcc66acf2..697b92d325240 100644 --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -5961,8 +5961,9 @@ def err_fold_expression_limit_exceeded: Error< "instantiating fold expression with %0 arguments exceeded expression nesting " "limit of %1">, DefaultFatal, NoSFINAE; -def note_function_like_macro_requires_parens : Note< - "'%0' exists, but as a function-like macro; perhaps, did you forget the parentheses?">; +def note_function_like_macro_requires_parens +: Note<"'%0' exists, but as a function-like macro; perhaps, did you forget " + "the parentheses?">; def err_unexpected_typedef : Error< "unexpected type name %0: expected expression">; def err_unexpected_namespace : Error< diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index dff03ac31ef2a..da894dd3a6d6a 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -2527,8 +2527,9 @@ bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, if (II->hasMacroDefinition()) { MacroInfo *MI = PP.getMacroInfo(II); if (MI && MI->isFunctionLike()) { -Diag( R.getNameLoc() ,diag::err_undeclared_var_use) << II->getName(); -Diag(MI->getDefinitionLoc(), diag::note_function_like_macro_requires_parens) +Diag(R.getNameLoc(), diag::err_undeclared_var_use) << II->getName(); +Diag(MI->getDefinitionLoc(), + diag::note_function_like_macro_requires_parens) << II->getName(); return true; } @@ -2645,7 +2646,7 @@ bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, << SS.getRange(); return true; } - + // Give up, we can't recover. Diag(R.getNameLoc(), diagnostic) << Name; return true; diff --git a/clang/test/Preprocessor/macro_with_initializer_list.cpp b/clang/test/Preprocessor/macro_with_initi
[clang] [NFC][analyzer] OOB test consolidation II: constraint checking (PR #126748)
https://github.com/NagyDonat updated https://github.com/llvm/llvm-project/pull/126748 From df63943adf054b94249b125078d4dbeafb437641 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Don=C3=A1t=20Nagy?= Date: Tue, 11 Feb 2025 16:22:32 +0100 Subject: [PATCH 1/2] [NFC][analyzer] OOB test consolidation II: constraint checking This commit heavily refactors `out-of-bounds-constraint-check.c`: 1. The complex combinations of several `clang_analyzer_eval` calls were replaced by `clang_analyzer_value`, which can directly query the range of a symbol. 2. Testcases were renamed to a (hopefully) more consistent scheme. 3. The use of `size_t` as an argument type was replaced by `unsigned long long`, which is usually a no-op, but seems to be a better choice if I look for `64u` in the output of `clang_analyzer_value`. 4. The single "dynamic extent" case was generalized into a full set of tests that use `malloc`. 5. Half of the testcases (the ones that don't use `malloc`) were changed to use an `int[5]` array instead of a string literal. After this change the tests in this file cover every functionality that was tested by the testcases `test_assume_after_access{,2}` in the file `out-of-bounds.c` so I was able to delete those two testcases (and therefore consolidate the validation of these constraints within a single test file). This is the second commit in a series that reorganizes the tests of `security.ArrayBound` to system that's easier to understand and maintain. (Note that this file wasn't significantly modified by the recent commit 6e17ed9b04e5523cc910bf171c3122dcc64b86db which renamed `alpha.security.ArrayBoundV2` to `security.ArrayBound`; but I still felt that this cleanup may be useful.) --- .../Analysis/out-of-bounds-constraint-check.c | 259 +++--- clang/test/Analysis/out-of-bounds.c | 16 +- 2 files changed, 156 insertions(+), 119 deletions(-) diff --git a/clang/test/Analysis/out-of-bounds-constraint-check.c b/clang/test/Analysis/out-of-bounds-constraint-check.c index df48c8c170713..b89af08cff222 100644 --- a/clang/test/Analysis/out-of-bounds-constraint-check.c +++ b/clang/test/Analysis/out-of-bounds-constraint-check.c @@ -1,112 +1,163 @@ // RUN: %clang_analyze_cc1 -analyzer-checker=core,unix.Malloc,security.ArrayBound,debug.ExprInspection \ // RUN: -analyzer-config eagerly-assume=false -verify %s -void clang_analyzer_eval(int); -void clang_analyzer_printState(void); - -typedef typeof(sizeof(int)) size_t; -const char a[] = "abcd"; // extent: 5 bytes - -void symbolic_size_t_and_int0(size_t len) { - (void)a[len + 1]; // no-warning - // We infered that the 'len' must be in a specific range to make the previous indexing valid. - // len: [0,3] - clang_analyzer_eval(len <= 3); // expected-warning {{TRUE}} - clang_analyzer_eval(len <= 2); // expected-warning {{UNKNOWN}} -} - -void symbolic_size_t_and_int1(size_t len) { - (void)a[len]; // no-warning - // len: [0,4] - clang_analyzer_eval(len <= 4); // expected-warning {{TRUE}} - clang_analyzer_eval(len <= 3); // expected-warning {{UNKNOWN}} -} - -void symbolic_size_t_and_int2(size_t len) { - (void)a[len - 1]; // no-warning - // len: [1,5] - clang_analyzer_eval(1 <= len && len <= 5); // expected-warning {{TRUE}} - clang_analyzer_eval(2 <= len); // expected-warning {{UNKNOWN}} - clang_analyzer_eval(len <= 4); // expected-warning {{UNKNOWN}} -} - -void symbolic_uint_and_int0(unsigned len) { - (void)a[len + 1]; // no-warning - // len: [0,3] - clang_analyzer_eval(0 <= len && len <= 3); // expected-warning {{TRUE}} - clang_analyzer_eval(1 <= len); // expected-warning {{UNKNOWN}} - clang_analyzer_eval(len <= 2); // expected-warning {{UNKNOWN}} -} - -void symbolic_uint_and_int1(unsigned len) { - (void)a[len]; // no-warning - // len: [0,4] - clang_analyzer_eval(0 <= len && len <= 4); // expected-warning {{TRUE}} - clang_analyzer_eval(1 <= len); // expected-warning {{UNKNOWN}} - clang_analyzer_eval(len <= 3); // expected-warning {{UNKNOWN}} -} -void symbolic_uint_and_int2(unsigned len) { - (void)a[len - 1]; // no-warning - // len: [1,5] - clang_analyzer_eval(1 <= len && len <= 5); // expected-warning {{TRUE}} - clang_analyzer_eval(2 <= len); // expected-warning {{UNKNOWN}} - clang_analyzer_eval(len <= 4); // expected-warning {{UNKNOWN}} -} - -void symbolic_int_and_int0(int len) { - (void)a[len + 1]; // no-warning - // len: [-1,3] - clang_analyzer_eval(-1 <= len && len <= 3); // expected-warning {{TRUE}} - clang_analyzer_eval(0 <= len); // expected-warning {{UNKNOWN}} - clang_analyzer_eval(len <= 2); // expected-warning {{UNKNOWN}} -} -void symbolic_int_and_int1(int len) { - (void)a[len]; // no-warning - // len: [0,4] - clang_analyzer_eval(0 <= len && len <= 4); // expected-warning {{TRUE}} - clang_analyzer_eval(1 <= len); // expected-warning {{UNKN
[clang] [NFC][analyzer] OOB test consolidation II: constraint checking (PR #126748)
https://github.com/NagyDonat edited https://github.com/llvm/llvm-project/pull/126748 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][Sema] Add diagnostic note for reference of function-like macros requiring without parentheses (PR #123495)
https://github.com/StarOne01 updated https://github.com/llvm/llvm-project/pull/123495 >From ea6c9ca9cffbf4327fc7bab85e37e2a3c2c0f0cd Mon Sep 17 00:00:00 2001 From: Prashanth Date: Sun, 19 Jan 2025 07:28:24 +0530 Subject: [PATCH 01/11] [clang][Sema] Add diagnostic note for function-like macros requiring parentheses --- clang/include/clang/Basic/DiagnosticSemaKinds.td | 2 ++ clang/lib/Sema/SemaExpr.cpp | 15 ++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td index bcae9e9f30093..d9c8fcc66acf2 100644 --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -5961,6 +5961,8 @@ def err_fold_expression_limit_exceeded: Error< "instantiating fold expression with %0 arguments exceeded expression nesting " "limit of %1">, DefaultFatal, NoSFINAE; +def note_function_like_macro_requires_parens : Note< + "'%0' exists, but as a function-like macro; perhaps, did you forget the parentheses?">; def err_unexpected_typedef : Error< "unexpected type name %0: expected expression">; def err_unexpected_namespace : Error< diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index 3cd4010740d19..dff03ac31ef2a 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -2522,6 +2522,19 @@ bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, DC = DC->getLookupParent(); } + // Check whether a similar function-like macro exists and suggest it + if (IdentifierInfo *II = Name.getAsIdentifierInfo()) { +if (II->hasMacroDefinition()) { + MacroInfo *MI = PP.getMacroInfo(II); + if (MI && MI->isFunctionLike()) { +Diag( R.getNameLoc() ,diag::err_undeclared_var_use) << II->getName(); +Diag(MI->getDefinitionLoc(), diag::note_function_like_macro_requires_parens) +<< II->getName(); +return true; + } +} + } + // We didn't find anything, so try to correct for a typo. TypoCorrection Corrected; if (S && Out) { @@ -2632,7 +2645,7 @@ bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, << SS.getRange(); return true; } - + // Give up, we can't recover. Diag(R.getNameLoc(), diagnostic) << Name; return true; >From c274178a0ce3a510eaaa9390b277b860bcc5a2a9 Mon Sep 17 00:00:00 2001 From: Prashanth Date: Sun, 19 Jan 2025 08:30:39 +0530 Subject: [PATCH 02/11] [clang][Tests] Modify tests for function-like macros according to the new behavior and Format the changes --- clang/include/clang/Basic/DiagnosticSemaKinds.td| 5 +++-- clang/lib/Sema/SemaExpr.cpp | 7 --- clang/test/Preprocessor/macro_with_initializer_list.cpp | 6 -- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td index d9c8fcc66acf2..697b92d325240 100644 --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -5961,8 +5961,9 @@ def err_fold_expression_limit_exceeded: Error< "instantiating fold expression with %0 arguments exceeded expression nesting " "limit of %1">, DefaultFatal, NoSFINAE; -def note_function_like_macro_requires_parens : Note< - "'%0' exists, but as a function-like macro; perhaps, did you forget the parentheses?">; +def note_function_like_macro_requires_parens +: Note<"'%0' exists, but as a function-like macro; perhaps, did you forget " + "the parentheses?">; def err_unexpected_typedef : Error< "unexpected type name %0: expected expression">; def err_unexpected_namespace : Error< diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index dff03ac31ef2a..da894dd3a6d6a 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -2527,8 +2527,9 @@ bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, if (II->hasMacroDefinition()) { MacroInfo *MI = PP.getMacroInfo(II); if (MI && MI->isFunctionLike()) { -Diag( R.getNameLoc() ,diag::err_undeclared_var_use) << II->getName(); -Diag(MI->getDefinitionLoc(), diag::note_function_like_macro_requires_parens) +Diag(R.getNameLoc(), diag::err_undeclared_var_use) << II->getName(); +Diag(MI->getDefinitionLoc(), + diag::note_function_like_macro_requires_parens) << II->getName(); return true; } @@ -2645,7 +2646,7 @@ bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, << SS.getRange(); return true; } - + // Give up, we can't recover. Diag(R.getNameLoc(), diagnostic) << Name; return true; diff --git a/clang/test/Preprocessor/macro_with_initializer_list.cpp b/clang/test/Preprocessor/macro_with_initi
[clang] [Driver][ROCm][ASan] Skip checking ':xnack+' feature for gfx12. (PR #126885)
@@ -1112,6 +1112,11 @@ bool AMDGPUToolChain::shouldSkipSanitizeOption( assert(OptionalGpuArch && "Invalid Target ID"); (void)OptionalGpuArch; + + // Skip checking 'xnack+' feature availability for gfx12 family. ampandey-1995 wrote: Sorry, but I didn't understand , could you please elaborate? https://github.com/llvm/llvm-project/pull/126885 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][Sema] Add diagnostic note for reference of function-like macros requiring without parentheses (PR #123495)
@@ -2347,6 +2347,27 @@ Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, return E; } +// Check whether a similar function-like macro exists and suggest it +static bool isFunctionLikeMacro(const DeclarationName &Name, Sema &SemaRef, +const SourceLocation &TypoLoc) { + + if (IdentifierInfo *II = Name.getAsIdentifierInfo()) { +if (II->hasMacroDefinition()) { + MacroInfo *MI = SemaRef.PP.getMacroInfo(II); + if (MI && MI->isFunctionLike()) { +SemaRef.Diag(TypoLoc, + diag::err_undeclared_var_use_suggest_func_like_macro) +<< II->getName(); StarOne01 wrote: Tried it, but gives `'FOO1' is defined as an object-like macro; did you mean ''FOO1'(...)'?` so reverted back. https://github.com/llvm/llvm-project/pull/123495 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Driver][ROCm][ASan] Skip checking ':xnack+' feature for gfx12. (PR #126885)
https://github.com/ampandey-1995 updated https://github.com/llvm/llvm-project/pull/126885 >From cfa9342304a03671ed261a4f0b0cbe0297bb050b Mon Sep 17 00:00:00 2001 From: Amit Pandey Date: Wed, 12 Feb 2025 15:47:33 +0530 Subject: [PATCH] [Driver][ROCm][ASan] Skip checking ':xnack+' feature for gfx12. Enable ASan instrumentation for 'gfx12' family targets.The GPU features like ':xnack+ or :sramecc+' are implicitly handled in the hardware for gfx12 family. --- clang/lib/Driver/ToolChains/AMDGPU.cpp | 5 + .../rocm/amdgcn/bitcode/oclc_isa_version_1200.bc | 0 clang/test/Driver/amdgpu-openmp-sanitize-options.c | 12 +++- clang/test/Driver/hip-sanitize-options.hip | 5 + clang/test/Driver/rocm-device-libs.cl| 6 ++ 5 files changed, 23 insertions(+), 5 deletions(-) create mode 100644 clang/test/Driver/Inputs/rocm/amdgcn/bitcode/oclc_isa_version_1200.bc diff --git a/clang/lib/Driver/ToolChains/AMDGPU.cpp b/clang/lib/Driver/ToolChains/AMDGPU.cpp index 8d5cb91ebad9a..3edd9f37897f1 100644 --- a/clang/lib/Driver/ToolChains/AMDGPU.cpp +++ b/clang/lib/Driver/ToolChains/AMDGPU.cpp @@ -1112,6 +1112,11 @@ bool AMDGPUToolChain::shouldSkipSanitizeOption( assert(OptionalGpuArch && "Invalid Target ID"); (void)OptionalGpuArch; + + // Skip checking 'xnack+' feature availability for gfx12 family. + if (llvm::AMDGPU::getIsaVersion(TargetID).Major == 12) +return false; + auto Loc = FeatureMap.find("xnack"); if (Loc == FeatureMap.end() || !Loc->second) { Diags.Report( diff --git a/clang/test/Driver/Inputs/rocm/amdgcn/bitcode/oclc_isa_version_1200.bc b/clang/test/Driver/Inputs/rocm/amdgcn/bitcode/oclc_isa_version_1200.bc new file mode 100644 index 0..e69de29bb2d1d diff --git a/clang/test/Driver/amdgpu-openmp-sanitize-options.c b/clang/test/Driver/amdgpu-openmp-sanitize-options.c index f6a8a7dc57ccc..bd3250a73f5b2 100644 --- a/clang/test/Driver/amdgpu-openmp-sanitize-options.c +++ b/clang/test/Driver/amdgpu-openmp-sanitize-options.c @@ -13,7 +13,6 @@ // RUN: | FileCheck --check-prefix=NOTSUPPORTED %s // GPU ASan Enabled Test Cases - // GPU ASan enabled for amdgpu-arch [gfx908:xnack+] // RUN: %clang -no-canonical-prefixes -### --target=x86_64-unknown-linux-gnu -fopenmp=libomp --offload-arch=gfx908:xnack+ -fsanitize=address -fgpu-sanitize --rocm-path=%S/Inputs/rocm %s 2>&1 \ // RUN: | FileCheck -check-prefixes=HOSTSAN,GPUSAN,SAN %s @@ -22,12 +21,15 @@ // RUN: %clang -no-canonical-prefixes -### --target=x86_64-unknown-linux-gnu -fopenmp=libomp --offload-arch=gfx908:xnack+ -fsanitize=address --rocm-path=%S/Inputs/rocm %s 2>&1 \ // RUN: | FileCheck -check-prefixes=HOSTSAN,GPUSAN,SAN %s -// ASan enabled for multiple amdgpu-arch [gfx908:xnack+,gfx900:xnack+] +// GPU ASan enabled for multiple amdgpu-arch [gfx908:xnack+,gfx900:xnack+] // RUN: %clang -no-canonical-prefixes -### --target=x86_64-unknown-linux-gnu -fopenmp=libomp --offload-arch=gfx908:xnack+ --offload-arch=gfx900:xnack+ -fsanitize=address -fgpu-sanitize --rocm-path=%S/Inputs/rocm %s 2>&1 \ // RUN: | FileCheck -check-prefixes=HOSTSAN,GPUSAN,SAN %s -// GPU ASan Disabled Test Cases +// GPU ASan enabled for amdgpu-arch [gfx1200] +// RUN: %clang -no-canonical-prefixes -### --target=x86_64-unknown-linux-gnu -fopenmp=libomp --offload-arch=gfx1200 -fsanitize=address -fgpu-sanitize --rocm-path=%S/Inputs/rocm %s 2>&1 \ +// RUN: | FileCheck -check-prefixes=HOSTSAN,GPUSAN,SAN %s +// GPU ASan Disabled Test Cases // GPU ASan disabled through '-fsanitize=address' without '-fgpu-sanitize' flag for amdgpu-arch [gfx908] // RUN: %clang -no-canonical-prefixes -### --target=x86_64-unknown-linux-gnu -fopenmp=libomp --offload-arch=gfx908 -fsanitize=address --rocm-path=%S/Inputs/rocm %s 2>&1 \ // RUN: | FileCheck -check-prefixes=NOXNACK,HOSTSAN,NOGPUSAN,SAN %s @@ -56,9 +58,9 @@ // HOSTSAN: {{"[^"]*clang[^"]*" "-cc1" "-triple" "x86_64-unknown-linux-gnu".* "-fopenmp".* "-fsanitize=address".* "-fopenmp-targets=amdgcn-amd-amdhsa".* "-x" "c".*}} -// GPUSAN: {{"[^"]*clang[^"]*" "-cc1" "-triple" "amdgcn-amd-amdhsa" "-aux-triple" "x86_64-unknown-linux-gnu".* "-emit-llvm-bc".* "-mlink-bitcode-file" "[^"]*asanrtl.bc".* "-mlink-bitcode-file" "[^"]*ockl.bc".* "-target-cpu" "(gfx908|gfx900)".* "-fopenmp".* "-fsanitize=address".* "-x" "c".*}} +// GPUSAN: {{"[^"]*clang[^"]*" "-cc1" "-triple" "amdgcn-amd-amdhsa" "-aux-triple" "x86_64-unknown-linux-gnu".* "-emit-llvm-bc".* "-mlink-bitcode-file" "[^"]*asanrtl.bc".* "-mlink-bitcode-file" "[^"]*ockl.bc".* "-target-cpu" "(gfx1200|gfx908|gfx900)".* "-fopenmp".* "-fsanitize=address".* "-x" "c".*}} // NOGPUSAN: {{"[^"]*clang[^"]*" "-cc1" "-triple" "amdgcn-amd-amdhsa" "-aux-triple" "x86_64-unknown-linux-gnu".* "-emit-llvm-bc".* "-target-cpu" "(gfx908|gfx900)".* "-fopenmp".* "-x" "c".*}} -// SAN: {{"[^"]*clang-offload-packager[^"]*" "-o".* "--image=file=.*.bc,triple=amdgcn-amd-amdhsa,arch=g
[clang] [Driver][ROCm][ASan] Skip checking ':xnack+' feature for gfx12. (PR #126885)
https://github.com/ampandey-1995 edited https://github.com/llvm/llvm-project/pull/126885 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [NFC][analyzer] OOB test consolidation II: constraint checking (PR #126748)
=?utf-8?q?Donát?= Nagy Message-ID: In-Reply-To: @@ -1,6 +1,4 @@ -// RUN: %clang_analyze_cc1 -Wno-array-bounds -analyzer-checker=core,security.ArrayBound,debug.ExprInspection -verify %s - -void clang_analyzer_eval(int); +// RUN: %clang_analyze_cc1 -Wno-array-bounds -analyzer-checker=core,security.ArrayBound -verify %s steakhal wrote: Makes sense. I just wanted to reevaluate this suppression. https://github.com/llvm/llvm-project/pull/126748 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [NFC][analyzer] OOB test consolidation II: constraint checking (PR #126748)
=?utf-8?q?Donát?= Nagy Message-ID: In-Reply-To: @@ -1,112 +1,163 @@ // RUN: %clang_analyze_cc1 -analyzer-checker=core,unix.Malloc,security.ArrayBound,debug.ExprInspection \ // RUN: -analyzer-config eagerly-assume=false -verify %s -void clang_analyzer_eval(int); -void clang_analyzer_printState(void); - -typedef typeof(sizeof(int)) size_t; -const char a[] = "abcd"; // extent: 5 bytes - -void symbolic_size_t_and_int0(size_t len) { - (void)a[len + 1]; // no-warning - // We infered that the 'len' must be in a specific range to make the previous indexing valid. - // len: [0,3] - clang_analyzer_eval(len <= 3); // expected-warning {{TRUE}} - clang_analyzer_eval(len <= 2); // expected-warning {{UNKNOWN}} -} - -void symbolic_size_t_and_int1(size_t len) { - (void)a[len]; // no-warning - // len: [0,4] - clang_analyzer_eval(len <= 4); // expected-warning {{TRUE}} - clang_analyzer_eval(len <= 3); // expected-warning {{UNKNOWN}} -} - -void symbolic_size_t_and_int2(size_t len) { - (void)a[len - 1]; // no-warning - // len: [1,5] - clang_analyzer_eval(1 <= len && len <= 5); // expected-warning {{TRUE}} - clang_analyzer_eval(2 <= len); // expected-warning {{UNKNOWN}} - clang_analyzer_eval(len <= 4); // expected-warning {{UNKNOWN}} -} - -void symbolic_uint_and_int0(unsigned len) { - (void)a[len + 1]; // no-warning - // len: [0,3] - clang_analyzer_eval(0 <= len && len <= 3); // expected-warning {{TRUE}} - clang_analyzer_eval(1 <= len); // expected-warning {{UNKNOWN}} - clang_analyzer_eval(len <= 2); // expected-warning {{UNKNOWN}} -} - -void symbolic_uint_and_int1(unsigned len) { - (void)a[len]; // no-warning - // len: [0,4] - clang_analyzer_eval(0 <= len && len <= 4); // expected-warning {{TRUE}} - clang_analyzer_eval(1 <= len); // expected-warning {{UNKNOWN}} - clang_analyzer_eval(len <= 3); // expected-warning {{UNKNOWN}} -} -void symbolic_uint_and_int2(unsigned len) { - (void)a[len - 1]; // no-warning - // len: [1,5] - clang_analyzer_eval(1 <= len && len <= 5); // expected-warning {{TRUE}} - clang_analyzer_eval(2 <= len); // expected-warning {{UNKNOWN}} - clang_analyzer_eval(len <= 4); // expected-warning {{UNKNOWN}} -} - -void symbolic_int_and_int0(int len) { - (void)a[len + 1]; // no-warning - // len: [-1,3] - clang_analyzer_eval(-1 <= len && len <= 3); // expected-warning {{TRUE}} - clang_analyzer_eval(0 <= len); // expected-warning {{UNKNOWN}} - clang_analyzer_eval(len <= 2); // expected-warning {{UNKNOWN}} -} -void symbolic_int_and_int1(int len) { - (void)a[len]; // no-warning - // len: [0,4] - clang_analyzer_eval(0 <= len && len <= 4); // expected-warning {{TRUE}} - clang_analyzer_eval(1 <= len); // expected-warning {{UNKNOWN}} - clang_analyzer_eval(len <= 3); // expected-warning {{UNKNOWN}} -} -void symbolic_int_and_int2(int len) { - (void)a[len - 1]; // no-warning - // len: [1,5] - clang_analyzer_eval(1 <= len && len <= 5); // expected-warning {{TRUE}} - clang_analyzer_eval(2 <= len); // expected-warning {{UNKNOWN}} - clang_analyzer_eval(len <= 4); // expected-warning {{UNKNOWN}} -} - -void symbolic_longlong_and_int0(long long len) { - (void)a[len + 1]; // no-warning - // len: [-1,3] - clang_analyzer_eval(-1 <= len && len <= 3); // expected-warning {{TRUE}} - clang_analyzer_eval(0 <= len); // expected-warning {{UNKNOWN}} - clang_analyzer_eval(len <= 2); // expected-warning {{UNKNOWN}} +// When the checker security.ArrayBound encounters an array subscript operation +// that _may be_ in bounds, it assumes that indexing _is_ in bound. This test +// file validates these assumptions. + +void clang_analyzer_value(int); + +// Simple case: memory area with a static extent. + +int FiveInts[5] = {1, 2, 3, 4, 5}; + +void int_plus_one(int len) { + (void)FiveInts[len + 1]; // no-warning + clang_analyzer_value(len); // expected-warning {{32s:{ [-1, 3] }}} steakhal wrote: Yes, checking only the ranges should suffice in this case. https://github.com/llvm/llvm-project/pull/126748 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] handle fp options in __builtin_convertvector (PR #125522)
https://github.com/ficol updated https://github.com/llvm/llvm-project/pull/125522 >From cb26d6a13e196bfc08221b7f6cd43ab45019e7d6 Mon Sep 17 00:00:00 2001 From: "Ficek, Jakub" Date: Mon, 3 Feb 2025 16:45:17 +0100 Subject: [PATCH 1/3] [clang] Handle fp options in __builtin_convertvector This patch allows using fpfeatures pragmas with __builtin_convertvector: - added TrailingObjects with FPOptionsOverride and methods for handling it to ConvertVectorExpr - added support for codegen, node dumping, and serialization of fpfeatures contained in ConvertVectorExpr --- clang/include/clang/AST/Expr.h| 80 +-- clang/include/clang/AST/Stmt.h| 15 + clang/include/clang/AST/TextNodeDumper.h | 1 + clang/lib/AST/ASTImporter.cpp | 7 +- clang/lib/AST/Expr.cpp| 20 ++ clang/lib/AST/TextNodeDumper.cpp | 6 ++ clang/lib/CodeGen/CGExprScalar.cpp| 2 + clang/lib/Sema/SemaChecking.cpp | 4 +- clang/lib/Serialization/ASTReaderStmt.cpp | 13 +++- clang/lib/Serialization/ASTWriterStmt.cpp | 4 ++ clang/test/AST/ast-dump-fpfeatures.cpp| 14 +++- clang/test/CodeGen/pragma-fenv_access.c | 9 +++ 12 files changed, 163 insertions(+), 12 deletions(-) diff --git a/clang/include/clang/AST/Expr.h b/clang/include/clang/AST/Expr.h index 7be4022649329..1e94427748354 100644 --- a/clang/include/clang/AST/Expr.h +++ b/clang/include/clang/AST/Expr.h @@ -4579,25 +4579,97 @@ class ShuffleVectorExpr : public Expr { /// ConvertVectorExpr - Clang builtin function __builtin_convertvector /// This AST node provides support for converting a vector type to another /// vector type of the same arity. -class ConvertVectorExpr : public Expr { +class ConvertVectorExpr final +: public Expr, + private llvm::TrailingObjects { private: Stmt *SrcExpr; TypeSourceInfo *TInfo; SourceLocation BuiltinLoc, RParenLoc; + friend TrailingObjects; friend class ASTReader; friend class ASTStmtReader; - explicit ConvertVectorExpr(EmptyShell Empty) : Expr(ConvertVectorExprClass, Empty) {} + explicit ConvertVectorExpr(bool HasFPFeatures, EmptyShell Empty) + : Expr(ConvertVectorExprClass, Empty) { +ConvertVectorExprBits.HasFPFeatures = HasFPFeatures; + } -public: ConvertVectorExpr(Expr *SrcExpr, TypeSourceInfo *TI, QualType DstType, ExprValueKind VK, ExprObjectKind OK, -SourceLocation BuiltinLoc, SourceLocation RParenLoc) +SourceLocation BuiltinLoc, SourceLocation RParenLoc, +FPOptionsOverride FPFeatures) : Expr(ConvertVectorExprClass, DstType, VK, OK), SrcExpr(SrcExpr), TInfo(TI), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) { +ConvertVectorExprBits.HasFPFeatures = FPFeatures.requiresTrailingStorage(); +if (hasStoredFPFeatures()) + setStoredFPFeatures(FPFeatures); setDependence(computeDependence(this)); } + size_t numTrailingObjects(OverloadToken) const { +return ConvertVectorExprBits.HasFPFeatures ? 1 : 0; + } + + FPOptionsOverride &getTrailingFPFeatures() { +assert(ConvertVectorExprBits.HasFPFeatures); +return *getTrailingObjects(); + } + + const FPOptionsOverride &getTrailingFPFeatures() const { +assert(ConvertVectorExprBits.HasFPFeatures); +return *getTrailingObjects(); + } + +public: + static ConvertVectorExpr *CreateEmpty(const ASTContext &C, +bool hasFPFeatures); + + static ConvertVectorExpr *Create(const ASTContext &C, Expr *SrcExpr, + TypeSourceInfo *TI, QualType DstType, + ExprValueKind VK, ExprObjectKind OK, + SourceLocation BuiltinLoc, + SourceLocation RParenLoc, + FPOptionsOverride FPFeatures); + + /// Get the FP contractibility status of this operator. Only meaningful for + /// operations on floating point types. + bool isFPContractableWithinStatement(const LangOptions &LO) const { +return getFPFeaturesInEffect(LO).allowFPContractWithinStatement(); + } + + /// Is FPFeatures in Trailing Storage? + bool hasStoredFPFeatures() const { +return ConvertVectorExprBits.HasFPFeatures; + } + + /// Get FPFeatures from trailing storage. + FPOptionsOverride getStoredFPFeatures() const { +return getTrailingFPFeatures(); + } + + /// Get the store FPOptionsOverride or default if not stored. + FPOptionsOverride getStoredFPFeaturesOrDefault() const { +return hasStoredFPFeatures() ? getStoredFPFeatures() : FPOptionsOverride(); + } + + /// Set FPFeatures in trailing storage, used by Serialization & ASTImporter. + void setStoredFPFeatures(FPOptionsOverride F) { getTrailingFPFeatures() = F; } + + /// Get the FP features status of this operator. Only meaningful for + /// operations on floating point types. + FPOptions getFPFe
[clang] [clang][Sema] Add diagnostic note for reference of function-like macros requiring without parentheses (PR #123495)
https://github.com/StarOne01 updated https://github.com/llvm/llvm-project/pull/123495 >From ea6c9ca9cffbf4327fc7bab85e37e2a3c2c0f0cd Mon Sep 17 00:00:00 2001 From: Prashanth Date: Sun, 19 Jan 2025 07:28:24 +0530 Subject: [PATCH 01/11] [clang][Sema] Add diagnostic note for function-like macros requiring parentheses --- clang/include/clang/Basic/DiagnosticSemaKinds.td | 2 ++ clang/lib/Sema/SemaExpr.cpp | 15 ++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td index bcae9e9f30093..d9c8fcc66acf2 100644 --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -5961,6 +5961,8 @@ def err_fold_expression_limit_exceeded: Error< "instantiating fold expression with %0 arguments exceeded expression nesting " "limit of %1">, DefaultFatal, NoSFINAE; +def note_function_like_macro_requires_parens : Note< + "'%0' exists, but as a function-like macro; perhaps, did you forget the parentheses?">; def err_unexpected_typedef : Error< "unexpected type name %0: expected expression">; def err_unexpected_namespace : Error< diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index 3cd4010740d19..dff03ac31ef2a 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -2522,6 +2522,19 @@ bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, DC = DC->getLookupParent(); } + // Check whether a similar function-like macro exists and suggest it + if (IdentifierInfo *II = Name.getAsIdentifierInfo()) { +if (II->hasMacroDefinition()) { + MacroInfo *MI = PP.getMacroInfo(II); + if (MI && MI->isFunctionLike()) { +Diag( R.getNameLoc() ,diag::err_undeclared_var_use) << II->getName(); +Diag(MI->getDefinitionLoc(), diag::note_function_like_macro_requires_parens) +<< II->getName(); +return true; + } +} + } + // We didn't find anything, so try to correct for a typo. TypoCorrection Corrected; if (S && Out) { @@ -2632,7 +2645,7 @@ bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, << SS.getRange(); return true; } - + // Give up, we can't recover. Diag(R.getNameLoc(), diagnostic) << Name; return true; >From c274178a0ce3a510eaaa9390b277b860bcc5a2a9 Mon Sep 17 00:00:00 2001 From: Prashanth Date: Sun, 19 Jan 2025 08:30:39 +0530 Subject: [PATCH 02/11] [clang][Tests] Modify tests for function-like macros according to the new behavior and Format the changes --- clang/include/clang/Basic/DiagnosticSemaKinds.td| 5 +++-- clang/lib/Sema/SemaExpr.cpp | 7 --- clang/test/Preprocessor/macro_with_initializer_list.cpp | 6 -- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td index d9c8fcc66acf2..697b92d325240 100644 --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -5961,8 +5961,9 @@ def err_fold_expression_limit_exceeded: Error< "instantiating fold expression with %0 arguments exceeded expression nesting " "limit of %1">, DefaultFatal, NoSFINAE; -def note_function_like_macro_requires_parens : Note< - "'%0' exists, but as a function-like macro; perhaps, did you forget the parentheses?">; +def note_function_like_macro_requires_parens +: Note<"'%0' exists, but as a function-like macro; perhaps, did you forget " + "the parentheses?">; def err_unexpected_typedef : Error< "unexpected type name %0: expected expression">; def err_unexpected_namespace : Error< diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index dff03ac31ef2a..da894dd3a6d6a 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -2527,8 +2527,9 @@ bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, if (II->hasMacroDefinition()) { MacroInfo *MI = PP.getMacroInfo(II); if (MI && MI->isFunctionLike()) { -Diag( R.getNameLoc() ,diag::err_undeclared_var_use) << II->getName(); -Diag(MI->getDefinitionLoc(), diag::note_function_like_macro_requires_parens) +Diag(R.getNameLoc(), diag::err_undeclared_var_use) << II->getName(); +Diag(MI->getDefinitionLoc(), + diag::note_function_like_macro_requires_parens) << II->getName(); return true; } @@ -2645,7 +2646,7 @@ bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, << SS.getRange(); return true; } - + // Give up, we can't recover. Diag(R.getNameLoc(), diagnostic) << Name; return true; diff --git a/clang/test/Preprocessor/macro_with_initializer_list.cpp b/clang/test/Preprocessor/macro_with_initi
[clang] [lldb] [llvm] [mlir] [clang][Sema] Fix initialization of `NonTypeTemplateParmDecl`... (PR #121768)
Alejandro =?utf-8?q?Álvarez_Ayllón?=, Alejandro =?utf-8?q?Álvarez_Ayllón?=, Alejandro =?utf-8?q?Álvarez_Ayllón?=, Alejandro =?utf-8?q?Álvarez_Ayllón?=, Alejandro =?utf-8?q?Álvarez_Ayllón?=, Alejandro =?utf-8?q?Álvarez_Ayllón?=,Yutong Zhu <115899167+yutongz...@users.noreply.github.com>, Juan Manuel Martinez =?utf-8?q?Caamaño?=, =?utf-8?q?Michał_Górny?= ,LLVM GN Syncbot ,Rahul Joshi ,David Sherwood ,Nick Sarnie ,Joseph Huber ,Vigneshwar Jayakumar ,Timm Baeder ,Hsiangkai Wang ,Keith Smiley ,Ivan Kosarev , =?utf-8?q?Michał_Górny?= ,Stanislav Mekhanoshin ,sitrin ,Florian Mayer ,Kazu Hirata ,Kazu Hirata ,Kazu Hirata ,Kazu Hirata =?utf-8?q?,?=Kazu Hirata ,Kazu Hirata ,Andreas Jonson ,Sharjeel Khan ,Razvan Lupusoru ,Ilia Kuklin ,Aaron Siddhartha Mondal ,"S. Bharadwaj Yadavalli" ,Nick Desaulniers ,Wael Yehia ,Balazs Benics ,Aaron Siddhartha Mondal ,Jonas Devlieghere ,Ryosuke Niwa ,Vigneshwar Jayakumar ,Vigneshwar Jayakumar ,Elvin Wang ,Renaud Kauffmann ,Zahira Ammarguellat ,Tai Ly ,Ryosuke Niwa ,Mark de Wever ,quic-areg ,Valentin Clement =?utf-8?b?KOODkOODrOODsw=?=,Nick Sarnie ,Kevin Gleason ,Kazu Hirata ,Philip Reames ,Joseph Huber ,David Green ,Florian Mayer ,Alireza Torabian ,Philip Reames ,Florian Mayer , Andrzej =?utf-8?q?Warzyński?= ,Alexey Bataev ,Florian Mayer ,vporpo ,Shoaib Meenai ,Nick Desaulniers ,Nathan Ridge ,lntue ,Brox Chen ,Michael Jones ,Philip Reames ,Lang Hames ,Shoaib Meenai ,Daniel Hoekwater ,lntue ,Florian Mayer ,Philip Reames ,Justin Fargnoli ,Philip Reames ,Arda Unal <3157490+ardau...@users.noreply.github.com>,Kazu Hirata ,Kazu Hirata ,Michael Jones ,Krzysztof Drewniak ,Christopher Ferris ,donald chen ,lonely eagle <2020382...@qq.com>,c8ef ,Thurston Dang ,Jie Fu ,"Miguel A. Arroyo" ,Luke Lau ,Hongtao Yu ,LLVM GN Syncbot ,Jim Lin ,Abhishek Kaushik ,Kazu Hirata ,Ethan Luis McDonough ,Vikram Hegde <115221833+vikra...@users.noreply.github.com>,Sam Elliott ,Haohai Wen ,Ethan Luis McDonough ,Matt Arsenault ,Vitaly Buka ,Owen Pan ,Craig Topper ,Amit Kumar Pandey <137622562+ampandey-1...@users.noreply.github.com>,Adam Siemieniuk ,Alex MacLean ,Nikita Popov ,Louis Dionne ,jeanPerier ,Fraser Cormack ,Timm Baeder ,Simon Pilgrim ,Nikita Popov ,Yeaseen ,Nikita Popov ,Pavel Labath , Alejandro =?utf-8?q?Álvarez_Ayllón?Message-ID: In-Reply-To: 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 82bd148a3f25439d7f52a32422dc1bcd2da03803 4892b2598adf37b848e321c6ed808e68b7c8fd97 --extensions cpp,h,c -- clang/test/CXX/stmt.stmt/stmt.select/stmt.switch/p4.cpp clang/test/Modules/malformed-constraint-template-non-type-parm-decl.cpp libc/src/math/generic/atan2f_float.h libclc/clc/include/clc/clc_convert.h libclc/clc/include/clc/float/definitions.h llvm/lib/Target/AMDGPU/GCNRewritePartialRegUses.h llvm/lib/Target/RISCV/RISCVVMV0Elimination.cpp bolt/tools/driver/llvm-bolt.cpp clang/include/clang/AST/ASTContext.h clang/include/clang/Basic/LangOptions.h clang/lib/AST/ASTContext.cpp clang/lib/AST/ByteCode/Interp.cpp clang/lib/AST/ByteCode/InterpBuiltin.cpp clang/lib/AST/DeclTemplate.cpp clang/lib/AST/ExprConstant.cpp clang/lib/CodeGen/CGHLSLRuntime.cpp clang/lib/CodeGen/CGOpenMPRuntime.cpp clang/lib/Driver/ToolChains/AMDGPU.cpp clang/lib/Driver/ToolChains/AMDGPUOpenMP.cpp clang/lib/Driver/ToolChains/Clang.cpp clang/lib/Driver/ToolChains/ROCm.h clang/lib/Sema/HeuristicResolver.cpp clang/lib/Sema/JumpDiagnostics.cpp clang/lib/Sema/SemaDecl.cpp clang/lib/Sema/SemaOpenMP.cpp clang/lib/Serialization/ASTWriterDecl.cpp clang/lib/StaticAnalyzer/Checkers/WebKit/ASTUtils.cpp clang/test/AST/ByteCode/cxx26.cpp clang/test/AST/ByteCode/new-delete.cpp clang/test/Analysis/Checkers/WebKit/call-args-counted-const-member.cpp clang/test/Analysis/Checkers/WebKit/mock-types.h clang/test/Driver/amdgpu-openmp-sanitize-options.c clang/test/Driver/linker-wrapper.c clang/test/Driver/sycl-offload-jit.cpp clang/test/Tooling/clang-linker-wrapper-spirv-elf.cpp clang/tools/clang-installapi/Options.cpp clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp clang/unittests/Format/TokenAnnotatorTest.cpp clang/unittests/Sema/HeuristicResolverTest.cpp compiler-rt/lib/profile/InstrProfiling.h compiler-rt/lib/profile/InstrProfilingFile.c compiler-rt/lib/scudo/standalone/chunk.h compiler-rt/lib/scudo/standalone/report.cpp compiler-rt/lib/scudo/standalone/report.h compiler-rt/lib/scudo/standalone/tests/report_test.cpp flang/lib/Lower/OpenACC.cpp flang/lib/Optimizer/Analysis/AliasAnalysis.cpp flang/lib/Optimizer/CodeGen/CodeGen.cpp flang/lib/Optimizer/Dialect/FIROps.cpp libc/include/llvm-libc-macros/endian-macros.h libc/include/llvm-libc-types/struct_tm.h libc/src/__support/FPUtil/double_double.h libc/src/__support/macros/optimization.h libc/src/math/generic/atan2f.cpp libc/src/math/generic/pow.cp
[clang] [clang][Sema] Fix initialization of `NonTypeTemplateParmDecl`... (PR #121768)
https://github.com/alejandro-alvarez-sonarsource updated https://github.com/llvm/llvm-project/pull/121768 From da2bbf99b8430d8b6aa6bf7969c9825b4d94219b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20=C3=81lvarez=20Ayll=C3=B3n?= Date: Mon, 18 Nov 2024 11:36:03 +0100 Subject: [PATCH 1/8] [clang][Sema] Fix initialization of `NonTypeTemplateParmDecl`... ...when there are invalid constraints. When attaching a `TypeConstraint`, in case of error, the trailing pointer that is supposed to point to the constraint is left uninitialized. Sometimes the uninitialized value will be a `nullptr`, but at other times it will not. If we traverse the AST (for instance, dumping it, or when writing the BMI), we may get a crash depending on the value that was left. The serialization may also contain a bogus value. With this commit, we always initialize this trailing pointer, using a `RecoveryExpr` in case of failure to parse. --- clang/lib/Sema/SemaTemplate.cpp | 18 ++- ...constraint-template-non-type-parm-decl.cpp | 54 +++ 2 files changed, 70 insertions(+), 2 deletions(-) create mode 100644 clang/test/Modules/malformed-constraint-template-non-type-parm-decl.cpp diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp index 20ec2fbeaa6a8..9b51f973fb2bb 100644 --- a/clang/lib/Sema/SemaTemplate.cpp +++ b/clang/lib/Sema/SemaTemplate.cpp @@ -1235,6 +1235,10 @@ bool Sema::AttachTypeConstraint(AutoTypeLoc TL, << NewConstrainedParm->getTypeSourceInfo() ->getTypeLoc() .getSourceRange(); +NewConstrainedParm->setPlaceholderTypeConstraint( +RecoveryExpr::Create(Context, OrigConstrainedParm->getType(), + OrigConstrainedParm->getBeginLoc(), + OrigConstrainedParm->getEndLoc(), {})); return true; } // FIXME: Concepts: This should be the type of the placeholder, but this is @@ -1242,8 +1246,13 @@ bool Sema::AttachTypeConstraint(AutoTypeLoc TL, DeclRefExpr *Ref = BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(), VK_PRValue, OrigConstrainedParm->getLocation()); - if (!Ref) + if (!Ref) { +NewConstrainedParm->setPlaceholderTypeConstraint( +RecoveryExpr::Create(Context, OrigConstrainedParm->getType(), + OrigConstrainedParm->getBeginLoc(), + OrigConstrainedParm->getEndLoc(), {})); return true; + } ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint( *this, TL.getNestedNameSpecifierLoc(), TL.getConceptNameInfo(), TL.getNamedConcept(), /*FoundDecl=*/TL.getFoundDecl(), TL.getLAngleLoc(), @@ -1255,8 +1264,13 @@ bool Sema::AttachTypeConstraint(AutoTypeLoc TL, }, EllipsisLoc); if (ImmediatelyDeclaredConstraint.isInvalid() || - !ImmediatelyDeclaredConstraint.isUsable()) + !ImmediatelyDeclaredConstraint.isUsable()) { +NewConstrainedParm->setPlaceholderTypeConstraint( +RecoveryExpr::Create(Context, OrigConstrainedParm->getType(), + OrigConstrainedParm->getBeginLoc(), + OrigConstrainedParm->getEndLoc(), {})); return true; + } NewConstrainedParm->setPlaceholderTypeConstraint( ImmediatelyDeclaredConstraint.get()); diff --git a/clang/test/Modules/malformed-constraint-template-non-type-parm-decl.cpp b/clang/test/Modules/malformed-constraint-template-non-type-parm-decl.cpp new file mode 100644 index 0..cea6404bbebd2 --- /dev/null +++ b/clang/test/Modules/malformed-constraint-template-non-type-parm-decl.cpp @@ -0,0 +1,54 @@ +// RUN: rm -rf %t +// RUN: split-file %s %t +// RUN: cd %t + +// RUN: %clang_cc1 -std=c++20 mod.cppm -emit-module-interface -o mod.pcm -fallow-pcm-with-compiler-errors -verify +// RUN: %clang_cc1 -std=c++20 main.cpp -fmodule-file=mod=mod.pcm -verify -fallow-pcm-with-compiler-errors -fsyntax-only -ast-dump-all | FileCheck %s + +//--- mod.cppm +export module mod; + +template +concept ReferenceOf = Q; + +// expected-error@+2 {{unknown type name 'AngleIsInvalidNow'}} +// expected-error@+1 {{constexpr variable 'angle' must be initialized by a constant expression}} +constexpr struct angle {AngleIsInvalidNow e;} angle; + +// expected-error@+1 {{non-type template argument is not a constant expression}} +template auto R, typename Rep> requires requires(Rep v) {cos(v);} +auto cos(const Rep& q); + +// expected-error@+1 {{non-type template argument is not a constant expression}} +template auto R, typename Rep> requires requires(Rep v) {tan(v);} +auto tan(const Rep& q); + +//--- main.cpp +// expected-no-diagnostics +import mod; + +// CHECK: |-FunctionTemplateDecl {{.*}} col:6 imported in mod hidden invalid cos +// CHECK-NEXT: | |-NonTypeTemplateParmDecl {{.*}} col:34 imported in mod hidden referenced invalid 'ReferenceOf auto' depth 0 index 0 R +// CHECK-
[clang-tools-extra] Add AllowFalseEvaluated flag to clang-tidy noexcept-move-constructor check (PR #126897)
Nechda wrote: Ask for review @PiotrZSL https://github.com/llvm/llvm-project/pull/126897 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [NFC][analyzer] OOB test consolidation II: constraint checking (PR #126748)
=?utf-8?q?Donát?= Nagy Message-ID: In-Reply-To: https://github.com/steakhal requested changes to this pull request. Please avoid matching the types of the `clang_analyzer_value` dumps, but be sure to match the whole range sets there, including their curlies. It's still important to know that it would have a single range associated. https://github.com/llvm/llvm-project/pull/126748 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][analyzer] fix false positive of BlockInCriticalSectionChecker (PR #126752)
https://github.com/flovent edited https://github.com/llvm/llvm-project/pull/126752 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][analyzer] fix false positive of BlockInCriticalSectionChecker (PR #126752)
https://github.com/flovent edited https://github.com/llvm/llvm-project/pull/126752 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][analyzer] fix false positive of BlockInCriticalSectionChecker (PR #126752)
https://github.com/flovent edited https://github.com/llvm/llvm-project/pull/126752 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][analyzer] fix false positive of BlockInCriticalSectionChecker (PR #126752)
@@ -339,6 +425,36 @@ void BlockInCriticalSectionChecker::reportBlockInCritSection( os.str(), ErrNode); R->addRange(Call.getSourceRange()); R->markInteresting(Call.getReturnValue()); + // for 'read' call, check whether it's file descriptor(first argument) is + // created by 'open' API with O_NONBLOCK flag and don't report for this + // situation. + if (Call.getCalleeIdentifier()->getName() == "read") { +do { + const auto *arg = Call.getArgExpr(0); + if (!arg) +break; + + const auto *DRE = dyn_cast(arg->IgnoreImpCasts()); flovent wrote: i am hoping to get the MemRegion of file descriptor here and compare its corresponding SVal between pred node and current node in `VisitNode`, i can't use `getArgSVal` to get SVal as region because `open` call is evaluated to a symbol or int(-1). is there a way to check binding from SVal to Expr? https://github.com/llvm/llvm-project/pull/126752 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][analyzer] fix false positive of BlockInCriticalSectionChecker (PR #126752)
https://github.com/flovent edited https://github.com/llvm/llvm-project/pull/126752 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][Sema] Fix type of an statement expression ending with an atomic type (PR #119711)
https://github.com/alejandro-alvarez-sonarsource updated https://github.com/llvm/llvm-project/pull/119711 From d398fa13c2fa141954c79ca68a59c6ac506b393f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20=C3=81lvarez=20Ayll=C3=B3n?= Date: Wed, 11 Dec 2024 15:43:58 +0100 Subject: [PATCH 1/5] Add regression test --- clang/test/Sema/gh106576.c | 16 1 file changed, 16 insertions(+) create mode 100644 clang/test/Sema/gh106576.c diff --git a/clang/test/Sema/gh106576.c b/clang/test/Sema/gh106576.c new file mode 100644 index 0..792977dea1413 --- /dev/null +++ b/clang/test/Sema/gh106576.c @@ -0,0 +1,16 @@ +// RUN: %clang_cc1 -fsyntax-only -verify %s + +typedef _Atomic char atomic_char; + +typedef _Atomic char atomic_char; + +atomic_char counter; + +char load_plus_one(void) { + return ({counter;}) + 1; // no crash +} + +char type_of_stmt_expr(void) { + typeof(({counter;})) y = ""; // expected-error-re {{incompatible pointer to integer conversion initializing 'typeof (({{{.*}}}))' (aka 'char') with an expression of type 'char[1]'}} + return y; +} From 296aa35fe32449067c69d2b40031af0dd6822a07 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20=C3=81lvarez=20Ayll=C3=B3n?= Date: Thu, 12 Dec 2024 15:08:56 +0100 Subject: [PATCH 2/5] Tentative fix --- clang/lib/Sema/SemaExpr.cpp | 13 +++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index 20bf6f7f6f28f..165447efb345c 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -15861,10 +15861,19 @@ ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) return Cast->getSubExpr(); + auto Ty = E->getType().getUnqualifiedType(); + + // If the type is an atomic, the statement type is the underlying type. + if (const AtomicType *AT = Ty->getAs()) { +Ty = AT->getValueType().getUnqualifiedType(); +return ImplicitCastExpr::Create(Context, Ty, CK_AtomicToNonAtomic, E, +/*base path*/ nullptr, VK_PRValue, +FPOptionsOverride()); + } + // FIXME: Provide a better location for the initialization. return PerformCopyInitialization( - InitializedEntity::InitializeStmtExprResult( - E->getBeginLoc(), E->getType().getUnqualifiedType()), + InitializedEntity::InitializeStmtExprResult(E->getBeginLoc(), Ty), SourceLocation(), E); } From d13e1090c641314aae8eef50f1b0fb5c0ec67e39 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20=C3=81lvarez=20Ayll=C3=B3n?= Date: Thu, 12 Dec 2024 15:30:07 +0100 Subject: [PATCH 3/5] Use PerformImplicitConversion --- clang/lib/Sema/SemaExpr.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index 165447efb345c..45ae97807c203 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -15866,9 +15866,7 @@ ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { // If the type is an atomic, the statement type is the underlying type. if (const AtomicType *AT = Ty->getAs()) { Ty = AT->getValueType().getUnqualifiedType(); -return ImplicitCastExpr::Create(Context, Ty, CK_AtomicToNonAtomic, E, -/*base path*/ nullptr, VK_PRValue, -FPOptionsOverride()); +return PerformImplicitConversion(E, Ty, AssignmentAction::Casting); } // FIXME: Provide a better location for the initialization. From 02d8385cc0f824ff0436a7b0a42d16555e5ee0c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20=C3=81lvarez=20Ayll=C3=B3n?= Date: Wed, 18 Dec 2024 09:19:51 +0100 Subject: [PATCH 4/5] Add release note --- clang/docs/ReleaseNotes.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index 408b2800f9e79..24420d9dd49d5 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -853,6 +853,7 @@ Bug Fixes to AST Handling - Clang now uses the location of the begin of the member expression for ``CallExpr`` involving deduced ``this``. (#GH116928) - Fixed printout of AST that uses pack indexing expression. (#GH116486) +- Fixed type deduction of an statement expression (a GCC extension) ending with an atomic type. (#GH106576) Miscellaneous Bug Fixes ^^^ From 2cfef9885cdf023b038cce86519f65a4e9c60bfa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20=C3=81lvarez=20Ayll=C3=B3n?= Date: Wed, 12 Feb 2025 11:22:03 +0100 Subject: [PATCH 5/5] Fix by using getAtomicUnqualifiedType --- clang/lib/Sema/SemaExpr.cpp | 11 ++- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index 28ee5b07152ff..263cc181ad8de 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -1591
[clang] [clang][analyzer] fix false positive of BlockInCriticalSectionChecker (PR #126752)
https://github.com/flovent edited https://github.com/llvm/llvm-project/pull/126752 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][analyzer] fix false positive of BlockInCriticalSectionChecker (PR #126752)
@@ -339,6 +425,36 @@ void BlockInCriticalSectionChecker::reportBlockInCritSection( os.str(), ErrNode); R->addRange(Call.getSourceRange()); R->markInteresting(Call.getReturnValue()); + // for 'read' call, check whether it's file descriptor(first argument) is + // created by 'open' API with O_NONBLOCK flag and don't report for this + // situation. + if (Call.getCalleeIdentifier()->getName() == "read") { +do { + const auto *arg = Call.getArgExpr(0); + if (!arg) +break; + + const auto *DRE = dyn_cast(arg->IgnoreImpCasts()); Xazax-hun wrote: I see. Unfortunately, matching on the memory region might not be the most reliable. Having things like `int a = b;` would move the value in a new memory region. Also, matching the AST in the bug reporter visitor is fragile as there are many ways to express something. E.g., imagine if someone has some logging and does something like `int fd = LOG(open(...))` where the `LOG` macro inserts some extra code? In general, we should try to do as little matching on the AST as possible and should rely in the symbols when we can. So my proposal would be to maintain a set of symbols in the analysis state. After each `open` call look at the returned symbol, and in case it was returning a non-blocking file descriptor put that symbol in the set. When we report a problem check if the file descriptor we use to report the problem is in the set. This works great for symbolic file descriptors. Unfortunately, this might break down for concrete integers like 1. But I am wondering if that is a rare edge case enough that we might not need to support. I'd expect open to almost always return a symbolic value. What do you think? https://github.com/llvm/llvm-project/pull/126752 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-tools-extra] [llvm] [clang] WIP: Improved Context Declaration tracking (PR #107942)
@@ -3636,18 +3644,23 @@ ExprResult Parser::ParseRequiresExpression() { // Start of requirement list llvm::SmallVector Requirements; - // C++2a [expr.prim.req]p2 - // Expressions appearing within a requirement-body are unevaluated operands. - EnterExpressionEvaluationContext Ctx( - Actions, Sema::ExpressionEvaluationContext::Unevaluated); - ParseScope BodyScope(this, Scope::DeclScope); // Create a separate diagnostic pool for RequiresExprBodyDecl. // Dependent diagnostics are attached to this Decl and non-depenedent // diagnostics are surfaced after this parse. ParsingDeclRAIIObject ParsingBodyDecl(*this, ParsingDeclRAIIObject::NoParent); - RequiresExprBodyDecl *Body = Actions.ActOnStartRequiresExpr( - RequiresKWLoc, LocalParameterDecls, getCurScope()); + RequiresExprBodyDecl *Body = + Actions.ActOnStartRequiresExpr(RequiresKWLoc, LocalParameterDecls, + getCurScope(), TemplateParameterDepth); + + LocalInstantiationScope InstScope(getActions()); + for (ParmVarDecl *D : LocalParameterDecls) +InstScope.InstantiatedLocal(D, D); zyn0217 wrote: Where would we use that? https://github.com/llvm/llvm-project/pull/107942 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] allow restrict qualifier for array types with pointer types as element types (PR #120896)
https://github.com/a-tarasyuk updated https://github.com/llvm/llvm-project/pull/120896 >From 295df258043ef5a87ae603eedd308b863bad7b59 Mon Sep 17 00:00:00 2001 From: Oleksandr T Date: Sun, 22 Dec 2024 15:14:30 +0200 Subject: [PATCH 01/10] [Clang] allow restrict qualifier for array types with pointer types as element types --- clang/docs/ReleaseNotes.rst | 1 + clang/lib/Sema/SemaType.cpp | 4 +++- clang/test/Sema/types.c | 10 +- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index 6b9e1109f3906..52daea9b8eb2b 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -332,6 +332,7 @@ C Language Changes -- - Extend clang's to define ``LONG_LONG_*`` macros for Android's bionic. +- Clang now allows ``restrict`` qualifier for array types with pointer elements (#GH92847). C2y Feature Support ^^^ diff --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp index 83464c50b4b23..e84daeee679a5 100644 --- a/clang/lib/Sema/SemaType.cpp +++ b/clang/lib/Sema/SemaType.cpp @@ -1595,12 +1595,14 @@ QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc, QualType ProblemTy; if (T->isAnyPointerType() || T->isReferenceType() || -T->isMemberPointerType()) { +T->isMemberPointerType() || T->isArrayType()) { QualType EltTy; if (T->isObjCObjectPointerType()) EltTy = T; else if (const MemberPointerType *PTy = T->getAs()) EltTy = PTy->getPointeeType(); + else if (T->isArrayType()) +EltTy = Context.getBaseElementType(T); else EltTy = T->getPointeeType(); diff --git a/clang/test/Sema/types.c b/clang/test/Sema/types.c index e0a6ba4f0691b..4c90634b7ce28 100644 --- a/clang/test/Sema/types.c +++ b/clang/test/Sema/types.c @@ -9,20 +9,20 @@ typedef int (*T)[2]; restrict T x; typedef int *S[2]; -restrict S y; // expected-error {{restrict requires a pointer or reference ('S' (aka 'int *[2]') is invalid)}} - - +restrict S y; // int128_t is available. int a(void) { __int128_t s; __uint128_t t; -} +} // expected-warning {{non-void function does not return a value}} + // but not a keyword int b(void) { int __int128_t; int __uint128_t; -} +} // expected-warning {{non-void function does not return a value}} + // __int128 is a keyword int c(void) { __int128 i; >From 9e8dcdb20a3dd1ea9b49d501c2593d1ac1c7e424 Mon Sep 17 00:00:00 2001 From: Oleksandr T Date: Fri, 31 Jan 2025 23:54:03 +0200 Subject: [PATCH 02/10] add additional tests --- clang/lib/Sema/SemaType.cpp | 2 +- clang/test/Sema/restrict-qualifier.c | 20 2 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 clang/test/Sema/restrict-qualifier.c diff --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp index e84daeee679a5..ab85d6f51d22f 100644 --- a/clang/lib/Sema/SemaType.cpp +++ b/clang/lib/Sema/SemaType.cpp @@ -1602,7 +1602,7 @@ QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc, else if (const MemberPointerType *PTy = T->getAs()) EltTy = PTy->getPointeeType(); else if (T->isArrayType()) -EltTy = Context.getBaseElementType(T); +EltTy = BuildQualifiedType(Context.getBaseElementType(T), Loc, Qs); else EltTy = T->getPointeeType(); diff --git a/clang/test/Sema/restrict-qualifier.c b/clang/test/Sema/restrict-qualifier.c new file mode 100644 index 0..a68e55b47b580 --- /dev/null +++ b/clang/test/Sema/restrict-qualifier.c @@ -0,0 +1,20 @@ +// RUN: %clang_cc1 -std=c2y -fsyntax-only -verify -pedantic %s + +typedef int (*T1)[2]; +restrict T1 t1; +static_assert(_Generic(typeof (t1), int (*restrict)[2] : 1, default : 0)); + +typedef int *T2[2]; +restrict T2 t2; +static_assert(_Generic(typeof (t2), int *restrict[2] : 1, default : 0)); + +typedef int *T3[2][2]; +restrict T3 t3; +static_assert(_Generic(typeof (t3), int *restrict[2][2] : 1, default : 0)); + +typedef int (*t4)(); +typedef t4 t5[2]; +typedef t5 restrict t6; // expected-error {{pointer to function type 'int (void)' may not be 'restrict' qualified}} + +typedef int t7[2]; +typedef t7 restrict t8; // expected-error {{restrict requires a pointer or reference ('int' is invalid)}} >From 7c85906d8a35abfa84ae20f7af952e2a15b6fa0f Mon Sep 17 00:00:00 2001 From: Oleksandr T Date: Sat, 1 Feb 2025 15:00:19 +0200 Subject: [PATCH 03/10] adjust array handling for clearer inner type check --- clang/lib/Sema/SemaType.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp index da63522482390..3dd4952a829e0 100644 --- a/clang/lib/Sema/SemaType.cpp +++ b/clang/lib/Sema/SemaType.cpp @@ -1598,12 +1598,14 @@ QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc, if (T->isAnyPointerType() || T->isReferenceType() ||
[clang] [clang][analyzer] fix false positive of BlockInCriticalSectionChecker (PR #126752)
@@ -339,6 +425,36 @@ void BlockInCriticalSectionChecker::reportBlockInCritSection( os.str(), ErrNode); R->addRange(Call.getSourceRange()); R->markInteresting(Call.getReturnValue()); + // for 'read' call, check whether it's file descriptor(first argument) is + // created by 'open' API with O_NONBLOCK flag and don't report for this + // situation. + if (Call.getCalleeIdentifier()->getName() == "read") { +do { + const auto *arg = Call.getArgExpr(0); + if (!arg) +break; + + const auto *DRE = dyn_cast(arg->IgnoreImpCasts()); flovent wrote: thank you for your detailed explanation, I did overlook some complex scenarios. And I agree with your point, Checking for open's return value before calling `read` is very necessary in a real project, this is a modified testcase with checking for file descirptor,in that case we can ignore concrete integers situation. ``` void foo() { std::lock_guard lock(mtx); const char *filename = "example.txt"; int fd = open(filename, O_RDONLY | O_NONBLOCK); char buffer[200] = {}; if (fd == -1) return; read(fd, buffer, 199); // no-warning: fd is a non-block file descriptor close(fd); } ``` https://github.com/llvm/llvm-project/pull/126752 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][analyzer] fix false positive of BlockInCriticalSectionChecker (PR #126752)
https://github.com/flovent edited https://github.com/llvm/llvm-project/pull/126752 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][Sema] Add diagnostic note for reference of function-like macros requiring without parentheses (PR #123495)
https://github.com/StarOne01 updated https://github.com/llvm/llvm-project/pull/123495 >From ea6c9ca9cffbf4327fc7bab85e37e2a3c2c0f0cd Mon Sep 17 00:00:00 2001 From: Prashanth Date: Sun, 19 Jan 2025 07:28:24 +0530 Subject: [PATCH 01/12] [clang][Sema] Add diagnostic note for function-like macros requiring parentheses --- clang/include/clang/Basic/DiagnosticSemaKinds.td | 2 ++ clang/lib/Sema/SemaExpr.cpp | 15 ++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td index bcae9e9f30093..d9c8fcc66acf2 100644 --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -5961,6 +5961,8 @@ def err_fold_expression_limit_exceeded: Error< "instantiating fold expression with %0 arguments exceeded expression nesting " "limit of %1">, DefaultFatal, NoSFINAE; +def note_function_like_macro_requires_parens : Note< + "'%0' exists, but as a function-like macro; perhaps, did you forget the parentheses?">; def err_unexpected_typedef : Error< "unexpected type name %0: expected expression">; def err_unexpected_namespace : Error< diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index 3cd4010740d19..dff03ac31ef2a 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -2522,6 +2522,19 @@ bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, DC = DC->getLookupParent(); } + // Check whether a similar function-like macro exists and suggest it + if (IdentifierInfo *II = Name.getAsIdentifierInfo()) { +if (II->hasMacroDefinition()) { + MacroInfo *MI = PP.getMacroInfo(II); + if (MI && MI->isFunctionLike()) { +Diag( R.getNameLoc() ,diag::err_undeclared_var_use) << II->getName(); +Diag(MI->getDefinitionLoc(), diag::note_function_like_macro_requires_parens) +<< II->getName(); +return true; + } +} + } + // We didn't find anything, so try to correct for a typo. TypoCorrection Corrected; if (S && Out) { @@ -2632,7 +2645,7 @@ bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, << SS.getRange(); return true; } - + // Give up, we can't recover. Diag(R.getNameLoc(), diagnostic) << Name; return true; >From c274178a0ce3a510eaaa9390b277b860bcc5a2a9 Mon Sep 17 00:00:00 2001 From: Prashanth Date: Sun, 19 Jan 2025 08:30:39 +0530 Subject: [PATCH 02/12] [clang][Tests] Modify tests for function-like macros according to the new behavior and Format the changes --- clang/include/clang/Basic/DiagnosticSemaKinds.td| 5 +++-- clang/lib/Sema/SemaExpr.cpp | 7 --- clang/test/Preprocessor/macro_with_initializer_list.cpp | 6 -- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td index d9c8fcc66acf2..697b92d325240 100644 --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -5961,8 +5961,9 @@ def err_fold_expression_limit_exceeded: Error< "instantiating fold expression with %0 arguments exceeded expression nesting " "limit of %1">, DefaultFatal, NoSFINAE; -def note_function_like_macro_requires_parens : Note< - "'%0' exists, but as a function-like macro; perhaps, did you forget the parentheses?">; +def note_function_like_macro_requires_parens +: Note<"'%0' exists, but as a function-like macro; perhaps, did you forget " + "the parentheses?">; def err_unexpected_typedef : Error< "unexpected type name %0: expected expression">; def err_unexpected_namespace : Error< diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index dff03ac31ef2a..da894dd3a6d6a 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -2527,8 +2527,9 @@ bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, if (II->hasMacroDefinition()) { MacroInfo *MI = PP.getMacroInfo(II); if (MI && MI->isFunctionLike()) { -Diag( R.getNameLoc() ,diag::err_undeclared_var_use) << II->getName(); -Diag(MI->getDefinitionLoc(), diag::note_function_like_macro_requires_parens) +Diag(R.getNameLoc(), diag::err_undeclared_var_use) << II->getName(); +Diag(MI->getDefinitionLoc(), + diag::note_function_like_macro_requires_parens) << II->getName(); return true; } @@ -2645,7 +2646,7 @@ bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, << SS.getRange(); return true; } - + // Give up, we can't recover. Diag(R.getNameLoc(), diagnostic) << Name; return true; diff --git a/clang/test/Preprocessor/macro_with_initializer_list.cpp b/clang/test/Preprocessor/macro_with_initi
[clang] [clang][Sema] Fix type of an statement expression ending with an atomic type (PR #119711)
https://github.com/alejandro-alvarez-sonarsource updated https://github.com/llvm/llvm-project/pull/119711 From d398fa13c2fa141954c79ca68a59c6ac506b393f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20=C3=81lvarez=20Ayll=C3=B3n?= Date: Wed, 11 Dec 2024 15:43:58 +0100 Subject: [PATCH 1/5] Add regression test --- clang/test/Sema/gh106576.c | 16 1 file changed, 16 insertions(+) create mode 100644 clang/test/Sema/gh106576.c diff --git a/clang/test/Sema/gh106576.c b/clang/test/Sema/gh106576.c new file mode 100644 index 0..792977dea1413 --- /dev/null +++ b/clang/test/Sema/gh106576.c @@ -0,0 +1,16 @@ +// RUN: %clang_cc1 -fsyntax-only -verify %s + +typedef _Atomic char atomic_char; + +typedef _Atomic char atomic_char; + +atomic_char counter; + +char load_plus_one(void) { + return ({counter;}) + 1; // no crash +} + +char type_of_stmt_expr(void) { + typeof(({counter;})) y = ""; // expected-error-re {{incompatible pointer to integer conversion initializing 'typeof (({{{.*}}}))' (aka 'char') with an expression of type 'char[1]'}} + return y; +} From 296aa35fe32449067c69d2b40031af0dd6822a07 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20=C3=81lvarez=20Ayll=C3=B3n?= Date: Thu, 12 Dec 2024 15:08:56 +0100 Subject: [PATCH 2/5] Tentative fix --- clang/lib/Sema/SemaExpr.cpp | 13 +++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index 20bf6f7f6f28f..165447efb345c 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -15861,10 +15861,19 @@ ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) return Cast->getSubExpr(); + auto Ty = E->getType().getUnqualifiedType(); + + // If the type is an atomic, the statement type is the underlying type. + if (const AtomicType *AT = Ty->getAs()) { +Ty = AT->getValueType().getUnqualifiedType(); +return ImplicitCastExpr::Create(Context, Ty, CK_AtomicToNonAtomic, E, +/*base path*/ nullptr, VK_PRValue, +FPOptionsOverride()); + } + // FIXME: Provide a better location for the initialization. return PerformCopyInitialization( - InitializedEntity::InitializeStmtExprResult( - E->getBeginLoc(), E->getType().getUnqualifiedType()), + InitializedEntity::InitializeStmtExprResult(E->getBeginLoc(), Ty), SourceLocation(), E); } From d13e1090c641314aae8eef50f1b0fb5c0ec67e39 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20=C3=81lvarez=20Ayll=C3=B3n?= Date: Thu, 12 Dec 2024 15:30:07 +0100 Subject: [PATCH 3/5] Use PerformImplicitConversion --- clang/lib/Sema/SemaExpr.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index 165447efb345c..45ae97807c203 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -15866,9 +15866,7 @@ ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { // If the type is an atomic, the statement type is the underlying type. if (const AtomicType *AT = Ty->getAs()) { Ty = AT->getValueType().getUnqualifiedType(); -return ImplicitCastExpr::Create(Context, Ty, CK_AtomicToNonAtomic, E, -/*base path*/ nullptr, VK_PRValue, -FPOptionsOverride()); +return PerformImplicitConversion(E, Ty, AssignmentAction::Casting); } // FIXME: Provide a better location for the initialization. From 02d8385cc0f824ff0436a7b0a42d16555e5ee0c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20=C3=81lvarez=20Ayll=C3=B3n?= Date: Wed, 18 Dec 2024 09:19:51 +0100 Subject: [PATCH 4/5] Add release note --- clang/docs/ReleaseNotes.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index 408b2800f9e79..24420d9dd49d5 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -853,6 +853,7 @@ Bug Fixes to AST Handling - Clang now uses the location of the begin of the member expression for ``CallExpr`` involving deduced ``this``. (#GH116928) - Fixed printout of AST that uses pack indexing expression. (#GH116486) +- Fixed type deduction of an statement expression (a GCC extension) ending with an atomic type. (#GH106576) Miscellaneous Bug Fixes ^^^ From 46a2b3b9aab3f3778c15e3f021241bcf612e3be6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20=C3=81lvarez=20Ayll=C3=B3n?= Date: Wed, 12 Feb 2025 11:22:03 +0100 Subject: [PATCH 5/5] Fix by using getAtomicUnqualifiedType --- clang/lib/Sema/SemaExpr.cpp | 11 ++- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index c564949cb2e47..0cdbca4f6723b 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -1594
[clang] [llvm] [llvm:ir] Add support for constant data exceeding 4GiB (PR #126481)
https://github.com/pzzp updated https://github.com/llvm/llvm-project/pull/126481 >From 3feb290783ff44972d5634b505ec3e051f1e2603 Mon Sep 17 00:00:00 2001 From: zhoupeng12 Date: Mon, 30 Oct 2023 18:13:07 +0800 Subject: [PATCH] [llvm:ir] Add support for constant data exceeding 4GiB --- clang/lib/CodeGen/CGExprConstant.cpp | 8 llvm/include/llvm/IR/Constants.h | 6 +++--- llvm/lib/Bitcode/Writer/BitcodeWriter.cpp| 8 llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp | 6 +++--- llvm/lib/IR/Constants.cpp| 9 - llvm/lib/Target/TargetLoweringObjectFile.cpp | 4 ++-- llvm/lib/Target/X86/X86MCInstLower.cpp | 2 +- 7 files changed, 21 insertions(+), 22 deletions(-) diff --git a/clang/lib/CodeGen/CGExprConstant.cpp b/clang/lib/CodeGen/CGExprConstant.cpp index ef11798869d3b..b0ff6fae65f16 100644 --- a/clang/lib/CodeGen/CGExprConstant.cpp +++ b/clang/lib/CodeGen/CGExprConstant.cpp @@ -364,14 +364,14 @@ bool ConstantAggregateBuilder::split(size_t Index, CharUnits Hint) { // FIXME: If possible, split into two ConstantDataSequentials at Hint. CharUnits ElemSize = getSize(CDS->getElementType()); replace(Elems, Index, Index + 1, -llvm::map_range(llvm::seq(0u, CDS->getNumElements()), -[&](unsigned Elem) { +llvm::map_range(llvm::seq(uint64_t(0u), CDS->getNumElements()), +[&](uint64_t Elem) { return CDS->getElementAsConstant(Elem); })); replace(Offsets, Index, Index + 1, llvm::map_range( -llvm::seq(0u, CDS->getNumElements()), -[&](unsigned Elem) { return Offset + Elem * ElemSize; })); +llvm::seq(uint64_t(0u), CDS->getNumElements()), +[&](uint64_t Elem) { return Offset + Elem * ElemSize; })); return true; } diff --git a/llvm/include/llvm/IR/Constants.h b/llvm/include/llvm/IR/Constants.h index 15b90589b7e2b..2af0fc8642e87 100644 --- a/llvm/include/llvm/IR/Constants.h +++ b/llvm/include/llvm/IR/Constants.h @@ -617,7 +617,7 @@ class ConstantDataSequential : public ConstantData { /// If this is a sequential container of integers (of any size), return the /// specified element in the low bits of a uint64_t. - uint64_t getElementAsInteger(unsigned i) const; + uint64_t getElementAsInteger(uint64_t i) const; /// If this is a sequential container of integers (of any size), return the /// specified element as an APInt. @@ -644,7 +644,7 @@ class ConstantDataSequential : public ConstantData { Type *getElementType() const; /// Return the number of elements in the array or vector. - unsigned getNumElements() const; + uint64_t getNumElements() const; /// Return the size (in bytes) of each element in the array/vector. /// The size of the elements is known to be a multiple of one byte. @@ -684,7 +684,7 @@ class ConstantDataSequential : public ConstantData { } private: - const char *getElementPointer(unsigned Elt) const; + const char *getElementPointer(uint64_t Elt) const; }; //===--===// diff --git a/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp b/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp index 7ca63c2c7251d..c95bfc5cf2415 100644 --- a/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp +++ b/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp @@ -2773,7 +2773,7 @@ void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal, cast(C)->isString()) { const ConstantDataSequential *Str = cast(C); // Emit constant strings specially. - unsigned NumElts = Str->getNumElements(); + uint64_t NumElts = Str->getNumElements(); // If this is a null-terminated string, use the denser CSTRING encoding. if (Str->isCString()) { Code = bitc::CST_CODE_CSTRING; @@ -2784,7 +2784,7 @@ void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal, } bool isCStr7 = Code == bitc::CST_CODE_CSTRING; bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING; - for (unsigned i = 0; i != NumElts; ++i) { + for (uint64_t i = 0; i != NumElts; ++i) { unsigned char V = Str->getElementAsInteger(i); Record.push_back(V); isCStr7 &= (V & 128) == 0; @@ -2801,10 +2801,10 @@ void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal, Code = bitc::CST_CODE_DATA; Type *EltTy = CDS->getElementType(); if (isa(EltTy)) { -for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) +for (uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i) Record.push_back(CDS->getElementAsInteger(i)); } else { -for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) +for (uint64_t i = 0, e = CDS->getNumElements(); i != e; ++i) Record.push_back(
[clang] [NFC][analyzer] OOB test consolidation II: constraint checking (PR #126748)
@@ -1,112 +1,163 @@ // RUN: %clang_analyze_cc1 -analyzer-checker=core,unix.Malloc,security.ArrayBound,debug.ExprInspection \ // RUN: -analyzer-config eagerly-assume=false -verify %s -void clang_analyzer_eval(int); -void clang_analyzer_printState(void); - -typedef typeof(sizeof(int)) size_t; -const char a[] = "abcd"; // extent: 5 bytes - -void symbolic_size_t_and_int0(size_t len) { - (void)a[len + 1]; // no-warning - // We infered that the 'len' must be in a specific range to make the previous indexing valid. - // len: [0,3] - clang_analyzer_eval(len <= 3); // expected-warning {{TRUE}} - clang_analyzer_eval(len <= 2); // expected-warning {{UNKNOWN}} -} - -void symbolic_size_t_and_int1(size_t len) { - (void)a[len]; // no-warning - // len: [0,4] - clang_analyzer_eval(len <= 4); // expected-warning {{TRUE}} - clang_analyzer_eval(len <= 3); // expected-warning {{UNKNOWN}} -} - -void symbolic_size_t_and_int2(size_t len) { - (void)a[len - 1]; // no-warning - // len: [1,5] - clang_analyzer_eval(1 <= len && len <= 5); // expected-warning {{TRUE}} - clang_analyzer_eval(2 <= len); // expected-warning {{UNKNOWN}} - clang_analyzer_eval(len <= 4); // expected-warning {{UNKNOWN}} -} - -void symbolic_uint_and_int0(unsigned len) { - (void)a[len + 1]; // no-warning - // len: [0,3] - clang_analyzer_eval(0 <= len && len <= 3); // expected-warning {{TRUE}} - clang_analyzer_eval(1 <= len); // expected-warning {{UNKNOWN}} - clang_analyzer_eval(len <= 2); // expected-warning {{UNKNOWN}} -} - -void symbolic_uint_and_int1(unsigned len) { - (void)a[len]; // no-warning - // len: [0,4] - clang_analyzer_eval(0 <= len && len <= 4); // expected-warning {{TRUE}} - clang_analyzer_eval(1 <= len); // expected-warning {{UNKNOWN}} - clang_analyzer_eval(len <= 3); // expected-warning {{UNKNOWN}} -} -void symbolic_uint_and_int2(unsigned len) { - (void)a[len - 1]; // no-warning - // len: [1,5] - clang_analyzer_eval(1 <= len && len <= 5); // expected-warning {{TRUE}} - clang_analyzer_eval(2 <= len); // expected-warning {{UNKNOWN}} - clang_analyzer_eval(len <= 4); // expected-warning {{UNKNOWN}} -} - -void symbolic_int_and_int0(int len) { - (void)a[len + 1]; // no-warning - // len: [-1,3] - clang_analyzer_eval(-1 <= len && len <= 3); // expected-warning {{TRUE}} - clang_analyzer_eval(0 <= len); // expected-warning {{UNKNOWN}} - clang_analyzer_eval(len <= 2); // expected-warning {{UNKNOWN}} -} -void symbolic_int_and_int1(int len) { - (void)a[len]; // no-warning - // len: [0,4] - clang_analyzer_eval(0 <= len && len <= 4); // expected-warning {{TRUE}} - clang_analyzer_eval(1 <= len); // expected-warning {{UNKNOWN}} - clang_analyzer_eval(len <= 3); // expected-warning {{UNKNOWN}} -} -void symbolic_int_and_int2(int len) { - (void)a[len - 1]; // no-warning - // len: [1,5] - clang_analyzer_eval(1 <= len && len <= 5); // expected-warning {{TRUE}} - clang_analyzer_eval(2 <= len); // expected-warning {{UNKNOWN}} - clang_analyzer_eval(len <= 4); // expected-warning {{UNKNOWN}} -} - -void symbolic_longlong_and_int0(long long len) { - (void)a[len + 1]; // no-warning - // len: [-1,3] - clang_analyzer_eval(-1 <= len && len <= 3); // expected-warning {{TRUE}} - clang_analyzer_eval(0 <= len); // expected-warning {{UNKNOWN}} - clang_analyzer_eval(len <= 2); // expected-warning {{UNKNOWN}} +// When the checker security.ArrayBound encounters an array subscript operation +// that _may be_ in bounds, it assumes that indexing _is_ in bound. This test +// file validates these assumptions. + +void clang_analyzer_value(int); + +// Simple case: memory area with a static extent. + +int FiveInts[5] = {1, 2, 3, 4, 5}; NagyDonat wrote: Good point, I'll switch to using `extern`. https://github.com/llvm/llvm-project/pull/126748 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] Add option assume-at-least-one-iteration (PR #125494)
https://github.com/gamesh411 approved this pull request. https://github.com/llvm/llvm-project/pull/125494 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [NFC] Delete useless call (PR #126874)
@@ -440,7 +440,6 @@ static SVal castArgToParamTypeIfNeeded(const CallEvent &Call, unsigned ArgIdx, return ArgVal; const FunctionDecl *Definition = CallExprDecl; - Definition->hasBody(Definition); schittir wrote: Yes, that makes sense. This change is wrong, and that's why I quickly closed the PRs associated with this. Thank you for your review. https://github.com/llvm/llvm-project/pull/126874 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] Simplify CallEvent castArgToParamTypeIfNeeded (PR #120981)
https://github.com/schittir deleted https://github.com/llvm/llvm-project/pull/120981 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [NFC] Delete useless call (PR #126874)
@@ -440,7 +440,6 @@ static SVal castArgToParamTypeIfNeeded(const CallEvent &Call, unsigned ArgIdx, return ArgVal; const FunctionDecl *Definition = CallExprDecl; - Definition->hasBody(Definition); steakhal wrote: The removal of this would break the `clang/test/Analysis/region-store.c:79:3` test case. It's intentional. The `hasBody` (awkwardly though), sets the parameter (`Definition`) to the definition decl of the function decl if it has definition. I could have used the `if (const auto *Def = CallExprDecl.getDefinition()) Definition = Def;` but that would have been longer to spell, along with a controlflow statement. https://github.com/llvm/llvm-project/pull/126874 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [NFC] Delete useless call (PR #126874)
@@ -440,7 +440,6 @@ static SVal castArgToParamTypeIfNeeded(const CallEvent &Call, unsigned ArgIdx, return ArgVal; const FunctionDecl *Definition = CallExprDecl; - Definition->hasBody(Definition); steakhal wrote: These tests can be run using `check-clang-analysis`, or using `check-clang`. https://github.com/llvm/llvm-project/pull/126874 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [NFC] Delete useless call (PR #126874)
https://github.com/steakhal edited https://github.com/llvm/llvm-project/pull/126874 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [analyzer] Simplify CallEvent castArgToParamTypeIfNeeded (PR #120981)
@@ -435,27 +435,27 @@ static SVal processArgument(SVal Value, const Expr *ArgumentExpr, /// runtime definition don't match in terms of argument and parameter count. static SVal castArgToParamTypeIfNeeded(const CallEvent &Call, unsigned ArgIdx, SVal ArgVal, SValBuilder &SVB) { - const FunctionDecl *RTDecl = - Call.getRuntimeDefinition().getDecl()->getAsFunction(); const auto *CallExprDecl = dyn_cast_or_null(Call.getDecl()); - - if (!RTDecl || !CallExprDecl) + if (!CallExprDecl) return ArgVal; + const FunctionDecl *Definition = CallExprDecl; + Definition->hasBody(Definition); schittir wrote: @steakhal - Did you intend to add this call? It appears useless without the return value check. Also, I don't see any tests associated with this change. Could you please point me to them? Thank you! https://github.com/llvm/llvm-project/pull/120981 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][analyzer] fix false positive of BlockInCriticalSectionChecker (PR #126752)
@@ -339,6 +425,36 @@ void BlockInCriticalSectionChecker::reportBlockInCritSection( os.str(), ErrNode); R->addRange(Call.getSourceRange()); R->markInteresting(Call.getReturnValue()); + // for 'read' call, check whether it's file descriptor(first argument) is + // created by 'open' API with O_NONBLOCK flag and don't report for this + // situation. + if (Call.getCalleeIdentifier()->getName() == "read") { Xazax-hun wrote: The result of `Call.getCalleeIdentifier()` could be null, e.g., when the name of the function is not a simple identifier (like certain operators). https://github.com/llvm/llvm-project/pull/126752 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][analyzer] fix false positive of BlockInCriticalSectionChecker (PR #126752)
@@ -339,6 +425,36 @@ void BlockInCriticalSectionChecker::reportBlockInCritSection( os.str(), ErrNode); R->addRange(Call.getSourceRange()); R->markInteresting(Call.getReturnValue()); + // for 'read' call, check whether it's file descriptor(first argument) is + // created by 'open' API with O_NONBLOCK flag and don't report for this + // situation. + if (Call.getCalleeIdentifier()->getName() == "read") { +do { + const auto *arg = Call.getArgExpr(0); + if (!arg) +break; + + const auto *DRE = dyn_cast(arg->IgnoreImpCasts()); Xazax-hun wrote: Matching the AST is not a good idea. What if the user writes something like `cond ? val1 : val2` as the argument? Any reason to not use `CallEvent::getArgSVal`? https://github.com/llvm/llvm-project/pull/126752 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][analyzer] fix false positive of BlockInCriticalSectionChecker (PR #126752)
https://github.com/Xazax-hun edited https://github.com/llvm/llvm-project/pull/126752 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][analyzer] fix false positive of BlockInCriticalSectionChecker (PR #126752)
https://github.com/Xazax-hun commented: Is read the only operation that is non-blocking in this case? Alternatively, instead of using a BugReporterVisitor, we could maintain a set of file handles that are OK to use. https://github.com/llvm/llvm-project/pull/126752 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Force expressions with UO_Not to not be non-negative (PR #126846)
https://github.com/YutongZhuu edited https://github.com/llvm/llvm-project/pull/126846 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [NFC][analyzer] OOB test consolidation II: constraint checking (PR #126748)
https://github.com/NagyDonat updated https://github.com/llvm/llvm-project/pull/126748 From df63943adf054b94249b125078d4dbeafb437641 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Don=C3=A1t=20Nagy?= Date: Tue, 11 Feb 2025 16:22:32 +0100 Subject: [PATCH 1/4] [NFC][analyzer] OOB test consolidation II: constraint checking This commit heavily refactors `out-of-bounds-constraint-check.c`: 1. The complex combinations of several `clang_analyzer_eval` calls were replaced by `clang_analyzer_value`, which can directly query the range of a symbol. 2. Testcases were renamed to a (hopefully) more consistent scheme. 3. The use of `size_t` as an argument type was replaced by `unsigned long long`, which is usually a no-op, but seems to be a better choice if I look for `64u` in the output of `clang_analyzer_value`. 4. The single "dynamic extent" case was generalized into a full set of tests that use `malloc`. 5. Half of the testcases (the ones that don't use `malloc`) were changed to use an `int[5]` array instead of a string literal. After this change the tests in this file cover every functionality that was tested by the testcases `test_assume_after_access{,2}` in the file `out-of-bounds.c` so I was able to delete those two testcases (and therefore consolidate the validation of these constraints within a single test file). This is the second commit in a series that reorganizes the tests of `security.ArrayBound` to system that's easier to understand and maintain. (Note that this file wasn't significantly modified by the recent commit 6e17ed9b04e5523cc910bf171c3122dcc64b86db which renamed `alpha.security.ArrayBoundV2` to `security.ArrayBound`; but I still felt that this cleanup may be useful.) --- .../Analysis/out-of-bounds-constraint-check.c | 259 +++--- clang/test/Analysis/out-of-bounds.c | 16 +- 2 files changed, 156 insertions(+), 119 deletions(-) diff --git a/clang/test/Analysis/out-of-bounds-constraint-check.c b/clang/test/Analysis/out-of-bounds-constraint-check.c index df48c8c170713..b89af08cff222 100644 --- a/clang/test/Analysis/out-of-bounds-constraint-check.c +++ b/clang/test/Analysis/out-of-bounds-constraint-check.c @@ -1,112 +1,163 @@ // RUN: %clang_analyze_cc1 -analyzer-checker=core,unix.Malloc,security.ArrayBound,debug.ExprInspection \ // RUN: -analyzer-config eagerly-assume=false -verify %s -void clang_analyzer_eval(int); -void clang_analyzer_printState(void); - -typedef typeof(sizeof(int)) size_t; -const char a[] = "abcd"; // extent: 5 bytes - -void symbolic_size_t_and_int0(size_t len) { - (void)a[len + 1]; // no-warning - // We infered that the 'len' must be in a specific range to make the previous indexing valid. - // len: [0,3] - clang_analyzer_eval(len <= 3); // expected-warning {{TRUE}} - clang_analyzer_eval(len <= 2); // expected-warning {{UNKNOWN}} -} - -void symbolic_size_t_and_int1(size_t len) { - (void)a[len]; // no-warning - // len: [0,4] - clang_analyzer_eval(len <= 4); // expected-warning {{TRUE}} - clang_analyzer_eval(len <= 3); // expected-warning {{UNKNOWN}} -} - -void symbolic_size_t_and_int2(size_t len) { - (void)a[len - 1]; // no-warning - // len: [1,5] - clang_analyzer_eval(1 <= len && len <= 5); // expected-warning {{TRUE}} - clang_analyzer_eval(2 <= len); // expected-warning {{UNKNOWN}} - clang_analyzer_eval(len <= 4); // expected-warning {{UNKNOWN}} -} - -void symbolic_uint_and_int0(unsigned len) { - (void)a[len + 1]; // no-warning - // len: [0,3] - clang_analyzer_eval(0 <= len && len <= 3); // expected-warning {{TRUE}} - clang_analyzer_eval(1 <= len); // expected-warning {{UNKNOWN}} - clang_analyzer_eval(len <= 2); // expected-warning {{UNKNOWN}} -} - -void symbolic_uint_and_int1(unsigned len) { - (void)a[len]; // no-warning - // len: [0,4] - clang_analyzer_eval(0 <= len && len <= 4); // expected-warning {{TRUE}} - clang_analyzer_eval(1 <= len); // expected-warning {{UNKNOWN}} - clang_analyzer_eval(len <= 3); // expected-warning {{UNKNOWN}} -} -void symbolic_uint_and_int2(unsigned len) { - (void)a[len - 1]; // no-warning - // len: [1,5] - clang_analyzer_eval(1 <= len && len <= 5); // expected-warning {{TRUE}} - clang_analyzer_eval(2 <= len); // expected-warning {{UNKNOWN}} - clang_analyzer_eval(len <= 4); // expected-warning {{UNKNOWN}} -} - -void symbolic_int_and_int0(int len) { - (void)a[len + 1]; // no-warning - // len: [-1,3] - clang_analyzer_eval(-1 <= len && len <= 3); // expected-warning {{TRUE}} - clang_analyzer_eval(0 <= len); // expected-warning {{UNKNOWN}} - clang_analyzer_eval(len <= 2); // expected-warning {{UNKNOWN}} -} -void symbolic_int_and_int1(int len) { - (void)a[len]; // no-warning - // len: [0,4] - clang_analyzer_eval(0 <= len && len <= 4); // expected-warning {{TRUE}} - clang_analyzer_eval(1 <= len); // expected-warning {{UNKN
[clang] [clang][analyzer] fix false positive of BlockInCriticalSectionChecker (PR #126752)
steakhal wrote: I want to review this PR before anyone would approve and merge this, as I was the one who plotted a potential solution in the linked issue. I hope I can get to this on the weekend. https://github.com/llvm/llvm-project/pull/126752 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [NFC][analyzer] OOB test consolidation II: constraint checking (PR #126748)
NagyDonat wrote: > Please avoid matching the types of the `clang_analyzer_value` dumps, but be > sure to match the whole range sets there, including their curlies. It's still > important to know that it would have a single range associated. Yes, that's what I was planning. Pushed a commit that removes the type markers, but keeps the curlies. Also, my previous commit accidentally removed `'-Wno-array-bounds'`, I re-added it. https://github.com/llvm/llvm-project/pull/126748 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][Sema] Fix initialization of `NonTypeTemplateParmDecl`... (PR #121768)
@@ -786,12 +786,16 @@ NonTypeTemplateParmDecl *NonTypeTemplateParmDecl::Create( QualType T, bool ParameterPack, TypeSourceInfo *TInfo) { AutoType *AT = C.getLangOpts().CPlusPlus20 ? T->getContainedAutoType() : nullptr; - return new (C, DC, - additionalSizeToAlloc, -Expr *>(0, -AT && AT->isConstrained() ? 1 : 0)) - NonTypeTemplateParmDecl(DC, StartLoc, IdLoc, D, P, Id, T, ParameterPack, - TInfo); + bool const HasConstraint = AT && AT->isConstrained(); alejandro-alvarez-sonarsource wrote: Thanks! Swapped the order of the cost. Would you mind doing the merge? https://github.com/llvm/llvm-project/pull/121768 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [Clang] [OpenMP] Add support for '#pragma omp stripe'. (PR #119891)
zahiraam wrote: > @zahiraam I've reverted your PR. I'm happy to test your revised version > though my build environment is no secret -- `-DLLVM_ENABLE_WERROR=On` along > with clang as the host compiler. Sorry about that! I will fix the error and merge it back. https://github.com/llvm/llvm-project/pull/119891 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][analyzer] fix false positive of BlockInCriticalSectionChecker (PR #126752)
@@ -145,6 +145,92 @@ using MutexDescriptor = std::variant; +class NonBlockOpenVisitor : public BugReporterVisitor { +private: + const VarRegion *VR; + const CallExpr *OpenCallExpr; + int O_NONBLOCKV; whisperity wrote: My suggestion is to call this `int` here something else. Maybe `int ValueOfONonBlockVFlag; or just `int ValueO_NONBLOCKV;`. Something that prevents an accidental expansion to invalid code `int 8;` or something in this file. Getting the value at runtime from the target architecture and putting it behind this variable is not a problem to do. The only concern here is the name of this variable. https://github.com/llvm/llvm-project/pull/126752 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][AST] Handle dependent representation of call to function with explicit object parameter in CallExpr::getBeginLoc() (PR #126868)
@@ -1648,8 +1648,11 @@ SourceLocation CallExpr::getBeginLoc() const { if (const auto *Method = dyn_cast_if_present(getCalleeDecl()); Method && Method->isExplicitObjectMemberFunction()) { -assert(getNumArgs() > 0 && getArg(0)); -return getArg(0)->getBeginLoc(); +if (!isTypeDependent()) { + assert(getNumArgs() > 0 && getArg(0)); + if (getNumArgs() > 0 && getArg(0)) AaronBallman wrote: IMO, the `assert` by itself is sufficient. Otherwise everyone is paying the overhead for the check which should never fail anyway. https://github.com/llvm/llvm-project/pull/126868 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][Sema] Fix type of an statement expression ending with an atomic type (PR #119711)
https://github.com/alejandro-alvarez-sonarsource updated https://github.com/llvm/llvm-project/pull/119711 From d398fa13c2fa141954c79ca68a59c6ac506b393f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20=C3=81lvarez=20Ayll=C3=B3n?= Date: Wed, 11 Dec 2024 15:43:58 +0100 Subject: [PATCH 1/5] Add regression test --- clang/test/Sema/gh106576.c | 16 1 file changed, 16 insertions(+) create mode 100644 clang/test/Sema/gh106576.c diff --git a/clang/test/Sema/gh106576.c b/clang/test/Sema/gh106576.c new file mode 100644 index 0..792977dea1413 --- /dev/null +++ b/clang/test/Sema/gh106576.c @@ -0,0 +1,16 @@ +// RUN: %clang_cc1 -fsyntax-only -verify %s + +typedef _Atomic char atomic_char; + +typedef _Atomic char atomic_char; + +atomic_char counter; + +char load_plus_one(void) { + return ({counter;}) + 1; // no crash +} + +char type_of_stmt_expr(void) { + typeof(({counter;})) y = ""; // expected-error-re {{incompatible pointer to integer conversion initializing 'typeof (({{{.*}}}))' (aka 'char') with an expression of type 'char[1]'}} + return y; +} From 296aa35fe32449067c69d2b40031af0dd6822a07 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20=C3=81lvarez=20Ayll=C3=B3n?= Date: Thu, 12 Dec 2024 15:08:56 +0100 Subject: [PATCH 2/5] Tentative fix --- clang/lib/Sema/SemaExpr.cpp | 13 +++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index 20bf6f7f6f28f..165447efb345c 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -15861,10 +15861,19 @@ ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) return Cast->getSubExpr(); + auto Ty = E->getType().getUnqualifiedType(); + + // If the type is an atomic, the statement type is the underlying type. + if (const AtomicType *AT = Ty->getAs()) { +Ty = AT->getValueType().getUnqualifiedType(); +return ImplicitCastExpr::Create(Context, Ty, CK_AtomicToNonAtomic, E, +/*base path*/ nullptr, VK_PRValue, +FPOptionsOverride()); + } + // FIXME: Provide a better location for the initialization. return PerformCopyInitialization( - InitializedEntity::InitializeStmtExprResult( - E->getBeginLoc(), E->getType().getUnqualifiedType()), + InitializedEntity::InitializeStmtExprResult(E->getBeginLoc(), Ty), SourceLocation(), E); } From d13e1090c641314aae8eef50f1b0fb5c0ec67e39 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20=C3=81lvarez=20Ayll=C3=B3n?= Date: Thu, 12 Dec 2024 15:30:07 +0100 Subject: [PATCH 3/5] Use PerformImplicitConversion --- clang/lib/Sema/SemaExpr.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index 165447efb345c..45ae97807c203 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -15866,9 +15866,7 @@ ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { // If the type is an atomic, the statement type is the underlying type. if (const AtomicType *AT = Ty->getAs()) { Ty = AT->getValueType().getUnqualifiedType(); -return ImplicitCastExpr::Create(Context, Ty, CK_AtomicToNonAtomic, E, -/*base path*/ nullptr, VK_PRValue, -FPOptionsOverride()); +return PerformImplicitConversion(E, Ty, AssignmentAction::Casting); } // FIXME: Provide a better location for the initialization. From 02d8385cc0f824ff0436a7b0a42d16555e5ee0c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20=C3=81lvarez=20Ayll=C3=B3n?= Date: Wed, 18 Dec 2024 09:19:51 +0100 Subject: [PATCH 4/5] Add release note --- clang/docs/ReleaseNotes.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index 408b2800f9e79..24420d9dd49d5 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -853,6 +853,7 @@ Bug Fixes to AST Handling - Clang now uses the location of the begin of the member expression for ``CallExpr`` involving deduced ``this``. (#GH116928) - Fixed printout of AST that uses pack indexing expression. (#GH116486) +- Fixed type deduction of an statement expression (a GCC extension) ending with an atomic type. (#GH106576) Miscellaneous Bug Fixes ^^^ From 2cfef9885cdf023b038cce86519f65a4e9c60bfa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20=C3=81lvarez=20Ayll=C3=B3n?= Date: Wed, 12 Feb 2025 11:22:03 +0100 Subject: [PATCH 5/5] Fix by using getAtomicUnqualifiedType --- clang/lib/Sema/SemaExpr.cpp | 11 ++- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index 28ee5b07152ff..263cc181ad8de 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -1591
[clang] [clang][analyzer] fix false positive of BlockInCriticalSectionChecker (PR #126752)
@@ -145,6 +145,92 @@ using MutexDescriptor = std::variant; +class NonBlockOpenVisitor : public BugReporterVisitor { +private: + const VarRegion *VR; + const CallExpr *OpenCallExpr; + int O_NONBLOCKV; flovent wrote: i understand now, thank you for explaining, i will change it in the subsequent modification https://github.com/llvm/llvm-project/pull/126752 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][Sema] Fix type of an statement expression ending with an atomic type (PR #119711)
@@ -15919,10 +15919,17 @@ ExprResult Sema::ActOnStmtExprResult(ExprResult ER) { if (Cast && Cast->getCastKind() == CK_ARCConsumeObject) return Cast->getSubExpr(); + auto Ty = E->getType().getUnqualifiedType(); alejandro-alvarez-sonarsource wrote: > Before you get too far into anything else, could you try just changing the > call to getUnqualifiedType() to getAtomicUnqualifiedType() in the original > code and seeing if that fixes the problem? That should be fine for the local, > short-term fix. It fixes it, yes, thanks! (Sorry for the force-push, I saw some seemingly unrelated tests were broken and I wanted to make sure it wasn't due to this, after un-merging `main` [all tests are green](https://buildkite.com/llvm-project/github-pull-requests/builds/146266#_)) https://github.com/llvm/llvm-project/pull/119711 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [openmp] [OpenMP][SIMD][FIX] Use conservative "omp simd ordered" lowering (PR #126172)
https://github.com/alexey-bataev closed https://github.com/llvm/llvm-project/pull/126172 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [WIP][OpenMP] dispatch directive semantics/codegen (PR #126914)
https://github.com/shiltian edited https://github.com/llvm/llvm-project/pull/126914 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][analyzer] fix false positive of BlockInCriticalSectionChecker (PR #126752)
flovent wrote: i have implemented the way using set successfully in my local development environment as @Xazax-hun suggested. the implementation detail is: 1. when we encounter `open` call, if open flag contains O_NONBLOCK, store call's return Symbol to set, 2. when we encounter `read` call, check whether file descriptor's Symbol exists in this set, if so don't report. it's different with your solution in the related issue, and it doesn't handle situation when open return -1. have any thoughts for the discussion above? @steakhal https://github.com/llvm/llvm-project/pull/126752 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] allow restrict qualifier for array types with pointer types as element types (PR #120896)
https://github.com/a-tarasyuk updated https://github.com/llvm/llvm-project/pull/120896 >From 295df258043ef5a87ae603eedd308b863bad7b59 Mon Sep 17 00:00:00 2001 From: Oleksandr T Date: Sun, 22 Dec 2024 15:14:30 +0200 Subject: [PATCH 01/10] [Clang] allow restrict qualifier for array types with pointer types as element types --- clang/docs/ReleaseNotes.rst | 1 + clang/lib/Sema/SemaType.cpp | 4 +++- clang/test/Sema/types.c | 10 +- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index 6b9e1109f3906..52daea9b8eb2b 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -332,6 +332,7 @@ C Language Changes -- - Extend clang's to define ``LONG_LONG_*`` macros for Android's bionic. +- Clang now allows ``restrict`` qualifier for array types with pointer elements (#GH92847). C2y Feature Support ^^^ diff --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp index 83464c50b4b23..e84daeee679a5 100644 --- a/clang/lib/Sema/SemaType.cpp +++ b/clang/lib/Sema/SemaType.cpp @@ -1595,12 +1595,14 @@ QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc, QualType ProblemTy; if (T->isAnyPointerType() || T->isReferenceType() || -T->isMemberPointerType()) { +T->isMemberPointerType() || T->isArrayType()) { QualType EltTy; if (T->isObjCObjectPointerType()) EltTy = T; else if (const MemberPointerType *PTy = T->getAs()) EltTy = PTy->getPointeeType(); + else if (T->isArrayType()) +EltTy = Context.getBaseElementType(T); else EltTy = T->getPointeeType(); diff --git a/clang/test/Sema/types.c b/clang/test/Sema/types.c index e0a6ba4f0691b..4c90634b7ce28 100644 --- a/clang/test/Sema/types.c +++ b/clang/test/Sema/types.c @@ -9,20 +9,20 @@ typedef int (*T)[2]; restrict T x; typedef int *S[2]; -restrict S y; // expected-error {{restrict requires a pointer or reference ('S' (aka 'int *[2]') is invalid)}} - - +restrict S y; // int128_t is available. int a(void) { __int128_t s; __uint128_t t; -} +} // expected-warning {{non-void function does not return a value}} + // but not a keyword int b(void) { int __int128_t; int __uint128_t; -} +} // expected-warning {{non-void function does not return a value}} + // __int128 is a keyword int c(void) { __int128 i; >From 9e8dcdb20a3dd1ea9b49d501c2593d1ac1c7e424 Mon Sep 17 00:00:00 2001 From: Oleksandr T Date: Fri, 31 Jan 2025 23:54:03 +0200 Subject: [PATCH 02/10] add additional tests --- clang/lib/Sema/SemaType.cpp | 2 +- clang/test/Sema/restrict-qualifier.c | 20 2 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 clang/test/Sema/restrict-qualifier.c diff --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp index e84daeee679a5..ab85d6f51d22f 100644 --- a/clang/lib/Sema/SemaType.cpp +++ b/clang/lib/Sema/SemaType.cpp @@ -1602,7 +1602,7 @@ QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc, else if (const MemberPointerType *PTy = T->getAs()) EltTy = PTy->getPointeeType(); else if (T->isArrayType()) -EltTy = Context.getBaseElementType(T); +EltTy = BuildQualifiedType(Context.getBaseElementType(T), Loc, Qs); else EltTy = T->getPointeeType(); diff --git a/clang/test/Sema/restrict-qualifier.c b/clang/test/Sema/restrict-qualifier.c new file mode 100644 index 0..a68e55b47b580 --- /dev/null +++ b/clang/test/Sema/restrict-qualifier.c @@ -0,0 +1,20 @@ +// RUN: %clang_cc1 -std=c2y -fsyntax-only -verify -pedantic %s + +typedef int (*T1)[2]; +restrict T1 t1; +static_assert(_Generic(typeof (t1), int (*restrict)[2] : 1, default : 0)); + +typedef int *T2[2]; +restrict T2 t2; +static_assert(_Generic(typeof (t2), int *restrict[2] : 1, default : 0)); + +typedef int *T3[2][2]; +restrict T3 t3; +static_assert(_Generic(typeof (t3), int *restrict[2][2] : 1, default : 0)); + +typedef int (*t4)(); +typedef t4 t5[2]; +typedef t5 restrict t6; // expected-error {{pointer to function type 'int (void)' may not be 'restrict' qualified}} + +typedef int t7[2]; +typedef t7 restrict t8; // expected-error {{restrict requires a pointer or reference ('int' is invalid)}} >From 7c85906d8a35abfa84ae20f7af952e2a15b6fa0f Mon Sep 17 00:00:00 2001 From: Oleksandr T Date: Sat, 1 Feb 2025 15:00:19 +0200 Subject: [PATCH 03/10] adjust array handling for clearer inner type check --- clang/lib/Sema/SemaType.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp index da63522482390..3dd4952a829e0 100644 --- a/clang/lib/Sema/SemaType.cpp +++ b/clang/lib/Sema/SemaType.cpp @@ -1598,12 +1598,14 @@ QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc, if (T->isAnyPointerType() || T->isReferenceType() ||
[libclc] [libclc] Fix int<->float conversion builtins (PR #126905)
https://github.com/frasercrmck created https://github.com/llvm/llvm-project/pull/126905 While working on moving the conversion builtins to the CLC library in 25c05541 it was discovered that many weren't passing the OpenCL-CTS tests. As it happens, the clspv-specific code for conversion implementations between integer and floating-point types was more correct. However: * The clspv code was generating 'sat' conversions to floating-point types, which are not legal * The clspv code around rtn/rtz conversions needed tweaking as it wasn't validating when sizeof(dst) > sizeof(src), e.g., int -> double. With this commit, the CTS failures seen before have been resolved. This also assumes that the new implementations are correct also for clspv. If this is the case, then 'clc' and 'clspv' modes are mutually exclusive and we can simplify the build process for conversions by not building clc-clspv-convert.cl. Note that there are still outstanding failures in 'rtz' and 'rtp' rounding modes between float->half, double->half, and double->float (i.e., floating-point types when sizeof(src) > sizeof(dst)). These will be looked at separately. >From 5677a1acb9e705d97713a11f8e154fbf511985b5 Mon Sep 17 00:00:00 2001 From: Fraser Cormack Date: Wed, 12 Feb 2025 10:50:54 + Subject: [PATCH] [libclc] Fix int<->float conversion builtins While working on moving the conversion builtins to the CLC library in 25c05541 it was discovered that many weren't passing the OpenCL-CTS tests. As it happens, the clspv-specific code for conversion implementations between integer and floating-point types was more correct. However: * The clspv code was generating 'sat' conversions to floating-point types, which are not legal * The clspv code around rtn/rtz conversions needed tweaking as it wasn't validating when sizeof(dst) > sizeof(src), e.g., int -> double. With this commit, the CTS failures seen before have been resolved. This also assumes that the new implementations are correct also for clspv. If this is the case, then 'clc' and 'clspv' modes are mutually exclusive and we can simplify the build process for conversions by not building clc-clspv-convert.cl. Note that there are still outstanding failures in 'rtz' and 'rtp' rounding modes between float->half, double->half, and double->float (i.e., floating-point types when sizeof(src) > sizeof(dst)). These will be looked at separately. --- libclc/generic/lib/gen_convert.py | 23 +++ 1 file changed, 7 insertions(+), 16 deletions(-) diff --git a/libclc/generic/lib/gen_convert.py b/libclc/generic/lib/gen_convert.py index 92f32694a52af..d2d5b7975275c 100644 --- a/libclc/generic/lib/gen_convert.py +++ b/libclc/generic/lib/gen_convert.py @@ -369,22 +369,13 @@ def generate_saturated_conversion(src, dst, size): elif src in float_types: -if clspv: -# Conversion from float to int -print( -f""" {dstn} y = __clc_convert_{dstn}(x); +# Conversion from float to int +print( +f""" {dstn} y = __clc_convert_{dstn}(x); y = __clc_select(y, ({dstn}){dst_min}, {bool_prefix}(x <= ({srcn}){dst_min}){bool_suffix}); y = __clc_select(y, ({dstn}){dst_max}, {bool_prefix}(x >= ({srcn}){dst_max}){bool_suffix}); return y;""" -) -else: -# Conversion from float to int -print( -f""" {dstn} y = __clc_convert_{dstn}(x); - y = __clc_select(y, ({dstn}){dst_min}, {bool_prefix}(x < ({srcn}){dst_min}){bool_suffix}); - y = __clc_select(y, ({dstn}){dst_max}, {bool_prefix}(x > ({srcn}){dst_max}){bool_suffix}); - return y;""" -) +) else: # Integer to integer convesion with sizeof(src) == sizeof(dst) @@ -494,7 +485,7 @@ def generate_float_conversion(src, dst, size, mode, sat): print(f" return __clc_convert_{dstn}(x);") else: print(f" {dstn} r = __clc_convert_{dstn}(x);") -if clspv: +if src in int_types: print(f" {srcn} y = __clc_convert_{srcn}_sat(r);") else: print(f" {srcn} y = __clc_convert_{srcn}(r);") @@ -507,7 +498,7 @@ def generate_float_conversion(src, dst, size, mode, sat): print(f" {srcn} abs_x = __clc_fabs(x);") print(f" {srcn} abs_y = __clc_fabs(y);") print(f" {booln} c = __clc_convert_{booln}(abs_y > abs_x);") -if clspv and sizeof_type[src] >= 4 and src in int_types: +if sizeof_type[src] >= sizeof_type[dst] and src in int_types: print(f" c = c || __clc_convert_{booln}(({srcn}){src_max} == x);") print( f" {dstn} sel = __clc_select(r, __clc_nextafter(r, __clc_sign(r) * ({dstn})-INFINITY), c);" @@ -533,7 +524,7 @@ def generate_float_conversion(src, dst, size, mode, sat): print(" return sel;") if mode == "_rtn": print(f" {booln} c = __clc_convert_{b
[clang] [Sema] -Wformat: warn about C23 %b %B when not in C23 language mode (PR #126694)
AaronBallman wrote: > > /cc @SharonXSharon > > thanks for submitting the fix! A noob question, I wonder in general why does > clang choose to warn on the invalid formatter instead of erroring out given > it'll be undefined behavior for invalid formatter? Functionally, some kinds of UB are worse than other kinds. For example, if the size and alignment are the same between the format specifier and the data, the UB could be benign, as with: https://godbolt.org/z/dGbzx3PYW so a warning sometimes may be preferable. Other situations are like the one above where C23 adds `%b`, but the code could be compiled in C17 mode but linked against a C23-compatible standard library. That said, it *might* make sense to make some of the diagnostics a warning which default to an error because plenty of forms of UB (especially for things like `sprintf`) can be dangerous. https://github.com/llvm/llvm-project/pull/126694 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[libclc] [libclc] Fix int<->float conversion builtins (PR #126905)
frasercrmck wrote: CC @rjodinchr. I remember you saying you're OOO so no pressure, but perhaps you could verify this commit with clspv? For clarity, the remaining failures I see are, e.g., ``` Error for vector size 1 found at 0x0001: *-0x0p+0 vs 0x0p+0 Input value: -0x1.02p-25 (convert_half_rtp( float )) *** convert_halfn_rtp( floatn ) FAILED ** Building convert_half_rtz( float ) test Testing... .. Error for vector size 1 found at 0x0001: *-0x0p+0 vs 0x0p+0 Input value: -0x1.02p-25 (convert_half_rtz( float )) *** convert_halfn_rtz( floatn ) FAILED ** ``` Looks like a problem with rounding to near zero to me. Does anyone else see this? https://github.com/llvm/llvm-project/pull/126905 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[libclc] [libclc] Stop installing CLC headers (PR #126908)
https://github.com/frasercrmck created https://github.com/llvm/llvm-project/pull/126908 The libclc headers are an implementation detail and are not intended to be used by others as OpenCL headers. The only artifacts of libclc we want to publish are the LLVM bytecode libraries. As the headers have been incidentally broken by recent changes, this commit takes the step to stop installing the headers at all. Downstreams can use clang's own OpenCL headers, and/or its -fdeclare-opencl-builtins flag. Fixes #119967. >From 980cd8632a5aee61919e40c6942c8ab0c772b164 Mon Sep 17 00:00:00 2001 From: Fraser Cormack Date: Wed, 12 Feb 2025 13:21:55 + Subject: [PATCH] [libclc] Stop installing CLC headers The libclc headers are an implementation detail and are not intended to be used by others as OpenCL headers. The only artifacts of libclc we want to publish are the LLVM bytecode libraries. As the headers have been incidentally broken by recent changes, this commit takes the step to stop installing the headers at all. Downstreams can use clang's own OpenCL headers, and/or its -fdeclare-opencl-builtins flag. Fixes #119967. --- libclc/CMakeLists.txt | 1 - libclc/libclc.pc.in | 2 -- 2 files changed, 3 deletions(-) diff --git a/libclc/CMakeLists.txt b/libclc/CMakeLists.txt index c88ea9700d100..9a3087b680cb9 100644 --- a/libclc/CMakeLists.txt +++ b/libclc/CMakeLists.txt @@ -222,7 +222,6 @@ set( tahiti_aliases pitcairn verde oland hainan bonaire kabini kaveri hawaii # pkg-config file configure_file( libclc.pc.in libclc.pc @ONLY ) install( FILES ${CMAKE_CURRENT_BINARY_DIR}/libclc.pc DESTINATION "${CMAKE_INSTALL_DATADIR}/pkgconfig" ) -install( DIRECTORY generic/include/clc DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}" ) if( ENABLE_RUNTIME_SUBNORMAL ) foreach( file IN ITEMS subnormal_use_default subnormal_disable ) diff --git a/libclc/libclc.pc.in b/libclc/libclc.pc.in index b6e06c9673501..3a9e58b3ef0cc 100644 --- a/libclc/libclc.pc.in +++ b/libclc/libclc.pc.in @@ -1,8 +1,6 @@ -includedir=@CMAKE_INSTALL_PREFIX@/@CMAKE_INSTALL_INCLUDEDIR@ libexecdir=@CMAKE_INSTALL_PREFIX@/@CMAKE_INSTALL_DATADIR@/clc Name: libclc Description: Library requirements of the OpenCL C programming language Version: @PROJECT_VERSION@ -Cflags: -I${includedir} Libs: -L${libexecdir} ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [libclang] Always Dup in createRef(StringRef) (PR #125020)
AaronBallman wrote: > The public libclang interface needs to be stable, yes... but in this context, > that's just the interfaces declared in clang/include/clang-c/CXString.h. We > can do whatever we want with the internal interface in > clang/tools/libclang/CXString.h. Oh, good catch! Agreed. :-) https://github.com/llvm/llvm-project/pull/125020 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[libclc] [libclc] Stop installing CLC headers (PR #126908)
frasercrmck wrote: CC @KarolHerbst. https://github.com/llvm/llvm-project/pull/126908 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] a1826b4 - [OpenMP][SIMD][FIX] Use conservative "omp simd ordered" lowering (#126172)
Author: Matt Date: 2025-02-12T08:53:47-05:00 New Revision: a1826b4d2603a2018ca348d430159ec59e0b72bd URL: https://github.com/llvm/llvm-project/commit/a1826b4d2603a2018ca348d430159ec59e0b72bd DIFF: https://github.com/llvm/llvm-project/commit/a1826b4d2603a2018ca348d430159ec59e0b72bd.diff LOG: [OpenMP][SIMD][FIX] Use conservative "omp simd ordered" lowering (#126172) A proposed fix for the issue #95611, [OpenMP][SIMD] ordered has no effect in a loop SIMD region as of LLVM 18.1.0 Changes: - Implement new lowering behavior: Conservatively serialize "omp simd" loops that have `omp simd ordered` directive to prevent incorrect vectorization (which results in incorrect execution behavior of the miscompiled program). Implementation outline: - We start with the optimistic default initial value of `LoopStack.setParallel(/Enable=/true);` in `CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D)`. - We only disable the loop parallel memory access assumption with `if (HasOrderedDirective) LoopStack.setParallel(/Enable=/false);` using the `HasOrderedDirective` (which tests for the presence of an `OMPOrderedDirective`). - This results in no longer incorrectly vectorizing the loop when the `omp simd ordered` directive is present. Motivation: We'd like to prevent incorrect vectorization of the loops marked with the `#pragma omp ordered simd` directive which has previously resulted in miscompiled code. At the same time, we'd like the usage outside of the `#pragma omp ordered simd` context to remain unaffected: Note that in the test "clang/test/OpenMP/ordered_codegen.cpp" we only "lose" the `!llvm.access.group` metadata in `foo_simd` alone. This is conservative, in that it's possible some of the loops would be possible to vectorize, but we prefer to avoid miscompilation of the loops that are currently illegal to vectorize. A concrete example follows: ```cpp // "test.c" #include #include #include #include #include #include int compare_float(float x1, float x2, float scalar) { const float diff = fabsf(x1 - x2); x1 = fabsf(x1); x2 = fabsf(x2); const float l = (x2 > x1) ? x2 : x1; if (diff <= l * scalar * FLT_EPSILON) return 1; else return 0; } #define ARRAY_SIZE 256 __attribute__((noinline)) void initialization_loop( float X[ARRAY_SIZE][ARRAY_SIZE], float Y[ARRAY_SIZE][ARRAY_SIZE]) { const float max = 1000.0; srand(time(NULL)); for (int r = 0; r < ARRAY_SIZE; r++) { for (int c = 0; c < ARRAY_SIZE; c++) { X[r][c] = ((float)rand() / (float)(RAND_MAX)) * max; Y[r][c] = X[r][c]; } } } __attribute__((noinline)) void omp_simd_loop(float X[ARRAY_SIZE][ARRAY_SIZE]) { for (int r = 1; r < ARRAY_SIZE; ++r) { for (int c = 1; c < ARRAY_SIZE; ++c) { #pragma omp simd for (int k = 2; k < ARRAY_SIZE; ++k) { #pragma omp ordered simd X[r][k] = X[r][k - 2] + sinf((float)(r / c)); } } } } __attribute__((noinline)) int comparison_loop(float X[ARRAY_SIZE][ARRAY_SIZE], float Y[ARRAY_SIZE][ARRAY_SIZE]) { int totalErrors_simd = 0; const float scalar = 1.0; for (int r = 1; r < ARRAY_SIZE; ++r) { for (int c = 1; c < ARRAY_SIZE; ++c) { for (int k = 2; k < ARRAY_SIZE; ++k) { Y[r][k] = Y[r][k - 2] + sinf((float)(r / c)); } } // check row for simd update for (int k = 0; k < ARRAY_SIZE; ++k) { if (!compare_float(X[r][k], Y[r][k], scalar)) { ++totalErrors_simd; } } } return totalErrors_simd; } int main(void) { float X[ARRAY_SIZE][ARRAY_SIZE]; float Y[ARRAY_SIZE][ARRAY_SIZE]; initialization_loop(X, Y); omp_simd_loop(X); const int totalErrors_simd = comparison_loop(X, Y); if (totalErrors_simd) { fprintf(stdout, "totalErrors_simd: %d \n", totalErrors_simd); fprintf(stdout, "%s : %d - FAIL: error in ordered simd computation.\n", __FILE__, __LINE__); } else { fprintf(stdout, "Success!\n"); } return totalErrors_simd; } ``` Before: ``` $ clang -fopenmp-simd -O3 -ffast-math -lm test.c -o test && ./test totalErrors_simd: 15408 test.c : 76 - FAIL: error in ordered simd computation. ``` clang 19.1.0: https://godbolt.org/z/6EvhxqEhe After: ``` $ clang -fopenmp-simd -O3 -ffast-math test.c -o test && ./test Success! ``` Co-authored-by: Matt P. Dziubinski Added: openmp/runtime/test/misc_bugs/simd_conservative_ordered.c Modified: clang/lib/CodeGen/CGStmtOpenMP.cpp clang/test/OpenMP/ordered_codegen.cpp Removed: diff --git a/clang/lib/CodeGen/CGStmtOpenMP.cpp b/clang/lib/CodeGen/CGStmtOpenMP.cpp index 8e694b95dc7e7..3542e939678cf 100644 --- a/clang/lib/CodeGen/CGStmtOpenMP.cpp +++ b/clang/lib/CodeGen/CGStmtOpenMP.cp
[clang] [Clang] Add __has_target_builtin macro (PR #126324)
@@ -96,6 +100,47 @@ the header file to conditionally make a function constexpr whenever the constant evaluation of the corresponding builtin (for example, ``std::fmax`` calls ``__builtin_fmax``) is supported in Clang. +``__has_target_builtin`` + + +This function-like macro takes a single identifier argument that is the name of +a builtin function, a builtin pseudo-function (taking one or more type +arguments), or a builtin template. +It evaluates to 1 if the builtin is supported on the current target or 0 if not. + +``__has_builtin`` and ``__has_target_builtin`` behave identically for normal C++ compilations. AaronBallman wrote: > if the user's goal is to check that the builtin can be codegen'd on the > current target being compiled, then yes they should use __has_target_builtin. > if they want to confirm it can be parsed but not necessarily codegen'd, then > they should use __has_builtin. if that's unclear let me know and i can try to > improve the doc Users don't typically think in terms of "parsed" and "codegenned", but more "works" and "doesn't work", which I think means "codegenned" in general. The line we're drawing here is pretty subtle, so perhaps more real world examples would help; it's hard to understand why a builtin can be parsed but cannot be used. https://github.com/llvm/llvm-project/pull/126324 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [HLSL] Change clang Driver Options to not set CXXOperatorNames (PR #126758)
llvm-ci wrote: LLVM Buildbot has detected a new failure on builder `flang-aarch64-out-of-tree` running on `linaro-flang-aarch64-out-of-tree` while building `clang` at step 7 "build-flang-unified-tree". Full details are available at: https://lab.llvm.org/buildbot/#/builders/53/builds/12221 Here is the relevant piece of the build log for the reference ``` Step 7 (build-flang-unified-tree) failure: build (failure) ... 1034.131 [26/35/15] Linking CXX executable unittests/Evaluate/logical.test 1034.204 [26/34/16] Linking CXX executable unittests/Evaluate/real.test 1034.456 [26/33/17] Linking CXX executable unittests/Evaluate/expression.test 1038.603 [26/32/18] Linking CXX executable unittests/Evaluate/intrinsics.test 1038.640 [26/31/19] Linking CXX executable unittests/Evaluate/folding.test 1057.584 [26/30/20] Building CXX object lib/Optimizer/Transforms/CMakeFiles/FIRTransforms.dir/SimplifyRegionLite.cpp.o 1059.523 [26/29/21] Building CXX object lib/Optimizer/Transforms/CMakeFiles/FIRTransforms.dir/ExternalNameConversion.cpp.o 1059.548 [26/28/22] Building CXX object lib/Optimizer/Transforms/CMakeFiles/FIRTransforms.dir/StackReclaim.cpp.o 1059.938 [26/27/23] Building CXX object lib/Optimizer/Transforms/CMakeFiles/FIRTransforms.dir/MemRefDataFlowOpt.cpp.o 1060.246 [26/26/24] Building CXX object lib/Optimizer/Passes/CMakeFiles/flangPasses.dir/Pipelines.cpp.o FAILED: lib/Optimizer/Passes/CMakeFiles/flangPasses.dir/Pipelines.cpp.o /usr/local/bin/c++ -DFLANG_INCLUDE_TESTS=1 -DFLANG_LITTLE_ENDIAN=1 -DGTEST_HAS_RTTI=0 -D_DEBUG -D_GLIBCXX_ASSERTIONS -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS -I/home/tcwg-buildbot/worker/flang-aarch64-out-of-tree/build_flang/lib/Optimizer/Passes -I/home/tcwg-buildbot/worker/flang-aarch64-out-of-tree/llvm-project/flang/lib/Optimizer/Passes -I/home/tcwg-buildbot/worker/flang-aarch64-out-of-tree/llvm-project/flang/include -I/home/tcwg-buildbot/worker/flang-aarch64-out-of-tree/build_flang/include -isystem /home/tcwg-buildbot/worker/flang-aarch64-out-of-tree/llvm-project/mlir/include -isystem /home/tcwg-buildbot/worker/flang-aarch64-out-of-tree/build_llvm/tools/mlir/include -isystem /home/tcwg-buildbot/worker/flang-aarch64-out-of-tree/llvm-project/llvm/include -isystem /home/tcwg-buildbot/worker/flang-aarch64-out-of-tree/build_llvm/include -isystem /home/tcwg-buildbot/worker/flang-aarch64-out-of-tree/llvm-project/clang/include -isystem /home/tcwg-buildbot/worker/flang-aarch64-out-of-tree/build_llvm/tools/clang/include -fPIC -fno-semantic-interposition -fvisibility-inlines-hidden -Werror=date-time -Werror=unguarded-availability-new -Wall -Wextra -Wno-unused-parameter -Wwrite-strings -Wcast-qual -Wmissing-field-initializers -pedantic -Wno-long-long -Wc++98-compat-extra-semi -Wimplicit-fallthrough -Wcovered-switch-default -Wno-noexcept-type -Wnon-virtual-dtor -Wdelete-non-virtual-dtor -Wsuggest-override -Wstring-conversion -Wmisleading-indentation -Wctad-maybe-unsupported -fdiagnostics-color -ffunction-sections -fdata-sections -Werror -Wno-deprecated-copy -Wno-string-conversion -Wno-ctad-maybe-unsupported -Wno-unused-command-line-argument -Wstring-conversion -Wcovered-switch-default -Wno-nested-anon-types -O3 -DNDEBUG -std=c++17 -D_GNU_SOURCE -D_DEBUG -D_GLIBCXX_ASSERTIONS -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS -fno-exceptions -funwind-tables -fno-rtti -UNDEBUG -MD -MT lib/Optimizer/Passes/CMakeFiles/flangPasses.dir/Pipelines.cpp.o -MF lib/Optimizer/Passes/CMakeFiles/flangPasses.dir/Pipelines.cpp.o.d -o lib/Optimizer/Passes/CMakeFiles/flangPasses.dir/Pipelines.cpp.o -c /home/tcwg-buildbot/worker/flang-aarch64-out-of-tree/llvm-project/flang/lib/Optimizer/Passes/Pipelines.cpp ../llvm-project/flang/lib/Optimizer/Passes/Pipelines.cpp:329:27: error: missing field 'tuneCPU' initializer [-Werror,-Wmissing-field-initializers] 329 |config.UnsafeFPMath})); | ^ 1 error generated. 1060.503 [26/25/25] Building CXX object lib/Optimizer/Transforms/CMakeFiles/FIRTransforms.dir/CharacterConversion.cpp.o 1060.515 [26/24/26] Building CXX object lib/Optimizer/Transforms/CMakeFiles/FIRTransforms.dir/VScaleAttr.cpp.o 1061.107 [26/23/27] Building CXX object lib/Optimizer/Transforms/CMakeFiles/FIRTransforms.dir/CompilerGeneratedNames.cpp.o 1061.215 [26/22/28] Building CXX object lib/Optimizer/Transforms/CMakeFiles/FIRTransforms.dir/FunctionAttr.cpp.o 1062.154 [26/21/29] Building CXX object lib/Optimizer/Transforms/CMakeFiles/FIRTransforms.dir/AlgebraicSimplification.cpp.o 1062.971 [26/20/30] Building CXX object lib/Optimizer/Transforms/CMakeFiles/FIRTransforms.dir/LoopVersioning.cpp.o 1064.891 [26/19/31] Building CXX object lib/Optimizer/Transforms/CMakeFiles/FIRTransforms.dir/AnnotateConstant.cpp.o 1065.574 [26/18/32] Building CXX object lib/Optimizer/Transforms/CMakeFiles/FIRTransforms.dir/ControlFlowConverter.cpp.o 1065.603 [26/17/33] Building
[clang] [llvm] [OpenMP][OpenMPIRBuilder] Support SPIR-V device variant matches (PR #126801)
https://github.com/sarnex edited https://github.com/llvm/llvm-project/pull/126801 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [OpenMP][OpenMPIRBuilder] Support SPIR-V device variant matches (PR #126801)
https://github.com/sarnex edited https://github.com/llvm/llvm-project/pull/126801 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [OpenMP][OpenMPIRBuilder] Support SPIR-V device variant matches (PR #126801)
llvmbot wrote: @llvm/pr-subscribers-clang-codegen Author: Nick Sarnie (sarnex) Changes We should be able to use `spirv64` as a device variant match and it should be considered a GPU. Also add the triple to an RTTI check. --- Full diff: https://github.com/llvm/llvm-project/pull/126801.diff 4 Files Affected: - (modified) clang/lib/CodeGen/CodeGenModule.h (+2-1) - (added) clang/test/OpenMP/spirv_variant_match.cpp (+46) - (modified) llvm/include/llvm/Frontend/OpenMP/OMPKinds.def (+2) - (modified) llvm/lib/Frontend/OpenMP/OMPContext.cpp (+2) ``diff diff --git a/clang/lib/CodeGen/CodeGenModule.h b/clang/lib/CodeGen/CodeGenModule.h index 0956296e2d5d8..c6f6fd5b9a7bd 100644 --- a/clang/lib/CodeGen/CodeGenModule.h +++ b/clang/lib/CodeGen/CodeGenModule.h @@ -1067,7 +1067,8 @@ class CodeGenModule : public CodeGenTypeCache { bool shouldEmitRTTI(bool ForEH = false) { return (ForEH || getLangOpts().RTTI) && !getLangOpts().CUDAIsDevice && !(getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice && - (getTriple().isNVPTX() || getTriple().isAMDGPU())); + (getTriple().isNVPTX() || getTriple().isAMDGPU() || + getTriple().isSPIRV())); } /// Get the address of the RTTI descriptor for the given type. diff --git a/clang/test/OpenMP/spirv_variant_match.cpp b/clang/test/OpenMP/spirv_variant_match.cpp new file mode 100644 index 0..b37858bc3008b --- /dev/null +++ b/clang/test/OpenMP/spirv_variant_match.cpp @@ -0,0 +1,46 @@ +// RUN: %clang_cc1 -verify -fopenmp -x c++ -triple x86_64-unknown-unknown -fopenmp-targets=spirv64-intel -emit-llvm-bc %s -o %t-host.bc -DDEVICE +// RUN: %clang_cc1 -verify -triple spirv64-intel -aux-triple x86_64-unknown-unknown -fopenmp -fopenmp-is-target-device \ +// RUN:-fopenmp-host-ir-file-path %t-host.bc -nogpulib %s -emit-llvm -DDEVICE -o - | FileCheck %s + +// RUN: %clang_cc1 -verify -fopenmp -x c++ -triple x86_64-unknown-unknown -fopenmp-targets=spirv64-intel -emit-llvm-bc %s -o %t-host.bc -DTARGET +// RUN: %clang_cc1 -verify -triple spirv64-intel -aux-triple x86_64-unknown-unknown -fopenmp -fopenmp-is-target-device \ +// RUN: -fopenmp-host-ir-file-path %t-host.bc -nogpulib %s -emit-llvm -DTARGET -o - | FileCheck %s + +// RUN: %clang_cc1 -verify -fopenmp -x c++ -triple x86_64-unknown-unknown -fopenmp-targets=spirv64-intel -emit-llvm-bc %s -o %t-host.bc -DTARGET_KIND +// RUN: %clang_cc1 -verify -triple spirv64-intel -aux-triple x86_64-unknown-unknown -fopenmp -fopenmp-is-target-device \ +// RUN: -fopenmp-host-ir-file-path %t-host.bc -nogpulib %s -emit-llvm -DTARGET_KIND -o - | FileCheck %s + +// RUN: %clang_cc1 -verify -fopenmp -x c++ -triple x86_64-unknown-unknown -fopenmp-targets=spirv64-intel -emit-llvm-bc %s -o %t-host.bc +// RUN: %clang_cc1 -verify -triple spirv64-intel -aux-triple x86_64-unknown-unknown -fopenmp -fopenmp-is-target-device \ +// RUN: -fopenmp-host-ir-file-path %t-host.bc -nogpulib %s -emit-llvm -o - | FileCheck %s + +// expected-no-diagnostics + +#pragma omp declare target +int foo() { return 0; } + +#ifdef DEVICE +#pragma omp begin declare variant match(device = {arch(spirv64)}) +#elif defined(TARGET) +#pragma omp begin declare variant match(target_device = {arch(spirv64)}) +#elif defined(TARGET_KIND) +#pragma omp begin declare variant match(target_device = {kind(gpu)}) +#else +#pragma omp begin declare variant match(device = {kind(gpu)}) +#endif + +int foo() { return 1; } +#pragma omp end declare variant +#pragma omp end declare target + +// CHECK-DAG: define{{.*}} @{{"_Z[0-9]+foo\$ompvariant\$.*"}}() + +// CHECK-DAG: call spir_func noundef i32 @{{"_Z[0-9]+foo\$ompvariant\$.*"}}() + +int main() { + int res; +#pragma omp target map(from \ + : res) + res = foo(); + return res; +} diff --git a/llvm/include/llvm/Frontend/OpenMP/OMPKinds.def b/llvm/include/llvm/Frontend/OpenMP/OMPKinds.def index 44a9a37c70597..f974cfc78c8dd 100644 --- a/llvm/include/llvm/Frontend/OpenMP/OMPKinds.def +++ b/llvm/include/llvm/Frontend/OpenMP/OMPKinds.def @@ -1269,6 +1269,7 @@ __OMP_TRAIT_PROPERTY(device, arch, x86_64) __OMP_TRAIT_PROPERTY(device, arch, amdgcn) __OMP_TRAIT_PROPERTY(device, arch, nvptx) __OMP_TRAIT_PROPERTY(device, arch, nvptx64) +__OMP_TRAIT_PROPERTY(device, arch, spirv64) __OMP_TRAIT_SET(target_device) @@ -1301,6 +1302,7 @@ __OMP_TRAIT_PROPERTY(target_device, arch, x86_64) __OMP_TRAIT_PROPERTY(target_device, arch, amdgcn) __OMP_TRAIT_PROPERTY(target_device, arch, nvptx) __OMP_TRAIT_PROPERTY(target_device, arch, nvptx64) +__OMP_TRAIT_PROPERTY(target_device, arch, spirv64) __OMP_TRAIT_SET(implementation) diff --git a/llvm/lib/Frontend/OpenMP/OMPContext.cpp b/llvm/lib/Frontend/OpenMP/OMPContext.cpp index 5e13da172d677..2edfd786c5c23 100644 --- a/llvm/lib/Frontend/OpenMP/OMPContext.cpp +++ b/llvm/lib/Frontend/OpenMP/OMPContext.cpp @@ -52,6 +52,7 @@ OMPContext::OMPContext(bool IsDeviceCompilation, Triple TargetTriple, case T
[clang] [Driver][ROCm][ASan] Skip checking ':xnack+' feature for gfx12. (PR #126885)
@@ -1112,6 +1112,11 @@ bool AMDGPUToolChain::shouldSkipSanitizeOption( assert(OptionalGpuArch && "Invalid Target ID"); (void)OptionalGpuArch; + + // Skip checking 'xnack+' feature availability for gfx12 family. jhuber6 wrote: The fact that target-id's push target features into the `mcpu` value always made this kind of thing messy. Why do we even need this if `xnack` isn't used on gfx12? Isn't it always on or something. https://github.com/llvm/llvm-project/pull/126885 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][Sema] Add diagnostic note for reference of function-like macros requiring without parentheses (PR #123495)
StarOne01 wrote: Done! (Sorry for force pushes 😅, git suddenly decided to act weird). https://github.com/llvm/llvm-project/pull/123495 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clangd] [C++20] [Modules] Add scanning cache (PR #125988)
kadircet wrote: > * Now the ScanningProjectModules are owned by different calls to > `ModulesBuilder::buildPrerequisiteModulesFor`. So we don't need to care about > thread safety in ScanningProjectModules. And if we make it the underlying > ProjectModules, we need to care about the thead safety and then we would have > a centralized scanner. It is not bad but it might be a bigger change. Not sure I understand the argument here. Please note that I am not suggesting to store a `ScanningProjectModules` (or any other `ProjectModules`) inside `CachingProjectModules`. We can't even if we wanted to, in theory any source file can belong to a different `ProjectModules`. Hence we store the `GlobalCompilationDatabase`, so that we can access a relevant `ProjectModules` when the cache is invalid or we don't have an entry. Hence we're not sharing any `ScanningProjectModules` instances across threads. As for thread-safety concerns in `CachingProjectModules` itself, I think we have the exact same requirements as this patch (https://github.com/llvm/llvm-project/pull/125988/files#diff-bfbef59d036ce319b5ed9b774f6ddb8dcd7efdba3384de03cb9a37f23ef678ba), basically underlying cache can be accessed concurrently, but rest should be outside the critical path. Does that make sense? If not could you elaborate on your concern? https://github.com/llvm/llvm-project/pull/125988 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [C++20] [Modules] Instantiate pending instantiations when GMF ends (PR #126842)
@@ -1104,9 +1104,13 @@ void Sema::ActOnStartOfTranslationUnit() { } void Sema::ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind) { - // No explicit actions are required at the end of the global module fragment. - if (Kind == TUFragmentKind::Global) + if (Kind == TUFragmentKind::Global) { +// Perform Pending Instantiations at the end of global module fragment so +// that the module ownership of TU-level decls won't get messed. +llvm::TimeTraceScope TimeScope("PerformPendingInstantiations"); +PerformPendingInstantiations(); mizvekov wrote: I find problematic the existing model of template instantiation module ownership. Surely a template may need a certain instantiation for multiple uses, possibly in different modules. If a template has been instantiated, we don't need to instantiate it again. It looks accidental that these declarations end up being owned by the module which first instantiated it. The instantiations should either have no ownership, perhaps homed to the owner of the pattern, or maybe be multiply owned. https://github.com/llvm/llvm-project/pull/126842 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] handle fp options in __builtin_convertvector (PR #125522)
ficol wrote: Hi @shafik, can you please review this PR after changes? https://github.com/llvm/llvm-project/pull/125522 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [NFC][analyzer] OOB test consolidation II: constraint checking (PR #126748)
=?utf-8?q?Don=C3=A1t?= Nagy , =?utf-8?q?Don=C3=A1t?= Nagy , =?utf-8?q?Don=C3=A1t?= Nagy Message-ID: In-Reply-To: https://github.com/steakhal approved this pull request. https://github.com/llvm/llvm-project/pull/126748 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [Clang][OpenMP] Support for dispatch construct (Sema & Codegen) support (PR #117904)
jtb20 wrote: The failures with this patch and not mine are just: PASS->FAIL: tests/5.1/dispatch/test_dispatch_is_device_ptr.c run PASS->FAIL: tests/5.1/dispatch/test_dispatch_nowait.c run that's actually probably neither here nor there, the clauses in question aren't implemented in my patch yet so the tests are likely succeeding "by accident". https://github.com/llvm/llvm-project/pull/117904 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 767b15f - [HLSL] Change clang Driver Options to not set CXXOperatorNames (#126758)
Author: Farzon Lotfi Date: 2025-02-12T09:21:39-05:00 New Revision: 767b15f9d57cf31fd6ba2aed8c17a8c30d5b5e6e URL: https://github.com/llvm/llvm-project/commit/767b15f9d57cf31fd6ba2aed8c17a8c30d5b5e6e DIFF: https://github.com/llvm/llvm-project/commit/767b15f9d57cf31fd6ba2aed8c17a8c30d5b5e6e.diff LOG: [HLSL] Change clang Driver Options to not set CXXOperatorNames (#126758) - Disable `CXXOperatorNames` for HLSL - Add tests to confirm we can use the alt names as functions Added: clang/test/SemaHLSL/use-cxx-alt-operator-names.hlsl Modified: clang/include/clang/Driver/Options.td Removed: diff --git a/clang/include/clang/Driver/Options.td b/clang/include/clang/Driver/Options.td index 1cf62ab466134..618815db28434 100644 --- a/clang/include/clang/Driver/Options.td +++ b/clang/include/clang/Driver/Options.td @@ -3397,7 +3397,7 @@ def fno_objc_weak : Flag<["-"], "fno-objc-weak">, Group, def fno_omit_frame_pointer : Flag<["-"], "fno-omit-frame-pointer">, Group, Visibility<[ClangOption, FlangOption]>; defm operator_names : BoolFOption<"operator-names", - LangOpts<"CXXOperatorNames">, Default, + LangOpts<"CXXOperatorNames">, Default, NegFlag, PosFlag>; diff --git a/clang/test/SemaHLSL/use-cxx-alt-operator-names.hlsl b/clang/test/SemaHLSL/use-cxx-alt-operator-names.hlsl new file mode 100644 index 0..e93be2bbf4e69 --- /dev/null +++ b/clang/test/SemaHLSL/use-cxx-alt-operator-names.hlsl @@ -0,0 +1,34 @@ +// RUN: %clang_cc1 -triple dxil-pc-shadermodel6.3-library %s -ast-dump | FileCheck %s + +// CHECK: -FunctionDecl {{.*}} and 'void ()' +void and() {} + +// CHECK: -FunctionDecl {{.*}} and_eq 'void ()' +void and_eq() {} + +// CHECK: -FunctionDecl {{.*}} bitand 'void ()' +void bitand() {} + +// CHECK: -FunctionDecl {{.*}} bitor 'void ()' +void bitor() {} + +// CHECK: -FunctionDecl {{.*}} compl 'void ()' +void compl() {} + +// CHECK: -FunctionDecl {{.*}} not 'void ()' +void not() {} + +// CHECK: -FunctionDecl {{.*}} not_eq 'void ()' +void not_eq() {} + +// CHECK: -FunctionDecl {{.*}} or 'void ()' +void or() {} + +// CHECK: -FunctionDecl {{.*}} or_eq 'void ()' +void or_eq() {} + +// CHECK: -FunctionDecl {{.*}} xor 'void ()' +void xor() {} + +// CHECK: -FunctionDecl {{.*}} xor_eq 'void ()' +void xor_eq() {} ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [HLSL] Change clang Driver Options to not set CXXOperatorNames (PR #126758)
https://github.com/farzonl closed https://github.com/llvm/llvm-project/pull/126758 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [DebugInfo] Update DIBuilder insertion to take InsertPosition (PR #126059)
https://github.com/OCHyams commented: > @OCHyams I believe you did the C API changes, are there any additional > concerns in this area? SGTM, just one inline question https://github.com/llvm/llvm-project/pull/126059 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [DebugInfo] Update DIBuilder insertion to take InsertPosition (PR #126059)
https://github.com/OCHyams edited https://github.com/llvm/llvm-project/pull/126059 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [Coverage][MC/DC] Show uncoverable and unreachable conditions (PR #94137)
https://github.com/Lambdaris updated https://github.com/llvm/llvm-project/pull/94137 >From 17075214ce351cc39db7e2da8d0bfcb196861c7b Mon Sep 17 00:00:00 2001 From: Lambdaris Date: Thu, 22 Aug 2024 21:31:03 +0800 Subject: [PATCH 1/3] [coverage] Count false counters when calculating max counter id --- clang/lib/CodeGen/CoverageMappingGen.cpp | 4 ++-- llvm/lib/ProfileData/Coverage/CoverageMapping.cpp | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/clang/lib/CodeGen/CoverageMappingGen.cpp b/clang/lib/CodeGen/CoverageMappingGen.cpp index f09157771d2b5..298be8141af89 100644 --- a/clang/lib/CodeGen/CoverageMappingGen.cpp +++ b/clang/lib/CodeGen/CoverageMappingGen.cpp @@ -1159,8 +1159,8 @@ struct CounterCoverageMappingBuilder BranchParams = mcdc::BranchParameters{ID, Conds}; // If a condition can fold to true or false, the corresponding branch - // will be removed. Create a region with both counters hard-coded to - // zero. This allows us to visualize them in a special way. + // will be removed. Create a region with the relative counter hard-coded + // to zero. This allows us to visualize them in a special way. // Alternatively, we can prevent any optimization done via // constant-folding by ensuring that ConstantFoldsToSimpleInteger() in // CodeGenFunction.c always returns false, but that is very heavy-handed. diff --git a/llvm/lib/ProfileData/Coverage/CoverageMapping.cpp b/llvm/lib/ProfileData/Coverage/CoverageMapping.cpp index c39585681911a..871c866d2f4d8 100644 --- a/llvm/lib/ProfileData/Coverage/CoverageMapping.cpp +++ b/llvm/lib/ProfileData/Coverage/CoverageMapping.cpp @@ -637,6 +637,8 @@ static unsigned getMaxCounterID(const CounterMappingContext &Ctx, unsigned MaxCounterID = 0; for (const auto &Region : Record.MappingRegions) { MaxCounterID = std::max(MaxCounterID, Ctx.getMaxCounterID(Region.Count)); +MaxCounterID = +std::max(MaxCounterID, Ctx.getMaxCounterID(Region.FalseCount)); } return MaxCounterID; } >From bd648350ec51d65e25b4f876bdd438a05b47f778 Mon Sep 17 00:00:00 2001 From: Lambdaris Date: Sat, 13 Jul 2024 10:45:29 +0800 Subject: [PATCH 2/3] [coverage] MC/DC reports unrechable and uncoverable conditions --- clang/docs/SourceBasedCodeCoverage.rst| 11 ++ .../ProfileData/Coverage/CoverageMapping.h| 65 ++--- .../ProfileData/Coverage/CoverageMapping.cpp | 133 +++--- .../llvm-cov/Inputs/mcdc-const-folding.o | Bin 34528 -> 34616 bytes llvm/test/tools/llvm-cov/Inputs/mcdc-const.o | Bin 5208 -> 5296 bytes llvm/test/tools/llvm-cov/Inputs/mcdc-macro.o | Bin 6408 -> 6488 bytes llvm/test/tools/llvm-cov/mcdc-const.test | 48 +++ llvm/test/tools/llvm-cov/mcdc-macro.test | 6 +- llvm/tools/llvm-cov/CoverageReport.cpp| 4 +- llvm/tools/llvm-cov/CoverageSummaryInfo.cpp | 2 +- .../tools/llvm-cov/SourceCoverageViewHTML.cpp | 7 +- .../tools/llvm-cov/SourceCoverageViewText.cpp | 14 +- 12 files changed, 218 insertions(+), 72 deletions(-) diff --git a/clang/docs/SourceBasedCodeCoverage.rst b/clang/docs/SourceBasedCodeCoverage.rst index 3e8642479a56d..1655535c97e39 100644 --- a/clang/docs/SourceBasedCodeCoverage.rst +++ b/clang/docs/SourceBasedCodeCoverage.rst @@ -522,6 +522,17 @@ starts a new boolean expression that is separated from the other conditions by the operator ``func()``. When this is encountered, a warning will be generated and the boolean expression will not be instrumented. +Besides, MC/DC may report conditions with three states: ``uncoverable``, ``constant`` and ``unreachable``. +``uncoverable`` means the condition could be evaluated but it cannot affect outcome of the decision. +``constant`` means the condition is always evaluated to the same value. +While ``unreachable`` means the condition is never evaluated. +For instance, in ``a || true || b``, value of the decision is always ``true``. +``a`` can not make the decision be ``false`` as it varies. And the second condition, ``true`` can not be evaluated to ``false``. +While ``b`` is always short-circuited. Hence ``a`` is ``uncoverable``, ``true`` is ``constant`` and ``b`` is ``unreachable``. +By default statistics of MCDC counts uncoverable and unreachable conditions but excludes constants. Users can pass option +``--mcdc-exclude`` to control this behavior. +If a decision is proved to no branch theoretically, it shows ``Folded`` rather than coverage percent. + Switch statements - diff --git a/llvm/include/llvm/ProfileData/Coverage/CoverageMapping.h b/llvm/include/llvm/ProfileData/Coverage/CoverageMapping.h index 4fc0133443192..f5f83b8e219fa 100644 --- a/llvm/include/llvm/ProfileData/Coverage/CoverageMapping.h +++ b/llvm/include/llvm/ProfileData/Coverage/CoverageMapping.h @@ -396,6 +396,13 @@ struct MCDCRecord { /// are effectively ignored. enum CondState { MCDC_DontCare = -1, MCDC_False = 0, MCDC_Tru
[clang] [llvm] [mlir] [NVPTX] Convert scalar function nvvm.annotations to attributes (PR #125908)
@@ -227,14 +228,14 @@ class NVVMDialectLLVMIRTranslationInterface } else if (attribute.getName() == grypp wrote: Sure sounds great https://github.com/llvm/llvm-project/pull/125908 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [Coverage][MC/DC] Show uncoverable and unreachable conditions (PR #94137)
Lambdaris wrote: > What's the current status? I think it's done and ready for review. > I think marking extended semantics (to Regions) will still be the issue. > Could we enhance "Gap"? Could you clarify the issue and how we enhance "gap" a bit more? Now the major work of this patch is in `MCDCRecordProcessor::processMCDCRecord`, marking some mcdc branch regions as we expected. https://github.com/llvm/llvm-project/pull/94137 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits