3435 Commits

Author SHA1 Message Date
Steven Wu
f9b69a378c Revert "[CMake] Fold export_executable_symbols_* into function args. (#101741)"
This reverts commit 5c56b46a32a8856a022a54291bc9294068f7ddbd. This break
lld build when using GENERATE_DRIVER.
2024-08-06 06:08:16 -07:00
Steven Wu
5c56b46a32
[CMake] Fold export_executable_symbols_* into function args. (#101741)
`LLVM_ENABLE_EXPORTED_SYMBOLS_IN_EXECUTABLES` is not completely
compatible with `export_executable_symbols` as the later will be ignored
if the previous is set to NO.

 Fix the issue by passing if symbols need to be exported to
`llvm_add_exectuable` so the link flag can be determined directly
without calling `export_executable_symbols_*` later.
2024-08-05 19:08:27 -07:00
Nathan James
154d00d5d0
Extend support for specifying languages and version in add_new_check.py (#100129)
- Allow specifying a language standard when adding a new check
- Simplify the language standards(and or-later) handlnig in
check_clang_tidy
2024-07-27 14:13:21 +01:00
Nathan James
ed1c67b129
Add a description parameter to the add_new_check script (#100111)
Adds a description parameter that automatically fills in the Release
notes and first line of the checks documentation. If omitted the usually
FIXME markers are left in their place.
2024-07-26 08:16:08 +01:00
Piotr Zegar
a27f816fe5
[clang-tidy] Fix crash in C language in readability-non-const-parameter (#100461)
Fix crash that happen when redeclaration got
different number of parameters than definition.

Fixes #100340
2024-07-25 17:26:01 +02:00
Nathan James
0762db6533
[clang-tidy] Fix crash in modernize-use-ranges (#100427)
Crash seems to be caused by the check function not handling inline
namespaces correctly for some instances. Changed how the Replacer is got
from the MatchResult now which should alleviate any potential issues

Fixes #100406
2024-07-25 17:25:37 +02:00
Clement Courbet
dd23b34789
[clang-tidy][performance-unnecessary-value-param] Make handleMoveFix virtual (#99867)
... so that downstream checks can override behaviour to do additional
processing.

Refactor the rest of the logic to `handleConstRefFix` (which is also
`virtual`).

This is otherwise and NFC.

This is similar to https://github.com/llvm/llvm-project/pull/73921 but
for `performance-unnecessary-value-param`.
2024-07-23 11:32:26 +02:00
Thomas Schenker
26c99c4217 [clang-tidy] fix misc-const-correctness to work with function-try-blocks (#99925)
Make the clang-tidy check misc-const-correctness work with
function-try-blocks.

Fixes #99860.
2024-07-23 07:38:49 +00:00
Piotr Zegar
f0fad9f3e0
Revert "[clang-tidy] fix misc-const-correctness to work with function-try-blocks" (#100069)
Reverts llvm/llvm-project#99925
2024-07-23 08:46:40 +02:00
Thomas Schenker
cd9e42cb0f
[clang-tidy] fix misc-const-correctness to work with function-try-blocks (#99925)
Make the clang-tidy check misc-const-correctness work with
function-try-blocks.

Fixes #99860.
2024-07-23 08:17:39 +02:00
Piotr Zegar
d48d4805f7 [clang-tidy][NFC] Fix tiny bug in areStatementsIdentical
Function areStatementsIdentical had an early exit
when classes of stmt does not match. That if were
added to speed up checking and do not calculate
hash id of both objects if they are not the same
type. Due to some bug, wrong pointer were used
and this resulted with comparing self to self.

This patch fixes this issue.
2024-07-22 20:46:48 +00:00
Piotr Zegar
04d5003f59 [clang-tidy][DOC] Update check documentation
Fix issues in list.rst, addapt add_new_check.py to new
format of that file, and run gen-static-analyzer-docs.py
to generate missing documentation for clang-analyzer.
2024-07-22 19:31:00 +00:00
Hana Dusíková
52dd4dbb1a
[clang-tidy] bugprone-exception-escape didn't detech catching of an exception with pointer type by void * exception handler (#99773)
As in title, code which checks eligibility of exceptions with pointer
types to be handled by exception handler of type `void *` disallowed
this case. It was working like this:

```c++
if (isStandardPointerConvertible(ExceptionCanTy, HandlerCanTy) &&
          isUnambiguousPublicBaseClass(
              ExceptionCanTy->getTypePtr()->getPointeeType().getTypePtr(),
              HandlerCanTy->getTypePtr()->getPointeeType().getTypePtr())) {
```

but in `isUnambiguousPublicBaseClass` there was code which looked for
definitions:

```c++
bool isUnambiguousPublicBaseClass(const Type *DerivedType,
                                  const Type *BaseType) {
  const auto *DerivedClass =
      DerivedType->getCanonicalTypeUnqualified()->getAsCXXRecordDecl();
  const auto *BaseClass =
      BaseType->getCanonicalTypeUnqualified()->getAsCXXRecordDecl();
  if (!DerivedClass || !BaseClass)
    return false;
```

This code disallowed usage of `void *` type which was already correctly
detected in `isStandardPointerConvertible`.

AFAIK this seems like misinterpretation of specification:

> 14.4 Handling an exception
> a standard [pointer conversion](https://eel.is/c++draft/conv.ptr) not
involving conversions to pointers to private or protected or ambiguous
classes
(https://eel.is/c++draft/except.handle#3.3.1)

and 

> 7.3.12 Pointer conversions
> ... If B is an inaccessible
([[class.access]](https://eel.is/c++draft/class.access)) or ambiguous
([[class.member.lookup]](https://eel.is/c++draft/class.member.lookup))
base class of D, a program that necessitates this conversion is
ill-formed[.](https://eel.is/c++draft/conv.ptr#3.sentence-2) ...
(https://eel.is/c++draft/conv.ptr#3)

14.4 is carving out private, protected, and ambiguous base classes, but
they are already carved out in 7.3.12 and implemented in
`isStandardPointerConvertible`

---------

Co-authored-by: Piotr Zegar <me@piotrzegar.pl>
2024-07-22 20:49:25 +02:00
matthew-f
9d76231fcd
[clang-tidy] Ensure functions are anchored in the global namespace (for cert-err-33) (#99380)
The regular expressions match functions that aren't anchored in the
global namespace. For example `::remove` matches any object with a
`removeXyz` method. This change is to remove these false positives
2024-07-22 20:26:54 +02:00
Nicolas van Kempen
315561c867
[run-clang-tidy.py] Refactor, add progress indicator, add type hints (#89490)
[There is
work](https://discourse.llvm.org/t/rfc-upgrading-llvms-minimum-required-python-version/67571)
to make Python 3.8 the minimum Python version for LLVM.

I edited this script because I wanted some indicator of progress while
going through files.
It now outputs `[XX/YYY]` with the number of processed and total files
after each completion.

The current version of this script is compatible downto Python 3.6 (this
is PyYAML's minimum version).
It would probably work with older Python 3 versions with an older PyYAML
or when YAML is disabled.

With the updates here, it is compatible downto Python 3.7. Python 3.7
was released June 2018.

https://github.com/llvm/llvm-project/pull/89302 is also touching this
file, I don't mind rebasing on top of that work if needed.

### Summary

 -  Add type annotations.
 -  Replace `threading` + `queue` with `asyncio`.
- **Add indicator of processed files over total files**. This is what I
set out to do initially.
- Only print the filename after completion, not the entire Clang-Tidy
invocation command. I find this neater but the behavior can easily be
restored.
2024-07-22 20:23:49 +02:00
Piotr Zegar
507c18b445 [clang-tidy] Few tiny fixes after #99084
Update documentation, and correct configuration
2024-07-18 18:19:37 +00:00
matthew-f
c736ca85c3
[clang-tidy] Ensure functions are anchored in the global namespace (#99084)
The regular expressions match functions that aren't anchored in the
global namespace. For example `::connect` matches `QObject::connect`
This change is to remove these false positives
2024-07-17 19:05:30 +02:00
Mike Crowe
666d224248
[clang-tidy] Fix modernize-use-std-print/format for fmt (#99021)
When fixing #92896 in 0e62d5cf55479981da5e05e406bbca4afb3cdc4f (#94104)
I failed to spot that I'd broken converting from fmt::printf,
fmt::fprintf and fmt::sprintf in these checks since the format parameter
of those functions is not a simple character pointer.

The first part of the previous fix to avoid the assert and instead
produce an error message was sufficient. It was only the second part
that required the format parameter of the called function to be a simple
character pointer that was problematic. Let's remove that second part
and add the now-expected error messages to the lit tests along with
fixing the prototype for the fmt functions to more accurately reflect
the ones used by the fmt library so they are actually useful.

Fixes #92896
2024-07-17 17:45:47 +02:00
Nathan James
77b2c68167
[clang-tidy] Add support for std::rotate(_copy) and inplace_merge to modernize-use-ranges (#99057)
These algorithms take 3 iterators for the range and we are only
interested in the first and last iterator argument. The ranges versions
of these take a range and an iterator(defined to be inside the range) so
the transformation is pretty similar `algo(I.begin, other, I.end,...)`
-> `ranges::algo(I, other,...)`
2024-07-17 16:50:24 +02:00
Chris Warner
f964e8a3f9
[clang-tidy] bugprone-implicit-widening ignores const exprs that fit (#98352)
Add an option to the
`bugprone-implicit-widening-of-multiplication-result` clang-tidy checker
to suppress warnings when the expression is made up of all compile-time
constants (literals, `constexpr` values or results, etc.) and the result
of the multiplication is guaranteed to fit in both the source and
destination types.

This currently only works for signed integer types:

* For unsigned integers, the well-defined rollover behavior on overflow
prevents the checker from detecting that the expression does not
actually fit in the source expr type, and would produce false negatives.
I have a somewhat-hacky stab at addressing this I'd like to submit as a
follow-on PR
* For floating-point types, there's probably a little additional work to
be done to `Expr` to calculate the result at compile time

Even still, this seems like a helpful addition just for signed types,
and additional types can be added.
2024-07-15 21:36:00 +02:00
Vitaly Goldshteyn
8e42e0d28a
[clang-tidy] Allow unnecessary-value-param to match templated functions including lambdas with auto. (#97767)
Clang-Tidy unnecessary-value-param value param will be triggered for
templated functions if at least one instantiontion with expensive to
copy type is present in translation unit.

It is relatively common mistake to write lambda functions with auto
arguments for expensive to copy types.
2024-07-15 21:26:39 +02:00
Nathan James
87ca6386f9
[clang-tidy] Allow specifying pipe syntax for use-ranges checks (#98696)
Add `UseReversePipe` option to (boost|modernize)-use-ranges checks. This
controls whether to create a reverse view using function syntax
(`reverse(Range)`) or pipe syntax (`Range | reverse`)
2024-07-15 21:22:15 +02:00
Krystian Stasiowski
e6ec7c8f74
[Clang][AST] Move NamespaceDecl bits to DeclContext (#98567)
Currently, `NamespaceDecl` has a member `AnonOrFirstNamespaceAndFlags`
which stores a few pieces of data:
- a bit indicating whether the namespace was declared `inline`, and
- a bit indicating whether the namespace was declared as a
_nested-namespace-definition_, and
- a pointer a `NamespaceDecl` that either stores:
- a pointer to the first declaration of that namespace if the
declaration is no the first declaration, or
- a pointer to the unnamed namespace that inhabits the namespace
otherwise.

`Redeclarable` already stores a pointer to the first declaration of an
entity, so it's unnecessary to store this in `NamespaceDecl`.
`DeclContext` has 8 bytes in which various bitfields can be stored for a
declaration, so it's not necessary to store these in `NamespaceDecl`
either. We only need to store a pointer to the unnamed namespace that
inhabits the first declaration of a namespace. This patch moves the two
bits currently stored in `NamespaceDecl` to `DeclContext`, and only
stores a pointer to the unnamed namespace that inhabits a namespace in
the first declaration of that namespace. Since `getOriginalNamespace`
always returns the same `NamespaceDecl` as `getFirstDecl`, this function
is removed to avoid confusion.
2024-07-15 13:57:56 -04:00
Piotr Zegar
b9852ff5fc
[clang-tidy] Ignore requires expr in bugprone-assignment-in-if-condition (#98079)
Ignore assignments in RequiresExpr, to avoid false positives.

Fixes #97972
2024-07-12 19:58:45 +02:00
Paul Kirth
a074f88695
[libc] Update libc namespace clang-tidy checks (#98424)
This patch updates the clang-tidy checks for llvm-libc to ensure that
the namespace macro used to declare the libc namespace is updated from
LIBC_NAMESPACE to LIBC_NAMESPACE_DECL which by default has hidden
visibility.

Co-authored-by: Prabhu Rajesakeran <prabhukr@google.com>
2024-07-11 13:36:07 -07:00
Kefu Chai
77ec20c2fc
[clang-tidy] let UseAfterMoveFinder::find() return an optional<UseAfterMove> (#98100)
before this change, we use an output parameter so
`UseAfterMoveFinder::find()` can return the found `UseAfterMove`, and
addition to it, `UseAfterMoveFinder::find()` return a bool, so we can
tell if a use-after-free is identified. this arrangement could be
confusing when one needs to understand when the each member variable of
the returned `UseAfterMove` instance is initialized.

in this change, we return an `std::optional<UseAfterMove>` instead of a
bool, so that it's more obvious on when/where the returned
`UseAfterMove` is initialized.

this change is a cleanup. so it does not change the behavior of this
check.

Signed-off-by: Kefu Chai <kefu.chai@scylladb.com>
2024-07-10 18:19:42 +02:00
Carlos Galvez
29896db09c
[clang-tidy] Do not warn on const variables in misc-use-internal-linkage (#97969)
Since in C++ they already have implicit internal linkage.

Fixes #97947
2024-07-09 12:20:44 +02:00
Nathan James
1038db6f02
[clang-tidy] Add checks to convert std library iterator algorithms into c++20 or boost ranges (#97764)
Added modernize-use-ranges
Added boost-use-ranges
2024-07-08 20:40:52 +02:00
Kefu Chai
915372a8db
[clang-tidy] In C++17, callee is guaranteed to be sequenced before arguments. (#93623)
This eliminates false positives in bugprone-use-after-move where a
variable
is used in the callee and moved from in the arguments.

We introduce one special case: If the callee is a MemberExpr with a
DeclRefExpr as its base, we consider it to be sequenced after the
arguments. This is because the variable referenced in the base will only
actually be accessed when the call happens, i.e. once all of the
arguments have been evaluated. This has no basis in the C++ standard,
but it reflects actual behavior that is relevant to a use-after-move
scenario:
```c++
a.bar(consumeA(std::move(a));
```
In this example, we end up accessing a after it has been moved from,
even though nominally the callee a.bar is evaluated before the argument
consumeA(std::move(a)).

Treating this scenario correctly has required rewriting the logic in
bugprone-use-after-move that governs whether the use happens in a later
loop iteration than the move. This was previously based on an unsound
heuristic (does the use come lexically before the move?); we now use a
more rigourous criterion based on reachability in the CFG.

Fixes #57758
Fixes #59612

Co-authored-by: martinboehme <mboehme@google.com>
2024-07-08 18:44:22 +02:00
Discookie
f329e3ed90
[clang-tidy] Add bugprone-pointer-arithmetic-on-polymorphic-object check (#91951)
Finds pointer arithmetic on classes that declare a virtual function.

This check corresponds to the SEI Cert rule [CTR56-CPP: Do not use
pointer arithmetic on polymorphic
objects](https://wiki.sei.cmu.edu/confluence/display/cplusplus/CTR56-CPP.+Do+not+use+pointer+arithmetic+on+polymorphic+objects).

```cpp
struct Base {
  virtual void ~Base();
};

struct Derived : public Base {};

void foo(Base *b) {
  b += 1; // passing `Derived` to `foo()` results in UB
}
```

[Results on open-source
projects](https://codechecker-demo.eastus.cloudapp.azure.com/Default/runs?run=Discookie-ctr56-with-classnames).
Most of the Qtbase reports are from having a `virtual override`
declaration, and the LLVM reports are true positives, as far as I can
tell.
2024-07-04 13:44:31 +00:00
Donát Nagy
fdcfb27746
[clang-tidy] Clarify diagnostics of bugprone-sizeof-expression (#95550)
… because they were strangely worded and in a few cases outright
incorrect.
2024-07-02 10:27:45 +02:00
Pascal Jungblut
7c50187b7d
[clang-tidy] Option to ignore anonymous namespaces in avoid-non-const-global-variables (#93827)
Add an option to ignore warnings for cppcoreguidelines
avoid-non-const-global-variables.

Understandably, the core guidelines discourage non const global
variables, even at the TU level (see
https://github.com/isocpp/CppCoreGuidelines/issues/2195). However,
having a small TU with an interface that uses a non const variable from
an anonymous namespace can be a valid choice.

This adds an option that disables the warning just for anonymous
namespaces, i.e. at the file level. The default is still to show a
warning, just as before.
2024-07-01 21:12:42 +02:00
Congcong Cai
e697943233
[clang-tidy] improve messages when auto-fix does not work (#96917)
Fixes: #93157
2024-06-28 21:35:05 +08:00
Congcong Cai
4558e45e7e
[clang-tidy] add option to avoid "no checks enabled" error (#96122)
When clang-tidy get an empty checks, it will throw "no checks enabled"
error and exit with non-zero return value.
It make clang-tidy's wrapper program confused when in big project some
files don't want to be checked and use `-checks=-*` to disable all
checks.

---------

Co-authored-by: Danny Mösch <danny.moesch@icloud.com>
2024-06-27 07:27:58 +08:00
Congcong Cai
019f525716
[clang-tidy] add fixhint for misc-use-internal-linkage (#96203) 2024-06-26 22:30:15 +08:00
Congcong Cai
6b29965fd9
[clang-tidy] align all help message in run-clang-tidy (#96199) 2024-06-26 08:05:00 +08:00
Clement Courbet
8348d720ef
[clang-tidy] Fix assert in performance-unnecessary-copy-init. (#96506)
`GetDirectCallee` can be null.

Fixes #96498.
2024-06-25 07:53:44 +02:00
Nikita Popov
48ef912e2b [VFS] Avoid <stack> include (NFC)
Directly use a vector instead of wrapping it in a stack, like we
do in most places.
2024-06-21 15:17:41 +02:00
Congcong Cai
dcbe0d43b5
[clang-tidy] fix false negatives for performance-inefficient-vector-operation (#95667)
Fixes: #95596
Avoid false negatives caused by different variable definition type and
variable initial value type in loop initialization expression.
2024-06-16 12:01:50 +08:00
Congcong Cai
a78c104a23
[clang-tidy]fix false positives of the result of std::move() is used as rvalue for performance-move-const-arg (#95633)
Fixes: #86404

---------

Co-authored-by: Danny Mösch <danny.moesch@icloud.com>
2024-06-15 21:06:30 +08:00
Congcong Cai
3d25e5ae99
[clang-tidy] avoid false positive when overload for bugprone-return-const-ref-from-parameter (#95434)
Fixes: #90274
2024-06-15 06:21:41 +08:00
Congcong Cai
3f9e2e179a [NFC][clang-tidy] fix typo in readability-else-after-return 2024-06-13 18:24:12 +08:00
Congcong Cai
b06da39cae
[clang-tidy] ignoring macro with hash preprocessing token in cppcoreguidelines-macro-usage (#95265)
`#` and `##` preprocessing tokens cannot be replaced by constexpr
function. It should be ignored in check.
2024-06-13 09:36:33 +08:00
Donát Nagy
546c816a52
[clang-tidy] Improve sizeof(pointer) handling in bugprone-sizeof-expression (#94356)
This commit reimplements the functionality of the Clang Static Analyzer
checker `alpha.core.SizeofPointer` within clang-tidy by adding a new
(off-by-default) option to bugprone-sizeof-expression which activates
reporting all the `sizeof(ptr)` expressions (where ptr is an expression
that produces a pointer).

The main motivation for this change is that `alpha.core.SizeofPointer`
was an AST-based checker, which did not rely on the path sensitive
capabilities of the Static Analyzer, so there was no reason to keep it
in the Static Analyzer instead of the more lightweight clang-tidy.

After this commit I'm planning to create a separate commit that deletes
`alpha.core.SizeofPointer` from Clang Static Analyzer.

It was natural to place this moved logic in bugprone-sizeof-expression,
because that check already provided several heuristics that reported
various especially suspicious classes of `sizeof(ptr)` expressions.

The new mode `WarnOnSizeOfPointer` is off-by-default, so it won't
surprise the existing users; but it can provide a more through coverage
for the vulnerability CWE-467 ("Use of sizeof() on a Pointer Type") than
the existing partial heuristics.

Previously this checker had an exception that the RHS of a
`sizeof(array) / sizeof(array[0])` expression is not reported; I
generalized this to an exception that the check doesn't report
`sizeof(expr[0])` and `sizeof(*expr)`. This idea is taken from the
Static Analyzer checker `alpha.core.SizeofPointer` (which had an
exception for `*expr`), but analysis of open source projects confirmed
that this indeed eliminates lots of unwanted results.

Note that the suppression of `sizeof(expr[0])` and `sizeof(*expr)`
reports also affects the "old" mode `WarnOnSizeOfPointerToAggregate`
which is enabled by default.

This commit also replaces the old message "suspicious usage of
'sizeof(A*)'; pointer to aggregate" with two more concrete messages; but
I feel that this tidy check would deserve a through cleanup of all the
diagnostic messages that it can produce. (I added a FIXME to mark one
outright misleading message.)
2024-06-11 14:16:42 +02:00
Eisuke Kawashima
d63be475e8
[clang-tidy] fix(clang-tools-extra/**.py): fix invalid escape sequences (#94028) 2024-06-10 21:05:40 +02:00
Clement Courbet
415a82c64a
[clang-tidy] doesNotMutateObject: Handle calls to member functions … (#94362)
…and operators that have non-const overloads.

This allows  `unnecessary-copy-initialization` to warn on more cases.

The common case is a class with a a set of const/non-sconst overloads
(e.g. std::vector::operator[]).

```
void F() {
  std::vector<Expensive> v;
  // ...

  const Expensive e = v[i];
}
```
2024-06-10 11:15:11 +02:00
Piotr Zegar
b55fb567e4
[clang-tidy] Improve bugprone-multi-level-implicit-pointer-conversion (#94524)
Ignore implicit pointer conversions that are part of a cast expression

Closes #93959
2024-06-09 11:55:08 +02:00
Piotr Zegar
31b84d459c
[clang-tidy] Extend modernize-use-designated-initializers with new options (#94651)
Add StrictCStandardCompliance and StrictCppStandardCompliance options
that default to true.

Closes #83732
2024-06-09 11:53:59 +02:00
Piotr Zegar
e329bfcb03
[clang-tidy] Ignore implicit functions in readability-implicit-bool-conversion (#94512)
Ignore implicit declarations and defaulted functions. Helps with issues
in generated code like, C++
spaceship operator.

Closes #93409
2024-06-09 11:52:46 +02:00
Piotr Zegar
d211abc625
[clang-tidy] Ignore non-math operators in readability-math-missing-parentheses (#94654)
Do not emit warnings for non-math operators.

Closes #92516
2024-06-09 09:01:41 +02:00