Subsystems (5)
From ddb88c610711c6494c57b2a9df205b2acf9b3cbc Mon Sep 17 00:00:00 2001
From: Bart Van Assche <[email protected]>
Date: Mon, 9 Nov 2026 12:27:28 -0800
Subject: [PATCH 00/73] Support more C23 features
Hi,
If nobody objects I will publish this patch series two weeks from now to the master branch at kernel.org.
The changes fall into five major functional themes:
1. C23 Standard & Preprocessor Support (~25 commits)
Major upgrade adding comprehensive ISO C23 and GNU C23 standard features:
* Preprocessor directives & macros:
- Add #elifdef and #elifndef.
- Add __has_include and __has_include_next.
- Add #embed directive and __has_embed.
- Add __has_c_attribute.
- Add __VA_OPT__ for variadic macro expansion.
* C23 Language Features:
- Keywords & Constants: bool, true, false, nullptr / nullptr_t, static_assert, alignas, alignof, thread_local, typeof_unqual, and u8 character constants / string literals.
- Types & Syntax:
* Support _BitInt(N).
* Support standard [[]] attribute syntax.
* Support fixed-underlying-type enumerations (enum foo : int).
* Support constexpr object specifiers and auto type inference.
* Support digit separators in numeric literals (e.g. 1'000'000).
* Support empty initializer braces ({}).
* Support storage-class specifiers in compound literals.
- Functions & Statements:
* Support labels before declarations and at block ends.
* Support unnamed parameters in function definitions.
* Support variadic functions without named parameters (void f(...)).
* Treat empty parameter list () as (void) and reject K&R functions.
* Options:
- Add -std=c23, -std=c2x, and -std=gnu23.
2. Linux Kernel Compatibility, Builtins & Attributes (~10 commits) Enable Sparse to parse modern Linux kernel code and headers cleanly:
* Support __attribute__((cleanup(...))):
- Integrate with linearize and -Wcontext to track lock/unlock semantics with scope-based resource management (RAII / guard() / scoped_guard()).
* Builtin Functions:
- Add __builtin_has_attribute().
- Add __builtin_infer_alloc_token() as a size_t integer constant.
- Add kernel builtins (__builtin_object_size, __builtin_counted_by_ref,
__builtin_get_counted_by).
- Suppress evaluation of __builtin_clz(0) and __builtin_ctz(0).
* Attributes & Types:
- Support __attribute__((packed)) and machine mode attributes on enums.
- Accept conditional expressions with only one void side.
- Ignore top-level non-array address space in compare_types().
- Support long token and string expansions dynamically.
- Undefine conflicting bitness macros when parsing -m flags on x86.
3. Bitwise Types & Conditional Context (Linus Torvalds Series, ~7 commits) Incorporate and harden Linus Torvalds's patch series:
* Context tracking:
- Add conditional context increment model (context(0, -1)) for trylock functions, with multi-attribute call handling and check_context() definition validation.
* Bitwise Types (SYM_RESTRICT):
- Simplify signed constants early (-5, +5, ~0) during type evaluation.
- Allow all-bits-set (~0, -1) as valid bitwise constants alongside 0.
- Allow ordered comparisons (<, <=, >, >=) between unsigned restricted types and unrestricted constants (0, ~0).
- Keep unrestricted constants unrestricted across regular and __force casts.
- Preserve MOD_SPECIFIER on bitwise types to retain MOD_UNSIGNED on bitwise typedefs.
4. Hardening, Memory Safety & Bug Fixes (~30 commits) Eliminate crashes, undefined behavior, and potential overflows:
* Allocators & Tokenizer:
- Harden slab allocation bounds, zeroing checks, and mmap fallbacks.
- Support 4096-byte identifiers and fix string escape bounds.
* Parser & AST:
- Guard against recursive symbols in c2xml.
- Harden warning and format string buffers in lib.c.
- Fix attribute propagation, enum overflow, and AST column counting.
* Evaluation, Inlining & Optimization:
- Fix pointer arithmetic, incomplete types, and qualifiers in evaluate.c.
- Fix generic expression duplication in inline.c and VLA bound copying.
- Guard against LLONG_MIN overflow on negation in simplify.c.
- Fix instruction traversal order in memops.c and skip mixed-size SSA.
- Fix dead store elimination (DSE) and asm operands in linearize/flow.
- Cast pointers to uintptr_t before relational comparisons in cse.c.
* Backends & Tools:
- Use LLVMCreateBuilderForModule() for LLVM 24+.
- Support arbitrary struct member counts and operand types in sparse-llvm.
- Fix buffer bounds and unsigned comparisons in compile-i386.c.
- Fix ctags, dissect, graph, and scheck helper utilities.
5. Tooling & CI Automation (2 commits)
* Add a comprehensive .clang-format configuration file.
* Add GitHub Actions workflow and test script to build the Linux kernel with Sparse.
Thanks,
Bart.
Bart Van Assche (66):
Makefile: Pass '--' to rm in clean target to handle dash-prefixed
files
sparse-llvm: Use LLVMCreateBuilderForModule() with LLVM 24 and later
typeof_unqual: Strip qualifiers and address space from types and
arrays
bitfield: Pack consecutive _Bool bitfields into byte containers
allocate: Harden slab allocation bounds, zeroing, and mmap checks
tokenize: Support 4096-byte identifiers and fix escape bounds
pre-process: Fix macro expansion and include directive handling options, lib: Harden warning buffers and command-line option parsing
builtin: Fix atomic builtin type checking and object_size bounds parse, show-parse: Fix attribute propagation, enum overflow, and
bounds
target-openrisc: Set target_openrisc.mach to MACH_OPENRISC
evaluate: Fix pointer arithmetic, incomplete types, and qualifiers
expand: Fix static initializer folding and floating-point casts
inline: Copy union cast types and VLA bounds when inlining linearize, flow: Fix asm operands, switch case bounds, and DSE memops, ssa: Walk parent insns in reverse and skip mixed-size SSA
simplify: Prevent overflow on LLONG_MIN negation and fix
simplifications
sparse: Gate context failure warning on Wcontext and catch underflow
ast-model: Return AST_N_COLUMNS and inspect child nodes lazily
c2xml: Guard against recursive symbols and free xmlGetProp() string
compile-i386: Fix buffer bounds, unsigned '<=' codegen, and null
checks
ctags: Fix line comparison order and handle SYM_RESTRICT and SYM_LABEL
dissect: Unwrap array element type via base_type()
example: Fix show_op() rotating buffer dimensions
graph: Check PSEUDO_SYM before dereferencing insn->func->sym
scheck: Fix slice() upper bit index calculation
sparse-llvm: Support arbitrary struct member counts and fix operand
types
inline: Duplicate generic expressions instead of evaluating them
lib: Avoid mutating fmt before va_start() in warning() cse, canon: Cast pointers to uintptr_t before relational comparison
clang-format: Add .clang-format configuration file
options: Add support for -std=c23, -std=c2x and -std=gnu23
preprocessor: Add support for #elifdef and #elifndef
preprocessor: Add support for __has_include and __has_include_next
c23: Add support for static_assert, alignas, alignof, thread_local
c23: Add support for bool, true, and false keywords
c23: Add support for nullptr and nullptr_t
c23: Add support for digit separators in numeric literals
c23: Support unnamed parameters in function definitions
c23: Support variadic functions without named parameters
c23: Support labels before declarations and at block ends
c23: Support auto type inference
c23: Support constexpr object specifier
c23: Support enumerations with fixed underlying types
c23: Support standard [[]] attribute syntax
preprocessor: Add support for __has_c_attribute
c23: Support empty initializer braces {}
preprocessor: Add support for __has_embed
preprocessor: Add support for #embed directive
c23: Add support for u8 character constants and string literals
preprocessor: Add support for __VA_OPT__
c23: Treat empty parameter list () as (void) and reject K&R functions
c23: Support storage-class specifiers in compound literals
c23: Add support for _BitInt(N)
enum: Support machine mode attributes on enumeration types
enum: Support __attribute__((packed)) on enumeration types
expand: Ignore top-level non-array address space in compare_types()
builtin: Support __builtin_infer_alloc_token() as a size_t ICE
builtin: Add support for Linux kernel compiler builtins
builtin: Add support for __builtin_has_attribute()
cleanup: Support __attribute__((cleanup(...))) in linearize and
-Wcontext
builtin: Do not evaluate __builtin_clz(0) and __builtin_ctz(0)
pre-process: Support long token and string expansions dynamically
x86: Undefine conflicting bitness macros when parsing -m flags
evaluate: Accept conditional expressions with only one void side
ci: Add Linux kernel GitHub Actions workflow and build script
Linus Torvalds (7):
context: Add "conditional context increment" model
expand: Simplify signed constants early
bitwise: Allow all-bits-set as a restricted value
bitwise: Allow restricted ordered compares with unrestricted values
bitwise: Keep unrestricted values unrestricted after a cast
bitwise: Don't remove MOD_SPECIFIER from 'bitwise' types
bitwise: Allow both regular casts and forced casts for restricted
values
.clang-format | 125 ++ .../build-linux-kernel-with-sparse.yml | 28 + Documentation/types.rst | 2 +- Makefile | 2 +- allocate.c | 45 +- allocate.h | 1 + ast-inspect.c | 1 + ast-model.c | 9 +- builtin.c | 249 ++- c2xml.c | 55 +- char.c | 146 +- ci/build-linux-kernel-with-sparse.sh | 23 + compat/mmap-blob.c | 4 +- compile-i386.c | 76 +- cse.c | 17 +- ctags.c | 4 +- dissect.c | 6 +- evaluate.c | 918 ++++++++- example.c | 2 +- expand.c | 696 ++++++- expand.h | 3 + expression.c | 482 ++++- expression.h | 14 +- flow.c | 3 + gcc-attr-list.h | 2 - graph.c | 33 +- ident-list.h | 33 +- inline.c | 343 +++- lib.c | 30 +- linearize.c | 624 +++++- linearize.h | 6 +- memops.c | 4 +- options.c | 84 +- options.h | 2 + parse.c | 1620 ++++++++++++--- parse.h | 5 + pre-process.c | 1824 +++++++++++++++-- predefine.c | 8 + scheck.c | 3 +- show-parse.c | 128 +- simplify.c | 230 ++- simplify.h | 1 + sparse-llvm.c | 183 +- sparse.c | 207 +- ssa.c | 6 + storage.c | 5 +- symbol.c | 314 ++- symbol.h | 150 +- target-openrisc.c | 2 +- token.h | 13 +- tokenize.c | 242 ++- validation/arch/x86-bitness-override.c | 17 + validation/arch/x86-bitness-undef.c | 16 + validation/atomic-builtins-const.c | 67 + validation/atomic-builtins-types.c | 47 + validation/attr_in_parameter.c | 2 + .../backend/c23-compound-literal-storage.c | 27 + validation/backend/c23-empty-init.c | 24 + validation/backend/c23-nullptr.c | 21 + validation/backend/struct-large-members.c | 83 + validation/bitfield-bool-layout.c | 9 +- validation/bitwise-all-bits-and-casts.c | 100 + validation/builtin-clz-ctz-zero.c | 11 + validation/builtin-counted-by-ref-err.c | 20 + validation/builtin-has-attribute-err.c | 19 + validation/builtin-has-attribute-more.c | 157 ++ validation/builtin-has-attribute-nonstring.c | 35 + validation/builtin-infer-alloc-token.c | 28 + validation/builtin-object-size-cycle.c | 44 + validation/builtins-kernel.c | 73 + validation/c11-c23-keywords-ident.c | 19 + validation/c11-va-start-error.c | 20 + validation/c23-alignof-pedantic.c | 20 + validation/c23-attributes-error.c | 20 + validation/c23-attributes-pedantic.c | 10 + validation/c23-attributes.c | 152 ++ validation/c23-auto-error.c | 71 + validation/c23-auto.c | 107 + validation/c23-bitint-error.c | 61 + validation/c23-bitint-pedantic.c | 13 + validation/c23-bitint.c | 214 ++ validation/c23-bool-error.c | 23 + validation/c23-bool.c | 45 + .../c23-compound-literal-register-addr.c | 17 + .../c23-compound-literal-storage-error.c | 37 + .../c23-compound-literal-storage-pedantic.c | 10 + validation/c23-compound-literal-storage.c | 27 + validation/c23-constexpr-error.c | 92 + validation/c23-constexpr-self-init.c | 41 + validation/c23-constexpr.c | 100 + validation/c23-digit-separators-error.c | 36 + validation/c23-digit-separators-pedantic.c | 12 + validation/c23-digit-separators.c | 29 + validation/c23-empty-init-error.c | 19 + validation/c23-empty-init-pedantic.c | 14 + validation/c23-empty-init.c | 64 + validation/c23-empty-parameters.c | 29 + validation/c23-empty-params-error.c | 47 + validation/c23-enum-type-cast.c | 70 + validation/c23-enum-type-error.c | 40 + validation/c23-enum-type.c | 116 ++ validation/c23-keywords-error.c | 48 + validation/c23-keywords.c | 30 + validation/c23-knr-error.c | 14 + validation/c23-labels-error.c | 48 + validation/c23-labels-gnu.c | 15 + validation/c23-labels-pedantic.c | 15 + validation/c23-labels.c | 67 + validation/c23-nullptr-assign.c | 35 + validation/c23-nullptr-error.c | 107 + validation/c23-nullptr.c | 107 + validation/c23-param-attribute.c | 28 + validation/c23-stdc-version.c | 11 + validation/c23-typeof-unqual.c | 113 + validation/c23-u8-char-error.c | 16 + validation/c23-u8-char-pedantic.c | 10 + validation/c23-u8-char-warn.c | 14 + validation/c23-u8-char.c | 37 + validation/c23-unnamed-params-error.c | 27 + validation/c23-unnamed-params-pedantic.c | 12 + validation/c23-unnamed-params.c | 47 + validation/c23-va-opt.c | 36 + validation/c23-variadic-error.c | 41 + validation/c23-variadic-no-named.c | 47 + validation/c2xml-recursive-types.c | 15 + validation/cleanup-context.c | 161 ++ validation/cleanup-errors.c | 77 + validation/cleanup-inline-loop.c | 31 + validation/cond-err-expand.c | 9 - validation/cond-one-void-pedantic.c | 39 + validation/cond-one-void.c | 47 + validation/context-fixes.c | 41 + validation/context.c | 101 +- validation/enum+mode.c | 26 +- validation/enum-packed.c | 85 + validation/eval-expand-inline-fixes.c | 49 + validation/eval-ptr-incomplete-and-inline.c | 70 + validation/eval-type-checks.c | 89 + validation/expand-bitint.c | 49 + validation/expand-const-and-float.c | 73 + validation/inline-generic.c | 25 + validation/linear/bitfield-bool.c | 44 + validation/linear/c23-nullptr.c | 20 + validation/linear/c23-unnamed-params.c | 27 + validation/linear/c23-va-start.c | 22 + validation/linear/cleanup-control-flow.c | 62 + validation/linear/cleanup-stmt-expr-asm.c | 48 + validation/linear/cond-one-void.c | 24 + validation/linear/control-flow-fixes.c | 44 + validation/long-string-expansion.c | 30 + validation/optim/simplify-memops-ssa-fixes.c | 103 + validation/optim/volatile-dse-and-cfg.c | 53 + validation/parser-enum-overflow.c | 13 + validation/parser-type-fixes.c | 93 + validation/preprocessor/c23-elifdef-error.c | 35 + validation/preprocessor/c23-elifdef.c | 44 + validation/preprocessor/c23-embed-error.c | 19 + validation/preprocessor/c23-embed-pedantic.c | 12 + validation/preprocessor/c23-embed.c | 72 + validation/preprocessor/c23-has-c-attribute.c | 60 + validation/preprocessor/c23-has-embed.c | 69 + .../preprocessor/c23-has-include-error.c | 18 + validation/preprocessor/c23-has-include.c | 51 + validation/preprocessor/c23-va-opt-error.c | 31 + validation/preprocessor/c23-va-opt.c | 73 + .../preprocessor/preprocess-crash-fixes.c | 25 + .../preprocess-errors-and-limits.c | 33 + validation/struct-packed-aligned-layout.c | 135 ++ validation/types-compatible-address-space.c | 39 + validation/weak-const-no-fold.c | 15 + 170 files changed, 13517 insertions(+), 1097 deletions(-) create mode 100644 .clang-format create mode 100644 .github/workflows/build-linux-kernel-with-sparse.yml create mode 100755 ci/build-linux-kernel-with-sparse.sh create mode 100644 validation/arch/x86-bitness-override.c create mode 100644 validation/arch/x86-bitness-undef.c create mode 100644 validation/atomic-builtins-const.c create mode 100644 validation/atomic-builtins-types.c create mode 100644 validation/backend/c23-compound-literal-storage.c create mode 100644 validation/backend/c23-empty-init.c create mode 100644 validation/backend/c23-nullptr.c create mode 100644 validation/backend/struct-large-members.c create mode 100644 validation/bitwise-all-bits-and-casts.c create mode 100644 validation/builtin-clz-ctz-zero.c create mode 100644 validation/builtin-counted-by-ref-err.c create mode 100644 validation/builtin-has-attribute-err.c create mode 100644 validation/builtin-has-attribute-more.c create mode 100644 validation/builtin-has-attribute-nonstring.c create mode 100644 validation/builtin-infer-alloc-token.c create mode 100644 validation/builtin-object-size-cycle.c create mode 100644 validation/builtins-kernel.c create mode 100644 validation/c11-c23-keywords-ident.c create mode 100644 validation/c11-va-start-error.c create mode 100644 validation/c23-alignof-pedantic.c create mode 100644 validation/c23-attributes-error.c create mode 100644 validation/c23-attributes-pedantic.c create mode 100644 validation/c23-attributes.c create mode 100644 validation/c23-auto-error.c create mode 100644 validation/c23-auto.c create mode 100644 validation/c23-bitint-error.c create mode 100644 validation/c23-bitint-pedantic.c create mode 100644 validation/c23-bitint.c create mode 100644 validation/c23-bool-error.c create mode 100644 validation/c23-bool.c create mode 100644 validation/c23-compound-literal-register-addr.c create mode 100644 validation/c23-compound-literal-storage-error.c create mode 100644 validation/c23-compound-literal-storage-pedantic.c create mode 100644 validation/c23-compound-literal-storage.c create mode 100644 validation/c23-constexpr-error.c create mode 100644 validation/c23-constexpr-self-init.c create mode 100644 validation/c23-constexpr.c create mode 100644 validation/c23-digit-separators-error.c create mode 100644 validation/c23-digit-separators-pedantic.c create mode 100644 validation/c23-digit-separators.c create mode 100644 validation/c23-empty-init-error.c create mode 100644 validation/c23-empty-init-pedantic.c create mode 100644 validation/c23-empty-init.c create mode 100644 validation/c23-empty-parameters.c create mode 100644 validation/c23-empty-params-error.c create mode 100644 validation/c23-enum-type-cast.c create mode 100644 validation/c23-enum-type-error.c create mode 100644 validation/c23-enum-type.c create mode 100644 validation/c23-keywords-error.c create mode 100644 validation/c23-keywords.c create mode 100644 validation/c23-knr-error.c create mode 100644 validation/c23-labels-error.c create mode 100644 validation/c23-labels-gnu.c create mode 100644 validation/c23-labels-pedantic.c create mode 100644 validation/c23-labels.c create mode 100644 validation/c23-nullptr-assign.c create mode 100644 validation/c23-nullptr-error.c create mode 100644 validation/c23-nullptr.c create mode 100644 validation/c23-param-attribute.c create mode 100644 validation/c23-stdc-version.c create mode 100644 validation/c23-typeof-unqual.c create mode 100644 validation/c23-u8-char-error.c create mode 100644 validation/c23-u8-char-pedantic.c create mode 100644 validation/c23-u8-char-warn.c create mode 100644 validation/c23-u8-char.c create mode 100644 validation/c23-unnamed-params-error.c create mode 100644 validation/c23-unnamed-params-pedantic.c create mode 100644 validation/c23-unnamed-params.c create mode 100644 validation/c23-va-opt.c create mode 100644 validation/c23-variadic-error.c create mode 100644 validation/c23-variadic-no-named.c create mode 100644 validation/c2xml-recursive-types.c create mode 100644 validation/cleanup-context.c create mode 100644 validation/cleanup-errors.c create mode 100644 validation/cleanup-inline-loop.c create mode 100644 validation/cond-one-void-pedantic.c create mode 100644 validation/cond-one-void.c create mode 100644 validation/context-fixes.c create mode 100644 validation/enum-packed.c create mode 100644 validation/eval-expand-inline-fixes.c create mode 100644 validation/eval-ptr-incomplete-and-inline.c create mode 100644 validation/eval-type-checks.c create mode 100644 validation/expand-bitint.c create mode 100644 validation/expand-const-and-float.c create mode 100644 validation/linear/bitfield-bool.c create mode 100644 validation/linear/c23-nullptr.c create mode 100644 validation/linear/c23-unnamed-params.c create mode 100644 validation/linear/c23-va-start.c create mode 100644 validation/linear/cleanup-control-flow.c create mode 100644 validation/linear/cleanup-stmt-expr-asm.c create mode 100644 validation/linear/cond-one-void.c create mode 100644 validation/linear/control-flow-fixes.c create mode 100644 validation/long-string-expansion.c create mode 100644 validation/optim/simplify-memops-ssa-fixes.c create mode 100644 validation/optim/volatile-dse-and-cfg.c create mode 100644 validation/parser-enum-overflow.c create mode 100644 validation/parser-type-fixes.c create mode 100644 validation/preprocessor/c23-elifdef-error.c create mode 100644 validation/preprocessor/c23-elifdef.c create mode 100644 validation/preprocessor/c23-embed-error.c create mode 100644 validation/preprocessor/c23-embed-pedantic.c create mode 100644 validation/preprocessor/c23-embed.c create mode 100644 validation/preprocessor/c23-has-c-attribute.c create mode 100644 validation/preprocessor/c23-has-embed.c create mode 100644 validation/preprocessor/c23-has-include-error.c create mode 100644 validation/preprocessor/c23-has-include.c create mode 100644 validation/preprocessor/c23-va-opt-error.c create mode 100644 validation/preprocessor/c23-va-opt.c create mode 100644 validation/preprocessor/preprocess-crash-fixes.c create mode 100644 validation/preprocessor/preprocess-errors-and-limits.c create mode 100644 validation/struct-packed-aligned-layout.c create mode 100644 validation/types-compatible-address-space.c create mode 100644 validation/weak-const-no-fold.c
PATCH 1/73 Makefile: Pass '--' to rm in clean target to handle dash-prefixed files
Pass '--' to rm in the clean target so that stray files starting with a hyphen (such as '-.o') are not interpreted as command-line options by rm.
--- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
Makefile +1 -1
@@ -288,7 +288,7 @@ validation/%: $(PROGRAMS) FORCE clean: clean-check - @rm -f *.[oa] .*.d $(PROGRAMS) version.h + @rm -f -- *.[oa] .*.d $(PROGRAMS) version.h clean-check: @echo " CLEAN" @find validation/ \( -name "*.c.output.*" \
PATCH 2/73 sparse-llvm: Use LLVMCreateBuilderForModule() with LLVM 24 and later
In reply to Bart Van AsscheCall LLVMCreateBuilderForModule(module) instead of LLVMCreateBuilderInContext(context) in output_fn() when building against LLVM 24 or later so that sparse-llvm builds without a deprecation warning after LLVM commit 46db5f8ab053 ("[llvm-c][ocaml] Accept Module instead of Context in IRBuilder bindings (#234209)").
--- sparse-llvm.c | 4 ++++ 1 file changed, 4 insertions(+)
sparse-llvm.c +4 -0
@@ -1182,7 +1182,11 @@ static void output_fn(LLVMModuleRef module, struct entrypoint *ep)LLVMSetFunctionCallConv (function.fn, LLVMCCallConv);LLVMSetLinkage (function.fn,function_linkage (sym)); +#if LLVM_VERSION_MAJOR >23 + function.builder =LLVMCreateBuilderForModule (module); +#else function.builder =LLVMCreateBuilderInContext (context); +#endif /* give a name to each argument */ nr_args =symbol_list_size (base_type->arguments);
PATCH 3/73 typeof_unqual: Strip qualifiers and address space from types and arrays
In reply to Bart Van AsscheExamine the target symbol type and clear MOD_QUALIFIER, non-array MOD_ATOMIC, and ctype.as in typeof_specifier_helper() and examine_typeof_helper() when qual is false. Add strip_array_qualifiers() to recursively clone SYM_ARRAY chains and strip element qualifiers and address spaces without mutating shared typedef or declaration symbols, while preserving MOD_ATOMIC on array element types per ISO C23 6.7.2.5p4.
Ensure that typeof_unqual() and __typeof_unqual__() remove qualifiers and address spaces from type names, expressions, and qualified array types instead of retaining qualifiers on the resulting type.
--- parse.c | 8 +++ symbol.c | 32 +++++++++- symbol.h | 1 + validation/c23-typeof-unqual.c | 113 +++++++++++++++++++++++++++++++++ 4 files changed, 151 insertions(+), 3 deletions(-) create mode 100644 validation/c23-typeof-unqual.c
parse.c +8 -0
@@ -1070,6 +1070,14 @@ static struct token *typeof_specifier_helper(struct token *token, struct symbolif (lookup_type (token->next)) {struct symbol *sym; token =typename (token->next, &sym,NULL ); + sym =examine_symbol_type (sym); +if (!qual) { + sym->ctype.modifiers &= ~MOD_QUALIFIER ; +if (!sym->ctype.base_type || sym->ctype.base_type->type !=SYM_ARRAY ) + sym->ctype.modifiers &= ~MOD_ATOMIC ; + sym->ctype.as =NULL ; + sym->ctype.base_type =strip_array_qualifiers (sym->ctype.base_type); + } ctx->ctype.base_type = sym->ctype.base_type;apply_ctype (token->pos, &ctx->ctype, &sym->ctype); }else {
symbol.c +29 -3
@@ -541,6 +541,27 @@ static struct symbol *examine_pointer_type(struct symbol *sym)return sym; } +struct symbol *strip_array_qualifiers (struct symbol *type) +{ +struct symbol *elem, *copy; +unsigned long strip; + +if (!type) +return NULL ; +if (type->type !=SYM_ARRAY && type->type !=SYM_NODE ) +return type; + elem =strip_array_qualifiers (type->ctype.base_type); + strip = type->ctype.modifiers &MOD_QUALIFIER ; +if (elem == type->ctype.base_type && !strip && !type->ctype.as) +return type; + copy =alloc_symbol (type->pos, type->type); + *copy = *type; + copy->ctype.base_type = elem; + copy->ctype.modifiers &= ~MOD_QUALIFIER ; + copy->ctype.as =NULL ; +return copy; +} +static struct symbol *examine_typeof_helper (struct symbol *sym,bool qual) {struct symbol *base =evaluate_expression (sym->initializer);
@@ -548,12 +569,17 @@ static struct symbol *examine_typeof_helper(struct symbol *sym, bool qual)if (!base) base = &bad_ctype; -if (base->type ==SYM_NODE ) { +while (base->type ==SYM_NODE ) { mod |= base->ctype.modifiers &MOD_TYPEOF ; -if (!qual) - mod &= ~MOD_QUALIFIER ; base = base->ctype.base_type; } +if (!qual) { + mod &= ~MOD_QUALIFIER ; +if (base->type !=SYM_ARRAY ) + mod &= ~MOD_ATOMIC ; + sym->ctype.as =NULL ; + base =strip_array_qualifiers (base); + }if (base->type ==SYM_BITFIELD )warning (base->pos,"typeof applied to bitfield type" ); sym->type =SYM_NODE ;
symbol.h +1 -0
@@ -351,6 +351,7 @@ extern void add_symbol(struct symbol_list **, struct symbol *);extern void bind_symbol (struct symbol *,struct ident *,enum namespace );extern void bind_symbol_with_scope (struct symbol *,struct ident *,enum namespace ,struct scope *); +extern struct symbol *strip_array_qualifiers (struct symbol *);extern struct symbol *examine_symbol_type (struct symbol *);extern struct symbol *examine_pointer_target (struct symbol *);extern const char *show_as (struct ident *as);
validation/c23-typeof-unqual.c new file +113 -0
113 lines not on this page · raw message
PATCH 4/73 bitfield: Pack consecutive _Bool bitfields into byte containers
In reply to Bart Van AsscheRound bitfield base storage unit sizes smaller than a byte up to bits_in_char in bitfield_base_size() and widen sub-byte bitfield access containers to uchar_ctype in bitfield_base_type() so _Bool bitfields use an 8-bit storage unit during both struct layout and IR linearization.
Allow consecutive _Bool bitfields to pack into a single byte in examine_struct_union_type() and emit bitfield extract and insert instructions at each member's bit_offset, matching the System V ABI, GCC, and Clang. Remove check-known-to-fail from validation/bitfield-bool-layout.c.
--- evaluate.c | 18 ++++++------- linearize.c | 2 ++ symbol.c | 2 ++ symbol.h | 2 ++ validation/bitfield-bool-layout.c | 9 +++---- validation/linear/bitfield-bool.c | 44 +++++++++++++++++++++++++++++++ 6 files changed, 62 insertions(+), 15 deletions(-) create mode 100644 validation/linear/bitfield-bool.c
evaluate.c +9 -9
@@ -1406,12 +1406,12 @@ static int check_assignment_types(struct symbol *target, struct expression **rp,return 1 ; }else if (!(sclass &TYPE_RESTRICT )) goto Cast; -if (t == &bool_ctype) { -if (is_fouled_type (s)) -warning ((*rp)->pos,"%s degrades to integer" , -show_typename (s->ctype.base_type)); - goto Cast; - } +if (is_bool_type (t)) { +if (is_fouled_type (s)) +warning ((*rp)->pos,"%s degrades to integer" , +show_typename (s->ctype.base_type)); + goto Cast; + } *typediff ="different base types" ;return 0 ; }
@@ -1475,7 +1475,7 @@ static int check_assignment_types(struct symbol *target, struct expression **rp,if (tclass &TYPE_NUM ) {/* XXX: need to turn into comparison with NULL */ -if (t == &bool_ctype && (sclass &TYPE_PTR )) +if (is_bool_type (t) && (sclass &TYPE_PTR )) goto Cast; *typediff ="different base types" ;return 0 ;
@@ -3064,7 +3064,7 @@ static struct symbol *evaluate_cast(struct expression *expr)warning (expr->pos,"cast to %s" ,show_typename (ttype));if (sclass &TYPE_RESTRICT ) { -if (ttype == &bool_ctype) { +if (is_bool_type (ttype)) {if (sclass &TYPE_FOULED )warning (expr->pos,"%s degrades to integer" ,show_typename (stype));
@@ -3111,7 +3111,7 @@ static struct symbol *evaluate_cast(struct expression *expr) } } -if (ttype == &bool_ctype) +if (is_bool_type (ttype))cast_to_bool (expr);// checks pointers to restricted
linearize.c +2 -0
@@ -934,6 +934,8 @@ static struct symbol *bitfield_base_type(struct symbol *sym) base = base->ctype.base_type;if (base->type ==SYM_BITFIELD ) { base = base->ctype.base_type; +if (base->bit_size < bits_in_char) + base = &uchar_ctype;if (sym->packed) {int size =bits_to_bytes (sym->bit_offset + sym->bit_size); sym =__alloc_symbol (0 );
symbol.c +2 -0
@@ -113,6 +113,8 @@ static int bitfield_base_size(struct symbol *sym) sym = sym->ctype.base_type;if (sym->type ==SYM_BITFIELD ) sym = sym->ctype.base_type; +if (sym->bit_size < bits_in_char) +return bits_in_char;return sym->bit_size; }
symbol.h +2 -0
@@ -477,6 +477,8 @@ static inline int is_bool_type(struct symbol *type) {if (type->type ==SYM_NODE ) type = type->ctype.base_type; +if (type->type ==SYM_BITFIELD ) + type = type->ctype.base_type;return type == &bool_ctype; }
validation/bitfield-bool-layout.c +3 -6
@@ -12,14 +12,11 @@ struct bfb foo(struct bfb s)/* * check-name: bitfield-bool-layout -* check-description: given that bool is here 1-bit wide -* each field here above completely 'fill' a bool. -* Thus 3 bools need to be allocated, but since the -* alignment is 1-byte the result has a size of 3 -* bytes, 24 bits thus instead of 8. +* check-description: Verify that consecutive _Bool bitfields pack into a +* single 1-byte (8-bit) storage unit rather than allocating a separate +* byte per bitfield (24 bits). * check-command: test-linearize -Wno-decl $file * -* check-known-to-fail * check-output-ignore * check-output-excludes: ret\\.24 * check-output-contains: ret\\.8
validation/linear/bitfield-bool.c new file +44 -0
44 lines not on this page · raw message
PATCH 5/73 allocate: Harden slab allocation bounds, zeroing, and mmap checks
In reply to Bart Van AsscheHarden allocator bounds and statistics handling in allocate.c and compat/mmap-blob.c:
- Zero reused freelist blocks with memset() instead of a pointer-sized loop in allocate().
- Check size > chunking - offset before calling blob_alloc() so blob header alignment overhead cannot underflow blob->left.
- Guard show_allocations() against division by zero when no allocations occurred.
- Check power-of-two chunk rounding and 4096-byte page alignment in blob_alloc() and blob_free().
--- allocate.c | 22 +++++++++++----------- compat/mmap-blob.c | 4 ++-- 2 files changed, 13 insertions(+), 13 deletions(-)
allocate.c +11 -11
@@ -33,6 +33,7 @@#include <stdlib.h> #include <stddef.h> #include <stdio.h> +#include <string.h> #include "lib.h" #include "allocate.h"
@@ -88,10 +89,7 @@ void *allocate(struct allocator_struct *desc, unsigned int size)void **p = desc->freelist; retval = p; desc->freelist = *p; -do { - *p =NULL ; - p++; - }while ((size -=sizeof (void *)) >0 ); +memset (retval,0 , size);return retval; }
@@ -100,17 +98,19 @@ void *allocate(struct allocator_struct *desc, unsigned int size) size = (size + alignment -1 ) & ~(alignment-1 );if (!blob || blob->left < size) {unsigned int offset, chunking = desc->chunking; -struct allocation_blob *newblob =blob_alloc (chunking); +struct allocation_blob *newblob; + + offset = offsetof(struct allocation_blob , data); + offset = (offset + alignment -1 ) & ~(alignment-1 ); +if (size > chunking - offset) +die ("alloc too big" ); + newblob =blob_alloc (chunking);if (!newblob)die ("out of memory" ); -if (size > chunking) -die ("alloc too big" ); desc->total_bytes += chunking; newblob->next = blob; blob = newblob; desc->blobs = newblob; - offset = offsetof(struct allocation_blob , data); - offset = (offset + alignment -1 ) & ~(alignment-1 ); blob->left = chunking - offset; blob->offset = offset - offsetof(struct allocation_blob , data); }
@@ -125,8 +125,8 @@ void show_allocations(struct allocator_struct *x)fprintf (stderr,"%s: %d allocations, %lu bytes (%lu total bytes, " "%6.2f%% usage, %6.2f average size)\n" , x->name, x->allocations, x->useful_bytes, x->total_bytes, -100 * (double ) x->useful_bytes / x->total_bytes, - (double ) x->useful_bytes / x->allocations); +100 * (double ) x->useful_bytes / (x->total_bytes ?:1 ), + (double ) x->useful_bytes / (x->allocations ?:1 )); }void get_allocator_stats (struct allocator_struct *x,struct allocator_stats *s)
compat/mmap-blob.c +2 -2
@@ -17,7 +17,7 @@ void *blob_alloc(unsigned long size) {void *ptr; -if (size & ~CHUNK ) +if (!size || (size & (CHUNK -1 )))die ("internal error: bad allocation size (%lu bytes)" , size); ptr =mmap (NULL , size,PROT_READ |PROT_WRITE ,MAP_PRIVATE |MAP_ANONYMOUS ,-1 ,0 );if (ptr ==MAP_FAILED )
@@ -27,7 +27,7 @@ void *blob_alloc(unsigned long size)void blob_free (void *addr,unsigned long size) { -if (!size || (size & ~CHUNK ) || ((unsigned long ) addr &512 )) +if (!size || (size & (CHUNK -1 )) || ((unsigned long ) addr &4095 ))die ("internal error: bad blob free (%lu bytes at %p)" , size, addr);#ifndef DEBUG munmap (addr, size);
PATCH 6/73 tokenize: Support 4096-byte identifiers and fix escape bounds
In reply to Bart Van AsscheSupport long identifiers and harden character escape and token handling in char.c, token.h, and tokenize.c:
- Widen struct ident's len field to unsigned short and enlarge identifier buffers in get_one_identifier() and show_ident() to 4096 bytes so identifiers longer than 255 bytes are not truncated.
- Guard parse_escape() against reading past the end of the buffer on a trailing backslash and cast input bytes to unsigned char.
- Format TOKEN_GNU_KLUDGE in show_token() and quote_token(), and use logical && when checking stream->pos && Wnewline_eof.
--- char.c | 5 +++-- token.h | 2 +- tokenize.c | 29 +++++++++++++++++------------ 3 files changed, 21 insertions(+), 15 deletions(-)
char.c +3 -2
@@ -8,14 +8,15 @@static const char *parse_escape (const char *p,unsigned *val,const char *end,int bits,struct position pos) { -unsigned c = *p++; +unsigned c = (unsigned char )*p++;unsigned d;if (c !='\\' ) { *val = c;return p; } - c = *p++; +if (p < end) + c = (unsigned char )*p++;switch (c) {case 'a' : c ='\a' ;break ;case 'b' : c ='\b' ;break ;
token.h +1 -1
@@ -70,7 +70,7 @@ extern int *hash_stream(const char *name);struct ident {struct ident *next;/* Hash chain of identifiers */ struct symbol *symbols;/* Pointer to semantic meaning list */ -unsigned char len;/* Length of identifier name */ +unsigned short len;/* Length of identifier name */ unsigned char tainted:1 , reserved:1 , keyword:1 ;
tokenize.c +17 -12
@@ -98,14 +98,14 @@ const char *show_special(int val)const char *show_ident (const struct ident *ident) { -static char buff[4 ][256 ]; +static char buff[4 ][4097 ];static int n;char *buffer;if (!ident)return "<noident>" ; buffer = buff[3 & ++n]; -sprintf (buffer,"%.*s" , ident->len, ident->name); +snprintf (buffer,sizeof (buff[0 ]),"%.*s" , ident->len, ident->name);return buffer; }
@@ -230,11 +230,11 @@ const char *show_token(const struct token *token) token->string->length - 1, 'L', '"');case TOKEN_STREAMBEGIN : -sprintf (buffer,"<beginning of '%s'>" ,stream_name (token->pos.stream)); +snprintf (buffer,sizeof (buffer),"<beginning of '%s'>" ,stream_name (token->pos.stream));return buffer;case TOKEN_STREAMEND : -sprintf (buffer,"<end of '%s'>" ,stream_name (token->pos.stream)); +snprintf (buffer,sizeof (buffer),"<end of '%s'>" ,stream_name (token->pos.stream));return buffer;case TOKEN_UNTAINT :
@@ -245,6 +245,9 @@ const char *show_token(const struct token *token)sprintf (buffer,"<argcnt>" );return buffer; +case TOKEN_GNU_KLUDGE : +return "," ; +default :sprintf (buffer,"unhandled token type '%d' " ,token_type (token));return buffer;
@@ -287,6 +290,8 @@ const char *quote_token(const struct token *token)case TOKEN_WIDE_STRING :return quote_char (token->string->data, token->string->length -1 ,'L' ,'"' ); +case TOKEN_GNU_KLUDGE : +return "," ;default :sprintf (buffer,"unhandled token type '%d' " ,token_type (token));return buffer;
@@ -427,7 +432,7 @@ got_eof: c ='\\' ; goto out; } -if (stream->pos & Wnewline_eof) +if (stream->pos && Wnewline_eof)warning (stream_pos (stream),"no newline at end of file" );else if (spliced)warning (stream_pos (stream),"backslash-newline at end of file" );
@@ -860,7 +865,7 @@ static struct ident *create_hashed_ident(const char *name, int len, unsigned lon p = &hash_table[hash];while ((ident = *p) !=NULL ) { -if (ident->len == (unsigned char ) len) { +if (ident->len == (unsigned short ) len) {if (memcmp (name, ident->name, len) !=0 ) goto next;
@@ -919,7 +924,7 @@ static int get_one_identifier(int c, stream_t *stream)struct token *token;struct ident *ident;unsigned long hash; -char buf[256 ]; +char buf[4096 ];int len =1 ;int next;
@@ -929,11 +934,11 @@ static int get_one_identifier(int c, stream_t *stream) next =nextchar (stream);if (!(cclass[next +1 ] & (Letter | Digit)))break ; -if (len >=sizeof (buf)) -break ; - hash =ident_hash_add (hash, next); - buf[len] = next; - len++; +if (len <sizeof (buf)) { + hash =ident_hash_add (hash, next); + buf[len] = next; + len++; + } };if (cclass[next +1 ] & Quote) {if (len ==1 && buf[0 ] =='L' ) {
PATCH 7/73 pre-process: Fix macro expansion and include directive handling
In reply to Bart Van AsscheFix buffer bounds, unterminated macro arguments, and include path checks in pre-process.c:
- Handle TOKEN_STREAMEND and TOKEN_STREAMBEGIN on unterminated macro argument lists and bound token-pasting buffers in combine().
- Widen token_name_sequence() to PATH_MAX and check remaining capacity with pointer subtraction to prevent buffer and pointer overflows.
- Reject directory paths in try_include() via fstat() and diagnose incomplete defined() expressions in #if directives.
- Add regression tests in validation/preprocessor/preprocess-crash-fixes.c and validation/preprocessor/preprocess-errors-and-limits.c.
--- pre-process.c | 83 +++++++++++++++---- .../preprocessor/preprocess-crash-fixes.c | 25 ++++++ .../preprocess-errors-and-limits.c | 33 ++++++++ 3 files changed, 123 insertions(+), 18 deletions(-) create mode 100644 validation/preprocessor/preprocess-crash-fixes.c create mode 100644 validation/preprocessor/preprocess-errors-and-limits.c
pre-process.c +65 -18
@@ -35,6 +35,7 @@#include <fcntl.h> #include <limits.h> #include <time.h> +#include <sys/stat.h> #include "lib.h" #include "allocate.h"
@@ -107,8 +108,12 @@ static int expand(struct token **, struct symbol *);static void replace_with_string (struct token *token,const char *str) { -int size =strlen (str) +1 ; -struct string *s =__alloc_string (size); +size_t size =strlen (str) +1 ; +struct string *s; + +if (size >INT_MAX -sizeof (struct string )) +die ("string too large" ); + s =__alloc_string (size); s->length = size;memcpy (s->data, str, size);
@@ -312,6 +317,13 @@ struct arg {int n_str; }; +static inline bool stream_end_token (const struct token *t) +{ +return eof_token (t) || +token_type (t) ==TOKEN_STREAMEND || +token_type (t) ==TOKEN_STREAMBEGIN ; +} +static int collect_arguments (struct token *start,struct token *arglist,struct arg *args,struct token *what) {int wanted = arglist->count.normal;
@@ -322,7 +334,7 @@ static int collect_arguments(struct token *start, struct token *arglist, structif (!wanted) { next =collect_arg (start,0 , &what->pos); -if (eof_token (next)) +if (stream_end_token (next)) goto Eclosing;if (!eof_token (start->next) || !match_op (next,')' )) { count++;
@@ -332,7 +344,7 @@ static int collect_arguments(struct token *start, struct token *arglist, structfor (count =0 ; count < wanted; count++) {struct argcount *p = &arglist->next->count; next =collect_arg (start, p->vararg, &what->pos); -if (eof_token (next)) +if (stream_end_token (next)) goto Eclosing;if (p->vararg && wanted ==1 &&eof_token (start->next))break ;
@@ -373,7 +385,7 @@ Emany: next =collect_arg (next,0 , &what->pos); count++; } -if (eof_token (next)) +if (stream_end_token (next)) goto Eclosing;sparse_error (what->pos,"macro \"%s\" passed %d arguments, but takes just %d" ,show_token (what), count, wanted);
@@ -382,7 +394,10 @@ Eclosing:sparse_error (what->pos,"unterminated argument list invoking macro \"%s\"" ,show_token (what)); out: - what->next = next->next; +if (stream_end_token (next)) + what->next = next; +else + what->next = next->next;return 0 ; }
@@ -499,12 +514,22 @@ static enum token_type combine(struct token *left, struct token *right, char *p)if (t2 !=TOKEN_IDENT && t2 !=TOKEN_NUMBER && t2 !=TOKEN_SPECIAL )return TOKEN_ERROR ; -strcpy (p,show_token (left)); -strcat (p,show_token (right)); - len =strlen (p); + { +const char *s1 =show_token (left); +int l1 =strlen (s1); +const char *s2; +int l2; -if (len >=256 ) -return TOKEN_ERROR ; +if (l1 >4096 ) +return TOKEN_ERROR ; +memcpy (p, s1, l1); + s2 =show_token (right); + l2 =strlen (s2); +if (l1 + l2 >4096 ) +return TOKEN_ERROR ; +memcpy (p + l1, s2, l2 +1 ); + len = l1 + l2; + }if (t1 ==TOKEN_IDENT ) {if (t2 ==TOKEN_SPECIAL )
@@ -537,7 +562,7 @@ static enum token_type combine(struct token *left, struct token *right, char *p)static int merge (struct token *left,struct token *right) { -static char buffer[512 ]; +static char buffer[4097 ];enum token_type res =combine (left, right, buffer);int n;
@@ -782,17 +807,22 @@ static int expand(struct token **list, struct symbol *sym)static const char *token_name_sequence (struct token *token,int endop,struct token *start) { -static char buffer[256 ]; +static char buffer[PATH_MAX ];char *ptr = buffer;while (!eof_token (token) && !match_op (token, endop)) { -int len; +size_t len, rem;const char *val;if (token_type (token) ==TOKEN_STRING ) val = token->string->data;else val =show_token (token); len =strlen (val); + rem =sizeof (buffer) - (size_t )(ptr - buffer); +if (len >= rem) { +sparse_error (token->pos,"header name too long" ); +return NULL ; + }memcpy (ptr, val, len); ptr += len; token = token->next;
@@ -896,23 +926,30 @@ static void set_stream_include_path(struct stream *stream)static int try_include (struct position pos,const char *path,const char *filename,int flen,struct token **where,const char **next_path) {int fd; +struct stat st;int plen =strlen (path); -static char fullname[PATH_MAX ]; +char fullname[PATH_MAX ]; +if (!flen || plen + flen +2 >sizeof (fullname)) +return 0 ;memcpy (fullname, path, plen);if (plen && path[plen-1 ] !='/' ) { fullname[plen] ='/' ; plen++; }memcpy (fullname+plen, filename, flen); + fullname[plen + flen] ='\0' ;if (already_tokenized (fullname))return 1 ; fd =open (fullname,O_RDONLY );if (fd >=0 ) { -char *streamname =xmemdup (fullname, plen + flen); - *where =tokenize (&pos, streamname, fd, *where, next_path); +if (fstat (fd, &st) ==0 && !S_ISDIR (st.st_mode)) { +char *streamname =xmemdup (fullname, plen + flen +1 ); + *where =tokenize (&pos, streamname, fd, *where, next_path); +close (fd); +return 1 ; + }close (fd); -return 1 ; }return 0 ; }
@@ -961,6 +998,8 @@ static int handle_include_path(struct stream *stream, struct token **list, struc token = next->next; filename =token_name_sequence (token, expect, token); +if (!filename) +return 1 ; flen =strlen (filename) +1 ;/* Absolute path? */
@@ -1649,6 +1688,14 @@ static int expression_value(struct token **where) list = &p->next; } +if (state ==1 || state ==2 ) { +sparse_error ((*beginning)->pos,"expected identifier after \"defined\"" ); +replace_with_bool (*beginning,0 ); + (*beginning)->next = &eof_token_entry; + }else if (state ==3 ) { +sparse_error ((*beginning)->pos,"missing ')' after \"defined\"" ); + } + p =constant_expression (*where, &expr);if (!eof_token (p))sparse_error (p->pos,"garbage at end: %s" ,show_token_sequence (p,0 ));
validation/preprocessor/preprocess-crash-fixes.c new file +25 -0
@@ -0,0 +1,25 @@ +#define REC_A (...) REC_B(__VA_ARGS__) +#define REC_B (...) REC_A(__VA_ARGS__) +extern int REC_A (int , ...); +int rec_nonempty =sizeof (REC_A (1 )); + +/* Recursive macro with empty __VA_ARGS__ must terminate without crash */ +#define REC_E (...) REC_F(__VA_ARGS__) +#define REC_F (...) REC_E(__VA_ARGS__) +extern int REC_E (void ); +int rec_empty =sizeof (REC_E ()); + +#define ID (x) x +int a =ID (1 ); + +/* Octal escape > 0377 */ +int oct_overflow ='\400' ; + +/* +* check-name: preprocess-crash-fixes +* check-command: sparse -Wno-decl $file +* +* check-error-start +preprocessor/preprocess-crash-fixes.c:16:20: warning: octal escape sequence out of range +* check-error-end +*/
validation/preprocessor/preprocess-errors-and-limits.c new file +33 -0
@@ -0,0 +1,33 @@ +#if defined() +#endif +#if defined(FOO +#endif +#if defined +#endif +#if defined( +#endif +#include "." +static const char *s = "\x"; + +/* 300-character identifier */ +static int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =42 ; + +static int get_val (void ) +{ +return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; +} + +/* +* check-name: preprocess-errors-and-limits +* check-command: sparse $file +* check-exit-value: 1 +* +* check-error-start +preprocessor/preprocess-errors-and-limits.c:10:27: warning: \x used with no following hex digits +preprocessor/preprocess-errors-and-limits.c:1:13: error: expected preprocessor identifier +preprocessor/preprocess-errors-and-limits.c:3:13: error: missing ')' after "defined" +preprocessor/preprocess-errors-and-limits.c:5:5: error: expected identifier after "defined" +preprocessor/preprocess-errors-and-limits.c:7:5: error: expected identifier after "defined" +preprocessor/preprocess-errors-and-limits.c:9:10: error: unable to open '.' +* check-error-end +*/
PATCH 8/73 options, lib: Harden warning buffers and command-line option parsing
In reply to Bart Van AsscheFix buffer sizing and command-line option parsing safety in lib.c and options.c:
- Enlarge the warning buffer in do_warn(), format with vsnprintf(), track warning counts without underflowing fmax_warnings, and allocate oversized add_pre_buffer() strings dynamically.
- Reject trailing characters and honor OPT_INVERSE in handle_switch_setval(), and diagnose missing arguments in -G, -include, -imacros, and -MF/-MQ/-MT switches.
--- lib.c | 24 ++++++++++++++++++++---- options.c | 19 +++++++++++-------- 2 files changed, 31 insertions(+), 12 deletions(-)
lib.c +20 -4
@@ -128,13 +128,13 @@ static const char *show_stream_name(struct position pos)static void do_warn (const char *type,struct position pos,const char * fmt,va_list args) { -static char buffer[512 ]; +static char buffer[4096 ];/* Shut up warnings if position is bad_token.pos */ if (pos.type ==TOKEN_BAD )return ; -vsprintf (buffer, fmt, args); +vsnprintf (buffer,sizeof (buffer), fmt, args);fflush (stdout); fprintf(stderr, "%s:%d:%d: %s%s%s\n",
@@ -181,6 +181,7 @@ static void do_error(struct position pos, const char * fmt, va_list args)void warning (struct position pos,const char * fmt, ...) {va_list args; +static unsigned int warnings =0 ;if (Wsparse_error) {va_start (args, fmt);
@@ -194,9 +195,13 @@ void warning(struct position pos, const char * fmt, ...)return ; } -if (!--fmax_warnings) { +if (++warnings > fmax_warnings) { +static int once =0 ; show_info =0 ; +if (once) +return ; fmt ="too many warnings" ; + once =1 ; }va_start (args, fmt);
@@ -256,11 +261,22 @@ void add_pre_buffer(const char *fmt, ...)unsigned int size;struct token *begin, *end;char buffer[4096 ]; +char *buf = buffer;va_start (args, fmt); size =vsnprintf (buffer,sizeof (buffer), fmt, args);va_end (args); - begin =tokenize_buffer (buffer, size, &end); +if (size >=sizeof (buffer)) { + buf =malloc (size +1 ); +if (!buf) +die ("out of memory" ); +va_start (args, fmt); +vsnprintf (buf, size +1 , fmt, args); +va_end (args); + } + begin =tokenize_buffer (buf, size, &end); +if (buf != buffer) +free (buf); *pre_buffer_next = begin; pre_buffer_next = &end->next; }
options.c +11 -8
@@ -315,7 +315,9 @@ static void handle_onoff_switch_finalize(const struct flag flags[])static int handle_switch_setval (const char *arg,const char *opt,const struct flag *flag,int options) { - *(flag->flag) = flag->mask; +if (*opt !='\0' ) +return 0 ; + *(flag->flag) = (options &OPT_INVERSE ) ?0 : flag->mask;return 1 ; }
@@ -548,7 +550,7 @@ static char **handle_switch_f(char *arg, char **next)static char **handle_switch_G (char *arg,char **next) { -if (!strcmp (arg,"G" ) && *next) +if (!strcmp (arg,"G" ) && next[1 ])return next +1 ;// "-G 0" else return next;// "-G0" or (bogus) terminal "-G"
@@ -599,11 +601,12 @@ static void add_cmdline_include(char *filename)static char **handle_switch_i (char *arg,char **next) { -if (*next && !strcmp (arg,"include" )) -add_cmdline_include (*++next); -else if (*next && !strcmp (arg,"imacros" )) -add_cmdline_include (*++next); -else if (*next && !strcmp (arg,"isystem" )) { +if (!strcmp (arg,"include" ) || !strcmp (arg,"imacros" )) { +char *path = *++next; +if (!path) +die ("missing argument for -%s option" , arg); +add_cmdline_include (path); + }else if (*next && !strcmp (arg,"isystem" )) {char *path = *++next;if (!path)die ("missing argument for -isystem option" );
@@ -620,7 +623,7 @@ static char **handle_switch_i(char *arg, char **next)static char **handle_switch_M (char *arg,char **next) {if (!strcmp (arg,"MF" ) || !strcmp (arg,"MQ" ) || !strcmp (arg,"MT" )) { -if (!*next) +if (!next[1 ])die ("missing argument for -%s option" , arg);return next +1 ; }
PATCH 9/73 builtin: Fix atomic builtin type checking and object_size bounds
In reply to Bart Van AsscheFix builtin argument evaluation and __builtin_object_size() expansion in builtin.c:
- Initialize sym upfront in eval_args() before reporting argument count errors.
- Accept integer, enum, pointer, and restricted bitwise types in eval_atomic_common() while preserving per-parameter const and volatile pointer qualifiers via make_atomic_ptr_type().
- Bound pointer-chasing hops, unwrap parenthesized expressions, guard null symbols, and clamp offset subtraction in expand_object_size().
- Add regression tests in validation/atomic-builtins-types.c, validation/atomic-builtins-const.c, and validation/builtin-object-size-cycle.c.
--- builtin.c | 112 +++++++++++++++++-------- symbol.c | 3 + symbol.h | 1 + validation/atomic-builtins-const.c | 67 +++++++++++++++ validation/atomic-builtins-types.c | 47 +++++++++++ validation/builtin-object-size-cycle.c | 44 ++++++++++ 6 files changed, 239 insertions(+), 35 deletions(-) create mode 100644 validation/atomic-builtins-const.c create mode 100644 validation/atomic-builtins-types.c create mode 100644 validation/builtin-object-size-cycle.c
builtin.c +77 -35
@@ -68,7 +68,7 @@ static int evaluate_pure_unop(struct expression *expr)static int eval_args (struct expression *expr,int n) {struct expression *arg; -struct symbol *sym; +struct symbol *sym = expr->fn->ctype;const char *msg;int rc =1 ;
@@ -87,7 +87,6 @@ static int eval_args(struct expression *expr, int n)return rc; error: - sym = expr->fn->ctype;expression_error (expr,"%s for %s" , msg,show_ident (sym->ident));return 0 ; }
@@ -454,47 +453,78 @@ struct symbol_op generic_int_op = { }; +static struct symbol *make_atomic_ptr_type (struct position pos, +struct symbol *target, +unsigned long mods, +struct ident *as) +{ +struct symbol *ptr =alloc_symbol (pos,SYM_PTR ); + ptr->ctype.base_type = target; + ptr->ctype.modifiers = mods; + ptr->ctype.as = as; + ptr->bit_size = bits_in_pointer; + ptr->ctype.alignment = pointer_alignment; +return ptr; +} +static int eval_atomic_common (struct expression *expr) {struct symbol *fntype = expr->fn->ctype->ctype.base_type;struct symbol_list *types =NULL ;struct symbol *ctype =NULL ; +struct symbol *valtype =NULL ; +struct symbol *aptr =NULL ;struct symbol *t;struct expression *arg;int n =0 ;// The number of arguments has already be verified. -// The first arg must be a pointer to an integral type. +// The first arg must be a pointer to an integral or pointer type. PREPARE_PTR_LIST (fntype->arguments, t); FOR_EACH_PTR(expr->args, arg) { -struct symbol *ptrtype =NULL ; -if (++n ==1 ) { - t = arg->ctype; -if (!t) +struct symbol *proto_ptr = t ? t->ctype.base_type :NULL ; +unsigned long proto_mods =MOD_VOLATILE ; +if (proto_ptr && proto_ptr->ctype.base_type) + proto_mods = proto_ptr->ctype.base_type->ctype.modifiers; + aptr = arg->ctype; +if (!aptr)return 0 ; -if (t->type ==SYM_NODE ) - t = t->ctype.base_type; -if (!t) +if (aptr->type ==SYM_NODE ) + aptr = aptr->ctype.base_type; +if (!aptr)return 0 ; -if (t->type !=SYM_PTR ) +if (aptr->type !=SYM_PTR ) goto err; - ptrtype = t; - t = t->ctype.base_type; -if (!t) + ctype =examine_pointer_target (aptr); +if (!ctype)return 0 ; -if (t->type ==SYM_NODE ) - t = t->ctype.base_type; -if (!t) -return 0 ; -if (t->type !=SYM_PTR && t->ctype.base_type != &int_type) +if (ctype->type !=SYM_PTR && ctype->ctype.base_type != &int_type && + !is_int_type (ctype) && !is_restricted_type (ctype)) goto err; - ctype = t; - t = ptrtype; + valtype = ctype; +if (aptr->ctype.modifiers &MOD_NOCAST ) { +struct symbol *node =alloc_symbol (arg->pos,SYM_NODE ); + *node = *ctype; + node->type =SYM_NODE ; + node->ctype.base_type = ctype; + node->ctype.modifiers |=MOD_NOCAST ; + valtype = node; + } + t =make_atomic_ptr_type ( + arg->pos, ctype, + proto_mods | (aptr->ctype.modifiers & (MOD_ATOMIC |MOD_NOCAST |MOD_NODEREF )), + aptr->ctype.as); + }else if (!t) { +break ; }else if (is_dynamic_type (t)) { - t = ctype; - }else if (t == &ptr_ctype) { - t = ptrtype; + t = valtype; + }else if (t == &ptr_ctype || t->ctype.base_type == &ptr_ctype) { + t =make_atomic_ptr_type (arg->pos, ctype, + aptr->ctype.modifiers &MOD_NOCAST ,NULL ); + }else if (t == &const_ptr_ctype || t->ctype.base_type == &const_ptr_ctype) { + t =make_atomic_ptr_type (arg->pos, ctype, +MOD_CONST | (aptr->ctype.modifiers &MOD_NOCAST ),NULL ); }add_ptr_list (&types, t);NEXT_PTR_LIST (t);
@@ -502,7 +532,7 @@ static int eval_atomic_common(struct expression *expr)FINISH_PTR_LIST (t);if (!expr->ctype)// set the return type, if needed - expr->ctype = ctype; + expr->ctype = valtype;return evaluate_arguments (types, expr->args); err:
@@ -528,8 +558,13 @@ static int expand_object_size(struct expression *expr, int cost)struct expression *arg =first_expression (expr->args);int type =get_expression_value_silent (ptr_list_nth (expr->args,1 ));unsigned long val =-1 , off =0 ; +int hops =0 ;while (arg) { +if (++hops >64 ) { + val =-1 ; +break ; + }switch (arg->type) {case EXPR_IMPLIED_CAST :case EXPR_CAST :
@@ -544,15 +579,20 @@ static int expand_object_size(struct expression *expr, int cost) arg = arg->left;continue ;case EXPR_PREOP : +if (arg->op =='(' ) { + arg = arg->unop; +continue ; + }// a deref is just intermediate variable // and so the offset needs to be zeroed. if (arg->op =='*' ) {struct expression *parent = arg; arg = arg->unop; - off =0 ; +if (!arg) +break ;switch (arg->type) {case EXPR_SYMBOL : - arg = arg->symbol->initializer; + arg = arg->symbol ? arg->symbol->initializer :NULL ;if (arg == parent) {// stop at self-initialized vars // and do not expand them.
@@ -562,6 +602,7 @@ static int expand_object_size(struct expression *expr, int cost) }continue ;default : + off =0 ;break ; } }
@@ -584,7 +625,7 @@ static int expand_object_size(struct expression *expr, int cost)else if (type &1 )return UNSAFE ;else - val -= off; + val = (off > val) ?0 : val - off; expr->flags |=CEF_SET_ICE ; expr->type =EXPR_VALUE ;
@@ -678,13 +719,14 @@ static const struct builtin_fn builtins_common[] = {#define size_t_ctype &size_t_alias#define va_list_ctype &ptr_ctype#define vol_ptr &volatile_ptr_ctype +#define cv_ptr &const_volatile_ptr_ctype { "__atomic_add_fetch", NULL, 0, { vol_ptr, &dyntype, &int_ctype }, .op = &atomic_op }, - { "__atomic_always_lock_free", &bool_ctype, 0, { size_t_ctype, vol_ptr }}, + { "__atomic_always_lock_free", &bool_ctype, 0, { size_t_ctype, cv_ptr }}, { "__atomic_and_fetch", NULL, 0, { vol_ptr, &dyntype, &int_ctype }, .op = &atomic_op }, { "__atomic_clear", &void_ctype, 0, { &volatile_bool_ptr_ctype, &int_ctype }}, - { "__atomic_compare_exchange", &bool_ctype, 0, { vol_ptr, &ptr_ctype, &ptr_ctype, &bool_ctype, &int_ctype, &int_ctype }, .op = &atomic_op }, + { "__atomic_compare_exchange", &bool_ctype, 0, { vol_ptr, &ptr_ctype, &const_ptr_ctype, &bool_ctype, &int_ctype, &int_ctype }, .op = &atomic_op }, { "__atomic_compare_exchange_n", &bool_ctype, 0, { vol_ptr, &ptr_ctype, &dyntype, &bool_ctype, &int_ctype, &int_ctype }, .op = &atomic_op }, - { "__atomic_exchange", &void_ctype, 0, { vol_ptr, &ptr_ctype, &ptr_ctype, &int_ctype }, .op = &atomic_op }, + { "__atomic_exchange", &void_ctype, 0, { vol_ptr, &const_ptr_ctype, &ptr_ctype, &int_ctype }, .op = &atomic_op }, { "__atomic_exchange_n", NULL, 0, { vol_ptr, &dyntype, &int_ctype }, .op = &atomic_op }, { "__atomic_fetch_add", NULL, 0, { vol_ptr, &dyntype, &int_ctype }, .op = &atomic_op }, { "__atomic_fetch_and", NULL, 0, { vol_ptr, &dyntype, &int_ctype }, .op = &atomic_op },
@@ -692,13 +734,13 @@ static const struct builtin_fn builtins_common[] = { { "__atomic_fetch_or", NULL, 0, { vol_ptr, &dyntype, &int_ctype }, .op = &atomic_op }, { "__atomic_fetch_sub", NULL, 0, { vol_ptr, &dyntype, &int_ctype }, .op = &atomic_op }, { "__atomic_fetch_xor", NULL, 0, { vol_ptr, &dyntype, &int_ctype }, .op = &atomic_op }, - { "__atomic_is_lock_free", &bool_ctype, 0, { size_t_ctype, vol_ptr }}, - { "__atomic_load", &void_ctype, 0, { vol_ptr, &ptr_ctype, &int_ctype }, .op = &atomic_op }, - { "__atomic_load_n", NULL, 0, { vol_ptr, &int_ctype }, .op = &atomic_op }, + { "__atomic_is_lock_free", &bool_ctype, 0, { size_t_ctype, cv_ptr }}, + { "__atomic_load", &void_ctype, 0, { cv_ptr, &ptr_ctype, &int_ctype }, .op = &atomic_op }, + { "__atomic_load_n", NULL, 0, { cv_ptr, &int_ctype }, .op = &atomic_op }, { "__atomic_nand_fetch",NULL, 0, { vol_ptr, &dyntype, &int_ctype }, .op = &atomic_op }, { "__atomic_or_fetch", NULL, 0, { vol_ptr, &dyntype, &int_ctype }, .op = &atomic_op }, { "__atomic_signal_fence", &void_ctype, 0, { &int_ctype }}, - { "__atomic_store", &void_ctype, 0, { vol_ptr, &ptr_ctype, &int_ctype }, .op = &atomic_op }, + { "__atomic_store", &void_ctype, 0, { vol_ptr, &const_ptr_ctype, &int_ctype }, .op = &atomic_op }, { "__atomic_store_n", &void_ctype, 0, { vol_ptr, &dyntype, &int_ctype }, .op = &atomic_op }, { "__atomic_sub_fetch", NULL, 0, { vol_ptr, &dyntype, &int_ctype }, .op = &atomic_op }, { "__atomic_test_and_set", &bool_ctype, 0, { vol_ptr, &int_ctype }},
symbol.c +3 -0
@@ -883,6 +883,7 @@ struct symbol const_void_ctype, const_char_ctype;struct symbol const_ptr_ctype, const_string_ctype;struct symbol const_wchar_ctype, const_wstring_ctype;struct symbol volatile_void_ctype, volatile_ptr_ctype; +struct symbol const_volatile_void_ctype, const_volatile_ptr_ctype;struct symbol volatile_bool_ctype, volatile_bool_ptr_ctype;struct symbol zero_int;
@@ -990,6 +991,8 @@ static const struct ctype_declare { { &const_wchar_ctype, T_CONST(&int_ctype, NULL, NULL) }, { &volatile_void_ctype,T_NODE(MOD_VOLATILE, &void_ctype, NULL, NULL) }, { &volatile_ptr_ctype, T_PTR(&volatile_void_ctype) }, + { &const_volatile_void_ctype, T_NODE(MOD_CONST | MOD_VOLATILE, &void_ctype, NULL, NULL) }, + { &const_volatile_ptr_ctype, T_PTR(&const_volatile_void_ctype) }, { &volatile_bool_ctype,T_NODE(MOD_VOLATILE, &bool_ctype, NULL, NULL) }, { &volatile_bool_ptr_ctype, T_PTR(&volatile_bool_ctype) }, { NULL, }
symbol.h +1 -0
@@ -316,6 +316,7 @@ extern struct symbol const_void_ctype, const_char_ctype;extern struct symbol const_ptr_ctype, const_string_ctype;extern struct symbol const_wchar_ctype, const_wstring_ctype;extern struct symbol volatile_void_ctype, volatile_ptr_ctype; +extern struct symbol const_volatile_void_ctype, const_volatile_ptr_ctype;extern struct symbol volatile_bool_ctype, volatile_bool_ptr_ctype;/* Special internal symbols */
validation/atomic-builtins-const.c new file +67 -0
67 lines not on this page · raw message
validation/atomic-builtins-types.c new file +47 -0
47 lines not on this page · raw message
validation/builtin-object-size-cycle.c new file +44 -0
44 lines not on this page · raw message
PATCH 10/73 parse, show-parse: Fix attribute propagation, enum overflow, and bounds
In reply to Bart Van AsscheFix parser attribute handling, enumerator overflow promotion, and type formatting bounds in expression.c, parse.c, show-parse.c, and symbol.h:
- Reject invalid integer suffixes and missing _Generic association expressions in expression.c.
- Propagate designated_init and transparent_union attributes on forward and post-brace tag declarations, promote overflowing enumerators while diagnosing ULLONG_MAX wraparound, validate alignment and address_space bounds, transfer context attributes across pointer return types, and guard null current_fn.
- Enlarge show-parse.c formatting buffers, reserve space for the trailing NUL byte, and route all type formatting through prepend() and append() with pointer-subtraction capacity checks.
- Add regression tests in validation/parser-type-fixes.c and validation/parser-enum-overflow.c.
--- expression.c | 16 +++++- parse.c | 81 ++++++++++++++++++++++++--- show-parse.c | 61 ++++++++++++-------- symbol.h | 2 + validation/parser-enum-overflow.c | 13 +++++ validation/parser-type-fixes.c | 93 +++++++++++++++++++++++++++++++ 6 files changed, 233 insertions(+), 33 deletions(-) create mode 100644 validation/parser-enum-overflow.c create mode 100644 validation/parser-type-fixes.c
expression.c +13 -3
@@ -290,8 +290,12 @@ static void get_number_value(struct expression *expr, struct token *token) size =2 ; end++; } - }else + }else if (c =='.' || c =='e' || c =='E' || c =='p' || c =='P' || +strchr (end,'.' ) ||strchr (end,'e' ) ||strchr (end,'E' )) { goto Float; + }else { + goto Enoint; + } }if (overflow) goto Eoverflow;
@@ -402,8 +406,12 @@ static struct token *generic_selection(struct token *token, struct expression ** token =typename (token, &map->type,NULL ); token =expect (token,':' ,"after typename" ); token =assignment_expression (token, &map->expr); - *last = map; - last = &map->next; +if (!map->expr) +sparse_error (token->pos,"expected expression after ':'" ); +else { + *last = map; + last = &map->next; + } }else if (match_ident (token, &default_ident)) {if (expr->def) {warning (token->pos,"multiple default in generic expression" );
@@ -412,6 +420,8 @@ static struct token *generic_selection(struct token *token, struct expression ** token = token->next; token =expect (token,':' ,"after typename" ); token =assignment_expression (token, &expr->def); +if (!expr->def) +sparse_error (token->pos,"expected expression after ':'" ); } } end:
parse.c +73 -8
156 lines not on this page · raw message
show-parse.c +39 -22
151 lines not on this page · raw message
symbol.h +2 -0
@@ -115,6 +115,8 @@ struct decl_state {unsigned char autotype;unsigned char forced;unsigned char packed; +unsigned char designated_init; +unsigned char transparent_union; };struct pseudo ;
validation/parser-enum-overflow.c new file +13 -0
@@ -0,0 +1,13 @@ +enum { +E_ULLMAX = ~0ULL , +E_ULL_OVERFLOW , +}; + +/* +* check-name: parser-enum-overflow +* check-command: sparse $file +* +* check-error-start +parser-enum-overflow.c:3:9: error: enumerator value for 'E_ULL_OVERFLOW' overflows +* check-error-end +*/
validation/parser-type-fixes.c new file +93 -0
93 lines not on this page · raw message
PATCH 11/73 target-openrisc: Set target_openrisc.mach to MACH_OPENRISC
In reply to Bart Van AsscheSet target_openrisc.mach to MACH_OPENRISC instead of MACH_NDS32 in target-openrisc.c so that OpenRISC targets report the correct machine architecture identifier.
--- target-openrisc.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
target-openrisc.c +1 -1
@@ -20,7 +20,7 @@ static void predefine_openrisc(const struct target *self) }const struct target target_openrisc = { - .mach =MACH_NDS32 , + .mach =MACH_OPENRISC , .bitness =ARCH_LP32 , .big_endian = true,
PATCH 12/73 evaluate: Fix pointer arithmetic, incomplete types, and qualifiers
In reply to Bart Van AsscheFix type checking and qualifier handling across evaluate.c, parse.c, symbol.c, and symbol.h:
- Distinguish forward-declared incomplete structs and unions (bit_size = -1) from complete GNU empty structs (bit_size = 0) via sym->defined, and preserve bit_size = -1 on arrays of incomplete types.
- Preserve unsigned integer index offsets in evaluate_ptr_add() and diagnose pointer addition and subtraction on incomplete types.
- Diagnose incomplete types in evaluate_alignof() and incomplete array or multi-dimensional VLA types in evaluate_generic_selection().
- Guard null index types in evaluate_offsetof(), null current_fn in check_label_declaration(), and symbolic '[...]' asm constraints.
- Preserve noderef and nocast qualifiers across conditional pointer targets and check pointee MOD_NOCAST on pointer casts.
--- evaluate.c | 104 ++++++++++++++++++++++++++++------ parse.c | 2 + symbol.c | 12 +++- symbol.h | 2 +- validation/eval-type-checks.c | 89 +++++++++++++++++++++++++++++ 5 files changed, 187 insertions(+), 22 deletions(-) create mode 100644 validation/eval-type-checks.c
evaluate.c +86 -18
@@ -246,6 +246,8 @@ static struct symbol *base_type(struct symbol *node, unsigned long *modp, structreturn node; } +#define MOD_IGN (MOD_QUALIFIER | MOD_FUN_ATTR) +static int is_same_type (struct expression *expr,struct symbol *new) {struct symbol *old = expr->ctype;
@@ -273,6 +275,13 @@ static int is_same_type(struct expression *expr, struct symbol *new)if (difmod ==MOD_CONST )return 0 ; } +if (old->type ==SYM_PTR && new->type ==SYM_PTR && oldas == newas && + (oldmod &MOD_NOCAST ) == (newmod &MOD_NOCAST )) { +if (!type_difference (&old->ctype, &new->ctype, +MOD_IGN |MOD_NODEREF ,MOD_IGN |MOD_NODEREF ) || + ((oldmod &MOD_NOCAST ) &&is_void_type (new->ctype.base_type))) +return 0 ; + }if ((oldmod | newmod) &MOD_NOCAST ) {const char *tofrom ="to/from" ;if (!(newmod &MOD_NOCAST ))
@@ -588,6 +597,10 @@ static struct symbol *evaluate_ptr_add(struct expression *expr, struct symbol *iexpression_error (expr,"arithmetics on pointers to functions" );return NULL ; } +if (!is_void_type (base) && base->bit_size <0 ) { +expression_error (expr,"arithmetics on pointers to incomplete type" ); +return NULL ; + }/* Get the size of whatever the pointer points to */ multiply =is_void_type (base) ?1 :bits_to_bytes (base->bit_size);
@@ -603,10 +616,10 @@ static struct symbol *evaluate_ptr_add(struct expression *expr, struct symbol *istruct expression *val =alloc_expression (expr->pos,EXPR_VALUE );unsigned long long v = index->value, mask; mask =sign_bit (itype->bit_size); -if (v & mask) +if (!(itype->ctype.modifiers &MOD_UNSIGNED ) && (v & mask)) v |= -mask;else - v &= mask -1 ; + v &= mask | (mask -1 ); v *= multiply; v &=bits_mask (bits_in_pointer); val->value = v;
@@ -638,8 +651,6 @@ static struct symbol *evaluate_ptr_add(struct expression *expr, struct symbol *istatic void examine_fn_arguments (struct symbol *fn); -#define MOD_IGN (MOD_QUALIFIER | MOD_FUN_ATTR) -const char *type_difference (struct ctype *c1,struct ctype *c2,unsigned long mod1,unsigned long mod2) {
@@ -812,6 +823,14 @@ static unsigned long target_qualifiers(struct symbol *type)return mod; } +static unsigned long cond_target_qualifiers (struct symbol *type) +{ +unsigned long mod = type->ctype.modifiers & (MOD_IGN |MOD_NODEREF |MOD_NOCAST ); +if (type->ctype.base_type && type->ctype.base_type->type ==SYM_ARRAY ) + mod =0 ; +return mod; +} +static struct symbol *evaluate_ptr_sub (struct expression *expr) {const char *typediff;
@@ -835,6 +854,10 @@ static struct symbol *evaluate_ptr_sub(struct expression *expr)expression_error (expr,"subtraction of functions? Share your drugs" );return NULL ; } +if (!is_void_type (lbase) && lbase->bit_size <0 ) { +expression_error (expr,"subtraction of pointers to incomplete type" ); +return NULL ; + } expr->ctype = ssize_t_ctype;if (lbase->bit_size > bits_in_char) {
@@ -1222,7 +1245,7 @@ static struct symbol *evaluate_conditional_expression(struct expression *expr)/* need to be lazier here */ lbase =examine_pointer_target (ltype); rbase =examine_pointer_target (rtype); - qual =target_qualifiers (ltype) |target_qualifiers (rtype); + qual =cond_target_qualifiers (ltype) |cond_target_qualifiers (rtype);if (lbase == &void_ctype) {/* XXX: pointers to function should warn here */
@@ -1433,8 +1456,8 @@ static int check_assignment_types(struct symbol *target, struct expression **rp, } b1 =examine_pointer_target (t); b2 =examine_pointer_target (s); - mod1 = t->ctype.modifiers &MOD_IGN ; - mod2 = s->ctype.modifiers &MOD_IGN ; + mod1 = t->ctype.modifiers & (MOD_IGN |MOD_NODEREF ); + mod2 = s->ctype.modifiers & (MOD_IGN |MOD_NODEREF );if (whitelist_pointers (b1, b2)) {/* * assignments to/from void * are OK, provided that
@@ -2310,14 +2333,32 @@ static struct symbol *evaluate_ptrsizeof(struct expression *expr)return size_t_ctype; } +static bool is_incomplete_alignof_type (struct symbol *type,bool is_type) +{ +while (type && type->type ==SYM_NODE ) + type = type->ctype.base_type; +while (type && type->type ==SYM_ARRAY ) { +if (is_type && !type->array_size) +return true; + type = type->ctype.base_type; +while (type && type->type ==SYM_NODE ) + type = type->ctype.base_type; + } +return !type || (type->bit_size <0 && type->type !=SYM_FN ); +} +static struct symbol *evaluate_alignof (struct expression *expr) {struct symbol *type; +bool is_type = expr->cast_type !=NULL ; type =evaluate_type_information (expr);if (!type)return NULL ; +if (is_incomplete_alignof_type (type, is_type)) +expression_error (expr,"cannot size alignment of incomplete type" ); + expr->type =EXPR_VALUE ; expr->value = type->ctype.alignment; expr->taint =0 ;
@@ -3268,7 +3309,11 @@ static struct symbol *evaluate_offsetof(struct expression *expr)struct expression *idx = expr->index, *m;struct symbol *i_type =evaluate_expression (idx);unsigned old_idx_flags; -int i_class =classify_type (i_type, &i_type); +int i_class; + +if (!i_type) +return NULL ; + i_class =classify_type (i_type, &i_type);if (!is_int (i_class)) {expression_error (expr,"non-integer index" );
@@ -3316,7 +3361,8 @@ static void check_label_declaration(struct position pos, struct symbol *label)sparse_error (pos,"label '%s' was not declared" ,show_ident (label->ident));/* fallthrough */ case NS_NONE : - current_fn->bogus_linear =1 ; +if (current_fn) + current_fn->bogus_linear =1 ;default :break ; }
@@ -3337,10 +3383,14 @@ static struct symbol *evaluate_generic_selection(struct expression *expr)struct symbol source;struct symbol *ctrl; -if (!evaluate_expression (expr->control)) +if (!evaluate_expression (expr->control)) { + expr->ctype = &bad_ctype;return NULL ; -if (!(ctrl =degenerate (expr->control))) + } +if (!(ctrl =degenerate (expr->control))) { + expr->ctype = &bad_ctype;return NULL ; + } source = *ctrl; source.ctype.modifiers &= ~(MOD_QUALIFIER |MOD_ATOMIC );
@@ -3352,18 +3402,31 @@ static struct symbol *evaluate_generic_selection(struct expression *expr)continue ; base = stype->ctype.base_type; -if (base->type ==SYM_ARRAY && base->array_size) { -get_expression_value_silent (base->array_size); -if (base->array_size->type ==EXPR_VALUE ) +if (base && base->type ==SYM_ARRAY ) { +bool is_vla = false; +struct symbol *arr = base; +while (arr && arr->type ==SYM_ARRAY ) { +if (arr->array_size) { +get_expression_value_silent (arr->array_size); +if (arr->array_size->type !=EXPR_VALUE ) { + is_vla = true; +break ; + } + } + arr = arr->ctype.base_type; +while (arr && arr->type ==SYM_NODE ) + arr = arr->ctype.base_type; + } +if (is_vla) { +sparse_error (stype->pos,"variable length array type in generic selection" );continue ; -sparse_error (stype->pos,"variable length array type in generic selection" ); -continue ; + } }if (is_func_type (stype)) {sparse_error (stype->pos,"function type in generic selection" );continue ; } -if (stype->bit_size <=0 ||is_void_type (stype)) { +if (stype->bit_size <0 ||is_void_type (stype)) {sparse_error (stype->pos,"incomplete type in generic selection" );continue ; }
@@ -3376,6 +3439,7 @@ static struct symbol *evaluate_generic_selection(struct expression *expr) res = expr->def;if (!res) {sparse_error (expr->pos,"no generic selection for '%s'" ,show_typename (ctrl)); + expr->ctype = &bad_ctype;return NULL ; }
@@ -3682,7 +3746,11 @@ static void parse_asm_constraint(struct asm_operand *op)break ;case '[' :// FIXME: symbolic matching constraint -return ; +while (*str && *str !=']' ) + str++; +if (*str ==']' ) + str++; +break ;default :if (arch_target->asm_constraint)
parse.c +2 -0
@@ -791,6 +791,8 @@ static struct token *struct_union_enum_specifier(enum type type, token =parse (token->next, sym); token =expect (token,'}' ,"at end of specifier" ); + sym->defined =1 ; + sym->examined =0 ; attr.ctype.base_type = sym; token =handle_attributes (token, &attr);apply_ctype (token->pos, &sym->ctype, &attr.ctype);
symbol.c +9 -3
@@ -215,6 +215,11 @@ static struct symbol * examine_struct_union_type(struct symbol *sym, int advancevoid (*fn)(struct symbol *,struct struct_union_info *);struct symbol *member; +if (!sym->defined) { + sym->bit_size =-1 ; +return sym; + } + fn = advance ? lay_out_struct : lay_out_union; FOR_EACH_PTR(sym->symbol_list, member) {if (member->ctype.base_type == &autotype_ctype) {
@@ -298,9 +303,10 @@ static struct symbol * examine_array_type(struct symbol *sym)if (!base_type)return sym; -if (array_size) { - bit_size =array_element_offset (base_type->bit_size, -get_expression_value_silent (array_size)); +if (array_size) { +unsigned long count =get_expression_value_silent (array_size); +if (base_type->bit_size >=0 ) + bit_size =array_element_offset (base_type->bit_size, count);if (array_size->type !=EXPR_VALUE ) {if (Wvla)warning (array_size->pos,"Variable length array is used." );
symbol.h +1 -1
@@ -149,7 +149,7 @@ struct symbol_op {struct symbol {enum type type:8 ;enum namespace namespace:9 ; -unsigned char used:1 , attr:2 , enum_member:1 , bound:1 ; +unsigned char used:1 , attr:2 , enum_member:1 , bound:1 , defined:1 ;struct position pos;/* Where this symbol was declared */ struct position endpos;/* Where this symbol ends*/ struct ident *ident;/* What identifier this symbol is associated with */
validation/eval-type-checks.c new file +89 -0
89 lines not on this page · raw message
PATCH 13/73 expand: Fix static initializer folding and floating-point casts
In reply to Bart Van AsscheFix constant folding and numeric conversions in expand.c:
- Avoid folding writable or volatile static objects and negative offsets in constant_symbol_value(), and guard volatile or bitfield dereferences in expand_dereference().
- Preserve unsigned integer-to-float and float-to-integer conversions in cast_value() while guarding against out-of-range and NaN host casts.
- Add regression test validation/expand-const-and-float.c.
--- expand.c | 76 ++++++++++++++++++++++++++--- validation/expand-const-and-float.c | 73 +++++++++++++++++++++++++++ 2 files changed, 143 insertions(+), 6 deletions(-) create mode 100644 validation/expand-const-and-float.c
expand.c +70 -6
@@ -97,6 +97,11 @@ void cast_value(struct expression *expr, struct symbol *newtype, struct expressiif (is_float_type (newtype) ||is_float_type (oldtype)) goto Float; +if (!is_bool_type (newtype) && new_size >64 && old_size >=64 && + new_size > old_size && (oldtype->ctype.modifiers &MOD_UNSIGNED ) && + (old->value & (1ULL <<63 ))) +return ; +// For pointers and integers, we can just move the value around expr->type =EXPR_VALUE ; expr->taint = old->taint;
@@ -144,16 +149,60 @@ Int: Float:if (!is_float_type (newtype)) { - value = (long long )old->fvalue; +long double fval = old->fvalue; + +if (is_bool_type (newtype)) { + expr->type =EXPR_VALUE ; + expr->taint =0 ; + expr->ctype = newtype; + expr->value = (fval !=0 ); +return ; + } +if (new_size <=0 || new_size >64 || !__builtin_isfinite (fval)) +return ; +if (newtype->ctype.modifiers &MOD_UNSIGNED ) { +unsigned long long uval; +if (!(fval >-1.0L && fval <0x1p64L )) +return ; + uval = (fval <=0.0L ) ?0ULL : (unsigned long long )fval; +if (new_size <64 && uval >= (1ULL << new_size)) +return ; + value = (long long )uval; + }else { +unsigned long long lim =1ULL << (new_size -1 ); +unsigned long long umag; +if (fval >=0.0L ) { +if (!(fval <0x1p63L )) +return ; + umag = (unsigned long long )fval; +if (umag >= lim) +return ; + value = (long long )umag; + }else { +long double mag = -fval; +if (!(mag <0x1p64L )) +return ; + umag = (unsigned long long )mag; +if (umag > lim) +return ; + value = (long long )(0ULL - umag); + } + } expr->type =EXPR_VALUE ; expr->taint =0 ; expr->ctype = newtype; goto Int; } -if (!is_float_type (oldtype)) - expr->fvalue = (long double )get_longlong (old); -else +if (!is_float_type (oldtype)) { +if ((oldtype->ctype.modifiers &MOD_UNSIGNED ) && + old_size >64 && (old->value & (1ULL <<63 ))) +return ; +if (oldtype->ctype.modifiers &MOD_UNSIGNED ) + expr->fvalue = (long double )(unsigned long long )get_longlong (old); +else + expr->fvalue = (long double )get_longlong (old); + }else expr->fvalue = old->fvalue;if (newtype->rank <=0 ) {
@@ -200,6 +249,8 @@ static int simplify_int_binop(struct expression *expr, struct symbol *ctype) }if (left->type !=EXPR_VALUE )return 0 ; +if (!ctype || ctype->bit_size <=0 || ctype->bit_size >64 ) +return 0 ; l = left->value; r = right->value; is_signed = !(ctype->ctype.modifiers &MOD_UNSIGNED ); mask =sign_bit (ctype->bit_size);
@@ -305,6 +356,8 @@ static int simplify_cmp_binop(struct expression *expr, struct symbol *ctype)if (left->type !=EXPR_VALUE || right->type !=EXPR_VALUE )return 0 ; +if (!ctype || ctype->bit_size <=0 || ctype->bit_size >64 ) +return 0 ; l = left->value; r = right->value; mask =sign_bit (ctype->bit_size); sl = l; sr = r;
@@ -665,8 +718,16 @@ static struct expression *constant_symbol_value(struct symbol *sym, int offset) {struct expression *value; +if (offset <0 ) +return NULL ; +if (sym->ctype.modifiers &MOD_VOLATILE ) +return NULL ;if (sym->ctype.modifiers &MOD_ACCESS )return NULL ; +if ((sym->ctype.modifiers & (MOD_TOPLEVEL |MOD_STATIC )) && + !(sym->ctype.modifiers &MOD_CONST ) && + !sym->string && sym->ident) +return NULL ; value = sym->initializer;if (!value)return NULL ;
@@ -707,6 +768,8 @@ static int expand_dereference(struct expression *expr)*/ if (expr->ctype->ctype.modifiers &MOD_NODEREF )warning (unop->pos,"dereference of noderef expression" ); +if (expr->ctype->ctype.modifiers &MOD_VOLATILE ) +return SIDE_EFFECTS ;/* * Is it "symbol" or "symbol + offset"?
@@ -732,7 +795,7 @@ static int expand_dereference(struct expression *expr)if (value->type ==EXPR_VALUE ) {if (!is_integral_type (ctype))return UNSAFE ; -if (is_bitfield_type (value->ctype)) +if (is_bitfield_type (ctype) ||is_bitfield_type (value->ctype))return UNSAFE ; expr->type =EXPR_VALUE ; expr->value = value->value;
@@ -866,7 +929,8 @@ static int expand_cast(struct expression *expr)/* Simplify normal integer casts.. */ if (target->type ==EXPR_VALUE || target->type ==EXPR_FVALUE ) {cast_value (expr, expr->ctype, target); -return 0 ; +if (expr->type ==EXPR_VALUE || expr->type ==EXPR_FVALUE ) +return 0 ; }return cost +1 ; }
validation/expand-const-and-float.c new file +73 -0
73 lines not on this page · raw message
PATCH 14/73 inline: Copy union cast types and VLA bounds when inlining
In reply to Bart Van AsscheDuplicate union EXPR_CAST target symbols and clone variable-length array SYM_ARRAY chains in inline.c so that union casts and VLA dimension expressions inside inlined functions do not share or mutate symbols across call sites.
Add regression tests in validation/eval-expand-inline-fixes.c and validation/eval-ptr-incomplete-and-inline.c.
--- inline.c | 101 ++++++++++++++++++-- validation/eval-expand-inline-fixes.c | 49 ++++++++++ validation/eval-ptr-incomplete-and-inline.c | 70 ++++++++++++++ 3 files changed, 213 insertions(+), 7 deletions(-) create mode 100644 validation/eval-expand-inline-fixes.c create mode 100644 validation/eval-ptr-incomplete-and-inline.c
inline.c +94 -7
@@ -35,6 +35,7 @@#include "evaluate.h" static void copy_statement (struct statement *src,struct statement *dst); +static struct expression *copy_expression (struct expression *expr);static struct expression *dup_expression (struct expression *expr) {
@@ -63,6 +64,64 @@ static struct symbol *copy_symbol(struct position pos, struct symbol *sym)return sym->replace; } +static struct symbol *copy_type (struct symbol *type) +{ +if (!type) +return NULL ; +switch (type->type) { +case SYM_NODE : { +struct symbol *base =copy_type (type->ctype.base_type); +struct symbol *n; +if (base == type->ctype.base_type) +return type; + n =alloc_symbol (type->pos,SYM_NODE ); + *n = *type; + n->ctype.base_type = base; +if (base && base->bit_size <0 ) + n->examined =0 ; +return n; + } +case SYM_ARRAY : { +struct symbol *elem =copy_type (type->ctype.base_type); +struct expression *size =copy_expression (type->array_size); +struct symbol *arr; +if (elem == type->ctype.base_type && size == type->array_size && !type->array_size) +return type; + arr =alloc_symbol (type->pos,SYM_ARRAY ); + *arr = *type; + arr->ctype.base_type = elem; + arr->array_size = size; +if (type->array_size || elem != type->ctype.base_type) + arr->examined =0 ; +return arr; + } +case SYM_PTR : { +struct symbol *base =copy_type (type->ctype.base_type); +struct symbol *ptr; +if (base == type->ctype.base_type) +return type; + ptr =alloc_symbol (type->pos,SYM_PTR ); + *ptr = *type; + ptr->ctype.base_type = base; +return ptr; + } +case SYM_TYPEOF : +case SYM_TYPEOF_UNQUAL : { +struct expression *init =copy_expression (type->initializer); +struct symbol *t; +if (init == type->initializer) +return type; + t =alloc_symbol (type->pos, type->type); + *t = *type; + t->initializer = init; + t->examined =0 ; +return t; + } +default : +return type; + } +} +static struct symbol_list *copy_symbol_list (struct symbol_list *src) {struct symbol_list *dst =NULL ;
@@ -155,11 +214,19 @@ static struct expression * copy_expression(struct expression *expr)/* Cast/sizeof/__alignof__ */ case EXPR_CAST : -if (!expr->cast_expression) -return NULL ; -if (expr->cast_expression->type ==EXPR_INITIALIZER ) { +if (!expr->cast_expression) { +struct symbol *cast_type =copy_type (expr->cast_type); +if (cast_type != expr->cast_type) { + expr =dup_expression (expr); + expr->cast_type = cast_type; + } +return expr; + } +if (expr->cast_expression->type ==EXPR_INITIALIZER || + (expr->cast_type && expr->cast_type->ctype.base_type && + expr->cast_type->ctype.base_type->type ==SYM_UNION )) {struct expression *cast = expr->cast_expression; -struct symbol *sym = expr->cast_type; +struct symbol *sym =copy_type (expr->cast_type); expr =dup_expression (expr); expr->cast_expression =copy_expression (cast); expr->cast_type =alloc_symbol (sym->pos, sym->type);
@@ -172,10 +239,12 @@ static struct expression * copy_expression(struct expression *expr)case EXPR_PTRSIZEOF :case EXPR_ALIGNOF : {struct expression *cast =copy_expression (expr->cast_expression); -if (cast == expr->cast_expression) +struct symbol *cast_type =copy_type (expr->cast_type); +if (cast == expr->cast_expression && cast_type == expr->cast_type)break ; expr =dup_expression (expr); expr->cast_expression = cast; + expr->cast_type = cast_type;break ; }
@@ -343,8 +412,10 @@ static struct statement *copy_one_statement(struct statement *stmt) newstmt->declaration =NULL ; FOR_EACH_PTR(stmt->declaration, sym) {struct symbol *newsym =copy_symbol (stmt->pos, sym); -if (newsym != sym) +if (newsym != sym) { + newsym->ctype.base_type =copy_type (newsym->ctype.base_type); newsym->initializer =copy_expression (sym->initializer); + }add_symbol (&newstmt->declaration, newsym); }END_FOR_EACH_PTR (sym); stmt = newstmt;
@@ -424,10 +495,20 @@ static struct statement *copy_one_statement(struct statement *stmt)break ; }case STMT_ITERATOR : { +struct symbol_list *old_syms = stmt->iterator_syms; +struct symbol *sym; stmt =dup_statement (stmt); stmt->iterator_break =copy_symbol (stmt->pos, stmt->iterator_break); stmt->iterator_continue =copy_symbol (stmt->pos, stmt->iterator_continue); - stmt->iterator_syms =copy_symbol_list (stmt->iterator_syms); + stmt->iterator_syms =NULL ; + FOR_EACH_PTR(old_syms, sym) { +struct symbol *newsym =copy_symbol (stmt->pos, sym); +if (newsym != sym) { + newsym->ctype.base_type =copy_type (newsym->ctype.base_type); + newsym->initializer =copy_expression (sym->initializer); + } +add_symbol (&stmt->iterator_syms, newsym); + }END_FOR_EACH_PTR (sym); stmt->iterator_pre_statement =copy_one_statement (stmt->iterator_pre_statement); stmt->iterator_pre_condition =copy_expression (stmt->iterator_pre_condition);
@@ -542,6 +623,8 @@ int inline_function(struct expression *expr, struct symbol *sym)if (name) { *a = *name; + a->bb_target =NULL ; + a->pseudo =NULL ;set_replace (name, a);add_symbol (&fn_symbol_list, a); a->initializer = arg;
@@ -557,6 +640,10 @@ int inline_function(struct expression *expr, struct symbol *sym) }END_FOR_EACH_PTR (arg);FINISH_PTR_LIST (name); + FOR_EACH_PTR(arg_decl, name) { + name->ctype.base_type =copy_type (name->ctype.base_type); + }END_FOR_EACH_PTR (name); +copy_statement (fn->inline_stmt, stmt);if (arg_decl) {
validation/eval-expand-inline-fixes.c new file +49 -0
49 lines not on this page · raw message
validation/eval-ptr-incomplete-and-inline.c new file +70 -0
70 lines not on this page · raw message
PATCH 15/73 linearize, flow: Fix asm operands, switch case bounds, and DSE
In reply to Bart Van AsscheFix IR linearization and dead-store elimination issues in flow.c and linearize.c:
- Continue scanning past OP_CALL for non-escaping locals while stopping at OP_ASM in kill_dead_stores_bb().
- Enlarge show_pseudo() formatting buffers and replace sprintf() with bounded snprintf().
- Guard VOID phi sources in linearize_logical(), register read-write '+r' asm outputs as inputs, guard non-string asm clobbers, and extend switch case values to the controlling expression width.
- Add regression test validation/linear/control-flow-fixes.c.
--- flow.c | 3 ++ linearize.c | 46 ++++++++++++++++---------- validation/linear/control-flow-fixes.c | 44 ++++++++++++++++++++++++ 3 files changed, 75 insertions(+), 18 deletions(-) create mode 100644 validation/linear/control-flow-fixes.c
flow.c +3 -0
@@ -518,6 +518,9 @@ static void kill_dead_stores_bb(pseudo_t pseudo, unsigned long generation, struccase OP_CALL :if (!local)return ; +continue ; +case OP_ASM : +return ;default :continue ; }
linearize.c +28 -18
119 lines not on this page · raw message
validation/linear/control-flow-fixes.c new file +44 -0
44 lines not on this page · raw message
PATCH 16/73 memops, ssa: Walk parent insns in reverse and skip mixed-size SSA
In reply to Bart Van AsscheFix dominated-store elimination and SSA promotion in memops.c and ssa.c:
- Walk parent basic block instructions in reverse order in kill_dominated_stores() so intervening loads or calls after a dominating store are visited before the store itself.
- Skip SSA promotion in ssa_convert_one_var() when loads or stores access the same variable with mixed sizes or non-zero offsets.
- Add regression test validation/optim/volatile-dse-and-cfg.c.
--- memops.c | 4 +- ssa.c | 6 +++ validation/optim/volatile-dse-and-cfg.c | 53 +++++++++++++++++++++++++ 3 files changed, 61 insertions(+), 2 deletions(-) create mode 100644 validation/optim/volatile-dse-and-cfg.c
memops.c +2 -2
@@ -252,14 +252,14 @@ static void kill_dominated_stores(struct basic_block *bb)if (bb_list_size (par->children) !=1 ) goto next_parent; - FOR_EACH_PTR(par->insns, dom) { + FOR_EACH_PTR_REVERSE(par->insns, dom) {if (!dom->bb)continue ;if (dom == insn) goto next_parent;if (!try_to_kill_store (insn, dom, local)) goto next_parent; - }END_FOR_EACH_PTR (dom); + }END_FOR_EACH_PTR_REVERSE (dom); next_parent: ; }END_FOR_EACH_PTR (par);
ssa.c +6 -0
@@ -139,6 +139,7 @@ static void ssa_convert_one_var(struct entrypoint *ep, struct symbol *var)bool local = true;int nbr_stores =0 ;int nbr_uses =0 ; +bool same_size = true;pseudo_t addr;/* Never used as a symbol? */
@@ -172,6 +173,8 @@ static void ssa_convert_one_var(struct entrypoint *ep, struct symbol *var) }/* fall through */ case OP_LOAD : +if (insn->size != var->bit_size || insn->offset !=0 ) + same_size = false;if (local) {if (!samebb) samebb = bb;
@@ -197,6 +200,9 @@ static void ssa_convert_one_var(struct entrypoint *ep, struct symbol *var)return ; } +if (!same_size) + goto external_visibility; +idf_compute (ep, &idf, alpha); FOR_EACH_PTR(idf, bb) {struct instruction *node =insert_phi_node (bb, var);
validation/optim/volatile-dse-and-cfg.c new file +53 -0
53 lines not on this page · raw message
PATCH 17/73 simplify: Prevent overflow on LLONG_MIN negation and fix simplifications
In reply to Bart Van AsscheAvoid undefined integer overflow and invalid IR transformations in linearize.h and simplify.c:
- Check that operand and instruction sizes do not exceed 64 bits before evaluating 64-bit constant simplifications or calling eval_op() and eval_unop().
- Use bits_mask(), sign_extend(), and zero_extend() instead of open-coded 64-bit shifts to avoid undefined shift overflow on 64-bit types.
- Check for null pseudo pointers in DEF_OPCODE(), canonical_order(), and simplification helpers before dereferencing operands.
- Update CFG edges and phi sources accurately in simplify_cgoto().
- Add regression test validation/optim/simplify-memops-ssa-fixes.c.
--- linearize.h | 2 +- simplify.c | 225 ++++++++++++++----- validation/optim/simplify-memops-ssa-fixes.c | 103 +++++++++ 3 files changed, 278 insertions(+), 52 deletions(-) create mode 100644 validation/optim/simplify-memops-ssa-fixes.c
linearize.h +1 -1
@@ -187,7 +187,7 @@ struct basic_block {// and OP_BADOP if not. It also assigns the defining instruction // to ``DEF``. #define DEF_OPCODE (DEF ,SRC ) \ - (((SRC)->type == PSEUDO_REG && (DEF = (SRC)->def)) ? DEF->opcode : OP_BADOP) + (((SRC) && (SRC)->type == PSEUDO_REG && (DEF = (SRC)->def)) ? DEF->opcode : OP_BADOP)static inline void add_bb (struct basic_block_list **list,struct basic_block *bb)
simplify.c +174 -51
540 lines not on this page · raw message
validation/optim/simplify-memops-ssa-fixes.c new file +103 -0
103 lines not on this page · raw message
PATCH 18/73 sparse: Gate context failure warning on Wcontext and catch underflow
In reply to Bart Van AsscheGate "context check failure" diagnostics on Wcontext in context_increase() and return early as soon as entry + sum drops below zero so an unexpected unlock followed by a lock in the same basic block still triggers a context imbalance warning.
Add regression test validation/context-fixes.c.
--- sparse.c | 5 ++++- validation/context-fixes.c | 41 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 validation/context-fixes.c
sparse.c +4 -1
@@ -59,10 +59,13 @@ static int context_increase(struct basic_block *bb, int entry)continue ; }else if (current >= val)continue ; -warning (insn->pos,"context check failure" ); +if (Wcontext) +warning (insn->pos,"context check failure" );continue ; } sum += val; +if (entry + sum <0 ) +return sum; }END_FOR_EACH_PTR (insn);return sum; }
validation/context-fixes.c new file +41 -0
41 lines not on this page · raw message
PATCH 19/73 ast-model: Return AST_N_COLUMNS and inspect child nodes lazily
In reply to Bart Van AsscheReturn AST_N_COLUMNS instead of 1 from ast_get_n_columns() so GtkTreeModel exposes the full column count to GTK tree views.
Populate child nodes lazily via inspect_child_node() and reject negative indices in ast_iter_nth_child() before indexing node->childnodes.
--- ast-model.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-)
ast-model.c +6 -3
@@ -227,7 +227,7 @@ ast_get_flags(GtkTreeModel *tree_model)static gint ast_get_n_columns (GtkTreeModel *tree_model) { -return 1 ; +return AST_N_COLUMNS ; }
@@ -427,8 +427,11 @@ ast_iter_nth_child(GtkTreeModel *tree_model, gint n) {AstNode *node = parent ? parent->user_data : (AstNode *) tree_model; -GArray *array = node->childnodes; -if (n >= array->len) +GArray *array; + +inspect_child_node (node); + array = node->childnodes; +if (n <0 || n >= array->len)return FALSE; iter->user_data = g_array_index(array, AstNode *, n);return TRUE;
PATCH 20/73 c2xml: Guard against recursive symbols and free xmlGetProp() string
In reply to Bart Van AsscheReturn early in examine_namespace() when sym->aux is already populated so mutually recursive struct definitions do not trigger infinite recursion.
Guard sym->ctype.base_type->aux in examine_symbol() and release the string allocated by xmlGetProp() with xmlFree() after xmlNewProp() copies it so analyzing recursive struct types does not leak memory under LeakSanitizer.
Add a regression test in validation/c2xml-recursive-types.c.
--- c2xml.c | 11 +++++++++-- validation/c2xml-recursive-types.c | 15 +++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) create mode 100644 validation/c2xml-recursive-types.c
c2xml.c +9 -2
@@ -190,8 +190,13 @@ static void examine_symbol(struct symbol *sym, xmlNodePtr node)if (!sym->ctype.base_type->aux) {examine_symbol (sym->ctype.base_type, root_node); } -xmlNewProp (child,BAD_CAST "base-type" , -xmlGetProp ((xmlNodePtr )sym->ctype.base_type->aux,BAD_CAST "id" )); +if (sym->ctype.base_type->aux) { +xmlChar *base_id =xmlGetProp ((xmlNodePtr )sym->ctype.base_type->aux,BAD_CAST "id" ); +if (base_id) { +xmlNewProp (child,BAD_CAST "base-type" , base_id); +xmlFree (base_id); + } + } }else {newProp (child,"base-type-builtin" , base); }
@@ -250,6 +255,8 @@ static void examine_macro(struct symbol *sym, xmlNodePtr node)static void examine_namespace (struct symbol *sym) { +if (sym->aux)/*already visited */ +return ;if (sym->ident && sym->ident->reserved)return ;
validation/c2xml-recursive-types.c new file +15 -0
@@ -0,0 +1,15 @@ +struct B ; +struct A { +struct B *b; +}; +struct B { +struct A *a; +}; + +/* +* check-name: c2xml-recursive-types +* check-command: c2xml $file +* check-output-ignore +* check-output-contains: <symbol type="struct".*ident="A" +* check-output-contains: <symbol type="struct".*ident="B" +*/
PATCH 21/73 compile-i386: Fix buffer bounds, unsigned '<=' codegen, and null checks
In reply to Bart Van AsscheHarden x86 code generation in compile-i386.c:
- Enlarge fixed formatting buffers and replace strcpy()/sprintf() calls with bounded snprintf() in stor_op_name(), emit_insn_atom(), and emit_global_noinit().
- Guard against zero-length array division by zero in emit_initializer() and use sym->bit_size / 8 directly in emit_array_noinit().
- Emit 'setbe' instead of 'setb' for SPECIAL_UNSIGNED_LTE in emit_compare().
- Handle SYM_PTR scalar initializers and guard current_func and stmt->goto_label before dereferencing them.
--- compile-i386.c | 76 ++++++++++++++++++++++++++++---------------------- 1 file changed, 43 insertions(+), 33 deletions(-)
compile-i386.c +43 -33
@@ -434,30 +434,30 @@ static void stor_sym_init(struct symbol *sym)static const char *stor_op_name (struct storage *s) { -static char name[32 ]; +static char name[256 ];switch (s->type) {case STOR_PSEUDO : -strcpy (name,pretty_offset ((int )pseudo_offset (s))); +snprintf (name,sizeof (name),"%s" ,pretty_offset ((int )pseudo_offset (s)));break ;case STOR_ARG : -strcpy (name,pretty_offset ((int )arg_offset (s))); +snprintf (name,sizeof (name),"%s" ,pretty_offset ((int )arg_offset (s)));break ;case STOR_SYM : -strcpy (name,show_ident (s->sym->ident)); +snprintf (name,sizeof (name),"%s" ,show_ident (s->sym->ident));break ;case STOR_REG : -strcpy (name, s->reg->name); +snprintf (name,sizeof (name),"%s" , s->reg->name);break ;case STOR_VALUE : -sprintf (name,"$%lld" , s->value); +snprintf (name,sizeof (name),"$%lld" , s->value);break ;case STOR_LABEL : -sprintf (name,"%s.L%d" , s->flags &STOR_LABEL_VAL ?"$" :"" , +snprintf (name,sizeof (name),"%s.L%d" , s->flags &STOR_LABEL_VAL ?"$" :"" , s->label);break ;case STOR_LABELSYM : -sprintf (name,"%s.LS%p" , s->flags &STOR_LABEL_VAL ?"$" :"" , +snprintf (name,sizeof (name),"%s.LS%p" , s->flags &STOR_LABEL_VAL ?"$" :"" , s->labelsym);break ; }
@@ -707,27 +707,27 @@ static void emit_section(const char *s)static void emit_insn_atom (struct function *f,struct atom *atom) { -char s[128 ]; -char comment[64 ]; +char s[512 ]; +char comment[128 ];struct storage *op1 = atom->op1;struct storage *op2 = atom->op2;if (atom->comment[0 ]) -sprintf (comment,"\t\t# %s" , atom->comment); +snprintf (comment,sizeof (comment),"\t\t# %s" , atom->comment);else comment[0 ] =0 ;if (atom->op2) { -char tmp[16 ]; -strcpy (tmp,stor_op_name (op1)); -sprintf (s,"\t%s\t%s, %s%s\n" , +char tmp[256 ]; +snprintf (tmp,sizeof (tmp),"%s" ,stor_op_name (op1)); +snprintf (s,sizeof (s),"\t%s\t%s, %s%s\n" , atom->insn, tmp,stor_op_name (op2), comment); }else if (atom->op1) -sprintf (s,"\t%s\t%s%s%s\n" , +snprintf (s,sizeof (s),"\t%s\t%s%s%s\n" , atom->insn,stor_op_name (op1), comment[0 ] ?"\t" :"" , comment);else -sprintf (s,"\t%s\t%s%s\n" , +snprintf (s,sizeof (s),"\t%s\t%s%s\n" , atom->insn, comment[0 ] ?"\t\t" :"" , comment);
@@ -941,16 +941,16 @@ static void emit_scalar(struct expression *expr, unsigned int bit_size)static void emit_global_noinit (const char *name,unsigned long modifiers,unsigned long alignment,unsigned int byte_size) { -char s[64 ]; +char s[256 ];if (modifiers &MOD_STATIC ) { -sprintf (s,"\t.local\t%s\n" , name); +snprintf (s,sizeof (s),"\t.local\t%s\n" , name);textbuf_push (&unit_post_text, s); }if (alignment) -sprintf (s,"\t.comm\t%s,%d,%lu\n" , name, byte_size, alignment); +snprintf (s,sizeof (s),"\t.comm\t%s,%d,%lu\n" , name, byte_size, alignment);else -sprintf (s,"\t.comm\t%s,%d\n" , name, byte_size); +snprintf (s,sizeof (s),"\t.comm\t%s,%d\n" , name, byte_size);textbuf_push (&unit_post_text, s); }
@@ -966,9 +966,14 @@ static void emit_initializer(struct symbol *sym,if (expr->type ==EXPR_VALUE ) {struct symbol *base_type = sym->ctype.base_type; +long long nr;assert (base_type !=NULL ); -emit_scalar (expr, sym->bit_size /get_expression_value (base_type->array_size)); + nr =get_expression_value (base_type->array_size); +if (nr >0 ) +emit_scalar (expr, sym->bit_size / nr); +else if (base_type->ctype.base_type && base_type->ctype.base_type->bit_size >0 ) +emit_scalar (expr, base_type->ctype.base_type->bit_size);return ; }if (expr->type !=EXPR_INITIALIZER )
@@ -1129,7 +1134,7 @@ static void emit_array_noinit(struct symbol *sym) {emit_global_noinit (show_ident (sym->ident), sym->ctype.modifiers, sym->ctype.alignment, -get_expression_value (sym->array_size) * (sym->bit_size /8 )); + sym->bit_size /8 );stor_sym_init (sym); }
@@ -1249,7 +1254,7 @@ static struct storage *emit_compare(struct expression *expr)case SPECIAL_UNSIGNED_GT : opname ="seta" ;break ;case SPECIAL_UNSIGNED_LTE : - opname ="setb" ;break ; + opname ="setbe" ;break ;case SPECIAL_UNSIGNED_GTE : opname ="setae" ;break ;default :
@@ -1820,13 +1825,16 @@ static void x86_symbol(struct symbol *sym)break ;case SYM_BASETYPE : +case SYM_PTR :if (sym->initializer) { -emit_object_pre (show_ident (sym->ident), - sym->ctype.modifiers, - sym->ctype.alignment, - sym->bit_size /8 ); -emit_scalar (sym->initializer, sym->bit_size); -stor_sym_init (sym); +if (sym->initializer->type ==EXPR_VALUE ) { +emit_object_pre (show_ident (sym->ident), + sym->ctype.modifiers, + sym->ctype.alignment, + sym->bit_size /8 ); +emit_scalar (sym->initializer, sym->bit_size); +stor_sym_init (sym); + } }else emit_scalar_noinit (sym);break ;
@@ -1857,8 +1865,8 @@ static void x86_symbol(struct symbol *sym)break ; } -if (sym->initializer && (type->type !=SYM_BASETYPE ) && - (type->type !=SYM_ARRAY )) { +if (current_func && sym->initializer && (type->type !=SYM_BASETYPE ) && + (type->type !=SYM_ARRAY ) && (type->type !=SYM_PTR )) {printf (" = \n" );x86_expression (sym->initializer); }
@@ -2039,12 +2047,14 @@ static struct storage *x86_statement(struct statement *stmt)if (stmt->goto_expression) {struct storage *val =x86_expression (stmt->goto_expression);printf ("\tgoto *v%d\n" , val->pseudo); - }else if (!strcmp ("break" ,show_ident (stmt->goto_label->ident))) { + }else if (stmt->goto_label && stmt->goto_label->ident && + !strcmp ("break" ,show_ident (stmt->goto_label->ident))) {struct storage *lbv =new_storage (STOR_LABEL ); lbv->label =loopstk_break (); lbv->flags =STOR_WANTS_FREE ;insn ("jmp" , lbv,NULL ,"'break'; go to loop bottom" ); - }else if (!strcmp ("continue" ,show_ident (stmt->goto_label->ident))) { + }else if (stmt->goto_label && stmt->goto_label->ident && + !strcmp ("continue" ,show_ident (stmt->goto_label->ident))) {struct storage *lbv =new_storage (STOR_LABEL ); lbv->label =loopstk_continue (); lbv->flags =STOR_WANTS_FREE ;
PATCH 22/73 ctags: Fix line comparison order and handle SYM_RESTRICT and SYM_LABEL
In reply to Bart Van AsscheReturn a tri-state comparison result for line numbers in cmp_sym() instead of a boolean '<' check that violates qsort()'s strict weak ordering.
Handle SYM_RESTRICT by recursing into its base type and ignore SYM_LABEL cleanly in examine_symbol().
--- ctags.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
ctags.c +3 -1
@@ -50,7 +50,7 @@ static int cmp_sym(const void *m, const void *n) ret =strcmp (stream_name (a_pos.stream),stream_name (b_pos.stream));if (!ret) -return a_pos.line < b_pos.line; +return (a_pos.line > b_pos.line) - (a_pos.line < b_pos.line); }return ret; }
@@ -155,8 +155,10 @@ static void examine_symbol(struct symbol *sym)case SYM_BITFIELD :case SYM_FN :case SYM_ARRAY : +case SYM_RESTRICT :examine_symbol (sym->ctype.base_type);break ; +case SYM_LABEL :case SYM_BASETYPE :break ;
PATCH 23/73 dissect: Unwrap array element type via base_type()
In reply to Bart Van AsscheUse base_type(in) instead of in->ctype.base_type when stepping through array subscripts in dissect.c so SYM_NODE wrappers are unwrapped properly.
--- dissect.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
dissect.c +1 -1
@@ -467,7 +467,7 @@ again: lookup_member(in, expr->ident, NULL)); }else {do_expression (U_R_VAL , expr->index); - in = in->ctype.base_type; + in =base_type (in); } }while ((expr = expr->down)); }
PATCH 24/73 example: Fix show_op() rotating buffer dimensions
In reply to Bart Van AsscheDeclare buf as char buf[4][256] instead of char buf[256][4] in show_op() so each of the 4 rotating slots holds 256 bytes instead of 4 bytes.
--- example.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
example.c +1 -1
@@ -168,7 +168,7 @@ struct operand {static const char *show_op (struct bb_state *state,struct operand *op) { -static char buf[256 ][4 ]; +static char buf[4 ][256 ];static int bufnr;char *p, *ret;int nr;
PATCH 25/73 graph: Check PSEUDO_SYM before dereferencing insn->func->sym
In reply to Bart Van AsscheVerify that insn->func->type is PSEUDO_SYM before reading insn->func->sym in graph_calls() so indirect calls through non-symbol pseudos do not read mismatched union members.
--- graph.c | 33 ++++++++++++++++----------------- 1 file changed, 16 insertions(+), 17 deletions(-)
graph.c +16 -17
@@ -135,28 +135,27 @@ static void graph_calls(struct entrypoint *ep, int internal)if (!insn->bb)continue ;if (insn->opcode ==OP_CALL && + insn->func->type ==PSEUDO_SYM && internal == !(insn->func->sym->ctype.modifiers &MOD_EXTERN )) {/* Find the symbol for the callee's definition */ struct symbol * sym; -if (insn->func->type ==PSEUDO_SYM ) { -for (sym = insn->func->sym->ident->symbols; - sym; sym = sym->next_id) { -if (sym->namespace &NS_SYMBOL && sym->ep) -break ; - } - -if (sym) -printf ("bb%p -> bb%p" -"[label=%d,line=%d,col=%d,op=call,style=bold,weight=30];\n" , - bb, sym->ep->entry->bb, - insn->pos.line, insn->pos.line, insn->pos.pos); -else -printf ("bb%p -> \"%s\" " -"[label=%d,line=%d,col=%d,op=extern,style=dashed];\n" , - bb,show_pseudo (insn->func), - insn->pos.line, insn->pos.line, insn->pos.pos); +for (sym = insn->func->sym->ident->symbols; + sym; sym = sym->next_id) { +if (sym->namespace &NS_SYMBOL && sym->ep) +break ; } + +if (sym) +printf ("bb%p -> bb%p" +"[label=%d,line=%d,col=%d,op=call,style=bold,weight=30];\n" , + bb, sym->ep->entry->bb, + insn->pos.line, insn->pos.line, insn->pos.pos); +else +printf ("bb%p -> \"%s\" " +"[label=%d,line=%d,col=%d,op=extern,style=dashed];\n" , + bb,show_pseudo (insn->func), + insn->pos.line, insn->pos.line, insn->pos.pos); } }END_FOR_EACH_PTR (insn); }END_FOR_EACH_PTR (bb);
PATCH 26/73 scheck: Fix slice() upper bit index calculation
In reply to Bart Van AsschePass new - 1 instead of old - new - 1 as the upper bit index to boolector_slice() in slice() so narrowing casts extract the low 'new' bits of the bit-vector.
--- scheck.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
scheck.c +1 -2
@@ -107,9 +107,8 @@ static BoolectorNode *sext(Btor *btor, struct instruction *insn, BoolectorNode *static BoolectorNode *slice (Btor *btor,struct instruction *insn,BoolectorNode *s) { -int old =boolector_get_width (btor, s);int new = insn->type->bit_size; -return boolector_slice (btor, s, old - new -1 ,0 ); +return boolector_slice (btor, s, new -1 ,0 ); }static void binary (Btor *btor,BoolectorSort s,struct instruction *insn)
PATCH 27/73 sparse-llvm: Support arbitrary struct member counts and fix operand types
In reply to Bart Van AsscheFix LLVM IR generation crashes and limits in sparse-llvm.c:
- Dynamically allocate elem_types in sym_struct_type() instead of asserting at 64 members, and handle zero-sized array element types in sym_array_type().
- Pass instruction operand types instead of NULL to pseudo_to_value() in output_op_compare(), output_op_cbr(), and output_op_sel().
- Read val->label_symbol instead of val->symbol for EXPR_LABEL in output_op_setval().
- Add a regression test in validation/backend/struct-large-members.c.
--- sparse-llvm.c | 23 +++---- validation/backend/struct-large-members.c | 83 +++++++++++++++++++++++ 2 files changed, 92 insertions(+), 14 deletions(-) create mode 100644 validation/backend/struct-large-members.c
sparse-llvm.c +9 -14
@@ -86,21 +86,17 @@ static LLVMTypeRef sym_array_type(struct symbol *sym)struct symbol *base_type; base_type = sym->ctype.base_type; -/* empty struct is undefined [6.7.2.1(8)] */ -assert (base_type->bit_size >0 ); - elem_type =symbol_type (base_type);if (!elem_type)return NULL ; -return LLVMArrayType (elem_type, sym->bit_size / base_type->bit_size); +return LLVMArrayType (elem_type, base_type->bit_size >0 ? sym->bit_size / base_type->bit_size :0 ); } -#define MAX_STRUCT_MEMBERS 64 -static LLVMTypeRef sym_struct_type (struct symbol *sym) { -LLVMTypeRef elem_types[MAX_STRUCT_MEMBERS ]; +unsigned n_memb =symbol_list_size (sym->symbol_list); +LLVMTypeRef *elem_types =calloc (n_memb,sizeof (LLVMTypeRef));struct symbol *member;char buffer[256 ];LLVMTypeRef ret;
@@ -114,14 +110,13 @@ static LLVMTypeRef sym_struct_type(struct symbol *sym) FOR_EACH_PTR(sym->symbol_list, member) {LLVMTypeRef member_type; -assert (nr <MAX_STRUCT_MEMBERS ); - member_type =symbol_type (member); elem_types[nr++] = member_type; }END_FOR_EACH_PTR (member);LLVMStructSetBody (ret, elem_types, nr,0 /* packed? */ ); +free (elem_types);return ret; }
@@ -663,11 +658,11 @@ static void output_op_compare(struct function *fn, struct instruction *insn)LLVMValueRef lhs, rhs, target;char target_name[64 ]; - lhs =pseudo_to_value (fn,NULL , insn->src1); + lhs =pseudo_to_value (fn, insn->itype, insn->src1);if (insn->src2->type ==PSEUDO_VAL ) rhs =constant_value (insn->src2->value,LLVMTypeOf (lhs));else - rhs =pseudo_to_value (fn,NULL , insn->src2); + rhs =pseudo_to_value (fn, insn->itype, insn->src2);if (!rhs) rhs =LLVMGetUndef (symbol_type (insn->type));
@@ -785,7 +780,7 @@ static LLVMValueRef bool_value(struct function *fn, LLVMValueRef value)static void output_op_cbr (struct function *fn,struct instruction *br) {LLVMValueRef cond =bool_value (fn, -pseudo_to_value (fn,NULL , br->cond)); +pseudo_to_value (fn, br->type ? br->type : &int_ctype, br->cond)); LLVMBuildCondBr(fn->builder, cond, br->bb_true->priv,
@@ -802,7 +797,7 @@ static void output_op_sel(struct function *fn, struct instruction *insn)LLVMValueRef target, src1, src2, src3;char name[MAX_PSEUDO_NAME ]; - src1 =bool_value (fn,pseudo_to_value (fn,NULL , insn->src1)); + src1 =bool_value (fn,pseudo_to_value (fn, insn->itype ? insn->itype : insn->type, insn->src1)); src2 =get_operand (fn, insn->type, insn->src2); src3 =get_operand (fn, insn->type, insn->src3);
@@ -1001,7 +996,7 @@ static void output_op_setval(struct function *fn, struct instruction *insn)switch (val->type) {case EXPR_LABEL : - target =LLVMBlockAddress (fn->fn, val->symbol->bb_target->priv); + target =LLVMBlockAddress (fn->fn, val->label_symbol->bb_target->priv);break ;default :assert (0 );
validation/backend/struct-large-members.c new file +83 -0
83 lines not on this page · raw message
PATCH 28/73 inline: Duplicate generic expressions instead of evaluating them
In reply to Bart Van AsscheDuplicate the EXPR_GENERIC expression, its control expression, its default expression, and each type-expression map entry during function inlining instead of evaluating the generic selection prematurely.
Prevent copy_symbol() from traversing already-evaluated expressions where compound literals (such as &(size_t){ 0 }) produce anonymous local symbols without replacement symbols and trigger false 'unreplaced symbol <noident>' warnings.
Allow evaluate_statement() to evaluate the selected branch of the copied generic expression when the expanded inlined function body is evaluated, and add validation/inline-generic.c.
--- inline.c | 18 ++++++++++++++---- validation/inline-generic.c | 25 +++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 4 deletions(-)
inline.c +14 -4
@@ -345,13 +345,23 @@ static struct expression * copy_expression(struct expression *expr) }break ; } -case EXPR_GENERIC : +case EXPR_GENERIC : { +struct type_expression *map, **p; expr =dup_expression (expr); expr->control =copy_expression (expr->control); -if (!evaluate_expression (expr)) -return NULL ; - expr =copy_expression (expr); + expr->def =copy_expression (expr->def); + p = &expr->map; +for (map = expr->map; map; map = map->next) { +struct type_expression *new_map =__alloc_type_expression (0 ); + *new_map = *map; + new_map->type =copy_type (map->type); + new_map->expr =copy_expression (map->expr); + *p = new_map; + p = &new_map->next; + } + *p =NULL ;break ; + }default :warning (expr->pos,"trying to copy expression type %d" , expr->type);
validation/inline-generic.c +25 -0
@@ -5,6 +5,31 @@ inline unsigned f(void) { return e(_Generic(b, int: c())); }static int g (void ) {return f (); }static int h (void ) {return f (); } +inline void *cl (void ) +{ +return _Generic((void *)0 , +void *: &(int ){0 }, + default: (void *)0); +} + +static void test_cl (void ) +{ +cl (); +} + +static inline int inl_gen_vla (int n,void *p) +{ +return _Generic((int (*)[n])p, +int (*)[n]: (int )sizeof (int [n]), + default: 0); +} + +static int test_gen_vla (int x,int y,void *p) +{ +return inl_gen_vla (x, p) +inl_gen_vla (y, p); +} +/* * check-name: inline-generic +* check-command: sparse -Wno-vla $file */
PATCH 29/73 lib: Avoid mutating fmt before va_start() in warning()
In reply to Bart Van AsscheIntroduce a separate local pointer variable warn_fmt for the format string passed to do_warn(). Avoid reassigning the function parameter fmt before va_start(args, fmt) to maintain standard variadic argument initialization semantics across ABIs and compilers.
--- lib.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
lib.c +3 -2
@@ -182,6 +182,7 @@ void warning(struct position pos, const char * fmt, ...) {va_list args;static unsigned int warnings =0 ; +const char *warn_fmt = fmt;if (Wsparse_error) {va_start (args, fmt);
@@ -200,12 +201,12 @@ void warning(struct position pos, const char * fmt, ...) show_info =0 ;if (once)return ; - fmt ="too many warnings" ; + warn_fmt ="too many warnings" ; once =1 ; }va_start (args, fmt); -do_warn ("warning: " , pos, fmt, args); +do_warn ("warning: " , pos, warn_fmt, args);va_end (args); }
PATCH 30/73 cse, canon: Cast pointers to uintptr_t before relational comparison
In reply to Bart Van AsscheCast pointer operands to uintptr_t before comparing them with relational operators (<) in cse.c, simplify.c, and storage.c.
Avoid undefined behavior under ISO C when comparing pointers that do not point to elements of the same object, and prevent AddressSanitizer invalid-pointer-pair aborts under detect_invalid_pointer_pairs=2.
--- cse.c | 17 +++++++++-------- simplify.c | 3 ++- storage.c | 5 +++-- 3 files changed, 14 insertions(+), 11 deletions(-)
cse.c +9 -8
@@ -10,6 +10,7 @@#include <stdlib.h> #include <stdio.h> #include <stddef.h> +#include <stdint.h> #include <assert.h> #include "parse.h"
@@ -28,9 +29,9 @@ static int phi_compare(pseudo_t phi1, pseudo_t phi2)const struct instruction *def2 = phi2->def;if (def1->src1 != def2->src1) -return def1->src1 < def2->src1 ?-1 :1 ; +return (uintptr_t )def1->src1 < (uintptr_t )def2->src1 ?-1 :1 ;if (def1->bb != def2->bb) -return def1->bb < def2->bb ?-1 :1 ; +return (uintptr_t )def1->bb < (uintptr_t )def2->bb ?-1 :1 ;return 0 ; }
@@ -184,7 +185,7 @@ static int insn_compare(const void *_i1, const void *_i2)case OP_SEL :if (i1->src3 != i2->src3) -return i1->src3 < i2->src3 ?-1 :1 ; +return (uintptr_t )i1->src3 < (uintptr_t )i2->src3 ?-1 :1 ;/* Fall-through to binops */ /* Binary arithmetic */
@@ -208,7 +209,7 @@ static int insn_compare(const void *_i1, const void *_i2)case OP_FDIV : case_binops:if (i1->src2 != i2->src2) -return i1->src2 < i2->src2 ?-1 :1 ; +return (uintptr_t )i1->src2 < (uintptr_t )i2->src2 ?-1 :1 ;/* Fall through to unops */ /* Unary */
@@ -216,17 +217,17 @@ static int insn_compare(const void *_i1, const void *_i2)case OP_FNEG :case OP_SYMADDR :if (i1->src1 != i2->src1) -return i1->src1 < i2->src1 ?-1 :1 ; +return (uintptr_t )i1->src1 < (uintptr_t )i2->src1 ?-1 :1 ;break ;case OP_LABEL :if (i1->bb_true != i2->bb_true) -return i1->bb_true < i2->bb_true ?-1 :1 ; +return (uintptr_t )i1->bb_true < (uintptr_t )i2->bb_true ?-1 :1 ;break ;case OP_SETVAL :if (i1->val != i2->val) -return i1->val < i2->val ?-1 :1 ; +return (uintptr_t )i1->val < (uintptr_t )i2->val ?-1 :1 ;break ;case OP_SETFVAL :
@@ -244,7 +245,7 @@ static int insn_compare(const void *_i1, const void *_i2)case OP_PTRCAST :case OP_UTPTR :case OP_PTRTU :if (i1->src != i2->src) -return i1->src < i2->src ?-1 :1 ; +return (uintptr_t )i1->src < (uintptr_t )i2->src ?-1 :1 ;// Note: if it can be guaranted that identical ->src // implies identical orig_type->bit_size, then this
simplify.c +2 -1
@@ -40,6 +40,7 @@// * `SHIFT(x, S)` is used for `LSR(x, S)` or `SHL(x, S)`. #include <assert.h> +#include <stdint.h> #include "parse.h" #include "expression.h"
@@ -1814,7 +1815,7 @@ static int canonical_order(pseudo_t p1, pseudo_t p2)return 0 ;switch (t1) {case PSEUDO_SYM : -return p1->sym <= p2->sym; +return (uintptr_t )p1->sym <= (uintptr_t )p2->sym;case PSEUDO_REG :case PSEUDO_ARG :return p1->nr <= p2->nr;
storage.c +3 -2
@@ -8,6 +8,7 @@*/ #include <stdio.h> #include <stdlib.h> +#include <stdint.h> #include <assert.h> #include "symbol.h"
@@ -33,7 +34,7 @@ static int hash_list_cmp(const void *_a, const void *_b)const struct storage_hash *a = _a;const struct storage_hash *b = _b;if (a->pseudo != b->pseudo) -return a->pseudo < b->pseudo ?-1 :1 ; +return (uintptr_t )a->pseudo < (uintptr_t )b->pseudo ?-1 :1 ;return 0 ; }
@@ -118,7 +119,7 @@ static int storage_hash_cmp(const void *_a, const void *_b)struct storage *bb = b->storage;if (a->bb != b->bb) -return a->bb < b->bb ?-1 :1 ; +return (uintptr_t )a->bb < (uintptr_t )b->bb ?-1 :1 ;if (a->inout != b->inout)return a->inout < b->inout ?-1 :1 ;if (aa->type != bb->type)
PATCH 31/73 context: Add "conditional context increment" model
In reply to Bart Van AsscheFrom: Linus Torvalds <[email protected]>
Use a negative output parameter to the "context" attribute to indicate that the context is increased conditionally.
Support "trylock()" kinds of functions that return success if the lock operation succeeded, matching Linux kernel commit 4a557a5d1a61 ("sparse:
introduce conditional lock acquire function attribute") for refcount_dec_and_lock() and friends.
[ bvanassche: Rewrite commit message in imperative mood, support multiple
context attributes in linearize_call_expression(), validate conditional context function definitions in check_context(), and extend validation/context.c ]
--- linearize.c | 42 ++++++++- sparse.c | 202 +++++++++++++++++++++++++++++++++++++++++-- validation/context.c | 101 +++++++++++++++++++--- 3 files changed, 318 insertions(+), 27 deletions(-)
linearize.c +38 -4
@@ -1539,19 +1539,20 @@ static pseudo_t linearize_call_expression(struct entrypoint *ep, struct expressiadd_one_insn (ep, insn);if (ctype) { +struct basic_block *post_call =NULL ; + FOR_EACH_PTR(ctype->contexts, context) {int in = context->in;int out = context->out;int check =0 ;int context_diff; + +if (out <0 ) +continue ;if (in <0 ) { check =1 ; in =0 ; } -if (out <0 ) { - check =0 ; - out =0 ; - } context_diff = out - in;if (check || context_diff) { insn =alloc_instruction (OP_CONTEXT ,0 );
@@ -1562,6 +1563,39 @@ static pseudo_t linearize_call_expression(struct entrypoint *ep, struct expressi } }END_FOR_EACH_PTR (context); + FOR_EACH_PTR(ctype->contexts, context) { +int in = context->in; +int out = context->out; + +if (out >=0 ) +continue ; +if (retval ==VOID ) { +warning (expr->pos,"nonsensical conditional output context with no condition" ); +continue ; + } +if (in) { +warning (expr->pos,"nonsensical conditional input context" ); +continue ; + } +if (!post_call) { +struct basic_block *set_context; + post_call =alloc_basic_block (ep, expr->pos); + set_context =alloc_basic_block (ep, expr->pos); +add_branch (ep, retval, set_context, post_call); +set_activeblock (ep, set_context); + } + insn =alloc_instruction (OP_CONTEXT ,0 ); + insn->increment = -out; + insn->check =0 ; + insn->context_expr = context->context; +add_one_insn (ep, insn); + }END_FOR_EACH_PTR (context); + +if (post_call) { +add_goto (ep, post_call); +set_activeblock (ep, post_call); + } +if (ctype->modifiers &MOD_NORETURN )add_unreachable (ep); }
sparse.c +193 -9
236 lines not on this page · raw message
validation/context.c +87 -14
122 lines not on this page · raw message
PATCH 32/73 expand: Simplify signed constants early
In reply to Bart Van AsscheFrom: Linus Torvalds <[email protected]>
Make constant simplification for trivial unary preops on integer constants ('-5', '+5', '~0') available at type evaluation time via early_simplify_preop().
Fold unary preop expressions such as '-5' and '~0' before bitwise type evaluation so that all-bits-set constants such as -1 or ~0 are recognized as special cases.
[ bvanassche: Combine the two commits from Linus Torvalds ("simplify
signed constants early" and "Fix early constant simplification"), rewrite the commit message in the imperative mood, include simplify.h in expand.c to fix make selfcheck, and guard bit_size in early_simplify_preop() ]
--- evaluate.c | 14 +++++++++++++- expand.c | 31 +++++++++++++++++++++++++------ simplify.h | 1 + 3 files changed, 39 insertions(+), 7 deletions(-)
evaluate.c +13 -1
@@ -35,6 +35,7 @@#include <limits.h> #include "evaluate.h" +#include "simplify.h" #include "lib.h" #include "allocate.h" #include "bits.h"
@@ -1944,10 +1945,21 @@ Normal: }else {return bad_expr_type (expr); } -if (expr->op =='+' ) +if (expr->op =='+' ) { *expr = *expr->unop; + expr->flags = flags; + expr->ctype = ctype; +return ctype; + } expr->flags = flags; expr->ctype = ctype; + +/* +* We simplify sign ops of constants early, turning +* a constant with a sign into just a plain constant +* rather than a preop. +*/ +early_simplify_preop (expr);return ctype; Restr:if (restricted_unop (expr->op, &ctype))
expand.c +25 -6
@@ -44,6 +44,7 @@#include "expression.h" #include "evaluate.h" #include "expand.h" +#include "simplify.h" static int expand_expression (struct expression *);
@@ -817,13 +818,24 @@ static int expand_dereference(struct expression *expr)return UNSAFE ; } -static int simplify_preop (struct expression *expr) +/* +* We want to do certain trivial constant simplifications +* early at the type evaluation stage, because those can +* depend on specific constants (ie ~0 is ok for restricted +* types). +* +* Return >0 for successful simplification, 0 for none, +* and <0 for "not simplified due to overflow". +*/ +int early_simplify_preop (struct expression *expr) {struct expression *op = expr->unop;unsigned long long v, mask;if (op->type !=EXPR_VALUE )return 0 ; +if (!expr->ctype || expr->ctype->bit_size <=0 || expr->ctype->bit_size >64 ) +return 0 ; mask =sign_bit (expr->ctype->bit_size); v = op->value;
@@ -831,7 +843,7 @@ static int simplify_preop(struct expression *expr)case '+' :break ;case '-' :if (v == mask && !(expr->ctype->ctype.modifiers &MOD_UNSIGNED )) - goto Overflow; +return -1 ; v = -v;break ;case '!' : v = !v;break ;
@@ -843,11 +855,18 @@ static int simplify_preop(struct expression *expr) expr->type =EXPR_VALUE ; expr->taint = op->taint;return 1 ; +} -Overflow: -if (!conservative) -warning (expr->pos,"constant integer operation overflow" ); -return 0 ; +static int simplify_preop (struct expression *expr) +{ +int simplified =early_simplify_preop (expr); + +if (simplified <0 ) { +if (!conservative) +warning (expr->pos,"constant integer operation overflow" ); + simplified =0 ; + } +return simplified; }static int simplify_float_preop (struct expression *expr)
simplify.h +1 -0
@@ -4,6 +4,7 @@#include "linearize.h" int simplify_instruction (struct instruction *insn); +int early_simplify_preop (struct expression *expr);int replace_with_pseudo (struct instruction *insn,pseudo_t pseudo);
PATCH 33/73 bitwise: Allow all-bits-set as a restricted value
In reply to Bart Van AsscheFrom: Linus Torvalds <[email protected]>
Allow all-bits-set (~0) as a valid constant for bitwise restricted types alongside zero, and suppress restricted value warnings on '~0' unless -Wtypesign is enabled.
Avoid false-positive bitwise warnings on wait-flag masks and similar bitwise types that use ~0 to represent all flags set.
[ bvanassche: Rewrite commit message in imperative mood, check bit widths
and signedness in restricted_value(), and add validation/bitwise-all-bits-and-casts.c ]
--- evaluate.c | 33 ++++++++++++++++++++++- validation/bitwise-all-bits-and-casts.c | 36 +++++++++++++++++++++++++ 2 files changed, 68 insertions(+), 1 deletion(-) create mode 100644 validation/bitwise-all-bits-and-casts.c
evaluate.c +32 -1
@@ -425,12 +425,43 @@ static struct symbol *bad_expr_type(struct expression *expr)return expr->ctype = &bad_ctype; } +static bool is_unsigned_restricted_or_int (struct symbol *sym) +{ +while (sym) { +if (sym->type ==SYM_NODE || sym->type ==SYM_ENUM || + sym->type ==SYM_RESTRICT || sym->type ==SYM_FOULED || + sym->type ==SYM_BITFIELD ) { +if (sym->ctype.modifiers &MOD_UNSIGNED ) +return true; + sym = sym->ctype.base_type; +continue ; + } +break ; + } +return sym && (sym->ctype.modifiers &MOD_UNSIGNED ); +} +static int restricted_value (struct expression *v,struct symbol *type) {if (v->type !=EXPR_VALUE )return 1 ; -if (v->value !=0 ) +if (v->value !=0 ) { +int vbits = v->ctype ? v->ctype->bit_size :0 ; +int tbits = type ? type->bit_size :0 ; +bool vsigned = v->ctype && !is_unsigned_restricted_or_int (v->ctype); +unsigned long long uval, tmask, vmask; + +if (vbits <=0 || tbits <=0 || vbits >64 || tbits >64 ) +return 1 ; + uval = (unsigned long long )bits_extend (v->value, vbits, vsigned); + tmask =bits_mask (tbits); + vmask =bits_mask (vbits); +if (uval == tmask || uval == ~0ULL ) +return 0 ; +if (vbits >= tbits && (v->value & vmask) == vmask) +return 0 ;return 1 ; + }return 0 ; }
validation/bitwise-all-bits-and-casts.c new file +36 -0
@@ -0,0 +1,36 @@ +typedef unsigned long long __attribute__((bitwise)) be64; +typedef unsigned int __attribute__((bitwise)) be32; +typedef unsigned short __attribute__((bitwise)) be16; + +static be32 test_all_bits (void ) +{ +be32 a = ~0 ; +be32 b = ~0U ; +be32 c =-1 ; +be32 d =0 ; +be32 e =+0 ; +be32 f =-0 ; + +return a | b | c | d | e | f; +} + +static be64 test_all_bits_64 (void ) +{ +be64 a = ~0 ; +be64 b = ~0ULL ; +be64 c =-1 ; + +return a | b | c; +} + +static be16 test_narrow_all_bits (void ) +{ +be16 a = ~0 ; +be16 b =0xffff ; +return a | b; +} + +/* +* check-name: bitwise-all-bits-and-casts +* check-command: sparse -Wbitwise $file +*/
PATCH 34/73 bitwise: Allow restricted ordered compares with unrestricted values
In reply to Bart Van AsscheFrom: Linus Torvalds <[email protected]>
Update restricted_binop() to check unrestricted values (0 and ~0) for ordered comparisons just like equality comparisons, and warn when '<' or '>' is used against 0 or ~0 because restricted types are unsigned and those comparisons are always true or false.
Allow idiomatic bounds checks such as 'flags <= 0' or 'flags >= ~0' on bitwise types while catching tautological comparisons.
[ bvanassche: Rewrite commit message in imperative mood, require unsigned
types in can_order() without warning on '<' or '>', pass the target type to restricted_value(), and extend validation/bitwise-all-bits-and-casts.c ]
--- evaluate.c | 25 ++++++++++++++++++++++--- validation/bitwise-all-bits-and-casts.c | 18 ++++++++++++++++++ 2 files changed, 40 insertions(+), 3 deletions(-)
evaluate.c +22 -3
@@ -465,7 +465,19 @@ static int restricted_value(struct expression *v, struct symbol *type)return 0 ; } -static int restricted_binop (int op,struct symbol *type) +/* +* Bitwise types can do ordered comparisons with +* the unrestricted values, but not in general +*/ +static bool can_order (struct symbol *type,struct expression *left,struct expression *right) +{ +if (!is_unsigned_restricted_or_int (type)) +return false; +return !restricted_value (left, type) || + !restricted_value (right, type); +} + +static int restricted_binop (int op,struct symbol *type,struct expression *left,struct expression *right) {switch (op) {case '&' :
@@ -478,6 +490,13 @@ static int restricted_binop(int op, struct symbol *type)case '^' :case '?' :return 2 ;/* keep fouled */ +case '<' : +case '>' : +case SPECIAL_LTE : +case SPECIAL_GTE : +if (can_order (type, left, right)) +return 3 ; +return 0 ;case SPECIAL_EQUAL :case SPECIAL_NOTEQUAL :return 3 ;/* warn if fouled */
@@ -530,7 +549,7 @@ static struct symbol *restricted_binop_type(int op, ctype = rtype;if (ctype) { -switch (restricted_binop (op, ctype)) { +switch (restricted_binop (op, ctype, left, right)) {case 1 :if ((lclass ^ rclass) &TYPE_FOULED ) ctype =unfoul (ctype);
@@ -1364,7 +1383,7 @@ static int evaluate_assign_op(struct expression *expr)return 0 ; }if (tclass &TYPE_RESTRICT ) { -if (!restricted_binop (op, t)) { +if (!restricted_binop (op, t, expr->left, expr->right)) {warning (expr->pos,"bad assignment (%s) to %s" ,show_special (op),show_typename (t)); expr->right =cast_to (expr->right, target);
validation/bitwise-all-bits-and-casts.c +18 -0
@@ -30,6 +30,24 @@ static be16 test_narrow_all_bits(void)return a | b; } +static int test_ordered_compare (be32 x,be16 y) +{ +int res =0 ; +if (x >0 ) + res++; +if (x <=0 ) + res++; +if (0 < x) + res++; +if (0 >= x) + res++; +if (x < ~0 ) + res++; +if (y <=0xffff ) + res++; +return res; +} +/* * check-name: bitwise-all-bits-and-casts * check-command: sparse -Wbitwise $file
PATCH 35/73 bitwise: Keep unrestricted values unrestricted after a cast
In reply to Bart Van AsscheFrom: Linus Torvalds <[email protected]>
Allow a cast of 0 or ~0 to its own restricted type (such as '(__le32) 0' or '(__le32) ~0') to remain an unrestricted constant in restricted_value().
Allow 0 or ~0 cast to a restricted type to match another restricted type even when the macro definition does not use '__force'.
[ bvanassche: Rewrite commit message in imperative mood, fix typo, reject
narrowing non-zero casts in restricted_value(), and extend validation/bitwise-all-bits-and-casts.c ]
--- evaluate.c | 17 +++++++++++++++++ validation/bitwise-all-bits-and-casts.c | 18 ++++++++++++------ 2 files changed, 29 insertions(+), 6 deletions(-)
evaluate.c +17 -0
@@ -443,6 +443,23 @@ static bool is_unsigned_restricted_or_int(struct symbol *sym)static int restricted_value (struct expression *v,struct symbol *type) { +if (v->type ==EXPR_CAST ) { +struct symbol *ctype; +int cclass =classify_type (v->ctype, &ctype); +struct expression *leaf = v->cast_expression; + +if (!is_int (cclass)) +return 1 ; +if (restricted_value (v->cast_expression, ctype)) +return 1 ; +while (leaf && leaf->type ==EXPR_CAST ) + leaf = leaf->cast_expression; +if (leaf && leaf->type ==EXPR_VALUE && leaf->value ==0 ) +return 0 ; +if (ctype->bit_size < type->bit_size &&is_unsigned_restricted_or_int (ctype)) +return 1 ; +return 0 ; + }if (v->type !=EXPR_VALUE )return 1 ;if (v->value !=0 ) {
validation/bitwise-all-bits-and-casts.c +12 -6
@@ -10,8 +10,10 @@ static be32 test_all_bits(void)be32 d =0 ;be32 e =+0 ;be32 f =-0 ; +be32 g = (be32 )0 ; +be32 i = (be32 )~0 ; -return a | b | c | d | e | f; +return a | b | c | d | e | f | g | i; }static be64 test_all_bits_64 (void )
@@ -19,15 +21,19 @@ static be64 test_all_bits_64(void)be64 a = ~0 ;be64 b = ~0ULL ;be64 c =-1 ; +be64 d = (be64 )0 ; +be64 f = (be64 )~0 ; -return a | b | c; +return a | b | c | d | f; } -static be16 test_narrow_all_bits (void ) +static be16 test_cross_cast_zero (void ) { -be16 a = ~0 ; -be16 b =0xffff ; -return a | b; +be16 k = (be32 )0 ; +be16 m = (be32 )~0 ; +be16 o = (unsigned short )~0 ; + +return k | m | o; }static int test_ordered_compare (be32 x,be16 y)
PATCH 36/73 bitwise: Don't remove MOD_SPECIFIER from 'bitwise' types
In reply to Bart Van AsscheFrom: Linus Torvalds <[email protected]>
Preserve MOD_SPECIFIER on 'bitwise' (SYM_RESTRICT) types in declaration_specifiers() so that signedness modifiers such as MOD_UNSIGNED are not stripped from the restricted type.
Prevent clearing MOD_SPECIFIER from dropping MOD_UNSIGNED on bitwise typedefs (such as 'typedef unsigned int __attribute__((bitwise)) le32;') so ordered comparisons like '(le32)-1 <= (le32)0' are not evaluated as signed comparisons.
[ bvanassche: Rewrite commit message in imperative mood, pass
expr->cast_expression to is_promoted() in evaluate_type_information(), and suppress redundant 'unsigned' modifier output for SYM_RESTRICT in show-parse.c ]
--- Documentation/types.rst | 2 +- evaluate.c | 2 +- parse.c | 1 - show-parse.c | 3 ++- 4 files changed, 4 insertions(+), 4 deletions(-)
Documentation/types.rst +1 -1
@@ -125,7 +125,7 @@ SYM_RESTRICT Used for bitwise types (aka 'restricted' types): * .ctype.base_type points to the underlying type (integer) * .ctype.modifiers & .as are like for SYM_NODE and the modifiers - are inherited from the base type with MOD_SPECIFIER removed + are inherited from the base type * .ident is the typedef name (if any). SYM_FOULED
evaluate.c +1 -1
@@ -2290,7 +2290,7 @@ static struct symbol *evaluate_type_information(struct expression *expr)* promoted - check that here */ if (is_restricted_type (sym)) { -if (sym->bit_size < bits_in_int &&is_promoted (expr)) +if (sym->bit_size < bits_in_int &&is_promoted (expr->cast_expression)) sym = &int_ctype; }else if (is_fouled_type (sym)) { sym = &int_ctype;
parse.c +0 -1
@@ -1709,7 +1709,6 @@ static struct token *declaration_specifiers(struct token *token, struct decl_sta } type =alloc_symbol (token->pos,SYM_BASETYPE ); *type = *ctx->ctype.base_type; - type->ctype.modifiers &= ~MOD_SPECIFIER ; type->ctype.base_type = ctx->ctype.base_type; type->type =SYM_RESTRICT ; ctx->ctype.base_type = type;
show-parse.c +2 -1
@@ -336,7 +336,8 @@ deeper:if (as)prepend (name,"%s " ,show_as (as)); -if (sym->type ==SYM_BASETYPE || sym->type ==SYM_ENUM ) +if (sym->type ==SYM_BASETYPE || sym->type ==SYM_ENUM || + sym->type ==SYM_RESTRICT ) mod &= ~MOD_SPECIFIER ; s =modifier_string (mod);prepend (name,"%s" , s);
PATCH 37/73 bitwise: Allow both regular casts and forced casts for restricted values
In reply to Bart Van AsscheFrom: Linus Torvalds <[email protected]>
Allow EXPR_FORCE_CAST as well as EXPR_CAST in restricted_value() when checking whether an expression is a cast of 0 or ~0.
Support restricted constants defined with '__force' in kernel headers (for example, '#define EPOLLIN (__force __poll_t)0x00000001') by recognizing both forced and unforced casts of 0 and ~0 in restricted_value().
[ bvanassche: Rewrite commit message in imperative mood, fix typo, unwrap
EXPR_FORCE_CAST in restricted_value(), and extend validation/bitwise-all-bits-and-casts.c ]
--- evaluate.c | 4 +-- validation/bitwise-all-bits-and-casts.c | 46 +++++++++++++++++++++++-- 2 files changed, 45 insertions(+), 5 deletions(-)
evaluate.c +2 -2
@@ -443,7 +443,7 @@ static bool is_unsigned_restricted_or_int(struct symbol *sym)static int restricted_value (struct expression *v,struct symbol *type) { -if (v->type ==EXPR_CAST ) { +if (v->type ==EXPR_CAST || v->type ==EXPR_FORCE_CAST ) {struct symbol *ctype;int cclass =classify_type (v->ctype, &ctype);struct expression *leaf = v->cast_expression;
@@ -452,7 +452,7 @@ static int restricted_value(struct expression *v, struct symbol *type)return 1 ;if (restricted_value (v->cast_expression, ctype))return 1 ; -while (leaf && leaf->type ==EXPR_CAST ) +while (leaf && (leaf->type ==EXPR_CAST || leaf->type ==EXPR_FORCE_CAST )) leaf = leaf->cast_expression;if (leaf && leaf->type ==EXPR_VALUE && leaf->value ==0 )return 0 ;
validation/bitwise-all-bits-and-casts.c +43 -3
83 lines not on this page · raw message
PATCH 38/73 clang-format: Add .clang-format configuration file
In reply to Bart Van AsscheAdd a .clang-format configuration file matching the sparse coding style (8-column tabs for indentation, 80-column line limit, Linux kernel brace and pointer alignment conventions, and foreach macro definitions) so that code formatting can be checked and applied consistently.
--- .clang-format | 125 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 125 insertions(+) create mode 100644 .clang-format
.clang-format new file +125 -0
@@ -0,0 +1,125 @@ +# SPDX-License-Identifier: MIT +# +# clang-format configuration file. Intended for clang-format >= 11. +# +# For more information, see: +# +# https://clang.llvm.org/docs/ClangFormat.html +# https://clang.llvm.org/docs/ClangFormatStyleOptions.html +# +--- +AccessModifierOffset: -4 +AlignAfterOpenBracket: Align +AlignConsecutiveAssignments: false +AlignConsecutiveDeclarations: false +AlignEscapedNewlines: Left +AlignOperands: true +AlignTrailingComments: false +AllowAllParametersOfDeclarationOnNextLine: false +AllowShortBlocksOnASingleLine: false +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: None +AllowShortIfStatementsOnASingleLine: false +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: false +BinPackArguments: true +BinPackParameters: true +BraceWrapping: + AfterClass: false + AfterControlStatement: false + AfterEnum: false + AfterFunction: true + AfterNamespace: true + AfterObjCDeclaration: false + AfterStruct: false + AfterUnion: false + AfterExternBlock: false + BeforeCatch: false + BeforeElse: false + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true +BreakBeforeBinaryOperators: None +BreakBeforeBraces: Custom +BreakBeforeInheritanceComma: false +BreakBeforeTernaryOperators: false +BreakConstructorInitializersBeforeComma: false +BreakConstructorInitializers: BeforeComma +BreakAfterJavaFieldAnnotations: false +BreakStringLiterals: false +ColumnLimit: 80 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: false +ConstructorInitializerAllOnOneLineOrOnePerLine: false +ConstructorInitializerIndentWidth: 8 +ContinuationIndentWidth: 8 +Cpp11BracedListStyle: false +DerivePointerAlignment: false +DisableFormat: false +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: false +ForEachMacros: + - 'FOR_EACH_PTR' + - 'FOR_EACH_PTR_NOTAG' + - 'FOR_EACH_PTR_REVERSE' + - 'FOR_EACH_PTR_REVERSE_TAG' + - 'FOR_EACH_PTR_TAG' + - 'RECURSE_PTR_REVERSE' + +IncludeBlocks: Preserve +IncludeCategories: + - Regex: '.*' + Priority: 1 +IncludeIsMainRegex: '(Test)?$' +IndentCaseLabels: false +IndentGotoLabels: false +IndentPPDirectives: None +IndentWidth: 8 +IndentWrappedFunctionNames: false +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: false +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +ObjCBinPackProtocolList: Auto +ObjCBlockIndentWidth: 8 +ObjCSpaceAfterProperty: true +ObjCSpaceBeforeProtocolList: true + +# Taken from git's rules +PenaltyBreakAssignment: 10 +PenaltyBreakBeforeFirstCallParameter: 30 +PenaltyBreakComment: 10 +PenaltyBreakFirstLessLess: 0 +PenaltyBreakString: 10 +PenaltyExcessCharacter: 100 +PenaltyReturnTypeOnItsOwnLine: 60 + +PointerAlignment: Right +ReflowComments: false +SortIncludes: false +SortUsingDeclarations: false +SpaceAfterCStyleCast: false +SpaceAfterTemplateKeyword: true +SpaceBeforeAssignmentOperators: true +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeParens: ControlStatementsExceptForEachMacros +SpaceBeforeRangeBasedForLoopColon: true +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: false +SpacesInContainerLiterals: false +SpacesInCStyleCastParentheses: false +SpacesInParentheses: false +SpacesInSquareBrackets: false +Standard: Cpp03 +TabWidth: 8 +UseTab: Always +...
PATCH 39/73 options: Add support for -std=c23, -std=c2x and -std=gnu23
In reply to Bart Van AsscheAdd STANDARD_C23 and STANDARD_GNU23 to enum standard, handle the c23, c2x, iso9899:2024, gnu23, and gnu2x arguments to -std=, and set __STDC_VERSION__ to 202311L when targeting C23 so that users and build systems can select ISO C23 and GNU23 language modes and feature-test macros.
--- options.c | 5 +++++ options.h | 2 ++ predefine.c | 4 ++++ validation/c23-stdc-version.c | 11 +++++++++++ 4 files changed, 22 insertions(+) create mode 100644 validation/c23-stdc-version.c
options.c +5 -0
@@ -797,6 +797,11 @@ static char **handle_switch_s(const char *arg, char **next)else if (!strcmp (arg,"gnu17" ) || !strcmp (arg,"gnu18" )) standard =STANDARD_GNU17 ; +else if (!strcmp (arg,"c23" ) || !strcmp (arg,"c2x" ) || + !strcmp (arg,"iso9899:2024" )) + standard =STANDARD_C23 ; +else if (!strcmp (arg,"gnu23" ) || !strcmp (arg,"gnu2x" )) + standard =STANDARD_GNU23 ;else die ("Unsupported C dialect" );
options.h +2 -0
@@ -27,6 +27,8 @@ enum standard {STANDARD_GNU11 =STANDARD_C11 |STANDARD_GNU ,STANDARD_C17 ,STANDARD_GNU17 =STANDARD_C17 |STANDARD_GNU , +STANDARD_C23 , + STANDARD_GNU23 = STANDARD_C23 | STANDARD_GNU, };extern int die_if_error;
predefine.c +4 -0
@@ -111,6 +111,10 @@ void predefined_macros(void)case STANDARD_GNU17 :predefine ("__STDC_VERSION__" ,1 ,"201710L" );break ; +case STANDARD_C23 : +case STANDARD_GNU23 : +predefine ("__STDC_VERSION__" ,1 ,"202311L" ); +break ; }if (!(standard &STANDARD_GNU ) && (standard !=STANDARD_NONE ))predefine ("__STRICT_ANSI__" ,1 ,"1" );
validation/c23-stdc-version.c new file +11 -0
@@ -0,0 +1,11 @@ +__STDC_VERSION__ + +/* +* check-name: c23-stdc-version +* check-command: sparse -E -std=c23 $file +* +* check-output-start + +202311L +* check-output-end +*/
PATCH 40/73 preprocessor: Add support for #elifdef and #elifndef
In reply to Bart Van AsscheSupport the #elifdef and #elifndef preprocessing directives introduced in C23 (WG14 N2645) as shorthand for #elif defined(...) and #elif !defined(...), and emit a pedantic warning when used in language modes prior to C23.
--- pre-process.c | 71 +++++++++++++++++++-- validation/preprocessor/c23-elifdef-error.c | 35 ++++++++++ validation/preprocessor/c23-elifdef.c | 44 +++++++++++++ 3 files changed, 145 insertions(+), 5 deletions(-) create mode 100644 validation/preprocessor/c23-elifdef-error.c create mode 100644 validation/preprocessor/c23-elifdef.c
pre-process.c +66 -5
@@ -1713,39 +1713,98 @@ static int handle_if(struct stream *stream, struct token **line, struct token *treturn preprocessor_if (stream, token, value); } -static int handle_elif (struct stream * stream,struct token **line,struct token *token) +static int do_handle_elif (struct stream *stream,struct token *token, +int (*eval)(struct token *), +bool (*check)(struct token *)) {struct token *top_if = stream->top_if;end_group (stream);if (!top_if) {nesting_error (stream); -sparse_error (token->pos,"unmatched #elif within stream" ); +sparse_error (token->pos,"unmatched #%s within stream" , +show_token (token));return 1 ; }if (token_type (top_if) ==TOKEN_ELSE ) {nesting_error (stream); -sparse_error (token->pos,"#elif after #else" ); +sparse_error (token->pos,"#%s after #else" ,show_token (token));if (!false_nesting) false_nesting =1 ;return 1 ; }dirty_stream (stream); -if (token_type (top_if) !=TOKEN_IF ) +if (token_type (top_if) !=TOKEN_IF ) { +if (false_nesting <=1 && check) +check (token);return 1 ; + }if (false_nesting) { false_nesting =0 ; -if (!expression_value (&token->next)) +if (!eval (token)) false_nesting =1 ; }else { +if (check) +check (token); false_nesting =1 ;token_type (top_if) =TOKEN_SKIP_GROUPS ; }return 1 ; } +static int eval_elif (struct token *token) +{ +return expression_value (&token->next); +} + +static bool check_elifdef (struct token *token) +{ +struct token *next = token->next; + +if (standard <STANDARD_C23 && Wpedantic) +warning (token->pos,"ISO C does not support #%s before C23" , +show_token (token)); +if (token_type (next) !=TOKEN_IDENT ) { +sparse_error (token->pos,"expected preprocessor identifier" ); +return false; + } +if (!eof_token (next->next)) +warning (next->next->pos, +"extra tokens at end of #%s directive" , +show_token (token)); +return true; +} + +static int eval_elifdef (struct token *token) +{ +return check_elifdef (token) &&token_defined (token->next); +} + +static int eval_elifndef (struct token *token) +{ +return check_elifdef (token) && !token_defined (token->next); +} + +static int handle_elif (struct stream *stream,struct token **line, +struct token *token) +{ +return do_handle_elif (stream, token, eval_elif,NULL ); +} + +static int handle_elifdef (struct stream *stream,struct token **line, +struct token *token) +{ +return do_handle_elif (stream, token, eval_elifdef, check_elifdef); +} + +static int handle_elifndef (struct stream *stream,struct token **line, +struct token *token) +{ +return do_handle_elif (stream, token, eval_elifndef, check_elifdef); +} +static int handle_else (struct stream *stream,struct token **line,struct token *token) {struct token *top_if = stream->top_if;
@@ -2163,6 +2222,8 @@ static void init_preprocessor(void) { "endif", handle_endif }, { "if", handle_if }, { "elif", handle_elif }, + { "elifdef", handle_elifdef }, + { "elifndef", handle_elifndef }, }; static struct { const char *name;
validation/preprocessor/c23-elifdef-error.c new file +35 -0
@@ -0,0 +1,35 @@ +#define FOO 1 + +#if 1 +int taken =1 ; +#elifdefFOO +int skipped1 =1 ; +#elifndefBAR +int skipped2 =1 ; +#elifdef 123 +int skipped3 =1 ; +#endif + +#if 0 +#if 1 +#elifdefFOO +#elifdef 123 +#endif +#endif + +/* +* check-name: c23-elifdef-error +* check-command: sparse -std=c17 -Wpedantic -E $file +* +* check-output-start + +int taken = 1; +* check-output-end +* +* check-error-start +preprocessor/c23-elifdef-error.c:5:2: warning: ISO C does not support #elifdef before C23 +preprocessor/c23-elifdef-error.c:7:2: warning: ISO C does not support #elifndef before C23 +preprocessor/c23-elifdef-error.c:9:2: warning: ISO C does not support #elifdef before C23 +preprocessor/c23-elifdef-error.c:9:2: error: expected preprocessor identifier +* check-error-end +*/
validation/preprocessor/c23-elifdef.c new file +44 -0
44 lines not on this page · raw message
PATCH 41/73 preprocessor: Add support for __has_include and __has_include_next
In reply to Bart Van AsscheSupport the C23 __has_include and __has_include_next preprocessor operators for querying the availability of header files so that code using feature test macros can conditionally include headers portably.
--- ident-list.h | 2 + pre-process.c | 303 +++++++++++++++++- .../preprocessor/c23-has-include-error.c | 18 ++ validation/preprocessor/c23-has-include.c | 51 +++ 4 files changed, 363 insertions(+), 11 deletions(-) create mode 100644 validation/preprocessor/c23-has-include-error.c create mode 100644 validation/preprocessor/c23-has-include.c
ident-list.h +2 -0
@@ -68,6 +68,8 @@ __IDENT(__VA_ARGS___ident, "__VA_ARGS__", 0);__IDENT (__func___ident,"__func__" ,0 );__IDENT (__FUNCTION___ident,"__FUNCTION__" ,0 );__IDENT (__PRETTY_FUNCTION___ident,"__PRETTY_FUNCTION__" ,0 ); +__IDENT (__has_include_ident,"__has_include" ,0 ); +__IDENT (__has_include_next_ident,"__has_include_next" ,0 );/* Sparse commands */ IDENT_RESERVED (__context__);
pre-process.c +292 -11
357 lines not on this page · raw message
validation/preprocessor/c23-has-include-error.c new file +18 -0
@@ -0,0 +1,18 @@ +int outside = __has_include(<stdio.h>); + +#if __has_include("") +#endif + +#if __has_include(<>) +#endif + +/* +* check-name: c23-has-include-error +* check-command: sparse -std=c23 -Wno-decl $file +* +* check-error-start +preprocessor/c23-has-include-error.c:1:15: error: '__has_include' used outside of preprocessing directive +preprocessor/c23-has-include-error.c:3:19: error: empty filename +preprocessor/c23-has-include-error.c:6:5: error: empty filename +* check-error-end +*/
validation/preprocessor/c23-has-include.c new file +51 -0
51 lines not on this page · raw message
PATCH 42/73 c23: Add support for static_assert, alignas, alignof, thread_local
In reply to Bart Van AsscheRegister static_assert, alignas, alignof, and thread_local as reserved C23 keywords and support single-argument static_assert(expr) without a message string per ISO C23 6.7.12:
- Mark static_assert and alignof as reserved identifiers in C23 mode while keeping them available as ordinary identifiers in pre-C23 modes.
- Warn under -Wpedantic when alignof or _Alignof is applied to an expression rather than a type name.
- Enforce ISO C23 constraints on alignas and thread_local declarations, and avoid materializing block-scope thread_local symbols as stack locals during linearization.
--- expression.c | 15 ++++- ident-list.h | 9 ++- linearize.c | 2 +- options.c | 2 + parse.c | 100 ++++++++++++++++++++++++++-- parse.h | 1 + symbol.h | 2 + validation/c11-c23-keywords-ident.c | 19 ++++++ validation/c23-alignof-pedantic.c | 20 ++++++ validation/c23-keywords-error.c | 48 +++++++++++++ validation/c23-keywords.c | 30 +++++++++ 11 files changed, 241 insertions(+), 7 deletions(-) create mode 100644 validation/c11-c23-keywords-ident.c create mode 100644 validation/c23-alignof-pedantic.c create mode 100644 validation/c23-keywords-error.c create mode 100644 validation/c23-keywords.c
expression.c +14 -1
@@ -646,13 +646,21 @@ static struct token *type_info_expression(struct token *token, struct expression **tree, int type) {struct expression *expr =alloc_expression (token->pos, type); +struct ident *op_ident = token->ident; +bool std_alignof = (op_ident == &_Alignof_ident || + op_ident == &alignof_ident);struct token *p; *tree = expr; expr->flags =CEF_SET_ICE ;/* XXX: VLA support will need that changed */ token = token->next; -if (!match_op (token,'(' ) || !lookup_type (token->next)) +if (!match_op (token,'(' ) || !lookup_type (token->next)) { +if (std_alignof && Wpedantic) +warning (expr->pos, +"ISO C does not allow '%s' on an expression" , +show_ident (op_ident));return unary_expression (token, &expr->cast_expression); + } p = token; token =typename (token->next, &expr->cast_type,NULL );
@@ -672,6 +680,10 @@ static struct token *type_info_expression(struct token *token,*/ if (match_op (token,'{' )) {struct expression *cast =alloc_expression (p->pos,EXPR_CAST ); +if (std_alignof && Wpedantic) +warning (expr->pos, +"ISO C does not allow '%s' on an expression" , +show_ident (op_ident)); cast->cast_type = expr->cast_type; expr->cast_type =NULL ; expr->cast_expression = cast;
@@ -691,6 +703,7 @@ static struct token *unary_expression(struct token *token, struct expression **tint type; } type_information[] = { { &sizeof_ident, EXPR_SIZEOF }, + { &alignof_ident, EXPR_ALIGNOF }, { &__alignof___ident, EXPR_ALIGNOF }, { &__alignof_ident, EXPR_ALIGNOF }, { &_Alignof_ident, EXPR_ALIGNOF },
ident-list.h +8 -1
@@ -43,12 +43,19 @@ IDENT(_Noreturn);IDENT_RESERVED (_Static_assert);IDENT (_Thread_local); +/* C23 keywords */ +IDENT (alignas); +IDENT (alignof); +IDENT (static_assert); +IDENT (thread_local); +/* Special case for L'\t' */ IDENT (L );/* Extended gcc identifiers */ IDENT (asm);IDENT_RESERVED (__asm);IDENT_RESERVED (__asm__); -IDENT (alignof);IDENT_RESERVED (__alignof);IDENT_RESERVED (__alignof__); +IDENT_RESERVED (__alignof); +IDENT_RESERVED (__alignof__);IDENT_RESERVED (__sizeof_ptr__);IDENT_RESERVED (__builtin_types_compatible_p);IDENT_RESERVED (__builtin_offsetof);
linearize.c +1 -1
@@ -1995,7 +1995,7 @@ static pseudo_t linearize_one_symbol(struct entrypoint *ep, struct symbol *sym)return VOID ;/* We need to output these puppies some day too.. */ -if (sym->ctype.modifiers & (MOD_STATIC |MOD_TOPLEVEL )) +if (sym->ctype.modifiers & (MOD_STATIC |MOD_TOPLEVEL |MOD_TLS ))return VOID ; sym->initialized =1 ;
options.c +2 -0
@@ -11,6 +11,7 @@#include "lib.h" #include "machine.h" #include "target.h" +#include "parse.h" #include <ctype.h> #include <stdio.h> #include <stdlib.h>
@@ -1068,4 +1069,5 @@ void handle_switch_finalize(void) {handle_switch_v_finalize ();handle_switch_W_finalize (); +init_parser_finalize (); }
parse.c +96 -4
196 lines not on this page · raw message
parse.h +1 -0
@@ -139,6 +139,7 @@ extern struct symbol *ctype_integer(int size, int want_unsigned);extern int inline_function (struct expression *expr,struct symbol *sym);extern void uninline (struct symbol *sym);extern void init_parser (int ); +extern void init_parser_finalize (void );struct token *expect (struct token *,int ,const char *);
symbol.h +2 -0
@@ -115,6 +115,7 @@ struct decl_state {unsigned char autotype;unsigned char forced;unsigned char packed; +unsigned char has_alignas;unsigned char designated_init;unsigned char transparent_union; };
@@ -199,6 +200,7 @@ struct symbol { torename:1, packed:1, transparent_union:1; + unsigned int has_alignas : 1; int rank:3; // arithmetic's rankstruct expression *array_size;struct ctype ctype;
validation/c11-c23-keywords-ident.c new file +19 -0
@@ -0,0 +1,19 @@ +static int test_c11_idents (void ) +{ + int alignas = 1; +int alignof =2 ; +int static_assert =3 ; + int thread_local = 4; +int bool =5 ; +int true =6 ; +int false =7 ; +int nullptr =8 ; + + return alignas + alignof + static_assert + thread_local + + bool + true + false +nullptr ; +} + +/* +* check-name: c11-c23-keywords-ident +* check-command: sparse -std=c11 $file +*/
validation/c23-alignof-pedantic.c new file +20 -0
@@ -0,0 +1,20 @@ +static int test (void ) +{ + alignas(8 )int x =0 ; +int a = alignof(int ); +int b = alignof(x ); +int c = _Alignof(x ); +int d = __alignof__(x ); +int e = __alignof(x ); +return a + b + c + d + e; +} + +/* +* check-name: c23-alignof-pedantic +* check-command: sparse -std=c23 -pedantic $file +* +* check-error-start +c23-alignof-pedantic.c:5:17: warning: ISO C does not allow 'alignof' on an expression +c23-alignof-pedantic.c:6:17: warning: ISO C does not allow '_Alignof' on an expression +* check-error-end +*/
validation/c23-keywords-error.c new file +48 -0
48 lines not on this page · raw message
validation/c23-keywords.c new file +30 -0
@@ -0,0 +1,30 @@ +static_assert (1 ); +static_assert (1 ,"file scope" ); + +struct s { + static_assert(1); + static_assert(1, "struct scope"); + alignas(16 )int a; +}; + +static_assert (alignof(struct s ) ==16 ); + +thread_localint tl; +alignas(double )static int aligned_dbl; + +static int test (void ) +{ +static_assert (1 ); +static_assert (1 ,"func scope" ); + alignas(8 )int x =0 ; +static thread_localint local_tl =3 ; +extern thread_localint tl; +static_assert (alignof(int ) <=8 ); +static_assert (alignof(double ) <=16 ); +return x + tl + local_tl + aligned_dbl; +} + +/* +* check-name: c23-keywords +* check-command: sparse -std=c23 -pedantic -Wno-decl $file +*/
PATCH 43/73 c23: Add support for bool, true, and false keywords
In reply to Bart Van AsscheRegister bool, true, and false as reserved keywords in C23 mode and evaluate true and false as integer constant expressions of type bool with values 1 and 0 in both C expressions and #if conditionals per ISO C23 6.4.4.5 and 6.10.1.
--- expression.c | 15 ++++++++++++- ident-list.h | 3 +++ parse.c | 3 +++ pre-process.c | 10 +++++++++ validation/c23-bool-error.c | 23 +++++++++++++++++++ validation/c23-bool.c | 45 +++++++++++++++++++++++++++++++++++++ 6 files changed, 98 insertions(+), 1 deletion(-) create mode 100644 validation/c23-bool-error.c create mode 100644 validation/c23-bool.c
expression.c +14 -1
@@ -466,9 +466,22 @@ struct token *primary_expression(struct token *token, struct expression **tree) }case TOKEN_IDENT : { -struct symbol *sym =lookup_symbol (token->ident,NS_SYMBOL |NS_TYPEDEF ); +struct symbol *sym;struct token *next = token->next; +if (standard >=STANDARD_C23 && + (token->ident == &true_ident || + token->ident == &false_ident)) { + expr =alloc_expression (token->pos,EXPR_VALUE ); + expr->flags =CEF_SET_INT ; + expr->ctype = &bool_ctype; + expr->value = (token->ident == &true_ident); + token = next; +break ; + } + + sym =lookup_symbol (token->ident,NS_SYMBOL |NS_TYPEDEF ); +if (!sym) { sym =handle_func (token);if (token->ident == &__builtin_types_compatible_p_ident) {
ident-list.h +3 -0
@@ -46,8 +46,11 @@ IDENT(_Thread_local);/* C23 keywords */ IDENT (alignas);IDENT (alignof); +IDENT (bool); +IDENT (false);IDENT (static_assert);IDENT (thread_local); +IDENT (true);/* Special case for L'\t' */ IDENT (L );
parse.c +3 -0
@@ -520,6 +520,7 @@ static struct init_keyword {N ("unsigned" , &unsigned_op),N ("__int128" , &int128_op), N("_Bool", &spec_op, .type = &bool_ctype), + N("bool", &spec_op, .type = &bool_ctype, .std = STANDARD_C23),/* Predeclared types */ N("__builtin_va_list", &spec_op, .type = &ptr_ctype),
@@ -655,6 +656,8 @@ void init_parser_finalize(void)if (standard >=STANDARD_C23 ) { static_assert_ident.reserved =1 ; alignof_ident.reserved =1 ; + true_ident.reserved =1 ; + false_ident.reserved =1 ; } }
pre-process.c +10 -0
@@ -1937,6 +1937,16 @@ static int expression_value(struct token **where)continue ;if (token_type (p) !=TOKEN_IDENT )break ; +if (standard >=STANDARD_C23 && + p->ident == &true_ident) { +replace_with_bool (p,1 ); +break ; + } +if (standard >=STANDARD_C23 && + p->ident == &false_ident) { +replace_with_bool (p,0 ); +break ; + }token_type (p) =TOKEN_ZERO_IDENT ;break ;case 1 :
validation/c23-bool-error.c new file +23 -0
@@ -0,0 +1,23 @@ +static int (bool); +static int (true); +static int (false); +typedef int bool ; + +static void bad_lvalue (void ) +{ + true = false; +} + +/* +* check-name: c23-bool-error +* check-command: sparse -std=c23 -Wno-decl $file +* +* check-error-start +c23-bool-error.c:1:12: error: Trying to use reserved word 'bool' as identifier +c23-bool-error.c:2:12: error: Trying to use reserved word 'true' as identifier +c23-bool-error.c:3:12: error: Trying to use reserved word 'false' as identifier +c23-bool-error.c:4:13: error: two or more data types in declaration specifiers +c23-bool-error.c:4:13: error: Trying to use reserved word 'bool' as identifier +c23-bool-error.c:8:14: error: not an lvalue +* check-error-end +*/
validation/c23-bool.c new file +45 -0
45 lines not on this page · raw message
PATCH 44/73 c23: Add support for nullptr and nullptr_t
In reply to Bart Van AsscheIntroduce the reserved C23 nullptr keyword and a dedicated nullptr_ctype base type representing nullptr_t per ISO C23 6.2.5 and 6.3.2.3:
- Evaluate nullptr as an address constant of type nullptr_ctype rather than an integer constant expression, rejecting nullptr in array bounds, enumerators, and switch controlling expressions.
- Support implicit and explicit conversions from nullptr_t expressions to any pointer type and bool, equality comparisons with pointers and null pointer constants, conditional expressions, _Generic associations, and variadic arguments, while rejecting relational comparisons, arithmetic, and non-bool/non-void/non-pointer casts.
- Lower nullptr_ctype as a pointer-sized null value in linearize and sparse-llvm.
--- evaluate.c | 186 +++++++++++++++++++++++++++++-- expression.c | 10 ++ ident-list.h | 1 + linearize.c | 2 + parse.c | 7 ++ show-parse.c | 1 + sparse-llvm.c | 26 +++-- symbol.c | 12 +- symbol.h | 13 ++- validation/backend/c23-nullptr.c | 21 ++++ validation/c23-nullptr-assign.c | 35 ++++++ validation/c23-nullptr-error.c | 107 ++++++++++++++++++ validation/c23-nullptr.c | 107 ++++++++++++++++++ validation/linear/c23-nullptr.c | 20 ++++ 14 files changed, 528 insertions(+), 20 deletions(-) create mode 100644 validation/backend/c23-nullptr.c create mode 100644 validation/c23-nullptr-assign.c create mode 100644 validation/c23-nullptr-error.c create mode 100644 validation/c23-nullptr.c create mode 100644 validation/linear/c23-nullptr.c
evaluate.c +178 -8
@@ -857,6 +857,8 @@ const char *type_difference(struct ctype *c1, struct ctype *c2,return "different address spaces" ;if (base1 != base2)return "different base types" ; +if (!base1 && t1->bit_size != t2->bit_size) +return "different base types" ;if (t1->rank != t2->rank)return "different type sizes" ; diff = (mod1 ^ mod2) & ~MOD_IGNORE ;
@@ -1106,7 +1108,11 @@ enum null_constant_type {static inline int is_null_pointer_constant (struct expression *e) { -if (e->ctype == &null_ctype) +if (e->ctype == &null_ctype || + (e->ctype && e->ctype->type ==SYM_NODE && e->ctype->ctype.base_type == &null_ctype)) +return NULL_PTR ; +if (is_nullptr_type (e->ctype) && + (e->type ==EXPR_VALUE || (e->flags &CEF_ADDR )))return NULL_PTR ;if (!(e->flags &CEF_ICE ))return NON_NULL ;
@@ -1148,6 +1154,87 @@ static struct symbol *evaluate_compare(struct expression *expr) goto OK; } +/* nullptr_t equality comparisons [C23 6.5.9] */ +if (ltype == &nullptr_ctype || rtype == &nullptr_ctype) { +int is_null1, is_null2; + +if (expr->op !=SPECIAL_EQUAL && expr->op !=SPECIAL_NOTEQUAL ) +return bad_expr_type (expr); + + is_null1 =is_null_pointer_constant (left); + is_null2 =is_null_pointer_constant (right); +if (ltype == &nullptr_ctype && rtype == &nullptr_ctype) { +if (is_null1 && is_null2) { + expr->type =EXPR_VALUE ; + expr->value = (expr->op ==SPECIAL_EQUAL ); + expr->flags |=CEF_ACE ; + } + goto OK; + } +if (ltype == &nullptr_ctype) { +if (rclass &TYPE_PTR ) { +if (is_null1 && is_null2) { +if (is_null2 ==NULL_ZERO ) +bad_null (right); + expr->type =EXPR_VALUE ; + expr->value = (expr->op ==SPECIAL_EQUAL ); + expr->flags |=CEF_ACE ; + goto OK; + } +if (rtype == &null_ctype) { + expr->left =cast_to (left, &ptr_ctype); + expr->right =cast_to (right, &ptr_ctype); + }else { + expr->left =cast_to (left, rtype); + } + goto OK; + } +if (is_null2) { +if (is_null2 ==NULL_ZERO ) +bad_null (right); +if (is_null1) { + expr->type =EXPR_VALUE ; + expr->value = (expr->op ==SPECIAL_EQUAL ); + expr->flags |=CEF_ACE ; + }else { + expr->right =cast_to (right, &nullptr_ctype); + } + goto OK; + } +return bad_expr_type (expr); + } +if (lclass &TYPE_PTR ) { +if (is_null1 && is_null2) { +if (is_null1 ==NULL_ZERO ) +bad_null (left); + expr->type =EXPR_VALUE ; + expr->value = (expr->op ==SPECIAL_EQUAL ); + expr->flags |=CEF_ACE ; + goto OK; + } +if (ltype == &null_ctype) { + expr->left =cast_to (left, &ptr_ctype); + expr->right =cast_to (right, &ptr_ctype); + }else { + expr->right =cast_to (right, ltype); + } + goto OK; + } +if (is_null1) { +if (is_null1 ==NULL_ZERO ) +bad_null (left); +if (is_null2) { + expr->type =EXPR_VALUE ; + expr->value = (expr->op ==SPECIAL_EQUAL ); + expr->flags |=CEF_ACE ; + }else { + expr->left =cast_to (left, &nullptr_ctype); + } + goto OK; + } +return bad_expr_type (expr); + } +/* at least one must be a pointer */ if (!((lclass | rclass) &TYPE_PTR ))return bad_expr_type (expr);
@@ -1276,6 +1363,29 @@ static struct symbol *evaluate_conditional_expression(struct expression *expr) goto out; } +if (ltype == &nullptr_ctype || rtype == &nullptr_ctype) { +if (ltype == &nullptr_ctype && rtype == &nullptr_ctype) { + ctype = &nullptr_ctype; + goto out; + } +if (ltype == &nullptr_ctype && (rclass &TYPE_PTR )) { + ctype = (rtype == &null_ctype) ? &ptr_ctype : rtype; + *cond =cast_to (*cond, ctype); +if (rtype == &null_ctype) + expr->cond_false =cast_to (expr->cond_false, ctype); + goto out; + } +if (rtype == &nullptr_ctype && (lclass &TYPE_PTR )) { + ctype = (ltype == &null_ctype) ? &ptr_ctype : ltype; +if (ltype == &null_ctype) + *cond =cast_to (*cond, ctype); + expr->cond_false =cast_to (expr->cond_false, ctype); + goto out; + } + typediff ="different types" ; + goto Err; + } +if ((lclass | rclass) &TYPE_PTR ) {int is_null1 =is_null_pointer_constant (*cond);int is_null2 =is_null_pointer_constant (expr->cond_false);
@@ -1486,6 +1596,20 @@ static int check_assignment_types(struct symbol *target, struct expression **rp,int tclass =classify_type (target, &t);int sclass =classify_type (source, &s); +if (t == &nullptr_ctype) { +int is_null; +if (s == &nullptr_ctype) +return 1 ; + is_null =is_null_pointer_constant (*rp); +if (is_null) { +if (is_null ==NULL_ZERO ) +bad_null (*rp); + goto Cast; + } + *typediff ="different base types" ; +return 0 ; + } +if (tclass & sclass &TYPE_NUM ) {if (tclass &TYPE_RESTRICT ) {/* allowed assignments unfoul */
@@ -1518,10 +1642,21 @@ static int check_assignment_types(struct symbol *target, struct expression **rp,bad_null (*rp); goto Cast; } +if (s == &nullptr_ctype) { +if (t == &null_ctype) { + *typediff ="different base types" ; +return 0 ; + } + goto Cast; + }if (!(sclass &TYPE_PTR )) { *typediff ="different base types" ;return 0 ; } +if (t == &null_ctype && s != &null_ctype) { + *typediff ="different base types" ; +return 0 ; + } b1 =examine_pointer_target (t); b2 =examine_pointer_target (s); mod1 = t->ctype.modifiers & (MOD_IGN |MOD_NODEREF );
@@ -1566,7 +1701,7 @@ static int check_assignment_types(struct symbol *target, struct expression **rp,if (tclass &TYPE_NUM ) {/* XXX: need to turn into comparison with NULL */ -if (is_bool_type (t) && (sclass &TYPE_PTR )) +if (is_bool_type (t) && ((sclass &TYPE_PTR ) || s == &nullptr_ctype)) goto Cast; *typediff ="different base types" ;return 0 ;
@@ -2067,9 +2202,13 @@ static struct symbol *evaluate_preop(struct expression *expr) expr->flags = expr->unop->flags & ~CEF_CONST_MASK ;/* * A logical negation never yields an address constant -* [6.6(9)]. +* [6.6(9)], though negating an address constant yields +* an arithmetic constant expression. */ - expr->flags &= ~CEF_ADDR ; +if (expr->unop->flags &CEF_ADDR ) { + expr->flags &= ~CEF_ADDR ; + expr->flags |=CEF_ACE ; + }if (is_safe_type (ctype))warning (expr->pos,"testing a 'safe expression'" );
@@ -2474,6 +2613,8 @@ int evaluate_arguments(struct symbol_list *argtypes, struct expression_list *hea *p =cast_to (expr, &ptr_ctype); elsedegenerate (expr ); + }else if (type == &nullptr_ctype) { +degenerate (expr); } }else if (!target->forced_arg){static char where[30 ];
@@ -2984,6 +3125,14 @@ static struct symbol *cast_to_bool(struct expression *expr)return NULL ; zero =alloc_const_expression (expr->pos,0 ); +if (otype == &nullptr_ctype) { + zero->ctype = otype; + expr->op =SPECIAL_NOTEQUAL ; + expr->type =EXPR_COMPARE ; + expr->left = old; + expr->right = zero; +return expr->ctype; + }if (oclass &TYPE_PTR ) zero->ctype = otype; expr->op =SPECIAL_NOTEQUAL ;
@@ -3030,7 +3179,7 @@ static int cast_flags(struct expression *expr, struct expression *old)*/ else if (old->flags & CEF_FLOAT) flags =CEF_SET_ICE ; - }else if (class &TYPE_PTR ) { + }else if ((class &TYPE_PTR ) || t == &nullptr_ctype) {/* * Casts of integer literals to pointer type yield * address constants [6.6(9)].
@@ -3145,6 +3294,19 @@ static struct symbol *evaluate_cast(struct expression *expr)if (expr->type ==EXPR_FORCE_CAST ) goto out; +if (ttype == &nullptr_ctype) { +if (stype != &nullptr_ctype && !is_null_pointer_constant (source)) +expression_error (expr,"conversion from '%s' to 'nullptr_t'" , +show_typename (source->ctype)); + goto out; + } +if (stype == &nullptr_ctype) { +if (!is_bool_type (ttype) && tclass !=TYPE_PTR ) +expression_error (expr,"conversion from 'nullptr_t' to '%s'" , +show_typename (ctype)); + goto out; + } +if (tclass & (TYPE_COMPOUND |TYPE_FN )) {/* * Special case: cast to union type (GCC extension)
@@ -3471,8 +3633,13 @@ static struct symbol *evaluate_generic_selection(struct expression *expr)return NULL ; } - source = *ctrl; - source.ctype.modifiers &= ~(MOD_QUALIFIER |MOD_ATOMIC ); +struct symbol *sel_ctrl = ctrl; + +if (ctrl->ctype.modifiers & (MOD_QUALIFIER |MOD_ATOMIC )) { + source = *ctrl; + source.ctype.modifiers &= ~(MOD_QUALIFIER |MOD_ATOMIC ); + sel_ctrl = &source; + }for (map = expr->map; map; map = map->next) {struct symbol *stype = map->type;struct symbol *base;
@@ -3509,7 +3676,7 @@ static struct symbol *evaluate_generic_selection(struct expression *expr)sparse_error (stype->pos,"incomplete type in generic selection" );continue ; } -if (!type_selection (&source, stype)) +if (!type_selection (sel_ctrl, stype))continue ; res = map->expr;
@@ -4009,6 +4176,9 @@ static void evaluate_switch_statement(struct statement *stmt)evaluate_statement (stmt->switch_statement);if (!sel)return ; +if (valid_type (sel->ctype) && !is_int_type (sel->ctype) && + !is_restricted_type (sel->ctype) && !is_fouled_type (sel->ctype)) +expression_error (sel,"switch quantity is not an integer" );if (sel->ctype &&is_enum_type (sel->ctype)) enumcase_holder =NULL ;/* Only check cases against switch */
expression.c +10 -0
@@ -480,6 +480,16 @@ struct token *primary_expression(struct token *token, struct expression **tree)break ; } +if (standard >=STANDARD_C23 && + token->ident == &nullptr_ident) { + expr =alloc_expression (token->pos,EXPR_VALUE ); + expr->flags =CEF_ADDR ; + expr->ctype = &nullptr_ctype; + expr->value =0 ; + token = next; +break ; + } + sym =lookup_symbol (token->ident,NS_SYMBOL |NS_TYPEDEF );if (!sym) {
ident-list.h +1 -0
@@ -48,6 +48,7 @@ IDENT(alignas);IDENT (alignof);IDENT (bool);IDENT (false); +IDENT (nullptr );IDENT (static_assert);IDENT (thread_local);IDENT (true);
linearize.c +2 -0
@@ -1276,6 +1276,8 @@ retry: switch (s->type) { case_int:return sign ?MTYPE_SINT :MTYPE_UINT ;case SYM_BASETYPE : +if (s == &nullptr_ctype) +return MTYPE_VPTR ;if (s->ctype.base_type == &fp_type)return MTYPE_FLOAT ;if (s->ctype.base_type == &int_type)
parse.c +7 -0
@@ -658,6 +658,7 @@ void init_parser_finalize(void) alignof_ident.reserved =1 ; true_ident.reserved =1 ; false_ident.reserved =1 ; + nullptr_ident.reserved =1 ; } }
@@ -1006,6 +1007,12 @@ static struct token *parse_enum_declaration(struct token *token, struct symbol * ctype = &void_ctype;if (expr && expr->ctype) ctype = expr->ctype; +if (is_nullptr_type (ctype)) { +sparse_error (expr->pos, +"enumerator value for '%s' is not an integer constant" , +show_ident (token->ident)); + ctype = &int_ctype; + } }else if (!ctype) { ctype = &int_ctype; }else if (is_int_type (ctype)) {
show-parse.c +1 -0
@@ -278,6 +278,7 @@ static struct ctype_name { { &void_ctype, "void", "" }, { &bool_ctype, "bool", "" }, + { &nullptr_ctype, "nullptr_t", "" }, { &float_ctype, "float", "F" }, { &double_ctype, "double", "" },
sparse-llvm.c +17 -9
@@ -154,6 +154,9 @@ static LLVMTypeRef sym_basetype_type(struct symbol *sym) {LLVMTypeRef ret =NULL ; +if (sym == &nullptr_ctype) +return LLVMPointerType (LLVMInt8TypeInContext (context),0 ); +if (is_float_type (sym)) {switch (sym->bit_size) {case 32 :
@@ -458,12 +461,17 @@ static LLVMValueRef value_to_ivalue(struct function *fn, struct symbol *ctype, Lreturn val; } +static inline bool is_llvm_ptr_type (struct symbol *type) +{ +return is_ptr_type (type) ||is_nullptr_type (type); +} +static LLVMValueRef value_to_pvalue (struct function *fn,struct symbol *ctype,LLVMValueRef val) {const char *name =LLVMGetValueName (val);LLVMTypeRef dtype =symbol_type (ctype); -assert (is_ptr_type (ctype)); +assert (is_llvm_ptr_type (ctype));switch (LLVMGetTypeKind (LLVMTypeOf (val))) {case LLVMIntegerTypeKind: val =LLVMBuildIntToPtr (fn->builder, val, dtype, name);
@@ -481,7 +489,7 @@ static LLVMValueRef adjust_type(struct function *fn, struct symbol *ctype, LLVMV {if (is_int_type (ctype))return value_to_ivalue (fn, ctype, val); -if (is_ptr_type (ctype)) +if (is_llvm_ptr_type (ctype))return value_to_pvalue (fn, ctype, val);return val; }
@@ -901,18 +909,18 @@ static void output_op_ptrcast(struct function *fn, struct instruction *insn)case OP_UTPTR :case OP_SEXT :// FIXME assert (is_int_type (otype)); -assert (is_ptr_type (insn->type)); +assert (is_llvm_ptr_type (insn->type)); op = LLVMIntToPtr;break ;case OP_PTRTU : -assert (is_ptr_type (otype)); +assert (is_llvm_ptr_type (otype));assert (is_int_type (insn->type)); op = LLVMPtrToInt;break ;case OP_PTRCAST :case OP_ZEXT :// FIXME -assert (is_ptr_type (otype)); -assert (is_ptr_type (insn->type)); +assert (is_llvm_ptr_type (otype)); +assert (is_llvm_ptr_type (insn->type)); op = LLVMBitCast;break ;default :
@@ -930,7 +938,7 @@ static void output_op_cast(struct function *fn, struct instruction *insn, LLVMOpstruct symbol *otype = insn->orig_type;char target_name[64 ]; -if (is_ptr_type (insn->type))// cast to void* is OP_CAST ... +if (is_llvm_ptr_type (insn->type))// cast to void* is OP_CAST ... return output_op_ptrcast (fn, insn);assert (is_int_type (insn->type));
@@ -939,7 +947,7 @@ static void output_op_cast(struct function *fn, struct instruction *insn, LLVMOppseudo_name (insn->target, target_name); dtype =symbol_type (insn->type); -if (is_ptr_type (otype)) { +if (is_llvm_ptr_type (otype)) { op = LLVMPtrToInt; }else if (is_float_type (otype)) {assert (op == LLVMFPToUI || op == LLVMFPToSI);
@@ -1252,7 +1260,7 @@ static LLVMValueRef output_data(LLVMModuleRef module, struct symbol *sym)if (initializer) {switch (initializer->type) {case EXPR_VALUE : - initial_value =LLVMConstInt (symbol_type (sym), initializer->value,1 ); + initial_value =constant_value (initializer->value,symbol_type (sym));break ;case EXPR_FVALUE : initial_value =LLVMConstReal (symbol_type (sym), initializer->fvalue);
symbol.c +10 -2
@@ -307,7 +307,14 @@ static struct symbol * examine_array_type(struct symbol *sym)unsigned long count =get_expression_value_silent (array_size);if (base_type->bit_size >=0 ) bit_size =array_element_offset (base_type->bit_size, count); -if (array_size->type !=EXPR_VALUE ) { +if (valid_type (array_size->ctype) && + !is_int_type (array_size->ctype) && + !is_restricted_type (array_size->ctype) && + !is_fouled_type (array_size->ctype)) { +sparse_error (array_size->pos, +"size of array has non-integer type" ); + bit_size =0 ; + }else if (array_size->type !=EXPR_VALUE ) {if (Wvla)warning (array_size->pos,"Variable length array is used." ); bit_size =-1 ;
@@ -875,7 +882,7 @@ struct symbol bool_ctype, void_ctype, type_ctype, float_ctype, double_ctype, ldouble_ctype, string_ctype, ptr_ctype, lazy_ptr_ctype, incomplete_ctype, label_ctype, bad_ctype, - null_ctype; + null_ctype, nullptr_ctype;struct symbol autotype_ctype;struct symbol schar_ptr_ctype, short_ptr_ctype;struct symbol int_ptr_ctype, uint_ptr_ctype;
@@ -942,6 +949,7 @@ static const struct ctype_declare { { &incomplete_ctype, T_BASETYPE }, { &autotype_ctype, T_BASETYPE }, { &bad_ctype, T_BASETYPE }, + { &nullptr_ctype, SYM_BASETYPE, 0, 0, &bits_in_pointer, &pointer_alignment, NULL }, { &char_ctype, T__INT(-2, char) }, { &schar_ctype, T_SINT(-2, char) },
symbol.h +12 -1
@@ -306,7 +306,7 @@ extern struct symbol bool_ctype, void_ctype, type_ctype, float_ctype, double_ctype, ldouble_ctype, string_ctype, ptr_ctype, lazy_ptr_ctype, incomplete_ctype, label_ctype, bad_ctype, - null_ctype; + null_ctype, nullptr_ctype;extern struct symbol autotype_ctype;extern struct symbol schar_ptr_ctype, short_ptr_ctype;extern struct symbol int_ptr_ctype, uint_ptr_ctype;
@@ -487,6 +487,13 @@ static inline int is_bool_type(struct symbol *type)return type == &bool_ctype; } +static inline int is_nullptr_type (const struct symbol *type) +{ +if (type && type->type ==SYM_NODE ) + type = type->ctype.base_type; +return type == &nullptr_ctype; +} +static inline int is_scalar_type (struct symbol *type) {if (type->type ==SYM_NODE )
@@ -505,6 +512,8 @@ static inline int is_scalar_type(struct symbol *type)return 1 ;if (type->ctype.base_type == &fp_type)return 1 ; +if (type == &nullptr_ctype) +return 1 ;return 0 ; }
@@ -524,6 +533,8 @@ static inline bool is_integral_type(struct symbol *type) }if (type->ctype.base_type == &int_type)return 1 ; +if (type == &nullptr_ctype) +return 1 ;return 0 ; }
validation/backend/c23-nullptr.c new file +21 -0
@@ -0,0 +1,21 @@ +typedef typeof (nullptr)nullptr_t ; + +extern int sink (const char *fmt, ...); + +static nullptr_t g_np =nullptr ; + +int test_nullptr_llvm (nullptr_t arg,int **out); +int test_nullptr_llvm (nullptr_t arg,int **out) +{ + *out = arg; + g_np =nullptr ; +return sink ("test" ,nullptr , arg, g_np); +} + +/* +* check-name: backend-c23-nullptr +* check-command: sparse-llvm-dis -m64 -std=c23 $file +* check-output-ignore +* check-output-contains: define i32 @test_nullptr_llvm( +* check-output-contains: @sink( +*/
validation/c23-nullptr-assign.c new file +35 -0
@@ -0,0 +1,35 @@ +typedef typeof (nullptr)nullptr_t ; + +void test (int *p,void *v) +{ +nullptr_t np; + np = p; + np = v; + np =0 ; + +int i =nullptr ; +double d = np; + (void )i; + (void )d; +} + +/* +* check-name: c23-nullptr-assign +* check-command: sparse -std=c23 -Wno-decl $file +* +* check-error-start +c23-nullptr-assign.c:6:12: warning: incorrect type in assignment (different base types) +c23-nullptr-assign.c:6:12: expected nullptr_t [usertype] np +c23-nullptr-assign.c:6:12: got int *p +c23-nullptr-assign.c:7:12: warning: incorrect type in assignment (different base types) +c23-nullptr-assign.c:7:12: expected nullptr_t [usertype] np +c23-nullptr-assign.c:7:12: got void *v +c23-nullptr-assign.c:8:14: warning: Using plain integer as NULL pointer +c23-nullptr-assign.c:10:17: warning: incorrect type in initializer (different base types) +c23-nullptr-assign.c:10:17: expected int i +c23-nullptr-assign.c:10:17: got nullptr_t +c23-nullptr-assign.c:11:20: warning: incorrect type in initializer (different base types) +c23-nullptr-assign.c:11:20: expected double d +c23-nullptr-assign.c:11:20: got nullptr_t [assigned] [usertype] np +* check-error-end +*/
validation/c23-nullptr-error.c new file +107 -0
107 lines not on this page · raw message
validation/c23-nullptr.c new file +107 -0
107 lines not on this page · raw message
validation/linear/c23-nullptr.c new file +20 -0
@@ -0,0 +1,20 @@ +typedef typeof (nullptr)nullptr_t ; + +static void *np_to_ptr (nullptr_t np) +{ +return np; +} + +static bool np_is_null (nullptr_t np) +{ +return !np; +} + +/* +* check-name: linear-c23-nullptr +* check-command: test-linearize -m64 -std=c23 $file +* +* check-output-ignore +* check-output-contains: ret\\.64 *%arg1 +* check-output-contains: seteq\\.1 +*/
PATCH 45/73 c23: Add support for digit separators in numeric literals
In reply to Bart Van AsscheAllow single quotes (') between digits in preprocessing numbers and strip them before parsing integer and floating-point values in expression.c to support C23 digit separators (WG14 N2626) and emit a pedantic warning in pre-C23 modes.
--- expression.c | 165 +++++++++++++++++++++ tokenize.c | 35 ++++- validation/c23-digit-separators-error.c | 36 +++++ validation/c23-digit-separators-pedantic.c | 12 ++ validation/c23-digit-separators.c | 29 ++++ 5 files changed, 275 insertions(+), 2 deletions(-) create mode 100644 validation/c23-digit-separators-error.c create mode 100644 validation/c23-digit-separators-pedantic.c create mode 100644 validation/c23-digit-separators.c
expression.c +165 -0
@@ -258,6 +258,157 @@ static unsigned long long parse_num(const char *nptr, char **end)return strtoull (nptr, end,0 ); } +static int is_digit_for_base (int c,int base) +{ +if (base ==2 ) +return c =='0' || c =='1' ; +if (base ==8 ) +return c >='0' && c <='7' ; +if (base ==16 ) +return isxdigit ((unsigned char )c); +return isdigit ((unsigned char )c); +} + +static int validate_digit_separators (struct expression *expr,const char *str) +{ +enum { +NUM_INT , +NUM_FRAC , +NUM_EXP_SIGN , +NUM_EXP , +NUM_SUFFIX , + } state =NUM_INT ; +int is_hex = (str[0 ] =='0' && (str[1 ] =='x' || str[1 ] =='X' )); +int is_bin = (str[0 ] =='0' && (str[1 ] =='b' || str[1 ] =='B' )); +int is_oct = (str[0 ] =='0' && !is_hex && !is_bin && +strchr (str,'.' ) ==NULL &&strchr (str,'e' ) ==NULL && +strchr (str,'E' ) ==NULL ); +int base = is_hex ?16 : is_bin ?2 : is_oct ?8 :10 ; +int in_digits =0 ; +int i = (is_hex || is_bin) ?2 :0 ; + +for (; str[i]; i++) { +char c = str[i]; + +if (c =='\'' ) { +char prev = i >0 ? str[i -1 ] :0 ; +char next = str[i +1 ]; + +if (prev =='\'' || next =='\'' ) { +sparse_error (expr->pos, +"adjacent digit separators" ); +return 0 ; + } +if (i ==2 && (is_hex || is_bin)) { +sparse_error ( + expr->pos, +"digit separator after base indicator" ); +return 0 ; + } +if (prev =='.' || next =='.' ) { +sparse_error ( + expr->pos, +"digit separator adjacent to decimal point" ); +return 0 ; + } +if (state ==NUM_EXP_SIGN || + (state !=NUM_SUFFIX && + ((is_hex && (next =='p' || next =='P' )) || + (!is_hex && (next =='e' || next =='E' )))) || + (!in_digits && state ==NUM_EXP )) { +sparse_error ( + expr->pos, +"digit separator adjacent to exponent" ); +return 0 ; + } +if (state ==NUM_SUFFIX || !in_digits || + !is_digit_for_base (next, base)) { +sparse_error ( + expr->pos, +"digit separator outside digit sequence" ); +return 0 ; + } + in_digits =0 ; +continue ; + } + +switch (state) { +case NUM_INT : +if (is_digit_for_base (c, base)) { + in_digits =1 ; + }else if (c =='.' && (base ==10 || base ==16 )) { + state =NUM_FRAC ; + in_digits =0 ; + }else if ((base ==10 && (c =='e' || c =='E' )) || + (base ==16 && (c =='p' || c =='P' ))) { + state =NUM_EXP_SIGN ; + base =10 ; + in_digits =0 ; + }else { + state =NUM_SUFFIX ; + in_digits =0 ; + } +break ; +case NUM_FRAC : +if (is_digit_for_base (c, base)) { + in_digits =1 ; + }else if ((base ==10 && (c =='e' || c =='E' )) || + (base ==16 && (c =='p' || c =='P' ))) { + state =NUM_EXP_SIGN ; + base =10 ; + in_digits =0 ; + }else { + state =NUM_SUFFIX ; + in_digits =0 ; + } +break ; +case NUM_EXP_SIGN : + state =NUM_EXP ; +if (c =='+' || c =='-' ) { + in_digits =0 ; + }else if (isdigit ((unsigned char )c)) { + in_digits =1 ; + }else { + state =NUM_SUFFIX ; + in_digits =0 ; + } +break ; +case NUM_EXP : +if (isdigit ((unsigned char )c)) { + in_digits =1 ; + }else { + state =NUM_SUFFIX ; + in_digits =0 ; + } +break ; +case NUM_SUFFIX : +break ; + } + } +return 1 ; +} + +static const char *strip_digit_separators (const char *str) +{ +size_t len; +char *buf, *dst; + +if (!strchr (str,'\'' )) +return str; + + len =strlen (str); + buf =__alloc_bytes (len +1 ); + dst = buf; + +while (*str) { +if (*str !='\'' ) + *dst++ = *str; + str++; + } + *dst ='\0' ; +return buf; +} +static void get_number_value (struct expression *expr,struct token *token) {const char *str = token->number;
@@ -268,6 +419,19 @@ static void get_number_value(struct expression *expr, struct token *token)int try_unsigned =1 ;int bits; +if (strchr (str,'\'' )) { +if (!validate_digit_separators (expr, str)) { + expr->type =EXPR_VALUE ; + expr->flags =CEF_SET_ICE ; + expr->ctype = &bad_ctype; +return ; + } +if (standard <STANDARD_C23 && Wpedantic) +warning (expr->pos, +"ISO C does not support digit separators before C23" ); + str =strip_digit_separators (str); + } + errno =0 ; value =parse_num (str, &end);if (end == str)
@@ -385,6 +549,7 @@ Float: Enoint:sparse_error (expr->pos,"constant %s is not a valid number" ,show_token (token)); expr->type =EXPR_VALUE ; + expr->flags =CEF_SET_ICE ; expr->value =0 ; expr->ctype = &int_ctype; }
tokenize.c +33 -2
@@ -50,6 +50,7 @@ typedef struct {int fd, offset, size;int pos, line, nr;int newline, whitespace; +int pushed_char;struct token **tokenlist;struct token *token;unsigned char *buffer;
@@ -446,8 +447,14 @@ got_eof:*/ static inline int nextchar (stream_t *stream) { -int offset = stream->offset; +int offset; +if (stream->pushed_char !=-2 ) { +int c = stream->pushed_char; + stream->pushed_char =-2 ; +return c; + } + offset = stream->offset;if (offset < stream->size) {int c = stream->buffer[offset++]; static const char special[256] = {
@@ -462,6 +469,19 @@ static inline int nextchar(stream_t *stream)return nextchar_slow (stream); } +static int peekchar (stream_t *stream) +{ +if (stream->pushed_char !=-2 ) +return stream->pushed_char; +if (stream->offset < stream->size) { +int c = stream->buffer[stream->offset]; +if (c !='\r' && c !='\\' ) +return c; + } + stream->pushed_char =nextchar_slow (stream); +return stream->pushed_char; +} +struct token eof_token_entry;static struct token *mark_eof (stream_t *stream)
@@ -558,8 +578,18 @@ static int get_one_number(int c, int next, stream_t *stream) *p++ = c;for (;;) {long class = cclass[next +1 ]; -if (!(class & (Dot | Digit | Letter))) +if (!(class & (Dot | Digit | Letter))) { +if (next =='\'' ) { +int after =peekchar (stream); +if (cclass[after +1 ] & (Digit | Letter)) { +if (p != buffer_end) + *p++ = next; + next =nextchar (stream); +continue ; + } + }break ; + }if (p != buffer_end) *p++ = next; next =nextchar (stream);
@@ -987,6 +1017,7 @@ static struct token *setup_stream(stream_t *stream, int idx, int fd, stream->offset =0 ; stream->size = buf_size; stream->buffer = buf; + stream->pushed_char =-2 ; begin =alloc_token (stream);token_type (begin) =TOKEN_STREAMBEGIN ;
validation/c23-digit-separators-error.c new file +36 -0
@@ -0,0 +1,36 @@ +int a = 1''0; +int b = 0x'1; +int b2 = 0b'1; +int c = 1'u; +int c2 = 123'u; +double d = 1.'0; +double e = 1'.'; +double f = 1e'0; +double g = 1'e0; +double h =1e +'0; +float i = 0x1p'0f; +float j =0x1.0p1'f ; +float k =1.0'f ; + +/* +* check-name: c23-digit-separators-error +* check-command: sparse -std=c23 -Wno-decl $file +* +* check-error-start +c23-digit-separators-error.c:1:10: error: Expected ; at end of declaration +c23-digit-separators-error.c:1:10: error: got '' +c23-digit-separators-error.c:2:9: error: digit separator after base indicator +c23-digit-separators-error.c:3:10: error: digit separator after base indicator +c23-digit-separators-error.c:4:9: error: digit separator outside digit sequence +c23-digit-separators-error.c:5:10: error: digit separator outside digit sequence +c23-digit-separators-error.c:6:12: error: digit separator adjacent to decimal point +c23-digit-separators-error.c:7:13: error: Expected ; at end of declaration +c23-digit-separators-error.c:7:13: error: got '.' +c23-digit-separators-error.c:8:12: error: digit separator adjacent to exponent +c23-digit-separators-error.c:9:12: error: digit separator adjacent to exponent +c23-digit-separators-error.c:10:12: error: digit separator adjacent to exponent +c23-digit-separators-error.c:11:11: error: digit separator adjacent to exponent +c23-digit-separators-error.c:12:11: error: digit separator outside digit sequence +c23-digit-separators-error.c:13:11: error: digit separator outside digit sequence +* check-error-end +*/
validation/c23-digit-separators-pedantic.c new file +12 -0
@@ -0,0 +1,12 @@ +int a =1'000 ; +double b =1'0.5 ; + +/* +* check-name: c23-digit-separators-pedantic +* check-command: sparse -std=c17 -Wpedantic -Wno-decl $file +* +* check-error-start +c23-digit-separators-pedantic.c:1:9: warning: ISO C does not support digit separators before C23 +c23-digit-separators-pedantic.c:2:12: warning: ISO C does not support digit separators before C23 +* check-error-end +*/
validation/c23-digit-separators.c new file +29 -0
@@ -0,0 +1,29 @@ +#if 0 +0' ' +1'+'2 +#endif + +#if 1'000 +2'000 ==3'000 +int pp =1 ; +#endif + +_Static_assert (1'000'000 ==1000000 ,"dec" ); +_Static_assert (0xdead'beef ==0xdeadbeef ,"hex" ); +_Static_assert (0XCAFE'BABE ==0xCAFEBABE ,"hex upper" ); +_Static_assert (0b1010'0101 ==0xa5 ,"bin" ); +_Static_assert (0B1111'0000 ==0xf0 ,"bin upper" ); +_Static_assert (0'123'456 ==0123456 ,"oct" ); +_Static_assert (1'000ULL ==1000ULL ,"ull" ); + +static int a =1'000'000 ; +static unsigned int b =0xdead'beef ; +static int c =0b1010'0101 ; +static int d =0'123'456 ; +static double e =1'000.000'1 ; +static double f =1'2.3'4e1'0 ; +static float g =0x1'a.b'cp1'0f ; + +/* +* check-name: c23-digit-separators +* check-command: sparse -std=c23 -Wno-decl $file +*/
PATCH 46/73 c23: Support unnamed parameters in function definitions
In reply to Bart Van AsscheAllow function definitions to omit parameter names in C23 mode per ISO C23 6.9.1 while rejecting unnamed parameters as an error in pre-C23 standards:
- Check for missing type specifiers before skipping local scope binding for unnamed parameters.
- Preserve argument side effects when inlining calls to functions with unnamed parameters without triggering unreplaced-symbol warnings.
- Advance parameter slot indices across unnamed parameters during linearization so subsequent named parameters keep their ABI slot index.
- Reject qualified, named, or multi-parameter uses of 'void'.
--- inline.c | 6 ++- linearize.c | 8 ++-- parse.c | 27 +++++++++----- validation/c23-unnamed-params-error.c | 27 ++++++++++++++ validation/c23-unnamed-params-pedantic.c | 12 ++++++ validation/c23-unnamed-params.c | 47 ++++++++++++++++++++++++ validation/linear/c23-unnamed-params.c | 27 ++++++++++++++ 7 files changed, 141 insertions(+), 13 deletions(-) create mode 100644 validation/c23-unnamed-params-error.c create mode 100644 validation/c23-unnamed-params-pedantic.c create mode 100644 validation/c23-unnamed-params.c create mode 100644 validation/linear/c23-unnamed-params.c
inline.c +5 -1
@@ -631,7 +631,7 @@ int inline_function(struct expression *expr, struct symbol *sym) FOR_EACH_PTR(expr->args, arg) {struct symbol *a =alloc_symbol (arg->pos,SYM_NODE ); -if (name) { +if (name && name->ident) { *a = *name; a->bb_target =NULL ; a->pseudo =NULL ;
@@ -639,6 +639,10 @@ int inline_function(struct expression *expr, struct symbol *sym)add_symbol (&fn_symbol_list, a); a->initializer = arg;add_symbol (&arg_decl, a); + }else if (name) { + *a = *name; + a->initializer = arg; +add_symbol (&arg_decl, a); }else {// This may create a node of a node but it will // be resolved later when the corresponding
linearize.c +5 -3
@@ -2607,12 +2607,14 @@ static struct entrypoint *linearize_fn(struct symbol *sym, struct symbol *base_tadd_one_insn (ep, entry); ep->entry = entry; -concat_symbol_list (base_type->arguments, &ep->syms); -/* FIXME!! We should do something else about varargs.. */ i =0 ; FOR_EACH_PTR(base_type->arguments, arg) { -linearize_argument (ep, arg, ++i); + ++i; +if (!arg->ident) +continue ; +add_symbol (&ep->syms, arg); +linearize_argument (ep, arg, i); }END_FOR_EACH_PTR (arg); result =linearize_fn_statement (ep, stmt);
parse.c +18 -9
@@ -1702,6 +1702,8 @@ static struct token *declaration_specifiers(struct token *token, struct decl_staspecifier_conflict (token->pos, seen & s->op->test, token->ident); + ctx->ctype.base_type = &bad_ctype; + seen |= Set_S;break ; } seen |= s->op->set;
@@ -2772,10 +2774,12 @@ static struct token *parameter_type_list(struct token *token, struct symbol *fn) sym =alloc_symbol (token->pos,SYM_NODE ); token =parameter_declaration (token, sym);if (sym->ctype.base_type == &void_ctype) { -/* Special case: (void) */ -if (!*list && !sym->ident) +/* Special case: sole unnamed unqualified (void) */ +if (!*list && !sym->ident &&match_op (token,')' ) && + !(sym->ctype.modifiers & (MOD_QUALIFIER |MOD_STORAGE |MOD_ATOMIC )))break ; -warning (token->pos,"void parameter" ); +sparse_error (sym->pos,"'void' must be the only parameter" ); + sym->ctype.base_type = &bad_ctype; }add_symbol (list, sym);if (!match_op (token,',' ))
@@ -2917,18 +2921,23 @@ struct token *initializer(struct expression **tree, struct token *token)static void declare_argument (struct symbol *sym,struct symbol *fn) { -if (!sym->ident) { -sparse_error (sym->pos,"no identifier for function argument" ); -return ; - }if (sym->ctype.base_type == &incomplete_ctype) { sym->ctype.base_type = &int_ctype;if (Wimplicit_int) { -sparse_error (sym->pos,"missing type declaration for parameter '%s'" , -show_ident (sym->ident)); +if (sym->ident) +sparse_error (sym->pos,"missing type declaration for parameter '%s'" , +show_ident (sym->ident)); +else +sparse_error (sym->pos,"missing type declaration for parameter" ); } } +if (!sym->ident) { +if (standard <STANDARD_C23 && sym->ctype.base_type != &bad_ctype) +sparse_error (sym->pos, +"omitting parameter name in function definition is a C23 feature" ); +return ; + }bind_symbol (sym, sym->ident,NS_SYMBOL ); }
validation/c23-unnamed-params-error.c new file +27 -0
@@ -0,0 +1,27 @@ +static void f_implicit(const) +{ +} + +static void f_void1 (void ,int ) +{ +} + +static void f_void2 (int ,void ) +{ +} + +static void f_cvoid (const void ) +{ +} + +/* +* check-name: c23-unnamed-params-error +* check-command: sparse -std=c23 $file +* +* check-error-start +c23-unnamed-params-error.c:1:24: error: missing type declaration for parameter +c23-unnamed-params-error.c:5:21: error: 'void' must be the only parameter +c23-unnamed-params-error.c:9:26: error: 'void' must be the only parameter +c23-unnamed-params-error.c:13:21: error: 'void' must be the only parameter +* check-error-end +*/
validation/c23-unnamed-params-pedantic.c new file +12 -0
@@ -0,0 +1,12 @@ +static void f1 (int ) +{ +} + +/* +* check-name: c23-unnamed-params-pedantic +* check-command: sparse -std=c11 $file +* +* check-error-start +c23-unnamed-params-pedantic.c:1:16: error: omitting parameter name in function definition is a C23 feature +* check-error-end +*/
validation/c23-unnamed-params.c new file +47 -0
47 lines not on this page · raw message
validation/linear/c23-unnamed-params.c new file +27 -0
@@ -0,0 +1,27 @@ +int f3 (int a,double ,int b); +int f3 (int a,double ,int b) +{ +return a + b; +} + +static inline int inl (int a,int ,int b) +{ +return a + b; +} + +extern int side_effect (void ); + +int caller (void ); +int caller (void ) +{ +return inl (10 ,side_effect (),20 ); +} + +/* +* check-name: linear-c23-unnamed-params +* check-command: test-linearize -m64 -std=c23 $file +* +* check-output-ignore +* check-output-contains: add\\.32 *%r[0-9]* <- %arg1, %arg3 +* check-output-contains: call\\.32 *%r[0-9]* <- side_effect +*/
PATCH 47/73 c23: Support variadic functions without named parameters
In reply to Bart Van AsscheAllow variadic function prototypes and definitions of the form 'f(...)' without a preceding named parameter and support single-argument va_start in C23 mode per ISO C23 6.7.6.3 and 7.16.1.4:
- Replace the predefined 2-argument __builtin_va_start macro in lib.c with builtin handlers for __builtin_va_start and __builtin_c23_va_start in builtin.c so <stdarg.h> works with both va_start(ap) and va_start(ap, ...).
- Validate that va_start appears inside a variadic function on a modifiable va_list lvalue, leave extra C23 va_start arguments unevaluated, and lower va_start to initialize ap.
--- builtin.c | 77 ++++++++++++++++++++++++++++++ lib.c | 1 - parse.c | 5 +- validation/c11-va-start-error.c | 20 ++++++++ validation/c23-variadic-error.c | 41 ++++++++++++++++ validation/c23-variadic-no-named.c | 47 ++++++++++++++++++ validation/linear/c23-va-start.c | 22 +++++++++ 7 files changed, 210 insertions(+), 3 deletions(-) create mode 100644 validation/c11-va-start-error.c create mode 100644 validation/c23-variadic-error.c create mode 100644 validation/c23-variadic-no-named.c create mode 100644 validation/linear/c23-va-start.c
builtin.c +77 -0
@@ -638,6 +638,81 @@ static struct symbol_op object_size_op = { .expand = expand_object_size, }; +static int args_va_start (struct expression *expr) +{ +struct symbol *sym = expr->fn->ctype; +bool is_c23 = !strcmp (show_ident (sym->ident),"__builtin_c23_va_start" ); +int n =expression_list_size (expr->args); +struct expression *arg; +int i =0 ; + +if (n <1 || (!is_c23 && standard <STANDARD_C23 && n <2 )) { +expression_error (expr,"not enough arguments for %s" , +show_ident (sym->ident)); +return 0 ; + } +if (!is_c23 && n >2 ) { +expression_error (expr,"too many arguments for %s" , +show_ident (sym->ident)); +return 0 ; + } + FOR_EACH_PTR(expr->args, arg) { +if (i ==1 && !is_c23) { +if (!evaluate_expression (arg)) +return 0 ; + } + i++; + }END_FOR_EACH_PTR (arg); +return 1 ; +} + +static int evaluate_va_start (struct expression *expr) +{ +struct expression *ap =first_expression (expr->args); +struct symbol *fntype = current_fn ? current_fn->ctype.base_type :NULL ; +struct expression *assign, *rhs; + +if (current_fn && current_fn->type ==SYM_FN ) + fntype = current_fn; +if (!fntype || !fntype->variadic) { +expression_error (expr,"'va_start' used in function with fixed args" ); +return 1 ; + } + +if (!evaluate_expression (ap) || !valid_type (ap->ctype)) +return 1 ; + { +struct symbol *atype = ap->ctype; +while (atype && atype->type ==SYM_NODE ) + atype = atype->ctype.base_type; +if (atype != &ptr_ctype) { +expression_error (expr,"incorrect type in 'va_start'" ); +return 1 ; + } + } + + rhs =alloc_expression (expr->pos,EXPR_VALUE ); + rhs->ctype = &ptr_ctype; + rhs->value =0 ; + + assign =alloc_expression (expr->pos,EXPR_ASSIGNMENT ); + assign->op ='=' ; + assign->left = ap; + assign->right = rhs; +evaluate_expression (assign); + + expr->type =EXPR_CAST ; + expr->cast_type = &void_ctype; + expr->cast_expression = assign; + expr->ctype = &void_ctype; +return 1 ; +} + +static struct symbol_op va_start_op = { + .args = args_va_start, + .evaluate = evaluate_va_start, +}; +static int evaluate_strlen (struct expression *expr) {struct expression *arg =first_expression (expr->args);
@@ -876,7 +951,9 @@ static const struct builtin_fn builtins_common[] = { { "__builtin_usub_overflow", &bool_ctype, 0, { &uint_ctype, &uint_ctype, &uint_ptr_ctype }}, { "__builtin_usubl_overflow", &bool_ctype, 0, { &ulong_ctype, &ulong_ctype, &ulong_ptr_ctype }}, { "__builtin_usubll_overflow", &bool_ctype, 0, { &ullong_ctype, &ullong_ctype, &ullong_ptr_ctype }}, + { "__builtin_c23_va_start", &void_ctype, 1, .op = &va_start_op }, { "__builtin_va_arg_pack_len", size_t_ctype, 0 }, + { "__builtin_va_start", &void_ctype, 1, .op = &va_start_op }, { "__builtin_vprintf", &int_ctype, 0, { &const_string_ctype, va_list_ctype }}, { "__builtin_vsnprintf", &int_ctype, 0, { &string_ctype, size_t_ctype, &const_string_ctype, va_list_ctype }}, { "__builtin_vsprintf", &int_ctype, 0, { &string_ctype, &const_string_ctype, va_list_ctype }},
lib.c +0 -1
@@ -299,7 +299,6 @@ static void create_builtin_stream(void)add_pre_buffer ("#add_system \"%s/include-fixed\"\n" , gcc_base_dir);add_pre_buffer ("#define __builtin_stdarg_start(a,b) ((a) = (__builtin_va_list)(&(b)))\n" ); -add_pre_buffer ("#define __builtin_va_start(a,b) ((a) = (__builtin_va_list)(&(b)))\n" );add_pre_buffer ("#define __builtin_ms_va_start(a,b) ((a) = (__builtin_ms_va_list)(&(b)))\n" );add_pre_buffer ("#define __builtin_va_arg(arg,type) ({ type __va_arg_ret = *(type *)(arg); arg += sizeof(type); __va_arg_ret; })\n" );add_pre_buffer ("#define __builtin_va_alist (*(void *)0)\n" );
parse.c +3 -2
@@ -1926,8 +1926,9 @@ static enum kind which_func(struct token *token, }if (next->special ==SPECIAL_ELLIPSIS ) { -warning (next->pos, -"variadic functions must have one named argument" ); +if (standard <STANDARD_C23 ) +warning (next->pos, +"variadic functions must have one named argument" );return Proto; }
validation/c11-va-start-error.c new file +20 -0
@@ -0,0 +1,20 @@ +#include <stdarg.h> + +static void f (int n, ...) +{ +va_list ap; + (void )n; +va_start (ap); +__builtin_va_start (ap); +} + +/* +* check-name: c11-va-start-error +* check-command: sparse -std=c11 $file +* +* check-error-start +c11-va-start-error.c:7:9: error: macro "va_start" requires 2 arguments, but only 1 given +c11-va-start-error.c:7:9: error: undefined identifier 'va_start' +c11-va-start-error.c:8:27: error: not enough arguments for __builtin_va_start +* check-error-end +*/
validation/c23-variadic-error.c new file +41 -0
41 lines not on this page · raw message
validation/c23-variadic-no-named.c new file +47 -0
47 lines not on this page · raw message
validation/linear/c23-va-start.c new file +22 -0
@@ -0,0 +1,22 @@ +#include <stdarg.h> + +int first_arg (...); +int first_arg (...) +{ +va_list ap; +int v; + +va_start (ap); + v =va_arg (ap, int); +va_end (ap); +return v; +} + +/* +* check-name: linear-c23-va-start +* check-command: test-linearize -m64 -std=c23 -Wuninitialized $file +* +* check-output-ignore +* check-output-excludes: __builtin_va_start +* check-output-excludes: __builtin_c23_va_start +*/
PATCH 48/73 c23: Support labels before declarations and at block ends
In reply to Bart Van AsscheAllow named, case, and default labels (including chained labels) to precede declarations and closing '}' braces inside compound statements per ISO C23 6.8.1 and 6.8.2:
- Handle label chains at the block-item level in statement_list() by attaching a synthesized empty statement when a label precedes a declaration, static_assert, or '}', and emit pedantic warnings in pre-C23 modes.
- Keep substatements of selection and iteration statements restricted to true statements in statement() so invalid forms such as 'if (c) int x = 1;' and '{ if (c) lbl: }' are rejected cleanly.
- Recognize labels whose identifier shadows an outer typedef name.
--- parse.c | 206 ++++++++++++++++++++++--------- validation/c23-labels-error.c | 48 +++++++ validation/c23-labels-gnu.c | 15 +++ validation/c23-labels-pedantic.c | 15 +++ validation/c23-labels.c | 67 ++++++++++ 5 files changed, 296 insertions(+), 55 deletions(-) create mode 100644 validation/c23-labels-error.c create mode 100644 validation/c23-labels-gnu.c create mode 100644 validation/c23-labels-pedantic.c create mode 100644 validation/c23-labels.c
parse.c +151 -55
@@ -62,8 +62,6 @@ static declarator_t autotype_specifier;static struct token *parse_if_statement (struct token *token,struct statement *stmt);static struct token *parse_return_statement (struct token *token,struct statement *stmt);static struct token *parse_loop_iterator (struct token *token,struct statement *stmt); -static struct token *parse_default_statement (struct token *token,struct statement *stmt); -static struct token *parse_case_statement (struct token *token,struct statement *stmt);static struct token *parse_switch_statement (struct token *token,struct statement *stmt);static struct token *parse_for_statement (struct token *token,struct statement *stmt);static struct token *parse_while_statement (struct token *token,struct statement *stmt);
@@ -315,11 +313,9 @@ static struct symbol_op loop_iter_op = { };static struct symbol_op default_op = { - .statement = parse_default_statement, };static struct symbol_op case_op = { - .statement = parse_case_statement, };static struct symbol_op switch_op = {
@@ -2518,32 +2514,6 @@ static struct token *parse_if_statement(struct token *token, struct statement *sreturn statement (token->next, &stmt->if_false); } -static inline struct token *case_statement (struct token *token,struct statement *stmt) -{ - stmt->type =STMT_CASE ; - token =expect (token,':' ,"after default/case" ); -add_case_statement (stmt); -if (match_op (token,'}' )) { -warning (token->pos,"statement expected after case label" ); - stmt->case_statement =alloc_statement (token->pos,STMT_NONE ); -return token; - } -return statement (token, &stmt->case_statement); -} - -static struct token *parse_case_statement (struct token *token,struct statement *stmt) -{ - token =parse_expression (token->next, &stmt->case_expression); -if (match_op (token,SPECIAL_ELLIPSIS )) - token =parse_expression (token->next, &stmt->case_to); -return case_statement (token, stmt); -} - -static struct token *parse_default_statement (struct token *token,struct statement *stmt) -{ -return case_statement (token->next, stmt); -} -static struct token *parse_loop_iterator (struct token *token,struct statement *stmt) {struct symbol *target =lookup_symbol (token->ident,NS_ITERATOR );
@@ -2646,46 +2616,129 @@ static struct token *handle_label_attributes(struct token *token, struct symbolreturn token; } +static bool is_label_token (struct token *token) +{ +struct token *p = token; +struct symbol *s; + +if (token_type (p) !=TOKEN_IDENT ) +return false; +if (p->ident == &case_ident || p->ident == &default_ident) +return true; + s =lookup_keyword (p->ident,NS_KEYWORD ); +if (s && s->op->statement) +return false; +if (p->ident->reserved) +return false; +return match_op (p->next,':' ); +} + +static struct token *parse_one_label (struct token *token, +struct statement **stmtp, +bool *is_case) +{ +struct decl_state attr_state = { }; +struct statement *stmt; + + *stmtp =NULL ; + *is_case = false; + +if (token->ident == &case_ident) { + stmt =alloc_statement (token->pos,STMT_CASE ); + token =parse_expression (token->next, &stmt->case_expression); +if (match_op (token,SPECIAL_ELLIPSIS )) + token =parse_expression (token->next, &stmt->case_to); + token =expect (token,':' ,"after default/case" ); +add_case_statement (stmt); + *stmtp = stmt; + *is_case = true; +return token; + } +if (token->ident == &default_ident) { + stmt =alloc_statement (token->pos,STMT_CASE ); + token =expect (token->next,':' ,"after default/case" ); +add_case_statement (stmt); + *stmtp = stmt; + *is_case = true; +return token; + } + + { +struct position pos = token->pos; +struct symbol *s =label_symbol (token,0 ); + s->label_modifiers |= attr_state.ctype.modifiers; + token =handle_label_attributes (token->next->next, s); +if (s->stmt) { +sparse_error (pos,"label '%s' redefined" , +show_ident (s->ident)); +return token; + } + stmt =alloc_statement (pos,STMT_LABEL ); + stmt->label_identifier = s; + stmt->label_scope = label_scope; +if (s->label_scope) { +if (!is_in_scope (label_scope, s->label_scope)) +warn_label_usage (stmt->pos, s->label_pos, + s->ident); + } + s->stmt = stmt; + *stmtp = stmt; +return token; + } +} +static struct token *statement (struct token *token,struct statement **tree) {struct statement *stmt =alloc_statement (token->pos,STMT_NONE ); +if (is_label_token (token)) { +struct statement *lbl =NULL ; +bool is_case = false; + + token =parse_one_label (token, &lbl, &is_case); +if (!lbl) +return statement (token, tree); + *tree = lbl; + tree = is_case ? &lbl->case_statement : &lbl->label_statement; +if (match_op (token,'}' )) { +sparse_error (token->pos, + is_case ?"statement expected after case label" : +"statement expected after label" ); + *tree =alloc_statement (token->pos,STMT_NONE ); +return token; + } +return statement (token, tree); + } + *tree = stmt;if (token_type (token) ==TOKEN_IDENT ) {struct symbol *s =lookup_keyword (token->ident,NS_KEYWORD );if (s && s->op->statement)return s->op->statement (token, stmt); - -if (match_op (token->next,':' )) { -struct symbol *s =label_symbol (token,0 ); - token =handle_label_attributes (token->next->next, s); -if (s->stmt) { -sparse_error (stmt->pos,"label '%s' redefined" ,show_ident (s->ident)); -// skip the label to avoid multiple definitions -return statement (token, tree); - } - stmt->type =STMT_LABEL ; - stmt->label_identifier = s; - stmt->label_scope = label_scope; -if (s->label_scope) { -if (!is_in_scope (label_scope, s->label_scope)) -warn_label_usage (stmt->pos, s->label_pos, s->ident); - } - s->stmt = stmt; -if (match_op (token,'}' )) { -warning (token->pos,"statement expected after label" ); - stmt->label_statement =alloc_statement (token->pos,STMT_NONE ); -return token; - } -return statement (token, &stmt->label_statement); - } }if (match_op (token,'{' )) { token =compound_statement (token->next, stmt);return expect (token,'}' ,"at end of compound statement" ); } - + +if (match_ident (token, &_Static_assert_ident) || + (standard >=STANDARD_C23 && +match_ident (token, &static_assert_ident))) { +sparse_error (token->pos,"declaration is not a statement" ); + stmt->type =STMT_NONE ; +return parse_static_assert (token,NULL ); + } + +if (lookup_type (token)) { +sparse_error (token->pos,"declaration is not a statement" ); + stmt->type =STMT_DECLARATION ; +start_block_scope (); + token =external_declaration (token, &stmt->declaration,NULL ); +end_block_scope (); +return token; + } + stmt->type =STMT_EXPRESSION ;return expression_statement (token, &stmt->expression); }
@@ -2714,6 +2767,49 @@ static struct token * statement_list(struct token *token, struct statement_list token =label_statement (token->next);for (;;) {struct statement * stmt; +struct statement *label_head =NULL ; +struct statement **label_tail = &label_head; +bool last_is_case = false; + +while (is_label_token (token)) { +struct statement *lbl =NULL ; +bool is_case = false; + + token =parse_one_label (token, &lbl, &is_case); +if (!lbl) +continue ; + *label_tail = lbl; + label_tail = is_case ? &lbl->case_statement : + &lbl->label_statement; + last_is_case = is_case; + } +if (label_head) { +if (eof_token (token) ||match_op (token,'}' )) { +if (standard <STANDARD_C23 ) +warning (token->pos, + last_is_case ?"statement expected after case label" : +"statement expected after label" ); + *label_tail =alloc_statement (token->pos,STMT_NONE ); +add_statement (list, label_head); +break ; + } +if (match_ident (token, &_Static_assert_ident) || + (standard >=STANDARD_C23 && +match_ident (token, &static_assert_ident)) || +lookup_type (token)) { +if (standard <STANDARD_C23 && Wpedantic) +warning (token->pos, +"a label can only be part of a statement and a declaration is not a statement" ); + *label_tail =alloc_statement (token->pos,STMT_NONE ); +add_statement (list, label_head); + }else { + seen_statement = Wdeclarationafterstatement; + token =statement (token, label_tail); +add_statement (list, label_head); +continue ; + } + } +if (eof_token (token))break ;if (match_op (token,'}' ))
validation/c23-labels-error.c new file +48 -0
48 lines not on this page · raw message
validation/c23-labels-gnu.c new file +15 -0
@@ -0,0 +1,15 @@ +static int test_gnu_case_range (int c) +{ +switch (c) { + case 1 ... 5: +int a =3 ; +return a; + case 6 ... 9: + } +return 0 ; +} + +/* +* check-name: c23-labels-gnu +* check-command: sparse -std=gnu23 -Wno-decl $file +*/
validation/c23-labels-pedantic.c new file +15 -0
@@ -0,0 +1,15 @@ +static void test_label_decl (void ) +{ + goto lbl; +lbl: +int x =42 ; +} + +/* +* check-name: c23-labels-pedantic +* check-command: sparse -std=c11 -pedantic -Wno-decl $file +* +* check-error-start +c23-labels-pedantic.c:5:9: warning: a label can only be part of a statement and a declaration is not a statement +* check-error-end +*/
validation/c23-labels.c new file +67 -0
67 lines not on this page · raw message
PATCH 49/73 c23: Support auto type inference
In reply to Bart Van AsscheAdd ISO C23 'auto' type inference when 'auto' appears without a type specifier, while preserving 'auto' as a block-scope storage-class specifier when combined with an explicit type:
- Infer the variable type from its assignment-expression initializer after array-to-pointer, function-to-pointer, and lvalue conversion so top-level qualifiers and _Atomic are stripped per C23 6.7.10p2.
- Bind C23 'auto' symbols before parsing their initializers and mark them underspecified during initializer parsing and evaluation so self-references are diagnosed per C23 6.2.1p7.
- Diagnose underspecified redeclarations in the same scope per C23 6.7p12, braced initializers, typedefs, empty declarations, type names, parameters, struct/union members, and file-scope 'auto' specifiers.
--- evaluate.c | 14 +++- parse.c | 129 +++++++++++++++++++++++++++++++++--- symbol.c | 59 ++++++++++++++++- symbol.h | 3 + validation/c23-auto-error.c | 68 +++++++++++++++++++ validation/c23-auto.c | 107 ++++++++++++++++++++++++++++++ 6 files changed, 365 insertions(+), 15 deletions(-) create mode 100644 validation/c23-auto-error.c create mode 100644 validation/c23-auto.c
evaluate.c +13 -1
@@ -87,6 +87,12 @@ static struct symbol *evaluate_symbol_expression(struct expression *expr)expression_error (expr,"undefined identifier '%s'" ,show_ident (expr->symbol_name));return NULL ; } +if (sym->underspecified) { +expression_error (expr, +"underspecified symbol '%s' used in its own initializer" , +show_ident (sym->ident)); +return NULL ; + }examine_symbol_type (sym);
@@ -3853,8 +3859,14 @@ static struct symbol *evaluate_symbol(struct symbol *sym)return NULL ;/* Evaluate the initializers */ -if (sym->initializer) +if (sym->initializer) { +bool mark_underspec = sym->c23_auto; +if (mark_underspec) + sym->underspecified =1 ;evaluate_initializer (sym, &sym->initializer); +if (mark_underspec) + sym->underspecified =0 ; + }/* And finally, evaluate the body of the symbol too */ if (base_type->type ==SYM_FN ) {
parse.c +118 -11
240 lines not on this page · raw message
symbol.c +56 -3
71 lines not on this page · raw message
symbol.h +3 -0
@@ -115,6 +115,7 @@ struct decl_state {unsigned char autotype;unsigned char forced;unsigned char packed; +unsigned char has_auto;unsigned char has_alignas;unsigned char designated_init;unsigned char transparent_union;
@@ -201,6 +202,8 @@ struct symbol { packed:1 , transparent_union:1; unsigned int has_alignas : 1; + unsigned int underspecified : 1; + unsigned int c23_auto : 1; int rank:3; // arithmetic's rankstruct expression *array_size;struct ctype ctype;
validation/c23-auto-error.c new file +68 -0
68 lines not on this page · raw message
validation/c23-auto.c new file +107 -0
107 lines not on this page · raw message
PATCH 50/73 c23: Support constexpr object specifier
In reply to Bart Van AsscheAdd support for the ISO C23 'constexpr' object specifier and enforce its linkage, qualification, and constant-initializer rules:
- Apply 'const' qualification after declarator parsing (cloning array chains) so pointers become top-level const ('int *const') and array elements become const without mutating shared array typedefs.
- Include MOD_CONSTEXPR in MOD_IGNORE for _Generic selection and give file-scope constexpr objects internal linkage per C23 6.2.2p3.
- Allow block-scope 'constexpr register' and 'constexpr auto', while rejecting constexpr on functions, parameters, struct/union members, empty declarations, typedefs, extern, thread_local, file-scope register, VLAs, and volatile, _Atomic, or restrict types.
- Mark constexpr symbols underspecified during initializer evaluation and validate scalar and aggregate initializers for null pointers, integer constant expressions, and exact target representability.
--- evaluate.c | 261 ++++++++++++++++++++++++++- expand.c | 90 +++++++-- expand.h | 3 + ident-list.h | 1 + parse.c | 108 ++++++++++- show-parse.c | 51 +++--- symbol.c | 6 +- symbol.h | 17 +- validation/c23-constexpr-error.c | 92 ++++++++++ validation/c23-constexpr-self-init.c | 41 +++++ validation/c23-constexpr.c | 100 ++++++++++ 11 files changed, 706 insertions(+), 64 deletions(-) create mode 100644 validation/c23-constexpr-error.c create mode 100644 validation/c23-constexpr-self-init.c create mode 100644 validation/c23-constexpr.c
evaluate.c +256 -5
@@ -35,6 +35,7 @@#include <limits.h> #include "evaluate.h" +#include "expand.h" #include "simplify.h" #include "lib.h" #include "allocate.h"
@@ -95,6 +96,8 @@ static struct symbol *evaluate_symbol_expression(struct expression *expr) }examine_symbol_type (sym); +if (sym->ctype.modifiers &MOD_CONSTEXPR ) +evaluate_symbol (sym); base_type =get_base_type (sym);if (!base_type) {
@@ -111,6 +114,14 @@ static struct symbol *evaluate_symbol_expression(struct expression *expr) expr->op ='*' ; expr->unop = addr; expr->flags =CEF_NONE ; +if (sym->ctype.modifiers &MOD_CONSTEXPR ) { +if (is_float_type (base_type)) + expr->flags =CEF_SET_FLOAT ; +else if (is_int_type (base_type)) + expr->flags =CEF_SET_ICE ; +else + expr->flags =CEF_ADDR ; + }/* The type of a symbol is the symbol itself! */ expr->ctype = sym;
@@ -2388,6 +2399,14 @@ static struct symbol *evaluate_member_dereference(struct expression *expr) expr->type =EXPR_PREOP ; expr->op ='*' ; expr->unop = add; +if (mod &MOD_CONSTEXPR ) { +if (is_float_type (ctype)) + expr->flags =CEF_SET_FLOAT ; +else if (is_int_type (ctype)) + expr->flags =CEF_SET_ICE ; +else + expr->flags =CEF_ADDR ; + } expr->ctype = member;return member;
@@ -2922,7 +2941,7 @@ found:else v = &top->ident_expression; - mods |= ctype->ctype.modifiers &MOD_STORAGE ; + mods |= ctype->ctype.modifiers & (MOD_STORAGE |MOD_CONSTEXPR );if (handle_initializer (v,1 , lclass, top->ctype, mods))continue ;
@@ -3015,6 +3034,161 @@ static struct expression *handle_scalar(struct expression *e, int nested)* { "string", ...} - we need to preserve that string literal recognizable * until we dig into the inner struct. */ +static void check_constexpr_scalar_init (struct expression *orig, +struct symbol *target) +{ +struct symbol *ttype, *stype; +int tclass =classify_type (target, &ttype); +int sclass =classify_type (orig->ctype, &stype); +struct expression tmp; + +if (!valid_type (target) || !valid_type (orig->ctype)) +return ; + +if ((tclass &TYPE_PTR ) ||is_nullptr_type (ttype)) { +if (!(orig->flags & (CEF_ACE |CEF_ADDR ))) { +sparse_error (orig->pos, +"non-constant initializer for constexpr object" ); +return ; + } + tmp = *orig; +if (!is_null_pointer_constant (&tmp) && + !(((sclass &TYPE_PTR ) ||is_nullptr_type (stype)) &&is_zero_constant (&tmp))) +sparse_error (orig->pos, +"constexpr pointer initializer is not null" ); +return ; + } + +if (is_int (tclass)) { +int sw, tw; +bool s_unsigned, t_unsigned, s_neg; + +if (!(orig->flags & (CEF_ACE |CEF_ADDR ))) { +sparse_error (orig->pos, +"non-constant initializer for constexpr object" ); +return ; + } +if (!(orig->flags &CEF_ICE ) || !is_int (sclass)) { +sparse_error ( + orig->pos, +"constexpr integer initializer is not an integer constant expression" ); +return ; + } + tmp = *orig; +expand_constexpr_initializer (&tmp); +if (tmp.type !=EXPR_VALUE ) { +sparse_error (orig->pos, +"non-constant initializer for constexpr object" ); +return ; + } + sw = stype->bit_size; + s_unsigned = (stype->ctype.modifiers &MOD_UNSIGNED ) !=0 ; + s_neg = !s_unsigned && sw >0 && sw <=64 && + (tmp.value &sign_bit (sw)) !=0 ; +if (is_bool_type (ttype)) { +if (s_neg || (tmp.value !=0 && tmp.value !=1 )) +sparse_error ( + orig->pos, +"constexpr initializer not representable in target type" ); +return ; + } + tw = ttype->bit_size; + t_unsigned = (ttype->ctype.modifiers &MOD_UNSIGNED ) !=0 ; +if (s_neg) { +long long sval = sw >64 ? (long long )tmp.value : +bits_extend (tmp.value, sw,1 ); +if (t_unsigned || + (tw <64 && sval < -(1LL << (tw -1 )))) +sparse_error ( + orig->pos, +"constexpr initializer not representable in target type" ); + }else { +unsigned long long uval = + sw >64 ? tmp.value : + (unsigned long long )zero_extend (tmp.value, sw); +int max_bits = t_unsigned ? tw : (tw -1 ); +if ((max_bits <=0 && uval !=0 ) || + (max_bits >0 && max_bits <64 && + (uval >> max_bits) !=0 )) +sparse_error ( + orig->pos, +"constexpr initializer not representable in target type" ); + } +return ; + } + +if (tclass &TYPE_FLOAT ) { +if (!(orig->flags &CEF_ACE ) || !(sclass &TYPE_NUM )) { +sparse_error (orig->pos, +"non-constant initializer for constexpr object" ); +return ; + } + tmp = *orig; +expand_constexpr_initializer (&tmp); +if (sclass &TYPE_FLOAT ) { +long double fv; +if (tmp.type !=EXPR_FVALUE ) { +sparse_error ( + orig->pos, +"non-constant initializer for constexpr object" ); +return ; + } + fv = tmp.fvalue; +if (stype->rank > ttype->rank && fv == fv) { +bool ok = ttype->rank <0 ? + ((long double )(float )fv == fv) : + (ttype->rank ==0 ? + ((long double )(double )fv == fv) : + true); +if (!ok) +sparse_error ( + orig->pos, +"constexpr initializer not representable in target type" ); + } + }else if (is_int (sclass)) { +int sw = stype->bit_size; +bool s_unsigned = (stype->ctype.modifiers &MOD_UNSIGNED ) !=0 ; +bool s_neg = !s_unsigned && sw >0 && sw <=64 && + (tmp.value &sign_bit (sw)) !=0 ; +if (tmp.type !=EXPR_VALUE ) { +sparse_error ( + orig->pos, +"non-constant initializer for constexpr object" ); +return ; + } +if (s_neg) { +long long sval = sw >64 ? (long long )tmp.value : +bits_extend (tmp.value, sw,1 ); +long double ld = ttype->rank <0 ? + (long double )(float )sval : + (ttype->rank ==0 ? + (long double )(double )sval : + (long double )sval); +if (sval !=LLONG_MIN && + (ld <= (long double )LLONG_MIN || + (long long )ld != sval)) +sparse_error ( + orig->pos, +"constexpr initializer not representable in target type" ); + }else { +unsigned long long uval = + sw >64 ? tmp.value : + (unsigned long long )zero_extend (tmp.value, sw); +long double ld = ttype->rank <0 ? + (long double )(float )uval : + (ttype->rank ==0 ? + (long double )(double )uval : + (long double )uval); +if (ld >=18446744073709551616.0L || + (unsigned long long )ld != uval) +sparse_error ( + orig->pos, +"constexpr initializer not representable in target type" ); + } + } + } +} +static int handle_initializer (struct expression **ep,int nested,int class,struct symbol *ctype,unsigned long mods) {
@@ -3026,20 +3200,27 @@ static int handle_initializer(struct expression **ep, int nested,/* scalar */ if (!(class &TYPE_COMPOUND )) { +struct expression orig; + e =handle_scalar (e, nested); +if (!e)return 0 ; *ep = e;if (!evaluate_expression (e))return 1 ; +degenerate (e); + orig = *e;compatible_assignment_types (e, ctype, ep,"initializer" );/* * Initializers for static storage duration objects * shall be constant expressions or a string literal [6.7.8(4)]. */ mods |= ctype->ctype.modifiers; - mods &= (MOD_TOPLEVEL |MOD_STATIC ); -if (mods && !(e->flags & (CEF_ACE |CEF_ADDR ))) +if (mods &MOD_CONSTEXPR ) +check_constexpr_scalar_init (&orig, ctype); +if ((mods & (MOD_TOPLEVEL |MOD_STATIC )) && + !(e->flags & (CEF_ACE |CEF_ADDR )))if (Wconstexpr_not_const)warning (e->pos,"non-constant initializer for static object" );
@@ -3084,12 +3265,18 @@ static int handle_initializer(struct expression **ep, int nested, type =evaluate_expression (e);if (!type)return 0 ; + mods |= ctype->ctype.modifiers;if (ctype->type ==SYM_NODE ) ctype = ctype->ctype.base_type;if (type->type ==SYM_NODE ) type = type->ctype.base_type; -if (ctype == type) +if (ctype == type) { +if ((mods &MOD_CONSTEXPR ) && !(e->flags & (CEF_ACE |CEF_ADDR ))) +sparse_error ( + e->pos, +"non-constant initializer for constexpr object" );return 1 ; + }return 0 ; String:
@@ -3843,6 +4030,55 @@ void check_duplicates(struct symbol *sym) } } +static bool check_constexpr_vm_type (struct symbol *type) +{ +while (type) { +examine_symbol_type (type); +switch (type->type) { +case SYM_NODE : +case SYM_PTR : + type = type->ctype.base_type; +continue ; +case SYM_ARRAY : +if (type->array_size && + type->array_size->type !=EXPR_VALUE ) +return true; + type = type->ctype.base_type; +continue ; +default : +return false; + } + } +return false; +} + +static bool has_invalid_constexpr_qualifiers (struct symbol *type) +{ +while (type) { +if (type->ctype.modifiers & + (MOD_VOLATILE |MOD_ATOMIC |MOD_RESTRICT )) +return true; +switch (type->type) { +case SYM_NODE : +case SYM_ARRAY : + type = type->ctype.base_type; +continue ; +case SYM_STRUCT : +case SYM_UNION : { +struct symbol *m; + FOR_EACH_PTR(type->symbol_list, m) { +if (has_invalid_constexpr_qualifiers (m)) +return true; + }END_FOR_EACH_PTR (m); +return false; + } +default : +return false; + } + } +return false; +} +static struct symbol *evaluate_symbol (struct symbol *sym) {struct symbol *base_type;
@@ -3858,9 +4094,24 @@ static struct symbol *evaluate_symbol(struct symbol *sym)if (!base_type)return NULL ; +if ((sym->ctype.modifiers &MOD_CONSTEXPR ) && + base_type->type !=SYM_FN && !(sym->ctype.modifiers &MOD_USERTYPE )) { +if (check_constexpr_vm_type (sym)) +sparse_error ( + sym->pos, +"constexpr variable '%s' cannot have variably modified type" , +show_ident (sym->ident)); +if (has_invalid_constexpr_qualifiers (sym)) +sparse_error ( + sym->pos, +"constexpr variable '%s' cannot have volatile, atomic, or restrict type" , +show_ident (sym->ident)); + } +/* Evaluate the initializers */ if (sym->initializer) { -bool mark_underspec = sym->c23_auto; +bool mark_underspec = sym->c23_auto || + (sym->ctype.modifiers &MOD_CONSTEXPR );if (mark_underspec) sym->underspecified =1 ;evaluate_initializer (sym, &sym->initializer);
expand.c +72 -18
134 lines not on this page · raw message
expand.h +3 -0
@@ -31,4 +31,7 @@#define SELECT_COST 20/* Cut-off for turning a conditional into a select */ #define BRANCH_COST 10/* Cost of a conditional branch */ +struct expression ; +void expand_constexpr_initializer (struct expression *expr); +#endif
ident-list.h +1 -0
@@ -47,6 +47,7 @@ IDENT(_Thread_local);IDENT (alignas);IDENT (alignof);IDENT (bool); +IDENT (constexpr);IDENT (false);IDENT (nullptr );IDENT (static_assert);
parse.c +101 -7
198 lines not on this page · raw message
show-parse.c +26 -25
57 lines not on this page · raw message
symbol.c +5 -1
@@ -563,7 +563,7 @@ static struct symbol * examine_node_type(struct symbol *sym) sym->ctype.alignment = alignment;/* Unsized array? The size might come from the initializer.. */ -if (bit_size <0 && base_type->type ==SYM_ARRAY ) { +if (bit_size <0 && base_type->type ==SYM_ARRAY && !base_type->array_size) {struct expression *initializer =get_symbol_initializer (sym);if (initializer) {struct symbol *node_type = base_type->ctype.base_type;
@@ -872,6 +872,10 @@ void bind_symbol_with_scope(struct symbol *sym, struct ident *ident, enum namespif (ns ==NS_SYMBOL &&toplevel (scope)) {unsigned mod =MOD_ADDRESSABLE |MOD_TOPLEVEL ; +if ((sym->ctype.modifiers &MOD_CONSTEXPR ) && + !(sym->ctype.modifiers &MOD_EXTERN )) + sym->ctype.modifiers |=MOD_STATIC ; +inherit_static (sym); scope = global_scope;
symbol.h +9 -8
@@ -117,6 +117,7 @@ struct decl_state {unsigned char packed;unsigned char has_auto;unsigned char has_alignas; +unsigned char is_constexpr;unsigned char designated_init;unsigned char transparent_union; };
@@ -254,10 +255,10 @@ struct symbol {#define MOD_GNU_INLINE 0x00010000#define MOD_USERTYPE 0x00020000 -// MOD UNUSED 0x00040000 -// MOD UNUSED 0x00080000 -// MOD UNUSED 0x00100000 -// MOD UNUSED 0x00200000 +#define MOD_CONSTEXPR 0x00040000 +// MOD UNUSED 0x00080000 +// MOD UNUSED 0x00100000 +// MOD UNUSED 0x00200000 #define MOD_UNUSED 0x00400000#define MOD_SAFE 0x00800000 // non-null/non-trapping pointer
@@ -275,7 +276,7 @@ struct symbol {#define MOD_ESIGNED (MOD_SIGNED | MOD_EXPLICITLY_SIGNED)#define MOD_SIGNEDNESS (MOD_SIGNED | MOD_UNSIGNED | MOD_EXPLICITLY_SIGNED)#define MOD_SPECIFIER MOD_SIGNEDNESS -#define MOD_IGNORE (MOD_STORAGE | MOD_ACCESS | MOD_USERTYPE | MOD_EXPLICITLY_SIGNED | MOD_EXT_VISIBLE | MOD_UNUSED | MOD_GNU_INLINE) +#define MOD_IGNORE (MOD_STORAGE | MOD_ACCESS | MOD_USERTYPE | MOD_EXPLICITLY_SIGNED | MOD_EXT_VISIBLE | MOD_UNUSED | MOD_GNU_INLINE | MOD_CONSTEXPR)#define MOD_QUALIFIER (MOD_CONST | MOD_VOLATILE | MOD_RESTRICT)#define MOD_PTRINHERIT (MOD_QUALIFIER | MOD_ATOMIC | MOD_NODEREF | MOD_NORETURN | MOD_NOCAST)/* modifiers preserved by typeof() operator */
@@ -287,9 +288,9 @@ struct symbol {/* do not warn when these are duplicated */ #define MOD_DUP_OK (MOD_UNUSED|MOD_GNU_INLINE)/* must be part of the declared symbol, not its type */ -#define MOD_DECLARE (MOD_STORAGE|MOD_INLINE|MOD_TLS|MOD_GNU_INLINE|MOD_UNUSED|MOD_PURE|MOD_NORETURN|MOD_EXT_VISIBLE) - - +#define MOD_DECLARE \ + (MOD_STORAGE | MOD_INLINE | MOD_TLS | MOD_GNU_INLINE | MOD_UNUSED | \ + MOD_PURE | MOD_NORETURN | MOD_EXT_VISIBLE | MOD_CONSTEXPR)/* Current parsing/evaluation function */ extern struct symbol *current_fn;
validation/c23-constexpr-error.c new file +92 -0
92 lines not on this page · raw message
validation/c23-constexpr-self-init.c new file +41 -0
41 lines not on this page · raw message
validation/c23-constexpr.c new file +100 -0
100 lines not on this page · raw message
PATCH 51/73 c23: Support enumerations with fixed underlying types
In reply to Bart Van AsscheImplement ISO C23 enumerations with fixed underlying types ('enum [tag] : type { ... }' and standalone 'enum tag : type;'):
- Parse and canonicalize fixed integer underlying types, enforce redeclaration compatibility, and reject non-standalone opaque specifiers per C23 6.7.2.2p5.
- Disambiguate fixed-type ': type' from unnamed enum bit-fields and _Generic 'enum tag: expr' associations.
- Type enumerators per C23 6.7.2.2p12-13 in C23 mode (giving fixed-enum members the underlying type during and after the brace list, and giving unfixed-enum members 'int' only when the entire enum fits in 'int'), while preserving per-enumerator GNU typing in pre-C23 modes.
- Support bool-backed enums and diagnose ULLONG_MAX auto-increment overflow before wraparound.
--- evaluate.c | 2 +- expand.c | 13 +- parse.c | 269 +++++++++++++++++++++++++------ symbol.c | 19 ++- symbol.h | 38 ++--- validation/c23-enum-type-cast.c | 70 ++++++++ validation/c23-enum-type-error.c | 40 +++++ validation/c23-enum-type.c | 116 +++++++++++++ 8 files changed, 494 insertions(+), 73 deletions(-) create mode 100644 validation/c23-enum-type-cast.c create mode 100644 validation/c23-enum-type-error.c create mode 100644 validation/c23-enum-type.c
evaluate.c +1 -1
@@ -2486,7 +2486,7 @@ static struct symbol *evaluate_sizeof(struct expression *expr) }if (is_bool_type (type)) { -if (Wsizeof_bool) +if (Wsizeof_bool &&cbase_type (type) == &bool_ctype)warning (expr->pos,"expression using sizeof _Bool" ); size =bits_to_bytes (bits_in_bool) * bits_in_char; }
expand.c +12 -1
@@ -106,12 +106,23 @@ void cast_value(struct expression *expr, struct symbol *newtype, struct expressi// For pointers and integers, we can just move the value around expr->type =EXPR_VALUE ; expr->taint = old->taint; -if (old_size == new_size) { +if (old_size == new_size && !is_bool_type (newtype)) { expr->value = old->value; expr->ctype = newtype;return ; } +if (is_bool_type (newtype)) { +bool non_zero = old->value !=0 ; +bool is_one = old->value ==1 ; + expr->ctype = newtype; + expr->value = non_zero; +if (!conservative && non_zero && !is_one) +warning (old->pos,"odd constant _Bool cast (%llx becomes 1)" , + old->value); +return ; + } +// expand it to the full "long long" value value =get_longlong (old); expr->ctype = newtype;
parse.c +222 -47
406 lines not on this page · raw message
symbol.c +14 -5
@@ -584,12 +584,21 @@ static struct symbol *examine_enum_type(struct symbol *sym)struct symbol *base_type =examine_base_type (sym); sym->ctype.modifiers |= (base_type->ctype.modifiers &MOD_SIGNEDNESS ); - sym->bit_size = bits_in_enum; -if (base_type->bit_size > sym->bit_size) - sym->bit_size = base_type->bit_size; - sym->ctype.alignment = enum_alignment; -if (base_type->ctype.alignment > sym->ctype.alignment) +if (sym->fixed_type) { +if (base_type == &bool_ctype) + sym->bit_size =bits_to_bytes (bits_in_bool) * bits_in_char; +else + sym->bit_size = base_type->bit_size; sym->ctype.alignment = base_type->ctype.alignment; + }else { + sym->bit_size = bits_in_enum; +if (base_type->bit_size > sym->bit_size) + sym->bit_size = base_type->bit_size; + sym->ctype.alignment = enum_alignment; +if (base_type->ctype.alignment > sym->ctype.alignment) + sym->ctype.alignment = base_type->ctype.alignment; + } + sym->rank = base_type->rank;return sym; }
symbol.h +19 -19
@@ -120,6 +120,8 @@ struct decl_state {unsigned char is_constexpr;unsigned char designated_init;unsigned char transparent_union; +unsigned char opaque_fixed_enum; +struct position opaque_fixed_enum_pos; };struct pseudo ;
@@ -186,22 +188,14 @@ struct symbol {struct /* NS_SYMBOL */ {unsigned long offset;int bit_size; -unsigned int bit_offset:8 , - bogus_linear:1 , - variadic:1 , - initialized:1 , - examined:1 , - expanding:1 , - evaluated:1 , - has_flex_array:1 , - string:1 , - designated_init:1 , - forced_arg:1 , - accessed:1 , - builtin:1 , - torename:1 , - packed:1 , - transparent_union:1 ; +unsigned int bit_offset :8 , bogus_linear :1 , + variadic :1 , initialized :1 , examined :1 , + expanding :1 , evaluated :1 , + has_flex_array :1 , string :1 , + designated_init :1 , forced_arg :1 , + accessed :1 , builtin :1 , torename :1 , + packed :1 , transparent_union :1 , + fixed_type :1 ;unsigned int has_alignas :1 ;unsigned int underspecified :1 ;unsigned int c23_auto :1 ;
@@ -435,6 +429,13 @@ static inline int is_func_type(struct symbol *type)return type->type ==SYM_FN ; } +static inline struct symbol *cbase_type (struct symbol *sym) +{ +while (sym && sym->type ==SYM_NODE ) + sym = sym->ctype.base_type; +return sym; +} +static inline int is_array_type (struct symbol *type) {if (type->type ==SYM_NODE )
@@ -484,9 +485,8 @@ static inline int is_void_type(struct symbol *type)static inline int is_bool_type (struct symbol *type) { -if (type->type ==SYM_NODE ) - type = type->ctype.base_type; -if (type->type ==SYM_BITFIELD ) +while (type && (type->type ==SYM_NODE || type->type ==SYM_ENUM || + type->type ==SYM_BITFIELD )) type = type->ctype.base_type;return type == &bool_ctype; }
validation/c23-enum-type-cast.c new file +70 -0
70 lines not on this page · raw message
validation/c23-enum-type-error.c new file +40 -0
@@ -0,0 +1,40 @@ +enum E1 :char {A =300 }; +enum E2 : unsigned char { B = -1 }; +enum E3 : unsigned char { C = 255, D }; +enum E4 : short; +enum E4 :int ; +enum E5 ; +enum E5 : short; +enum E6 : short; +enum E6 {F }; +enum E7 :float ; +enum E8 :bool {B0 =0 ,B1 ,B2 }; +enum E9 : unsigned long long { UMAX = ~0ULL, UOVER }; +enum E10 :int bad_var; +typedef enum E11 : short e11_t; +void bad_enum_param (enum E12 :int p); +int bad_enum_sizeof =sizeof (enum E13 :int ); +enum E14 :char ; +enum E14 : signed char; + +/* +* check-name: C23 enum with fixed underlying type errors +* check-command: sparse -std=c23 $file +* +* check-error-start +c23-enum-type-error.c:1:18: error: enumerator value outside the range of underlying type +c23-enum-type-error.c:2:27: error: enumerator value outside the range of underlying type +c23-enum-type-error.c:3:36: error: enumerator value outside the range of underlying type +c23-enum-type-error.c:5:14: error: 'enum' underlying type incompatible with previous declaration +c23-enum-type-error.c:7:16: error: 'enum' declared both with and without fixed underlying type +c23-enum-type-error.c:9:9: error: 'enum' declared with but defined without fixed underlying type +c23-enum-type-error.c:10:16: error: invalid 'enum' underlying type +c23-enum-type-error.c:11:30: error: enumerator value outside the range of underlying type +c23-enum-type-error.c:12:46: error: enumerator value outside the range of underlying type +c23-enum-type-error.c:13:10: error: 'enum' underlying type may not be specified here +c23-enum-type-error.c:14:18: error: 'enum' underlying type may not be specified here +c23-enum-type-error.c:15:30: error: 'enum' underlying type may not be specified here +c23-enum-type-error.c:16:39: error: 'enum' underlying type may not be specified here +c23-enum-type-error.c:18:23: error: 'enum' underlying type incompatible with previous declaration +* check-error-end +*/
validation/c23-enum-type.c new file +116 -0
116 lines not on this page · raw message
PATCH 52/73 c23: Support standard [[]] attribute syntax
In reply to Bart Van AsscheParse C23 '[[]]' attribute specifier sequences across declarations, declarators, types, structs, enums, parameters, labels, and statements per ISO C23 6.7.12:
- Map standard attributes (nodiscard, maybe_unused, deprecated, fallthrough, noreturn, _Noreturn, reproducible, unsequenced) and gnu::/__gnu__:: scoped attributes to their Sparse modifiers, while ignoring unknown vendor-scoped attributes cleanly.
- Support '[[]]' attributes after declarator identifiers and after function parameter lists without misapplying function modifiers to pointer declarators.
- Distinguish attributed case and default labels from named goto labels inside switch statements, and warn under -Wpedantic in pre-C23 modes.
--- ident-list.h | 2 + parse.c | 275 +++++++++++++++++++++++---- symbol.h | 7 +- validation/attr_in_parameter.c | 2 + validation/c23-attributes-error.c | 20 ++ validation/c23-attributes-pedantic.c | 10 + validation/c23-attributes.c | 149 +++++++++++++++ validation/c23-param-attribute.c | 28 +++ 8 files changed, 448 insertions(+), 45 deletions(-) create mode 100644 validation/c23-attributes-error.c create mode 100644 validation/c23-attributes-pedantic.c create mode 100644 validation/c23-attributes.c create mode 100644 validation/c23-param-attribute.c
ident-list.h +2 -0
@@ -65,6 +65,8 @@ IDENT_RESERVED(__sizeof_ptr__);IDENT_RESERVED (__builtin_types_compatible_p);IDENT_RESERVED (__builtin_offsetof);IDENT_RESERVED (__label__); +IDENT (gnu); +IDENT (__gnu__);/* Preprocessor idents. Direct use of __IDENT avoids mentioning the keyword * itself by name, preventing these tokens from expanding when compiling
parse.c +233 -42
482 lines not on this page · raw message
symbol.h +4 -3
@@ -110,6 +110,7 @@ struct decl_state {struct symbol_op *mode;struct expression *cleanup;unsigned long f_modifiers;// function attributes +unsigned long ident_modifiers;// declarator-id C23 attributes unsigned long storage_class;unsigned char prefer_abstract;unsigned char autotype;
@@ -272,11 +273,11 @@ struct symbol {#define MOD_SPECIFIER MOD_SIGNEDNESS#define MOD_IGNORE (MOD_STORAGE | MOD_ACCESS | MOD_USERTYPE | MOD_EXPLICITLY_SIGNED | MOD_EXT_VISIBLE | MOD_UNUSED | MOD_GNU_INLINE | MOD_CONSTEXPR)#define MOD_QUALIFIER (MOD_CONST | MOD_VOLATILE | MOD_RESTRICT) -#define MOD_PTRINHERIT (MOD_QUALIFIER | MOD_ATOMIC | MOD_NODEREF | MOD_NORETURN | MOD_NOCAST) -/* modifiers preserved by typeof() operator */ -#define MOD_TYPEOF (MOD_QUALIFIER | MOD_ATOMIC | MOD_NOCAST | MOD_SPECIFIER)/* modifiers for function attributes */ #define MOD_FUN_ATTR (MOD_PURE|MOD_NORETURN) +#define MOD_PTRINHERIT (MOD_QUALIFIER | MOD_ATOMIC | MOD_NODEREF | MOD_FUN_ATTR | MOD_NOCAST) +/* modifiers preserved by typeof() operator */ +#define MOD_TYPEOF (MOD_QUALIFIER | MOD_ATOMIC | MOD_NOCAST | MOD_SPECIFIER)/* like cvr-qualifiers but 'reversed' (OK: source <= target) */ #define MOD_REV_QUAL (MOD_PURE|MOD_NORETURN)/* do not warn when these are duplicated */
validation/attr_in_parameter.c +2 -0
@@ -7,6 +7,8 @@ static void g(int A *x)f (x, x); p = q; } +static void h (__attribute__((unused))int x); +/* * check-name: attribute after ( in direct-declarator */
validation/c23-attributes-error.c new file +20 -0
@@ -0,0 +1,20 @@ +[[nodiscard] static int unclosed; +[[gnu::]] static int missing_scoped; + +static void test_if_attr_decl (int c) +{ +if (c) + [[maybe_unused]] int z = 3; +} + +/* +* check-name: c23-attributes-error +* check-command: sparse -std=c23 $file +* +* check-error-start +c23-attributes-error.c:1:14: error: Expected ] at end of attribute specifier +c23-attributes-error.c:1:14: error: got static +c23-attributes-error.c:2:8: error: expected attribute name after '::' +c23-attributes-error.c:7:17: error: declaration is not a statement +* check-error-end +*/
validation/c23-attributes-pedantic.c new file +10 -0
@@ -0,0 +1,10 @@ +[[maybe_unused]]static int x; + +/* +* check-name: C23 [[]] standard attribute syntax pedantic warning +* check-command: sparse -std=c11 -Wpedantic $file +* +* check-error-start +c23-attributes-pedantic.c:1:1: warning: C23 attribute syntax is a C23 extension +* check-error-end +*/
validation/c23-attributes.c new file +149 -0
149 lines not on this page · raw message
validation/c23-param-attribute.c new file +28 -0
@@ -0,0 +1,28 @@ +/* +* Check that function declarators properly parse parameter lists +* where parameters have standard C23 attributes. +*/ + +static void f1 ([[maybe_unused]]int x) +{ +} + +static int f2 ([[maybe_unused]]int a, [[maybe_unused]]int b) +{ +return a; +} + +static void (*fp)([[maybe_unused]]int ); + +static void test_call (void ) +{ +f1 (10 ); +f2 (1 ,2 ); + fp = f1; +fp (20 ); +} + +/* +* check-name: C23 parameter attributes +* check-command: sparse -std=c23 $file +*/
PATCH 53/73 preprocessor: Add support for __has_c_attribute
In reply to Bart Van AsscheSupport the C23 __has_c_attribute preprocessor operator for testing support for standard C23 and vendor attributes so that preprocessor conditionals can probe whether specific attributes are supported before using them.
--- pre-process.c | 66 +++++++++++++++++++ validation/c23-attributes.c | 3 + validation/preprocessor/c23-has-c-attribute.c | 60 +++++++++++++++++ 3 files changed, 129 insertions(+) create mode 100644 validation/preprocessor/c23-has-c-attribute.c
pre-process.c +66 -0
@@ -2364,6 +2364,71 @@ static int handle_nondirective(struct stream *stream, struct token **line, strucreturn 1 ; } +static bool expand_has_c_attribute (struct token *token,struct arg *args) +{ +struct token *arg = args[0 ].expanded; +const char *name; +const char *val ="0" ; +char buf[4096 ]; + +if (token_type (arg) !=TOKEN_IDENT ) { +sparse_error (eof_token (arg) ? token->pos : arg->pos, +"identifier expected" ); +return false; + } + +if (match_op (arg->next,':' ) &&match_op (arg->next->next,':' )) { +struct token *attr = arg->next->next->next; +if (token_type (attr) !=TOKEN_IDENT || !eof_token (attr->next)) { +sparse_error (eof_token (attr) ? token->pos : attr->pos, +"identifier expected" ); +return false; + } +if (arg->ident == &gnu_ident || arg->ident == &__gnu___ident) { +struct symbol *sym =lookup_symbol (attr->ident,NS_KEYWORD ); +if (sym && sym->op && sym->op->attribute) + val ="1" ; + } +token_type (token) =TOKEN_NUMBER ; + token->number = val; +return true; + } + +if (!eof_token (arg->next)) { +sparse_error (arg->next->pos,"expected ')'" ); +return false; + } + + name =show_ident (arg->ident); +if (name[0 ] =='_' && name[1 ] =='_' ) { +size_t len =strlen (name); +if (len >4 && name[len -1 ] =='_' && name[len -2 ] =='_' ) { +if (len -4 <sizeof (buf)) { +memcpy (buf, name +2 , len -4 ); + buf[len -4 ] ='\0' ; + name = buf; + } + } + } + +if (!strcmp (name,"deprecated" )) + val ="201904L" ; +else if (!strcmp (name,"fallthrough" )) + val ="201910L" ; +else if (!strcmp (name,"nodiscard" )) + val ="202003L" ; +else if (!strcmp (name,"maybe_unused" )) + val ="202106L" ; +else if (!strcmp (name,"noreturn" ) || !strcmp (name,"_Noreturn" )) + val ="202202L" ; +else if (!strcmp (name,"reproducible" ) || !strcmp (name,"unsequenced" )) + val ="202207L" ; + +token_type (token) =TOKEN_NUMBER ; + token->number = val; +return true; +} +static bool expand_has_attribute (struct token *token,struct arg *args) {struct token *arg = args[0 ].expanded;
@@ -2528,6 +2593,7 @@ static void init_preprocessor(void) { "__INCLUDE_LEVEL__", expand_include_level }, { "__has_attribute", NULL, expand_has_attribute }, { "__has_builtin", NULL, expand_has_builtin }, + { "__has_c_attribute", NULL, expand_has_c_attribute }, { "__has_extension", NULL, expand_has_extension }, { "__has_feature", NULL, expand_has_feature }, { "__has_include", NULL, NULL },
validation/c23-attributes.c +3 -0
@@ -1,3 +1,6 @@ +static_assert (__has_c_attribute (maybe_unused) !=0 ); +static_assert (__has_c_attribute (nodiscard) !=0 ); + [[maybe_unused]]static int unused_var; [[nodiscard]]static int get_val (void )
validation/preprocessor/c23-has-c-attribute.c new file +60 -0
60 lines not on this page · raw message
PATCH 54/73 c23: Support empty initializer braces {}
In reply to Bart Van AsscheSupport empty initializer braces '{}' for scalar, pointer, nullptr_t, aggregate, union, and variable-length array objects and compound literals in C23 mode per ISO C23 6.7.11:
- Synthesize zero/null scalar initializers in handle_scalar() without emitting spurious nested scalar-brace warnings, and keep warning under -Wpedantic before C23.
- Preserve runtime bounds on VLA empty initializers ('int vla[n] = {}') and reject empty initializers for incomplete arrays ('int a[] = {}') and incomplete structs or unions.
- Lower empty aggregate and null-pointer static initializers cleanly in linearize and sparse-llvm.
--- evaluate.c | 23 +++++- linearize.c | 2 +- parse.c | 5 ++ sparse-llvm.c | 114 +++++++++++++++++++-------- symbol.c | 6 ++ validation/backend/c23-empty-init.c | 24 ++++++ validation/c23-auto-error.c | 5 +- validation/c23-constexpr-error.c | 2 +- validation/c23-empty-init-error.c | 19 +++++ validation/c23-empty-init-pedantic.c | 14 ++++ validation/c23-empty-init.c | 64 +++++++++++++++ 11 files changed, 239 insertions(+), 39 deletions(-) create mode 100644 validation/backend/c23-empty-init.c create mode 100644 validation/c23-empty-init-error.c create mode 100644 validation/c23-empty-init-pedantic.c create mode 100644 validation/c23-empty-init.c
evaluate.c +21 -2
@@ -2987,7 +2987,8 @@ static int is_string_literal(struct expression **v)* an effect of screwup). In case of anything not legal, we are definitely * having an effect of screwup, so just fail and let the caller warn. */ -static struct expression *handle_scalar (struct expression *e,int nested) +static struct expression *handle_scalar (struct expression *e,int nested, +int class,struct symbol *ctype) {struct expression *v =NULL , *p;int count =0 ;
@@ -3001,6 +3002,19 @@ static struct expression *handle_scalar(struct expression *e, int nested) v = p; count++; }END_FOR_EACH_PTR (p); +if (count ==0 ) { +if (standard >=STANDARD_C23 ) { + v =alloc_const_expression (e->pos,0 ); +if (class &TYPE_PTR ) + v->ctype = &null_ctype; +else if (is_nullptr_type (ctype)) { + v->ctype = &nullptr_ctype; + v->flags =CEF_ADDR ; + } +return v; + } +return NULL ; + }if (count !=1 )return NULL ;switch (v->type) {
@@ -3202,7 +3216,7 @@ static int handle_initializer(struct expression **ep, int nested,if (!(class &TYPE_COMPOUND )) {struct expression orig; - e =handle_scalar (e, nested); + e =handle_scalar (e, nested, class, ctype);if (!e)return 0 ;
@@ -3302,6 +3316,11 @@ static void evaluate_initializer(struct symbol *ctype, struct expression **ep) {struct symbol *type;int class =classify_type (ctype, &type); +if ((type->type ==SYM_STRUCT || type->type ==SYM_UNION ) && + (type->bit_size <0 || !type->endpos.line)) { +expression_error (*ep,"initializer for incomplete type" ); +return ; + }if (!handle_initializer (ep,0 , class, ctype,0 ))expression_error (*ep,"invalid initializer" ); }
linearize.c +1 -1
@@ -2003,7 +2003,7 @@ static pseudo_t linearize_one_symbol(struct entrypoint *ep, struct symbol *sym) sym->initialized =1 ; ad.address =symbol_pseudo (ep, sym); -if (sym->initializer && !is_scalar_type (sym)) { +if (sym->initializer && !is_scalar_type (sym) && sym->bit_size >0 ) {// default zero initialization [6.7.9.21] // FIXME: this init the whole aggregate while // only the existing fields need to be initialized.
parse.c +5 -0
@@ -3456,6 +3456,11 @@ struct token *initializer(struct expression **tree, struct token *token) } token =initializer_list (&expr->expr_list, token->next); +if (ptr_list_empty ((struct ptr_list *)expr->expr_list)) { +if (standard <STANDARD_C23 && Wpedantic) +warning (expr->pos, +"ISO C forbids empty initializer braces before C23" ); + }return expect (token,'}' ,"at end of initializer" ); }return assignment_expression (token, tree);
sparse-llvm.c +80 -34
132 lines not on this page · raw message
symbol.c +6 -0
@@ -569,6 +569,12 @@ static struct symbol * examine_node_type(struct symbol *sym)struct symbol *node_type = base_type->ctype.base_type;int count =count_array_initializer (node_type, initializer); +if (standard >=STANDARD_C23 && + initializer->type ==EXPR_INITIALIZER && +ptr_list_empty ((struct ptr_list *)initializer->expr_list)) +sparse_error (sym->pos, +"empty initializer for incomplete array" ); +if (node_type && node_type->bit_size >=0 ) bit_size =implicit_array_size (sym, count); }
validation/backend/c23-empty-init.c new file +24 -0
@@ -0,0 +1,24 @@ +typedef typeof (nullptr)nullptr_t ; + +struct s { +int a; +void *p; +}; + +static nullptr_t g_np = {}; +static void *g_ptr = {}; +static struct s g_s = {}; + +int test_vla_empty (int n); +int test_vla_empty (int n) +{ +int vla[n] = {}; +return vla[0 ] + g_s.a + (g_np !=nullptr ) + (g_ptr !=nullptr ); +} + +/* +* check-name: backend-c23-empty-init +* check-command: sparse-llvm-dis -m64 -std=c23 -Wno-vla $file +* check-output-ignore +* check-output-contains: define i32 @test_vla_empty( +*/
validation/c23-auto-error.c +4 -1
@@ -28,10 +28,12 @@ void block_errors(void)int bad_cast = (auto )1 ; _Atomic(auto) bad_atomic = 1; auto braced = { 1 }; + auto empty = {}; (void )bad_sz; (void )bad_cast; (void )bad_atomic; (void )braced; + (void )empty; }/*
@@ -56,6 +58,7 @@ c23-auto-error.c:29:16: error: Trying to use reserved word 'auto' as identifier c23-auto-error.c:29:23: error: Expected ; at end of declaration c23-auto-error.c:29:23: error: got bad_atomic c23-auto-error.c:30:14: error: auto requires a scalar initializer expression +c23-auto-error.c:31:14: error: auto requires a scalar initializer expression c23-auto-error.c:2:15: error: invalid initializer c23-auto-error.c:7:13: error: underspecified symbol 'self' used in its own initializer c23-auto-error.c:9:18: error: underspecified symbol 'self_expr' used in its own initializer
@@ -63,6 +66,6 @@ c23-auto-error.c:10:23: error: underspecified symbol 'self_sz' used in its own ic23-auto-error.c:10:16: error: cannot size expression c23-auto-error.c:25:31: error: underspecified symbol 'shadow' used in its own initializer c23-auto-error.c:27:22: error: cannot size expression -c23-auto-error.c:33:15: error: undefined identifier 'bad_atomic' +c23-auto-error.c:34:15: error: undefined identifier 'bad_atomic' * check-error-end */
validation/c23-constexpr-error.c +1 -1
@@ -50,7 +50,7 @@ void assign_and_vla_test(int n) constexprint arr[2 ] = {1 ,2 }; arr[0 ] =3 ; - constexprint (*vla)[n] =nullptr ; + constexprint vla[n] = {}; (void )vla; }
validation/c23-empty-init-error.c new file +19 -0
@@ -0,0 +1,19 @@ +static int inc_arr[] = {}; + +struct inc_struct ; + +static void bad_init (void ) +{ +struct inc_struct x = {}; + (void )x; +} + +/* +* check-name: c23-empty-init-error +* check-command: sparse -std=c23 $file +* +* check-error-start +c23-empty-init-error.c:1:12: error: empty initializer for incomplete array +c23-empty-init-error.c:7:31: error: initializer for incomplete type +* check-error-end +*/
validation/c23-empty-init-pedantic.c new file +14 -0
@@ -0,0 +1,14 @@ +struct s { +int a; +}; + +static struct s s = {}; + +/* +* check-name: c23 empty initializer pedantic warning +* check-command: sparse -std=c11 -Wpedantic $file +* +* check-error-start +c23-empty-init-pedantic.c:5:21: warning: ISO C forbids empty initializer braces before C23 +* check-error-end +*/
validation/c23-empty-init.c new file +64 -0
64 lines not on this page · raw message
PATCH 55/73 preprocessor: Add support for __has_embed
In reply to Bart Van AsscheAdd support for the C23 __has_embed preprocessor operator to check resource availability and parameters prior to inclusion via #embed. Predefine the __STDC_EMBED_NOT_FOUND__, __STDC_EMBED_FOUND__, and __STDC_EMBED_EMPTY__ constants to allow portable feature detection in preprocessor expressions.
--- ident-list.h | 9 + pre-process.c | 445 +++++++++++++++++++++++- predefine.c | 3 + validation/preprocessor/c23-has-embed.c | 69 ++++ 4 files changed, 522 insertions(+), 4 deletions(-) create mode 100644 validation/preprocessor/c23-has-embed.c
ident-list.h +9 -0
@@ -84,6 +84,15 @@ __IDENT(__FUNCTION___ident, "__FUNCTION__", 0);__IDENT (__PRETTY_FUNCTION___ident,"__PRETTY_FUNCTION__" ,0 );__IDENT (__has_include_ident,"__has_include" ,0 );__IDENT (__has_include_next_ident,"__has_include_next" ,0 ); +__IDENT (__has_embed_ident,"__has_embed" ,0 ); +IDENT (limit); +IDENT (prefix); +IDENT (suffix); +IDENT (if_empty); +__IDENT (__limit___ident,"__limit__" ,0 ); +__IDENT (__prefix___ident,"__prefix__" ,0 ); +__IDENT (__suffix___ident,"__suffix__" ,0 ); +__IDENT (__if_empty___ident,"__if_empty__" ,0 );/* Sparse commands */ IDENT_RESERVED (__context__);
pre-process.c +441 -4
494 lines not on this page · raw message
predefine.c +3 -0
@@ -123,6 +123,9 @@ void predefined_macros(void)predefine ("__STDC_NO_COMPLEX__" ,1 ,"1" );predefine ("__STDC_NO_THREADS__" ,1 ,"1" ); } +predefine ("__STDC_EMBED_NOT_FOUND__" ,1 ,"0" ); +predefine ("__STDC_EMBED_FOUND__" ,1 ,"1" ); +predefine ("__STDC_EMBED_EMPTY__" ,1 ,"2" );predefine ("__CHAR_BIT__" ,1 ,"%d" , bits_in_char);if (funsigned_char)
validation/preprocessor/c23-has-embed.c new file +69 -0
69 lines not on this page · raw message
PATCH 56/73 preprocessor: Add support for #embed directive
In reply to Bart Van AsscheAdd support for the C23 #embed preprocessor directive to embed binary resource files into source code as comma-delimited integer constant sequences, supporting the standard limit, prefix, suffix, and if_empty parameters.
--- pre-process.c | 396 +++++++++++++++++++ validation/preprocessor/c23-embed-error.c | 19 + validation/preprocessor/c23-embed-pedantic.c | 12 + validation/preprocessor/c23-embed.c | 72 ++++ 4 files changed, 499 insertions(+) create mode 100644 validation/preprocessor/c23-embed-error.c create mode 100644 validation/preprocessor/c23-embed-pedantic.c create mode 100644 validation/preprocessor/c23-embed.c
pre-process.c +396 -0
@@ -35,6 +35,7 @@#include <fcntl.h> #include <limits.h> #include <time.h> +#include <errno.h> #include <sys/stat.h> #include "lib.h"
@@ -1661,6 +1662,400 @@ err:return false; } +static int open_embed_file (struct stream *stream,const char *filename, +int expect) +{ +char fullname[PATH_MAX ]; +const char **path; +size_t flen =strlen (filename); + +if (filename[0 ] =='/' ) +return open (filename,O_RDONLY ); + +set_stream_include_path (stream); + path = expect ? angle_includepath : quote_includepath; +if (!path) +return -1 ; +while (*path !=NULL ) { +const char *p = *path++; +size_t plen =strlen (p); +if (plen + flen +2 >sizeof (fullname)) +continue ; +memcpy (fullname, p, plen); +if (plen && p[plen -1 ] !='/' ) { + fullname[plen] ='/' ; + plen++; + } +memcpy (fullname + plen, filename, flen +1 ); +int fd =open (fullname,O_RDONLY ); +if (fd >=0 ) +return fd; + } +return -1 ; +} + +static int free_preprocessor_line (struct token *token); + +static int handle_embed (struct stream *stream,struct token **line, +struct token *token) +{ +char filename[PATH_MAX ]; +int expect =0 ; +struct token *next = token->next; +struct token **param_p; +struct token *prefix_start =NULL , *prefix_end =NULL ; +struct token *suffix_start =NULL , *suffix_end =NULL ; +struct token *if_empty_start =NULL , *if_empty_end =NULL ; +int has_limit =0 ; +unsigned long long limit_val = ~0ULL ; +unsigned int seen_params =0 ; +int fd; +struct stat st; +unsigned char *buf =NULL ; +ssize_t bytes_read =0 ; +struct token *head =NULL , **tail = &head; +static char num_strs[256 ][4 ]; +static int num_strs_inited =0 ; + +if (standard <STANDARD_C23 && Wpedantic) +warning (token->pos,"#embed before C23 is an extension" ); + + next =scan_next (&token->next); +if (match_op (next,'<' )) { + expect ='>' ; + next = next->next; +if (!collect_angle_filename (&next, filename,sizeof (filename), + token->pos)) +return 1 ; + }else if (token_type (next) ==TOKEN_STRING ) { +if (!extract_string_filename (&next, filename,sizeof (filename))) +return 1 ; + }else { +while (token_type (next =scan_next (&token->next)) == +TOKEN_IDENT && + !expand_one_symbol (&token->next)) + ; + next =scan_next (&token->next); +if (match_op (next,'<' )) { +struct token **p = &next->next; +struct token *t; + +while (!eof_token (t =scan_next (p)) && + !match_op (t,'>' )) { +if (token_type (t) !=TOKEN_IDENT || +expand_one_symbol (p)) + p = &t->next; + } + expect ='>' ; + next = next->next; +if (!collect_angle_filename (&next, filename, +sizeof (filename), + token->pos)) +return 1 ; + }else if (token_type (next) ==TOKEN_STRING ) { +if (!extract_string_filename (&next, filename, +sizeof (filename))) +return 1 ; + }else { +sparse_error (next->pos, +"expected \"FILENAME\" or <FILENAME>" ); +return 1 ; + } + } + + param_p = &next; +while (!eof_token (next =scan_next (param_p))) { +if (token_type (next) ==TOKEN_IDENT ) { +struct ident *id; +struct position id_pos; +enum embed_param_kind kind; +struct token *pstart, *pend =NULL ; +int depth =1 ; + +if (!expand_one_symbol (param_p)) +continue ; + next = *param_p; +if (token_type (next) !=TOKEN_IDENT ) { +sparse_error (next->pos, +"unexpected token in #embed" ); +return 1 ; + } + id = next->ident; + id_pos = next->pos; +if (match_op (next->next,':' ) && +match_op (next->next->next,':' )) { +struct token *attr = next->next->next->next; + +if (token_type (attr) ==TOKEN_IDENT ) +sparse_error ( + id_pos, +"unknown embed parameter '%s::%s'" , +show_ident (id), +show_ident (attr->ident)); +else +sparse_error (attr->pos, +"identifier expected" ); +return 1 ; + } + + kind =classify_embed_param (id); +if (kind ==EMBED_PARAM_NONE ) { +sparse_error (id_pos, +"unknown embed parameter '%s'" , +show_ident (id)); +return 1 ; + } +if (seen_params & kind) { +sparse_error (id_pos, +"duplicate embed parameter '%s'" , +show_ident (id)); +return 1 ; + } + seen_params |= kind; + + next =scan_next (&next->next); +if (!match_op (next,'(' )) { +sparse_error (id_pos,"expected '(' after '%s'" , +show_ident (id)); +return 1 ; + } + pstart = next->next; + next = next->next; +while (!eof_token (next) && depth >0 ) { +if (match_op (next,'(' )) + depth++; +else if (match_op (next,')' ) && !--depth) +break ; + pend = next; + next = next->next; + } +if (!match_op (next,')' )) { +sparse_error (id_pos,"expected ')'" ); +return 1 ; + } + next = next->next; +if (kind ==EMBED_PARAM_LIMIT ) { +if (!eval_embed_limit_expr (id_pos, pstart, pend, + &limit_val)) +return 1 ; + has_limit =1 ; + }else if (kind ==EMBED_PARAM_PREFIX ) { + prefix_start = pstart; + prefix_end = pend; + }else if (kind ==EMBED_PARAM_SUFFIX ) { + suffix_start = pstart; + suffix_end = pend; + }else if (kind ==EMBED_PARAM_IF_EMPTY ) { + if_empty_start = pstart; + if_empty_end = pend; + } + param_p = &next; +continue ; + } +sparse_error (next->pos,"unexpected token in #embed" ); +return 1 ; + } + + fd =open_embed_file (stream, filename, expect); +if (fd <0 ) { +sparse_error (token->pos,"unable to open '%s'" , filename); +return 1 ; + } + +if (fstat (fd, &st) <0 ) { +close (fd); +sparse_error (token->pos,"unable to stat '%s'" , filename); +return 1 ; + } +if (S_ISDIR (st.st_mode)) { +close (fd); +sparse_error (token->pos,"'%s' is a directory" , filename); +return 1 ; + } + +if (S_ISREG (st.st_mode) || has_limit) { +unsigned long long to_read = +S_ISREG (st.st_mode) ? (unsigned long long )st.st_size : + limit_val; + +if (has_limit && limit_val < to_read) + to_read = limit_val; +if (to_read >MAX_EMBED_SIZE ) { +sparse_error ( + token->pos, +"'%s' is too large to embed (%llu bytes, max %d bytes)" , + filename, to_read,MAX_EMBED_SIZE ); +close (fd); +return 1 ; + } + buf =malloc (to_read ? to_read :1 ); +if (!buf) { +sparse_error ( + token->pos, +"out of memory allocating #embed buffer for '%s'" , + filename); +close (fd); +return 1 ; + } +if (to_read >0 ) { +size_t total =0 ; + +while (total < to_read) { +ssize_t r = +read (fd, buf + total, to_read - total); +if (r <0 ) { +if (errno ==EINTR || errno ==EAGAIN ) +continue ; +sparse_error (token->pos, +"error reading '%s': %s" , + filename,strerror (errno)); +free (buf); +close (fd); +return 1 ; + } +if (r ==0 ) +break ; + total += r; + } + bytes_read = total; + } + }else { +size_t cap =4096 ; +size_t total =0 ; + + buf =malloc (cap); +if (!buf) { +sparse_error ( + token->pos, +"out of memory allocating #embed buffer for '%s'" , + filename); +close (fd); +return 1 ; + } +for (;;) { +ssize_t r; + +if (total == cap) { +size_t new_cap = cap *2 ; +unsigned char *nbuf; + +if (new_cap >MAX_EMBED_SIZE +1 ) + new_cap =MAX_EMBED_SIZE +1 ; + nbuf =realloc (buf, new_cap); +if (!nbuf) { +sparse_error ( + token->pos, +"out of memory allocating #embed buffer for '%s'" , + filename); +free (buf); +close (fd); +return 1 ; + } + buf = nbuf; + cap = new_cap; + } + r =read (fd, buf + total, cap - total); +if (r <0 ) { +if (errno ==EINTR || errno ==EAGAIN ) +continue ; +sparse_error (token->pos, +"error reading '%s': %s" , + filename,strerror (errno)); +free (buf); +close (fd); +return 1 ; + } +if (r ==0 ) +break ; + total += r; +if (total >MAX_EMBED_SIZE ) { +sparse_error ( + token->pos, +"'%s' is too large to embed (max %d bytes)" , + filename,MAX_EMBED_SIZE ); +free (buf); +close (fd); +return 1 ; + } + } + bytes_read = total; + } +close (fd); + +if (bytes_read ==0 ) { +if (if_empty_start && if_empty_end) { +struct token *p = if_empty_start; +while (p) { +struct token *t =dup_token (p, &token->pos); + *tail = t; + tail = &t->next; +if (p == if_empty_end) +break ; + p = p->next; + } + *tail = *line; + *line = head; + } +free (buf); +free_preprocessor_line (token); +return 0 ; + } + +if (prefix_start && prefix_end) { +struct token *p = prefix_start; +while (p) { +struct token *t =dup_token (p, &token->pos); + *tail = t; + tail = &t->next; +if (p == prefix_end) +break ; + p = p->next; + } + } + +if (!num_strs_inited) { +for (unsigned int i =0 ; i <256 ; i++) +snprintf (num_strs[i],sizeof (num_strs[i]),"%u" , + i &0xff ); + num_strs_inited =1 ; + } + +for (ssize_t i =0 ; i < bytes_read; i++) { +if (i >0 ) { +struct token *comma =alloc_token (&token->pos); +token_type (comma) =TOKEN_SPECIAL ; + comma->special =',' ; + *tail = comma; + tail = &comma->next; + } +struct token *num =alloc_token (&token->pos); +token_type (num) =TOKEN_NUMBER ; + num->number = num_strs[buf[i]]; + *tail = num; + tail = &num->next; + } + +if (suffix_start && suffix_end) { +struct token *p = suffix_start; +while (p) { +struct token *t =dup_token (p, &token->pos); + *tail = t; + tail = &t->next; +if (p == suffix_end) +break ; + p = p->next; + } + } + +if (head) { + *tail = *line; + *line = head; + } +free (buf); +free_preprocessor_line (token); +return 0 ; +} +static int free_preprocessor_line (struct token *token) {while (token_type (token) !=TOKEN_EOF ) {
@@ -2993,6 +3388,7 @@ static void init_preprocessor(void) { "error", handle_error }, { "include", handle_include }, { "include_next", handle_include_next }, + { "embed", handle_embed }, { "pragma", handle_pragma }, { "line", handle_line }, { "ident", handle_ident },
validation/preprocessor/c23-embed-error.c new file +19 -0
@@ -0,0 +1,19 @@ +int outside =__has_embed ("options.h" ); + +#if __has_embed("options.h" limit(1) limit(2)) +#endif + +#embed "options.h" limit(1) __limit__(2) +#embed "options.h" vendor::param(1) + +/* +* check-name: c23-embed-error +* check-command: sparse -std=c23 -Wno-decl -I.. $file +* +* check-error-start +preprocessor/c23-embed-error.c:1:15: error: '__has_embed' used outside of preprocessing directive +preprocessor/c23-embed-error.c:3:38: error: duplicate embed parameter 'limit' +preprocessor/c23-embed-error.c:6:29: error: duplicate embed parameter '__limit__' +preprocessor/c23-embed-error.c:7:20: error: unknown embed parameter 'vendor::param' +* check-error-end +*/
validation/preprocessor/c23-embed-pedantic.c new file +12 -0
@@ -0,0 +1,12 @@ +static const unsigned char data[] = { +#embed "options.h" limit(1) +}; + +/* +* check-name: c23-embed-pedantic +* check-command: sparse -std=c11 -Wpedantic -I.. $file +* +* check-error-start +preprocessor/c23-embed-pedantic.c:2:2: warning: #embed before C23 is an extension +* check-error-end +*/
validation/preprocessor/c23-embed.c new file +72 -0
72 lines not on this page · raw message
PATCH 57/73 c23: Add support for u8 character constants and string literals
In reply to Bart Van AsscheSupport C23 UTF-8 character constants (u8'c') and UTF-8 string literals (u8"...") with unsigned char (char8_t) element type per ISO C23 6.4.4.4 and 6.4.5:
- Type u8"..." literals (including narrow + u8"" concatenations) as arrays of unsigned char in C23 mode while preserving char[] typing in C11/C17, and diagnose pointer signedness mismatches with char * in C23.
- Parse \uXXXX and \UXXXXXXXX universal character names in character and string literals, reject u8"" concatenation with wide strings, and emit errors on multi-byte or multi-character u8'...' constants.
- Warn under -Wpedantic when u8 character constants are used before C23.
--- char.c | 111 ++++++++++++++++++++++++++++-- evaluate.c | 7 +- expression.c | 15 ++-- expression.h | 3 +- ident-list.h | 3 +- pre-process.c | 21 +++++- token.h | 6 ++ tokenize.c | 102 ++++++++++++++++++--------- validation/c23-u8-char-error.c | 16 +++++ validation/c23-u8-char-pedantic.c | 10 +++ validation/c23-u8-char-warn.c | 14 ++++ validation/c23-u8-char.c | 37 ++++++++++ 12 files changed, 296 insertions(+), 49 deletions(-) create mode 100644 validation/c23-u8-char-error.c create mode 100644 validation/c23-u8-char-pedantic.c create mode 100644 validation/c23-u8-char-warn.c create mode 100644 validation/c23-u8-char.c
char.c +105 -6
@@ -6,6 +6,54 @@#include "expression.h" #include "char.h" +static const char *parse_ucn (const char *p,const char *end,int digits, +unsigned *cp,struct position pos) +{ +unsigned val =0 ; +int i; + +for (i =0 ; i < digits; i++) { +unsigned d; +if (p >= end || (d =hexval (*p)) >15 ) { +sparse_error (pos,"incomplete universal character name" ); + *cp =0 ; +return p; + } + val = (val <<4 ) + d; + p++; + } +if ((val >=0xd800 && val <=0xdfff ) || val >0x10ffff ) { +sparse_error (pos,"invalid universal character name" ); + val =0 ; + } + *cp = val; +return p; +} + +static int encode_utf8 (unsigned cp,char out[4 ]) +{ +if (cp <=0x7f ) { + out[0 ] = cp; +return 1 ; + } +if (cp <=0x7ff ) { + out[0 ] =0xc0 | (cp >>6 ); + out[1 ] =0x80 | (cp &0x3f ); +return 2 ; + } +if (cp <=0xffff ) { + out[0 ] =0xe0 | (cp >>12 ); + out[1 ] =0x80 | ((cp >>6 ) &0x3f ); + out[2 ] =0x80 | (cp &0x3f ); +return 3 ; + } + out[0 ] =0xf0 | (cp >>18 ); + out[1 ] =0x80 | ((cp >>12 ) &0x3f ); + out[2 ] =0x80 | ((cp >>6 ) &0x3f ); + out[3 ] =0x80 | (cp &0x3f ); +return 4 ; +} +static const char *parse_escape (const char *p,unsigned *val,const char *end,int bits,struct position pos) {unsigned c = (unsigned char )*p++;
@@ -26,6 +74,11 @@ static const char *parse_escape(const char *p, unsigned *val, const char *end, icase 'f' : c ='\f' ;break ;case 'r' : c ='\r' ;break ;case 'e' : c ='\e' ;break ; +case 'u' : +case 'U' : + p =parse_ucn (p, end, c =='u' ?4 :8 , &c, pos); + *val = c; +return p;case 'x' : {unsigned mask = -(1U << (bits -4 ));for (c =0 ; p < end; c = (c <<4 ) + d) {
@@ -75,6 +128,7 @@ void get_char_constant(struct token *token, unsigned long long *val)switch (type) {case TOKEN_CHAR :case TOKEN_WIDE_CHAR : +case TOKEN_UTF8_CHAR : p = token->string->data; end = p + token->string->length -1 ;if (end == p) {
@@ -86,14 +140,34 @@ void get_char_constant(struct token *token, unsigned long long *val) case TOKEN_CHAR_EMBEDDED_0 ... TOKEN_CHAR_EMBEDDED_3: end = p + type -TOKEN_CHAR ;break ; -default : + case TOKEN_WIDE_CHAR_EMBEDDED_0 ... TOKEN_WIDE_CHAR_EMBEDDED_3: end = p + type -TOKEN_WIDE_CHAR ; +break ; +default : + end = p + type -TOKEN_UTF8_CHAR ; +break ; } p =parse_escape (p, &v, end, - type <TOKEN_WIDE_CHAR ? bits_in_char : wchar_ctype->bit_size, token->pos); -if (p != end) + (type >=TOKEN_WIDE_CHAR && + type <=TOKEN_WIDE_CHAR_EMBEDDED_3 ) ? + wchar_ctype->bit_size : + bits_in_char, + token->pos); +if (type >=TOKEN_UTF8_CHAR && type <=TOKEN_UTF8_CHAR_EMBEDDED_3 ) { +if (p != end || v >0xff || + (token->embedded[0 ] =='\\' && + (token->embedded[1 ] =='u' || token->embedded[1 ] =='U' ) && + v >0x7f ) || + (type ==TOKEN_UTF8_CHAR && token->string->data[0 ] =='\\' && + (token->string->data[1 ] =='u' || + token->string->data[1 ] =='U' ) && + v >0x7f )) +sparse_error (token->pos, +"multi-character UTF-8 character constant" ); + }else if (p != end) {warning (token->pos,"multi-character character constant" ); + } *val = v; }
@@ -103,6 +177,7 @@ struct token *get_string_constant(struct token *token, struct expression *expr)struct token *next = token->next, *done =NULL ;int stringtype =token_type (token);int is_wide = stringtype ==TOKEN_WIDE_STRING ; +int is_utf8 = stringtype ==TOKEN_UTF8_STRING ;static char buffer[MAX_STRING ];int len =0 ;int bits;
@@ -112,6 +187,12 @@ struct token *get_string_constant(struct token *token, struct expression *expr)switch (token_type (next)) {case TOKEN_WIDE_STRING : is_wide =1 ; + next = next->next; +break ; +case TOKEN_UTF8_STRING : + is_utf8 =1 ; + next = next->next; +break ;case TOKEN_STRING : next = next->next;break ;
@@ -119,18 +200,35 @@ struct token *get_string_constant(struct token *token, struct expression *expr) done = next; } } +if (is_wide && is_utf8) { +sparse_error (token->pos, +"unsupported non-standard concatenation of string literals" ); + is_utf8 =0 ; + } bits = is_wide ? wchar_ctype->bit_size: bits_in_char;while (token != done) {unsigned v;const char *p = token->string->data;const char *end = p + token->string->length -1 ;while (p < end) { +bool is_ucn = (*p =='\\' && p +1 < end && + (p[1 ] =='u' || p[1 ] =='U' ));if (*p =='\\' ) esc_count++; p =parse_escape (p, &v, end, bits, token->pos); -if (len <MAX_STRING ) - buffer[len] = v; - len++; +if (is_ucn && !is_wide) { +char utf8[4 ]; +int i, n =encode_utf8 (v, utf8); +for (i =0 ; i < n; i++) { +if (len <MAX_STRING ) + buffer[len] = utf8[i]; + len++; + } + }else { +if (len <MAX_STRING ) + buffer[len] = v; + len++; + } } token = token->next; }
@@ -148,5 +246,6 @@ struct token *get_string_constant(struct token *token, struct expression *expr) } expr->string = string; expr->wide = is_wide; + expr->utf8 = is_utf8;return token; }
evaluate.c +5 -2
@@ -135,7 +135,8 @@ static struct symbol *evaluate_string(struct expression *expr)struct expression *addr =alloc_expression (expr->pos,EXPR_SYMBOL );struct expression *initstr =alloc_expression (expr->pos,EXPR_STRING );unsigned int length = expr->string->length; -struct symbol *char_type = expr->wide ? wchar_ctype : &char_ctype; +struct symbol *char_type = expr->wide ? wchar_ctype : + (expr->utf8 && standard >=STANDARD_C23 ) ? &uchar_ctype : &char_ctype; sym->array_size =alloc_const_expression (expr->pos, length); sym->bit_size = length * char_type->bit_size;
@@ -148,6 +149,8 @@ static struct symbol *evaluate_string(struct expression *expr) sym->evaluated =1 ; initstr->ctype = sym; + initstr->wide = expr->wide; + initstr->utf8 = expr->utf8; initstr->string = expr->string; array->array_size = sym->array_size;
@@ -1599,7 +1602,7 @@ static int whitelist_pointers(struct symbol *t1, struct symbol *t2)if (t1 == t2)return 1 ;if (t1->rank ==-2 && t2->rank ==-2 ) -return 1 ; +return !Wtypesign && !Wpedantic && standard <STANDARD_C23 ;if (t1->rank != t2->rank)return 0 ;return !Wtypesign;
expression.c +11 -4
@@ -599,17 +599,23 @@ struct token *primary_expression(struct token *token, struct expression **tree)struct expression *expr =NULL ;switch (token_type (token)) { - case TOKEN_CHAR ... TOKEN_WIDE_CHAR_EMBEDDED_3: + case TOKEN_CHAR ... TOKEN_UTF8_CHAR_EMBEDDED_3: expr =alloc_expression (token->pos,EXPR_VALUE ); expr->flags =CEF_SET_CHAR ;get_char_constant (token, &expr->value); -// TODO: handle 'u8', 'u' & 'U' prefixes. -if (token_type (token) <TOKEN_WIDE_CHAR ) { +// TODO: handle 'u' & 'U' prefixes. +if (token_type (token) <=TOKEN_CHAR_EMBEDDED_3 ) { expr->ctype = &char_ctype;cast_value (expr, &int_ctype, expr); - }else { + }else if (token_type (token) <=TOKEN_WIDE_CHAR_EMBEDDED_3 ) { expr->ctype = wchar_ctype; + }else { +if (standard <STANDARD_C23 && Wpedantic) +warning (token->pos, +"UTF-8 character constants are a C23 feature" ); + expr->ctype = &uchar_ctype; +cast_value (expr, &uchar_ctype, expr); } token = token->next;break ;
@@ -709,6 +715,7 @@ struct token *primary_expression(struct token *token, struct expression **tree)case TOKEN_STRING :case TOKEN_WIDE_STRING : +case TOKEN_UTF8_STRING : expr =alloc_expression (token->pos,EXPR_STRING ); token =get_string_constant (token, expr);break ;
expression.h +2 -1
@@ -175,7 +175,8 @@ struct expression {// EXPR_STRING struct { -int wide; +char wide; +char utf8;struct string *string; };
ident-list.h +2 -1
@@ -54,8 +54,9 @@ IDENT(static_assert);IDENT (thread_local);IDENT (true); -/* Special case for L'\t' */ +/* Special case for L'\t' and u8'a' */ IDENT (L ); +IDENT (u8);/* Extended gcc identifiers */ IDENT (asm);IDENT_RESERVED (__asm);IDENT_RESERVED (__asm__);
pre-process.c +18 -3
@@ -507,12 +507,19 @@ static enum token_type combine(struct token *left, struct token *right, char *p)return TOKEN_ERROR ;if (t1 ==TOKEN_IDENT && left->ident == &L_ident) { -if (t2 >=TOKEN_CHAR && t2 <TOKEN_WIDE_CHAR ) +if (t2 >=TOKEN_CHAR && t2 <=TOKEN_CHAR_EMBEDDED_3 )return t2 +TOKEN_WIDE_CHAR -TOKEN_CHAR ;if (t2 ==TOKEN_STRING )return TOKEN_WIDE_STRING ; } +if (t1 ==TOKEN_IDENT && left->ident == &u8_ident) { +if (t2 >=TOKEN_CHAR && t2 <=TOKEN_CHAR_EMBEDDED_3 ) +return t2 +TOKEN_UTF8_CHAR -TOKEN_CHAR ; +if (t2 ==TOKEN_STRING ) +return TOKEN_UTF8_STRING ; + } +if (t2 !=TOKEN_IDENT && t2 !=TOKEN_NUMBER && t2 !=TOKEN_SPECIAL )return TOKEN_ERROR ;
@@ -592,12 +599,15 @@ static int merge(struct token *left, struct token *right)case TOKEN_WIDE_CHAR :case TOKEN_WIDE_STRING : +case TOKEN_UTF8_CHAR : +case TOKEN_UTF8_STRING :token_type (left) = res; left->pos.noexpand =0 ; left->string = right->string;return 1 ; case TOKEN_WIDE_CHAR_EMBEDDED_0 ... TOKEN_WIDE_CHAR_EMBEDDED_3: + case TOKEN_UTF8_CHAR_EMBEDDED_0 ... TOKEN_UTF8_CHAR_EMBEDDED_3:token_type (left) = res; left->pos.noexpand =0 ;memcpy (left->embedded, right->embedded,4 );
@@ -620,7 +630,9 @@ static struct token *dup_token(const struct token *token, struct position *strea alloc->pos.stream = pos.stream; alloc->pos.line = pos.line; alloc->pos.pos = pos.pos; -if (token_type (alloc) ==TOKEN_STRING ||token_type (alloc) ==TOKEN_WIDE_STRING ) +if (token_type (alloc) ==TOKEN_STRING || +token_type (alloc) ==TOKEN_WIDE_STRING || +token_type (alloc) ==TOKEN_UTF8_STRING ) token->string->immutable =1 ;return alloc; }
@@ -2165,12 +2177,15 @@ static int token_different(struct token *t1, struct token *t2)break ; case TOKEN_CHAR_EMBEDDED_0 ... TOKEN_CHAR_EMBEDDED_3: case TOKEN_WIDE_CHAR_EMBEDDED_0 ... TOKEN_WIDE_CHAR_EMBEDDED_3: + case TOKEN_UTF8_CHAR_EMBEDDED_0 ... TOKEN_UTF8_CHAR_EMBEDDED_3: different =memcmp (t1->embedded, t2->embedded,4 );break ;case TOKEN_CHAR :case TOKEN_WIDE_CHAR : +case TOKEN_UTF8_CHAR :case TOKEN_STRING : -case TOKEN_WIDE_STRING : { +case TOKEN_WIDE_STRING : +case TOKEN_UTF8_STRING : {struct string *s1, *s2; s1 = t1->string;
token.h +6 -0
@@ -94,8 +94,14 @@ enum token_type {TOKEN_WIDE_CHAR_EMBEDDED_1 ,TOKEN_WIDE_CHAR_EMBEDDED_2 ,TOKEN_WIDE_CHAR_EMBEDDED_3 , +TOKEN_UTF8_CHAR , +TOKEN_UTF8_CHAR_EMBEDDED_0 , +TOKEN_UTF8_CHAR_EMBEDDED_1 , +TOKEN_UTF8_CHAR_EMBEDDED_2 , +TOKEN_UTF8_CHAR_EMBEDDED_3 ,TOKEN_STRING ,TOKEN_WIDE_STRING , +TOKEN_UTF8_STRING ,TOKEN_SPECIAL ,TOKEN_STREAMBEGIN , TOKEN_STREAMEND,
tokenize.c +70 -32
149 lines not on this page · raw message
validation/c23-u8-char-error.c new file +16 -0
@@ -0,0 +1,16 @@ +static unsigned char e1 = u8''; +static unsigned char e2 = u8'ab'; +static unsigned char e3 =u8'\u00e9' ; +static const void *e4 =u8"a" L"b" ; + +/* +* check-name: c23-u8-char-error +* check-command: sparse -std=c23 $file +* +* check-error-start +c23-u8-char-error.c:1:27: error: empty character constant +c23-u8-char-error.c:2:27: error: multi-character UTF-8 character constant +c23-u8-char-error.c:3:27: error: multi-character UTF-8 character constant +c23-u8-char-error.c:4:25: error: unsupported non-standard concatenation of string literals +* check-error-end +*/
validation/c23-u8-char-pedantic.c new file +10 -0
@@ -0,0 +1,10 @@ +static int x =u8'a' ; + +/* +* check-name: c23-u8-char-pedantic +* check-command: sparse -std=c11 -Wpedantic $file +* +* check-error-start +c23-u8-char-pedantic.c:1:16: warning: UTF-8 character constants are a C23 feature +* check-error-end +*/
validation/c23-u8-char-warn.c new file +14 -0
@@ -0,0 +1,14 @@ +static unsigned char w1 =u8'\x100' ; +static const char *w2 =u8"test" ; + +/* +* check-name: c23-u8-char-warn +* check-command: sparse -std=c23 $file +* +* check-error-start +c23-u8-char-warn.c:1:27: warning: hex escape sequence out of range +c23-u8-char-warn.c:2:25: warning: incorrect type in initializer (different signedness) +c23-u8-char-warn.c:2:25: expected char const *static [toplevel] w2 +c23-u8-char-warn.c:2:25: got unsigned char * +* check-error-end +*/
validation/c23-u8-char.c new file +37 -0
@@ -0,0 +1,37 @@ +static_assert (sizeof (u8'a' ) ==1 ,"sizeof u8 char" ); +static_assert (u8'a' ==97 ,"value u8 char" ); +static_assert (u8'\0' ==0 ,"u8 nul" ); +static_assert (u8'\xff' ==255 ,"u8 0xff is unsigned" ); +static_assert (u8'\u0041' ==65 ,"u8 UCN ASCII" ); +static_assert(_Generic(u8'a', unsigned char: 1, char: 0, int: 0, default: 0) == 1, +"type u8 char" ); + +static_assert (sizeof (u8"hello" ) ==6 ,"sizeof u8 string" ); +static_assert (sizeof (u8"\u00e9" ) ==3 ,"sizeof 2-byte UTF-8 UCN string" ); +static_assert (sizeof (u8"\U0001F600" ) ==5 ,"sizeof 4-byte UTF-8 UCN string" ); +static_assert (sizeof (u8"ab" "cd" ) ==5 ,"concat u8 + narrow" ); +static_assert (sizeof ("ab" u8"cd" ) ==5 ,"concat narrow + u8" ); +static_assert(_Generic(u8"hello", unsigned char *: 1, char *: 0, default: 0) == 1, +"u8 string decays to unsigned char *" ); +static_assert(_Generic("ab" u8"cd", unsigned char *: 1, char *: 0, default: 0) == 1, +"narrow + u8 string decays to unsigned char *" ); + +static const unsigned char c =u8'z' ; +static const unsigned char *s =u8"test" ; +static char s1[] =u8"abc" ; +static unsigned char s2[] =u8"abc" ; +static signed char s3[] =u8"abc" ; + +#define CAT (a, b) a##b +static const unsigned char c2 =CAT (u8,'x' ); +static const unsigned char *s_cat =CAT (u8,"yz" ); + +static int use_vars (void ) +{ +return c + s[0 ] + s1[0 ] + s2[0 ] + s3[0 ] + c2 + s_cat[0 ]; +} + +/* +* check-name: c23-u8-char +* check-command: sparse -std=c23 -pedantic $file +*/
PATCH 58/73 preprocessor: Add support for __VA_OPT__
In reply to Bart Van AsscheAdd support for the __VA_OPT__ functional macro replacement operator introduced in C23. Expand the contents of __VA_OPT__(...) if and only if variable arguments are passed to the variadic macro, eliminating trailing delimiter issues in variadic macro expansion portably.
--- ident-list.h | 1 + pre-process.c | 331 ++++++++++++++++++--- token.h | 3 + tokenize.c | 10 + validation/c23-va-opt.c | 36 +++ validation/preprocessor/c23-va-opt-error.c | 31 ++ validation/preprocessor/c23-va-opt.c | 73 +++++ 7 files changed, 446 insertions(+), 39 deletions(-) create mode 100644 validation/c23-va-opt.c create mode 100644 validation/preprocessor/c23-va-opt-error.c create mode 100644 validation/preprocessor/c23-va-opt.c
ident-list.h +1 -0
@@ -80,6 +80,7 @@ IDENT(c_generic_selections);IDENT (c_static_assert);__IDENT (pragma_ident,"__pragma__" ,0 );__IDENT (__VA_ARGS___ident,"__VA_ARGS__" ,0 ); +__IDENT (__VA_OPT___ident,"__VA_OPT__" ,0 );__IDENT (__func___ident,"__func__" ,0 );__IDENT (__FUNCTION___ident,"__FUNCTION__" ,0 );__IDENT (__PRETTY_FUNCTION___ident,"__PRETTY_FUNCTION__" ,0 );
pre-process.c +292 -39
500 lines not on this page · raw message
token.h +3 -0
@@ -110,6 +110,8 @@ enum token_type {TOKEN_QUOTED_ARGUMENT ,TOKEN_CONCAT ,TOKEN_GNU_KLUDGE , +TOKEN_VA_OPT , +TOKEN_STR_VA_OPT ,TOKEN_UNTAINT ,TOKEN_ARG_COUNT , TOKEN_IF,
@@ -200,6 +202,7 @@ struct token {int argnum;struct argcount count;char embedded[4 ]; +struct token *target; }; };
tokenize.c +10 -0
@@ -265,6 +265,12 @@ const char *show_token(const struct token *token)sprintf (buffer,"<argcnt>" );return buffer; +case TOKEN_VA_OPT : +return "__VA_OPT__(...)" ; + +case TOKEN_STR_VA_OPT : +return "#__VA_OPT__(...)" ; +case TOKEN_GNU_KLUDGE :return "," ;
@@ -321,6 +327,10 @@ const char *quote_token(const struct token *token)case TOKEN_UTF8_STRING :return quote_char (token->string->data, token->string->length -1 ,"u8" ,'"' ); +case TOKEN_VA_OPT : +return "__VA_OPT__(...)" ; +case TOKEN_STR_VA_OPT : +return "#__VA_OPT__(...)" ;case TOKEN_GNU_KLUDGE :return "," ;default :
validation/c23-va-opt.c new file +36 -0
@@ -0,0 +1,36 @@ +#define EMPTY +#define COUNT_VA (...) 0 __VA_OPT__(+1) +static_assert (COUNT_VA () ==0 ,"empty" ); +static_assert (COUNT_VA (EMPTY ) ==0 ,"empty macro" ); +static_assert (COUNT_VA (x) ==1 ,"one" ); +static_assert (COUNT_VA (x, y) ==1 ,"two" ); + +#define ADD_OPT (x, ...) (x __VA_OPT__(+__VA_ARGS__)) +static_assert (ADD_OPT (10 ) ==10 ,"add 1" ); +static_assert (ADD_OPT (10 ,20 ) ==30 ,"add 2" ); + +#define STR_OPT (...) #__VA_OPT__(__VA_ARGS__) +static_assert (sizeof (STR_OPT ()) ==1 ,"str empty" ); +static_assert (sizeof (STR_OPT (EMPTY )) ==1 ,"str empty macro" ); +static_assert (sizeof (STR_OPT (abc)) ==4 ,"str abc" ); + +#define PASTE_OPT (p, ...) p ## __VA_OPT__(_ok) +enum { val =10 , val_ok =20 }; +static_assert (PASTE_OPT (val) ==10 ,"paste empty" ); +static_assert (PASTE_OPT (val,1 ) ==20 ,"paste non-empty" ); + +static int foo (int a, ...) +{ +return a; +} + +#define CALL_FOO (...) foo(0 __VA_OPT__(, __VA_ARGS__)) +static int test (void ) +{ +return CALL_FOO () +CALL_FOO (1 ) +CALL_FOO (1 ,2 ); +} + +/* +* check-name: c23-va-opt-compile +* check-command: sparse -std=c23 -Wno-decl $file +*/
validation/preprocessor/c23-va-opt-error.c new file +31 -0
@@ -0,0 +1,31 @@ +#define BAD0 __VA_OPT__(1) +#define BAD1 (x) __VA_OPT__(x) +#define BAD2 (...) __VA_OPT__ +#define BAD3 (...) __VA_OPT__(1 +#define BAD4 (...) __VA_OPT__(__VA_OPT__(1)) +#define BAD5 (...) __VA_OPT__(##x) +#define BAD6 (...) __VA_OPT__(x##) +#define BAD7 (__VA_OPT__) 1 +#define __VA_OPT__ 1 + +/* +* check-name: c23-va-opt-error +* check-command: sparse -std=c23 -E $file +* +* check-output-start + + +* check-output-end +* +* check-error-start +preprocessor/c23-va-opt-error.c:1:14: error: __VA_OPT__ can only appear in the expansion of a variadic macro +preprocessor/c23-va-opt-error.c:2:17: error: __VA_OPT__ can only appear in the expansion of a variadic macro +preprocessor/c23-va-opt-error.c:3:19: error: expected '(' after __VA_OPT__ +preprocessor/c23-va-opt-error.c:4:19: error: unterminated __VA_OPT__ +preprocessor/c23-va-opt-error.c:5:30: error: __VA_OPT__ cannot appear within __VA_OPT__ +preprocessor/c23-va-opt-error.c:6:30: error: '##' cannot appear at the beginning of __VA_OPT__ +preprocessor/c23-va-opt-error.c:7:31: error: '##' cannot appear at the end of __VA_OPT__ +preprocessor/c23-va-opt-error.c:8:14: error: __VA_OPT__ cannot appear in a macro parameter list +preprocessor/c23-va-opt-error.c:9:9: error: "__VA_OPT__" cannot be used as a macro name +* check-error-end +*/
validation/preprocessor/c23-va-opt.c new file +73 -0
73 lines not on this page · raw message
PATCH 59/73 c23: Treat empty parameter list () as (void) and reject K&R functions
In reply to Bart Van AsscheTreat an empty parameter list '()' in a function declarator as '(void)' and reject K&R identifier-list function declarations and definitions in C23 mode per ISO C23 6.7.6.3 and 6.9.1:
- Parse '()' as a zero-parameter prototype in C23 mode so calls with arguments and conflicting redeclarations are diagnosed.
- Track identifier-list declarators via kr_args on SYM_FN and report an error in C23 mode on K&R function definitions (with or without parameter declarations) and K&R function or function-pointer declarations.
--- parse.c | 34 ++++++++++++++++++--- symbol.h | 1 + validation/c23-empty-parameters.c | 29 ++++++++++++++++++ validation/c23-empty-params-error.c | 47 +++++++++++++++++++++++++++++ validation/c23-knr-error.c | 14 +++++++++ 5 files changed, 120 insertions(+), 5 deletions(-) create mode 100644 validation/c23-empty-parameters.c create mode 100644 validation/c23-empty-params-error.c create mode 100644 validation/c23-knr-error.c
parse.c +29 -5
@@ -2241,9 +2241,14 @@ static enum kind which_func(struct token *token,if (lookup_type (next) || next != token->next)return Proto;/* identifier list not in definition; complain */ -if (prefer_abstract) -warning (token->pos, -"identifier list not in definition" ); +if (prefer_abstract || !n) { +if (standard >=STANDARD_C23 ) +sparse_error (token->pos, +"identifier list not in definition" ); +else +warning (token->pos, +"identifier list not in definition" ); + }return K_R ; }
@@ -2251,6 +2256,8 @@ static enum kind which_func(struct token *token,return Bad_Func;if (next->special ==')' ) { +if (standard >=STANDARD_C23 ) +return Proto;/* don't complain about those */ if (!n ||match_op (next->next,';' ) ||match_op (next->next,',' ))return Empty;
@@ -3284,6 +3291,7 @@ static struct token * statement_list(struct token *token, struct statement_liststatic struct token *identifier_list (struct token *token,struct symbol *fn) {struct symbol_list **list = &fn->arguments; + fn->kr_args =1 ;for (;;) {struct symbol *sym =alloc_symbol (token->pos,SYM_NODE ); sym->ident = token->ident;
@@ -3304,6 +3312,9 @@ static struct token *parameter_type_list(struct token *token, struct symbol *fn) {struct symbol_list **list = &fn->arguments; +if (match_op (token,')' )) +return token; +for (;;) {struct symbol *sym;
@@ -3602,7 +3613,10 @@ static struct token *parse_k_r_arguments(struct token *token, struct symbol *dec {struct symbol_list *args =NULL ; -if (Wold_style_definition) +if (standard >=STANDARD_C23 ) +sparse_error (token->pos, +"old-style function definition is invalid in C23" ); +else if (Wold_style_definition)warning (token->pos,"non-ANSI definition of function '%s'" ,show_ident (decl->ident)); do {
@@ -3772,8 +3786,15 @@ struct token *external_declaration(struct token *token, struct symbol_list **lis }if (lookup_type (token))return parse_k_r_arguments (token, decl, list); -if (match_op (token,'{' )) +if (match_op (token,'{' )) { +if (standard >=STANDARD_C23 && base_type->kr_args) +sparse_error (decl->pos, +"old-style function definition is invalid in C23" );return parse_function_body (token, decl, list); + } +if (standard >=STANDARD_C23 && base_type->kr_args) +sparse_error (decl->pos, +"identifier list not in function definition" );if (!(decl->ctype.modifiers &MOD_STATIC )) decl->ctype.modifiers |=MOD_EXTERN ;
@@ -3977,6 +3998,9 @@ struct token *external_declaration(struct token *token, struct symbol_list **lis base_type = decl->ctype.base_type;if (!is_typedef && base_type && base_type->type ==SYM_FN ) { decl->ctype.modifiers |= ctx.f_modifiers; +if (standard >=STANDARD_C23 && base_type->kr_args) +sparse_error (decl->pos, +"identifier list not in function definition" );if (!(decl->ctype.modifiers &MOD_STATIC )) decl->ctype.modifiers |=MOD_EXTERN ; }
symbol.h +1 -0
@@ -198,6 +198,7 @@ struct symbol { packed : 1, transparent_union : 1, fixed_type : 1; unsigned int has_alignas : 1; + unsigned int kr_args : 1; unsigned int underspecified : 1; unsigned int c23_auto : 1; int rank:3; // arithmetic's rank
validation/c23-empty-parameters.c new file +29 -0
@@ -0,0 +1,29 @@ +int f (); +int f (void ) +{ +return 0 ; +} + +int g (void ); +int g () +{ +return 1 ; +} + +static int h () +{ +return 2 ; +} + +static int test (void ) +{ +int (*fp)() = f; +int (*fp2)(void ) = h; + +return fp () +fp2 () +g (); +} + +/* +* check-name: c23-empty-parameters +* check-command: sparse -std=c23 -Wstrict-prototypes -pedantic $file +*/
validation/c23-empty-params-error.c new file +47 -0
47 lines not on this page · raw message
validation/c23-knr-error.c new file +14 -0
@@ -0,0 +1,14 @@ +int old_func (a, b) +int a, b; +{ +return a + b; +} + +/* +* check-name: c23-knr-error +* check-command: sparse -std=c23 $file +* +* check-error-start +c23-knr-error.c:2:1: error: old-style function definition is invalid in C23 +* check-error-end +*/
PATCH 60/73 c23: Support storage-class specifiers in compound literals
In reply to Bart Van AsscheSupport C23 storage-class specifiers (constexpr, static, register, and thread_local) in compound literals per ISO C23 6.5.2.5:
- Allow static, register, constexpr, and static thread_local compound literals while rejecting extern, typedef, auto, file-scope register, and un-static block-scope thread_local compound literals.
- Keep block-scope constexpr compound literals at automatic storage duration unless static is also specified, enforce constant initializers on static and thread_local objects in C23 mode, and warn when taking the address or decaying an array of a register compound literal.
- Emit anonymous static and thread_local compound literal globals and their constant scalar or array initializers in sparse-llvm, and warn under -Wpedantic before C23.
--- evaluate.c | 28 +++++++-- expand.c | 5 +- expression.c | 61 ++++++++++++++++--- expression.h | 1 + parse.c | 59 +++++++++++++----- sparse-llvm.c | 10 ++- symbol.h | 4 +- .../backend/c23-compound-literal-storage.c | 27 ++++++++ .../c23-compound-literal-register-addr.c | 17 ++++++ .../c23-compound-literal-storage-error.c | 37 +++++++++++ .../c23-compound-literal-storage-pedantic.c | 10 +++ validation/c23-compound-literal-storage.c | 27 ++++++++ 12 files changed, 252 insertions(+), 34 deletions(-) create mode 100644 validation/backend/c23-compound-literal-storage.c create mode 100644 validation/c23-compound-literal-register-addr.c create mode 100644 validation/c23-compound-literal-storage-error.c create mode 100644 validation/c23-compound-literal-storage-pedantic.c create mode 100644 validation/c23-compound-literal-storage.c
evaluate.c +22 -6
@@ -1918,7 +1918,10 @@ static struct symbol *create_pointer(struct expression *expr, struct symbol *symaccess_symbol (sym);if (sym->ctype.modifiers &MOD_REGISTER ) { -warning (expr->pos,"taking address of 'register' variable '%s'" ,show_ident (sym->ident)); +if (sym->ident) +warning (expr->pos,"taking address of 'register' variable '%s'" ,show_ident (sym->ident)); +else +warning (expr->pos,"taking address of 'register' compound literal" ); sym->ctype.modifiers &= ~MOD_REGISTER ; }if (sym->type ==SYM_NODE ) {
@@ -2944,7 +2947,7 @@ found:else v = &top->ident_expression; - mods |= ctype->ctype.modifiers & (MOD_STORAGE |MOD_CONSTEXPR ); + mods |= ctype->ctype.modifiers & (MOD_STORAGE |MOD_TLS |MOD_CONSTEXPR );if (handle_initializer (v,1 , lclass, top->ctype, mods))continue ;
@@ -3236,10 +3239,14 @@ static int handle_initializer(struct expression **ep, int nested, mods |= ctype->ctype.modifiers;if (mods &MOD_CONSTEXPR )check_constexpr_scalar_init (&orig, ctype); -if ((mods & (MOD_TOPLEVEL |MOD_STATIC )) && - !(e->flags & (CEF_ACE |CEF_ADDR ))) -if (Wconstexpr_not_const) +else if ((mods & (MOD_TOPLEVEL |MOD_STATIC |MOD_TLS )) && +valid_type (ctype->ctype.base_type) && + !(e->flags & (CEF_ACE |CEF_ADDR ))) { +if (standard >=STANDARD_C23 ) +sparse_error (e->pos,"non-constant initializer for static object" ); +else if (Wconstexpr_not_const)warning (e->pos,"non-constant initializer for static object" ); + }return 1 ; }
@@ -3443,13 +3450,22 @@ static struct symbol *evaluate_compound_literal(struct expression *expr, struct addr->ctype = &lazy_ptr_ctype;/* Lazy eval */ addr->symbol = sym; -if (sym->ctype.modifiers &MOD_TOPLEVEL ) +if (sym->ctype.modifiers & (MOD_TOPLEVEL |MOD_STATIC |MOD_TLS )) addr->flags |=CEF_ADDR ; expr->type =EXPR_PREOP ; expr->op ='*' ; expr->deref = addr; expr->ctype = sym; +if (sym->ctype.modifiers &MOD_CONSTEXPR ) { +struct symbol *base_type =get_base_type (sym); +if (is_float_type (base_type)) + expr->flags =CEF_SET_FLOAT ; +else if (is_int_type (base_type)) + expr->flags =CEF_SET_ICE ; +else + expr->flags =CEF_ADDR ; + }return sym; }
expand.c +2 -3
@@ -848,9 +848,8 @@ static int expand_dereference(struct expression *expr) expr->type =EXPR_VALUE ; expr->value = value->value; expr->taint =0 ; -if ((sym->ctype.modifiers &MOD_CONSTEXPR ) && -is_int_type (ctype)) - expr->flags =CEF_SET_ICE ; +if (sym->ctype.modifiers &MOD_CONSTEXPR ) + expr->flags =is_int_type (ctype) ?CEF_SET_ICE :CEF_ADDR ;return 0 ; }else if (value->type ==EXPR_FVALUE ) {if (!is_float_type (ctype))
expression.c +54 -7
133 lines not on this page · raw message
expression.h +1 -0
@@ -319,6 +319,7 @@ static inline struct expression *alloc_const_expression(struct position pos, int/* Type name parsing */ struct token *typename (struct token *,struct symbol **,int *); +void check_typename_storage (struct symbol *sym);static inline int lookup_type (struct token *token) {
parse.c +44 -15
105 lines not on this page · raw message
sparse-llvm.c +9 -1
@@ -318,7 +318,7 @@ static LLVMValueRef get_sym_value(LLVMModuleRef module, struct symbol *sym)LLVMValueRef result =NULL ;struct expression *expr; -assert (sym->bb_target ==NULL ); +assert (sym->namespace !=NS_LABEL ); expr = sym->initializer;if (expr && !sym->ident) {
@@ -348,6 +348,14 @@ static LLVMValueRef get_sym_value(LLVMModuleRef module, struct symbol *sym) } } +if (!sym->ident && (sym->ctype.modifiers & (MOD_STATIC |MOD_TOPLEVEL |MOD_TLS ))) { +if (!sym->aux) { +expand_symbol (sym); + sym->aux =output_data (module, sym); + } +return sym->aux; + } +if (LLVMGetTypeKind (type) == LLVMFunctionTypeKind) { result =LLVMGetNamedFunction (module, name);if (!result)
symbol.h +2 -2
@@ -196,7 +196,7 @@ struct symbol { designated_init : 1, forced_arg : 1, accessed : 1, builtin : 1, torename : 1, packed : 1, transparent_union : 1, - fixed_type : 1; + fixed_type : 1, explicit_typedef : 1; unsigned int has_alignas : 1; unsigned int kr_args : 1; unsigned int underspecified : 1;
@@ -282,7 +282,7 @@ struct symbol {/* like cvr-qualifiers but 'reversed' (OK: source <= target) */ #define MOD_REV_QUAL (MOD_PURE|MOD_NORETURN)/* do not warn when these are duplicated */ -#define MOD_DUP_OK (MOD_UNUSED|MOD_GNU_INLINE) +#define MOD_DUP_OK (MOD_UNUSED|MOD_GNU_INLINE|MOD_USERTYPE)/* must be part of the declared symbol, not its type */ #define MOD_DECLARE \ (MOD_STORAGE | MOD_INLINE | MOD_TLS | MOD_GNU_INLINE | MOD_UNUSED | \
validation/backend/c23-compound-literal-storage.c new file +27 -0
@@ -0,0 +1,27 @@ +static const int *g_arr = (static int[]){ 1, 2, 3 }; + +int *test_cl_static_scalar_addr (void ); +int *test_cl_static_scalar_addr (void ) +{ + return &(static int){ 42 }; +} + +int test_cl_llvm (void ); +int test_cl_llvm (void ) +{ + int *lp = (static int[]){ 7, 8, 9 }; + int *tp = (static thread_local int[]){ 14 }; + register int rv = (register int){ 12 }; +int ce = (constexprint ){42 }; + + lp[0 ] +=1 ; +return g_arr[0 ] + lp[0 ] + tp[0 ] + rv + ce; +} + +/* +* check-name: backend-c23-compound-literal-storage +* check-command: sparse-llvm-dis -m64 -std=c23 $file +* check-output-ignore +* check-output-contains: private global i32 42 +* check-output-contains: define i32 @test_cl_llvm( +*/
validation/c23-compound-literal-register-addr.c new file +17 -0
@@ -0,0 +1,17 @@ +static void bad_reg_addr (void ) +{ + int *p = &(register int){ 1 }; + int *q = (register int[]){ 1, 2 }; + (void )p; + (void )q; +} + +/* +* check-name: c23-compound-literal-register-addr +* check-command: sparse -std=c23 $file +* +* check-error-start +c23-compound-literal-register-addr.c:3:20: warning: taking address of 'register' compound literal +c23-compound-literal-register-addr.c:4:19: warning: taking address of 'register' compound literal +* check-error-end +*/
validation/c23-compound-literal-storage-error.c new file +37 -0
@@ -0,0 +1,37 @@ +void *e = (extern int[]){ 1 }; +void *t = (typedef int[]){ 1 }; +int f_reg = sizeof((register int){ 1 }); + +static void bad_block_literals (int non_const) +{ + int *a1 = (auto int[]){ 1, 2 }; +int a2 = (auto ){1 }; + int *tl = (thread_local int[]){ 14 }; + int *nc = (static int[]){ non_const }; + int *dup_s = (static static int[]){ 1 }; + int s_reg = (static register int){ 1 }; + + (void )a1; + (void )a2; + (void )tl; + (void )nc; + (void )dup_s; + (void )s_reg; +} + +/* +* check-name: c23-compound-literal-storage-error +* check-command: sparse -std=c23 -Wno-decl $file +* +* check-error-start +c23-compound-literal-storage-error.c:1:12: error: 'extern' is not allowed in compound literal +c23-compound-literal-storage-error.c:2:12: error: 'typedef' is not allowed in compound literal +c23-compound-literal-storage-error.c:3:21: error: file-scope compound literal cannot specify 'register' +c23-compound-literal-storage-error.c:7:20: error: 'auto' is not allowed in compound literal +c23-compound-literal-storage-error.c:8:19: error: 'auto' is not allowed in compound literal +c23-compound-literal-storage-error.c:9:20: error: block-scope compound literal with 'thread_local' requires 'static' +c23-compound-literal-storage-error.c:11:37: error: duplicate static +c23-compound-literal-storage-error.c:12:38: error: multiple storage classes +c23-compound-literal-storage-error.c:10:35: error: non-constant initializer for static object +* check-error-end +*/
validation/c23-compound-literal-storage-pedantic.c new file +10 -0
@@ -0,0 +1,10 @@ +static const int *p = (static int[]){ 1, 2, 3 }; + +/* +* check-name: c23-compound-literal-storage-pedantic +* check-command: sparse -std=c11 -Wpedantic $file +* +* check-error-start +c23-compound-literal-storage-pedantic.c:1:24: warning: storage-class specifiers in compound literals are a C23 feature +* check-error-end +*/
validation/c23-compound-literal-storage.c new file +27 -0
@@ -0,0 +1,27 @@ +static const int *p = (static int[]){ 1, 2, 3 }; +static const int *cp = (constexprint []){4 ,5 ,6 }; + +static int test (void ) +{ + static int *lp = (static int[]){ 7, 8, 9 }; + register int rv = (register int){ 12 }; + int *tp = (static thread_local int[]){ 14 }; + const int *lcp = &(static constexpr int){ 99 }; +int auto_ce = (constexprint ){42 }; + +return lp[0 ] + rv + tp[0 ] + *lcp + auto_ce + p[0 ] + cp[0 ]; +} + +static_assert(sizeof((static int[]){ 1, 2, 3 }) == 3 * sizeof(int), + "sizeof static compound literal"); +static_assert (sizeof ((constexprint []){1 ,2 ,3 ,4 }) ==4 *sizeof (int ), +"sizeof constexpr compound literal" ); +static_assert(sizeof((thread_local int[]){ 14, 15 }) == 2 * sizeof(int), + "sizeof file-scope thread_local compound literal"); +static_assert ((constexprint ){42 } ==42 , +"constexpr scalar compound literal in ICE" ); + +/* +* check-name: c23-compound-literal-storage +* check-command: sparse -std=c23 -pedantic $file +*/
PATCH 61/73 c23: Add support for _BitInt(N)
In reply to Bart Van AsscheImplement ISO C23 bit-precise integer types _BitInt(N) and unsigned _BitInt(N) up to __BITINT_MAXWIDTH__ (128):
- Parse _BitInt(N) specifiers, validate signed (N >= 2) and unsigned (N >= 1) width bounds, and parse case-matching wb/WB and uwb/UWB integer constant suffixes while rejecting mixed-case wB/Wb.
- Keep _BitInt(N) unpromoted during integer promotions per C23 6.3.1.1p2 and implement C23 6.3.1.8 usual arithmetic conversions between _BitInt(N) and standard integer types.
- Mask and sign-extend constant expressions to effective_int_width() and store the upper 64 bits in struct expression (value_hi) so 65..128-bit constants parse, fold, and compare with full precision.
- Enforce _BitInt bit-field width/sign rules, reject string-literal array initialization of _BitInt(8)[], and check pointer width/rank compatibility.
--- evaluate.c | 105 ++++++++- expand.c | 366 +++++++++++++++++++++++++++---- expression.c | 103 ++++++++- expression.h | 2 + ident-list.h | 1 + linearize.c | 23 +- parse.c | 89 +++++++- predefine.c | 1 + show-parse.c | 9 + sparse-llvm.c | 8 + symbol.c | 54 ++++- symbol.h | 61 +++++- validation/c23-bitint-error.c | 61 ++++++ validation/c23-bitint-pedantic.c | 13 ++ validation/c23-bitint.c | 214 ++++++++++++++++++ validation/expand-bitint.c | 49 +++++ 16 files changed, 1086 insertions(+), 73 deletions(-) create mode 100644 validation/c23-bitint-error.c create mode 100644 validation/c23-bitint-pedantic.c create mode 100644 validation/c23-bitint.c create mode 100644 validation/expand-bitint.c
evaluate.c +95 -10
@@ -187,6 +187,8 @@ static inline struct symbol *integer_promotion(struct symbol *type) type = type->ctype.base_type; } mod = type->ctype.modifiers; +if (is_bitint_type (type)) +return type;if (width < bits_in_int)return &int_ctype;
@@ -229,6 +231,43 @@ static struct symbol *bigger_int_type(struct symbol *left, struct symbol *right)if (left == right)return left; +if (is_bitint_type (left) ||is_bitint_type (right)) { +int lwidth =effective_int_width (left); +int rwidth =effective_int_width (right); +int lunsigned = (left->ctype.modifiers &MOD_UNSIGNED ) !=0 ; +int runsigned = (right->ctype.modifiers &MOD_UNSIGNED ) !=0 ; +int uwidth, swidth; + +if (lunsigned == runsigned) { +if (lwidth > rwidth) +return left; +if (rwidth > lwidth) +return right; +return is_bitint_type (left) ? right : left; + } + +if (lunsigned) { + utype = left; + stype = right; + uwidth = lwidth; + swidth = rwidth; + }else { + utype = right; + stype = left; + uwidth = rwidth; + swidth = lwidth; + } + +if (uwidth > swidth) +return utype; +if (uwidth == swidth) { +if (!is_bitint_type (utype) ||is_bitint_type (stype)) +return utype; +return unsigned_types[stype->rank]; + } +return stype; + } + lmod = left->ctype.modifiers; rmod = right->ctype.modifiers;if (((lmod ^ rmod) &MOD_UNSIGNED ) ==0 )
@@ -879,8 +918,15 @@ const char *type_difference(struct ctype *c1, struct ctype *c2,return "different base types" ;if (!base1 && t1->bit_size != t2->bit_size)return "different base types" ; -if (t1->rank != t2->rank) -return "different type sizes" ; +if (is_bitint_type (t1) ||is_bitint_type (t2)) { +if (!is_bitint_type (t1) || !is_bitint_type (t2)) +return "different base types" ; +if (t1->bitint_width != t2->bitint_width) +return "different bit widths" ; + }else { +if (t1->rank != t2->rank) +return "different type sizes" ; + } diff = (mod1 ^ mod2) & ~MOD_IGNORE ;if (!diff)return NULL ;
@@ -1601,6 +1647,13 @@ static int whitelist_pointers(struct symbol *t1, struct symbol *t2)return 0 ;if (t1 == t2)return 1 ; +if (is_bitint_type (t1) ||is_bitint_type (t2)) { +if (!is_bitint_type (t1) || !is_bitint_type (t2)) +return 0 ; +if (t1->bitint_width != t2->bitint_width) +return 0 ; +return !Wtypesign; + }if (t1->rank ==-2 && t2->rank ==-2 )return !Wtypesign && !Wpedantic && standard <STANDARD_C23 ;if (t1->rank != t2->rank)
@@ -3101,19 +3154,49 @@ static void check_constexpr_scalar_init(struct expression *orig, "non-constant initializer for constexpr object");return ; } - sw = stype->bit_size; + sw =effective_int_width (stype); s_unsigned = (stype->ctype.modifiers &MOD_UNSIGNED ) !=0 ; - s_neg = !s_unsigned && sw >0 && sw <=64 && - (tmp.value &sign_bit (sw)) !=0 ; + s_neg = !s_unsigned && + (sw >64 ? tmp.value_neg : + (sw >0 && (tmp.value &sign_bit (sw)) !=0 ));if (is_bool_type (ttype)) { -if (s_neg || (tmp.value !=0 && tmp.value !=1 )) +if (s_neg || tmp.value_hi !=0 || + (tmp.value !=0 && tmp.value !=1 ))sparse_error ( orig->pos,"constexpr initializer not representable in target type" );return ; } - tw = ttype->bit_size; + tw =effective_int_width (ttype); t_unsigned = (ttype->ctype.modifiers &MOD_UNSIGNED ) !=0 ; +#ifdef __SIZEOF_INT128__ +if (s_neg) { +__int128 sval = + sw >64 ? + (__int128)(((unsigned __int128 )tmp.value_hi <<64 ) | + tmp.value) : + (__int128 )bits_extend (tmp.value, sw,1 ); +if (t_unsigned || + (tw <128 && sval < -((__int128 )1 << (tw -1 )))) +sparse_error ( + orig->pos, +"constexpr initializer not representable in target type" ); + }else { +unsigned __int128 uval = + sw >64 ? + (((unsigned __int128 )tmp.value_hi <<64 ) | + tmp.value) : + (unsigned __int128 )(unsigned long long )zero_extend ( + tmp.value, sw); +int max_bits = t_unsigned ? tw : (tw -1 ); +if ((max_bits <=0 && uval !=0 ) || + (max_bits >0 && max_bits <128 && + (uval >> max_bits) !=0 )) +sparse_error ( + orig->pos, +"constexpr initializer not representable in target type" ); + } +#else if (s_neg) {long long sval = sw >64 ? (long long )tmp.value :bits_extend (tmp.value, sw,1 );
@@ -3134,6 +3217,7 @@ static void check_constexpr_scalar_init(struct expression *orig, orig->pos, "constexpr initializer not representable in target type"); } +#endif return ; }
@@ -3166,10 +3250,11 @@ static void check_constexpr_scalar_init(struct expression *orig, "constexpr initializer not representable in target type"); } }else if (is_int (sclass)) { -int sw = stype->bit_size; +int sw =effective_int_width (stype);bool s_unsigned = (stype->ctype.modifiers &MOD_UNSIGNED ) !=0 ; -bool s_neg = !s_unsigned && sw >0 && sw <=64 && - (tmp.value &sign_bit (sw)) !=0 ; +bool s_neg = !s_unsigned && + (sw >64 ? tmp.value_neg : + (sw >0 && (tmp.value &sign_bit (sw)) !=0 ));if (tmp.type !=EXPR_VALUE ) { sparse_error( orig->pos,
expand.c +328 -38
578 lines not on this page · raw message
expression.c +102 -1
132 lines not on this page · raw message
expression.h +2 -0
@@ -160,6 +160,7 @@ struct expression { enum expression_type type:8; unsigned flags:8; unsigned zero_init:1; + unsigned value_neg:1;int op;struct position pos;struct symbol *ctype;
@@ -167,6 +168,7 @@ struct expression {// EXPR_VALUE struct {unsigned long long value; +unsigned long long value_hi;unsigned taint; };
ident-list.h +1 -0
@@ -44,6 +44,7 @@ IDENT_RESERVED(_Static_assert);IDENT (_Thread_local);/* C23 keywords */ +IDENT (_BitInt);IDENT (alignas);IDENT (alignof);IDENT (bool);
linearize.c +22 -1
@@ -1824,7 +1824,7 @@ static pseudo_t linearize_cond_branch(struct entrypoint *ep, struct expression *case EXPR_STRING :case EXPR_VALUE : -add_goto (ep, expr->value ? bb_true : bb_false); +add_goto (ep, (expr->value || expr->value_hi) ? bb_true : bb_false);break ;case EXPR_FVALUE :add_goto (ep, expr->fvalue ? bb_true : bb_false);
@@ -1920,6 +1920,27 @@ static pseudo_t linearize_expression(struct entrypoint *ep, struct expression *ereturn add_symbol_address (ep, expr);case EXPR_VALUE : +if (effective_int_width (expr->ctype) >64 ) { +if (expr->value_hi != (expr->value_neg ? ~0ULL :0ULL ) || + (expr->value_neg && !(expr->value & (1ULL <<63 )))) { +pseudo_t hi =cast_pseudo ( + ep,value_pseudo (expr->value_hi), + &ullong_ctype, expr->ctype); + hi =add_binary_op (ep, expr->ctype,OP_SHL , hi, +value_pseudo (64 )); +if (expr->value) { +pseudo_t lo =cast_pseudo ( + ep,value_pseudo (expr->value), + &ullong_ctype, expr->ctype); + hi =add_binary_op (ep, expr->ctype, +OP_OR , hi, lo); + } +return hi; + } +if (!expr->value_neg && (expr->value & (1ULL <<63 ))) +return cast_pseudo (ep,value_pseudo (expr->value), + &ullong_ctype, expr->ctype); + }return value_pseudo (expr->value);case EXPR_STRING :
parse.c +81 -8
163 lines not on this page · raw message
predefine.c +1 -0
@@ -128,6 +128,7 @@ void predefined_macros(void)predefine ("__STDC_EMBED_EMPTY__" ,1 ,"2" );predefine ("__CHAR_BIT__" ,1 ,"%d" , bits_in_char); +predefine ("__BITINT_MAXWIDTH__" ,1 ,"%d" , bits_in_longlonglong);if (funsigned_char)predefine ("__CHAR_UNSIGNED__" ,1 ,"1" );
show-parse.c +9 -0
@@ -350,6 +350,15 @@ deeper:if (!sym) goto out; +if (sym->type ==SYM_BASETYPE &&is_bitint_type (sym)) { +if (sym->ctype.modifiers &MOD_UNSIGNED ) +prepend (name,"unsigned _BitInt(%d)" , + sym->bitint_width); +else +prepend (name,"_BitInt(%d)" , sym->bitint_width); + goto out; + } +if ((typename =builtin_typename (sym))) {if (name->start != name->end)prepend (name," " );
sparse-llvm.c +8 -0
@@ -1270,6 +1270,14 @@ static LLVMValueRef expr_to_const_val(LLVMModuleRef module, struct symbol *sym,switch (initializer->type) {case EXPR_VALUE : +if (effective_int_width (initializer->ctype) >64 && +LLVMGetTypeKind (dtype) == LLVMIntegerTypeKind) { +uint64_t words[2 ] = { + initializer->value, + initializer->value_hi, + }; +return LLVMConstIntOfArbitraryPrecision (dtype,2 , words); + }return constant_value (initializer->value, dtype);case EXPR_FVALUE :return LLVMConstReal (dtype, initializer->fvalue);
symbol.c +51 -3
81 lines not on this page · raw message
symbol.h +49 -12
103 lines not on this page · raw message
validation/c23-bitint-error.c new file +61 -0
61 lines not on this page · raw message
validation/c23-bitint-pedantic.c new file +13 -0
@@ -0,0 +1,13 @@ +static _BitInt(10) a; +static auto b =42wb ; + +/* +* check-name: C23 _BitInt pedantic +* check-command: sparse -std=c17 -Wpedantic $file +* +* check-error-start +c23-bitint-pedantic.c:1:15: warning: '_BitInt' is a C23 feature +c23-bitint-pedantic.c:2:13: warning: 'auto' type inference is a C23 feature +c23-bitint-pedantic.c:2:17: warning: bit-precise integer suffix is a C23 feature +* check-error-end +*/
validation/c23-bitint.c new file +214 -0
214 lines not on this page · raw message
validation/expand-bitint.c new file +49 -0
49 lines not on this page · raw message
PATCH 62/73 enum: Support machine mode attributes on enumeration types
In reply to Bart Van AsscheSupport GCC machine mode attributes (such as mode(__byte__)) on both enum declarations and enum type definitions:
- Apply prefix and postfix mode attributes on enum definitions to the enum's underlying type, size, alignment, and rank when no C23 fixed underlying type is present.
- Inspect underlying SYM_NODE and SYM_ENUM signedness in to_*_mode() so unsigned enums preserve unsignedness when converted to a mode.
- Expand validation/enum+mode.c and remove check-known-to-fail.
--- parse.c | 84 ++++++++++++++++++++++++++++++------------ symbol.c | 2 +- symbol.h | 1 + validation/enum+mode.c | 26 ++++++++++++- 4 files changed, 87 insertions(+), 26 deletions(-)
parse.c +61 -23
@@ -992,6 +992,20 @@ static struct token *struct_union_enum_specifier(enum type type,else warning (token->pos,"attribute __transparent_union__ applied to non-union type" ); } +if (sym->type ==SYM_ENUM && attr.mode && attr.mode->to_mode && + !sym->fixed_type && sym->ctype.base_type && +is_int_type (sym->ctype.base_type)) { +struct symbol *mtype = attr.mode->to_mode (sym); +if (mtype) { + sym->ctype.base_type = mtype; + sym->has_mode =1 ; + sym->ctype.modifiers &= ~MOD_SIGNEDNESS ; + sym->ctype.modifiers |= (mtype->ctype.modifiers &MOD_SIGNEDNESS ); + sym->bit_size = mtype->bit_size; + sym->ctype.alignment = mtype->ctype.alignment; + sym->rank = mtype->rank; + } + } sym->endpos = token->pos;
@@ -1599,62 +1613,86 @@ static struct token *attribute_address_space(struct token *token, struct symbolreturn token; } +static inline bool is_int_or_enum (struct symbol *ctype) +{ +if (!ctype) +return false; +if (ctype->type ==SYM_ENUM ) +return true; +if (ctype->ctype.base_type == &int_type) +return true; +if (ctype->type ==SYM_NODE && ctype->ctype.base_type && + (ctype->ctype.base_type->type ==SYM_ENUM || + ctype->ctype.base_type->ctype.base_type == &int_type)) +return true; +return false; +} + +static inline bool is_unsigned_mode_type (struct symbol *ctype) +{ +if (!ctype) +return false; +if (ctype->type ==SYM_NODE || ctype->type ==SYM_ENUM ) +examine_symbol_type (ctype); +while (ctype && (ctype->type ==SYM_NODE || ctype->type ==SYM_ENUM )) { +if (ctype->ctype.modifiers &MOD_UNSIGNED ) +return true; +if (ctype->ctype.modifiers &MOD_SIGNED ) +return false; + ctype = ctype->ctype.base_type; + } +return ctype && (ctype->ctype.modifiers &MOD_UNSIGNED ); +} +static struct symbol *to_QI_mode (struct symbol *ctype) { -if (ctype->ctype.base_type != &int_type) +if (!is_int_or_enum (ctype))return NULL ; -if (ctype == &char_ctype) -return ctype; -return ctype->ctype.modifiers &MOD_UNSIGNED ? &uchar_ctype - : &schar_ctype; +if (cbase_type (ctype) == &char_ctype) +return &char_ctype; +return is_unsigned_mode_type (ctype) ? &uchar_ctype : &schar_ctype; }static struct symbol *to_HI_mode (struct symbol *ctype) { -if (ctype->ctype.base_type != &int_type) +if (!is_int_or_enum (ctype))return NULL ; -return ctype->ctype.modifiers &MOD_UNSIGNED ? &ushort_ctype - : &sshort_ctype; +return is_unsigned_mode_type (ctype) ? &ushort_ctype : &sshort_ctype; }static struct symbol *to_SI_mode (struct symbol *ctype) { -if (ctype->ctype.base_type != &int_type) +if (!is_int_or_enum (ctype))return NULL ; -return ctype->ctype.modifiers &MOD_UNSIGNED ? &uint_ctype - : &sint_ctype; +return is_unsigned_mode_type (ctype) ? &uint_ctype : &sint_ctype; }static struct symbol *to_DI_mode (struct symbol *ctype) { -if (ctype->ctype.base_type != &int_type) +if (!is_int_or_enum (ctype))return NULL ; -return ctype->ctype.modifiers &MOD_UNSIGNED ? &ullong_ctype - : &sllong_ctype; +return is_unsigned_mode_type (ctype) ? &ullong_ctype : &sllong_ctype; }static struct symbol *to_TI_mode (struct symbol *ctype) { -if (ctype->ctype.base_type != &int_type) +if (!is_int_or_enum (ctype))return NULL ; -return ctype->ctype.modifiers &MOD_UNSIGNED ? &uint128_ctype - : &sint128_ctype; +return is_unsigned_mode_type (ctype) ? &uint128_ctype : &sint128_ctype; }static struct symbol *to_pointer_mode (struct symbol *ctype) { -if (ctype->ctype.base_type != &int_type) +if (!is_int_or_enum (ctype))return NULL ; -return ctype->ctype.modifiers &MOD_UNSIGNED ? uintptr_ctype - : intptr_ctype; +return is_unsigned_mode_type (ctype) ? uintptr_ctype : intptr_ctype; }static struct symbol *to_word_mode (struct symbol *ctype) { -if (ctype->ctype.base_type != &int_type) +if (!is_int_or_enum (ctype))return NULL ; -return ctype->ctype.modifiers &MOD_UNSIGNED ? &ulong_ctype - : &slong_ctype; +return is_unsigned_mode_type (ctype) ? &ulong_ctype : &slong_ctype; }static struct token *attribute_mode (struct token *token,struct symbol *attr,struct decl_state *ctx)
symbol.c +1 -1
@@ -592,7 +592,7 @@ static struct symbol *examine_enum_type(struct symbol *sym)struct symbol *base_type =examine_base_type (sym); sym->ctype.modifiers |= (base_type->ctype.modifiers &MOD_SIGNEDNESS ); -if (sym->fixed_type) { +if (sym->fixed_type || sym->has_mode) {if (base_type == &bool_ctype) sym->bit_size =bits_to_bytes (bits_in_bool) * bits_in_char;else
symbol.h +1 -0
@@ -214,6 +214,7 @@ struct symbol { unsigned int kr_args : 1; unsigned int underspecified : 1; unsigned int c23_auto : 1; + unsigned int has_mode : 1; int rank:3; // arithmetic's rankstruct expression *array_size;struct ctype ctype;
validation/enum+mode.c +24 -2
@@ -3,6 +3,7 @@ enum e { ZERO, ONE, TWO };struct s {enum e __attribute__ ((mode (__byte__))) b;enum e __attribute__ ((mode (__word__))) w; +enum e __attribute__ ((mode (__DI__))) d;enum e __attribute__ ((mode (__TI__))) t; };
@@ -10,9 +11,30 @@ static struct s s;_Static_assert (sizeof (s.b) ==1 ,"" );_Static_assert (sizeof (s.w) ==sizeof (long ),"" ); -_Static_assert (sizeof (s.t) ==sizeof (long long ),"" ); +_Static_assert (sizeof (s.d) ==sizeof (long long ),"" ); +_Static_assert (sizeof (s.t) ==16 ,"" ); + +typedef enum {M_ZERO ,M_ONE } __attribute__((mode (__byte__)))byte_enum_t ; +_Static_assert (sizeof (byte_enum_t) ==1 ,"typedef anon enum mode" ); +_Static_assert ((byte_enum_t)-1 >0 ,"unsigned enum mode stays unsigned" ); + +typedef enum tagged_m {TM_0 ,TM_1 } __attribute__((mode (__byte__)))tagged_byte_t ; +_Static_assert (sizeof (tagged_byte_t) ==1 ,"typedef tagged enum mode" ); +_Static_assert (sizeof (enum tagged_m ) ==1 ,"tagged enum itself gets mode" ); + +enum __attribute__((mode(__HI__))) hi_enum { HI_0 = -1, HI_1 = 1 }; +_Static_assert (sizeof (enum hi_enum ) ==2 ,"prefix mode on enum" ); +_Static_assert ((enum hi_enum )-1 <0 ,"signed enum mode stays signed" ); + +enum post_qi {PQ_0 =0 ,PQ_1 =200 } __attribute__((mode (__QI__))); +_Static_assert (sizeof (enum post_qi ) ==1 ,"postfix mode on enum" ); +_Static_assert ((enum post_qi )-1 >0 ,"postfix QI mode unsigned" ); + +typedef enum {UE_0 =0 ,UE_1 =1 }uenum_t ; +static uenum_t __attribute__((mode (__byte__))) ub; +_Static_assert (sizeof (ub) ==1 ,"typedef var mode size" ); +_Static_assert ((typeof (ub))-1 >0 ,"typedef var mode unsigned" );/* * check-name: enum+mode -* check-known-to-fail */
PATCH 63/73 enum: Support __attribute__((packed)) on enumeration types
In reply to Bart Van AsscheSupport GCC/Clang __attribute__((packed)) on enumeration types so packed enums select the narrowest integer type fitting their range:
- Define get_enum_base_type() and record the enumerator range on the enum symbol so prefix and postfix packed attributes shrink the enum size and alignment.
- Preserve sym->packed across subsequent tag lookups with '|=' instead of '='.
- Warn when both 'packed' and 'aligned' attributes are applied to an enum type since Clang and GCC treat that combination differently, and diagnose array element types whose size is not a multiple of their alignment in examine_array_type().
- Avoid overwriting invalid (&bad_ctype), incomplete, bitwise (SYM_RESTRICT), mode-attributed, or C23 fixed-underlying-type enums.
- Add regression tests in validation/enum-packed.c.
--- parse.c | 92 +++++++++++++++++----------------------- symbol.c | 87 ++++++++++++++++++++++++++++++++++--- symbol.h | 10 +++++ validation/enum-packed.c | 85 +++++++++++++++++++++++++++++++++++++ 4 files changed, 214 insertions(+), 60 deletions(-) create mode 100644 validation/enum-packed.c
parse.c +39 -53
@@ -891,6 +891,8 @@ static struct token *struct_union_enum_specifier(enum type type, sym->rank = underlying->rank; } token =handle_attributes (token, &attr); + sym->packed |= attr.packed; + sym->has_aligned |= attr.has_aligned;if (!match_op (token,'{' )) { ctx->opaque_fixed_enum =1 ; ctx->opaque_fixed_enum_pos = colon_pos;
@@ -972,6 +974,8 @@ static struct token *struct_union_enum_specifier(enum type type,return token; } + sym->packed |= attr.packed; + sym->has_aligned |= attr.has_aligned; token =parse (token->next, sym); token =expect (token,'}' ,"at end of specifier" ); sym->defined =1 ;
@@ -979,7 +983,11 @@ static struct token *struct_union_enum_specifier(enum type type, attr.ctype.base_type = sym; token =handle_attributes (token, &attr);apply_ctype (token->pos, &sym->ctype, &attr.ctype); - sym->packed = attr.packed; + sym->packed |= attr.packed; + sym->has_aligned |= attr.has_aligned; +if (sym->type ==SYM_ENUM && sym->packed && sym->has_aligned) +warning (sym->pos, +"Clang and GCC treat 'packed' and 'aligned' attributes on enum types differently" );if (attr.designated_init) {if (sym->type ==SYM_STRUCT ) sym->designated_init =1 ;
@@ -1006,6 +1014,16 @@ static struct token *struct_union_enum_specifier(enum type type, sym->rank = mtype->rank; } } +if (sym->type ==SYM_ENUM && sym->packed && !sym->fixed_type && + !sym->has_mode && sym->ctype.base_type && +is_int_type (sym->ctype.base_type)) { +struct symbol *base =get_enum_base_type (sym->range,1 ); +if (base && base != &bad_ctype) { + sym->ctype.base_type = base; + sym->ctype.modifiers &= ~MOD_SIGNEDNESS ; + sym->ctype.modifiers |= (base->ctype.modifiers &MOD_SIGNEDNESS ); + } + } sym->endpos = token->pos;
@@ -1045,24 +1063,6 @@ static struct token *union_specifier(struct token *token, struct symbol *sym, streturn struct_union_enum_specifier (SYM_UNION , token, ctx, parse_union_declaration); } -/// -// safe right shift -// -// This allow to use a shift amount as big (or bigger) -// than the width of the value to be shifted, in which case -// the result is, of course, 0. -static unsigned long long rshift (unsigned long long val,unsigned int n) -{ -if (n >= (sizeof (val) *8 )) -return 0 ; -return val >> n; -} - -struct range { -long long neg; -unsigned long long pos; -}; -static void update_range (struct range *range,unsigned long long uval,struct symbol *vtype) {long long sval = uval;
@@ -1076,24 +1076,6 @@ static void update_range(struct range *range, unsigned long long uval, struct sy } } -static int type_is_ok (struct symbol *type,struct range range) -{ -int shift = type->bit_size; -int is_unsigned = type->ctype.modifiers &MOD_UNSIGNED ; - -if (!is_unsigned) - shift--; -if (rshift (range.pos, shift)) -return 0 ; -if (range.neg ==0 ) -return 1 ; -if (is_unsigned) -return 0 ; -if (rshift (~range.neg, shift)) -return 0 ; -return 1 ; -} -static struct range type_range (struct symbol *type) {struct range range;
@@ -1315,20 +1297,9 @@ static struct token *parse_enum_declaration(struct token *token, struct symbol * base_type = &bad_ctype; }else if (!is_int_type (base_type)) ; -else if (type_is_ok (&uint_ctype, range)) - base_type = &uint_ctype; -else if (type_is_ok (&int_ctype, range)) - base_type = &int_ctype; -else if (type_is_ok (&ulong_ctype, range)) - base_type = &ulong_ctype; -else if (type_is_ok (&long_ctype, range)) - base_type = &long_ctype; -else if (type_is_ok (&ullong_ctype, range)) - base_type = &ullong_ctype; -else if (type_is_ok (&llong_ctype, range)) - base_type = &llong_ctype;else - base_type = &bad_ctype; + base_type =get_enum_base_type (range, parent->packed); + parent->range = range; parent->ctype.base_type = base_type; parent->ctype.modifiers |= (base_type->ctype.modifiers &MOD_UNSIGNED );
@@ -1491,10 +1462,9 @@ static struct token *ignore_attribute(struct token *token, struct symbol *attr,static struct token *attribute_packed (struct token *token,struct symbol *attr,struct decl_state *ctx) { -if (!ctx->ctype.alignment) { +if (!ctx->ctype.alignment) ctx->ctype.alignment =1 ; - ctx->packed =1 ; - } + ctx->packed =1 ;return token; }
@@ -1513,6 +1483,7 @@ static struct token *attribute_aligned(struct token *token, struct symbol *attr,return token; }else if (alignment > ctx->ctype.alignment) ctx->ctype.alignment = alignment; + ctx->has_aligned =1 ;return token; }
@@ -2004,6 +1975,8 @@ static struct token *declaration_specifiers(struct token *token, struct decl_sta seen |= Set_S | Set_T; ctx->ctype.base_type = s->ctype.base_type;apply_ctype (token->pos, &ctx->ctype, &s->ctype); +if (s->ctype.alignment > ctx->typedef_alignment) + ctx->typedef_alignment = s->ctype.alignment; token = token->next;continue ; }
@@ -2422,12 +2395,14 @@ static struct token *direct_declarator(struct token *token, struct decl_state *c }else if (match_op (token,'(' ) &&is_nested (token, &next, ctx->prefer_abstract)) {struct symbol *base_type = ctype->base_type; +unsigned int saved_td_align = ctx->typedef_alignment;if (token->next != next) next =handle_attributes (token->next, ctx); token =declarator (next, ctx); token =expect (token,')' ,"in nested declarator" );while (ctype->base_type != base_type) ctype = &ctype->base_type->ctype; + ctx->typedef_alignment = saved_td_align; p =NULL ; }
@@ -2459,6 +2434,7 @@ static struct token *direct_declarator(struct token *token, struct decl_state *creturn token; } +bool saw_array = false;while (match_op (token,'[' ) && !match_c23_attribute (token)) {struct symbol *array; array =alloc_indirect_symbol (token->pos, ctype,SYM_ARRAY );
@@ -2466,9 +2442,12 @@ static struct token *direct_declarator(struct token *token, struct decl_state *c token =expect (token,']' ,"in abstract_array_declarator" ); array->endpos = token->pos; ctype = &array->ctype; + saw_array = true;if (match_c23_attribute (token)) token =handle_attributes (token, ctx); } +if (saw_array && ctx->typedef_alignment > ctype->alignment) + ctype->alignment = ctx->typedef_alignment;return token; }
@@ -2485,6 +2464,7 @@ static struct token *pointer(struct token *token, struct decl_state *ctx) ctx->ctype.as =NULL ; ctx->ctype.contexts =NULL ; ctx->ctype.alignment =0 ; + ctx->typedef_alignment =0 ; token =handle_qualifiers (token->next, ctx); ctx->ctype.base_type->endpos = token->pos;
@@ -2553,6 +2533,7 @@ static struct token *declaration_list(struct token *token, struct symbol_list **struct decl_state ctx = {.prefer_abstract =0 };struct ctype saved;unsigned long mod; +unsigned int saved_td_align; token =declaration_specifiers (token, &ctx);if (ctx.opaque_fixed_enum)
@@ -2560,10 +2541,12 @@ static struct token *declaration_list(struct token *token, struct symbol_list ** "'enum' underlying type may not be specified here"); mod =decl_modifiers (&ctx); saved = ctx.ctype; + saved_td_align = ctx.typedef_alignment;for (;;) {struct symbol *decl =alloc_symbol (token->pos,SYM_NODE ); ctx.cleanup =NULL ; ctx.ident_modifiers =0 ; + ctx.typedef_alignment = saved_td_align; ctx.ident = &decl->ident; token =declarator (token, &ctx);
@@ -3801,6 +3784,7 @@ struct token *external_declaration(struct token *token, struct symbol_list **lisstruct decl_state ctx = { .ident = &ident };struct ctype saved;unsigned long saved_f_modifiers; +unsigned int saved_td_align;struct symbol *base_type;unsigned long mod;int is_typedef;
@@ -3840,6 +3824,7 @@ struct token *external_declaration(struct token *token, struct symbol_list **lis saved = ctx.ctype; saved_f_modifiers = ctx.f_modifiers; + saved_td_align = ctx.typedef_alignment; token =declarator (token, &ctx); token =handle_asm_name (token, &ctx); token =handle_attributes (token, &ctx);
@@ -4108,6 +4093,7 @@ struct token *external_declaration(struct token *token, struct symbol_list **lis ctx.cleanup =NULL ; ctx.ident_modifiers =0 ; ctx.f_modifiers = saved_f_modifiers; + ctx.typedef_alignment = saved_td_align; token =handle_attributes (token, &ctx); token =declarator (token, &ctx); token =handle_asm_name (token, &ctx);
symbol.c +80 -7
119 lines not on this page · raw message
symbol.h +10 -0
@@ -87,6 +87,11 @@ enum keyword { KW_EXACT = 1 << 9, }; +struct range { +long long neg; +unsigned long long pos; +}; +struct context {struct expression *context;unsigned int in, out;
@@ -112,10 +117,12 @@ struct decl_state {unsigned long f_modifiers;// function attributes unsigned long ident_modifiers;// declarator-id C23 attributes unsigned long storage_class; +unsigned int typedef_alignment;unsigned char prefer_abstract;unsigned char autotype;unsigned char forced;unsigned char packed; +unsigned char has_aligned;unsigned char has_auto;unsigned char has_alignas;unsigned char is_constexpr;
@@ -215,6 +222,7 @@ struct symbol { unsigned int underspecified : 1; unsigned int c23_auto : 1; unsigned int has_mode : 1; + unsigned int has_aligned : 1; int rank:3; // arithmetic's rankstruct expression *array_size;struct ctype ctype;
@@ -225,6 +233,7 @@ struct symbol {struct symbol_list *inline_symbol_list;struct expression *initializer;struct expression *cleanup; +struct range range;struct entrypoint *ep;struct symbol *definition; };
@@ -373,6 +382,7 @@ extern void bind_symbol_with_scope(struct symbol *, struct ident *, enum namespaextern struct symbol *strip_array_qualifiers (struct symbol *);extern struct symbol *examine_symbol_type (struct symbol *);extern struct symbol *examine_pointer_target (struct symbol *); +extern struct symbol *get_enum_base_type (struct range range,int packed);extern const char *show_as (struct ident *as);extern const char *show_typename (struct symbol *sym);extern const char *builtin_typename (struct symbol *sym);
validation/enum-packed.c new file +85 -0
85 lines not on this page · raw message
PATCH 64/73 expand: Ignore top-level non-array address space in compare_types()
In reply to Bart Van AsscheClear c1.as and c2.as in compare_types() only when base_type is not SYM_ARRAY so that __builtin_types_compatible_p() ignores top-level scalar address spaces while still distinguishing both pointer target address spaces and array element address spaces.
Add active validation tests in validation/types-compatible-address-space.c instead of placing assertions in check-known-to-fail typeof-addresspace.c.
--- expand.c | 9 +++-- validation/types-compatible-address-space.c | 39 +++++++++++++++++++++ 2 files changed, 46 insertions(+), 2 deletions(-) create mode 100644 validation/types-compatible-address-space.c
expand.c +7 -2
@@ -790,8 +790,13 @@ static int expand_comma(struct expression *expr)static int compare_types (int op,struct symbol *left,struct symbol *right) { -struct ctype c1 = {.base_type = left}; -struct ctype c2 = {.base_type = right}; +struct ctype c1 = left->type ==SYM_NODE ? left->ctype : (struct ctype ){.base_type = left}; +struct ctype c2 = right->type ==SYM_NODE ? right->ctype : (struct ctype ){.base_type = right}; + +if (!c1.base_type || c1.base_type->type !=SYM_ARRAY ) + c1.as =NULL ; +if (!c2.base_type || c2.base_type->type !=SYM_ARRAY ) + c2.as =NULL ;switch (op) {case SPECIAL_EQUAL :return !type_difference (&c1, &c2,MOD_IGN ,MOD_IGN );
validation/types-compatible-address-space.c new file +39 -0
@@ -0,0 +1,39 @@ +#define __as1 __attribute__((address_space(1))) +#define __as2 __attribute__((address_space(2))) + +typedef int __as1 as1_int_t; +typedef int __as1 as1_arr_t[4]; +typedef int __as1 as1_mat_t[2][4]; + +static void test_types_compatible_as (void ) +{ + int __as1 obj, *ptr; + +/* Top-level address space on scalar / pointer itself is ignored */ + _Static_assert(__builtin_types_compatible_p(int __as1, int), "scalar as1 vs int"); +_Static_assert (__builtin_types_compatible_p (as1_int_t, int),"typedef scalar as1 vs int" ); +_Static_assert (__builtin_types_compatible_p (typeof (obj), int),"typeof(obj) vs int" ); +_Static_assert (__builtin_types_compatible_p (typeof (*ptr), int),"typeof(*ptr) vs int" ); + _Static_assert(__builtin_types_compatible_p(int * __as1, int *), "ptr own as1 vs int *"); + +/* Pointee address space must match */ + _Static_assert(!__builtin_types_compatible_p(int __as1 *, int *), "pointee as1 vs default"); + _Static_assert(!__builtin_types_compatible_p(typeof(ptr), int *), "typeof(ptr) vs int *"); + _Static_assert(!__builtin_types_compatible_p(int __as1 *, int __as2 *), "pointee as1 vs as2"); + _Static_assert(__builtin_types_compatible_p(int __as1 *, int __as1 *), "pointee as1 vs as1"); + +/* Array element address space must match */ + _Static_assert(!__builtin_types_compatible_p(int __as1[4], int[4]), "array elem as1 vs default"); +_Static_assert (!__builtin_types_compatible_p (as1_arr_t, int[4 ]),"typedef array as1 vs int[4]" ); +_Static_assert (!__builtin_types_compatible_p (typeof (as1_arr_t), int[4 ]),"typeof(as1_arr_t) vs int[4]" ); + _Static_assert(!__builtin_types_compatible_p(int __as1[4], int __as2[4]), "array elem as1 vs as2"); + _Static_assert(__builtin_types_compatible_p(int __as1[4], int __as1[4]), "array elem as1 vs as1"); + _Static_assert(!__builtin_types_compatible_p(int __as1[2][4], int[2][4]), "2d array elem as1 vs default"); +_Static_assert (!__builtin_types_compatible_p (as1_mat_t, int[2 ][4 ]),"typedef 2d array as1 vs int[2][4]" ); + _Static_assert(__builtin_types_compatible_p(int __as1[2][4], int __as1[2][4]), "2d array elem as1 vs as1"); +} + +/* +* check-name: types-compatible-address-space +* check-command: sparse $file +*/
PATCH 65/73 builtin: Support __builtin_infer_alloc_token() as a size_t ICE
In reply to Bart Van AsscheDeclare __builtin_infer_alloc_token() returning size_t_ctype and fold calls to integer constant expression 0 (CEF_SET_ICE) while evaluating all arguments without type restrictions.
Support __kmalloc_token(...) in the Linux kernel's slab allocator on both 32-bit and 64-bit targets without an #ifdef __CHECKER__ workaround, and add validation/builtin-infer-alloc-token.c.
--- builtin.c | 21 +++++++++++++++++++ validation/builtin-infer-alloc-token.c | 28 ++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 validation/builtin-infer-alloc-token.c
builtin.c +21 -0
@@ -638,6 +638,26 @@ static struct symbol_op object_size_op = { .expand = expand_object_size, }; +static int evaluate_infer_alloc_token (struct expression *expr) +{ + expr->flags |=CEF_SET_ICE ; +return 1 ; +} + +static int expand_infer_alloc_token (struct expression *expr,int cost) +{ + expr->flags =CEF_SET_ICE ; + expr->type =EXPR_VALUE ; + expr->value =0 ; + expr->taint =0 ; +return 0 ; +} + +static struct symbol_op infer_alloc_token_op = { + .evaluate = evaluate_infer_alloc_token, + .expand = expand_infer_alloc_token, +}; +static int args_va_start (struct expression *expr) {struct symbol *sym = expr->fn->ctype;
@@ -865,6 +885,7 @@ static const struct builtin_fn builtins_common[] = { { "__builtin_index", &string_ctype, 0, { &const_string_ctype, &int_ctype }}, { "__builtin_inf", &double_ctype, 0 }, { "__builtin_inff", &float_ctype, 0 }, + { "__builtin_infer_alloc_token", size_t_ctype, 1, .op = &infer_alloc_token_op }, { "__builtin_infl", &ldouble_ctype, 0 }, { "__builtin_isdigit", &int_ctype, 0, { &int_ctype }, .op = &isdigit_op }, { "__builtin_isfinite", &int_ctype, 1, .op = &fp_unop_op },
validation/builtin-infer-alloc-token.c new file +28 -0
@@ -0,0 +1,28 @@ +typedef struct {__SIZE_TYPE__ v; }kmalloc_token_t ; + +_Static_assert (__builtin_infer_alloc_token (1 ) ==0 ,"infer_alloc_token ICE" ); +_Static_assert (__builtin_infer_alloc_token (1 ,2 ) ==0 ,"infer_alloc_token 2-arg ICE" ); +_Static_assert (__builtin_types_compatible_p (typeof (__builtin_infer_alloc_token (1 )), + __SIZE_TYPE__),"size_t return type" ); + +static const __SIZE_TYPE__ static_tok =__builtin_infer_alloc_token (64 ); + +static __SIZE_TYPE__ test_infer (int size,int flags) +{ +__SIZE_TYPE__ tok =__builtin_infer_alloc_token (size, flags); +return tok + static_tok; +} + +static __SIZE_TYPE__ test_infer_single (int size) +{ +return __builtin_infer_alloc_token (size); +} + +static kmalloc_token_t test_struct (int size) +{ +return (kmalloc_token_t ){ .v =__builtin_infer_alloc_token (size) }; +} + +/* +* check-name: builtin-infer-alloc-token +*/
PATCH 66/73 builtin: Add support for Linux kernel compiler builtins
In reply to Bart Van AsscheAdd support for compiler builtins used across the Linux kernel:
- Support __builtin_dynamic_object_size(ptr, type) via object_size_op.
- Support __builtin_thread_pointer() returning void * and __builtin_alloca_uninitialized(size) returning void *.
- Validate that __builtin_counted_by_ref() receives one argument and fold it to (void *)0 for flexible array members.
Add validation tests in validation/builtins-kernel.c and validation/builtin-counted-by-ref-err.c.
--- builtin.c | 22 +++++++++++++ validation/builtin-counted-by-ref-err.c | 20 ++++++++++++ validation/builtins-kernel.c | 42 +++++++++++++++++++++++++ 3 files changed, 84 insertions(+) create mode 100644 validation/builtin-counted-by-ref-err.c create mode 100644 validation/builtins-kernel.c
builtin.c +22 -0
@@ -733,6 +733,24 @@ static struct symbol_op va_start_op = { .evaluate = evaluate_va_start, }; +static int args_counted_by_ref (struct expression *expr) +{ +return eval_args (expr,1 ); +} + +static int expand_counted_by_ref (struct expression *expr,int cost) +{ + expr->type =EXPR_VALUE ; + expr->value =0 ; + expr->taint =0 ; +return 0 ; +} + +static struct symbol_op counted_by_ref_op = { + .args = args_counted_by_ref, + .expand = expand_counted_by_ref, +}; +static int evaluate_strlen (struct expression *expr) {struct expression *arg =first_expression (expr->args);
@@ -852,6 +870,7 @@ static const struct builtin_fn builtins_common[] = { { "__builtin_add_overflow", &bool_ctype, 1, .op = &overflow_op }, { "__builtin_add_overflow_p", &bool_ctype, 1, .op = &overflow_p_op }, { "__builtin_alloca", &ptr_ctype, 0, { size_t_ctype }}, + { "__builtin_alloca_uninitialized", &ptr_ctype, 0, { size_t_ctype }}, { "__builtin_bcmp", &int_ctype , 0, { &const_ptr_ctype, &const_ptr_ctype, size_t_ctype }}, { "__builtin_bcopy", &void_ctype, 0, { &const_ptr_ctype, &ptr_ctype, size_t_ctype }}, { "__builtin_bswap16", &ushort_ctype, 0, { &ushort_ctype }, .op = &bswap_op },
@@ -859,6 +878,7 @@ static const struct builtin_fn builtins_common[] = { { "__builtin_bswap64", &ullong_ctype, 0, { &ullong_ctype }, .op = &bswap_op }, { "__builtin_bzero", &void_ctype, 0, { &ptr_ctype, size_t_ctype }}, { "__builtin_calloc", &ptr_ctype, 0, { size_t_ctype, size_t_ctype }}, + { "__builtin_counted_by_ref", &ptr_ctype, 1, .op = &counted_by_ref_op }, { "__builtin_clrsb", &int_ctype, 0, { &int_ctype }, .op = &clrsb_op }, { "__builtin_clrsbl", &int_ctype, 0, { &long_ctype }, .op = &clrsb_op }, { "__builtin_clrsbll", &int_ctype, 0, { &llong_ctype }, .op = &clrsb_op },
@@ -868,6 +888,7 @@ static const struct builtin_fn builtins_common[] = { { "__builtin_ctz", &int_ctype, 0, { &int_ctype }, .op = &ctz_op }, { "__builtin_ctzl", &int_ctype, 0, { &long_ctype }, .op = &ctz_op }, { "__builtin_ctzll", &int_ctype, 0, { &llong_ctype }, .op = &ctz_op }, + { "__builtin_dynamic_object_size", size_t_ctype, 0, { &const_ptr_ctype, &int_ctype }, .op = &object_size_op}, { "__builtin_exit", &void_ctype, 0, { &int_ctype }}, { "__builtin_extract_return_addr", &ptr_ctype, 0, { &ptr_ctype }}, { "__builtin_fabs", &double_ctype, 0, { &double_ctype }},
@@ -961,6 +982,7 @@ static const struct builtin_fn builtins_common[] = { { "__builtin_strstr", &string_ctype, 0, { &const_string_ctype, &const_string_ctype }}, { "__builtin_sub_overflow", &bool_ctype, 1, .op = &overflow_op }, { "__builtin_sub_overflow_p", &bool_ctype, 1, .op = &overflow_p_op }, + { "__builtin_thread_pointer", &ptr_ctype, 0 }, { "__builtin_trap", &void_ctype, 0 }, { "__builtin_uadd_overflow", &bool_ctype, 0, { &uint_ctype, &uint_ctype, &uint_ptr_ctype }}, { "__builtin_uaddl_overflow", &bool_ctype, 0, { &ulong_ctype, &ulong_ctype, &ulong_ptr_ctype }},
validation/builtin-counted-by-ref-err.c new file +20 -0
@@ -0,0 +1,20 @@ +struct fam { +int count; +char arr[]; +}; + +static void test_cbr_args (struct fam *f) +{ + (void )__builtin_counted_by_ref (); + (void )__builtin_counted_by_ref (f->arr,1 ); +} + +/* +* check-name: builtin-counted-by-ref-err +* check-command: sparse $file +* +* check-error-start +builtin-counted-by-ref-err.c:8:39: error: not enough arguments for __builtin_counted_by_ref +builtin-counted-by-ref-err.c:9:39: error: too many arguments for __builtin_counted_by_ref +* check-error-end +*/
validation/builtins-kernel.c new file +42 -0
42 lines not on this page · raw message
PATCH 67/73 builtin: Add support for __builtin_has_attribute()
In reply to Bart Van AsscheImplement EXPR_HAS_ATTRIBUTE to evaluate __builtin_has_attribute queries at compile time across symbols, expressions, and anonymous type names:
- Distinguish __attribute__((const)) and [[unsequenced]] from pure via MOD_FCONST (0x80000000UL) and report const on const-qualified object declarations without conflating pure functions or pointer targets.
- Define MOD_NONSTRING (0x40000000) for the nonstring attribute instead of ignoring it, and support nonstring in __builtin_has_attribute() so Linux kernel strtomem_pad() static assertions succeed.
- Match GCC packed+aligned struct, union, bitfield, typedef, and _Alignas ABI layout via explicit_alignment on decl_state and symbol, and prevent typedef MOD_ALIGNED, MOD_WEAK, and MOD_NONSTRING modifiers from leaking onto pointers.
- Support bitwise SYM_RESTRICT types, struct member attribute queries without parent leakage, redeclaration attribute inheritance, and TOKEN_IDENT validation.
Add validation/struct-packed-aligned-layout.c,validation/builtin-has-attribute-more.c,validation/builtin-has-attribute-nonstring.c, andvalidation/builtin-has-attribute-err.c.
--- ast-inspect.c | 1 + builtin.c | 1 + c2xml.c | 44 +++--- dissect.c | 4 + evaluate.c | 36 ++++- expand.c | 121 +++++++++++++- expression.c | 82 ++++++++++ expression.h | 8 + gcc-attr-list.h | 2 - ident-list.h | 1 + inline.c | 6 + parse.c | 108 ++++++++++--- show-parse.c | 5 + simplify.c | 2 +- symbol.c | 30 ++-- symbol.h | 20 ++- validation/builtin-has-attribute-err.c | 19 +++ validation/builtin-has-attribute-more.c | 157 +++++++++++++++++++ validation/builtin-has-attribute-nonstring.c | 35 +++++ validation/builtins-kernel.c | 31 ++++ validation/struct-packed-aligned-layout.c | 135 ++++++++++++++++ validation/weak-const-no-fold.c | 15 ++ 22 files changed, 801 insertions(+), 62 deletions(-) create mode 100644 validation/builtin-has-attribute-err.c create mode 100644 validation/builtin-has-attribute-more.c create mode 100644 validation/builtin-has-attribute-nonstring.c create mode 100644 validation/struct-packed-aligned-layout.c create mode 100644 validation/weak-const-no-fold.c
ast-inspect.c +1 -0
@@ -180,6 +180,7 @@ static const char *expression_type_name(enum expression_type type) [EXPR_FVALUE] = "EXPR_FVALUE", [EXPR_SLICE] = "EXPR_SLICE", [EXPR_OFFSETOF] = "EXPR_OFFSETOF", + [EXPR_HAS_ATTRIBUTE] = "EXPR_HAS_ATTRIBUTE", };return expression_type_name[type] ?:"UNKNOWN_EXPRESSION_TYPE" ; }
builtin.c +1 -0
@@ -900,6 +900,7 @@ static const struct builtin_fn builtins_common[] = { { "__builtin_fmal", &ldouble_ctype, 0, { &ldouble_ctype, &ldouble_ctype, &ldouble_ctype }}, { "__builtin_frame_address", &ptr_ctype, 0, { &uint_ctype }}, { "__builtin_free", &void_ctype, 0, { &ptr_ctype }}, + { "__builtin_has_attribute", &int_ctype, 1 }, { "__builtin_huge_val", &double_ctype, 0 }, { "__builtin_huge_valf", &float_ctype, 0 }, { "__builtin_huge_vall", &ldouble_ctype, 0 },
c2xml.c +22 -22
56 lines not on this page · raw message
dissect.c +4 -0
@@ -483,6 +483,10 @@ again: ret =do_expression (mode, expr->def); } +break ;case EXPR_HAS_ATTRIBUTE : +if (expr->has_attr_expr) +do_expression (mode, expr->has_attr_expr); +break ;case EXPR_SYMBOL : ret =report_symbol (mode, expr); }
evaluate.c +35 -1
@@ -2433,7 +2433,8 @@ static struct symbol *evaluate_member_dereference(struct expression *expr)* The member needs to take on the address space and modifiers of * the "parent" type. */ - member =convert_to_as_mod (member, address_space, mod); + member =convert_to_as_mod (member, address_space, + mod & (MOD_PTRINHERIT |MOD_CONSTEXPR )); ctype =get_base_type (member);if (!lvalue_expression (deref)) {
@@ -4098,6 +4099,39 @@ struct symbol *evaluate_expression(struct expression *expr)case EXPR_GENERIC :return evaluate_generic_selection (expr); +case EXPR_HAS_ATTRIBUTE : +if (expr->has_attr_expr) { +struct expression *sub = expr->has_attr_expr; +while (sub && sub->type ==EXPR_PREOP && sub->op =='(' ) + sub = sub->unop; +if (sub && sub->type ==EXPR_SYMBOL ) { + expr->has_attr_decl = true; +evaluate_expression (expr->has_attr_expr); + }else if (sub && sub->type ==EXPR_DEREF ) { +struct symbol *dctype =evaluate_expression (sub->deref); +if (dctype && sub->member) { +int offset =0 ; +examine_symbol_type (dctype); +if (dctype->type ==SYM_NODE ) + dctype = dctype->ctype.base_type; +if (dctype && (dctype->type ==SYM_STRUCT || + dctype->type ==SYM_UNION )) { + expr->has_attr_sym =find_identifier ( + sub->member, dctype->symbol_list, &offset); + expr->has_attr_decl = true; + } + } +evaluate_expression (expr->has_attr_expr); + }else { +evaluate_expression (expr->has_attr_expr); + } + } +if (expr->has_attr_sym) +examine_symbol_type (expr->has_attr_sym); + expr->ctype = &int_ctype; + expr->flags =CEF_SET_ICE ; +return &int_ctype; +/* These can not exist as stand-alone expressions */ case EXPR_INITIALIZER :case EXPR_IDENTIFIER :
expand.c +119 -2
145 lines not on this page · raw message
expression.c +82 -0
94 lines not on this page · raw message
expression.h +8 -0
@@ -65,6 +65,7 @@ enum expression_type {EXPR_SLICE ,EXPR_OFFSETOF ,EXPR_GENERIC , + EXPR_HAS_ATTRIBUTE, };
@@ -265,6 +266,13 @@ struct expression {struct expression *def;struct type_expression *map; }; +// EXPR_HAS_ATTRIBUTE +struct { +struct symbol *has_attr_sym; +struct expression *has_attr_expr; +struct ident *has_attr_ident; +bool has_attr_decl; + }; }; };
gcc-attr-list.h +0 -2
@@ -127,7 +127,6 @@ GCC_ATTR(noipa) GCC_ATTR(nomicromips) GCC_ATTR(nomips16) GCC_ATTR(nonnull) -GCC_ATTR(nonstring) GCC_ATTR(noplt) GCC_ATTR(nosave_low_regs) GCC_ATTR(not_nested)
@@ -204,6 +203,5 @@ GCC_ATTR(warn_if_not_aligned) GCC_ATTR(warn_unused) GCC_ATTR(warn_unused_result) GCC_ATTR(warning) -GCC_ATTR(weak) GCC_ATTR(weakref) GCC_ATTR(zda)
ident-list.h +1 -0
@@ -66,6 +66,7 @@ IDENT_RESERVED(__alignof__);IDENT_RESERVED (__sizeof_ptr__);IDENT_RESERVED (__builtin_types_compatible_p);IDENT_RESERVED (__builtin_offsetof); +IDENT (__builtin_has_attribute);IDENT_RESERVED (__label__);IDENT (gnu);IDENT (__gnu__);
inline.c +6 -0
@@ -363,6 +363,12 @@ static struct expression * copy_expression(struct expression *expr)break ; } +case EXPR_HAS_ATTRIBUTE : + expr =dup_expression (expr); +if (expr->has_attr_expr) + expr->has_attr_expr =copy_expression (expr->has_attr_expr); +break ; +default :warning (expr->pos,"trying to copy expression type %d" , expr->type); }
parse.c +90 -18
260 lines not on this page · raw message
show-parse.c +5 -0
@@ -138,6 +138,7 @@ static const char *show_modifiers(unsigned long mod, int term) { MOD_NODEREF, "[noderef]" }, { MOD_NORETURN, "[noreturn]" }, { MOD_PURE, "[pure]" }, + { MOD_FCONST, "[const]" }, { MOD_SAFE, "[safe]" }, { MOD_SIGNED, "[signed]" }, { MOD_TLS, "[tls]" },
@@ -145,6 +146,9 @@ static const char *show_modifiers(unsigned long mod, int term) { MOD_UNSIGNED, "[unsigned]" }, { MOD_UNUSED, "[unused]" }, { MOD_USERTYPE, "[usertype]" }, + { MOD_WEAK, "[weak]" }, + { MOD_ALIGNED, "[aligned]" }, + { MOD_NONSTRING, "[nonstring]" }, };for (i =0 ; i <ARRAY_SIZE (mod_names); i++) {
@@ -1188,6 +1192,7 @@ int show_expression(struct expression *expr)case EXPR_PTRSIZEOF :case EXPR_ALIGNOF :case EXPR_OFFSETOF : +case EXPR_HAS_ATTRIBUTE :warning (expr->pos,"invalid expression after evaluation" );return 0 ;case EXPR_CAST :
simplify.c +1 -1
@@ -365,7 +365,7 @@ int kill_insn(struct instruction *insn, int force)/* a "pure" function can be killed too */ struct symbol *fntype =first_symbol (insn->fntypes); -if (!(fntype->ctype.modifiers &MOD_PURE )) +if (!(fntype->ctype.modifiers & (MOD_PURE |MOD_FCONST )))return 0 ; }kill_use_list (insn->arguments);
symbol.c +21 -9
@@ -141,19 +141,23 @@ static void lay_out_struct(struct symbol *sym, struct struct_union_info *info) info->flex_array = sym; } - alignment = info->packed ?1 : sym->ctype.alignment; +bool packed = info->packed || sym->packed; + + alignment = packed ? (sym->explicit_alignment ? :1 ) : sym->ctype.alignment; align_bit_mask =bytes_to_bits (alignment) -1 ;/* * Bitfields have some very special rules.. */ if (is_bitfield_type (sym)) { +if (sym->explicit_alignment) + bit_size = (bit_size + align_bit_mask) & ~align_bit_mask;unsigned long bit_offset = bit_size & align_bit_mask;int room =bitfield_base_size (sym) - bit_offset;// Zero-width fields just fill up the unit. int width = base_size ? : (bit_offset ? room :0 ); -if (width > room && !info->packed) { +if (width > room && !packed) { bit_size = (bit_size + align_bit_mask) & ~align_bit_mask; bit_offset =0 ; }
@@ -163,7 +167,7 @@ static void lay_out_struct(struct symbol *sym, struct struct_union_info *info) info->bit_size = bit_size + width;// warning (sym->pos, "bitfield: offset=%d:%d size=:%d", sym->offset, sym->bit_offset, width); -if (info->packed && sym->type ==SYM_NODE ) +if (packed && sym->type ==SYM_NODE ) sym->packed =1 ;return ; }
@@ -232,10 +236,13 @@ static struct symbol * examine_struct_union_type(struct symbol *sym, int advanceif (!member->ident)examine_anonymous_member (member); -if (member->ctype.alignment > info.max_align && !sym->packed) { +unsigned long member_align = (sym->packed || member->packed) + ? (member->explicit_alignment ? :1 ) + : member->ctype.alignment; +if (member_align > info.max_align) {// Unnamed bitfields do not affect alignment. if (member->ident || !is_bitfield_type (member)) - info.max_align = member->ctype.alignment; + info.max_align = member_align; }if (has_flexible_array (member))
@@ -245,7 +252,7 @@ static struct symbol * examine_struct_union_type(struct symbol *sym, int advancefn (member, &info); }END_FOR_EACH_PTR (member); -if (!sym->ctype.alignment) +if (sym->ctype.alignment < info.max_align) sym->ctype.alignment = info.max_align; bit_size = info.bit_size;if (info.align_size) {
@@ -566,7 +573,7 @@ static struct symbol * examine_node_type(struct symbol *sym)/* Pick up signedness information into the node */ sym->ctype.modifiers |= (MOD_SIGNEDNESS & base_type->ctype.modifiers); -if (!sym->ctype.alignment) +if (!sym->ctype.alignment || (!sym->packed && sym->ctype.alignment < alignment)) sym->ctype.alignment = alignment;/* Unsized array? The size might come from the initializer.. */
@@ -885,8 +892,12 @@ static void inherit_declaration(struct symbol *sym, struct symbol *prev) {unsigned long mods = prev->ctype.modifiers; -// inherit function attributes - sym->ctype.modifiers |= mods &MOD_FUN_ATTR ; +// inherit function and declaration attributes + sym->ctype.modifiers |= mods & (MOD_FUN_ATTR |MOD_WEAK |MOD_ALIGNED |MOD_NONSTRING ); +if ((mods &MOD_ALIGNED ) && prev->ctype.alignment > sym->ctype.alignment) + sym->ctype.alignment = prev->ctype.alignment; +if (prev->explicit_alignment > sym->explicit_alignment) + sym->explicit_alignment = prev->explicit_alignment; }void check_declaration (struct symbol *sym)
@@ -906,6 +917,7 @@ void check_declaration(struct symbol *sym)if (sym->ctype.modifiers &MOD_EXTERN ) {if ((next->ctype.modifiers & (MOD_TOPLEVEL |MOD_STATIC )) ==MOD_TOPLEVEL ) { sym->same_symbol = next; +inherit_declaration (sym, next);return ; } }
symbol.h +13 -7
@@ -117,6 +117,8 @@ struct decl_state {unsigned long f_modifiers;// function attributes unsigned long ident_modifiers;// declarator-id C23 attributes unsigned long storage_class; +unsigned long typedef_mods; +unsigned int explicit_alignment;unsigned int typedef_alignment;unsigned char prefer_abstract;unsigned char autotype;
@@ -199,6 +201,7 @@ struct symbol {unsigned long offset;int bit_size;int bitint_width; +unsigned int explicit_alignment; unsigned int bit_offset : 8; unsigned int bogus_linear : 1; unsigned int variadic : 1;
@@ -276,8 +279,8 @@ struct symbol {#define MOD_USERTYPE 0x00020000#define MOD_CONSTEXPR 0x00040000#define MOD_BITINT 0x00080000 -// MOD UNUSED 0x00100000 -// MOD UNUSED 0x00200000 +#define MOD_WEAK 0x00100000 +#define MOD_ALIGNED 0x00200000#define MOD_UNUSED 0x00400000#define MOD_SAFE 0x00800000 // non-null/non-trapping pointer
@@ -287,6 +290,8 @@ struct symbol {#define MOD_NODEREF 0x08000000#define MOD_NORETURN 0x10000000#define MOD_EXT_VISIBLE 0x20000000 +#define MOD_NONSTRING 0x40000000 +#define MOD_FCONST 0x80000000UL#define MOD_ACCESS (MOD_ASSIGNED | MOD_ADDRESSABLE)
@@ -295,21 +300,22 @@ struct symbol {#define MOD_ESIGNED (MOD_SIGNED | MOD_EXPLICITLY_SIGNED)#define MOD_SIGNEDNESS (MOD_SIGNED | MOD_UNSIGNED | MOD_EXPLICITLY_SIGNED)#define MOD_SPECIFIER (MOD_SIGNEDNESS | MOD_BITINT) -#define MOD_IGNORE (MOD_STORAGE | MOD_ACCESS | MOD_USERTYPE | MOD_EXPLICITLY_SIGNED | MOD_EXT_VISIBLE | MOD_UNUSED | MOD_GNU_INLINE | MOD_CONSTEXPR) +#define MOD_IGNORE (MOD_STORAGE | MOD_ACCESS | MOD_USERTYPE | MOD_EXPLICITLY_SIGNED | MOD_EXT_VISIBLE | MOD_UNUSED | MOD_GNU_INLINE | MOD_WEAK | MOD_ALIGNED | MOD_NONSTRING | MOD_CONSTEXPR)#define MOD_QUALIFIER (MOD_CONST | MOD_VOLATILE | MOD_RESTRICT)/* modifiers for function attributes */ -#define MOD_FUN_ATTR (MOD_PURE|MOD_NORETURN) +#define MOD_FUN_ATTR (MOD_PURE|MOD_NORETURN|MOD_FCONST)#define MOD_PTRINHERIT (MOD_QUALIFIER | MOD_ATOMIC | MOD_NODEREF | MOD_FUN_ATTR | MOD_NOCAST)/* modifiers preserved by typeof() operator */ #define MOD_TYPEOF (MOD_QUALIFIER | MOD_ATOMIC | MOD_NOCAST | MOD_SPECIFIER)/* like cvr-qualifiers but 'reversed' (OK: source <= target) */ -#define MOD_REV_QUAL (MOD_PURE|MOD_NORETURN) +#define MOD_REV_QUAL (MOD_PURE|MOD_NORETURN|MOD_FCONST)/* do not warn when these are duplicated */ -#define MOD_DUP_OK (MOD_UNUSED|MOD_GNU_INLINE|MOD_USERTYPE) +#define MOD_DUP_OK (MOD_UNUSED|MOD_GNU_INLINE|MOD_WEAK|MOD_ALIGNED|MOD_USERTYPE|MOD_NONSTRING|MOD_FUN_ATTR)/* must be part of the declared symbol, not its type */ #define MOD_DECLARE \ (MOD_STORAGE | MOD_INLINE | MOD_TLS | MOD_GNU_INLINE | MOD_UNUSED | \ - MOD_PURE | MOD_NORETURN | MOD_EXT_VISIBLE | MOD_CONSTEXPR) + MOD_PURE | MOD_NORETURN | MOD_FCONST | MOD_EXT_VISIBLE | \ + MOD_CONSTEXPR | MOD_WEAK | MOD_ALIGNED | MOD_NONSTRING)/* Current parsing/evaluation function */ extern struct symbol *current_fn;
validation/builtin-has-attribute-err.c new file +19 -0
@@ -0,0 +1,19 @@ +static int x; + +static int test_err (void ) +{ +return __builtin_has_attribute (x,123 ) + +__builtin_has_attribute (x,"aligned" ) + + __builtin_has_attribute(x, ); +} + +/* +* check-name: builtin-has-attribute-err +* check-command: sparse $file +* +* check-error-start +builtin-has-attribute-err.c:5:43: error: expected attribute name +builtin-has-attribute-err.c:6:43: error: expected attribute name +builtin-has-attribute-err.c:7:43: error: expected attribute name +* check-error-end +*/
validation/builtin-has-attribute-more.c new file +157 -0
157 lines not on this page · raw message
validation/builtin-has-attribute-nonstring.c new file +35 -0
@@ -0,0 +1,35 @@ +struct s_msg { +char str[16 ]; +char nonstr[16 ] __attribute__((__nonstring__)); +}; + +static struct s_msg msg; +static char global_nonstr[32] __attribute__((nonstring)); +static char global_str[32 ]; +static char *ptr_nonstr __attribute__((nonstring)); +static char *ptr_str; + +extern char ext_nonstr[8] __attribute__((nonstring)); +char ext_nonstr[8 ]; + +_Static_assert (__has_attribute (nonstring),"has_attribute nonstring" ); +_Static_assert (__has_attribute (__nonstring__),"has_attribute __nonstring__" ); +_Static_assert (__builtin_has_attribute (msg.nonstr, nonstring),"msg.nonstr has nonstring" ); +_Static_assert (__builtin_has_attribute (msg.nonstr, __nonstring__),"msg.nonstr has __nonstring__" ); +_Static_assert (!__builtin_has_attribute (msg.str, nonstring),"msg.str does not have nonstring" ); +_Static_assert (__builtin_has_attribute (global_nonstr, nonstring),"global_nonstr has nonstring" ); +_Static_assert (!__builtin_has_attribute (global_str, nonstring),"global_str does not have nonstring" ); +_Static_assert (__builtin_has_attribute (ptr_nonstr, nonstring),"ptr_nonstr has nonstring" ); +_Static_assert (!__builtin_has_attribute (ptr_str, nonstring),"ptr_str does not have nonstring" ); +_Static_assert (__builtin_has_attribute (ext_nonstr, nonstring),"redecl nonstring" ); + +#ifdef __CHECKER__ +typedef char nonstr_arr [8 ] __attribute__((nonstring)); +static nonstr_arr *ns_p; +_Static_assert (!__builtin_has_attribute (ns_p, nonstring),"ptr to typedef nonstring does not leak" ); +#endif + +/* +* check-name: builtin-has-attribute-nonstring +* check-command: sparse -Wno-decl $file +*/
validation/builtins-kernel.c +31 -0
@@ -2,6 +2,10 @@#error "missing __builtin_dynamic_object_size"#endif +#if !__has_builtin (__builtin_has_attribute) +#error "missing __builtin_has_attribute" +#endif +#if !__has_builtin (__builtin_thread_pointer)#error "missing __builtin_thread_pointer"#endif
@@ -14,6 +18,33 @@#error "missing __builtin_counted_by_ref"#endif +extern int weak_var __attribute__((__weak__)); +_Static_assert (__builtin_has_attribute (weak_var, __weak__),"weak_var has __weak__" ); +_Static_assert (__builtin_has_attribute (weak_var, weak),"weak_var has weak" ); +_Static_assert (__builtin_has_attribute (*&weak_var, __weak__),"*&weak_var has __weak__" ); + +struct s_packed { +int a; +char b; +} __attribute__((__packed__ )); + +_Static_assert(__builtin_has_attribute(struct s_packed, packed), "s_packed has packed"); +_Static_assert(__builtin_has_attribute(struct s_packed, __packed__), "s_packed has __packed__"); + +struct s_normal { + int a; + char b; + int c __attribute__((__packed__)); +}; +static struct s_normal s_norm_inst; + +_Static_assert(!__builtin_has_attribute(struct s_normal, packed), "s_normal not packed"); +_Static_assert(__builtin_has_attribute(s_norm_inst.c, packed), "s_norm_inst.c packed"); +_Static_assert(!__builtin_has_attribute(weak_var, packed), "weak_var not packed"); + +static int aligned_var __attribute__((aligned(16))); +_Static_assert (__builtin_has_attribute (aligned_var, aligned),"aligned_var has aligned" ); +struct fam {int count;char arr[];
validation/struct-packed-aligned-layout.c new file +135 -0
135 lines not on this page · raw message
validation/weak-const-no-fold.c new file +15 -0
@@ -0,0 +1,15 @@ +const int __attribute__((weak)) weak_const =10 ; + +int read_weak_const (void ) +{ +return weak_const; +} + +/* +* check-name: weak-const-no-fold +* check-command: test-linearize -Wno-decl $file +* +* check-output-ignore +* check-output-contains: load\\.32.*\\[weak_const\\] +* check-output-excludes: ret\\.32.*\\$10 +*/
PATCH 68/73 cleanup: Support __attribute__((cleanup(...))) in linearize and -Wcontext
In reply to Bart Van AsscheImplement evaluation and linearization for __attribute__((cleanup(...))) so that scope-based resource management in the Linux kernel (such as guard(mutex)(&lock), scoped_guard, and __free(...) in include/linux/cleanup.h) is modeled accurately by -Wcontext:
- Validate in parse.c and evaluate.c that the cleanup attribute names a function, applies only to local automatic variables, and type-checks calls to fn(&var).
- Maintain a lexical cleanup_scope tree in linearize.c across compound statements, declarations, iterators, and switches, and record cleanup variables as their declarations are linearized.
- Emit cleanup calls in reverse declaration order (LIFO) on block exit, loop/switch break and continue, goto, and return after evaluating the return expression.
- Copy expanded cleanup expressions correctly in inline.c: handle statement expressions that expand_compound() collapsed into a single non-compound statement and preserve the constraint flags of asm operands since cleanup expressions are not re-evaluated after copying.
Add validation tests in validation/cleanup-context.c, validation/cleanup-errors.c, validation/cleanup-inline-loop.c, validation/linear/cleanup-control-flow.c, and validation/linear/cleanup-stmt-expr-asm.c.
--- evaluate.c | 38 ++ expand.c | 8 +- inline.c | 218 +++++++++- linearize.c | 478 +++++++++++++++++++++- linearize.h | 4 + parse.c | 22 +- parse.h | 4 + symbol.h | 1 + validation/cleanup-context.c | 161 ++++++++ validation/cleanup-errors.c | 77 ++++ validation/cleanup-inline-loop.c | 31 ++ validation/linear/cleanup-control-flow.c | 62 +++ validation/linear/cleanup-stmt-expr-asm.c | 48 +++ 13 files changed, 1129 insertions(+), 23 deletions(-) create mode 100644 validation/cleanup-context.c create mode 100644 validation/cleanup-errors.c create mode 100644 validation/cleanup-inline-loop.c create mode 100644 validation/linear/cleanup-control-flow.c create mode 100644 validation/linear/cleanup-stmt-expr-asm.c
evaluate.c +38 -0
@@ -4236,6 +4236,41 @@ static bool has_invalid_constexpr_qualifiers(struct symbol *type)return false; } +static void evaluate_cleanup (struct symbol *sym) +{ +struct expression *var_expr, *addr_expr, *fn_expr, *call; + +if (!sym->cleanup || sym->cleanup->type !=EXPR_SYMBOL ) +return ; + +if (sym->ctype.modifiers & (MOD_TOPLEVEL |MOD_STATIC |MOD_EXTERN )) { +sparse_error (sym->pos,"cleanup attribute may only be applied to local variables" ); + sym->cleanup =NULL ; +return ; + } + + var_expr =alloc_expression (sym->pos,EXPR_SYMBOL ); + var_expr->symbol = sym; + var_expr->symbol_name = sym->ident; +evaluate_expression (var_expr); + + addr_expr =alloc_expression (sym->pos,EXPR_PREOP ); + addr_expr->op ='&' ; + addr_expr->unop = var_expr; +evaluate_expression (addr_expr); + + fn_expr =alloc_expression (sym->cleanup->pos,EXPR_SYMBOL ); + fn_expr->symbol = sym->cleanup->symbol; + fn_expr->symbol_name = sym->cleanup->symbol_name; + + call =alloc_expression (sym->pos,EXPR_CALL ); + call->fn = fn_expr; +add_expression (&call->args, addr_expr); +evaluate_call (call); + + sym->cleanup = call; +} +static struct symbol *evaluate_symbol (struct symbol *sym) {struct symbol *base_type;
@@ -4276,6 +4311,9 @@ static struct symbol *evaluate_symbol(struct symbol *sym) sym->underspecified =0 ; } +if (sym->cleanup) +evaluate_cleanup (sym); +/* And finally, evaluate the body of the symbol too */ if (base_type->type ==SYM_FN ) {struct symbol *curr = current_fn;
expand.c +7 -1
@@ -1736,6 +1736,7 @@ int expand_symbol(struct symbol *sym)return 0 ; retval =expand_expression (sym->initializer); +expand_expression (sym->cleanup);/* expand the body of the symbol */ if (base_type->type ==SYM_FN ) {if (base_type->stmt)
@@ -1856,13 +1857,18 @@ static int expand_statement(struct statement *stmt)case STMT_IF :return expand_if_statement (stmt); -case STMT_ITERATOR : +case STMT_ITERATOR : { +struct symbol *sym; + FOR_EACH_PTR(stmt->iterator_syms, sym) { +expand_symbol (sym); + }END_FOR_EACH_PTR (sym);expand_expression (stmt->iterator_pre_condition);expand_expression (stmt->iterator_post_condition);expand_statement (stmt->iterator_pre_statement);expand_statement (stmt->iterator_statement);expand_statement (stmt->iterator_post_statement);return SIDE_EFFECTS ; + }case STMT_SWITCH :expand_expression (stmt->switch_expression);
inline.c +211 -7
297 lines not on this page · raw message
linearize.c +466 -12
588 lines not on this page · raw message
linearize.h +4 -0
@@ -321,6 +321,9 @@ static inline void replace_bb_in_list(struct basic_block_list **list,replace_ptr_list_entry ((struct ptr_list **)list, old, new, count); } +struct cleanup_scope ; +DECLARE_ALLOCATOR (cleanup_scope); +struct entrypoint {struct symbol *name;struct symbol_list *syms;
@@ -329,6 +332,7 @@ struct entrypoint {struct basic_block *active;struct instruction *entry;unsigned int dom_levels;/* max levels in the dom tree */ +struct cleanup_scope *cleanup_scope; };extern void insert_select (struct basic_block *bb,struct instruction *br,struct instruction *phi,pseudo_t if_true,pseudo_t if_false);
parse.c +19 -3
@@ -1512,7 +1512,7 @@ static struct token *attribute_cleanup(struct token *token, struct symbol *attr,else if (token_type (token) !=TOKEN_IDENT )sparse_error (token->pos,"argument is not an identifier" ); token =primary_expression (token, &expr); -if (expr && expr->type ==EXPR_SYMBOL ) +if (expr && expr->type ==EXPR_SYMBOL &&match_op (token,')' )) ctx->cleanup = expr;return expect (token,')' ,"after attribute's argument'" ); }
@@ -2609,7 +2609,8 @@ static struct token *declaration_list(struct token *token, struct symbol_list ** decl->ctype = ctx.ctype; decl->ctype.modifiers |= mod; - decl->cleanup = ctx.cleanup; +if (ctx.cleanup) +sparse_error (decl->pos,"cleanup attribute may only be applied to local variables" ); decl->packed = ctx.packed; decl->explicit_alignment = ctx.explicit_alignment;apply_fn_ptr_modifiers (decl, ctx.f_modifiers);
@@ -2681,6 +2682,8 @@ static struct token *parameter_declaration(struct token *token, struct symbol *sapply_fn_ptr_modifiers (sym, ctx.f_modifiers); sym->endpos = token->pos; sym->forced_arg = ctx.forced; +if (ctx.cleanup) +sparse_error (sym->pos,"cleanup attribute may only be applied to local variables" );if (ctx.has_auto || ctx.autotype) { sparse_error(sym->pos, "parameter '%s' cannot be declared %s",
@@ -3845,6 +3848,7 @@ struct token *external_declaration(struct token *token, struct symbol_list **lisstruct symbol *decl;struct decl_state ctx = { .ident = &ident };struct ctype saved; +struct expression *saved_cleanup;struct symbol *base_type;unsigned long mod, saved_f_modifiers;unsigned int saved_explicit_alignment, saved_td_align;
@@ -3889,6 +3893,7 @@ struct token *external_declaration(struct token *token, struct symbol_list **lis saved_td_align = ctx.typedef_alignment; saved_f_modifiers = ctx.f_modifiers; saved = ctx.ctype; + saved_cleanup = ctx.cleanup; token =declarator (token, &ctx); token =handle_asm_name (token, &ctx); token =handle_attributes (token, &ctx);
@@ -3945,6 +3950,10 @@ struct token *external_declaration(struct token *token, struct symbol_list **lis } } }else if (base_type && base_type->type ==SYM_FN ) { +if (decl->cleanup) { +sparse_error (decl->pos,"cleanup attribute may only be applied to local variables" ); + decl->cleanup =NULL ; + }if (ctx.is_constexpr) { sparse_error( decl->pos,
@@ -4033,6 +4042,9 @@ struct token *external_declaration(struct token *token, struct symbol_list **lisadd_symbol (list, decl);fn_local_symbol (decl); } + }else if (decl->cleanup) { +sparse_error (decl->pos,"cleanup attribute may only be applied to local variables" ); + decl->cleanup =NULL ; }check_declaration (decl);if (decl->same_symbol) {
@@ -4161,7 +4173,7 @@ struct token *external_declaration(struct token *token, struct symbol_list **lis ctx.typedef_alignment = saved_td_align; ctx.f_modifiers = saved_f_modifiers; ctx.ctype = saved; - ctx.cleanup =NULL ; + ctx.cleanup = saved_cleanup; ctx.ident_modifiers =0 ; token =handle_attributes (token, &ctx); token =declarator (token, &ctx);
@@ -4195,6 +4207,10 @@ struct token *external_declaration(struct token *token, struct symbol_list **lis/* Function declarations are automatically extern unless specifically static */ base_type = decl->ctype.base_type;if (!is_typedef && base_type && base_type->type ==SYM_FN ) { +if (decl->cleanup) { +sparse_error (decl->pos,"cleanup attribute may only be applied to local variables" ); + decl->cleanup =NULL ; + } decl->ctype.modifiers |= ctx.f_modifiers;if (standard >=STANDARD_C23 && base_type->kr_args) sparse_error(decl->pos,
parse.h +4 -0
@@ -44,9 +44,12 @@ enum statement_type { STMT_RANGE, }; +struct cleanup_scope ; + struct statement { enum statement_type type; struct position pos; + struct cleanup_scope *cleanup_scope; union { struct /* declaration */ { struct symbol_list *declaration;
@@ -138,6 +141,7 @@ extern struct symbol *ctype_integer(int size, int want_unsigned);extern int inline_function (struct expression *expr,struct symbol *sym);extern void uninline (struct symbol *sym); +extern struct expression *copy_cleanup_expression (struct expression *expr);extern void init_parser (int );extern void init_parser_finalize (void );
symbol.h +1 -0
@@ -251,6 +251,7 @@ struct symbol { }; };pseudo_t pseudo; +struct cleanup_scope *cleanup_scope; };/* Modifiers */
validation/cleanup-context.c new file +161 -0
161 lines not on this page · raw message
validation/cleanup-errors.c new file +77 -0
77 lines not on this page · raw message
validation/cleanup-inline-loop.c new file +31 -0
@@ -0,0 +1,31 @@ +#define __cleanup (f) __attribute__((cleanup(f))) + +static inline void cleanup_fn (int *p) +{ +int tmp = *p; +while (tmp >0 ) { + tmp--; +if (tmp ==0 ) + goto done; + } +done: + *p = tmp; +} + +static int test_multiple_exits (int cond) +{ + int x __cleanup(cleanup_fn) = 2; +if (cond ==1 ) +return 1 ; +if (cond ==2 ) +return 2 ; +return 0 ; +} + +/* +* check-name: inline cleanup with loop across multiple exits +* check-command: test-linearize -Wno-decl $file +* +* check-output-ignore +* check-output-excludes: VOID +*/
validation/linear/cleanup-control-flow.c new file +62 -0
62 lines not on this page · raw message
validation/linear/cleanup-stmt-expr-asm.c new file +48 -0
48 lines not on this page · raw message
PATCH 69/73 builtin: Do not evaluate __builtin_clz(0) and __builtin_ctz(0)
In reply to Bart Van AsscheDo not evaluate __builtin_clz() and __builtin_ctz() at compile time when the argument is zero. Return SIDE_EFFECTS instead so that the expression is not constant-folded.
Avoid undefined behavior in the host compiler. Prevent crashes when sparse is built with -fsanitize=undefined and run with UBSAN_OPTIONS=halt_on_error=1, as passing zero to the host compiler builtins invokes undefined behavior.
Add a regression test in validation/builtin-clz-ctz-zero.c to verify that passing zero to __builtin_clz() and __builtin_ctz() does not cause sparse to crash.
--- builtin.c | 16 +++++++++------- validation/builtin-clz-ctz-zero.c | 11 +++++++++++ 2 files changed, 20 insertions(+), 7 deletions(-) create mode 100644 validation/builtin-clz-ctz-zero.c
builtin.c +9 -7
@@ -246,7 +246,7 @@ static struct symbol_op bswap_op = { }; -#define EXPAND_FINDBIT (name) \ +#define EXPAND_FINDBIT (name, zero_is_ub) \ static int expand_##name(struct expression *expr, int cost) \ { \ struct expression *arg; \
@@ -257,6 +257,8 @@ static int expand_##name(struct expression *expr, int cost) \ \ arg =first_expression (expr->args); \ val =get_expression_value_silent (arg); \ +if (zero_is_ub && !val) \ +return SIDE_EFFECTS ; \switch (arg->ctype->bit_size) { \case sizeof (int ) *8 : \ val = __builtin_##name(val); break; \
@@ -277,12 +279,12 @@ static struct symbol_op name##_op = { \ .expand = expand_##name, \ } -EXPAND_FINDBIT (clz); -EXPAND_FINDBIT (ctz); -EXPAND_FINDBIT (clrsb); -EXPAND_FINDBIT (ffs); -EXPAND_FINDBIT (parity); -EXPAND_FINDBIT (popcount); +EXPAND_FINDBIT (clz,1 ); +EXPAND_FINDBIT (ctz,1 ); +EXPAND_FINDBIT (clrsb,0 ); +EXPAND_FINDBIT (ffs,0 ); +EXPAND_FINDBIT (parity,0 ); +EXPAND_FINDBIT (popcount,0 );static int evaluate_fp_unop (struct expression *expr) {
validation/builtin-clz-ctz-zero.c new file +11 -0
@@ -0,0 +1,11 @@ +static int ctz_zero =__builtin_ctz (0 ); +static int clz_zero =__builtin_clz (0 ); +static int ctzll_zero =__builtin_ctzll (0 ); +static int clzll_zero =__builtin_clzll (0 ); + +/* +* check-name: __builtin_clz and __builtin_ctz with zero +* check-command: sparse -Wno-decl $file +* check-error-start +* check-error-end +*/
PATCH 70/73 pre-process: Support long token and string expansions dynamically
In reply to Bart Van AsscheDynamically resize token and string buffers in show_token_sequence(), tokenize.c, and get_string_constant() in char.c, check allocation and size bounds, increase MAX_STRING in token.h to 65535, and round oversized slab allocations up to chunk multiples in allocate.c.
Prevent "too long token expansion" errors, 64 KB string literal truncation, die("alloc too big") aborts, and fixed-buffer overflows when formatting, stringifying, or concatenating deeply nested macro expansions such as those found in modern Linux kernel headers.
Add a regression test in validation/long-string-expansion.c.
--- allocate.c | 27 ++++++++--- allocate.h | 1 + char.c | 46 +++++++++++------- pre-process.c | 58 ++++++++++++++++------ token.h | 2 +- tokenize.c | 78 +++++++++++++++++++++--------- validation/long-string-expansion.c | 30 ++++++++++++ 7 files changed, 179 insertions(+), 63 deletions(-) create mode 100644 validation/long-string-expansion.c
allocate.c +19 -8
@@ -30,6 +30,7 @@* efficient: allocate larger "blobs", and give out individual * small bits and pieces of it with no maintenance overhead. */ +#include <limits.h> #include <stdlib.h> #include <stddef.h> #include <stdio.h>
@@ -60,7 +61,7 @@ void drop_all_allocations(struct allocator_struct *desc) desc->freelist =NULL ;while (blob) {struct allocation_blob *next = blob->next; -blob_free (blob, desc->chunking); +blob_free (blob, blob->size); blob = next; } }
@@ -97,22 +98,32 @@ void *allocate(struct allocator_struct *desc, unsigned int size) desc->useful_bytes += size; size = (size + alignment -1 ) & ~(alignment-1 );if (!blob || blob->left < size) { -unsigned int offset, chunking = desc->chunking; +unsigned long offset, chunking = desc->chunking;struct allocation_blob *newblob; offset = offsetof(struct allocation_blob , data); offset = (offset + alignment -1 ) & ~(alignment-1 ); -if (size > chunking - offset) -die ("alloc too big" ); +if (size > chunking - offset) { +unsigned long need = (unsigned long )size + offset; + chunking = (need + chunking -1 ) & ~(chunking -1 ); +if (chunking < need || chunking - offset >UINT_MAX ) +die ("alloc too big" ); + } newblob =blob_alloc (chunking);if (!newblob)die ("out of memory" ); desc->total_bytes += chunking; - newblob->next = blob; + newblob->size = chunking; + newblob->left = chunking - offset; + newblob->offset = offset - offsetof(struct allocation_blob , data); +if (blob && blob->left > newblob->left - size) { + newblob->next = blob->next; + blob->next = newblob; + }else { + newblob->next = blob; + desc->blobs = newblob; + } blob = newblob; - desc->blobs = newblob; - blob->left = chunking - offset; - blob->offset = offset - offsetof(struct allocation_blob , data); } retval = blob->data + blob->offset; blob->offset += size;
allocate.h +1 -0
@@ -5,6 +5,7 @@struct allocation_blob {struct allocation_blob *next; +unsigned long size;unsigned int left, offset;unsigned char data[]; };
char.c +29 -17
75 lines not on this page · raw message
pre-process.c +43 -15
87 lines not on this page · raw message
token.h +1 -1
@@ -206,7 +206,7 @@ struct token { }; }; -#define MAX_STRING 8191 +#define MAX_STRING 65535static inline struct token *containing_token (struct token **p) {
tokenize.c +56 -22
140 lines not on this page · raw message
validation/long-string-expansion.c new file +30 -0
@@ -0,0 +1,30 @@ +#define S16 "0123456789abcdef" +#define S64 S16 S16 S16 S16 +#define S256 S64 S64 S64 S64 +#define S1024 S256 S256 S256 S256 +#define S4096 S1024 S1024 S1024 S1024 +#define S16384 S4096 S4096 S4096 S4096 +#define S65536 S16384 S16384 S16384 S16384 + +#define STR_INNER (x) #x +#define STR (x) STR_INNER(x) + +#define T4 a+a+a+a +#define T16 T4+T4+T4+T4 +#define T64 T16+T16+T16+T16 +#define T256 T64+T64+T64+T64 +#define T1024 T256+T256+T256+T256 +#define T4096 T1024+T1024+T1024+T1024 +#define T16384 T4096+T4096+T4096+T4096 +#define T65536 T16384+T16384+T16384+T16384 + +/* Concatenated string literal > 65535 bytes */ +_Static_assert(sizeof(S65536 S16) == 65536 + 16 + 1, "concat > 64KB"); + +/* Stringified macro expansion with escaped quotes > 65535 bytes */ +_Static_assert (sizeof (STR ("q" T65536 )) >130000 ,"stringify > 64KB" ); + +/* +* check-name: long-string-expansion +* check-command: sparse $file +*/
PATCH 71/73 x86: Undefine conflicting bitness macros when parsing -m flags
In reply to Bart Van AsscheEmit #undef directives for conflicting x86 bitness macros in handle_mbitness() in options.c at the command-line position of -m16, -m32, -m64, or -mx32, while preserving explicit -D macro definitions that appear later on the command line.
Prevent inconsistent word size errors and static assertion failures in the Linux kernel when real-mode 16-bit code is compiled under an x86_64 kernel build that passes -D__x86_64__ before -m16 in CHECKFLAGS, and add validation/arch/x86-bitness-undef.c and x86-bitness-override.c.
--- options.c | 58 +++++++++++++++++++++++--- validation/arch/x86-bitness-override.c | 17 ++++++++ validation/arch/x86-bitness-undef.c | 16 +++++++ 3 files changed, 85 insertions(+), 6 deletions(-) create mode 100644 validation/arch/x86-bitness-override.c create mode 100644 validation/arch/x86-bitness-undef.c
options.c +52 -6
@@ -671,13 +671,59 @@ static char **handle_multiarch_dir(char *arg, char **next)return next; } +static int handle_mbitness (const char *arg,const char *opt,const struct flag *flag,int options) +{ +if (opt[0 ] !='\0' || (options &OPT_INVERSE )) +return 0 ; + *flag->flag = flag->val; +if (arch_target->mach ==MACH_I386 || arch_target->mach ==MACH_X86_64 ) { +switch (flag->val) { +case ARCH_LP32 : +add_pre_buffer ("#undef __x86_64__\n" +"#undef __x86_64\n" +"#undef __amd64__\n" +"#undef __amd64\n" +"#ifndef __i386__\n" +"#define __i386__ 1\n" +"#endif\n" +"#ifndef __i386\n" +"#define __i386 1\n" +"#endif\n" +"#if !defined(__STRICT_ANSI__) && !defined(i386)\n" +"#define i386 1\n" +"#endif\n" ); +break ; +case ARCH_LP64 : +case ARCH_X32 : +case ARCH_LLP64 : +add_pre_buffer ("#undef __i386__\n" +"#undef __i386\n" +"#undef i386\n" +"#ifndef __x86_64__\n" +"#define __x86_64__ 1\n" +"#endif\n" +"#ifndef __x86_64\n" +"#define __x86_64 1\n" +"#endif\n" +"#ifndef __amd64__\n" +"#define __amd64__ 1\n" +"#endif\n" +"#ifndef __amd64\n" +"#define __amd64 1\n" +"#endif\n" ); +break ; + } + } +return 1 ; +} +static const struct flag mflags[] = { - {"64" , &arch_m64,NULL ,OPT_VAL ,ARCH_LP64 }, - {"32" , &arch_m64,NULL ,OPT_VAL ,ARCH_LP32 }, - {"31" , &arch_m64,NULL ,OPT_VAL ,ARCH_LP32 }, - {"16" , &arch_m64,NULL ,OPT_VAL ,ARCH_LP32 }, - {"x32" ,&arch_m64,NULL ,OPT_VAL ,ARCH_X32 }, - {"size-llp64" , &arch_m64,NULL ,OPT_VAL ,ARCH_LLP64 }, + {"64" , &arch_m64, handle_mbitness,OPT_VAL ,ARCH_LP64 }, + {"32" , &arch_m64, handle_mbitness,OPT_VAL ,ARCH_LP32 }, + {"31" , &arch_m64, handle_mbitness,OPT_VAL ,ARCH_LP32 }, + {"16" , &arch_m64, handle_mbitness,OPT_VAL ,ARCH_LP32 }, + {"x32" ,&arch_m64, handle_mbitness,OPT_VAL ,ARCH_X32 }, + {"size-llp64" , &arch_m64, handle_mbitness,OPT_VAL ,ARCH_LLP64 }, {"size-long" , &arch_msize_long }, {"arch=" ,NULL , handle_march }, {"big-endian" , &arch_big_endian,NULL },
validation/arch/x86-bitness-override.c new file +17 -0
@@ -0,0 +1,17 @@ +#ifdef __x86_64__ +defined_x86_64 +#endif +#ifdef __i386__ +defined_i386 +#endif + +/* +* check-name: arch/x86-bitness-override +* check-command: sparse --arch=x86_64 -m16 -D__x86_64__ -E $file +* +* check-output-start + +defined_x86_64 +defined_i386 +* check-output-end +*/
validation/arch/x86-bitness-undef.c new file +16 -0
@@ -0,0 +1,16 @@ +#ifdef __x86_64__ +defined_x86_64 +#endif +#ifdef __i386__ +defined_i386 +#endif + +/* +* check-name: arch/x86-bitness-undef +* check-command: sparse --arch=x86_64 -D__x86_64__ -m16 -E $file +* +* check-output-start + +defined_i386 +* check-output-end +*/
PATCH 72/73 evaluate: Accept conditional expressions with only one void side
In reply to Bart Van AsscheAccept conditional expressions in which exactly one of the second and third operands has complete type void as a GNU extension matching GCC and Clang: give the expression type void, evaluate the non-void operand only for its side effects, warn only under -Wpedantic, and avoid emitting zero-sized phi nodes in linearize_conditional().
Support Linux kernel macros such as STA_ASSIGN in net/mac80211/trace.h and nfs_errorf() in fs/nfs/internal.h without false "incompatible types in conditional expression" errors while continuing to diagnose uses of the void result value.
Update validation/cond-err-expand.c and add validation/cond-one-void.c and validation/cond-one-void-pedantic.c.
--- evaluate.c | 113 ++++++++++++++++++---------- expand.c | 17 ++++- linearize.c | 19 +++++ validation/cond-err-expand.c | 9 --- validation/cond-one-void-pedantic.c | 39 ++++++++++ validation/cond-one-void.c | 47 ++++++++++++ validation/linear/cond-one-void.c | 24 ++++++ 7 files changed, 217 insertions(+), 51 deletions(-) create mode 100644 validation/cond-one-void-pedantic.c create mode 100644 validation/cond-one-void.c create mode 100644 validation/linear/cond-one-void.c
evaluate.c +72 -41
@@ -1421,6 +1421,37 @@ static struct symbol *evaluate_conditional_expression(struct expression *expr) lclass =classify_type (ltype, <ype); rclass =classify_type (rtype, &rtype); + +/* +* GNU extension supported by gcc and clang: if exactly one of the +* second and third operands has type void, the result has type void +* and the other operand is only evaluated for its side effects. +* ISO C forbids this [6.5.15(3)]. +*/ +if ((ltype == &void_ctype) != (rtype == &void_ctype)) { +struct symbol *other_type = (ltype == &void_ctype) ? rtype : ltype; + +if (!valid_type (other_type)) { + expr->flags =CEF_NONE ; + expr->ctype = &bad_ctype; +return NULL ; + } +if (other_type == &incomplete_ctype || other_type->bit_size <0 || + ((other_type->type ==SYM_STRUCT || other_type->type ==SYM_UNION ) && + !other_type->defined)) { +expression_error (expr,"expression has incomplete type '%s'" , +show_typename (other_type)); +return NULL ; + } +if (Wpedantic) +warning (expr->pos,"ISO C forbids conditional expression with only one void side" ); +if (expr->cond_true) + *cond =cast_to (*cond, &void_ctype); + expr->cond_false =cast_to (expr->cond_false, &void_ctype); + ctype = &void_ctype; + goto out; + } +if (lclass & rclass &TYPE_NUM ) { ctype =usual_conversions ('?' , *cond, expr->cond_false, lclass, rclass, ltype, rtype);
@@ -3127,7 +3158,8 @@ static void check_constexpr_scalar_init(struct expression *orig, } tmp = *orig;if (!is_null_pointer_constant (&tmp) && - !(((sclass &TYPE_PTR ) ||is_nullptr_type (stype)) &&is_zero_constant (&tmp))) + !(((sclass &TYPE_PTR ) ||is_nullptr_type (stype)) && +is_zero_constant (&tmp)))sparse_error (orig->pos,"constexpr pointer initializer is not null" );return ;
@@ -3309,7 +3341,6 @@ static int handle_initializer(struct expression **ep, int nested,struct expression orig; e =handle_scalar (e, nested, class, ctype); -if (!e)return 0 ; *ep = e;
@@ -3323,11 +3354,11 @@ static int handle_initializer(struct expression **ep, int nested,* shall be constant expressions or a string literal [6.7.8(4)]. */ mods |= ctype->ctype.modifiers; -if (mods &MOD_CONSTEXPR ) +if (mods &MOD_CONSTEXPR ) {check_constexpr_scalar_init (&orig, ctype); -else if ((mods & (MOD_TOPLEVEL |MOD_STATIC |MOD_TLS )) && -valid_type (ctype->ctype.base_type) && - !(e->flags & (CEF_ACE |CEF_ADDR ))) { + }else if ((mods & (MOD_TOPLEVEL |MOD_STATIC |MOD_TLS )) && +valid_type (ctype->ctype.base_type) && + !(e->flags & (CEF_ACE |CEF_ADDR ))) {if (standard >=STANDARD_C23 )sparse_error (e->pos,"non-constant initializer for static object" );else if (Wconstexpr_not_const)
@@ -4187,6 +4218,41 @@ void check_duplicates(struct symbol *sym) } } +static void evaluate_cleanup (struct symbol *sym) +{ +struct expression *var_expr, *addr_expr, *fn_expr, *call; + +if (!sym->cleanup || sym->cleanup->type !=EXPR_SYMBOL ) +return ; + +if (sym->ctype.modifiers & (MOD_TOPLEVEL |MOD_STATIC |MOD_EXTERN )) { +sparse_error (sym->pos,"cleanup attribute may only be applied to local variables" ); + sym->cleanup =NULL ; +return ; + } + + var_expr =alloc_expression (sym->pos,EXPR_SYMBOL ); + var_expr->symbol = sym; + var_expr->symbol_name = sym->ident; +evaluate_expression (var_expr); + + addr_expr =alloc_expression (sym->pos,EXPR_PREOP ); + addr_expr->op ='&' ; + addr_expr->unop = var_expr; +evaluate_expression (addr_expr); + + fn_expr =alloc_expression (sym->cleanup->pos,EXPR_SYMBOL ); + fn_expr->symbol = sym->cleanup->symbol; + fn_expr->symbol_name = sym->cleanup->symbol_name; + + call =alloc_expression (sym->pos,EXPR_CALL ); + call->fn = fn_expr; +add_expression (&call->args, addr_expr); +evaluate_call (call); + + sym->cleanup = call; +} +static bool check_constexpr_vm_type (struct symbol *type) {while (type) {
@@ -4236,41 +4302,6 @@ static bool has_invalid_constexpr_qualifiers(struct symbol *type)return false; } -static void evaluate_cleanup (struct symbol *sym) -{ -struct expression *var_expr, *addr_expr, *fn_expr, *call; - -if (!sym->cleanup || sym->cleanup->type !=EXPR_SYMBOL ) -return ; - -if (sym->ctype.modifiers & (MOD_TOPLEVEL |MOD_STATIC |MOD_EXTERN )) { -sparse_error (sym->pos,"cleanup attribute may only be applied to local variables" ); - sym->cleanup =NULL ; -return ; - } - - var_expr =alloc_expression (sym->pos,EXPR_SYMBOL ); - var_expr->symbol = sym; - var_expr->symbol_name = sym->ident; -evaluate_expression (var_expr); - - addr_expr =alloc_expression (sym->pos,EXPR_PREOP ); - addr_expr->op ='&' ; - addr_expr->unop = var_expr; -evaluate_expression (addr_expr); - - fn_expr =alloc_expression (sym->cleanup->pos,EXPR_SYMBOL ); - fn_expr->symbol = sym->cleanup->symbol; - fn_expr->symbol_name = sym->cleanup->symbol_name; - - call =alloc_expression (sym->pos,EXPR_CALL ); - call->fn = fn_expr; -add_expression (&call->args, addr_expr); -evaluate_call (call); - - sym->cleanup = call; -} -static struct symbol *evaluate_symbol (struct symbol *sym) {struct symbol *base_type;
expand.c +16 -1
@@ -850,6 +850,7 @@ static int expand_conditional(struct expression *expr) cond_cost =expand_expression (cond);if (cond->type ==EXPR_VALUE ) { +struct symbol *ctype = expr->ctype;unsigned flags = expr->flags;if (!cond->value && !cond->value_hi) valt = valf;
@@ -860,13 +861,27 @@ static int expand_conditional(struct expression *expr) expr->flags = flags;if (expr->type ==EXPR_VALUE ) expr->taint |= cond->taint; +if (ctype == &void_ctype && expr->ctype != &void_ctype) { +if (expr->type ==EXPR_VALUE || expr->type ==EXPR_FVALUE ) { + expr->type =EXPR_VALUE ; + expr->value =0 ; + expr->ctype = &void_ctype; + }else { +struct expression *sub =alloc_expression (expr->pos, expr->type); + *sub = *expr; + expr->type =EXPR_CAST ; + expr->ctype = &void_ctype; + expr->cast_type = &void_ctype; + expr->cast_expression = sub; + } + }return cost; } cost =expand_expression (valt); cost +=expand_expression (valf); -if (cost <SELECT_COST ) { +if (expr->ctype != &void_ctype && cost <SELECT_COST ) { expr->type =EXPR_SELECT ; cost -=BRANCH_COST -1 ; }
linearize.c +19 -0
@@ -1699,6 +1699,14 @@ static pseudo_t linearize_short_conditional(struct entrypoint *ep, struct expres bb_false =alloc_basic_block (ep, expr_false->pos); merge =alloc_basic_block (ep, expr->pos); +if (expr->ctype == &void_ctype ||type_size (expr->ctype) <=0 ) { +linearize_cond_branch (ep, cond, merge, bb_false); +set_activeblock (ep, bb_false); +linearize_expression (ep, expr_false); +set_activeblock (ep, merge); +return VOID ; + } + src1 =linearize_expression (ep, cond); phi1 =alloc_phi (ep->active, src1, expr->ctype);add_branch (ep, src1, merge, bb_false);
@@ -1728,6 +1736,17 @@ static pseudo_t linearize_conditional(struct entrypoint *ep, struct expression *linearize_cond_branch (ep, cond, bb_true, bb_false); +if (expr->ctype == &void_ctype ||type_size (expr->ctype) <=0 ) { +set_activeblock (ep, bb_true); +linearize_expression (ep, expr_true); +add_goto (ep, merge); + +set_activeblock (ep, bb_false); +linearize_expression (ep, expr_false); +set_activeblock (ep, merge); +return VOID ; + } +set_activeblock (ep, bb_true); src1 =linearize_expression (ep, expr_true); phi1 =alloc_phi (ep->active, src1, expr->ctype);
validation/cond-err-expand.c +0 -9
@@ -17,15 +17,6 @@ void bar(void)* check-name: cond-err-expand.c * check-command: test-linearize -Wno-decl $file * -* check-error-start -cond-err-expand.c:8:11: error: incompatible types in conditional expression (different base types): -cond-err-expand.c:8:11: int -cond-err-expand.c:8:11: void -cond-err-expand.c:13:11: error: incompatible types in conditional expression (different base types): -cond-err-expand.c:13:11: void -cond-err-expand.c:13:11: int -* check-error-end -* * check-output-ignore * check-output-excludes: call.* __builtin_constant_p */
validation/cond-one-void-pedantic.c new file +39 -0
@@ -0,0 +1,39 @@ +void *f (void ); +void g (void ); +int h (void ); +extern void *p; + +static void test (int c) +{ + c ?f () :g (); + c ?g () :h (); + c ?1 :g (); + c ? p :g (); + p ?:g (); + c ?g () : (void )0 ;// both sides void: always OK + (void )(c ?h () :g ()); +} + +static int use_value (int c) +{ +int x = c ?h () :g ();// KO: void value used +return x; +} + +/* +* check-name: cond-one-void-pedantic +* check-command: sparse -Wpedantic $file +* +* check-error-start +cond-one-void-pedantic.c:8:11: warning: ISO C forbids conditional expression with only one void side +cond-one-void-pedantic.c:9:11: warning: ISO C forbids conditional expression with only one void side +cond-one-void-pedantic.c:10:11: warning: ISO C forbids conditional expression with only one void side +cond-one-void-pedantic.c:11:11: warning: ISO C forbids conditional expression with only one void side +cond-one-void-pedantic.c:12:11: warning: ISO C forbids conditional expression with only one void side +cond-one-void-pedantic.c:14:18: warning: ISO C forbids conditional expression with only one void side +cond-one-void-pedantic.c:19:19: warning: ISO C forbids conditional expression with only one void side +cond-one-void-pedantic.c:19:19: warning: incorrect type in initializer (different base types) +cond-one-void-pedantic.c:19:19: expected int x +cond-one-void-pedantic.c:19:19: got void +* check-error-end +*/
validation/cond-one-void.c new file +47 -0
47 lines not on this page · raw message
validation/linear/cond-one-void.c new file +24 -0
@@ -0,0 +1,24 @@ +void *f (void ); +void g (void ); +int h (void ); + +void test_cond_void_ir (int c,void *p) +{ + c ?f () :g (); + c ?g () :h (); + c ?1 :g (); + p ?:g (); +1 ?:g (); +0 ?:g (); +} + +/* +* check-name: cond-one-void-linearize +* check-command: test-linearize -Wno-decl $file +* +* check-output-ignore +* check-output-excludes: VOID +* check-output-excludes: phi\\. +* check-output-excludes: phisrc\\. +* check-output-excludes: select\\. +*/
PATCH 73/73 ci: Add Linux kernel GitHub Actions workflow and build script
In reply to Bart Van AsscheAdd a GitHub Actions workflow and helper script to build the Linux kernel with sparse under AddressSanitizer and UndefinedBehaviorSanitizer so regressions not covered by the validation suite are caught on a large real-world C codebase:
- .github/workflows/build-linux-kernel-with-sparse.yml: Run on push, pull_request, daily schedule, and workflow_dispatch with read-only repository contents permissions.
- ci/build-linux-kernel-with-sparse.sh: Clean and build sparse in asan mode, clone ../linux-kernel or upstream torvalds/linux.git, neutralize non-core __CHECKER__ guards, and run a defconfig C=1 kernel check with detect_invalid_pointer_pairs=2 and halt_on_error=1.
--- .../build-linux-kernel-with-sparse.yml | 28 +++++++++++++++++++ ci/build-linux-kernel-with-sparse.sh | 23 +++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 .github/workflows/build-linux-kernel-with-sparse.yml create mode 100755 ci/build-linux-kernel-with-sparse.sh
.github/workflows/build-linux-kernel-with-sparse.yml new file +28 -0
@@ -0,0 +1,28 @@ +# See also https://docs.github.com/en/actions/learn-github-actions/workflow-syntax-for-github-actions + +name: Build Linux kernel with sparse + +on: + push: + pull_request: + schedule: + - cron: '0 0 * * *' + workflow_dispatch: + +permissions: + contents: read + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@main + + - name: install + run: sudo ci/install.sh + + - name: build Linux kernel with sparse + run: | + sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc + ci/build-linux-kernel-with-sparse.sh
ci/build-linux-kernel-with-sparse.sh new file +23 -0
@@ -0,0 +1,23 @@ +#!/bin/bash + +set -euo pipefail + +make clean +export MODE=asan +ci/build.sh + +rm -rf linux-kernel +if [ -e ../linux-kernel ]; then + git clone ../linux-kernel linux-kernel +else + git clone --depth=3 https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git linux-kernel +fi +cd linux-kernel +# Make most __CHECKER__ checks ineffective. +{ git grep -lw __CHECKER__ || [ $? -eq 1 ]; } | + { grep -vE '^arch/|^include/linux/compiler|^include/uapi/linux/types.h|^include/linux/bug.h' || [ $? -eq 1 ]; } | + xargs -r -d '\n' sed -i 's/__CHECKER__/___CHECKER___/g' +make defconfig +export ASAN_OPTIONS=detect_invalid_pointer_pairs=2 +export UBSAN_OPTIONS=halt_on_error=1 +make -sj"$(nproc)" C=1 CHECK="${PWD}/../sparse"