aboutsummaryrefslogtreecommitdiff
path: root/clang/lib/Sema/SemaChecking.cpp
AgeCommit message (Collapse)AuthorFilesLines
2025-05-24[clang][NFC] Clean up SemaChecking.cpp (#141041)Timm Baeder1-75/+70
Make pointer parameters const, remove some unused parameters, fix coding style, etc.
2025-05-22[clang] Move Diags.isIgnored() check below faster checks (#141084)Timm Baeder1-4/+4
Because this check is relatively slow and the others aren't as much. http://llvm-compile-time-tracker.com/compare.php?from=4a158f675be7fd1b3763bf39980d801db89744f8&to=886a8fab041ff7574d54cccddbc1a9b968c1bb58&stat=instructions:u
2025-05-18[Sema] Use llvm::is_contained (NFC) (#140455)Kazu Hirata1-3/+1
2025-05-17[clang] Use llvm::stable_sort (NFC) (#140413)Kazu Hirata1-5/+4
2025-05-15[Clang] Add warnings when mixing different charN_t types (#138708)cor3ntin1-0/+47
charN_t represent code units of different UTF encodings. Therefore the values of 2 different charN_t objects do not represent the same characters. In order to avoid comparing apples and oranges, we add new warnings to warn on: - Implicit conversions - Comparisons - Other cases involving arithmetic conversions We only produce the warning if we cannot establish the comparison would be safe through constant evaluation. The new `-Wimplicit-unicode-conversion` warning is enabled by default. Note that this PR intentionally doesn;t touches char/wchar_t, but it would be worth considering also warning on extending the new warnings to these types (in a follow up) Additionally most arithmetic operations on charN_t don't really make sense (ie what does it mean to addition code units), so we could add warnings for that. Fixes #138526
2025-05-14[clang] Save ShuffleVectorExpr args as ConstantExpr (#139709)Timm Baeder1-11/+11
The passed indices have to be constant integers anyway, which we verify before creating the ShuffleVectorExpr. Use the value we create there and save the indices using a ConstantExpr instead. This way, we don't have to evaluate the args every time we call getShuffleMaskIdx().
2025-05-13[Clang] Fix Sema::checkArgCount for 0-arg functions (#139638)Hood Chatham1-1/+1
When calling a function that expects zero arguments with one argument, `Call->getArg(1)` will trap when trying to format the diagnostic. This also seems to improve the rendering of the diagnostic some of the time. Before: ``` $ ./bin/clang -c a.c a.c:2:30: error: too many arguments to function call, expected 2, have 4 2 | __builtin_annotation(1, 2, 3, 4); | ~ ^ ``` After: ``` $ ./bin/clang -c a.c a.c:2:30: error: too many arguments to function call, expected 2, have 4 2 | __builtin_annotation(1, 2, 3, 4); | ^~~~ ``` Split from #139580. --------- Co-authored-by: Mariya Podchishchaeva <mariya.podchishchaeva@intel.com>
2025-05-13[NFC] Use more isa and isa_and_nonnull instead dyn_cast for predicates (#137393)Max Graey1-2/+3
Also fix some typos in comments --------- Co-authored-by: Mehdi Amini <joker.eph@gmail.com>
2025-05-07[clang] Handle CC attrs for UEFI (#138935)Prabhu Rajasekaran1-5/+5
UEFI's default ABI is MS ABI. Handle the calling convention attributes accordingly.
2025-05-07Add braces to silence -Wdangling-else; NFCAaron Ballman1-1/+2
2025-05-07[C] Handle comma operator for implicit int->enum conversions (#138752)Aaron Ballman1-1/+23
In C++, the type of an enumerator is the type of the enumeration, whereas in C, the type of the enumerator is 'int'. The type of a comma operator is the type of the right-hand operand, which means you can get an implicit conversion with this code in C but not in C++: ``` enum E { Zero }; enum E foo() { return ((void)0, Zero); } ``` We were previously incorrectly diagnosing this code as being incompatible with C++ because the type of the paren expression would be 'int' there, whereas in C++ the type is 'E'. So now we handle the comma operator with special logic when analyzing implicit conversions in C. When analyzing the left-hand operand of a comma operator, we do not need to check for that operand causing an implicit conversion for the entire comma expression. So we only check for that case with the right-hand operand. This addresses a concern brought up post-commit: https://github.com/llvm/llvm-project/pull/137658#issuecomment-2854525259
2025-05-06[Clang] Implement the core language parts of P2786 - Trivial relocation ↵cor3ntin1-0/+51
(#127636) This adds - The parsing of `trivially_relocatable_if_eligible`, `replaceable_if_eligible` keywords - `__builtin_trivially_relocate`, implemented in terms of memmove. In the future this should - Add the appropriate start/end lifetime markers that llvm does not have (`start_lifetime_as`) - Add support for ptrauth when that's upstreamed - the `__builtin_is_cpp_trivially_relocatable` and `__builtin_is_replaceable` traits Fixes #127609
2025-05-02[clang][NFC] Convert `Sema::VarArgKind` to scoped enumVlad Serebrennikov1-5/+5
2025-05-02[clang][NFC] Convert `Sema::ArithConvKind` to scoped enumVlad Serebrennikov1-1/+1
2025-05-02[clang][NFC] Convert `Sema::PointerAuthDiscArgKind` to scoped enumVlad Serebrennikov1-2/+2
2025-05-01[clang] Add scoped enum support to `StreamingDiagnostic` (#138089)Vlad Serebrennikov1-5/+3
This patch adds templated `operator<<` for diagnostics that pass scoped enums, saving people from `llvm::to_underlying()` clutter on the side of emitting the diagnostic. This eliminates 80 out of 220 usages of `llvm::to_underlying()` in Clang. I also backported `std::is_scoped_enum_v` from C++23.
2025-05-01[clang][NFC] Convert `Sema::BuiltinCountedByRefKind` to scoped enumVlad Serebrennikov1-6/+6
2025-05-01[clang][NFC] Convert `Sema::VariadicCallType` to scoped enumVlad Serebrennikov1-26/+31
2025-04-29Silence spurious -Wnontrivial-memcall warnings in C mode (#137429)Akira Hatanaka1-5/+5
clang currently issues a warning when memset is used on a struct that contains an address-discriminated pointer field, even though this is entirely valid behavior. For example: ``` struct S { int * __ptrauth(1, 1, 100) p; } s; memset(&s, 0, sizeof(struct S)); ``` Only allow the warning to be emitted in C++ mode to silence the warning. rdar://142495870
2025-04-29[C] Add new -Wimplicit-int-enum-cast to -Wc++-compat (#137658)Aaron Ballman1-2/+8
This introduces a new diagnostic group to diagnose implicit casts from int to an enumeration type. In C, this is valid, but it is not compatible with C++. Additionally, this moves the "implicit conversion from enum type to different enum type" diagnostic from `-Wenum-conversion` to a new group `-Wimplicit-enum-enum-cast`, which is a more accurate home for it. `-Wimplicit-enum-enum-cast` is also under `-Wimplicit-int-enum-cast`, as it is the same incompatibility (the enumeration on the right-hand is promoted to `int`, so it's an int -> enum conversion). Fixes #37027
2025-04-28[clang][NFC] Convert `Sema::FormatStringType` to scoped enumVlad Serebrennikov1-83/+94
2025-04-24[clang] Ensure correct copying of records with authenticated fields (#136783)Oliver Hunt1-0/+3
When records contain fields with pointer authentication, even simple copies can require additional work be performed. This patch contains the core functionality required to handle user defined structs, as well as the implicitly constructed structs for blocks, etc. Co-authored-by: Ahmed Bougacha Co-authored-by: Akira Hatanaka Co-authored-by: John Mccall
2025-04-20[Clang] Consider preferred_type in bitfield warnings (#116760) (#116785)Oliver Hunt1-7/+29
Very simply extends the bitfield sema checks for assignment to fields with a preferred type specified to consider the preferred type if the decl storage type is not explicitly an enum type. This does mean that if the preferred and explicit types have different storage requirements we may not warn in all possible cases, but that's a scenario for which the warnings are much more complex and confusing.
2025-04-19[clang] llvm::append_range (NFC) (#136440)Kazu Hirata1-1/+1
2025-04-16[HLSL][OpenCL] Strip addrspace from implicit cast diags (#135830)Chris B1-0/+8
The address space of a source value for an implicit cast isn't really relevant when emitting conversion warnings. Since the lvalue->rvalue cast effectively removes the address space they don't factor in, but they do create visual noise in the diagnostics. This is a small quality-of-life fixup to get in as HLSL adopts more address space annotations.
2025-04-15[PAC] Add support for __ptrauth type qualifier (#100830)Akira Hatanaka1-0/+57
The qualifier allows programmer to directly control how pointers are signed when they are stored in a particular variable. The qualifier takes three arguments: the signing key, a flag specifying whether address discrimination should be used, and a non-negative integer that is used for additional discrimination. ``` typedef void (*my_callback)(const void*); my_callback __ptrauth(ptrauth_key_process_dependent_code, 1, 0xe27a) callback; ``` Co-Authored-By: John McCall rjmccall@apple.com
2025-04-15[clang] consistently quote expressions in diagnostics (#134769)Matheus Izvekov1-1/+4
2025-04-14Clang: Add elementwise minnum/maxnum builtin functions (#129207)YunQiang Su1-0/+2
With https://github.com/llvm/llvm-project/pull/112852, we claimed that llvm.minnum and llvm.maxnum should treat +0.0>-0.0, while libc doesn't require fmin(3)/fmax(3) for it. To make llvm.minnum/llvm.maxnum easy to use, we define the builtin functions for them, include __builtin_elementwise_minnum __builtin_elementwise_maxnum All of them support _Float16, __bf16, float, double, long double.
2025-04-07[DirectX] Add target builtins (#134439)Farzon Lotfi1-0/+3
- fixes #132303 - Moves dot2add from a language builtin to a target builtin. - Sets the scaffolding for Sema checks for DX builtins - Setup DirectX backend as able to have target builtins - Adds a DX TargetBuiltins emitter in `clang/lib/CodeGen/TargetBuiltins/DirectX.cpp`
2025-04-07[Clang] Use "syncscope" instead of "synchscope". NFC. (#134616)Jay Foad1-1/+1
This matches the spelling of the keyword in LLVM IR.
2025-03-27[clang] Use *Set::insert_range (NFC) (#133357)Kazu Hirata1-3/+2
We can use *Set::insert_range to collapse: for (auto Elem : Range) Set.insert(E); down to: Set.insert_range(Range); In some cases, we can further fold that into the set declaration.
2025-03-18[clang] Improve diagnostics for vector builtins (#125673)Fraser Cormack1-127/+99
This commit improves the diagnostics for vector (elementwise) builtins in a couple of ways. It primarily provides more precise type-checking diagnostics for builtins with specific type requirements. Previously many builtins were receiving a catch-all diagnostic suggesting types which aren't valid. It also makes consistent the type-checking behaviour between various binary and ternary builtins. The binary builtins would check for mismatched argument types before specific type requirements, whereas ternary builtins would perform the checks in the reverse order. The binary builtins now behave as the ternary ones do.
2025-03-18[Clang] Demote mixed enumeration arithmetic error to a warning (#131811)cor3ntin1-1/+1
In C++, defaulted to an error. C++ removed these features but the removal negatively impacts users. Fixes #92340
2025-03-17[Clang][NFC] Rename SecondArgIsLastNamedArgument for clarity and consistency ↵Imad Aldij1-5/+5
(#131346) Change the name of the control variable `SecondArgIsLastNamedArgument` to `SecondArgIsLastNonVariadicArgument` for clarity and consistency. Following feedback on earlier PR that was merged: - https://github.com/llvm/llvm-project/pull/131238#discussion_r1995690691_
2025-03-15[C23] Add __builtin_c23_va_start (#131166)Aaron Ballman1-13/+37
This builtin is supported by GCC and is a way to improve diagnostic behavior for va_start in C23 mode. C23 no longer requires a second argument to the va_start macro in support of variadic functions with no leading parameters. However, we still want to diagnose passing more than two arguments, or diagnose when passing something other than the last parameter in the variadic function. This also updates the freestanding <stdarg.h> header to use the new builtin, same as how GCC works. Fixes #124031
2025-03-14[clang] Fix inaccurate wording of ↵Imad Aldij1-1/+1
warn_second_arg_of_va_start_not_last_named_param (#131238) Rename and update the wording of `warn_second_arg_of_va_start_not_last_named_param` to best indicate that it's actually the last non-variadic parameter instead. Fixes #131171
2025-03-12Revert "[HLSL] error on out of bounds vector accesses (#128952)"Hans Wennborg1-23/+0
This caused false-positive errors, see comment on the PR. > Add Sema checking and diagnostics to error on out of bounds vector > accesses > Add tests > Closes #91640 This reverts commit f1e36759d2e6c26d2d5825f955c51fd595909b52.
2025-03-12[Clang] Add __builtin_elementwise_exp10 in the same fashion as exp/exp2 ↵Juan Manuel Martinez Caamaño1-0/+1
(#130746) Clang has __builtin_elementwise_exp and __builtin_elementwise_exp2 intrinsics, but no __builtin_elementwise_exp10. There doesn't seem to be a good reason not to expose the exp10 flavour of this intrinsic too. This commit introduces this intrinsic following the same pattern as the exp and exp2 versions. Fixes: SWDEV-519541
2025-03-11[HLSL] error on out of bounds vector accesses (#128952)Sarah Spall1-0/+23
Add Sema checking and diagnostics to error on out of bounds vector accesses Add tests Closes #91640 --------- Co-authored-by: Chris B <beanz@abolishcrlf.org> Co-authored-by: Aaron Ballman <aaron@aaronballman.com>
2025-03-10[Clang] Force expressions with UO_Not to not be non-negative (#126846)Yutong Zhu1-0/+36
This PR addresses the bug of not throwing warnings for the following code: ```c++ int test13(unsigned a, int *b) { return a > ~(95 != *b); // expected-warning {{comparison of integers of different signs}} } ``` However, in the original issue, a comment mentioned that negation, pre-increment, and pre-decrement operators are also incorrect in this case. Fixes #18878
2025-03-06[clang] Fix FP -Wformat in functions with 2+ attribute((format)) (#129954)apple-fcloutier1-11/+12
When defining functions with two or more format attributes, if the format strings don't have the same format family, there is a false positive warning that the incorrect kind of format string is being passed at forwarded format string call sites. This happens because we check that the format string family of each format attribute is compatible before we check that we're using the associated format parameter. The fix is to move the check down one scope, after we've established that we are checking the right parameter. Tests are updated to include a true negative and a true positive of this situation.
2025-02-25[clang] Fix use-after-scope when diagnosting __attribute__((format_matches))Benjamin Kramer1-4/+5
I don't think this will ever crash, but asan complains about it. SUMMARY: AddressSanitizer: stack-use-after-scope clang/lib/Sema/SemaChecking.cpp:6925:43 in void (anonymous namespace)::CheckFormatHandler::EmitFormatDiagnostic<clang::CharSourceRange>(clang::PartialDiagnostic, clang::SourceLocation, bool, clang::CharSourceRange, llvm::ArrayRef<clang::FixItHint>) While there switch to stable_sort to not give a flipped error message half of the time.
2025-02-24[clang] Implement __attribute__((format_matches)) (#116708)apple-fcloutier1-140/+689
This implements ``__attribute__((format_matches))``, as described in the RFC: https://discourse.llvm.org/t/rfc-format-attribute-attribute-format-like/83076 The ``format`` attribute only allows the compiler to check that a format string matches its arguments. If the format string is passed independently of its arguments, there is no way to have the compiler check it. ``format_matches(flavor, fmtidx, example)`` allows the compiler to check format strings against the ``example`` format string instead of against format arguments. See the changes to AttrDocs.td in this diff for more information. Implementation-wise, this change subclasses CheckPrintfHandler and CheckScanfHandler to allow them to collect specifiers into arrays, and implements comparing that two specifiers are equivalent. `checkFormatStringExpr` gets a new `ReferenceFormatString` argument that is piped down when calling a function with the `format_matches` attribute (and is `nullptr` otherwise); this is the string that the actual format string is compared against. Although this change does not enable -Wformat-nonliteral by default, IMO, all the pieces are now in place such that it could be.
2025-02-19[clang] handle fp options in __builtin_convertvector (#125522)Jakub Ficek1-2/+2
This patch allows using fpfeatures pragmas with __builtin_convertvector: - added TrailingObjects with FPOptionsOverride and methods for handling it to ConvertVectorExpr - added support for codegen, node dumping, and serialization of fpfeatures contained in ConvertVectorExpr
2025-02-15[HLSL] Implement HLSL intialization list support (#123141)Chris B1-2/+6
This PR implements HLSL's initialization list behvaior as specified in the draft language specifcation under [*Decl.Init.Agg*](https://microsoft.github.io/hlsl-specs/specs/hlsl.html#Decl.Init.Agg). This behavior is a bit unusual for C/C++ because intermediate braces in initializer lists are ignored and a whole array of additional conversions occur unintuitively to how initializaiton works in C. The implementaiton in this PR generates a valid C/C++ initialization list AST for the HLSL initializer so that there are no changes required to Clang's CodeGen to support this. This design will also allow us to use Clang's rewrite to convert HLSL initializers to valid C/C++ initializers that are equivalent. It does have the downside that it will generate often redundant accesses during codegen. The IR optimizer is extremely good at eliminating those so this will have no impact on the final executable performance. There is some opportunity for optimizing the initializer list generation that we could consider in subsequent commits. One notable opportunity would be to identify aggregate objects that occur in the same place in both initializers and do not require converison, those aggregates could be initialized as aggregates rather than fully scalarized. Closes #56067 --------- Co-authored-by: Finn Plummer <50529406+inbelic@users.noreply.github.com> Co-authored-by: Helena Kotas <hekotas@microsoft.com> Co-authored-by: Justin Bogner <mail@justinbogner.com>
2025-02-04[StrTable] Teach main builtin TableGen to use direct enums, strings, and infoChandler Carruth1-1/+0
This moves the main builtins and several targets to use nice generated string tables and info structures rather than X-macros. Even without obvious prefixes factored out, the resulting tables are significantly smaller and much cheaper to compile with out all the X-macro overhead. This leaves the X-macros in place for atomic builtins which have a wide range of uses that don't seem reasonable to fold into TableGen. As future work, these should move to their own file (whether as X-macros or just generated patterns) so the AST headers don't have to include all the data for other builtins.
2025-02-04[StrTable] Switch Clang builtins to use string tablesChandler Carruth1-7/+9
This both reapplies #118734, the initial attempt at this, and updates it significantly. First, it uses the newly added `StringTable` abstraction for string tables, and simplifies the construction to build the string table and info arrays separately. This should reduce any `constexpr` compile time memory or CPU cost of the original PR while significantly improving the APIs throughout. It also restructures the builtins to support sharding across several independent tables. This accomplishes two improvements from the original PR: 1) It improves the APIs used significantly. 2) When builtins are defined from different sources (like SVE vs MVE in AArch64), this allows each of them to build their own string table independently rather than having to merge the string tables and info structures. 3) It allows each shard to factor out a common prefix, often cutting the size of the strings needed for the builtins by a factor two. The second point is important both to allow different mechanisms of construction (for example a `.def` file and a tablegen'ed `.inc` file, or different tablegen'ed `.inc files), it also simply reduces the sizes of these tables which is valuable given how large they are in some cases. The third builds on that size reduction. Initially, we use this new sharding rather than merging tables in AArch64, LoongArch, RISCV, and X86. Mostly this helps ensure the system works, as without further changes these still push scaling limits. Subsequent commits will more deeply leverage the new structure, including using the prefix capabilities which cannot be easily factored out here and requires deep changes to the targets.
2025-01-29[clang] Restrict the use of scalar types in vector builtins (#119423)Fraser Cormack1-33/+73
This commit restricts the use of scalar types in vector math builtins, particularly the `__builtin_elementwise_*` builtins. Previously, small scalar integer types would be promoted to `int`, as per the usual conversions. This would silently do the wrong thing for certain operations, such as `add_sat`, `popcount`, `bitreverse`, and others. Similarly, since unsigned integer types were promoted to `int`, something like `add_sat(unsigned char, unsigned char)` would perform a *signed* operation. With this patch, promotable scalar integer types are not promoted to int, and are kept intact. If any of the types differ in the binary and ternary builtins, an error is issued. Similarly an error is issued if builtins are supplied integer types of different signs. Mixing enums of different types in binary/ternary builtins now consistently raises an error in all language modes. This brings the behaviour surrounding scalar types more in line with that of vector types. No change is made to vector types, which are both not promoted and whose element types must match. Fixes #84047. RFC: https://discourse.llvm.org/t/rfc-change-behaviour-of-elementwise-builtins-on-scalar-integer-types/83725
2025-01-22[Clang] Re-write codegen for atomic_test_and_set and atomic_clear (#121943)Oliver Stannard1-15/+50
Re-write the sema and codegen for the atomic_test_and_set and atomic_clear builtin functions to go via AtomicExpr, like the other atomic builtins do. This simplifies the code, because AtomicExpr already handles things like generating code for to dynamically select the memory ordering, which was duplicated for these builtins. This also fixes a few crash bugs, one when passing an integer to the pointer argument, and one when using an array. This also adds diagnostics for the memory orderings which are not valid for atomic_clear according to https://gcc.gnu.org/onlinedocs/gcc/_005f_005fatomic-Builtins.html, which were missing before. Fixes https://github.com/llvm/llvm-project/issues/111293. This is a re-land of #120449, modified to allow any non-const pointer type for the first argument.
2025-01-20[Clang] Fix warning for non std functions with name `infinity` (#123417)Amr Hesham1-15/+32
Fix reporting diagnostic for non std functions that has the name `infinity` Fixes: #123231