94 changes: 94 additions & 0 deletions clang-tools-extra/clang-tidy/utils/UseRangesCheck.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
//===--- UseRangesCheck.h - clang-tidy --------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_UTILS_USERANGESCHECK_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_UTILS_USERANGESCHECK_H

#include "../ClangTidyCheck.h"
#include "IncludeInserter.h"
#include "clang/AST/Decl.h"
#include "clang/AST/Expr.h"
#include "clang/Basic/Diagnostic.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include <optional>

namespace clang::tidy::utils {

/// Base class for handling converting std iterator algorithms to a range
/// equivalent.
class UseRangesCheck : public ClangTidyCheck {
public:
struct Indexes {
enum Replace { First, Second };
unsigned BeginArg;
unsigned EndArg = BeginArg + 1;
Replace ReplaceArg = First;
};

using Signature = SmallVector<Indexes, 2>;

struct ReverseIteratorDescriptor {
StringRef ReverseAdaptorName;
std::optional<StringRef> ReverseHeader;
ArrayRef<std::pair<StringRef, StringRef>> FreeReverseNames;
};

class Replacer : public llvm::RefCountedBase<Replacer> {
public:
/// Gets the name to replace a function with, return std::nullopt for a
/// replacement where we just call a different overload.
virtual std::optional<std::string>
getReplaceName(const NamedDecl &OriginalName) const = 0;

/// Gets the header needed to access the replaced function
/// Return std::nullopt if no new header is needed.
virtual std::optional<std::string>
getHeaderInclusion(const NamedDecl &OriginalName) const;

/// Gets an array of all the possible overloads for a function with indexes
/// where begin and end arguments are.
virtual ArrayRef<Signature> getReplacementSignatures() const = 0;
virtual ~Replacer() = default;
};

using ReplacerMap = llvm::StringMap<llvm::IntrusiveRefCntPtr<Replacer>>;

UseRangesCheck(StringRef Name, ClangTidyContext *Context);
/// Gets a map of function to replace and methods to create the replacements
virtual ReplacerMap getReplacerMap() const = 0;
/// Create a diagnostic for the CallExpr
/// Override this to support custom diagnostic messages
virtual DiagnosticBuilder createDiag(const CallExpr &Call);

virtual std::optional<ReverseIteratorDescriptor> getReverseDescriptor() const;

/// Gets the fully qualified names of begin and end functions.
/// The functions must take the container as their one and only argument
/// `::std::begin` and `::std::end` are a common example
virtual ArrayRef<std::pair<StringRef, StringRef>>
getFreeBeginEndMethods() const;

void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP,
Preprocessor *ModuleExpanderPP) final;
void registerMatchers(ast_matchers::MatchFinder *Finder) final;
void check(const ast_matchers::MatchFinder::MatchResult &Result) final;
bool isLanguageVersionSupported(const LangOptions &LangOpts) const override;
void storeOptions(ClangTidyOptions::OptionMap &Options) override;
std::optional<TraversalKind> getCheckTraversalKind() const override;

private:
ReplacerMap Replaces;
std::optional<ReverseIteratorDescriptor> ReverseDescriptor;
IncludeInserter Inserter;
};

} // namespace clang::tidy::utils

#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_UTILS_USERANGESCHECK_H
2 changes: 0 additions & 2 deletions clang-tools-extra/clangd/index/remote/server/Server.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -499,8 +499,6 @@ int main(int argc, char *argv[]) {
}

llvm::errs().SetBuffered();
// Don't flush stdout when logging for thread safety.
llvm::errs().tie(nullptr);
auto Logger = makeLogger(LogPrefix.getValue(), llvm::errs());
clang::clangd::LoggingSession LoggingSession(*Logger);

Expand Down
2 changes: 1 addition & 1 deletion clang-tools-extra/clangd/support/ThreadsafeFS.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ class VolatileFileSystem : public llvm::vfs::ProxyFileSystem {
llvm::StringRef FileName = llvm::sys::path::filename(Path);
if (FileName.starts_with("preamble-") && FileName.ends_with(".pch"))
return File;
return std::unique_ptr<VolatileFile>(new VolatileFile(std::move(*File)));
return std::make_unique<VolatileFile>(std::move(*File));
}

private:
Expand Down
2 changes: 0 additions & 2 deletions clang-tools-extra/clangd/tool/ClangdMain.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -840,8 +840,6 @@ clangd accepts flags on the commandline, and in the CLANGD_FLAGS environment var
// Use buffered stream to stderr (we still flush each log message). Unbuffered
// stream can cause significant (non-deterministic) latency for the logger.
llvm::errs().SetBuffered();
// Don't flush stdout when logging, this would be both slow and racy!
llvm::errs().tie(nullptr);
StreamLogger Logger(llvm::errs(), LogLevel);
LoggingSession LoggingSession(Logger);
// Write some initial logs before we start doing any real work.
Expand Down
27 changes: 26 additions & 1 deletion clang-tools-extra/docs/ReleaseNotes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -131,12 +131,23 @@ Improvements to clang-tidy
New checks
^^^^^^^^^^

- New :doc:`boost-use-ranges
<clang-tidy/checks/boost/use-ranges>` check.

Detects calls to standard library iterator algorithms that could be replaced
with a Boost ranges version instead.

- New :doc:`bugprone-crtp-constructor-accessibility
<clang-tidy/checks/bugprone/crtp-constructor-accessibility>` check.

Detects error-prone Curiously Recurring Template Pattern usage, when the CRTP
can be constructed outside itself and the derived class.

- New :doc:`bugprone-pointer-arithmetic-on-polymorphic-object
<clang-tidy/checks/bugprone/pointer-arithmetic-on-polymorphic-object>` check.

Finds pointer arithmetic performed on classes that contain a virtual function.

- New :doc:`bugprone-return-const-ref-from-parameter
<clang-tidy/checks/bugprone/return-const-ref-from-parameter>` check.

Expand Down Expand Up @@ -169,6 +180,12 @@ New checks
Finds initializer lists for aggregate types that could be
written as designated initializers instead.

- New :doc:`modernize-use-ranges
<clang-tidy/checks/modernize/use-ranges>` check.

Detects calls to standard library iterator algorithms that could be replaced
with a ranges version instead.

- New :doc:`modernize-use-std-format
<clang-tidy/checks/modernize/use-std-format>` check.

Expand Down Expand Up @@ -199,6 +216,11 @@ New checks
New check aliases
^^^^^^^^^^^^^^^^^

- New alias :doc:`cert-ctr56-cpp <clang-tidy/checks/cert/ctr56-cpp>` to
:doc:`bugprone-pointer-arithmetic-on-polymorphic-object
<clang-tidy/checks/bugprone/pointer-arithmetic-on-polymorphic-object>`
was added.

- New alias :doc:`cert-int09-c <clang-tidy/checks/cert/int09-c>` to
:doc:`readability-enum-initial-value <clang-tidy/checks/readability/enum-initial-value>`
was added.
Expand Down Expand Up @@ -267,7 +289,10 @@ Changes in existing checks

- Improved :doc:`bugprone-use-after-move
<clang-tidy/checks/bugprone/use-after-move>` check to also handle
calls to ``std::forward``.
calls to ``std::forward``. Fixed sequencing of designated initializers. Fixed
sequencing of callees: In C++17 and later, the callee of a function is guaranteed
to be sequenced before the arguments, so don't warn if the use happens in the
callee and the move happens in one of the arguments.

- Improved :doc:`cppcoreguidelines-avoid-non-const-global-variables
<clang-tidy/checks/cppcoreguidelines/avoid-non-const-global-variables>` check
Expand Down
86 changes: 86 additions & 0 deletions clang-tools-extra/docs/clang-tidy/checks/boost/use-ranges.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
.. title:: clang-tidy - boost-use-ranges

boost-use-ranges
================

Detects calls to standard library iterator algorithms that could be replaced
with a Boost ranges version instead.

Example
-------

.. code-block:: c++

auto Iter1 = std::find(Items.begin(), Items.end(), 0);
auto AreSame = std::equal(Items1.cbegin(), Items1.cend(), std::begin(Items2),
std::end(Items2));


transforms to:

.. code-block:: c++

auto Iter1 = boost::range::find(Items, 0);
auto AreSame = boost::range::equal(Items1, Items2);

Calls to the following std library algorithms are checked:
``includes``,``set_union``,``set_intersection``,``set_difference``,
``set_symmetric_difference``,``unique``,``lower_bound``,``stable_sort``,
``equal_range``,``remove_if``,``sort``,``random_shuffle``,``remove_copy``,
``stable_partition``,``remove_copy_if``,``count``,``copy_backward``,
``reverse_copy``,``adjacent_find``,``remove``,``upper_bound``,``binary_search``,
``replace_copy_if``,``for_each``,``generate``,``count_if``,``min_element``,
``reverse``,``replace_copy``,``fill``,``unique_copy``,``transform``,``copy``,
``replace``,``find``,``replace_if``,``find_if``,``partition``,``max_element``,
``find_end``,``merge``,``partial_sort_copy``,``find_first_of``,``search``,
``lexicographical_compare``,``equal``,``mismatch``,``next_permutation``,
``prev_permutation``,``push_heap``,``pop_heap``,``make_heap``,``sort_heap``,
``copy_if``,``is_permutation``,``is_partitioned``,``find_if_not``,
``partition_copy``,``any_of``,``iota``,``all_of``,``partition_point``,
``is_sorted``,``none_of``,``is_sorted_until``,``reduce``,``accumulate``,
``parital_sum``,``adjacent_difference``.

The check will also look for the following functions from the
``boost::algorithm`` namespace:
``reduce``,``find_backward``,``find_not_backward``,``find_if_backward``,
``find_if_not_backward``,``hex``,``hex_lower``,``unhex``,
``is_partitioned_until``,``is_palindrome``,``copy_if``,``copy_while``,
``copy_until``,``copy_if_while``,``copy_if_until``,``is_permutation``,
``is_partitioned``,``one_of``,``one_of_equal``,``find_if_not``,
``partition_copy``,``any_of``,``any_of_equal``,``iota``,``all_of``,
``all_of_equal``,``partition_point``,``is_sorted_until``,``is_sorted``,
``is_increasing``,``is_decreasing``,``is_strictly_increasing``,
``is_strictly_decreasing``,``none_of``,``none_of_equal``,``clamp_range``,
``apply_permutation``,``apply_reverse_permutation``.

Reverse Iteration
-----------------

If calls are made using reverse iterators on containers, The code will be
fixed using the ``boost::adaptors::reverse`` adaptor.

.. code-block:: c++

auto AreSame = std::equal(Items1.rbegin(), Items1.rend(),
std::crbegin(Items2), std::crend(Items2));

transformst to:

.. code-block:: c++

auto AreSame = std::equal(boost::adaptors::reverse(Items1),
boost::adaptors::reverse(Items2));

Options
-------

.. option:: IncludeStyle

A string specifying which include-style is used, `llvm` or `google`. Default
is `llvm`.

.. option:: IncludeBoostSystem

If `true` (default value) the boost headers are included as system headers
with angle brackets (`#include <boost.hpp>`), otherwise quotes are used
(`#include "boost.hpp"`).
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
.. title:: clang-tidy - bugprone-pointer-arithmetic-on-polymorphic-object

bugprone-pointer-arithmetic-on-polymorphic-object
=================================================

Finds pointer arithmetic performed on classes that contain a virtual function.

Pointer arithmetic on polymorphic objects where the pointer's static type is
different from its dynamic type is undefined behavior, as the two types could
have different sizes, and thus the vtable pointer could point to an
invalid address.

Finding pointers where the static type contains a virtual member function is a
good heuristic, as the pointer is likely to point to a different,
derived object.

Example:

.. code-block:: c++

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

struct Derived : public Base {};

void foo() {
Base *b = new Derived[10];
b += 1;
// warning: pointer arithmetic on class that declares a virtual function can
// result in undefined behavior if the dynamic type differs from the
// pointer type

delete[] static_cast<Derived*>(b);
}

Options
-------

.. option:: IgnoreInheritedVirtualFunctions

When `true`, objects that only inherit a virtual function are not checked.
Classes that do not declare a new virtual function are excluded
by default, as they make up the majority of false positives.
Default: `false`.

.. code-block:: c++

void bar() {
Base *b = new Base[10];
b += 1; // warning, as Base declares a virtual destructor
delete[] b;

Derived *d = new Derived[10]; // Derived overrides the destructor, and
// declares no other virtual functions
d += 1; // warning only if IgnoreVirtualDeclarationsOnly is set to false
delete[] d;
}

References
----------

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>`_.
10 changes: 10 additions & 0 deletions clang-tools-extra/docs/clang-tidy/checks/cert/ctr56-cpp.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
.. title:: clang-tidy - cert-ctr56-cpp
.. meta::
:http-equiv=refresh: 5;URL=../bugprone/pointer-arithmetic-on-polymorphic-object.html

cert-ctr56-cpp
==============

The `cert-ctr56-cpp` check is an alias, please see
:doc:`bugprone-pointer-arithmetic-on-polymorphic-object
<../bugprone/pointer-arithmetic-on-polymorphic-object>` for more information.
3 changes: 3 additions & 0 deletions clang-tools-extra/docs/clang-tidy/checks/list.rst
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ Clang-Tidy Checks
:doc:`android-cloexec-pipe2 <android/cloexec-pipe2>`, "Yes"
:doc:`android-cloexec-socket <android/cloexec-socket>`, "Yes"
:doc:`android-comparison-in-temp-failure-retry <android/comparison-in-temp-failure-retry>`,
:doc:`boost-use-ranges <boost/use-ranges>`, "Yes"
:doc:`boost-use-to-string <boost/use-to-string>`, "Yes"
:doc:`bugprone-argument-comment <bugprone/argument-comment>`, "Yes"
:doc:`bugprone-assert-side-effect <bugprone/assert-side-effect>`,
Expand Down Expand Up @@ -157,6 +158,7 @@ Clang-Tidy Checks
:doc:`bugprone-unused-raii <bugprone/unused-raii>`, "Yes"
:doc:`bugprone-unused-return-value <bugprone/unused-return-value>`,
:doc:`bugprone-use-after-move <bugprone/use-after-move>`,
:doc:`bugprone-pointer-arithmetic-on-polymorphic-object <bugprone/pointer-arithmetic-on-polymorphic-object>`,
:doc:`bugprone-virtual-near-miss <bugprone/virtual-near-miss>`, "Yes"
:doc:`cert-dcl50-cpp <cert/dcl50-cpp>`,
:doc:`cert-dcl58-cpp <cert/dcl58-cpp>`,
Expand Down Expand Up @@ -300,6 +302,7 @@ Clang-Tidy Checks
:doc:`modernize-use-noexcept <modernize/use-noexcept>`, "Yes"
:doc:`modernize-use-nullptr <modernize/use-nullptr>`, "Yes"
:doc:`modernize-use-override <modernize/use-override>`, "Yes"
:doc:`modernize-use-ranges <modernize/use-ranges>`, "Yes"
:doc:`modernize-use-starts-ends-with <modernize/use-starts-ends-with>`, "Yes"
:doc:`modernize-use-std-format <modernize/use-std-format>`, "Yes"
:doc:`modernize-use-std-numbers <modernize/use-std-numbers>`, "Yes"
Expand Down
79 changes: 79 additions & 0 deletions clang-tools-extra/docs/clang-tidy/checks/modernize/use-ranges.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
.. title:: clang-tidy - modernize-use-ranges

modernize-use-ranges
====================

Detects calls to standard library iterator algorithms that could be replaced
with a ranges version instead.

Example
-------

.. code-block:: c++

auto Iter1 = std::find(Items.begin(), Items.end(), 0);
auto AreSame = std::equal(Items1.cbegin(), Items1.cend(),
std::begin(Items2), std::end(Items2));


transforms to:

.. code-block:: c++

auto Iter1 = std::ranges::find(Items, 0);
auto AreSame = std::ranges::equal(Items1, Items2);

Calls to the following std library algorithms are checked:
``::std::all_of``,``::std::any_of``,``::std::none_of``,``::std::for_each``,
``::std::find``,``::std::find_if``,``::std::find_if_not``,
``::std::adjacent_find``,``::std::copy``,``::std::copy_if``,
``::std::copy_backward``,``::std::move``,``::std::move_backward``,
``::std::fill``,``::std::transform``,``::std::replace``,``::std::replace_if``,
``::std::generate``,``::std::remove``,``::std::remove_if``,
``::std::remove_copy``,``::std::remove_copy_if``,``::std::unique``,
``::std::unique_copy``,``::std::sample``,``::std::partition_point``,
``::std::lower_bound``,``::std::upper_bound``,``::std::equal_range``,
``::std::binary_search``,``::std::push_heap``,``::std::pop_heap``,
``::std::make_heap``,``::std::sort_heap``,``::std::next_permutation``,
``::std::prev_permutation``,``::std::iota``,``::std::reverse``,
``::std::reverse_copy``,``::std::shift_left``,``::std::shift_right``,
``::std::is_partitioned``,``::std::partition``,``::std::partition_copy``,
``::std::stable_partition``,``::std::sort``,``::std::stable_sort``,
``::std::is_sorted``,``::std::is_sorted_until``,``::std::is_heap``,
``::std::is_heap_until``,``::std::max_element``,``::std::min_element``,
``::std::minmax_element``,``::std::uninitialized_copy``,
``::std::uninitialized_fill``,``::std::uninitialized_move``,
``::std::uninitialized_default_construct``,
``::std::uninitialized_value_construct``,``::std::destroy``,
``::std::partial_sort_copy``,``::std::includes``,
``::std::set_union``,``::std::set_intersection``,``::std::set_difference``,
``::std::set_symmetric_difference``,``::std::merge``,
``::std::lexicographical_compare``,``::std::find_end``,``::std::search``,
``::std::is_permutation``,``::std::equal``,``::std::mismatch``.

Reverse Iteration
-----------------

If calls are made using reverse iterators on containers, The code will be
fixed using the ``std::views::reverse`` adaptor.

.. code-block:: c++

auto AreSame = std::equal(Items1.rbegin(), Items1.rend(),
std::crbegin(Items2), std::crend(Items2));

transformst to:

.. code-block:: c++

auto AreSame = std::equal(std::views::reverse(Items1),
std::views::reverse(Items2));

Options
-------

.. option:: IncludeStyle

A string specifying which include-style is used, `llvm` or `google`. Default
is `llvm`.

194 changes: 194 additions & 0 deletions clang-tools-extra/test/clang-tidy/checkers/boost/use-ranges.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
// RUN: %check_clang_tidy -std=c++14 %s boost-use-ranges %t
// RUN: %check_clang_tidy -std=c++17 %s boost-use-ranges %t -check-suffixes=,CPP17

// CHECK-FIXES: #include <boost/range/algorithm/find.hpp>
// CHECK-FIXES: #include <boost/range/algorithm/reverse.hpp>
// CHECK-FIXES: #include <boost/range/algorithm/set_algorithm.hpp>
// CHECK-FIXES: #include <boost/range/algorithm/equal.hpp>
// CHECK-FIXES: #include <boost/range/algorithm/permutation.hpp>
// CHECK-FIXES: #include <boost/range/algorithm/heap_algorithm.hpp>
// CHECK-FIXES: #include <boost/algorithm/cxx11/copy_if.hpp>
// CHECK-FIXES: #include <boost/algorithm/cxx11/is_sorted.hpp>
// CHECK-FIXES-CPP17: #include <boost/algorithm/cxx17/reduce.hpp>
// CHECK-FIXES: #include <boost/range/adaptor/reversed.hpp>
// CHECK-FIXES: #include <boost/range/numeric.hpp>

namespace std {

template <typename T> class vector {
public:
using iterator = T *;
using const_iterator = const T *;
constexpr const_iterator begin() const;
constexpr const_iterator end() const;
constexpr const_iterator cbegin() const;
constexpr const_iterator cend() const;
constexpr iterator begin();
constexpr iterator end();
};

template <typename Container> constexpr auto begin(const Container &Cont) {
return Cont.begin();
}

template <typename Container> constexpr auto begin(Container &Cont) {
return Cont.begin();
}

template <typename Container> constexpr auto end(const Container &Cont) {
return Cont.end();
}

template <typename Container> constexpr auto end(Container &Cont) {
return Cont.end();
}

template <typename Container> constexpr auto cbegin(const Container &Cont) {
return Cont.cbegin();
}

template <typename Container> constexpr auto cend(const Container &Cont) {
return Cont.cend();
}
// Find
template< class InputIt, class T >
InputIt find(InputIt first, InputIt last, const T& value);

template <typename Iter> void reverse(Iter begin, Iter end);

template <class InputIt1, class InputIt2>
bool includes(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2);

template <class ForwardIt1, class ForwardIt2>
bool is_permutation(ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2,
ForwardIt2 last2);

template <class BidirIt>
bool next_permutation(BidirIt first, BidirIt last);

template <class ForwardIt1, class ForwardIt2>
bool equal(ForwardIt1 first1, ForwardIt1 last1,
ForwardIt2 first2, ForwardIt2 last2);

template <class RandomIt>
void push_heap(RandomIt first, RandomIt last);

template <class InputIt, class OutputIt, class UnaryPred>
OutputIt copy_if(InputIt first, InputIt last, OutputIt d_first, UnaryPred pred);

template <class ForwardIt>
ForwardIt is_sorted_until(ForwardIt first, ForwardIt last);

template <class InputIt>
void reduce(InputIt first, InputIt last);

template <class InputIt, class T>
T reduce(InputIt first, InputIt last, T init);

template <class InputIt, class T, class BinaryOp>
T reduce(InputIt first, InputIt last, T init, BinaryOp op) {
// Need a definition to suppress undefined_internal_type when invoked with lambda
return init;
}

template <class InputIt, class T>
T accumulate(InputIt first, InputIt last, T init);

} // namespace std

namespace boost {
namespace range_adl_barrier {
template <typename T> void *begin(T &);
template <typename T> void *end(T &);
template <typename T> void *const_begin(const T &);
template <typename T> void *const_end(const T &);
} // namespace range_adl_barrier
using namespace range_adl_barrier;

template <typename T> void *rbegin(T &);
template <typename T> void *rend(T &);

template <typename T> void *const_rbegin(T &);
template <typename T> void *const_rend(T &);
namespace algorithm {

template <class InputIterator, class T, class BinaryOperation>
T reduce(InputIterator first, InputIterator last, T init, BinaryOperation bOp) {
return init;
}
} // namespace algorithm
} // namespace boost

bool returnTrue(int val) {
return true;
}

void stdLib() {
std::vector<int> I, J;
std::find(I.begin(), I.end(), 0);
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a boost version of this algorithm
// CHECK-FIXES: boost::range::find(I, 0);

std::reverse(I.cbegin(), I.cend());
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a boost version of this algorithm
// CHECK-FIXES: boost::range::reverse(I);

std::includes(I.begin(), I.end(), std::begin(J), std::end(J));
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a boost version of this algorithm
// CHECK-FIXES: boost::range::includes(I, J);

std::equal(std::cbegin(I), std::cend(I), J.begin(), J.end());
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a boost version of this algorithm
// CHECK-FIXES: boost::range::equal(I, J);

std::next_permutation(I.begin(), I.end());
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a boost version of this algorithm
// CHECK-FIXES: boost::range::next_permutation(I);

std::push_heap(I.begin(), I.end());
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a boost version of this algorithm
// CHECK-FIXES: boost::range::push_heap(I);

std::copy_if(I.begin(), I.end(), J.begin(), &returnTrue);
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a boost version of this algorithm
// CHECK-FIXES: boost::algorithm::copy_if(I, J.begin(), &returnTrue);

std::is_sorted_until(I.begin(), I.end());
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a boost version of this algorithm
// CHECK-FIXES: boost::algorithm::is_sorted_until(I);

std::reduce(I.begin(), I.end());
// CHECK-MESSAGES-CPP17: :[[@LINE-1]]:3: warning: use a boost version of this algorithm
// CHECK-FIXES-CPP17: boost::algorithm::reduce(I);

std::reduce(I.begin(), I.end(), 2);
// CHECK-MESSAGES-CPP17: :[[@LINE-1]]:3: warning: use a boost version of this algorithm
// CHECK-FIXES-CPP17: boost::algorithm::reduce(I, 2);

std::reduce(I.begin(), I.end(), 0, [](int a, int b){ return a + b; });
// CHECK-MESSAGES-CPP17: :[[@LINE-1]]:3: warning: use a boost version of this algorithm
// CHECK-FIXES-CPP17: boost::algorithm::reduce(I, 0, [](int a, int b){ return a + b; });

std::equal(boost::rbegin(I), boost::rend(I), J.begin(), J.end());
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a boost version of this algorithm
// CHECK-FIXES: boost::range::equal(boost::adaptors::reverse(I), J);

std::accumulate(I.begin(), I.end(), 0);
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a boost version of this algorithm
// CHECK-FIXES: boost::accumulate(I, 0);
}

void boostLib() {
std::vector<int> I;
boost::algorithm::reduce(I.begin(), I.end(), 0, [](int a, int b){ return a + b; });
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranged version of this algorithm
// CHECK-FIXES: boost::algorithm::reduce(I, 0, [](int a, int b){ return a + b; });

boost::algorithm::reduce(boost::begin(I), boost::end(I), 1, [](int a, int b){ return a + b; });
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranged version of this algorithm
// CHECK-FIXES: boost::algorithm::reduce(I, 1, [](int a, int b){ return a + b; });

boost::algorithm::reduce(boost::const_begin(I), boost::const_end(I), 2, [](int a, int b){ return a + b; });
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranged version of this algorithm
// CHECK-FIXES: boost::algorithm::reduce(I, 2, [](int a, int b){ return a + b; });
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
// RUN: %check_clang_tidy %s bugprone-pointer-arithmetic-on-polymorphic-object %t --

class Base {
public:
virtual ~Base() {}
};

class Derived : public Base {};

class FinalDerived final : public Base {};

class AbstractBase {
public:
virtual void f() = 0;
virtual ~AbstractBase() {}
};

class AbstractInherited : public AbstractBase {};

class AbstractOverride : public AbstractInherited {
public:
void f() override {}
};

void operators() {
Base *b = new Derived[10];

b += 1;
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: pointer arithmetic on polymorphic object of type 'Base' can result in undefined behavior if the dynamic type differs from the pointer type [bugprone-pointer-arithmetic-on-polymorphic-object]

b = b + 1;
// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: pointer arithmetic on polymorphic object of type 'Base' can result in undefined behavior if the dynamic type differs from the pointer type [bugprone-pointer-arithmetic-on-polymorphic-object]

b++;
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: pointer arithmetic on polymorphic object of type 'Base' can result in undefined behavior if the dynamic type differs from the pointer type [bugprone-pointer-arithmetic-on-polymorphic-object]

--b;
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: pointer arithmetic on polymorphic object of type 'Base' can result in undefined behavior if the dynamic type differs from the pointer type [bugprone-pointer-arithmetic-on-polymorphic-object]

b[1];
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: pointer arithmetic on polymorphic object of type 'Base' can result in undefined behavior if the dynamic type differs from the pointer type [bugprone-pointer-arithmetic-on-polymorphic-object]

delete[] static_cast<Derived*>(b);
}

void subclassWarnings() {
Base *b = new Base[10];

// False positive that's impossible to distinguish without
// path-sensitive analysis, but the code is bug-prone regardless.
b += 1;
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: pointer arithmetic on polymorphic object of type 'Base'

delete[] b;

// Common false positive is a class that overrides all parent functions.
// Is a warning because of the check configuration.
Derived *d = new Derived[10];

d += 1;
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: pointer arithmetic on polymorphic object of type 'Derived'

delete[] d;

// Final classes cannot have a dynamic type.
FinalDerived *fd = new FinalDerived[10];

fd += 1;
// no-warning

delete[] fd;
}

void abstractWarnings() {
// Classes with an abstract member funtion are always matched.
AbstractBase *ab = new AbstractOverride[10];

ab += 1;
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: pointer arithmetic on polymorphic object of type 'AbstractBase'

delete[] static_cast<AbstractOverride*>(ab);

AbstractInherited *ai = new AbstractOverride[10];

ai += 1;
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: pointer arithmetic on polymorphic object of type 'AbstractInherited'

delete[] static_cast<AbstractOverride*>(ai);

// Is a warning because of the check configuration.
AbstractOverride *ao = new AbstractOverride[10];

ao += 1;
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: pointer arithmetic on polymorphic object of type 'AbstractOverride'

delete[] ao;
}

template <typename T>
void templateWarning(T *t) {
// FIXME: Tidy doesn't support template instantiation locations properly.
t += 1;
// no-warning
}

void functionArgument(Base *b) {
b += 1;
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: pointer arithmetic on polymorphic object of type 'Base'

templateWarning(b);
}

using BaseAlias = Base;
using DerivedAlias = Derived;
using FinalDerivedAlias = FinalDerived;

using BasePtr = Base*;
using DerivedPtr = Derived*;
using FinalDerivedPtr = FinalDerived*;

void typeAliases(BaseAlias *b, DerivedAlias *d, FinalDerivedAlias *fd,
BasePtr bp, DerivedPtr dp, FinalDerivedPtr fdp) {
b += 1;
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: pointer arithmetic on polymorphic object of type 'Base'

d += 1;
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: pointer arithmetic on polymorphic object of type 'Derived'

fd += 1;
// no-warning

bp += 1;
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: pointer arithmetic on polymorphic object of type 'Base'

dp += 1;
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: pointer arithmetic on polymorphic object of type 'Derived'

fdp += 1;
// no-warning
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
// RUN: %check_clang_tidy %s bugprone-pointer-arithmetic-on-polymorphic-object %t -- \
// RUN: -config="{CheckOptions: \
// RUN: {bugprone-pointer-arithmetic-on-polymorphic-object.IgnoreInheritedVirtualFunctions: true}}"

class Base {
public:
virtual ~Base() {}
};

class Derived : public Base {};

class FinalDerived final : public Base {};

class AbstractBase {
public:
virtual void f() = 0;
virtual ~AbstractBase() {}
};

class AbstractInherited : public AbstractBase {};

class AbstractOverride : public AbstractInherited {
public:
void f() override {}
};

void operators() {
Base *b = new Derived[10];

b += 1;
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: pointer arithmetic on polymorphic object of type 'Base' can result in undefined behavior if the dynamic type differs from the pointer type [bugprone-pointer-arithmetic-on-polymorphic-object]

b = b + 1;
// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: pointer arithmetic on polymorphic object of type 'Base' can result in undefined behavior if the dynamic type differs from the pointer type [bugprone-pointer-arithmetic-on-polymorphic-object]

b++;
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: pointer arithmetic on polymorphic object of type 'Base' can result in undefined behavior if the dynamic type differs from the pointer type [bugprone-pointer-arithmetic-on-polymorphic-object]

--b;
// CHECK-MESSAGES: :[[@LINE-1]]:5: warning: pointer arithmetic on polymorphic object of type 'Base' can result in undefined behavior if the dynamic type differs from the pointer type [bugprone-pointer-arithmetic-on-polymorphic-object]

b[1];
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: pointer arithmetic on polymorphic object of type 'Base' can result in undefined behavior if the dynamic type differs from the pointer type [bugprone-pointer-arithmetic-on-polymorphic-object]

delete[] static_cast<Derived*>(b);
}

void subclassWarnings() {
Base *b = new Base[10];

// False positive that's impossible to distinguish without
// path-sensitive analysis, but the code is bug-prone regardless.
b += 1;
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: pointer arithmetic on polymorphic object of type 'Base'

delete[] b;

// Common false positive is a class that overrides all parent functions.
Derived *d = new Derived[10];

d += 1;
// no-warning

delete[] d;

// Final classes cannot have a dynamic type.
FinalDerived *fd = new FinalDerived[10];

fd += 1;
// no-warning

delete[] fd;
}

void abstractWarnings() {
// Classes with an abstract member funtion are always matched.
AbstractBase *ab = new AbstractOverride[10];

ab += 1;
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: pointer arithmetic on polymorphic object of type 'AbstractBase'

delete[] static_cast<AbstractOverride*>(ab);

AbstractInherited *ai = new AbstractOverride[10];

ai += 1;
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: pointer arithmetic on polymorphic object of type 'AbstractInherited'

delete[] static_cast<AbstractOverride*>(ai);

// If all abstract member functions are overridden, the class is not matched.
AbstractOverride *ao = new AbstractOverride[10];

ao += 1;
// no-warning

delete[] ao;
}

template <typename T>
void templateWarning(T *t) {
// FIXME: Tidy doesn't support template instantiation locations properly.
t += 1;
// no-warning
}

void functionArgument(Base *b) {
b += 1;
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: pointer arithmetic on polymorphic object of type 'Base'

templateWarning(b);
}

using BaseAlias = Base;
using DerivedAlias = Derived;
using FinalDerivedAlias = FinalDerived;

using BasePtr = Base*;
using DerivedPtr = Derived*;
using FinalDerivedPtr = FinalDerived*;

void typeAliases(BaseAlias *b, DerivedAlias *d, FinalDerivedAlias *fd,
BasePtr bp, DerivedPtr dp, FinalDerivedPtr fdp) {
b += 1;
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: pointer arithmetic on polymorphic object of type 'Base'

d += 1;
// no-warning

fd += 1;
// no-warning

bp += 1;
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: pointer arithmetic on polymorphic object of type 'Base'

dp += 1;
// no-warning

fdp += 1;
// no-warning
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// RUN: %check_clang_tidy -std=c++11 -check-suffixes=,CXX11 %s bugprone-use-after-move %t -- -- -fno-delayed-template-parsing
// RUN: %check_clang_tidy -std=c++17-or-later %s bugprone-use-after-move %t -- -- -fno-delayed-template-parsing

typedef decltype(nullptr) nullptr_t;
Expand Down Expand Up @@ -135,6 +136,7 @@ class A {
A &operator=(A &&);

void foo() const;
void bar(int i) const;
int getInt() const;

operator bool() const;
Expand Down Expand Up @@ -576,6 +578,19 @@ void useAndMoveInLoop() {
std::move(a);
}
}
// Same as above, but the use and the move are in different CFG blocks.
{
A a;
for (int i = 0; i < 10; ++i) {
if (i < 10)
a.foo();
// CHECK-NOTES: [[@LINE-1]]:9: warning: 'a' used after it was moved
// CHECK-NOTES: [[@LINE+3]]:9: note: move occurred here
// CHECK-NOTES: [[@LINE-3]]:9: note: the use happens in a later loop
if (i < 10)
std::move(a);
}
}
// However, this case shouldn't be flagged -- the scope of the declaration of
// 'a' is important.
{
Expand Down Expand Up @@ -1352,6 +1367,40 @@ void ifWhileAndSwitchSequenceInitDeclAndCondition() {
}
}

// In a function call, the expression that determines the callee is sequenced
// before the arguments -- but only in C++17 and later.
namespace CalleeSequencedBeforeArguments {
int consumeA(std::unique_ptr<A> a);
int consumeA(A &&a);

void calleeSequencedBeforeArguments() {
{
std::unique_ptr<A> a;
a->bar(consumeA(std::move(a)));
// CHECK-NOTES-CXX11: [[@LINE-1]]:5: warning: 'a' used after it was moved
// CHECK-NOTES-CXX11: [[@LINE-2]]:21: note: move occurred here
// CHECK-NOTES-CXX11: [[@LINE-3]]:5: note: the use and move are unsequenced
}
{
std::unique_ptr<A> a;
std::unique_ptr<A> getArg(std::unique_ptr<A> a);
getArg(std::move(a))->bar(a->getInt());
// CHECK-NOTES: [[@LINE-1]]:31: warning: 'a' used after it was moved
// CHECK-NOTES: [[@LINE-2]]:12: note: move occurred here
// CHECK-NOTES-CXX11: [[@LINE-3]]:31: note: the use and move are unsequenced
}
{
A a;
// Nominally, the callee `a.bar` is evaluated before the argument
// `consumeA(std::move(a))`, but in effect `a` is only accessed after the
// call to `A::bar()` happens, i.e. after the argument has been evaluted.
a.bar(consumeA(std::move(a)));
// CHECK-NOTES: [[@LINE-1]]:5: warning: 'a' used after it was moved
// CHECK-NOTES: [[@LINE-2]]:11: note: move occurred here
}
}
} // namespace CalleeSequencedBeforeArguments

// Some statements in templates (e.g. null, break and continue statements) may
// be shared between the uninstantiated and instantiated versions of the
// template and therefore have multiple parents. Make sure the sequencing code
Expand Down Expand Up @@ -1469,7 +1518,6 @@ class CtorInitOrder {
// CHECK-NOTES: [[@LINE-1]]:11: warning: 'val' used after it was moved
s{std::move(val)} {} // wrong order
// CHECK-NOTES: [[@LINE-1]]:9: note: move occurred here
// CHECK-NOTES: [[@LINE-4]]:11: note: the use happens in a later loop iteration than the move

private:
bool a;
Expand Down
208 changes: 208 additions & 0 deletions clang-tools-extra/test/clang-tidy/checkers/modernize/use-ranges.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
// RUN: %check_clang_tidy -std=c++20 %s modernize-use-ranges %t
// RUN: %check_clang_tidy -std=c++23 %s modernize-use-ranges %t -check-suffixes=,CPP23

// CHECK-FIXES: #include <algorithm>
// CHECK-FIXES-CPP23: #include <numeric>
// CHECK-FIXES: #include <ranges>

namespace std {

template <typename T> class vector {
public:
using iterator = T *;
using const_iterator = const T *;
using reverse_iterator = T*;
using reverse_const_iterator = const T*;

constexpr const_iterator begin() const;
constexpr const_iterator end() const;
constexpr const_iterator cbegin() const;
constexpr const_iterator cend() const;
constexpr iterator begin();
constexpr iterator end();
constexpr reverse_const_iterator rbegin() const;
constexpr reverse_const_iterator rend() const;
constexpr reverse_const_iterator crbegin() const;
constexpr reverse_const_iterator crend() const;
constexpr reverse_iterator rbegin();
constexpr reverse_iterator rend();
};

template <typename Container> constexpr auto begin(const Container &Cont) {
return Cont.begin();
}

template <typename Container> constexpr auto begin(Container &Cont) {
return Cont.begin();
}

template <typename Container> constexpr auto end(const Container &Cont) {
return Cont.end();
}

template <typename Container> constexpr auto end(Container &Cont) {
return Cont.end();
}

template <typename Container> constexpr auto cbegin(const Container &Cont) {
return Cont.cbegin();
}

template <typename Container> constexpr auto cend(const Container &Cont) {
return Cont.cend();
}

template <typename Container> constexpr auto rbegin(const Container &Cont) {
return Cont.rbegin();
}

template <typename Container> constexpr auto rbegin(Container &Cont) {
return Cont.rbegin();
}

template <typename Container> constexpr auto rend(const Container &Cont) {
return Cont.rend();
}

template <typename Container> constexpr auto rend(Container &Cont) {
return Cont.rend();
}

template <typename Container> constexpr auto crbegin(const Container &Cont) {
return Cont.crbegin();
}

template <typename Container> constexpr auto crend(const Container &Cont) {
return Cont.crend();
}
// Find
template< class InputIt, class T >
InputIt find( InputIt first, InputIt last, const T& value );

// Reverse
template <typename Iter> void reverse(Iter begin, Iter end);

// Includes
template <class InputIt1, class InputIt2>
bool includes(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2);

// IsPermutation
template <class ForwardIt1, class ForwardIt2>
bool is_permutation(ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2);
template <class ForwardIt1, class ForwardIt2>
bool is_permutation(ForwardIt1 first1, ForwardIt1 last1, ForwardIt2 first2,
ForwardIt2 last2);

// Equal
template <class InputIt1, class InputIt2>
bool equal(InputIt1 first1, InputIt1 last1, InputIt2 first2);

template <class InputIt1, class InputIt2>
bool equal(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2);

template <class InputIt1, class InputIt2, class BinaryPred>
bool equal(InputIt1 first1, InputIt1 last1,
InputIt2 first2, InputIt2 last2, BinaryPred p) {
// Need a definition to suppress undefined_internal_type when invoked with lambda
return true;
}

template <class ForwardIt, class T>
void iota(ForwardIt first, ForwardIt last, T value);

} // namespace std

void Positives() {
std::vector<int> I, J;
std::find(I.begin(), I.end(), 0);
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm
// CHECK-FIXES: std::ranges::find(I, 0);

std::find(I.cbegin(), I.cend(), 1);
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm
// CHECK-FIXES: std::ranges::find(I, 1);

std::find(std::begin(I), std::end(I), 2);
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm
// CHECK-FIXES: std::ranges::find(I, 2);

std::find(std::cbegin(I), std::cend(I), 3);
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm
// CHECK-FIXES: std::ranges::find(I, 3);

std::find(std::cbegin(I), I.cend(), 4);
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm
// CHECK-FIXES: std::ranges::find(I, 4);

std::reverse(I.begin(), I.end());
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm
// CHECK-FIXES: std::ranges::reverse(I);

std::includes(I.begin(), I.end(), I.begin(), I.end());
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm
// CHECK-FIXES: std::ranges::includes(I, I);

std::includes(I.begin(), I.end(), J.begin(), J.end());
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm
// CHECK-FIXES: std::ranges::includes(I, J);

std::is_permutation(I.begin(), I.end(), J.begin(), J.end());
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm
// CHECK-FIXES: std::ranges::is_permutation(I, J);

std::equal(I.begin(), I.end(), J.begin(), J.end());
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm
// CHECK-FIXES: std::ranges::equal(I, J);

std::equal(I.begin(), I.end(), J.begin(), J.end(), [](int a, int b){ return a == b; });
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm
// CHECK-FIXES: std::ranges::equal(I, J, [](int a, int b){ return a == b; });

std::iota(I.begin(), I.end(), 0);
// CHECK-MESSAGES-CPP23: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm
// CHECK-FIXES-CPP23: std::ranges::iota(I, 0);

using std::find;
namespace my_std = std;

// Potentially these could be updated to better qualify the replaced function name
find(I.begin(), I.end(), 5);
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm
// CHECK-FIXES: std::ranges::find(I, 5);

my_std::find(I.begin(), I.end(), 6);
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm
// CHECK-FIXES: std::ranges::find(I, 6);
}

void Reverse(){
std::vector<int> I, J;
std::find(I.rbegin(), I.rend(), 0);
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm
// CHECK-FIXES: std::ranges::find(std::views::reverse(I), 0);

std::equal(std::rbegin(I), std::rend(I), J.begin(), J.end());
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm
// CHECK-FIXES: std::ranges::equal(std::views::reverse(I), J);

std::equal(I.begin(), I.end(), std::crbegin(J), std::crend(J));
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: use a ranges version of this algorithm
// CHECK-FIXES: std::ranges::equal(I, std::views::reverse(J));
}

void Negatives() {
std::vector<int> I, J;
std::find(I.begin(), J.end(), 0);
std::find(I.begin(), I.begin(), 0);
std::find(I.end(), I.begin(), 0);


// Need both ranges for this one
std::is_permutation(I.begin(), I.end(), J.begin());

// We only have one valid match here and the ranges::equal function needs 2 complete ranges
std::equal(I.begin(), I.end(), J.begin());
std::equal(I.begin(), I.end(), J.end(), J.end());
std::equal(std::rbegin(I), std::rend(I), std::rend(J), std::rbegin(J));
std::equal(I.begin(), J.end(), I.begin(), I.end());
}
2 changes: 1 addition & 1 deletion clang/cmake/caches/Fuchsia-stage2.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ if(WIN32 OR LLVM_WINSYSROOT)
set(RUNTIMES_${target}_CMAKE_MODULE_LINKER_FLAGS ${WINDOWS_LINK_FLAGS} CACHE STRING "")
endif()

foreach(target aarch64-unknown-linux-gnu;armv7-unknown-linux-gnueabihf;i386-unknown-linux-gnu;riscv64-unknown-linux-gnu;x86_64-unknown-linux-gnu)
foreach(target aarch64-linux-gnu;armv7-linux-gnueabihf;i386-linux-gnu;riscv64-linux-gnu;x86_64-linux-gnu)
if(LINUX_${target}_SYSROOT)
# Set the per-target builtins options.
list(APPEND BUILTIN_TARGETS "${target}")
Expand Down
48 changes: 29 additions & 19 deletions clang/docs/ReleaseNotes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,13 @@ ABI Changes in This Version
earlier versions of Clang unless such code is built with the compiler option
`-fms-compatibility-version=19.14` to imitate the MSVC 1914 mangling behavior.

- Fixed Microsoft name mangling for auto non-type template arguments of pointer
to member type for MSVC 1920+. This change resolves incompatibilities with code
compiled by MSVC 1920+ but will introduce incompatibilities with code compiled by
earlier versions of Clang unless such code is built with the compiler option
`-fms-compatibility-version=19.14` to imitate the MSVC 1914 mangling behavior.
(GH#70899).

AST Dumping Potentially Breaking Changes
----------------------------------------

Expand Down Expand Up @@ -147,22 +154,6 @@ Clang Frontend Potentially Breaking Changes
- The ``hasTypeLoc`` AST matcher will no longer match a ``classTemplateSpecializationDecl``;
existing uses should switch to ``templateArgumentLoc`` or ``hasAnyTemplateArgumentLoc`` instead.

- The comment parser now matches comments to declarations even if there is a
preprocessor macro in between the comment and declaration. This change is
intended to improve Clang's support for parsing documentation comments and
to better conform to Doxygen's behavior.

This has the potential to cause ``-Wdocumentation`` warnings, especially in
cases where a function-like macro has a documentation comment and is followed
immediately by a normal function. The function-like macro's documentation
comments will be attributed to the subsequent function and may cause
``-Wdocumentation`` warnings such as mismatched parameter names, or invalid
return documentation comments.

In cases where the ``-Wdocumentation`` warnings are thrown, the suggested fix
is to document the declaration following the macro so that the warnings are
fixed.

Clang Python Bindings Potentially Breaking Changes
--------------------------------------------------
- Renamed ``CursorKind`` variant 272 from ``OMP_TEAMS_DISTRIBUTE_DIRECTIVE``
Expand Down Expand Up @@ -245,9 +236,6 @@ C++20 Feature Support
``<expected>`` from libstdc++ to work correctly with Clang.

- User defined constructors are allowed for copy-list-initialization with CTAD.
The example code for deduction guides for std::map in
(`cppreference <https://en.cppreference.com/w/cpp/container/map/deduction_guides>`_)
will now work.
(#GH62925).

C++23 Feature Support
Expand Down Expand Up @@ -281,6 +269,7 @@ C++2c Feature Support

- Implemented `P2809R3: Trivial infinite loops are not Undefined Behavior <https://wg21.link/P2809R3>`_.

- Implemented `P3144R2 Deleting a Pointer to an Incomplete Type Should be Ill-formed <https://wg21.link/P3144R2>`_.

Resolutions to C++ Defect Reports
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Expand Down Expand Up @@ -354,6 +343,11 @@ C23 Feature Support
- Properly promote bit-fields of bit-precise integer types to the field's type
rather than to ``int``. #GH87641

- Added the ``INFINITY`` and ``NAN`` macros to Clang's ``<float.h>``
freestanding implementation; these macros were defined in ``<math.h>`` in C99
but C23 added them to ``<float.h>`` in
`WG14 N2848 <https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2848.pdf>`_.

Non-comprehensive list of changes in this release
-------------------------------------------------

Expand Down Expand Up @@ -442,6 +436,12 @@ New Compiler Flags
Matches MSVC behaviour by defining ``__STDC__`` to ``1`` when
MSVC compatibility mode is used. It has no effect for C++ code.

- ``-Wc++23-compat`` group was added to help migrating existing codebases
to C++23.

- ``-Wc++2c-compat`` group was added to help migrating existing codebases
to upcoming C++26.

Deprecated Compiler Flags
-------------------------

Expand Down Expand Up @@ -480,6 +480,10 @@ Modified Compiler Flags
evaluating to ``true`` and an empty body such as ``while(1);``)
are considered infinite, even when the ``-ffinite-loop`` flag is set.

- Diagnostics groups about compatibility with a particular C++ Standard version
now include dianostics about C++26 features that are not present in older
versions.

Removed Compiler Flags
-------------------------

Expand Down Expand Up @@ -965,6 +969,12 @@ Bug Fixes to C++ Support
forward-declared class. (#GH93512).
- Fixed a bug in access checking inside return-type-requirement of compound requirements. (#GH93788).
- Fixed an assertion failure about invalid conversion when calling lambda. (#GH96205).
- Fixed a bug where the first operand of binary ``operator&`` would be transformed as if it was the operand
of the address of operator. (#GH97483).
- Fixed an assertion failure about a constant expression which is a known integer but is not
evaluated to an integer. (#GH96670).
- Fixed a bug where references to lambda capture inside a ``noexcept`` specifier were not correctly
instantiated. (#GH95735).

Bug Fixes to AST Handling
^^^^^^^^^^^^^^^^^^^^^^^^^
Expand Down
Binary file added clang/docs/analyzer/images/analyzer_html.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added clang/docs/analyzer/images/analyzer_xcode.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added clang/docs/analyzer/images/scan_build_cmd.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 4 additions & 0 deletions clang/docs/analyzer/user-docs.rst
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,9 @@ Contents:
.. toctree::
:maxdepth: 2

user-docs/Installation
user-docs/CommandLineUsage
user-docs/UsingWithXCode
user-docs/FilingBugs
user-docs/CrossTranslationUnit
user-docs/TaintAnalysisConfiguration
239 changes: 239 additions & 0 deletions clang/docs/analyzer/user-docs/CommandLineUsage.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,239 @@
Command Line Usage: scan-build and CodeChecker
==============================================

This document provides guidelines for running the static analyzer from the command line on whole projects.
CodeChecker and scan-build are two CLI tools for using CSA on multiple files (tranlation units).
Both provide a way of driving the analyzer, detecting compilation flags, and generating reports.
CodeChecker is more actively maintained, provides heuristics for working with multiple versions of popular compilers and it also comes with a web-based GUI for viewing, filtering, categorizing and suppressing the results.
Therefore CodeChecker is recommended in case you need any of the above features or just more customizability in general.

Comparison of CodeChecker and scan-build
----------------------------------------

The static analyzer is by design a GUI tool originally intended to be consumed by the XCode IDE.
Its purpose is to find buggy execution paths in the program, and such paths are very hard to comprehend by looking at a non-interactive standard output.
It is possible, however, to invoke the static analyzer from the command line in order to obtain analysis results, and then later view them interactively in a graphical interface.
The following tools are used commonly to run the analyzer from the command line.
Both tools are wrapper scripts to drive the analysis and the underlying invocations of the Clang compiler:

1. scan-build_ is an old and simple command line tool that emits static analyzer warnings as HTML files while compiling your project. You can view the analysis results in your web browser.
- Useful for individual developers who simply want to view static analysis results at their desk, or in a very simple collaborative environment.
- Works on all major platforms (Windows, Linux, macOS) and is available as a package in many Linux distributions.
- Does not include support for cross-translation-unit analysis.

2. CodeChecker_ is a driver and web server that runs the static analyzer on your projects on demand and maintains a database of issues.
- Perfect for managing large amounts of thee static analyzer warnings in a collaborative environment.
- Generally much more feature-rich than scan-build.
- Supports incremental analysis: Results can be stored in a database, subsequent analysis runs can be compared to list the newly added defects.
- :doc:`CrossTranslationUnit` is supported fully on Linux via CodeChecker.
- Can run clang-tidy checkers too.
- Open source, but out-of-tree, i.e. not part of the LLVM project.

scan-build
----------

**scan-build** is a command line utility that enables a user to run the static analyzer over their codebase as part of performing a regular build (from the command line).

How does it work?
~~~~~~~~~~~~~~~~~

During a project build, as source files are compiled they are also analyzed in tandem by the static analyzer.

Upon completion of the build, results are then presented to the user within a web browser.

Will it work with any build system?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

**scan-build** has little or no knowledge about how you build your code. It works by overriding the ``CC`` and ``CXX`` environment variables to (hopefully) change your build to use a "fake" compiler instead of the one that would normally build your project. This fake compiler executes either ``clang`` or ``gcc`` (depending on the platform) to compile your code and then executes the static analyzer to analyze your code.

This "poor man's interposition" works amazingly well in many cases and falls down in others. Please consult the information on this page on making the best use of **scan-build**, which includes getting it to work when the aforementioned hack fails to work.

.. image:: ../images/scan_build_cmd.png

.. image:: ../images/analyzer_html.png

**Viewing static analyzer results in a web browser**

Basic Usage
~~~~~~~~~~~

Basic usage of ``scan-build`` is designed to be simple: just place the word "scan-build" in front of your build command::

$ scan-build make
$ scan-build xcodebuild

In the first case ``scan-build`` analyzes the code of a project built with ``make`` and in the second case ``scan-build`` analyzes a project built using ``xcodebuild``.

Here is the general format for invoking ``scan-build``::

$ scan-build [scan-build options] <command> [command options]

Operationally, ``scan-build`` literally runs <command> with all of the subsequent options passed to it. For example, one can pass ``-j4`` to ``make`` get a parallel build over 4 cores::

$ scan-build make -j4

In almost all cases, ``scan-build`` makes no effort to interpret the options after the build command; it simply passes them through. In general, ``scan-build`` should support parallel builds, but **not distributed builds**.

It is also possible to use ``scan-build`` to analyze specific files::

$ scan-build gcc -c t1.c t2.c

This example causes the files ``t1.c`` and ``t2.c`` to be analyzed.

For Windows Users
~~~~~~~~~~~~~~~~~

Windows users must have Perl installed to use scan-build.

``scan-build.bat`` script allows you to launch scan-build in the same way as it described in the Basic Usage section above. To invoke scan-build from an arbitrary location, add the path to the folder containing scan-build.bat to your PATH environment variable.

If you have unexpected compilation/make problems when running scan-build with MinGW/MSYS the following information may be helpful:

- If getting unexpected ``"fatal error: no input files"`` while building with MSYS make from the Windows cmd, try one of these solutions:
- Use MinGW ``mingw32-make`` instead of MSYS ``make`` and exclude the path to MSYS from PATH to prevent ``mingw32-make`` from using MSYS utils. MSYS utils are dependent on the MSYS runtime and they are not intended for being run from the Windows cmd. Specifically, makefile commands with backslashed quotes may be heavily corrupted when passed for execution.
- Run ``make`` from the sh shell::

$ scan-build [scan-build options] sh -c "make [make options]"

- If getting ``"Error : *** target pattern contains no `%'"`` while using GNU Make 3.81, try to use another version of make.

Other Options
~~~~~~~~~~~~~

As mentioned above, extra options can be passed to ``scan-build``. These options prefix the build command. For example::

$ scan-build -k -V make
$ scan-build -k -V xcodebuild

Here is a subset of useful options:

- **-o**: Target directory for HTML report files. Subdirectories will be created as needed to represent separate "runs" of the analyzer. If this option is not specified, a directory is created in ``/tmp`` to store the reports.
- **-h** *(or no arguments)*: Display all ``scan-build`` options.
- **-k**, **--keep-going**: Add a "keep on going" option to the specified build command. This option currently supports ``make`` and ``xcodebuild``. This is a convenience option; one can specify this behavior directly using build options.
- **-v**: Verbose output from scan-build and the analyzer. **A second and third "-v" increases verbosity**, and is useful for filing bug reports against the analyzer.
- **-V**: View analysis results in a web browser when the build command completes.
- **--use-analyzer Xcode** *(or)* **--use-analyzer [path to clang]**: ``scan-build`` uses the 'clang' executable relative to itself for static analysis. One can override this behavior with this option by using the 'clang' packaged with Xcode (on OS X) or from the PATH.

A complete list of options can be obtained by running ``scan-build`` with no arguments.

Output of scan-build
~~~~~~~~~~~~~~~~~~~~

The output of scan-build is a set of HTML files, each one which represents a separate bug report. A single ``index.html`` file is generated for surveying all of the bugs. You can then just open ``index.html`` in a web browser to view the bug reports.

Where the HTML files are generated is specified with a **-o** option to ``scan-build``. If **-o** isn't specified, a directory in ``/tmp`` is created to store the files (``scan-build`` will print a message telling you where they are). If you want to view the reports immediately after the build completes, pass **-V** to ``scan-build``.

Recommended Usage Guidelines
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

This section describes a few recommendations with running the analyzer.

Always Analyze a Project in its "Debug" Configuration
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Most projects can be built in a "debug" mode that enables assertions. Assertions are picked up by the static analyzer to prune infeasible paths, which in some cases can greatly reduce the number of false positives (bogus error reports) emitted by the tool.

Another option is to use ``--force-analyze-debug-code`` flag of **scan-build** tool which would enable assertions automatically.

Use Verbose Output when Debugging scan-build
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

``scan-build`` takes a **-v** option to emit verbose output about what it's doing; two **-v** options emit more information. Redirecting the output of ``scan-build`` to a text file (make sure to redirect standard error) is useful for filing bug reports against ``scan-build`` or the analyzer, as we can see the exact options (and files) passed to the analyzer. For more comprehensible logs, don't perform a parallel build.

Run './configure' through scan-build
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

If an analyzed project uses an autoconf generated ``configure`` script, you will probably need to run ``configure`` script through ``scan-build`` in order to analyze the project.

**Example**::

$ scan-build ./configure
$ scan-build --keep-cc make

The reason ``configure`` also needs to be run through ``scan-build`` is because ``scan-build`` scans your source files by *interposing* on the compiler. This interposition is currently done by ``scan-build`` temporarily setting the environment variable ``CC`` to ``ccc-analyzer``. The program ``ccc-analyzer`` acts like a fake compiler, forwarding its command line arguments over to the compiler to perform regular compilation and ``clang`` to perform static analysis.

Running ``configure`` typically generates makefiles that have hardwired paths to the compiler, and by running ``configure`` through ``scan-build`` that path is set to ``ccc-analyzer``.

Analyzing iPhone Projects
~~~~~~~~~~~~~~~~~~~~~~~~~

Conceptually Xcode projects for iPhone applications are nearly the same as their cousins for desktop applications. **scan-build** can analyze these projects as well, but users often encounter problems with just building their iPhone projects from the command line because there are a few extra preparative steps they need to take (e.g., setup code signing).

Recommendation: use "Build and Analyze"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The absolute easiest way to analyze iPhone projects is to use the `Analyze feature in Xcode <https://developer.apple.com/library/ios/recipes/xcode_help-source_editor/chapters/Analyze.html#//apple_ref/doc/uid/TP40009975-CH4-SW1>`_ (which is based on the static analyzer). There a user can analyze their project right from a menu without most of the setup described later.

`Instructions are available <../xcode.html>`_ on this website on how to use open source builds of the analyzer as a replacement for the one bundled with Xcode.

Using scan-build directly
~~~~~~~~~~~~~~~~~~~~~~~~~

If you wish to use **scan-build** with your iPhone project, keep the following things in mind:

- Analyze your project in the ``Debug`` configuration, either by setting this as your configuration with Xcode or by passing ``-configuration Debug`` to ``xcodebuild``.
- Analyze your project using the ``Simulator`` as your base SDK. It is possible to analyze your code when targeting the device, but this is much easier to do when using Xcode's *Build and Analyze* feature.
- Check that your code signing SDK is set to the simulator SDK as well, and make sure this option is set to ``Don't Code Sign``.

Note that you can most of this without actually modifying your project. For example, if your application targets iPhoneOS 2.2, you could run **scan-build** in the following manner from the command line::

$ scan-build xcodebuild -configuration Debug -sdk iphonesimulator2.2

Alternatively, if your application targets iPhoneOS 3.0::

$ scan-build xcodebuild -configuration Debug -sdk iphonesimulator3.0

Gotcha: using the right compiler
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Recall that **scan-build** analyzes your project by using a compiler to compile the project and ``clang`` to analyze your project. The script uses simple heuristics to determine which compiler should be used (it defaults to ``clang`` on Darwin and ``gcc`` on other platforms). When analyzing iPhone projects, **scan-build** may pick the wrong compiler than the one Xcode would use to build your project. For example, this could be because multiple versions of a compiler may be installed on your system, especially if you are developing for the iPhone.

When compiling your application to run on the simulator, it is important that **scan-build** finds the correct version of ``gcc/clang``. Otherwise, you may see strange build errors that only happen when you run ``scan-build``.

**scan-build** provides the ``--use-cc`` and ``--use-c++`` options to hardwire which compiler scan-build should use for building your code. Note that although you are chiefly interested in analyzing your project, keep in mind that running the analyzer is intimately tied to the build, and not being able to compile your code means it won't get fully analyzed (if at all).

If you aren't certain which compiler Xcode uses to build your project, try just running ``xcodebuild`` (without **scan-build**). You should see the full path to the compiler that Xcode is using, and use that as an argument to ``--use-cc``.

CodeChecker
-----------

Basic Usage
~~~~~~~~~~~

Install CodeChecker as described here: `CodeChecker Install Guide <https://github.com/Ericsson/codechecker/#Install-guide>`_.

Create a compilation database. If you use cmake then pass the ``-DCMAKE_EXPORT_COMPILE_COMMANDS=1`` parameter to cmake. Cmake will create a ``compile_commands.json`` file.
If you have a Makefile based or similar build system then you can log the build commands with the help of CodeChecker::

make clean
CodeChecker log -b "make" -o compile_commands.json

Analyze your project::

CodeChecker analyze compile_commands.json -o ./reports

View the analysis results.
Print the detailed results in the command line::

CodeChecker parse --print-steps ./reports

Or view the detailed results in a browser::

CodeChecker parse ./reports -e html -o ./reports_html
firefox ./reports_html/index.html

Optional: store the analysis results in a DB::

mkdir ./ws
CodeChecker server -w ./ws -v 8555 &
CodeChecker store ./reports --name my-project --url http://localhost:8555/Default

Optional: manage (categorize, suppress) the results in your web browser::

firefox http://localhost:8555/Default

Detailed Usage
~~~~~~~~~~~~~~

For extended documentation please refer to the `official site of CodeChecker <https://github.com/Ericsson/codechecker/blob/master/docs/usage.md>`_!

18 changes: 18 additions & 0 deletions clang/docs/analyzer/user-docs/FilingBugs.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
Filing Bugs and Feature Requests
================================

We encourage users to file bug reports for any problems that they encounter.
We also welcome feature requests. When filing a bug report, please do the
following:

- Include the checker build (for prebuilt Mac OS X binaries) or the git hash.

- Provide a self-contained, reduced test case that exhibits the issue you are
experiencing.

- Test cases don't tell us everything. Please briefly describe the problem you
are seeing, including what you thought should have been the expected behavior
and why.

Please `file bugs and feature requests <https://llvm.org/docs/HowToSubmitABug.html>`_
in `LLVM's issue tracker <https://github.com/llvm/llvm-project/issues>`_ and label the report with the ``clang:static analyzer`` label.
37 changes: 37 additions & 0 deletions clang/docs/analyzer/user-docs/Installation.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
Obtaining the Static Analyzer
=============================

This page describes how to download and install the analyzer. Once the analyzer is installed, follow the :doc:`CommandLineUsage` on using the command line to get started analyzing your code.

.. contents::
:local:


Building the Analyzer from Source
---------------------------------

Currently there are no officially supported binary distributions for the static analyzer.
You must build Clang and LLVM manually.
To do so, please follow the instructions for `building Clang from source code <https://clang.llvm.org/get_started.html#build>`_.

Once the Clang is built, you need to add the location of the ``clang`` binary and the locations of the command line utilities (`CodeChecker` or ``scan-build`` and ``scan-view``) to you PATH for :doc:`CommandLineUsage`.

[Legacy] Packaged Builds (Mac OS X)
-----------------------------------

Semi-regular pre-built binaries of the analyzer used to be available on Mac OS X. These were built to run on OS X 10.7 and later.

For older builds for MacOS visit https://clang-analyzer.llvm.org/release_notes.html.

Packaged builds for other platforms may eventually be provided, but we need volunteers who are willing to help provide such regular builds. If you wish to help contribute regular builds of the analyzer on other platforms, please get in touch via `LLVM Discourse <https://discourse.llvm.org/>`_.

[Legacy] Using Packaged Builds
------------------------------

To use the legacy pacakge builds, simply unpack it anywhere. If the build archive has the name **``checker-XXX.tar.bz2``** then the archive will expand to a directory called **``checker-XXX``**. You do not need to place this directory or the contents of this directory in any special place. Uninstalling the analyzer is as simple as deleting this directory.

Most of the files in the **``checker-XXX``** directory will be supporting files for the analyzer that you can simply ignore. Most users will only care about two files, which are located at the top of the **``checker-XXX``** directory:

* **scan-build**: ``scan-build`` is the high-level command line utility for running the analyzer
* **scan-view**: ``scan-view`` a companion command line utility to ``scan-build``, ``scan-view`` is used to view analysis results generated by ``scan-build``. There is an option that one can pass to ``scan-build`` to cause ``scan-view`` to run as soon as it the analysis of a build completes

88 changes: 88 additions & 0 deletions clang/docs/analyzer/user-docs/UsingWithXCode.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
Running the analyzer within Xcode
=================================

.. contents::
:local:

Since Xcode 3.2, users have been able to run the static analyzer `directly within Xcode <https://developer.apple.com/library/ios/recipes/xcode_help-source_editor/chapters/Analyze.html#//apple_ref/doc/uid/TP40009975-CH4-SW1>`_.

It integrates directly with the Xcode build system and presents analysis results directly within Xcode's editor.

Can I use the open source analyzer builds with Xcode?
-----------------------------------------------------

**Yes**. Instructions are included below.

.. image:: ../images/analyzer_xcode.png

**Viewing static analyzer results in Xcode**

Key features:
-------------

- **Integrated workflow:** Results are integrated within Xcode. There is no experience of using a separate tool, and activating the analyzer requires a single keystroke or mouse click.
- **Transparency:** Works effortlessly with Xcode projects (including iPhone projects).
- **Cons:** Doesn't work well with non-Xcode projects. For those, consider :doc:`CommandLineUsage`.

Getting Started
---------------

Xcode is available as a free download from Apple on the `Mac App Store <https://itunes.apple.com/us/app/xcode/id497799835?mt=12>`_, with `instructions available <https://developer.apple.com/library/ios/recipes/xcode_help-source_editor/chapters/Analyze.html#//apple_ref/doc/uid/TP40009975-CH4-SW1>`_ for using the analyzer.

Using open source analyzer builds with Xcode
--------------------------------------------

By default, Xcode uses the version of ``clang`` that came bundled with it to analyze your code. It is possible to change Xcode's behavior to use an alternate version of ``clang`` for this purpose while continuing to use the ``clang`` that came with Xcode for compiling projects.

Why try open source builds?
----------------------------

The advantage of using open source analyzer builds (provided on this website) is that they are often newer than the analyzer provided with Xcode, and thus can contain bug fixes, new checks, or simply better analysis.

On the other hand, new checks can be experimental, with results of variable quality. Users are encouraged to file bug reports (for any version of the analyzer) where they encounter false positives or other issues here: :doc:`FilingBugs`.

set-xcode-analyzer
------------------

Starting with analyzer build checker-234, analyzer builds contain a command line utility called ``set-xcode-analyzer`` that allows users to change what copy of ``clang`` that Xcode uses for analysis::

$ set-xcode-analyzer -h
Usage: set-xcode-analyzer [options]

Options:
-h, --help show this help message and exit
--use-checker-build=PATH
Use the Clang located at the provided absolute path,
e.g. /Users/foo/checker-1
--use-xcode-clang Use the Clang bundled with Xcode

Operationally, **set-xcode-analyzer** edits Xcode's configuration files to point it to use the version of ``clang`` you specify for static analysis. Within this model it provides you two basic modes:

- **--use-xcode-clang:** Switch Xcode (back) to using the ``clang`` that came bundled with it for static analysis.
- **--use-checker-build:** Switch Xcode to using the ``clang`` provided by the specified analyzer build.

Things to keep in mind
----------------------

- You should quit Xcode prior to running ``set-xcode-analyzer``.
- You will need to run ``set-xcode-analyzer`` under **``sudo``** in order to have write privileges to modify the Xcode configuration files.

Examples
--------

**Example 1**: Telling Xcode to use checker-235::

$ pwd
/tmp
$ tar xjf checker-235.tar.bz2
$ sudo checker-235/set-xcode-analyzer --use-checker-build=/tmp/checker-235

Note that you typically won't install an analyzer build in ``/tmp``, but the point of this example is that ``set-xcode-analyzer`` just wants a full path to an untarred analyzer build.

**Example 2**: Telling Xcode to use a very specific version of ``clang``::

$ sudo set-xcode-analyzer --use-checker-build=~/mycrazyclangbuild/bin/clang

**Example 3**: Resetting Xcode to its default behavior::

$ sudo set-xcode-analyzer --use-xcode-clang
3 changes: 2 additions & 1 deletion clang/include/clang/AST/ASTConsumer.h
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ namespace clang {
class ASTDeserializationListener; // layering violation because void* is ugly
class SemaConsumer; // layering violation required for safe SemaConsumer
class TagDecl;
class DeclaratorDecl;
class VarDecl;
class FunctionDecl;
class ImportDecl;
Expand Down Expand Up @@ -105,7 +106,7 @@ class ASTConsumer {
/// CompleteExternalDeclaration - Callback invoked at the end of a translation
/// unit to notify the consumer that the given external declaration should be
/// completed.
virtual void CompleteExternalDeclaration(VarDecl *D) {}
virtual void CompleteExternalDeclaration(DeclaratorDecl *D) {}

/// Callback invoked when an MSInheritanceAttr has been attached to a
/// CXXRecordDecl.
Expand Down
1 change: 1 addition & 0 deletions clang/include/clang/Basic/CodeGenOptions.def
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ VALUE_CODEGENOPT(Name, Bits, Default)
#endif

CODEGENOPT(DisableIntegratedAS, 1, 0) ///< -no-integrated-as
CODEGENOPT(Crel, 1, 0) ///< -Wa,--crel
CODEGENOPT(RelaxELFRelocations, 1, 1) ///< -Wa,-mrelax-relocations={yes,no}
CODEGENOPT(AsmVerbose , 1, 0) ///< -dA, -fverbose-asm.
CODEGENOPT(PreserveAsmComments, 1, 1) ///< -dA, -fno-preserve-as-comments.
Expand Down
9 changes: 9 additions & 0 deletions clang/include/clang/Basic/DiagnosticCommonKinds.td
Original file line number Diff line number Diff line change
Expand Up @@ -367,6 +367,15 @@ def warn_target_unrecognized_env : Warning<
def err_target_unsupported_abi_with_fpu : Error<
"'%0' ABI is not supported with FPU">;

def err_ppc_impossible_musttail: Error<
"'musttail' attribute for this call is impossible because %select{"
"long calls can not be tail called on PPC|"
"indirect calls can not be tail called on PPC|"
"external calls can not be tail called on PPC}0"
>;
def err_aix_musttail_unsupported: Error<
"'musttail' attribute is not supported on AIX">;

// Source manager
def err_cannot_open_file : Error<"cannot open file '%0': %1">, DefaultFatal;
def err_file_modified : Error<
Expand Down
4 changes: 4 additions & 0 deletions clang/include/clang/Basic/DiagnosticDriverKinds.td
Original file line number Diff line number Diff line change
Expand Up @@ -801,6 +801,10 @@ def warn_drv_missing_multilib : Warning<
def note_drv_available_multilibs : Note<
"available multilibs are:%0">;

def err_drv_experimental_crel : Error<
"-Wa,--allow-experimental-crel must be specified to use -Wa,--crel. "
"CREL is experimental and uses a non-standard section type code">;

def warn_android_unversioned_fallback : Warning<
"using unversioned Android target directory %0 for target %1; unversioned "
"directories will not be used in Clang 19 -- provide a versioned directory "
Expand Down
34 changes: 24 additions & 10 deletions clang/include/clang/Basic/DiagnosticGroups.td
Original file line number Diff line number Diff line change
Expand Up @@ -344,7 +344,8 @@ def CXX98Compat : DiagGroup<"c++98-compat",
CXXPre14Compat,
CXXPre17Compat,
CXXPre20Compat,
CXXPre23Compat]>;
CXXPre23Compat,
CXXPre26Compat]>;
// Warnings for C++11 features which are Extensions in C++98 mode.
def CXX98CompatPedantic : DiagGroup<"c++98-compat-pedantic",
[CXX98Compat,
Expand All @@ -353,7 +354,8 @@ def CXX98CompatPedantic : DiagGroup<"c++98-compat-pedantic",
CXXPre14CompatPedantic,
CXXPre17CompatPedantic,
CXXPre20CompatPedantic,
CXXPre23CompatPedantic]>;
CXXPre23CompatPedantic,
CXXPre26CompatPedantic]>;

def CXX11NarrowingConstReference : DiagGroup<"c++11-narrowing-const-reference">;
def CXX11Narrowing : DiagGroup<"c++11-narrowing", [CXX11NarrowingConstReference]>;
Expand Down Expand Up @@ -384,42 +386,54 @@ def CXX11Compat : DiagGroup<"c++11-compat",
CXXPre14Compat,
CXXPre17Compat,
CXXPre20Compat,
CXXPre23Compat]>;
CXXPre23Compat,
CXXPre26Compat]>;
def : DiagGroup<"c++0x-compat", [CXX11Compat]>;
def CXX11CompatPedantic : DiagGroup<"c++11-compat-pedantic",
[CXX11Compat,
CXXPre14CompatPedantic,
CXXPre17CompatPedantic,
CXXPre20CompatPedantic,
CXXPre23CompatPedantic]>;
CXXPre23CompatPedantic,
CXXPre26CompatPedantic]>;

def CXX14Compat : DiagGroup<"c++14-compat", [CXXPre17Compat,
CXXPre20Compat,
CXXPre23Compat]>;
CXXPre23Compat,
CXXPre26Compat]>;
def CXX14CompatPedantic : DiagGroup<"c++14-compat-pedantic",
[CXX14Compat,
CXXPre17CompatPedantic,
CXXPre20CompatPedantic,
CXXPre23CompatPedantic]>;
CXXPre23CompatPedantic,
CXXPre26CompatPedantic]>;

def CXX17Compat : DiagGroup<"c++17-compat", [DeprecatedRegister,
DeprecatedIncrementBool,
CXX17CompatMangling,
CXXPre20Compat,
CXXPre23Compat]>;
CXXPre23Compat,
CXXPre26Compat]>;
def CXX17CompatPedantic : DiagGroup<"c++17-compat-pedantic",
[CXX17Compat,
CXXPre20CompatPedantic,
CXXPre23CompatPedantic]>;
CXXPre23CompatPedantic,
CXXPre26CompatPedantic]>;
def : DiagGroup<"c++1z-compat", [CXX17Compat]>;

def CXX20Compat : DiagGroup<"c++20-compat", [CXXPre23Compat]>;
def CXX20Compat : DiagGroup<"c++20-compat", [CXXPre23Compat,
CXXPre26Compat]>;
def CXX20CompatPedantic : DiagGroup<"c++20-compat-pedantic",
[CXX20Compat,
CXXPre23CompatPedantic]>;
CXXPre23CompatPedantic,
CXXPre26CompatPedantic]>;
def : DiagGroup<"c++2a-compat", [CXX20Compat]>;
def : DiagGroup<"c++2a-compat-pedantic", [CXX20CompatPedantic]>;

def CXX23Compat : DiagGroup<"c++23-compat", [CXXPre26Compat]>;

def CXX26Compat : DiagGroup<"c++2c-compat", [DeleteIncomplete]>;

def ExitTimeDestructors : DiagGroup<"exit-time-destructors">;
def FlexibleArrayExtensions : DiagGroup<"flexible-array-extensions">;
def FourByteMultiChar : DiagGroup<"four-char-constants">;
Expand Down
6 changes: 4 additions & 2 deletions clang/include/clang/Basic/DiagnosticSemaKinds.td
Original file line number Diff line number Diff line change
Expand Up @@ -7696,7 +7696,6 @@ def err_qualified_objc_access : Error<
def ext_freestanding_complex : Extension<
"complex numbers are an extension in a freestanding C99 implementation">;

// FIXME: Remove when we support imaginary.
def err_imaginary_not_supported : Error<"imaginary types are not supported">;

// Obj-c expressions
Expand Down Expand Up @@ -7989,8 +7988,11 @@ def ext_delete_void_ptr_operand : ExtWarn<
def err_ambiguous_delete_operand : Error<
"ambiguous conversion of delete expression of type %0 to a pointer">;
def warn_delete_incomplete : Warning<
"deleting pointer to incomplete type %0 may cause undefined behavior">,
"deleting pointer to incomplete type %0 is incompatible with C++2c"
" and may cause undefined behavior">,
InGroup<DeleteIncomplete>;
def err_delete_incomplete : Error<
"cannot delete pointer to incomplete type %0">;
def err_delete_incomplete_class_type : Error<
"deleting incomplete class type %0; no conversions to pointer type">;
def err_delete_explicit_conversion : Error<
Expand Down
5 changes: 5 additions & 0 deletions clang/include/clang/Basic/TokenKinds.def
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,11 @@ KEYWORD(_Atomic , KEYALL|KEYNOOPENCL)
KEYWORD(_Bool , KEYNOCXX)
KEYWORD(_Complex , KEYALL)
KEYWORD(_Generic , KEYALL)
// Note, C2y removed support for _Imaginary; we retain it as a keyword because
// 1) it's a reserved identifier, so we're allowed to steal it, 2) there's no
// good way to specify a keyword in earlier but not later language modes within
// this file, 3) this allows us to provide a better diagnostic in case a user
// does use the keyword.
KEYWORD(_Imaginary , KEYALL)
KEYWORD(_Noreturn , KEYALL)
KEYWORD(_Static_assert , KEYALL)
Expand Down
11 changes: 7 additions & 4 deletions clang/include/clang/Driver/Options.td
Original file line number Diff line number Diff line change
Expand Up @@ -4612,10 +4612,10 @@ def inline_asm_EQ : Joined<["-"], "inline-asm=">, Group<m_Group>,
NormalizedValuesScope<"CodeGenOptions">, NormalizedValues<["IAD_ATT", "IAD_Intel"]>,
MarshallingInfoEnum<CodeGenOpts<"InlineAsmDialect">, "IAD_ATT">;
def mcmodel_EQ : Joined<["-"], "mcmodel=">, Group<m_Group>,
Visibility<[ClangOption, CC1Option]>,
Visibility<[ClangOption, CC1Option, FlangOption, FC1Option]>,
MarshallingInfoString<TargetOpts<"CodeModel">, [{"default"}]>;
def mlarge_data_threshold_EQ : Joined<["-"], "mlarge-data-threshold=">, Group<m_Group>,
Flags<[TargetSpecific]>, Visibility<[ClangOption, CC1Option]>,
Flags<[TargetSpecific]>, Visibility<[ClangOption, CC1Option,FlangOption, FC1Option]>,
MarshallingInfoInt<TargetOpts<"LargeDataThreshold">, "0">;
def mtls_size_EQ : Joined<["-"], "mtls-size=">, Group<m_Group>,
Visibility<[ClangOption, CC1Option]>,
Expand Down Expand Up @@ -6319,9 +6319,9 @@ def mno_gather : Flag<["-"], "mno-gather">, Group<m_Group>,
def mno_scatter : Flag<["-"], "mno-scatter">, Group<m_Group>,
HelpText<"Disable generation of scatter instructions in auto-vectorization(x86 only)">;
def mapx_features_EQ : CommaJoined<["-"], "mapx-features=">, Group<m_x86_Features_Group>,
HelpText<"Enable features of APX">, Values<"egpr,push2pop2,ppx,ndd,ccmp,nf,cf,zu">;
HelpText<"Enable features of APX">, Values<"egpr,push2pop2,ppx,ndd,ccmp,nf,cf,zu">, Visibility<[ClangOption, CLOption, FlangOption]>;
def mno_apx_features_EQ : CommaJoined<["-"], "mno-apx-features=">, Group<m_x86_Features_Group>,
HelpText<"Disable features of APX">, Values<"egpr,push2pop2,ppx,ndd,ccmp,nf,cf,zu">;
HelpText<"Disable features of APX">, Values<"egpr,push2pop2,ppx,ndd,ccmp,nf,cf,zu">, Visibility<[ClangOption, CLOption, FlangOption]>;
// For stability, we only add a feature to -mapxf after it passes the validation of llvm-test-suite && cpu2017 on Intel SDE.
def mapxf : Flag<["-"], "mapxf">, Alias<mapx_features_EQ>, AliasArgs<["egpr","push2pop2","ppx","ndd","ccmp","nf","cf"]>;
def mno_apxf : Flag<["-"], "mno-apxf">, Alias<mno_apx_features_EQ>, AliasArgs<["egpr","push2pop2","ppx","ndd","ccmp","nf","cf"]>;
Expand Down Expand Up @@ -7027,6 +7027,9 @@ def massembler_no_warn : Flag<["-"], "massembler-no-warn">,
def massembler_fatal_warnings : Flag<["-"], "massembler-fatal-warnings">,
HelpText<"Make assembler warnings fatal">,
MarshallingInfoFlag<CodeGenOpts<"FatalWarnings">>;
def crel : Flag<["--"], "crel">,
HelpText<"Enable CREL relocation format (ELF only)">,
MarshallingInfoFlag<CodeGenOpts<"Crel">>;
def mrelax_relocations_no : Flag<["-"], "mrelax-relocations=no">,
HelpText<"Disable x86 relax relocations">,
MarshallingInfoNegativeFlag<CodeGenOpts<"RelaxELFRelocations">>;
Expand Down
2 changes: 1 addition & 1 deletion clang/include/clang/Frontend/MultiplexConsumer.h
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ class MultiplexConsumer : public SemaConsumer {
void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override;
void HandleImplicitImportDecl(ImportDecl *D) override;
void CompleteTentativeDefinition(VarDecl *D) override;
void CompleteExternalDeclaration(VarDecl *D) override;
void CompleteExternalDeclaration(DeclaratorDecl *D) override;
void AssignInheritanceModel(CXXRecordDecl *RD) override;
void HandleVTable(CXXRecordDecl *RD) override;
ASTMutationListener *GetASTMutationListener() override;
Expand Down
4 changes: 2 additions & 2 deletions clang/include/clang/Sema/DeclSpec.h
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@ class DeclSpec {

enum TSC {
TSC_unspecified,
TSC_imaginary,
TSC_imaginary, // Unsupported
TSC_complex
};

Expand Down Expand Up @@ -875,7 +875,7 @@ class DeclSpec {
}

/// Finish - This does final analysis of the declspec, issuing diagnostics for
/// things like "_Imaginary" (lacking an FP type). After calling this method,
/// things like "_Complex" (lacking an FP type). After calling this method,
/// DeclSpec is guaranteed self-consistent, even if an error occurred.
void Finish(Sema &S, const PrintingPolicy &Policy);

Expand Down
5 changes: 2 additions & 3 deletions clang/include/clang/Sema/Sema.h
Original file line number Diff line number Diff line change
Expand Up @@ -3098,7 +3098,7 @@ class Sema final : public SemaBase {
TentativeDefinitionsType TentativeDefinitions;

/// All the external declarations encoutered and used in the TU.
SmallVector<VarDecl *, 4> ExternalDeclarations;
SmallVector<DeclaratorDecl *, 4> ExternalDeclarations;

/// Generally null except when we temporarily switch decl contexts,
/// like in \see SemaObjC::ActOnObjCTemporaryExitContainerContext.
Expand Down Expand Up @@ -4533,8 +4533,7 @@ class Sema final : public SemaBase {
bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);

/// Check Target Version attrs
bool checkTargetVersionAttr(SourceLocation LiteralLoc, Decl *D,
StringRef &Str, bool &isDefault);
bool checkTargetVersionAttr(SourceLocation Loc, Decl *D, StringRef Str);
bool checkTargetClonesAttrString(
SourceLocation LiteralLoc, StringRef Str, const StringLiteral *Literal,
Decl *D, bool &HasDefault, bool &HasCommas, bool &HasNotDefault,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
#include "llvm/ADT/iterator_range.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/ErrorHandling.h"
#include <cassert>
#include <cstdint>
#include <limits>
Expand Down Expand Up @@ -99,6 +100,8 @@ class MemRegion : public llvm::FoldingSetNode {
#define REGION(Id, Parent) Id ## Kind,
#define REGION_RANGE(Id, First, Last) BEGIN_##Id = First, END_##Id = Last,
#include "clang/StaticAnalyzer/Core/PathSensitive/Regions.def"
#undef REGION
#undef REGION_RANGE
};

private:
Expand Down Expand Up @@ -171,6 +174,8 @@ class MemRegion : public llvm::FoldingSetNode {

Kind getKind() const { return kind; }

StringRef getKindStr() const;

template<typename RegionTy> const RegionTy* getAs() const;
template <typename RegionTy>
LLVM_ATTRIBUTE_RETURNS_NONNULL const RegionTy *castAs() const;
Expand Down
7 changes: 3 additions & 4 deletions clang/lib/AST/ASTContext.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -284,10 +284,9 @@ RawComment *ASTContext::getRawCommentForDeclNoCacheImpl(
StringRef Text(Buffer + CommentEndOffset,
DeclLocDecomp.second - CommentEndOffset);

// There should be no other declarations between comment and declaration.
// Preprocessor directives are implicitly allowed to be between a comment and
// its associated decl.
if (Text.find_last_of(";{}@") != StringRef::npos)
// There should be no other declarations or preprocessor directives between
// comment and declaration.
if (Text.find_last_of(";{}#@") != StringRef::npos)
return nullptr;

return CommentBeforeDecl;
Expand Down
11 changes: 9 additions & 2 deletions clang/lib/AST/Decl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -612,19 +612,26 @@ LinkageComputer::getLVForNamespaceScopeDecl(const NamedDecl *D,
assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
"Not a name having namespace scope");
ASTContext &Context = D->getASTContext();
const auto *Var = dyn_cast<VarDecl>(D);

// C++ [basic.link]p3:
// A name having namespace scope (3.3.6) has internal linkage if it
// is the name of

if (getStorageClass(D->getCanonicalDecl()) == SC_Static) {
if ((getStorageClass(D->getCanonicalDecl()) == SC_Static) ||
(Context.getLangOpts().C23 && Var && Var->isConstexpr())) {
// - a variable, variable template, function, or function template
// that is explicitly declared static; or
// (This bullet corresponds to C99 6.2.2p3.)

// C23 6.2.2p3
// If the declaration of a file scope identifier for
// an object contains any of the storage-class specifiers static or
// constexpr then the identifier has internal linkage.
return LinkageInfo::internal();
}

if (const auto *Var = dyn_cast<VarDecl>(D)) {
if (Var) {
// - a non-template variable of non-volatile const-qualified type, unless
// - it is explicitly declared extern, or
// - it is declared in the purview of a module interface unit
Expand Down
9 changes: 6 additions & 3 deletions clang/lib/AST/ExprConstant.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15859,9 +15859,12 @@ static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,

if (const auto *CE = dyn_cast<ConstantExpr>(Exp)) {
if (CE->hasAPValueResult()) {
Result.Val = CE->getAPValueResult();
IsConst = true;
return true;
APValue APV = CE->getAPValueResult();
if (!APV.isLValue()) {
Result.Val = std::move(APV);
IsConst = true;
return true;
}
}

// The SubExpr is usually just an IntegerLiteral.
Expand Down
54 changes: 40 additions & 14 deletions clang/lib/AST/Interp/Compiler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,12 @@ bool InitLink::emit(Compiler<Emitter> *Ctx, const Expr *E) const {
case K_Field:
// We're assuming there's a base pointer on the stack already.
return Ctx->emitGetPtrFieldPop(Offset, E);
case K_Temp:
return Ctx->emitGetPtrLocal(Offset, E);
case K_Decl:
return Ctx->visitDeclRef(D, E);
default:
llvm_unreachable("Unhandled InitLink kind");
}
return true;
}
Expand Down Expand Up @@ -1285,7 +1289,13 @@ bool Compiler<Emitter>::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
template <class Emitter>
bool Compiler<Emitter>::visitInitList(ArrayRef<const Expr *> Inits,
const Expr *ArrayFiller, const Expr *E) {
if (E->getType()->isVoidType())

QualType QT = E->getType();

if (const auto *AT = QT->getAs<AtomicType>())
QT = AT->getValueType();

if (QT->isVoidType())
return this->emitInvalid(E);

// Handle discarding first.
Expand All @@ -1298,17 +1308,16 @@ bool Compiler<Emitter>::visitInitList(ArrayRef<const Expr *> Inits,
}

// Primitive values.
if (std::optional<PrimType> T = classify(E->getType())) {
if (std::optional<PrimType> T = classify(QT)) {
assert(!DiscardResult);
if (Inits.size() == 0)
return this->visitZeroInitializer(*T, E->getType(), E);
return this->visitZeroInitializer(*T, QT, E);
assert(Inits.size() == 1);
return this->delegate(Inits[0]);
}

QualType T = E->getType();
if (T->isRecordType()) {
const Record *R = getRecord(E->getType());
if (QT->isRecordType()) {
const Record *R = getRecord(QT);

if (Inits.size() == 1 && E->getType() == Inits[0]->getType())
return this->delegate(Inits[0]);
Expand All @@ -1325,6 +1334,7 @@ bool Compiler<Emitter>::visitInitList(ArrayRef<const Expr *> Inits,

auto initCompositeField = [=](const Record::Field *FieldToInit,
const Expr *Init) -> bool {
InitLinkScope<Emitter> ILS(this, InitLink::Field(FieldToInit->Offset));
// Non-primitive case. Get a pointer to the field-to-initialize
// on the stack and recurse into visitInitializer().
if (!this->emitGetPtrField(FieldToInit->Offset, Init))
Expand Down Expand Up @@ -1405,8 +1415,8 @@ bool Compiler<Emitter>::visitInitList(ArrayRef<const Expr *> Inits,
return this->emitFinishInit(E);
}

if (T->isArrayType()) {
if (Inits.size() == 1 && E->getType() == Inits[0]->getType())
if (QT->isArrayType()) {
if (Inits.size() == 1 && QT == Inits[0]->getType())
return this->delegate(Inits[0]);

unsigned ElementIndex = 0;
Expand Down Expand Up @@ -1438,7 +1448,7 @@ bool Compiler<Emitter>::visitInitList(ArrayRef<const Expr *> Inits,
// FIXME: This should go away.
if (ArrayFiller) {
const ConstantArrayType *CAT =
Ctx.getASTContext().getAsConstantArrayType(E->getType());
Ctx.getASTContext().getAsConstantArrayType(QT);
uint64_t NumElems = CAT->getZExtSize();

for (; ElementIndex != NumElems; ++ElementIndex) {
Expand All @@ -1450,7 +1460,7 @@ bool Compiler<Emitter>::visitInitList(ArrayRef<const Expr *> Inits,
return this->emitFinishInit(E);
}

if (const auto *ComplexTy = E->getType()->getAs<ComplexType>()) {
if (const auto *ComplexTy = QT->getAs<ComplexType>()) {
unsigned NumInits = Inits.size();

if (NumInits == 1)
Expand Down Expand Up @@ -1480,7 +1490,7 @@ bool Compiler<Emitter>::visitInitList(ArrayRef<const Expr *> Inits,
return true;
}

if (const auto *VecT = E->getType()->getAs<VectorType>()) {
if (const auto *VecT = QT->getAs<VectorType>()) {
unsigned NumVecElements = VecT->getNumElements();
assert(NumVecElements >= Inits.size());

Expand Down Expand Up @@ -2266,6 +2276,7 @@ bool Compiler<Emitter>::VisitMaterializeTemporaryExpr(
const Expr *Inner = E->getSubExpr()->skipRValueSubobjectAdjustments();
if (std::optional<unsigned> LocalIndex =
allocateLocal(Inner, E->getExtendingDecl())) {
InitLinkScope<Emitter> ILS(this, InitLink::Temp(*LocalIndex));
if (!this->emitGetPtrLocal(*LocalIndex, E))
return false;
return this->visitInitializer(SubExpr);
Expand Down Expand Up @@ -2442,6 +2453,13 @@ bool Compiler<Emitter>::VisitCXXConstructExpr(const CXXConstructExpr *E) {
if (T->isRecordType()) {
const CXXConstructorDecl *Ctor = E->getConstructor();

// Trivial copy/move constructor. Avoid copy.
if (Ctor->isDefaulted() && Ctor->isCopyOrMoveConstructor() &&
Ctor->isTrivial() &&
E->getArg(0)->isTemporaryObject(Ctx.getASTContext(),
T->getAsCXXRecordDecl()))
return this->visitInitializer(E->getArg(0));

// If we're discarding a construct expression, we still need
// to allocate a variable and call the constructor and destructor.
if (DiscardResult) {
Expand Down Expand Up @@ -3572,6 +3590,7 @@ VarCreationState Compiler<Emitter>::visitVarDecl(const VarDecl *VD, bool Topleve
return !Init || (checkDecl() && initGlobal(*GlobalIndex));
} else {
VariableScope<Emitter> LocalScope(this, VD);
InitLinkScope<Emitter> ILS(this, InitLink::Decl(VD));

if (VarT) {
unsigned Offset = this->allocateLocalPrimitive(
Expand Down Expand Up @@ -3906,7 +3925,8 @@ bool Compiler<Emitter>::VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
SourceLocScope<Emitter> SLS(this, E);

bool Old = InitStackActive;
InitStackActive = !isa<FunctionDecl>(E->getUsedContext());
InitStackActive =
!(E->getUsedContext()->getDeclKind() == Decl::CXXConstructor);
bool Result = this->delegate(E->getExpr());
InitStackActive = Old;
return Result;
Expand Down Expand Up @@ -3968,8 +3988,14 @@ bool Compiler<Emitter>::VisitCXXThisExpr(const CXXThisExpr *E) {
// currently being initialized. Here we emit the necessary instruction(s) for
// this scenario.
if (InitStackActive && !InitStack.empty()) {
for (const InitLink &IL : InitStack) {
if (!IL.emit<Emitter>(this, E))
unsigned StartIndex = 0;
for (StartIndex = InitStack.size() - 1; StartIndex > 0; --StartIndex) {
if (InitStack[StartIndex].Kind != InitLink::K_Field)
break;
}

for (unsigned I = StartIndex, N = InitStack.size(); I != N; ++I) {
if (!InitStack[I].template emit<Emitter>(this, E))
return false;
}
return true;
Expand Down
9 changes: 7 additions & 2 deletions clang/lib/AST/Interp/Compiler.h
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ struct InitLink {
enum {
K_This = 0,
K_Field = 1,
K_Decl = 2,
K_Temp = 2,
K_Decl = 3,
};

static InitLink This() { return InitLink{K_This}; }
Expand All @@ -56,6 +57,11 @@ struct InitLink {
IL.Offset = Offset;
return IL;
}
static InitLink Temp(unsigned Offset) {
InitLink IL{K_Temp};
IL.Offset = Offset;
return IL;
}
static InitLink Decl(const ValueDecl *D) {
InitLink IL{K_Decl};
IL.D = D;
Expand All @@ -66,7 +72,6 @@ struct InitLink {
template <class Emitter>
bool emit(Compiler<Emitter> *Ctx, const Expr *E) const;

private:
uint32_t Kind;
union {
unsigned Offset;
Expand Down
10 changes: 7 additions & 3 deletions clang/lib/AST/Interp/EvalEmitter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ EvaluationResult EvalEmitter::interpretDecl(const VarDecl *VD,
bool CheckFullyInitialized) {
this->CheckFullyInitialized = CheckFullyInitialized;
S.EvaluatingDecl = VD;
EvalResult.setSource(VD);

if (const Expr *Init = VD->getAnyInitializer()) {
QualType T = VD->getType();
Expand Down Expand Up @@ -156,7 +157,8 @@ template <> bool EvalEmitter::emitRet<PT_Ptr>(const SourceInfo &Info) {
if (!Ptr.isConst() && Ptr.block()->getEvalID() != Ctx.getEvalID())
return false;

if (std::optional<APValue> V = Ptr.toRValue(Ctx)) {
if (std::optional<APValue> V =
Ptr.toRValue(Ctx, EvalResult.getSourceType())) {
EvalResult.setValue(*V);
} else {
return false;
Expand Down Expand Up @@ -186,7 +188,8 @@ bool EvalEmitter::emitRetValue(const SourceInfo &Info) {
if (CheckFullyInitialized && !EvalResult.checkFullyInitialized(S, Ptr))
return false;

if (std::optional<APValue> APV = Ptr.toRValue(S.getCtx())) {
if (std::optional<APValue> APV =
Ptr.toRValue(S.getCtx(), EvalResult.getSourceType())) {
EvalResult.setValue(*APV);
return true;
}
Expand Down Expand Up @@ -257,7 +260,8 @@ void EvalEmitter::updateGlobalTemporaries() {
if (std::optional<PrimType> T = Ctx.classify(E->getType())) {
TYPE_SWITCH(*T, { *Cached = Ptr.deref<T>().toAPValue(); });
} else {
if (std::optional<APValue> APV = Ptr.toRValue(Ctx))
if (std::optional<APValue> APV =
Ptr.toRValue(Ctx, Temp->getTemporaryExpr()->getType()))
*Cached = *APV;
}
}
Expand Down
2 changes: 1 addition & 1 deletion clang/lib/AST/Interp/EvaluationResult.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ std::optional<APValue> EvaluationResult::toRValue() const {

// We have a pointer and want an RValue.
if (const auto *P = std::get_if<Pointer>(&Value))
return P->toRValue(*Ctx);
return P->toRValue(*Ctx, getSourceType());
else if (const auto *FP = std::get_if<FunctionPointer>(&Value)) // Nope
return FP->toAPValue();
llvm_unreachable("Unhandled lvalue kind");
Expand Down
9 changes: 9 additions & 0 deletions clang/lib/AST/Interp/EvaluationResult.h
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,15 @@ class EvaluationResult final {

bool checkFullyInitialized(InterpState &S, const Pointer &Ptr) const;

QualType getSourceType() const {
if (const auto *D =
dyn_cast_if_present<ValueDecl>(Source.dyn_cast<const Decl *>()))
return D->getType();
else if (const auto *E = Source.dyn_cast<const Expr *>())
return E->getType();
return QualType();
}

/// Dump to stderr.
void dump() const;

Expand Down
18 changes: 17 additions & 1 deletion clang/lib/AST/Interp/Interp.h
Original file line number Diff line number Diff line change
Expand Up @@ -922,6 +922,7 @@ inline bool CmpHelperEQ<Pointer>(InterpState &S, CodePtr OpPC, CompareFn Fn) {
return true;
}

// Reject comparisons to weak pointers.
for (const auto &P : {LHS, RHS}) {
if (P.isZero())
continue;
Expand All @@ -934,6 +935,20 @@ inline bool CmpHelperEQ<Pointer>(InterpState &S, CodePtr OpPC, CompareFn Fn) {
}

if (!Pointer::hasSameBase(LHS, RHS)) {
if (LHS.isOnePastEnd() && !RHS.isOnePastEnd() && !RHS.isZero() &&
RHS.getOffset() == 0) {
const SourceInfo &Loc = S.Current->getSource(OpPC);
S.FFDiag(Loc, diag::note_constexpr_pointer_comparison_past_end)
<< LHS.toDiagnosticString(S.getCtx());
return false;
} else if (RHS.isOnePastEnd() && !LHS.isOnePastEnd() && !LHS.isZero() &&
LHS.getOffset() == 0) {
const SourceInfo &Loc = S.Current->getSource(OpPC);
S.FFDiag(Loc, diag::note_constexpr_pointer_comparison_past_end)
<< RHS.toDiagnosticString(S.getCtx());
return false;
}

S.Stk.push<BoolT>(BoolT::from(Fn(ComparisonCategoryResult::Unordered)));
return true;
} else {
Expand Down Expand Up @@ -1294,7 +1309,8 @@ inline bool InitGlobalTempComp(InterpState &S, CodePtr OpPC,
S.SeenGlobalTemporaries.push_back(
std::make_pair(P.getDeclDesc()->asExpr(), Temp));

if (std::optional<APValue> APV = P.toRValue(S.getCtx())) {
if (std::optional<APValue> APV =
P.toRValue(S.getCtx(), Temp->getTemporaryExpr()->getType())) {
*Cached = *APV;
return true;
}
Expand Down
Loading