diff --git a/external/llvm-project/.ci/compute_projects.py b/external/llvm-project/.ci/compute_projects.py index 17a2136a270d..40dd0507a9ea 100644 --- a/external/llvm-project/.ci/compute_projects.py +++ b/external/llvm-project/.ci/compute_projects.py @@ -57,6 +57,13 @@ ".ci": {"llvm", "clang", "lld", "lldb"}, } +# This mapping describes runtimes that should be enabled for a specific project, +# but not necessarily run for testing. The only case of this currently is lldb +# which needs some runtimes enabled for tests. +DEPENDENT_RUNTIMES_TO_BUILD = {"lldb": {"libcxx", "libcxxabi", "libunwind"}} + +# This mapping describes runtimes that should be tested when the key project is +# touched. DEPENDENT_RUNTIMES_TO_TEST = {"clang": {"libcxx", "libcxxabi", "libunwind"}} EXCLUDE_LINUX = { @@ -180,16 +187,20 @@ def _compute_project_check_targets(projects_to_test: Set[str]) -> Set[str]: def _compute_runtimes_to_test(projects_to_test: Set[str]) -> Set[str]: runtimes_to_test = set() for project_to_test in projects_to_test: - if project_to_test not in DEPENDENT_RUNTIMES_TO_TEST: - continue - runtimes_to_test.update(DEPENDENT_RUNTIMES_TO_TEST[project_to_test]) + if project_to_test in DEPENDENT_RUNTIMES_TO_TEST: + runtimes_to_test.update(DEPENDENT_RUNTIMES_TO_TEST[project_to_test]) + if project_to_test in DEPENDENT_RUNTIMES_TO_BUILD: + runtimes_to_test.update(DEPENDENT_RUNTIMES_TO_BUILD[project_to_test]) return runtimes_to_test -def _compute_runtime_check_targets(runtimes_to_test: Set[str]) -> Set[str]: +def _compute_runtime_check_targets(projects_to_test: Set[str]) -> Set[str]: check_targets = set() - for runtime_to_test in runtimes_to_test: - check_targets.add(PROJECT_CHECK_TARGETS[runtime_to_test]) + for project_to_test in projects_to_test: + if project_to_test not in DEPENDENT_RUNTIMES_TO_TEST: + continue + for runtime_to_test in DEPENDENT_RUNTIMES_TO_TEST[project_to_test]: + check_targets.add(PROJECT_CHECK_TARGETS[runtime_to_test]) return check_targets @@ -216,8 +227,8 @@ def get_env_variables(modified_files: list[str], platform: str) -> Set[str]: projects_to_test = _compute_projects_to_test(modified_projects, platform) projects_to_build = _compute_projects_to_build(projects_to_test) projects_check_targets = _compute_project_check_targets(projects_to_test) - runtimes_to_test = _compute_runtimes_to_test(projects_to_test) - runtimes_check_targets = _compute_runtime_check_targets(runtimes_to_test) + runtimes_to_build = _compute_runtimes_to_test(projects_to_test) + runtimes_check_targets = _compute_runtime_check_targets(projects_to_test) # We use a semicolon to separate the projects/runtimes as they get passed # to the CMake invocation and thus we need to use the CMake list separator # (;). We use spaces to separate the check targets as they end up getting @@ -225,7 +236,7 @@ def get_env_variables(modified_files: list[str], platform: str) -> Set[str]: return { "projects_to_build": ";".join(sorted(projects_to_build)), "project_check_targets": " ".join(sorted(projects_check_targets)), - "runtimes_to_build": ";".join(sorted(runtimes_to_test)), + "runtimes_to_build": ";".join(sorted(runtimes_to_build)), "runtimes_check_targets": " ".join(sorted(runtimes_check_targets)), } diff --git a/external/llvm-project/.ci/compute_projects_test.py b/external/llvm-project/.ci/compute_projects_test.py index 885f1dd6af84..ae376ea6a43c 100644 --- a/external/llvm-project/.ci/compute_projects_test.py +++ b/external/llvm-project/.ci/compute_projects_test.py @@ -205,6 +205,17 @@ def test_ci(self): "check-cxx check-cxxabi check-unwind", ) + def test_lldb(self): + env_variables = compute_projects.get_env_variables( + ["lldb/CMakeLists.txt"], "Linux" + ) + self.assertEqual(env_variables["projects_to_build"], "clang;lldb;llvm") + self.assertEqual(env_variables["project_check_targets"], "check-lldb") + self.assertEqual( + env_variables["runtimes_to_build"], "libcxx;libcxxabi;libunwind" + ) + self.assertEqual(env_variables["runtimes_check_targets"], "") + if __name__ == "__main__": unittest.main() diff --git a/external/llvm-project/.ci/metrics/metrics.py b/external/llvm-project/.ci/metrics/metrics.py index 171bc20a9571..143e6ab4cf46 100644 --- a/external/llvm-project/.ci/metrics/metrics.py +++ b/external/llvm-project/.ci/metrics/metrics.py @@ -1,12 +1,9 @@ import collections import datetime -import dateutil import github -import json import logging import os import requests -import sys import time from dataclasses import dataclass @@ -55,18 +52,6 @@ # by trial and error). GRAFANA_METRIC_MAX_AGE_MN = 120 -# Lists the BuildKite jobs we want to track. Maps the BuildKite job name to -# the metric name in Grafana. This is important not to lose metrics history -# if the workflow name changes. -BUILDKITE_WORKFLOW_TO_TRACK = { - ":linux: Linux x64": "buildkite_linux", - ":windows: Windows x64": "buildkite_windows", -} - -# Number of builds to fetch per page. Since we scrape regularly, this can -# remain small. -BUILDKITE_GRAPHQL_BUILDS_PER_PAGE = 50 - @dataclass class JobMetrics: @@ -86,181 +71,6 @@ class GaugeMetric: time_ns: int -def buildkite_fetch_page_build_list( - buildkite_token: str, after_cursor: str = None -) -> list[dict[str, str]]: - """Fetches a page of the build list using the GraphQL BuildKite API. - - Returns the BUILDKITE_GRAPHQL_BUILDS_PER_PAGE last running/queued builds, - or the BUILDKITE_GRAPHQL_BUILDS_PER_PAGE running/queued builds - older than the one pointer by |after_cursor| if provided. - The |after_cursor| value is taken from the previous page returned by the - API. - - Args: - buildkite_token: the secret token to authenticate GraphQL requests. - after_cursor: cursor after which to start the page fetch. - - Returns: - The most recent builds after cursor (if set) with the following format: - [ - { - "cursor": , - "number": , - } - ] - """ - - BUILDKITE_GRAPHQL_QUERY = """ - query OrganizationShowQuery {{ - organization(slug: "llvm-project") {{ - pipelines(search: "Github pull requests", first: 1) {{ - edges {{ - node {{ - builds (state: [CANCELING, CREATING, FAILING, RUNNING], first: {PAGE_SIZE}, after: {AFTER}) {{ - edges {{ - cursor - node {{ - number - }} - }} - }} - }} - }} - }} - }} - }} - """ - query = BUILDKITE_GRAPHQL_QUERY.format( - PAGE_SIZE=BUILDKITE_GRAPHQL_BUILDS_PER_PAGE, - AFTER="null" if after_cursor is None else '"{}"'.format(after_cursor), - ) - query = json.dumps({"query": query}) - url = "https://graphql.buildkite.com/v1" - headers = { - "Authorization": "Bearer " + buildkite_token, - "Content-Type": "application/json", - } - data = requests.post(url, data=query, headers=headers).json() - # De-nest the build list. - if "errors" in data: - logging.info("Failed to fetch BuildKite jobs: {}".format(data["errors"])) - return [] - builds = data["data"]["organization"]["pipelines"]["edges"][0]["node"]["builds"][ - "edges" - ] - # Fold cursor info into the node dictionnary. - return [{**x["node"], "cursor": x["cursor"]} for x in builds] - - -def buildkite_get_build_info(build_number: str) -> dict: - """Returns all the info associated with the provided build number. - - Note: for unknown reasons, graphql returns no jobs for a given build, - while this endpoint does, hence why this uses this API instead of graphql. - - Args: - build_number: which build number to fetch info for. - - Returns: - The info for the target build, a JSON dictionnary. - """ - - URL = "https://buildkite.com/llvm-project/github-pull-requests/builds/{}.json" - return requests.get(URL.format(build_number)).json() - - -def buildkite_get_incomplete_tasks(buildkite_token: str) -> list: - """Returns all the running/pending BuildKite builds. - - Args: - buildkite_token: the secret token to authenticate GraphQL requests. - last_cursor: the cursor to stop at if set. If None, a full page is fetched. - """ - output = [] - cursor = None - while True: - page = buildkite_fetch_page_build_list(buildkite_token, cursor) - if len(page) == 0: - break - cursor = page[-1]["cursor"] - output += page - return output - - -def buildkite_get_metrics( - buildkite_token: str, previously_incomplete: set[int] -) -> (list[JobMetrics], set[int]): - """Returns a tuple with: - - - the metrics recorded for newly completed workflow jobs. - - the set of workflow still running now. - - Args: - buildkite_token: the secret token to authenticate GraphQL requests. - previously_incomplete: the set of running workflows the last time this - function was called. - """ - - running_builds = buildkite_get_incomplete_tasks(buildkite_token) - incomplete_now = set([x["number"] for x in running_builds]) - output = [] - - for build_id in previously_incomplete: - if build_id in incomplete_now: - continue - - info = buildkite_get_build_info(build_id) - metric_timestamp = dateutil.parser.isoparse(info["finished_at"]) - for job in info["jobs"]: - # This workflow is not interesting to us. - if job["name"] not in BUILDKITE_WORKFLOW_TO_TRACK: - continue - - # Don't count canceled jobs. - if job["canceled_at"]: - continue - - created_at = dateutil.parser.isoparse(job["created_at"]) - scheduled_at = dateutil.parser.isoparse(job["scheduled_at"]) - started_at = dateutil.parser.isoparse(job["started_at"]) - finished_at = dateutil.parser.isoparse(job["finished_at"]) - - job_name = BUILDKITE_WORKFLOW_TO_TRACK[job["name"]] - queue_time = (started_at - scheduled_at).seconds - run_time = (finished_at - started_at).seconds - status = bool(job["passed"]) - - # Grafana will refuse to ingest metrics older than ~2 hours, so we - # should avoid sending historical data. - metric_age_mn = ( - datetime.datetime.now(datetime.timezone.utc) - metric_timestamp - ).total_seconds() / 60 - if metric_age_mn > GRAFANA_METRIC_MAX_AGE_MN: - logging.warning( - f"Job {job['name']} from workflow {build_id} dropped due" - + f" to staleness: {metric_age_mn}mn old." - ) - continue - - metric_timestamp_ns = int(metric_timestamp.timestamp()) * 10**9 - workflow_id = build_id - workflow_name = "Github pull requests" - output.append( - JobMetrics( - job_name, - queue_time, - run_time, - status, - metric_timestamp_ns, - workflow_id, - workflow_name, - ) - ) - - return output, incomplete_now - - def github_get_metrics( github_repo: github.Repository, last_workflows_seen_as_completed: set[int] ) -> tuple[list[JobMetrics], int]: @@ -478,7 +288,6 @@ def upload_metrics(workflow_metrics, metrics_userid, api_key): def main(): # Authenticate with Github github_auth = Auth.Token(os.environ["GITHUB_TOKEN"]) - buildkite_token = os.environ["BUILDKITE_TOKEN"] grafana_api_key = os.environ["GRAFANA_API_KEY"] grafana_metrics_userid = os.environ["GRAFANA_METRICS_USERID"] @@ -486,9 +295,6 @@ def main(): # Because the Github queries are broken, we'll simply log a 'processed' # bit for the last COUNT_TO_PROCESS workflows. gh_last_workflows_seen_as_completed = set() - # Stores the list of pending/running builds in BuildKite we need to check - # at the next iteration. - bk_incomplete = set() # Enter the main loop. Every five minutes we wake up and dump metrics for # the relevant jobs. @@ -500,13 +306,8 @@ def main(): github_repo, gh_last_workflows_seen_as_completed ) - bk_metrics, bk_incomplete = buildkite_get_metrics( - buildkite_token, bk_incomplete - ) - - metrics = gh_metrics + bk_metrics - upload_metrics(metrics, grafana_metrics_userid, grafana_api_key) - logging.info(f"Uploaded {len(metrics)} metrics") + upload_metrics(gh_metrics, grafana_metrics_userid, grafana_api_key) + logging.info(f"Uploaded {len(gh_metrics)} metrics") time.sleep(SCRAPE_INTERVAL_SECONDS) diff --git a/external/llvm-project/.ci/monolithic-linux.sh b/external/llvm-project/.ci/monolithic-linux.sh index a0ce8f3b80f1..7503ea4e6a99 100755 --- a/external/llvm-project/.ci/monolithic-linux.sh +++ b/external/llvm-project/.ci/monolithic-linux.sh @@ -47,7 +47,7 @@ function at-exit { python3 "${MONOREPO_ROOT}"/.ci/generate_test_report_buildkite.py ":linux: Linux x64 Test Results" \ "linux-x64-test-results" $retcode "${BUILD_DIR}"/test-results.*.xml else - python3 "${MONOREPO_ROOT}"/.ci/generate_test_report_github.py ":linux: Linux x64 Test Results" \ + python3 "${MONOREPO_ROOT}"/.ci/generate_test_report_github.py ":penguin: Linux x64 Test Results" \ $retcode "${BUILD_DIR}"/test-results.*.xml >> $GITHUB_STEP_SUMMARY fi } @@ -55,6 +55,8 @@ trap at-exit EXIT projects="${1}" targets="${2}" +runtimes="${3}" +runtime_targets="${4}" lit_args="-v --xunit-xml-output ${BUILD_DIR}/test-results.xml --use-unique-output-file-name --timeout=1200 --time-tests" @@ -70,7 +72,7 @@ export LLVM_SYMBOLIZER_PATH=`which llvm-symbolizer` # It will not be built unless it is used. cmake -S "${MONOREPO_ROOT}"/llvm -B "${BUILD_DIR}" \ -D LLVM_ENABLE_PROJECTS="${projects}" \ - -D LLVM_ENABLE_RUNTIMES="libcxx;libcxxabi;libunwind" \ + -D LLVM_ENABLE_RUNTIMES="${runtimes}" \ -G Ninja \ -D CMAKE_PREFIX_PATH="${HOME}/.local" \ -D CMAKE_BUILD_TYPE=Release \ @@ -91,62 +93,28 @@ echo "--- ninja" # Targets are not escaped as they are passed as separate arguments. ninja -C "${BUILD_DIR}" -k 0 ${targets} -runtimes="${3}" -runtime_targets="${4}" - # Compiling runtimes with just-built Clang and running their tests # as an additional testing for Clang. -if [[ "${runtimes}" != "" ]]; then - if [[ "${runtime_targets}" == "" ]]; then - echo "Runtimes to build are specified, but targets are not." - exit 1 - fi - - echo "--- ninja install-clang" - - ninja -C ${BUILD_DIR} install-clang install-clang-resource-headers - - RUNTIMES_BUILD_DIR="${MONOREPO_ROOT}/build-runtimes" - INSTALL_DIR="${BUILD_DIR}/install" - mkdir -p ${RUNTIMES_BUILD_DIR} - +if [[ "${runtimes_targets}" != "" ]]; then echo "--- cmake runtimes C++26" - rm -rf "${RUNTIMES_BUILD_DIR}" - cmake -S "${MONOREPO_ROOT}/runtimes" -B "${RUNTIMES_BUILD_DIR}" -GNinja \ - -D CMAKE_C_COMPILER="${INSTALL_DIR}/bin/clang" \ - -D CMAKE_CXX_COMPILER="${INSTALL_DIR}/bin/clang++" \ - -D LLVM_ENABLE_RUNTIMES="${runtimes}" \ - -D LIBCXX_CXX_ABI=libcxxabi \ - -D CMAKE_BUILD_TYPE=RelWithDebInfo \ - -D CMAKE_INSTALL_PREFIX="${INSTALL_DIR}" \ - -D LIBCXX_TEST_PARAMS="std=c++26" \ - -D LIBCXXABI_TEST_PARAMS="std=c++26" \ - -D LLVM_LIT_ARGS="${lit_args}" + cmake \ + -D LIBCXX_TEST_PARAMS="std=c++26" \ + -D LIBCXXABI_TEST_PARAMS="std=c++26" \ + "${BUILD_DIR}" echo "--- ninja runtimes C++26" - ninja -vC "${RUNTIMES_BUILD_DIR}" ${runtime_targets} + ninja -C "${BUILD_DIR}" ${runtime_targets} echo "--- cmake runtimes clang modules" - # We don't need to do a clean build of runtimes, because LIBCXX_TEST_PARAMS - # and LIBCXXABI_TEST_PARAMS only affect lit configuration, which successfully - # propagates without a clean build. Other that those two variables, builds - # are supposed to be the same. - - cmake -S "${MONOREPO_ROOT}/runtimes" -B "${RUNTIMES_BUILD_DIR}" -GNinja \ - -D CMAKE_C_COMPILER="${INSTALL_DIR}/bin/clang" \ - -D CMAKE_CXX_COMPILER="${INSTALL_DIR}/bin/clang++" \ - -D LLVM_ENABLE_RUNTIMES="${runtimes}" \ - -D LIBCXX_CXX_ABI=libcxxabi \ - -D CMAKE_BUILD_TYPE=RelWithDebInfo \ - -D CMAKE_INSTALL_PREFIX="${INSTALL_DIR}" \ - -D LIBCXX_TEST_PARAMS="enable_modules=clang" \ - -D LIBCXXABI_TEST_PARAMS="enable_modules=clang" \ - -D LLVM_LIT_ARGS="${lit_args}" + cmake \ + -D LIBCXX_TEST_PARAMS="enable_modules=clang" \ + -D LIBCXXABI_TEST_PARAMS="enable_modules=clang" \ + "${BUILD_DIR}" echo "--- ninja runtimes clang modules" - ninja -vC "${RUNTIMES_BUILD_DIR}" ${runtime_targets} + ninja -C "${BUILD_DIR}" ${runtime_targets} fi diff --git a/external/llvm-project/.ci/monolithic-windows.sh b/external/llvm-project/.ci/monolithic-windows.sh index 8dc49aa15819..a0997420b0d3 100755 --- a/external/llvm-project/.ci/monolithic-windows.sh +++ b/external/llvm-project/.ci/monolithic-windows.sh @@ -42,7 +42,7 @@ function at-exit { python "${MONOREPO_ROOT}"/.ci/generate_test_report_buildkite.py ":windows: Windows x64 Test Results" \ "windows-x64-test-results" $retcode "${BUILD_DIR}"/test-results.*.xml else - python "${MONOREPO_ROOT}"/.ci/generate_test_report_github.py ":windows: Windows x64 Test Results" \ + python "${MONOREPO_ROOT}"/.ci/generate_test_report_github.py ":window: Windows x64 Test Results" \ $retcode "${BUILD_DIR}"/test-results.*.xml >> $GITHUB_STEP_SUMMARY fi } diff --git a/external/llvm-project/.git-blame-ignore-revs b/external/llvm-project/.git-blame-ignore-revs index 30d9f6b883ce..01569c619f8f 100644 --- a/external/llvm-project/.git-blame-ignore-revs +++ b/external/llvm-project/.git-blame-ignore-revs @@ -100,3 +100,9 @@ d33bf2e9df578ff7e44fd22504d6ad5a122b7ee6 # [lldb][NFC] clang-format MainLoopPosix.cpp 66bdbfbaa08fa3d8e64a7fe136a8fb717f5cdbb7 + +# [clang-tidy][NFC] Run clang-format on "clang-tools-extra/clang-tidy" +65d66625b3e2b8322ed99d82edabecbafcd0885b +ce46adb8b7ce645353eccaedf31ed9765dab77bb +68070f908bb7ac5f0b5fa9722caa504ecf723f6b +5213c57cb1f0d78aad9a253b7f6a2b62ff4c7859 diff --git a/external/llvm-project/.github/new-prs-labeler.yml b/external/llvm-project/.github/new-prs-labeler.yml index f6a7a6072478..162161ff13fb 100644 --- a/external/llvm-project/.github/new-prs-labeler.yml +++ b/external/llvm-project/.github/new-prs-labeler.yml @@ -554,6 +554,12 @@ flang:fir-hlfir: flang:codegen: - flang/**/CodeGen/** +llvm:codegen: + - llvm/lib/CodeGen/* + - llvm/lib/CodeGen/MIRParser/* + - llvm/lib/CodeGen/LiveDebugValues/* + - llvm/lib/CodeGen/AsmPrinter/* + llvm:globalisel: - llvm/**/GlobalISel/** - llvm/utils/TableGen/GlobalISel* diff --git a/external/llvm-project/.github/workflows/buildbot-psdb-trigger.yml b/external/llvm-project/.github/workflows/buildbot-psdb-trigger.yml index 10ba788abf4d..471fd4001ae8 100644 --- a/external/llvm-project/.github/workflows/buildbot-psdb-trigger.yml +++ b/external/llvm-project/.github/workflows/buildbot-psdb-trigger.yml @@ -9,7 +9,8 @@ on: jobs: trigger-build: if: github.event.pull_request.draft == false - runs-on: self-hosted + runs-on: + group: compiler-generic-runners env: PR_SHA: ${{ github.event.pull_request.head.sha != '' && github.event.pull_request.head.sha || github.sha }} PR_NUMBER: ${{ github.event.pull_request.number != '' && github.event.pull_request.number || 0 }} diff --git a/external/llvm-project/.github/workflows/containers/github-action-ci-windows/Dockerfile b/external/llvm-project/.github/workflows/containers/github-action-ci-windows/Dockerfile index 09cda4bb574b..eafe45fac8ea 100644 --- a/external/llvm-project/.github/workflows/containers/github-action-ci-windows/Dockerfile +++ b/external/llvm-project/.github/workflows/containers/github-action-ci-windows/Dockerfile @@ -85,7 +85,7 @@ RUN powershell -Command \ RUN git config --system core.longpaths true & \ git config --global core.autocrlf false -ARG RUNNER_VERSION=2.324.0 +ARG RUNNER_VERSION=2.325.0 ENV RUNNER_VERSION=$RUNNER_VERSION RUN powershell -Command \ diff --git a/external/llvm-project/.github/workflows/containers/github-action-ci/Dockerfile b/external/llvm-project/.github/workflows/containers/github-action-ci/Dockerfile index 52c20e049ee7..f2716f0a9c6a 100644 --- a/external/llvm-project/.github/workflows/containers/github-action-ci/Dockerfile +++ b/external/llvm-project/.github/workflows/containers/github-action-ci/Dockerfile @@ -86,7 +86,7 @@ WORKDIR /home/gha FROM ci-container as ci-container-agent -ENV GITHUB_RUNNER_VERSION=2.324.0 +ENV GITHUB_RUNNER_VERSION=2.325.0 RUN mkdir actions-runner && \ cd actions-runner && \ diff --git a/external/llvm-project/.github/workflows/docs.yml b/external/llvm-project/.github/workflows/docs.yml index 0692633b71a5..3970271e4adb 100644 --- a/external/llvm-project/.github/workflows/docs.yml +++ b/external/llvm-project/.github/workflows/docs.yml @@ -205,7 +205,7 @@ jobs: steps.docs-changed-subprojects.outputs.workflow_any_changed == 'true' run: | cmake -B flang-build -GNinja -DCMAKE_BUILD_TYPE=Release -DLLVM_ENABLE_PROJECTS="clang;mlir;flang" -DLLVM_ENABLE_SPHINX=ON ./llvm - TZ=UTC ninja -C flang-build docs-flang-html + TZ=UTC ninja -C flang-build docs-flang-html docs-flang-man mkdir built-docs/flang cp -r flang-build/docs/* built-docs/flang/ - name: Upload docs diff --git a/external/llvm-project/.github/workflows/email-check.yaml b/external/llvm-project/.github/workflows/email-check.yaml index f4481d5cf558..904ad718f97d 100644 --- a/external/llvm-project/.github/workflows/email-check.yaml +++ b/external/llvm-project/.github/workflows/email-check.yaml @@ -32,7 +32,8 @@ jobs: COMMENT: >- ⚠️ We detected that you are using a GitHub private e-mail address to contribute to the repo.
Please turn off [Keep my email addresses private](https://github.com/settings/emails) setting in your account.
- See [LLVM Discourse](https://discourse.llvm.org/t/hidden-emails-on-github-should-we-do-something-about-it) for more information. + See [LLVM Developer Policy](https://llvm.org/docs/DeveloperPolicy.html#email-addresses) and + [LLVM Discourse](https://discourse.llvm.org/t/hidden-emails-on-github-should-we-do-something-about-it) for more information. run: | cat << EOF > comments [{"body" : "$COMMENT"}] diff --git a/external/llvm-project/.github/workflows/libcxx-build-and-test.yaml b/external/llvm-project/.github/workflows/libcxx-build-and-test.yaml index 80f2432b78de..f0bdf6c0b589 100644 --- a/external/llvm-project/.github/workflows/libcxx-build-and-test.yaml +++ b/external/llvm-project/.github/workflows/libcxx-build-and-test.yaml @@ -52,8 +52,8 @@ jobs: cxx: [ 'clang++-21' ] include: - config: 'generic-gcc' - cc: 'gcc-14' - cxx: 'g++-14' + cc: 'gcc-15' + cxx: 'g++-15' steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - name: ${{ matrix.config }}.${{ matrix.cxx }} @@ -92,8 +92,8 @@ jobs: cxx: [ 'clang++-21' ] include: - config: 'generic-gcc-cxx11' - cc: 'gcc-14' - cxx: 'g++-14' + cc: 'gcc-15' + cxx: 'g++-15' - config: 'generic-cxx26' cc: 'clang-20' cxx: 'clang++-20' diff --git a/external/llvm-project/amd/comgr/CMakeLists.txt b/external/llvm-project/amd/comgr/CMakeLists.txt index 922e040ea94d..c4fc39edba25 100644 --- a/external/llvm-project/amd/comgr/CMakeLists.txt +++ b/external/llvm-project/amd/comgr/CMakeLists.txt @@ -179,12 +179,24 @@ message("") option(COMGR_DISABLE_SPIRV "To disable SPIRV in Comgr" OFF) if (NOT COMGR_DISABLE_SPIRV) - # TODO: Explore switching this to CHECK_INCLUDE_FILE_CXX() macro - if (NOT EXISTS "${LLVM_INCLUDE_DIRS}/LLVMSPIRVLib/LLVMSPIRVLib.h") + # Candidate include paths for LLVMSPIRVLib.h: + # 1. ${LLVM_INCLUDE_DIRS}/LLVMSPIRVLib (standalone build) + # 2. ${LLVM_EXTERNAL_SPIRV_LLVM_TRANSLATOR_SOURCE_DIR}/include (external project) + # 3. ${CMAKE_SOURCE_DIR}/projects/SPIRV-LLVM-Translator/include (usual location) + find_path( + FOUND_SPIRV_INCLUDE_DIR + LLVMSPIRVLib.h + PATHS + "${LLVM_INCLUDE_DIRS}/LLVMSPIRVLib" + "${LLVM_EXTERNAL_SPIRV_LLVM_TRANSLATOR_SOURCE_DIR}/include" + "${CMAKE_SOURCE_DIR}/projects/SPIRV-LLVM-Translator/include" + NO_DEFAULT_PATH + ) + if (NOT EXISTS "${FOUND_SPIRV_INCLUDE_DIR}/LLVMSPIRVLib.h") message("-- LLVMSPIRVLib/LLVMSPIRVLib.h not found") set(COMGR_DISABLE_SPIRV ON) else() - message("-- LLVMSPIRVLib/LLVMSPIRVLib.h found") + message("-- LLVMSPIRVLib/LLVMSPIRVLib.h found at ${FOUND_SPIRV_INCLUDE_DIR}") endif() endif() @@ -195,7 +207,7 @@ else() message("-- Comgr SPIRV Enabled") target_include_directories(amd_comgr PRIVATE - "${LLVM_INCLUDE_DIRS}/LLVMSPIRVLib") + "${FOUND_SPIRV_INCLUDE_DIR}") endif() diff --git a/external/llvm-project/amd/comgr/README.md b/external/llvm-project/amd/comgr/README.md index 21710c8e5514..1e3056378698 100644 --- a/external/llvm-project/amd/comgr/README.md +++ b/external/llvm-project/amd/comgr/README.md @@ -198,13 +198,11 @@ improving performance by reducing on-disk file I/O. Currently, VFS is only suppo for the device library link step, but we aim to progressively add support for more actions. -By default, VFS is turned off. Set the environment variable `AMD_COMGR_USE_VFS=1` to -enable it. +By default, VFS is turned on. -* `AMD_COMGR_USE_VFS`: When unset or "0", VFS support is turned off. -* Users may use the API `amd_comgr_action_info_set_vfs` to enable VFS for individual actions - without having to modify system-wide environment variables. Note that API is effective only - if `AMD_COMGR_USE_VFS` is unset. +* `AMD_COMGR_USE_VFS`: When set to "0", VFS support is turned off. +* Users may use the API `amd_comgr_action_info_set_vfs` to disable VFS for individual actions + without having to modify system-wide environment variables. * If `AMD_COMGR_SAVE_TEMPS` is set and not "0", VFS support is turned off irrespective of `AMD_COMGR_USE_VFS` or the use of `amd_comgr_action_info_set_vfs`. diff --git a/external/llvm-project/amd/comgr/cmake/DeviceLibs.cmake b/external/llvm-project/amd/comgr/cmake/DeviceLibs.cmake index d8f5654dfee5..3c5654d93dae 100644 --- a/external/llvm-project/amd/comgr/cmake/DeviceLibs.cmake +++ b/external/llvm-project/amd/comgr/cmake/DeviceLibs.cmake @@ -59,7 +59,8 @@ foreach(AMDGCN_LIB_TARGET ${AMD_DEVICE_LIBS_TARGETS}) add_dependencies(amd_comgr ${AMDGCN_LIB_TARGET}_header) list(APPEND TARGETS_INCLUDES "#include \"${header}\"") - list(APPEND TARGETS_HEADERS "${INC_DIR}/${header}") + list(APPEND TARGETS_HEADERS_FILENAME "${header}") + list(APPEND TARGETS_HEADERS_REALPATH "${INC_DIR}/${header}") endforeach() list(JOIN TARGETS_INCLUDES "\n" TARGETS_INCLUDES) @@ -113,8 +114,8 @@ find_package(Python3 REQUIRED Interpreter) set(DEVICE_LIBS_ID_SCRIPT "${CMAKE_CURRENT_SOURCE_DIR}/cmake/device-libs-id.py") set(DEVICE_LIBS_ID_HEADER ${INC_DIR}/libraries_sha.inc) add_custom_command(OUTPUT ${DEVICE_LIBS_ID_HEADER} - COMMAND ${Python3_EXECUTABLE} ${DEVICE_LIBS_ID_SCRIPT} --varname DEVICE_LIBS_ID --output ${DEVICE_LIBS_ID_HEADER} ${TARGETS_HEADERS} - DEPENDS ${DEVICE_LIBS_ID_SCRIPT} ${TARGETS_HEADERS} + COMMAND ${Python3_EXECUTABLE} ${DEVICE_LIBS_ID_SCRIPT} --varname DEVICE_LIBS_ID --output ${DEVICE_LIBS_ID_HEADER} --parent-directory ${INC_DIR} ${TARGETS_HEADERS_FILENAME} + DEPENDS ${DEVICE_LIBS_ID_SCRIPT} ${TARGETS_HEADERS_REALPATH} COMMENT "Generating ${INC_DIR}/libraries_sha.inc" ) set_property(DIRECTORY APPEND PROPERTY ADDITIONAL_MAKE_CLEAN_FILES ${INC_DIR}/libraries_sha.inc) diff --git a/external/llvm-project/amd/comgr/cmake/device-libs-id.py b/external/llvm-project/amd/comgr/cmake/device-libs-id.py index 06ac7a4522f4..09362fb207ca 100644 --- a/external/llvm-project/amd/comgr/cmake/device-libs-id.py +++ b/external/llvm-project/amd/comgr/cmake/device-libs-id.py @@ -4,11 +4,14 @@ from argparse import ArgumentParser from hashlib import sha256 -from functools import reduce +from os.path import join as join_path if __name__ == "__main__": parser = ArgumentParser(description='Generate id by computing a hash of the generated headers') parser.add_argument("headers", nargs='+', help='List of headers to generate id from') + # On Windows, we cannot list the realpath for every individual header since we hit cmd.exe's + # maximum command line lenght. As a workaround, we pass the pwd and the headers separately. + parser.add_argument("--parent-directory", help='Parent directory for the headers', required=True) parser.add_argument("--varname", help='Name of the variable to generate', required=True) parser.add_argument("--output", help='Name of the header to generate', required=True) @@ -16,8 +19,8 @@ args.headers.sort() hash = sha256() - for x in args.headers: - hash.update(open(x, 'rb').read()) + for header in args.headers: + hash.update(open(join_path(args.parent_directory, header), 'rb').read()) digest_uchar = hash.digest() digest_elts = ", ".join(map(str, digest_uchar)) print(f"static const unsigned char {args.varname}[] = {{{digest_elts}, 0}};", file=open(args.output, 'w')) diff --git a/external/llvm-project/amd/comgr/docs/ReleaseNotes.md b/external/llvm-project/amd/comgr/docs/ReleaseNotes.md index d3dcb3215340..abca63906622 100644 --- a/external/llvm-project/amd/comgr/docs/ReleaseNotes.md +++ b/external/llvm-project/amd/comgr/docs/ReleaseNotes.md @@ -38,8 +38,9 @@ Bug Fixes New APIs -------- - amd\_comgr\_info\_set\_vfs\_() (v3.1) - - By setting this ActionInfo property, a user can explicitly dictate if - device libraries should be linked using a Virtual File System (VFS). + - By setting this ActionInfo property, users can explicitly dictate if + device libraries should be linked using the real file system or a + Virtual File System (VFS). Deprecated APIs --------------- diff --git a/external/llvm-project/amd/comgr/src/comgr.h b/external/llvm-project/amd/comgr/src/comgr.h index 1511e8632fe7..e419a46baf6d 100644 --- a/external/llvm-project/amd/comgr/src/comgr.h +++ b/external/llvm-project/amd/comgr/src/comgr.h @@ -204,7 +204,7 @@ struct DataAction { amd_comgr_language_t Language; bool Logging; bool ShouldLinkDeviceLibs = false; - bool ShouldUseVFS = false; + bool ShouldUseVFS = true; std::vector BundleEntryIDs; diff --git a/external/llvm-project/amd/comgr/test-lit/spirv-to-reloc-debuginfo.hip b/external/llvm-project/amd/comgr/test-lit/spirv-to-reloc-debuginfo.hip index 7f5db667adcd..4fa7cc4cbe0c 100644 --- a/external/llvm-project/amd/comgr/test-lit/spirv-to-reloc-debuginfo.hip +++ b/external/llvm-project/amd/comgr/test-lit/spirv-to-reloc-debuginfo.hip @@ -1,4 +1,4 @@ -// REQUIRES: comgr-has-spirv,fix-rhel-issue +// REQUIRES: comgr-has-spirv // COM: Generate a debuginfo SPIR-V file from a HIP kernel // RUN: clang -x hip --offload-arch=amdgcnspirv -nogpulib -nogpuinc \ diff --git a/external/llvm-project/amd/comgr/test-lit/vfs-tests/vfs-tests.cl b/external/llvm-project/amd/comgr/test-lit/vfs-tests/vfs-tests.cl index 6c6932ab2a0f..bc7c66af8521 100644 --- a/external/llvm-project/amd/comgr/test-lit/vfs-tests/vfs-tests.cl +++ b/external/llvm-project/amd/comgr/test-lit/vfs-tests/vfs-tests.cl @@ -23,7 +23,7 @@ // COM: Verify success of compilation for all scenarios // STATUS: ReturnStatus: AMD_COMGR_STATUS_SUCCESS -// OUT-NA-NA-NA: File System: Real +// OUT-NA-NA-NA: File System: VFS // OUT-NA-VFS-NOVFS: File System: VFS // OUT-NA-VFS-NA: File System: VFS // OUT-NA-NOVFS-VFS: File System: Real diff --git a/external/llvm-project/amd/comgr/test/source/multiple-note-records-one-kernel.s b/external/llvm-project/amd/comgr/test/source/multiple-note-records-one-kernel.s index 026cd939cc9a..48ba0e5a1683 100644 --- a/external/llvm-project/amd/comgr/test/source/multiple-note-records-one-kernel.s +++ b/external/llvm-project/amd/comgr/test/source/multiple-note-records-one-kernel.s @@ -120,7 +120,7 @@ _ZN17__HIP_CoordinatesI14__HIP_BlockDimE1xE: .zero 1 .size _ZN17__HIP_CoordinatesI14__HIP_BlockDimE1xE, 1 - .ident "AMD clang version 17.0.0 (https://github.com/RadeonOpenCompute/llvm-project roc-6.0.0 23483 7208e8d15fbf218deb74483ea8c549c67ca4985e)" + .ident "AMD clang version 17.0.0 (https://github.com/ROCm/llvm-project roc-6.0.0 23483 7208e8d15fbf218deb74483ea8c549c67ca4985e)" .section ".note.GNU-stack" .addrsig .amdgpu_metadata diff --git a/external/llvm-project/amd/comgr/test/source/multiple-note-records.s b/external/llvm-project/amd/comgr/test/source/multiple-note-records.s index 553deff220ab..ee268bd9b39f 100644 --- a/external/llvm-project/amd/comgr/test/source/multiple-note-records.s +++ b/external/llvm-project/amd/comgr/test/source/multiple-note-records.s @@ -216,7 +216,7 @@ _ZN17__HIP_CoordinatesI14__HIP_BlockDimE1xE: .zero 1 .size _ZN17__HIP_CoordinatesI14__HIP_BlockDimE1xE, 1 - .ident "AMD clang version 17.0.0 (https://github.com/RadeonOpenCompute/llvm-project roc-6.0.0 23483 7208e8d15fbf218deb74483ea8c549c67ca4985e)" + .ident "AMD clang version 17.0.0 (https://github.com/ROCm/llvm-project roc-6.0.0 23483 7208e8d15fbf218deb74483ea8c549c67ca4985e)" .section ".note.GNU-stack" .addrsig .amdgpu_metadata diff --git a/external/llvm-project/amd/device-libs/CMakeLists.txt b/external/llvm-project/amd/device-libs/CMakeLists.txt index b6cb5f28c425..a0d82249bfee 100644 --- a/external/llvm-project/amd/device-libs/CMakeLists.txt +++ b/external/llvm-project/amd/device-libs/CMakeLists.txt @@ -106,7 +106,7 @@ if(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR) set ( CPACK_PACKAGE_DESCRIPTION_SUMMARY "Radeon Open Compute - device libraries" ) set ( CPACK_PACKAGE_DESCRIPTION "This package includes LLVM bitcode libraries." ) set ( CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE.TXT" ) - set ( CPACK_DEBIAN_PACKAGE_HOMEPAGE "https://github.com/RadeonOpenCompute/ROCm-Device-Libs" ) + set ( CPACK_DEBIAN_PACKAGE_HOMEPAGE "https://github.com/ROCm/llvm-project/tree/amd-staging/amd/device-libs" ) # Install License file install ( FILES "${CPACK_RESOURCE_FILE_LICENSE}" diff --git a/external/llvm-project/amd/device-libs/opencl/src/devenq/schedule_rocm.cl b/external/llvm-project/amd/device-libs/opencl/src/devenq/schedule_rocm.cl index 731da8853e72..209eebeebc02 100644 --- a/external/llvm-project/amd/device-libs/opencl/src/devenq/schedule_rocm.cl +++ b/external/llvm-project/amd/device-libs/opencl/src/devenq/schedule_rocm.cl @@ -61,16 +61,23 @@ min_command(uint slot_num, __global AmdAqlWrap* wraps) return minCommand; } +static inline bool +check_pcie_support(__global SchedulerParam* param) { + #define kInvalidWriteIndex (ulong)(-1) + return (param->write_index == kInvalidWriteIndex) ? true : false; +} + static inline void EnqueueDispatch(__global hsa_kernel_dispatch_packet_t* aqlPkt, __global SchedulerParam* param) { __global hsa_queue_t* child_queue = param->child_queue; - - // ulong index = __ockl_hsa_queue_add_write_index(child_queue, 1, __ockl_memory_order_relaxed); - // The original code seen above relies on PCIe 3 atomics, which might not be supported on some systems, so use a device side global - // for workaround. - ulong index = atomic_fetch_add_explicit((__global atomic_ulong*)¶m->write_index, (ulong)1, memory_order_relaxed, memory_scope_device); + ulong index; + if (check_pcie_support(param)) { + index = __ockl_hsa_queue_add_write_index(child_queue, 1, __ockl_memory_order_relaxed); + } else { + index = atomic_fetch_add_explicit((__global atomic_ulong*)¶m->write_index, (ulong)1, memory_order_relaxed, memory_scope_device); + } const ulong queueMask = child_queue->size - 1; __global hsa_kernel_dispatch_packet_t* dispatch_packet = &(((__global hsa_kernel_dispatch_packet_t*)(child_queue->base_address))[index & queueMask]); @@ -82,17 +89,20 @@ EnqueueScheduler(__global SchedulerParam* param) { __global hsa_queue_t* child_queue = param->child_queue; - // ulong index = __ockl_hsa_queue_add_write_index(child_queue, 1, __ockl_memory_order_relaxed); - // The original code seen above relies on PCIe 3 atomics, which might not be supported on some systems, so use a device side global - // for workaround. - ulong index = atomic_fetch_add_explicit((__global atomic_ulong*)¶m->write_index, (ulong)1, memory_order_relaxed, memory_scope_device); + ulong index; + if (check_pcie_support(param)) { + index = __ockl_hsa_queue_add_write_index(child_queue, 1, __ockl_memory_order_relaxed); + } else { + index = atomic_fetch_add_explicit((__global atomic_ulong*)¶m->write_index, (ulong)1, memory_order_relaxed, memory_scope_device); + } const ulong queueMask = child_queue->size - 1; __global hsa_kernel_dispatch_packet_t* dispatch_packet = &(((__global hsa_kernel_dispatch_packet_t*)(child_queue->base_address))[index & queueMask]); *dispatch_packet = param->scheduler_aql; - // This is part of the PCIe 3 atomics workaround, to write the final write_index value back to the child_queue - __ockl_hsa_queue_store_write_index(child_queue, index + 1, __ockl_memory_order_relaxed); + if (!check_pcie_support(param)) { + __ockl_hsa_queue_store_write_index(child_queue, index + 1, __ockl_memory_order_relaxed); + } __ockl_hsa_signal_store(child_queue->doorbell_signal, index, __ockl_memory_order_release); } diff --git a/external/llvm-project/amd/hipcc/CMakeLists.txt b/external/llvm-project/amd/hipcc/CMakeLists.txt index 53f472c66e45..7512aa93baaa 100755 --- a/external/llvm-project/amd/hipcc/CMakeLists.txt +++ b/external/llvm-project/amd/hipcc/CMakeLists.txt @@ -70,7 +70,7 @@ set(CPACK_DEB_COMPONENT_INSTALL ON) set(CPACK_DEBIAN_FILE_NAME "DEB-DEFAULT") set(CPACK_DEBIAN_PACKAGE_DEPENDS "rocm-core") set(CPACK_DEBIAN_PACKAGE_RECOMMENDS "perl (>= 5.0)") -set(CPACK_DEBIAN_PACKAGE_HOMEPAGE "https://github.com/ROCm-Developer-Tools/HIPCC") +set(CPACK_DEBIAN_PACKAGE_HOMEPAGE "https://github.com/ROCm/llvm-project/tree/amd-staging/amd/hipcc") if(DEFINED ENV{CPACK_DEBIAN_PACKAGE_RELEASE}) set(CPACK_DEBIAN_PACKAGE_RELEASE $ENV{CPACK_DEBIAN_PACKAGE_RELEASE}) else() diff --git a/external/llvm-project/amd/utils/translate-legacy-branch-to-omnibus-monorepo.sh b/external/llvm-project/amd/utils/translate-legacy-branch-to-omnibus-monorepo.sh index d7c6ef65de24..49551cd7089c 100755 --- a/external/llvm-project/amd/utils/translate-legacy-branch-to-omnibus-monorepo.sh +++ b/external/llvm-project/amd/utils/translate-legacy-branch-to-omnibus-monorepo.sh @@ -13,15 +13,15 @@ #| #| Value Repository #| ----------- --------------------------------------------------------- -#| comgr https://github.com/RadeonOpenCompute/ROCm-CompilerSupport -#| device-libs https://github.com/RadeonOpenCompute/ROCm-Device-Libs -#| hipcc https://github.com/ROCm-Developer-Tools/HIPCC +#| comgr https://github.com/ROCm/llvm-project/tree/amd-staging/amd/comgr +#| device-libs https://github.com/ROCm/llvm-project/tree/amd-staging/amd/device-libs +#| hipcc https://github.com/ROCm/llvm-project/tree/amd-staging/amd/hipcc #| #| BASE-BRANCH identifies the branch upon which the to-be-translated branch is #| based (e.g. amd-stg-open). #| #| The TARGET-REPO-DIR must locate a fresh clone of the ROCm llvm-project -#| repository (https://github.com/RadeonOpenCompute/llvm-project). If the +#| repository (https://github.com/ROCm/llvm-project). If the #| script is to be invoked repeatedly the same clone may be reused. It is #| NOT recommended to use any clone which contains local refs that have not #| been saved elsewhere, as they may be clobbered! diff --git a/external/llvm-project/bolt/include/bolt/Core/BinaryBasicBlock.h b/external/llvm-project/bolt/include/bolt/Core/BinaryBasicBlock.h index 25cccc4edecf..629f0ce8314d 100644 --- a/external/llvm-project/bolt/include/bolt/Core/BinaryBasicBlock.h +++ b/external/llvm-project/bolt/include/bolt/Core/BinaryBasicBlock.h @@ -52,9 +52,8 @@ class BinaryBasicBlock { uint64_t MispredictedCount; /// number of branches mispredicted bool operator<(const BinaryBranchInfo &Other) const { - return (Count < Other.Count) || - (Count == Other.Count && - MispredictedCount < Other.MispredictedCount); + return std::tie(Count, MispredictedCount) < + std::tie(Other.Count, Other.MispredictedCount); } }; diff --git a/external/llvm-project/bolt/include/bolt/Core/BinaryFunction.h b/external/llvm-project/bolt/include/bolt/Core/BinaryFunction.h index 6b22ff62c555..ca8b786f4ab6 100644 --- a/external/llvm-project/bolt/include/bolt/Core/BinaryFunction.h +++ b/external/llvm-project/bolt/include/bolt/Core/BinaryFunction.h @@ -388,6 +388,10 @@ class BinaryFunction { /// The profile data for the number of times the function was executed. uint64_t ExecutionCount{COUNT_NO_PROFILE}; + /// Profile data for the number of times this function was entered from + /// external code (DSO, JIT, etc). + uint64_t ExternEntryCount{0}; + /// Profile match ratio. float ProfileMatchRatio{0.0f}; @@ -1877,6 +1881,10 @@ class BinaryFunction { return *this; } + /// Set the profile data for the number of times the function was entered from + /// external code (DSO/JIT). + void setExternEntryCount(uint64_t Count) { ExternEntryCount = Count; } + /// Adjust execution count for the function by a given \p Count. The value /// \p Count will be subtracted from the current function count. /// @@ -1904,6 +1912,10 @@ class BinaryFunction { /// Return COUNT_NO_PROFILE if there's no profile info. uint64_t getExecutionCount() const { return ExecutionCount; } + /// Return the profile information about the number of times the function was + /// entered from external code (DSO/JIT). + uint64_t getExternEntryCount() const { return ExternEntryCount; } + /// Return the raw profile information about the number of branch /// executions corresponding to this function. uint64_t getRawSampleCount() const { return RawSampleCount; } @@ -2348,6 +2360,7 @@ class BinaryFunction { releaseCFG(); CurrentState = State::Emitted; } + clearList(Relocations); } /// Process LSDA information for the function. diff --git a/external/llvm-project/bolt/include/bolt/Core/MCPlusBuilder.h b/external/llvm-project/bolt/include/bolt/Core/MCPlusBuilder.h index b23345298550..804100db8079 100644 --- a/external/llvm-project/bolt/include/bolt/Core/MCPlusBuilder.h +++ b/external/llvm-project/bolt/include/bolt/Core/MCPlusBuilder.h @@ -405,7 +405,7 @@ class MCPlusBuilder { bool equals(const MCExpr &A, const MCExpr &B, CompFuncTy Comp) const; - virtual bool equals(const MCTargetExpr &A, const MCTargetExpr &B, + virtual bool equals(const MCSpecifierExpr &A, const MCSpecifierExpr &B, CompFuncTy Comp) const; virtual bool isBranch(const MCInst &Inst) const { diff --git a/external/llvm-project/bolt/include/bolt/Passes/PAuthGadgetScanner.h b/external/llvm-project/bolt/include/bolt/Passes/PAuthGadgetScanner.h index 98a49df862eb..c6b9cc2eb4b9 100644 --- a/external/llvm-project/bolt/include/bolt/Passes/PAuthGadgetScanner.h +++ b/external/llvm-project/bolt/include/bolt/Passes/PAuthGadgetScanner.h @@ -77,9 +77,7 @@ struct MCInstInBFReference { return BF == RHS.BF && Offset == RHS.Offset; } bool operator<(const MCInstInBFReference &RHS) const { - if (BF != RHS.BF) - return BF < RHS.BF; - return Offset < RHS.Offset; + return std::tie(BF, Offset) < std::tie(RHS.BF, RHS.Offset); } operator MCInst &() const { assert(BF != nullptr); diff --git a/external/llvm-project/bolt/include/bolt/Profile/DataAggregator.h b/external/llvm-project/bolt/include/bolt/Profile/DataAggregator.h index 6d918134137d..3f07a6dc03a4 100644 --- a/external/llvm-project/bolt/include/bolt/Profile/DataAggregator.h +++ b/external/llvm-project/bolt/include/bolt/Profile/DataAggregator.h @@ -78,6 +78,13 @@ class DataAggregator : public DataReader { static bool checkPerfDataMagic(StringRef FileName); private: + struct LBREntry { + uint64_t From; + uint64_t To; + bool Mispred; + }; + friend raw_ostream &operator<<(raw_ostream &OS, const LBREntry &); + struct PerfBranchSample { SmallVector LBR; }; @@ -370,33 +377,46 @@ class DataAggregator : public DataReader { /// memory. /// /// File format syntax: - /// {B|F|f|T} [:] [:] [] - /// [] + /// E + /// S + /// T + /// B + /// [Ff] + /// + /// where , , have the format [:] /// - /// B - indicates an aggregated branch - /// F - an aggregated fall-through + /// E - name of the sampling event used for subsequent entries + /// S - indicates an aggregated basic sample at + /// B - indicates an aggregated branch from to + /// F - an aggregated fall-through from to /// f - an aggregated fall-through with external origin - used to disambiguate /// between a return hitting a basic block head and a regular internal /// jump to the block - /// T - an aggregated trace: branch with a fall-through (from, to, ft_end) + /// T - an aggregated trace: branch from to with a fall-through + /// to /// - /// - build id of the object containing the start address. We can - /// skip it for the main binary and use "X" for an unknown object. This will - /// save some space and facilitate human parsing. + /// - build id of the object containing the address. We can skip it for + /// the main binary and use "X" for an unknown object. This will save some + /// space and facilitate human parsing. /// - /// - hex offset from the object base load address (0 for the - /// main executable unless it's PIE) to the start address. + /// - hex offset from the object base load address (0 for the + /// main executable unless it's PIE) to the address. /// - /// , - same for the end address. - /// - /// - same for the fallthrough_end address. - /// - /// - total aggregated count of the branch or a fall-through. + /// - total aggregated count. /// /// - the number of times the branch was mispredicted. - /// Omitted for fall-throughs. /// /// Example: + /// Basic samples profile: + /// E cycles + /// S 41be50 3 + /// E br_inst_retired.near_taken + /// S 41be60 6 + /// + /// Trace profile combining branches and fall-throughs: + /// T 4b196f 4b19e0 4b19ef 2 + /// + /// Legacy branch profile with separate branches and fall-throughs: /// F 41be50 41be50 3 /// F 41be90 41be90 4 /// B 4b1942 39b57f0 3 0 @@ -463,7 +483,6 @@ class DataAggregator : public DataReader { /// Debugging dump methods void dump() const; - void dump(const LBREntry &LBR) const; void dump(const PerfBranchSample &Sample) const; void dump(const PerfMemSample &Sample) const; @@ -491,6 +510,12 @@ class DataAggregator : public DataReader { friend class YAMLProfileWriter; }; + +inline raw_ostream &operator<<(raw_ostream &OS, + const DataAggregator::LBREntry &L) { + OS << formatv("{0:x} -> {1:x}/{2}", L.From, L.To, L.Mispred ? 'M' : 'P'); + return OS; +} } // namespace bolt } // namespace llvm diff --git a/external/llvm-project/bolt/include/bolt/Profile/DataReader.h b/external/llvm-project/bolt/include/bolt/Profile/DataReader.h index 5df1b5a8f4a0..6f527ba3931d 100644 --- a/external/llvm-project/bolt/include/bolt/Profile/DataReader.h +++ b/external/llvm-project/bolt/include/bolt/Profile/DataReader.h @@ -32,18 +32,6 @@ namespace bolt { class BinaryFunction; -struct LBREntry { - uint64_t From; - uint64_t To; - bool Mispred; -}; - -inline raw_ostream &operator<<(raw_ostream &OS, const LBREntry &LBR) { - OS << "0x" << Twine::utohexstr(LBR.From) << " -> 0x" - << Twine::utohexstr(LBR.To); - return OS; -} - struct Location { bool IsSymbol; StringRef Name; @@ -109,6 +97,9 @@ struct FuncBranchData { /// Total execution count for the function. int64_t ExecutionCount{0}; + /// Total entry count from external code for the function. + uint64_t ExternEntryCount{0}; + /// Indicate if the data was used. bool Used{false}; diff --git a/external/llvm-project/bolt/include/bolt/Profile/ProfileYAMLMapping.h b/external/llvm-project/bolt/include/bolt/Profile/ProfileYAMLMapping.h index a8d9a15311d9..41e2bd1651ef 100644 --- a/external/llvm-project/bolt/include/bolt/Profile/ProfileYAMLMapping.h +++ b/external/llvm-project/bolt/include/bolt/Profile/ProfileYAMLMapping.h @@ -206,6 +206,7 @@ struct BinaryFunctionProfile { uint32_t Id{0}; llvm::yaml::Hex64 Hash{0}; uint64_t ExecCount{0}; + uint64_t ExternEntryCount{0}; std::vector Blocks; std::vector InlineTree; bool Used{false}; @@ -218,6 +219,7 @@ template <> struct MappingTraits { YamlIO.mapRequired("fid", BFP.Id); YamlIO.mapRequired("hash", BFP.Hash); YamlIO.mapRequired("exec", BFP.ExecCount); + YamlIO.mapOptional("extern", BFP.ExternEntryCount, 0); YamlIO.mapRequired("nblocks", BFP.NumBasicBlocks); YamlIO.mapOptional("blocks", BFP.Blocks, std::vector()); diff --git a/external/llvm-project/bolt/lib/Core/BinaryContext.cpp b/external/llvm-project/bolt/lib/Core/BinaryContext.cpp index 36b789d42936..84f185346970 100644 --- a/external/llvm-project/bolt/lib/Core/BinaryContext.cpp +++ b/external/llvm-project/bolt/lib/Core/BinaryContext.cpp @@ -1032,10 +1032,8 @@ void BinaryContext::adjustCodePadding() { if (!hasValidCodePadding(BF)) { if (HasRelocations) { - if (opts::Verbosity >= 1) { - this->outs() << "BOLT-INFO: function " << BF - << " has invalid padding. Ignoring the function.\n"; - } + this->errs() << "BOLT-WARNING: function " << BF + << " has invalid padding. Ignoring the function\n"; BF.setIgnored(); } else { BF.setMaxSize(BF.getSize()); diff --git a/external/llvm-project/bolt/lib/Core/BinaryFunction.cpp b/external/llvm-project/bolt/lib/Core/BinaryFunction.cpp index ceb9390b546e..b998d7160aae 100644 --- a/external/llvm-project/bolt/lib/Core/BinaryFunction.cpp +++ b/external/llvm-project/bolt/lib/Core/BinaryFunction.cpp @@ -471,6 +471,8 @@ void BinaryFunction::print(raw_ostream &OS, std::string Annotation) { OS << "\n Sample Count: " << RawSampleCount; OS << "\n Profile Acc : " << format("%.1f%%", ProfileMatchRatio * 100.0f); } + if (ExternEntryCount) + OS << "\n Extern Entry Count: " << ExternEntryCount; if (opts::PrintDynoStats && !getLayout().block_empty()) { OS << '\n'; @@ -1526,8 +1528,6 @@ Error BinaryFunction::disassemble() { if (uint64_t Offset = getFirstInstructionOffset()) Labels[Offset] = BC.Ctx->createNamedTempSymbol(); - clearList(Relocations); - if (!IsSimple) { clearList(Instructions); return createNonFatalBOLTError(""); @@ -3244,16 +3244,26 @@ void BinaryFunction::setTrapOnEntry() { } void BinaryFunction::setIgnored() { + IsIgnored = true; + if (opts::processAllFunctions()) { // We can accept ignored functions before they've been disassembled. - // In that case, they would still get disassembled and emited, but not + // In that case, they would still get disassembled and emitted, but not // optimized. - assert(CurrentState == State::Empty && - "cannot ignore non-empty functions in current mode"); - IsIgnored = true; + if (CurrentState != State::Empty) { + BC.errs() << "BOLT-ERROR: cannot ignore non-empty function " << *this + << " in current mode\n"; + exit(1); + } return; } + IsSimple = false; + LLVM_DEBUG(dbgs() << "Ignoring " << getPrintName() << '\n'); + + if (CurrentState == State::Empty) + return; + clearDisasmState(); // Clear CFG state too. @@ -3273,9 +3283,11 @@ void BinaryFunction::setIgnored() { CurrentState = State::Empty; - IsIgnored = true; - IsSimple = false; - LLVM_DEBUG(dbgs() << "Ignoring " << getPrintName() << '\n'); + // Fix external references in the original function body. + if (BC.HasRelocations) { + LLVM_DEBUG(dbgs() << "Scanning refs in " << *this << '\n'); + scanExternalRefs(); + } } void BinaryFunction::duplicateConstantIslands() { @@ -3764,7 +3776,6 @@ void BinaryFunction::postProcessBranches() { MCSymbol *BinaryFunction::addEntryPointAtOffset(uint64_t Offset) { assert(Offset && "cannot add primary entry point"); - assert(CurrentState == State::Empty || CurrentState == State::Disassembled); const uint64_t EntryPointAddress = getAddress() + Offset; MCSymbol *LocalSymbol = getOrCreateLocalLabel(EntryPointAddress); @@ -3773,6 +3784,8 @@ MCSymbol *BinaryFunction::addEntryPointAtOffset(uint64_t Offset) { if (EntrySymbol) return EntrySymbol; + assert(CurrentState == State::Empty || CurrentState == State::Disassembled); + if (BinaryData *EntryBD = BC.getBinaryDataAtAddress(EntryPointAddress)) { EntrySymbol = EntryBD->getSymbol(); } else { diff --git a/external/llvm-project/bolt/lib/Core/HashUtilities.cpp b/external/llvm-project/bolt/lib/Core/HashUtilities.cpp index 6bdf30460f34..e01768387d6c 100644 --- a/external/llvm-project/bolt/lib/Core/HashUtilities.cpp +++ b/external/llvm-project/bolt/lib/Core/HashUtilities.cpp @@ -67,6 +67,7 @@ std::string hashExpr(BinaryContext &BC, const MCExpr &Expr) { .append(hashInteger(BinaryExpr.getOpcode())) .append(hashExpr(BC, *BinaryExpr.getRHS())); } + case MCExpr::Specifier: case MCExpr::Target: return std::string(); } diff --git a/external/llvm-project/bolt/lib/Core/MCPlusBuilder.cpp b/external/llvm-project/bolt/lib/Core/MCPlusBuilder.cpp index 7752079b6153..fa8f4d1df308 100644 --- a/external/llvm-project/bolt/lib/Core/MCPlusBuilder.cpp +++ b/external/llvm-project/bolt/lib/Core/MCPlusBuilder.cpp @@ -114,17 +114,19 @@ bool MCPlusBuilder::equals(const MCExpr &A, const MCExpr &B, equals(*BinaryA.getRHS(), *BinaryB.getRHS(), Comp); } - case MCExpr::Target: { - const auto &TargetExprA = cast(A); - const auto &TargetExprB = cast(B); + case MCExpr::Specifier: { + const auto &TargetExprA = cast(A); + const auto &TargetExprB = cast(B); return equals(TargetExprA, TargetExprB, Comp); } + case MCExpr::Target: + llvm_unreachable("Not implemented"); } llvm_unreachable("Invalid expression kind!"); } -bool MCPlusBuilder::equals(const MCTargetExpr &A, const MCTargetExpr &B, +bool MCPlusBuilder::equals(const MCSpecifierExpr &A, const MCSpecifierExpr &B, CompFuncTy Comp) const { llvm_unreachable("target-specific expressions are unsupported"); } diff --git a/external/llvm-project/bolt/lib/Passes/ADRRelaxationPass.cpp b/external/llvm-project/bolt/lib/Passes/ADRRelaxationPass.cpp index 4b37a061ac12..c3954c94a7f9 100644 --- a/external/llvm-project/bolt/lib/Passes/ADRRelaxationPass.cpp +++ b/external/llvm-project/bolt/lib/Passes/ADRRelaxationPass.cpp @@ -81,17 +81,15 @@ void ADRRelaxationPass::runOnFunction(BinaryFunction &BF) { It = BB.eraseInstruction(std::prev(It)); } else if (std::next(It) != BB.end() && BC.MIB->isNoop(*std::next(It))) { BB.eraseInstruction(std::next(It)); - } else if (!opts::StrictMode && !BF.isSimple()) { + } else if (!BF.isSimple()) { // If the function is not simple, it may contain a jump table undetected // by us. This jump table may use an offset from the branch instruction // to land in the desired place. If we add new instructions, we // invalidate this offset, so we have to rely on linker-inserted NOP to // replace it with ADRP, and abort if it is not present. auto L = BC.scopeLock(); - BC.errs() << formatv( - "BOLT-ERROR: Cannot relax adr in non-simple function " - "{0}. Use --strict option to override\n", - BF.getOneName()); + BC.errs() << "BOLT-ERROR: cannot relax ADR in non-simple function " + << BF << '\n'; PassFailed = true; return; } diff --git a/external/llvm-project/bolt/lib/Passes/ProfileQualityStats.cpp b/external/llvm-project/bolt/lib/Passes/ProfileQualityStats.cpp index dfd74d3dd571..64cc662c3ab2 100644 --- a/external/llvm-project/bolt/lib/Passes/ProfileQualityStats.cpp +++ b/external/llvm-project/bolt/lib/Passes/ProfileQualityStats.cpp @@ -532,6 +532,9 @@ void computeFlowMappings(const BinaryContext &BC, FlowInfo &TotalFlowMap) { std::vector &MaxCountMap = TotalMaxCountMaps[FunctionNum]; std::vector &MinCountMap = TotalMinCountMaps[FunctionNum]; + // Record external entry count into CallGraphIncomingFlows + CallGraphIncomingFlows[FunctionNum] += Function->getExternEntryCount(); + // Update MaxCountMap, MinCountMap, and CallGraphIncomingFlows auto recordCall = [&](const BinaryBasicBlock *SourceBB, const MCSymbol *DestSymbol, uint64_t Count, diff --git a/external/llvm-project/bolt/lib/Passes/RetpolineInsertion.cpp b/external/llvm-project/bolt/lib/Passes/RetpolineInsertion.cpp index 98e5a8fba645..bda26206e16c 100644 --- a/external/llvm-project/bolt/lib/Passes/RetpolineInsertion.cpp +++ b/external/llvm-project/bolt/lib/Passes/RetpolineInsertion.cpp @@ -195,7 +195,7 @@ std::string createRetpolineFunctionTag(BinaryContext &BC, TagOS << "+"; if (MemRef.DispExpr) - MemRef.DispExpr->print(TagOS, BC.AsmInfo.get()); + BC.AsmInfo->printExpr(TagOS, *MemRef.DispExpr); else TagOS << MemRef.DispImm; diff --git a/external/llvm-project/bolt/lib/Profile/DataAggregator.cpp b/external/llvm-project/bolt/lib/Profile/DataAggregator.cpp index d0620b64cad2..ade8478f556e 100644 --- a/external/llvm-project/bolt/lib/Profile/DataAggregator.cpp +++ b/external/llvm-project/bolt/lib/Profile/DataAggregator.cpp @@ -61,6 +61,12 @@ FilterMemProfile("filter-mem-profile", cl::init(true), cl::cat(AggregatorCategory)); +static cl::opt ParseMemProfile( + "parse-mem-profile", + cl::desc("enable memory profile parsing if it's present in the input data, " + "on by default unless `--itrace` is set."), + cl::init(true), cl::cat(AggregatorCategory)); + static cl::opt FilterPID("pid", cl::desc("only use samples from process with specified PID"), @@ -181,6 +187,10 @@ void DataAggregator::start() { "script -F pid,event,ip", /*Wait = */false); } else if (!opts::ITraceAggregation.empty()) { + // Disable parsing memory profile from trace data, unless requested by user. + if (!opts::ParseMemProfile.getNumOccurrences()) + opts::ParseMemProfile = false; + std::string ItracePerfScriptArgs = llvm::formatv( "script -F pid,brstack --itrace={0}", opts::ITraceAggregation); launchPerfProcess("branch events with itrace", MainEventsPPI, @@ -191,12 +201,9 @@ void DataAggregator::start() { /*Wait = */ false); } - // Note: we launch script for mem events regardless of the option, as the - // command fails fairly fast if mem events were not collected. - launchPerfProcess("mem events", - MemEventsPPI, - "script -F pid,event,addr,ip", - /*Wait = */false); + if (opts::ParseMemProfile) + launchPerfProcess("mem events", MemEventsPPI, "script -F pid,event,addr,ip", + /*Wait = */ false); launchPerfProcess("process events", MMapEventsPPI, "script --show-mmap-events --no-itrace", @@ -217,7 +224,8 @@ void DataAggregator::abort() { sys::Wait(TaskEventsPPI.PI, 1, &Error); sys::Wait(MMapEventsPPI.PI, 1, &Error); sys::Wait(MainEventsPPI.PI, 1, &Error); - sys::Wait(MemEventsPPI.PI, 1, &Error); + if (opts::ParseMemProfile) + sys::Wait(MemEventsPPI.PI, 1, &Error); deleteTempFiles(); @@ -506,7 +514,8 @@ Error DataAggregator::preprocessProfile(BinaryContext &BC) { errs() << "PERF2BOLT: failed to parse samples\n"; // Special handling for memory events - if (!prepareToParse("mem events", MemEventsPPI, MemEventsErrorCallback)) + if (opts::ParseMemProfile && + !prepareToParse("mem events", MemEventsPPI, MemEventsErrorCallback)) if (const std::error_code EC = parseMemEvents()) errs() << "PERF2BOLT: failed to parse memory events: " << EC.message() << '\n'; @@ -580,8 +589,10 @@ void DataAggregator::processProfile(BinaryContext &BC) { } } - for (auto &FuncBranches : NamesToBranches) + for (auto &FuncBranches : NamesToBranches) { llvm::stable_sort(FuncBranches.second.Data); + llvm::stable_sort(FuncBranches.second.EntryData); + } for (auto &MemEvents : NamesToMemEvents) llvm::stable_sort(MemEvents.second.Data); @@ -733,8 +744,10 @@ bool DataAggregator::doBranch(uint64_t From, uint64_t To, uint64_t Count, // corresponds to a return (if \p IsFrom) or a call continuation (otherwise). auto handleAddress = [&](uint64_t &Addr, bool IsFrom) { BinaryFunction *Func = getBinaryFunctionContainingAddress(Addr); - if (!Func) + if (!Func) { + Addr = 0; return std::pair{Func, false}; + } Addr -= Func->getAddress(); @@ -972,7 +985,7 @@ bool DataAggregator::recordExit(BinaryFunction &BF, uint64_t From, bool Mispred, return true; } -ErrorOr DataAggregator::parseLBREntry() { +ErrorOr DataAggregator::parseLBREntry() { LBREntry Res; ErrorOr FromStrRes = parseString('/'); if (std::error_code EC = FromStrRes.getError()) @@ -1204,60 +1217,74 @@ ErrorOr DataAggregator::parseLocationOrOffset() { } std::error_code DataAggregator::parseAggregatedLBREntry() { - while (checkAndConsumeFS()) { - } + enum AggregatedLBREntry : char { + INVALID = 0, + EVENT_NAME, // E + TRACE, // T + SAMPLE, // S + BRANCH, // B + FT, // F + FT_EXTERNAL_ORIGIN // f + } Type = INVALID; + + // The number of fields to parse, set based on Type. + int AddrNum = 0; + int CounterNum = 0; + // Storage for parsed fields. + StringRef EventName; + std::optional Addr[3]; + int64_t Counters[2] = {0}; + + while (Type == INVALID || Type == EVENT_NAME) { + while (checkAndConsumeFS()) { + } + ErrorOr StrOrErr = + parseString(FieldSeparator, Type == EVENT_NAME); + if (std::error_code EC = StrOrErr.getError()) + return EC; + StringRef Str = StrOrErr.get(); - ErrorOr TypeOrErr = parseString(FieldSeparator); - if (std::error_code EC = TypeOrErr.getError()) - return EC; - enum AggregatedLBREntry { TRACE, BRANCH, FT, FT_EXTERNAL_ORIGIN, INVALID }; - auto Type = StringSwitch(TypeOrErr.get()) - .Case("T", TRACE) - .Case("B", BRANCH) - .Case("F", FT) - .Case("f", FT_EXTERNAL_ORIGIN) - .Default(INVALID); - if (Type == INVALID) { - reportError("expected T, B, F or f"); - return make_error_code(llvm::errc::io_error); - } + if (Type == EVENT_NAME) { + EventName = Str; + break; + } - while (checkAndConsumeFS()) { - } - ErrorOr From = parseLocationOrOffset(); - if (std::error_code EC = From.getError()) - return EC; + Type = StringSwitch(Str) + .Case("T", TRACE) + .Case("S", SAMPLE) + .Case("E", EVENT_NAME) + .Case("B", BRANCH) + .Case("F", FT) + .Case("f", FT_EXTERNAL_ORIGIN) + .Default(INVALID); + + if (Type == INVALID) { + reportError("expected T, S, E, B, F or f"); + return make_error_code(llvm::errc::io_error); + } - while (checkAndConsumeFS()) { + using SSI = StringSwitch; + AddrNum = SSI(Str).Case("T", 3).Case("S", 1).Case("E", 0).Default(2); + CounterNum = SSI(Str).Case("B", 2).Case("E", 0).Default(1); } - ErrorOr To = parseLocationOrOffset(); - if (std::error_code EC = To.getError()) - return EC; - ErrorOr TraceFtEnd = std::error_code(); - if (Type == AggregatedLBREntry::TRACE) { + for (int I = 0; I < AddrNum; ++I) { while (checkAndConsumeFS()) { } - TraceFtEnd = parseLocationOrOffset(); - if (std::error_code EC = TraceFtEnd.getError()) + ErrorOr AddrOrErr = parseLocationOrOffset(); + if (std::error_code EC = AddrOrErr.getError()) return EC; + Addr[I] = AddrOrErr.get(); } - while (checkAndConsumeFS()) { - } - ErrorOr Frequency = - parseNumberField(FieldSeparator, Type != AggregatedLBREntry::BRANCH); - if (std::error_code EC = Frequency.getError()) - return EC; - - uint64_t Mispreds = 0; - if (Type == AggregatedLBREntry::BRANCH) { + for (int I = 0; I < CounterNum; ++I) { while (checkAndConsumeFS()) { } - ErrorOr MispredsOrErr = parseNumberField(FieldSeparator, true); - if (std::error_code EC = MispredsOrErr.getError()) + ErrorOr CountOrErr = + parseNumberField(FieldSeparator, I + 1 == CounterNum); + if (std::error_code EC = CountOrErr.getError()) return EC; - Mispreds = static_cast(MispredsOrErr.get()); + Counters[I] = CountOrErr.get(); } if (!checkAndConsumeNewLine()) { @@ -1265,16 +1292,31 @@ std::error_code DataAggregator::parseAggregatedLBREntry() { return make_error_code(llvm::errc::io_error); } - BinaryFunction *FromFunc = getBinaryFunctionContainingAddress(From->Offset); - BinaryFunction *ToFunc = getBinaryFunctionContainingAddress(To->Offset); + if (Type == EVENT_NAME) { + EventNames.insert(EventName); + return std::error_code(); + } - for (BinaryFunction *BF : {FromFunc, ToFunc}) - if (BF) - BF->setHasProfileAvailable(); + const uint64_t FromOffset = Addr[0]->Offset; + BinaryFunction *FromFunc = getBinaryFunctionContainingAddress(FromOffset); + if (FromFunc) + FromFunc->setHasProfileAvailable(); + + int64_t Count = Counters[0]; + int64_t Mispreds = Counters[1]; + + if (Type == SAMPLE) { + BasicSamples[FromOffset] += Count; + NumTotalSamples += Count; + return std::error_code(); + } - uint64_t Count = static_cast(Frequency.get()); + const uint64_t ToOffset = Addr[1]->Offset; + BinaryFunction *ToFunc = getBinaryFunctionContainingAddress(ToOffset); + if (ToFunc) + ToFunc->setHasProfileAvailable(); - Trace Trace(From->Offset, To->Offset); + Trace Trace(FromOffset, ToOffset); // Taken trace if (Type == TRACE || Type == BRANCH) { TakenBranchInfo &Info = BranchLBRs[Trace]; @@ -1285,8 +1327,9 @@ std::error_code DataAggregator::parseAggregatedLBREntry() { } // Construct fallthrough part of the trace if (Type == TRACE) { - Trace.From = To->Offset; - Trace.To = TraceFtEnd->Offset; + const uint64_t TraceFtEndOffset = Addr[2]->Offset; + Trace.From = ToOffset; + Trace.To = TraceFtEndOffset; Type = FromFunc == ToFunc ? FT : FT_EXTERNAL_ORIGIN; } // Add fallthrough trace @@ -1400,54 +1443,16 @@ void DataAggregator::parseLBRSample(const PerfBranchSample &Sample, const uint64_t TraceTo = NextLBR->From; const BinaryFunction *TraceBF = getBinaryFunctionContainingAddress(TraceFrom); - if (opts::HeatmapMode == opts::HeatmapModeKind::HM_Exclusive) { - FTInfo &Info = FallthroughLBRs[Trace(TraceFrom, TraceTo)]; + FTInfo &Info = FallthroughLBRs[Trace(TraceFrom, TraceTo)]; + if (TraceBF && TraceBF->containsAddress(LBR.From)) ++Info.InternCount; - } else if (TraceBF && TraceBF->containsAddress(TraceTo)) { - FTInfo &Info = FallthroughLBRs[Trace(TraceFrom, TraceTo)]; - if (TraceBF->containsAddress(LBR.From)) - ++Info.InternCount; - else - ++Info.ExternCount; - } else { - const BinaryFunction *ToFunc = - getBinaryFunctionContainingAddress(TraceTo); - if (TraceBF && ToFunc) { - LLVM_DEBUG({ - dbgs() << "Invalid trace starting in " << TraceBF->getPrintName() - << formatv(" @ {0:x}", TraceFrom - TraceBF->getAddress()) - << formatv(" and ending @ {0:x}\n", TraceTo); - }); - ++NumInvalidTraces; - } else { - LLVM_DEBUG({ - dbgs() << "Out of range trace starting in " - << (TraceBF ? TraceBF->getPrintName() : "None") - << formatv(" @ {0:x}", - TraceFrom - (TraceBF ? TraceBF->getAddress() : 0)) - << " and ending in " - << (ToFunc ? ToFunc->getPrintName() : "None") - << formatv(" @ {0:x}\n", - TraceTo - (ToFunc ? ToFunc->getAddress() : 0)); - }); - ++NumLongRangeTraces; - } - } + else + ++Info.ExternCount; ++NumTraces; } NextLBR = &LBR; - // Record branches outside binary functions for heatmap. - if (opts::HeatmapMode == opts::HeatmapModeKind::HM_Exclusive) { - TakenBranchInfo &Info = BranchLBRs[Trace(LBR.From, LBR.To)]; - ++Info.TakenCount; - continue; - } - uint64_t From = getBinaryFunctionContainingAddress(LBR.From) ? LBR.From : 0; - uint64_t To = getBinaryFunctionContainingAddress(LBR.To) ? LBR.To : 0; - if (!From && !To) - continue; - TakenBranchInfo &Info = BranchLBRs[Trace(From, To)]; + TakenBranchInfo &Info = BranchLBRs[Trace(LBR.From, LBR.To)]; ++Info.TakenCount; Info.MispredCount += LBR.Mispred; } @@ -2259,6 +2264,7 @@ std::error_code DataAggregator::writeBATYAML(BinaryContext &BC, YamlBF.Id = BF->getFunctionNumber(); YamlBF.Hash = BAT->getBFHash(FuncAddress); YamlBF.ExecCount = BF->getKnownExecutionCount(); + YamlBF.ExternEntryCount = BF->getExternEntryCount(); YamlBF.NumBasicBlocks = BAT->getNumBasicBlocks(FuncAddress); const BoltAddressTranslation::BBHashMapTy &BlockMap = BAT->getBBHashMap(FuncAddress); @@ -2368,16 +2374,10 @@ std::error_code DataAggregator::writeBATYAML(BinaryContext &BC, void DataAggregator::dump() const { DataReader::dump(); } -void DataAggregator::dump(const LBREntry &LBR) const { - Diag << "From: " << Twine::utohexstr(LBR.From) - << " To: " << Twine::utohexstr(LBR.To) << " Mispred? " << LBR.Mispred - << "\n"; -} - void DataAggregator::dump(const PerfBranchSample &Sample) const { Diag << "Sample LBR entries: " << Sample.LBR.size() << "\n"; for (const LBREntry &LBR : Sample.LBR) - dump(LBR); + Diag << LBR << '\n'; } void DataAggregator::dump(const PerfMemSample &Sample) const { diff --git a/external/llvm-project/bolt/lib/Profile/DataReader.cpp b/external/llvm-project/bolt/lib/Profile/DataReader.cpp index c512394f26a3..afe24216d7f5 100644 --- a/external/llvm-project/bolt/lib/Profile/DataReader.cpp +++ b/external/llvm-project/bolt/lib/Profile/DataReader.cpp @@ -85,6 +85,7 @@ void FuncBranchData::appendFrom(const FuncBranchData &FBD, uint64_t Offset) { } llvm::stable_sort(Data); ExecutionCount += FBD.ExecutionCount; + ExternEntryCount += FBD.ExternEntryCount; for (auto I = FBD.EntryData.begin(), E = FBD.EntryData.end(); I != E; ++I) { assert(I->To.Name == FBD.Name); auto NewElmt = EntryData.insert(EntryData.end(), *I); @@ -269,6 +270,7 @@ Error DataReader::preprocessProfile(BinaryContext &BC) { if (FuncBranchData *FuncData = getBranchDataForNames(Function.getNames())) { setBranchData(Function, FuncData); Function.ExecutionCount = FuncData->ExecutionCount; + Function.ExternEntryCount = FuncData->ExternEntryCount; FuncData->Used = true; } } @@ -419,6 +421,7 @@ void DataReader::matchProfileData(BinaryFunction &BF) { if (fetchProfileForOtherEntryPoints(BF)) { BF.ProfileMatchRatio = evaluateProfileData(BF, *FBD); BF.ExecutionCount = FBD->ExecutionCount; + BF.ExternEntryCount = FBD->ExternEntryCount; BF.RawSampleCount = FBD->getNumExecutedBranches(); } return; @@ -449,6 +452,7 @@ void DataReader::matchProfileData(BinaryFunction &BF) { setBranchData(BF, NewBranchData); NewBranchData->Used = true; BF.ExecutionCount = NewBranchData->ExecutionCount; + BF.ExternEntryCount = NewBranchData->ExternEntryCount; BF.ProfileMatchRatio = 1.0f; break; } @@ -1190,6 +1194,8 @@ std::error_code DataReader::parse() { if (BI.To.IsSymbol && BI.To.Offset == 0) { I = GetOrCreateFuncEntry(BI.To.Name); I->second.ExecutionCount += BI.Branches; + if (!BI.From.IsSymbol) + I->second.ExternEntryCount += BI.Branches; } } diff --git a/external/llvm-project/bolt/lib/Profile/YAMLProfileReader.cpp b/external/llvm-project/bolt/lib/Profile/YAMLProfileReader.cpp index 33ce40ac2eee..086e47b661e1 100644 --- a/external/llvm-project/bolt/lib/Profile/YAMLProfileReader.cpp +++ b/external/llvm-project/bolt/lib/Profile/YAMLProfileReader.cpp @@ -176,6 +176,7 @@ bool YAMLProfileReader::parseFunctionProfile( uint64_t FunctionExecutionCount = 0; BF.setExecutionCount(YamlBF.ExecCount); + BF.setExternEntryCount(YamlBF.ExternEntryCount); uint64_t FuncRawBranchCount = 0; for (const yaml::bolt::BinaryBasicBlockProfile &YamlBB : YamlBF.Blocks) diff --git a/external/llvm-project/bolt/lib/Profile/YAMLProfileWriter.cpp b/external/llvm-project/bolt/lib/Profile/YAMLProfileWriter.cpp index f1fe45f21a0f..1632aa1c6bfe 100644 --- a/external/llvm-project/bolt/lib/Profile/YAMLProfileWriter.cpp +++ b/external/llvm-project/bolt/lib/Profile/YAMLProfileWriter.cpp @@ -226,6 +226,7 @@ YAMLProfileWriter::convert(const BinaryFunction &BF, bool UseDFS, YamlBF.Hash = BF.getHash(); YamlBF.NumBasicBlocks = BF.size(); YamlBF.ExecCount = BF.getKnownExecutionCount(); + YamlBF.ExternEntryCount = BF.getExternEntryCount(); DenseMap InlineTreeNodeId; if (PseudoProbeDecoder && BF.getGUID()) { std::tie(YamlBF.InlineTree, InlineTreeNodeId) = @@ -303,9 +304,8 @@ YAMLProfileWriter::convert(const BinaryFunction &BF, bool UseDFS, } // Sort targets in a similar way to getBranchData, see Location::operator< llvm::sort(CSTargets, [](const auto &RHS, const auto &LHS) { - if (RHS.first != LHS.first) - return RHS.first < LHS.first; - return RHS.second.Offset < LHS.second.Offset; + return std::tie(RHS.first, RHS.second.Offset) < + std::tie(LHS.first, LHS.second.Offset); }); for (auto &KV : CSTargets) YamlBB.CallSites.push_back(KV.second); diff --git a/external/llvm-project/bolt/lib/Rewrite/RewriteInstance.cpp b/external/llvm-project/bolt/lib/Rewrite/RewriteInstance.cpp index 69c39cf5e5ba..e1aa00a3d749 100644 --- a/external/llvm-project/bolt/lib/Rewrite/RewriteInstance.cpp +++ b/external/llvm-project/bolt/lib/Rewrite/RewriteInstance.cpp @@ -3446,6 +3446,7 @@ void RewriteInstance::disassembleFunctions() { BC->outs() << "BOLT-INFO: could not disassemble function " << Function << ". Will ignore.\n"; // Forcefully ignore the function. + Function.scanExternalRefs(); Function.setIgnored(); }); diff --git a/external/llvm-project/bolt/lib/Target/AArch64/AArch64MCPlusBuilder.cpp b/external/llvm-project/bolt/lib/Target/AArch64/AArch64MCPlusBuilder.cpp index 9d5a578cfbdf..eb1d9d8a1951 100644 --- a/external/llvm-project/bolt/lib/Target/AArch64/AArch64MCPlusBuilder.cpp +++ b/external/llvm-project/bolt/lib/Target/AArch64/AArch64MCPlusBuilder.cpp @@ -177,7 +177,7 @@ class AArch64MCPlusBuilder : public MCPlusBuilder { return true; } - bool equals(const MCTargetExpr &A, const MCTargetExpr &B, + bool equals(const MCSpecifierExpr &A, const MCSpecifierExpr &B, CompFuncTy Comp) const override { const auto &AArch64ExprA = cast(A); const auto &AArch64ExprB = cast(B); diff --git a/external/llvm-project/bolt/lib/Target/RISCV/RISCVMCPlusBuilder.cpp b/external/llvm-project/bolt/lib/Target/RISCV/RISCVMCPlusBuilder.cpp index 581f22f2a2b7..c7d664ab09d4 100644 --- a/external/llvm-project/bolt/lib/Target/RISCV/RISCVMCPlusBuilder.cpp +++ b/external/llvm-project/bolt/lib/Target/RISCV/RISCVMCPlusBuilder.cpp @@ -10,7 +10,7 @@ // //===----------------------------------------------------------------------===// -#include "MCTargetDesc/RISCVMCExpr.h" +#include "MCTargetDesc/RISCVMCAsmInfo.h" #include "MCTargetDesc/RISCVMCTargetDesc.h" #include "bolt/Core/MCPlusBuilder.h" #include "llvm/BinaryFormat/ELF.h" @@ -31,10 +31,10 @@ class RISCVMCPlusBuilder : public MCPlusBuilder { public: using MCPlusBuilder::MCPlusBuilder; - bool equals(const MCTargetExpr &A, const MCTargetExpr &B, + bool equals(const MCSpecifierExpr &A, const MCSpecifierExpr &B, CompFuncTy Comp) const override { - const auto &RISCVExprA = cast(A); - const auto &RISCVExprB = cast(B); + const auto &RISCVExprA = cast(A); + const auto &RISCVExprB = cast(B); if (RISCVExprA.getSpecifier() != RISCVExprB.getSpecifier()) return false; @@ -245,7 +245,7 @@ class RISCVMCPlusBuilder : public MCPlusBuilder { MCContext *Ctx) { Inst.setOpcode(Opcode); Inst.clear(); - Inst.addOperand(MCOperand::createExpr(RISCVMCExpr::create( + Inst.addOperand(MCOperand::createExpr(MCSpecifierExpr::create( MCSymbolRefExpr::create(Target, MCSymbolRefExpr::VK_None, *Ctx), ELF::R_RISCV_CALL_PLT, *Ctx))); } @@ -342,7 +342,7 @@ class RISCVMCPlusBuilder : public MCPlusBuilder { } const MCSymbol *getTargetSymbol(const MCExpr *Expr) const override { - auto *RISCVExpr = dyn_cast(Expr); + auto *RISCVExpr = dyn_cast(Expr); if (RISCVExpr && RISCVExpr->getSubExpr()) return getTargetSymbol(RISCVExpr->getSubExpr()); @@ -435,19 +435,19 @@ class RISCVMCPlusBuilder : public MCPlusBuilder { case ELF::R_RISCV_TLS_GD_HI20: // The GOT is reused so no need to create GOT relocations case ELF::R_RISCV_PCREL_HI20: - return RISCVMCExpr::create(Expr, ELF::R_RISCV_PCREL_HI20, Ctx); + return MCSpecifierExpr::create(Expr, ELF::R_RISCV_PCREL_HI20, Ctx); case ELF::R_RISCV_PCREL_LO12_I: case ELF::R_RISCV_PCREL_LO12_S: - return RISCVMCExpr::create(Expr, RISCVMCExpr::VK_PCREL_LO, Ctx); + return MCSpecifierExpr::create(Expr, RISCV::S_PCREL_LO, Ctx); case ELF::R_RISCV_HI20: - return RISCVMCExpr::create(Expr, ELF::R_RISCV_HI20, Ctx); + return MCSpecifierExpr::create(Expr, ELF::R_RISCV_HI20, Ctx); case ELF::R_RISCV_LO12_I: case ELF::R_RISCV_LO12_S: - return RISCVMCExpr::create(Expr, RISCVMCExpr::VK_LO, Ctx); + return MCSpecifierExpr::create(Expr, RISCV::S_LO, Ctx); case ELF::R_RISCV_CALL: - return RISCVMCExpr::create(Expr, ELF::R_RISCV_CALL_PLT, Ctx); + return MCSpecifierExpr::create(Expr, ELF::R_RISCV_CALL_PLT, Ctx); case ELF::R_RISCV_CALL_PLT: - return RISCVMCExpr::create(Expr, ELF::R_RISCV_CALL_PLT, Ctx); + return MCSpecifierExpr::create(Expr, ELF::R_RISCV_CALL_PLT, Ctx); } } @@ -466,10 +466,10 @@ class RISCVMCPlusBuilder : public MCPlusBuilder { return false; const auto *ImmExpr = ImmOp.getExpr(); - if (!isa(ImmExpr)) + if (!isa(ImmExpr)) return false; - switch (cast(ImmExpr)->getSpecifier()) { + switch (cast(ImmExpr)->getSpecifier()) { default: return false; case ELF::R_RISCV_CALL_PLT: diff --git a/external/llvm-project/bolt/lib/Utils/CMakeLists.txt b/external/llvm-project/bolt/lib/Utils/CMakeLists.txt index efba6d54449d..94933644ef5e 100644 --- a/external/llvm-project/bolt/lib/Utils/CMakeLists.txt +++ b/external/llvm-project/bolt/lib/Utils/CMakeLists.txt @@ -6,12 +6,25 @@ set(version_inc "${CMAKE_CURRENT_BINARY_DIR}/VCSVersion.inc") set(generate_vcs_version_script "${LLVM_CMAKE_DIR}/GenerateVersionFromVCS.cmake") +if(llvm_vc AND LLVM_APPEND_VC_REV) + set(llvm_source_dir ${LLVM_MAIN_SRC_DIR}) +endif() +if(LLVM_VC_REPOSITORY AND LLVM_VC_REVISION) + set(llvm_source_dir ${LLVM_SOURCE_DIR}) + set(llvm_vc_repository ${LLVM_VC_REPOSITORY}) + set(llvm_vc_revision ${LLVM_VC_REVISION}) +endif() +if(bolt_vc AND LLVM_APPEND_VC_REV) + set(bolt_source_dir ${BOLT_SOURCE_DIR}) +endif() + # Create custom target to generate the VC revision include. add_custom_command(OUTPUT "${version_inc}" DEPENDS "${llvm_vc}" "${bolt_vc}" "${generate_vcs_version_script}" COMMAND ${CMAKE_COMMAND} "-DNAMES=BOLT" + "-DLLVM_SOURCE_DIR=${llvm_source_dir}" + "-DBOLT_SOURCE_DIR=${bolt_source_dir}" "-DHEADER_FILE=${version_inc}" - "-DBOLT_SOURCE_DIR=${BOLT_SOURCE_DIR}" "-DLLVM_VC_REPOSITORY=${llvm_vc_repository}" "-DLLVM_VC_REVISION=${llvm_vc_revision}" "-DLLVM_FORCE_VC_REVISION=${LLVM_FORCE_VC_REVISION}" diff --git a/external/llvm-project/bolt/test/AArch64/adr-relaxation-fail.s b/external/llvm-project/bolt/test/AArch64/adr-relaxation-fail.s new file mode 100644 index 000000000000..2b04bf8db697 --- /dev/null +++ b/external/llvm-project/bolt/test/AArch64/adr-relaxation-fail.s @@ -0,0 +1,33 @@ +## Check that llvm-bolt generates a proper error message when ADR instruction +## cannot be relaxed. + +# RUN: llvm-mc -filetype=obj -triple aarch64-unknown-unknown %s -o %t.o +# RUN: %clang %cflags %t.o -o %t.exe -Wl,-q -static +# RUN: not llvm-bolt %t.exe -o %t.bolt 2>&1 | FileCheck %s +# RUN: not llvm-bolt %t.exe -o %t.bolt --strict 2>&1 | FileCheck %s + +# CHECK: BOLT-ERROR: cannot relax ADR in non-simple function _start + +## The function contains unknown control flow and llvm-bolt fails to recover +## CFG. As BOLT has to preserve the function layout, the ADR instruction cannot +## be relaxed into ADRP+ADD. + .text + .globl _start + .type _start, %function +_start: + .cfi_startproc + adr x1, foo + adr x2, .L1 +.L1: + br x0 + ret x0 + .cfi_endproc + .size _start, .-_start + + .globl foo + .type foo, %function +foo: + .cfi_startproc + ret x0 + .cfi_endproc + .size foo, .-foo diff --git a/external/llvm-project/bolt/test/AArch64/adr-relaxation.s b/external/llvm-project/bolt/test/AArch64/adr-relaxation.s index 0aa3c71f29aa..864650c3287d 100644 --- a/external/llvm-project/bolt/test/AArch64/adr-relaxation.s +++ b/external/llvm-project/bolt/test/AArch64/adr-relaxation.s @@ -3,7 +3,7 @@ # RUN: llvm-mc -filetype=obj -triple aarch64-unknown-unknown %s -o %t.o # RUN: %clang %cflags %t.o -o %t.exe -Wl,-q -static # RUN: llvm-bolt %t.exe -o %t.bolt --split-functions --split-strategy=random2 -# RUN: llvm-objdump -d --disassemble-symbols=_start %t.bolt | FileCheck %s +# RUN: llvm-objdump -d -j .text %t.bolt | FileCheck %s # RUN: llvm-objdump -d --disassemble-symbols=foo.cold.0 %t.bolt \ # RUN: | FileCheck --check-prefix=CHECK-FOO %s @@ -13,11 +13,10 @@ .globl _start .type _start, %function _start: -# CHECK: <_start>: .cfi_startproc +# CHECK: <_start>: +# CHECK-NEXT: adr adr x1, _start -# CHECK-NOT: adrp -# CHECK: adr cmp x1, x11 b.hi .L1 mov x0, #0x0 @@ -35,15 +34,29 @@ foo: .cfi_startproc cmp x1, x11 b.hi .L2 - mov x0, #0x0 .L2: # CHECK-FOO: : - adr x1, foo -# CHECK-FOO: adrp +# CHECK-FOO-NEXT: adrp # CHECK-FOO-NEXT: add + adr x1, foo ret x30 .cfi_endproc .size foo, .-foo -## Force relocation mode. - .reloc 0, R_AARCH64_NONE +## bar is a non-simple function. We can still relax ADR, because it has a +## preceding NOP. + .globl bar + .type bar, %function +bar: + .cfi_startproc +# CHECK-LABEL: : +# CHECK-NEXT: adrp +# CHECK-NEXT: add + nop + adr x0, foo + adr x1, .L3 + br x1 +.L3: + ret x0 + .cfi_endproc + .size bar, .-bar diff --git a/external/llvm-project/bolt/test/AArch64/patch-ignored.s b/external/llvm-project/bolt/test/AArch64/patch-ignored.s new file mode 100644 index 000000000000..377d4dacea60 --- /dev/null +++ b/external/llvm-project/bolt/test/AArch64/patch-ignored.s @@ -0,0 +1,33 @@ +## Check that llvm-bolt patches functions that are getting ignored after their +## CFG was constructed. + +# RUN: %clang %cflags %s -o %t.exe -Wl,-q +# RUN: llvm-bolt %t.exe -o %t.bolt --force-patch 2>&1 | FileCheck %s +# RUN: llvm-objdump -d %t.bolt | FileCheck %s --check-prefix=CHECK-OBJDUMP + + .text + +## The function is too small to be patched and BOLT is forced to ignore it under +## --force-patch. Check that the reference to _start is updated. +# CHECK: BOLT-WARNING: failed to patch entries in unpatchable + .globl unpatchable + .type unpatchable, %function +unpatchable: + .cfi_startproc +# CHECK-OBJDUMP: : +# CHECK-OBJDUMP-NEXT: bl {{.*}} <_start> + bl _start + ret + .cfi_endproc + .size unpatchable, .-unpatchable + + .globl _start + .type _start, %function +_start: + .cfi_startproc + cmp x0, 1 + b.eq .L0 +.L0: + ret x30 + .cfi_endproc + .size _start, .-_start diff --git a/external/llvm-project/bolt/test/AArch64/r_aarch64_prelxx.s b/external/llvm-project/bolt/test/AArch64/r_aarch64_prelxx.s index 73bf8387d363..5cbe2c50b294 100644 --- a/external/llvm-project/bolt/test/AArch64/r_aarch64_prelxx.s +++ b/external/llvm-project/bolt/test/AArch64/r_aarch64_prelxx.s @@ -12,16 +12,14 @@ // CHECKPREL-NEXT: R_AARCH64_PREL32 {{.*}} _start + 4 // CHECKPREL-NEXT: R_AARCH64_PREL64 {{.*}} _start + 8 -// RUN: llvm-bolt %t.exe -o %t.bolt --strict +// RUN: llvm-bolt %t.exe -o %t.bolt // RUN: llvm-objdump -D %t.bolt | FileCheck %s --check-prefix=CHECKPREL32 // CHECKPREL32: [[#%x,DATATABLEADDR:]] : // CHECKPREL32-NEXT: 00: // CHECKPREL32-NEXT: 04: {{.*}} .word 0x[[#%x,VALUE:]] -// 4 is offset in datatable -// 8 is addend -// CHECKPREL32: [[#DATATABLEADDR + 4 - 8 + VALUE]] <_start>: +// CHECKPREL32: [[#DATATABLEADDR + VALUE]] <_start>: // RUN: llvm-objdump -D %t.bolt | FileCheck %s --check-prefix=CHECKPREL64 // CHECKPREL64: [[#%x,DATATABLEADDR:]] : @@ -30,16 +28,15 @@ // CHECKPREL64-NEXT: 08: {{.*}} .word 0x[[#%x,VALUE:]] // CHECKPREL64-NEXT: 0c: {{.*}} .word 0x00000000 -// 8 is offset in datatable -// 12 is addend -// CHECKPREL64: [[#DATATABLEADDR + 8 - 12 + VALUE]] <_start>: +// CHECKPREL64: [[#DATATABLEADDR + VALUE]] <_start>: .section .text .align 4 .globl _start .type _start, %function _start: - adr x0, datatable + adrp x0, datatable + add x0, x0, :lo12:datable mov x0, #0 ret diff --git a/external/llvm-project/bolt/test/AArch64/test-indirect-branch.s b/external/llvm-project/bolt/test/AArch64/test-indirect-branch.s index b99737ee97ac..a9fa7737d3d2 100644 --- a/external/llvm-project/bolt/test/AArch64/test-indirect-branch.s +++ b/external/llvm-project/bolt/test/AArch64/test-indirect-branch.s @@ -7,8 +7,8 @@ // RUN: llvm-mc -filetype=obj -triple aarch64-unknown-unknown -mattr=+pauth %s -o %t.o // RUN: %clang %cflags --target=aarch64-unknown-linux %t.o -o %t.exe -Wl,-q -// RUN: llvm-bolt %t.exe -o %t.bolt --print-cfg --strict --debug-only=mcplus \ -// RUN: -v=1 2>&1 | FileCheck %s +// RUN: llvm-bolt %t.exe -o %t.bolt --print-cfg --debug-only=mcplus -v=1 2>&1 \ +// RUN: | FileCheck %s // Pattern 1: there is no shift amount after the 'add' instruction. // @@ -45,6 +45,7 @@ _start: .type test1, %function test1: mov x1, #0 + nop adr x3, datatable add x3, x3, x1, lsl #2 ldr w2, [x3] @@ -56,6 +57,11 @@ test1_1: ret test1_2: ret + .size test1, .-test1 + +// Temporary workaround for PC-relative relocations from datatable leaking into +// test2 function and creating phantom entry points. +.skip 0x100 // Pattern 2 // CHECK: BOLT-DEBUG: failed to match indirect branch: nop/adr instead of adrp/add @@ -65,6 +71,7 @@ test2: nop adr x3, jump_table ldrh w3, [x3, x1, lsl #1] + nop adr x1, test2_0 add x3, x1, w3, sxth #2 br x3 diff --git a/external/llvm-project/bolt/test/X86/Inputs/pre-aggregated-basic.txt b/external/llvm-project/bolt/test/X86/Inputs/pre-aggregated-basic.txt new file mode 100644 index 000000000000..dcb85a1d4e44 --- /dev/null +++ b/external/llvm-project/bolt/test/X86/Inputs/pre-aggregated-basic.txt @@ -0,0 +1,19 @@ +E cycles +S 4005f0 1 +S 4005f0 1 +S 400610 1 +S 400ad1 2 +S 400b10 1 +S 400bb7 1 +S 400bbc 2 +S 400d90 1 +S 400dae 1 +S 400e00 2 +S 401170 22 +S 401180 58 +S 4011a0 33 +S 4011a9 33 +S 4011ad 58 +S 4011b2 22 +S X:7f36d18d60c0 2 +S X:7f36d18f2ce0 1 diff --git a/external/llvm-project/bolt/test/X86/entry-point-fallthru.s b/external/llvm-project/bolt/test/X86/entry-point-fallthru.s index edf14247b0c4..850247b97d27 100644 --- a/external/llvm-project/bolt/test/X86/entry-point-fallthru.s +++ b/external/llvm-project/bolt/test/X86/entry-point-fallthru.s @@ -6,6 +6,10 @@ # RUN: link_fdata %s %t %t.preagg PREAGG # RUN: perf2bolt %t -p %t.preagg --pa -o %t.fdata | FileCheck %s # CHECK: traces mismatching disassembled function contents: 0 +# RUN: FileCheck %s --check-prefix=CHECK-FDATA --input-file %t.fdata +# CHECK-FDATA: 1 main 0 1 main 6 0 1 +# CHECK-FDATA-NEXT: 1 main e 1 main 11 0 1 +# CHECK-FDATA-NEXT: 1 main 11 1 main 0 0 1 .globl main main: diff --git a/external/llvm-project/bolt/test/X86/patch-ignored.s b/external/llvm-project/bolt/test/X86/patch-ignored.s new file mode 100644 index 000000000000..4f98b51ca1ca --- /dev/null +++ b/external/llvm-project/bolt/test/X86/patch-ignored.s @@ -0,0 +1,44 @@ +## Check that llvm-bolt patches functions that are getting ignored after their +## CFG was constructed. + +# RUN: %clang %cflags %s -o %t.exe -Wl,-q +# RUN: llvm-bolt %t.exe -o %t.bolt 2>&1 | FileCheck %s +# RUN: llvm-objdump -d %t.bolt | FileCheck %s --check-prefix=CHECK-OBJDUMP + + .text + +## After the CFG is built, the following function will be marked as ignored +## due to the presence of the internal call. +# CHECK: BOLT-WARNING: will skip the following function +# CHECK-NEXT: internal_call + .globl internal_call + .type internal_call, %function +internal_call: + .cfi_startproc +# CHECK-OBJDUMP: : + call .L1 + jmp .L2 +# CHECK-OBJDUMP: jmp +.L1: + jmp _start +# CHECK-OBJDUMP: jmp +# CHECK-OBJDUMP-SAME: <_start> + ret +.L2: + jmp _start +# CHECK-OBJDUMP: jmp +# CHECK-OBJDUMP-SAME: <_start> + .cfi_endproc + .size internal_call, .-internal_call + + .globl _start + .type _start, %function +_start: + .cfi_startproc + cmpq %rdi, 1 + jne .L0 + movq %rdi, %rax +.L0: + ret + .cfi_endproc + .size _start, .-_start diff --git a/external/llvm-project/bolt/test/X86/pre-aggregated-perf.test b/external/llvm-project/bolt/test/X86/pre-aggregated-perf.test index c05a06bf7494..c4f5b8f2ea44 100644 --- a/external/llvm-project/bolt/test/X86/pre-aggregated-perf.test +++ b/external/llvm-project/bolt/test/X86/pre-aggregated-perf.test @@ -36,37 +36,48 @@ RUN: llvm-bolt %t.exe -p %p/Inputs/pre-aggregated.txt --pa -o %t.null | FileChec CHECK: BOLT-INFO: 4 out of 7 functions in the binary (57.1%) have non-empty execution profile -RUN: cat %t | sort | FileCheck %s -check-prefix=PERF2BOLT -RUN: cat %t.new | FileCheck %s -check-prefix=NEWFORMAT +RUN: FileCheck %s -check-prefix=PERF2BOLT --input-file %t +RUN: FileCheck %s -check-prefix=NEWFORMAT --input-file %t.new ## Test --profile-format option with perf2bolt RUN: perf2bolt %t.exe -o %t.fdata --pa -p %p/Inputs/pre-aggregated.txt \ RUN: --profile-format=fdata -RUN: cat %t.fdata | sort | FileCheck %s -check-prefix=PERF2BOLT +RUN: FileCheck %s -check-prefix=PERF2BOLT --input-file %t.fdata RUN: perf2bolt %t.exe -o %t.yaml --pa -p %p/Inputs/pre-aggregated.txt \ RUN: --profile-format=yaml --profile-use-dfs -RUN: cat %t.yaml | FileCheck %s -check-prefix=NEWFORMAT +RUN: FileCheck %s -check-prefix=NEWFORMAT --input-file %t.yaml ## Test --profile-format option with llvm-bolt --aggregate-only RUN: llvm-bolt %t.exe -o %t.bolt.fdata --pa -p %p/Inputs/pre-aggregated.txt \ RUN: --aggregate-only --profile-format=fdata -RUN: cat %t.bolt.fdata | sort | FileCheck %s -check-prefix=PERF2BOLT +RUN: FileCheck %s -check-prefix=PERF2BOLT --input-file %t.bolt.fdata RUN: llvm-bolt %t.exe -o %t.bolt.yaml --pa -p %p/Inputs/pre-aggregated.txt \ RUN: --aggregate-only --profile-format=yaml --profile-use-dfs -RUN: cat %t.bolt.yaml | FileCheck %s -check-prefix=NEWFORMAT - -PERF2BOLT: 0 [unknown] 7f36d18d60c0 1 main 53c 0 2 -PERF2BOLT: 1 main 451 1 SolveCubic 0 0 2 -PERF2BOLT: 1 main 490 0 [unknown] 4005f0 0 1 -PERF2BOLT: 1 main 537 0 [unknown] 400610 0 1 -PERF2BOLT: 1 usqrt 30 1 usqrt 32 0 22 -PERF2BOLT: 1 usqrt 30 1 usqrt 39 4 33 -PERF2BOLT: 1 usqrt 35 1 usqrt 39 0 22 -PERF2BOLT: 1 usqrt 3d 1 usqrt 10 0 58 -PERF2BOLT: 1 usqrt 3d 1 usqrt 3f 0 22 -PERF2BOLT: 1 usqrt a 1 usqrt 10 0 22 +RUN: FileCheck %s -check-prefix=NEWFORMAT --input-file %t.bolt.yaml + +## Test pre-aggregated basic profile +RUN: perf2bolt %t.exe -o %t --pa -p %p/Inputs/pre-aggregated-basic.txt -o %t.ba \ +RUN: 2>&1 | FileCheck %s --check-prefix=BASIC-ERROR +RUN: perf2bolt %t.exe -o %t --pa -p %p/Inputs/pre-aggregated-basic.txt -o %t.ba.nl \ +RUN: -nl 2>&1 | FileCheck %s --check-prefix=BASIC-SUCCESS +RUN: FileCheck %s --input-file %t.ba.nl --check-prefix CHECK-BASIC-NL +BASIC-ERROR: BOLT-INFO: 0 out of 7 functions in the binary (0.0%) have non-empty execution profile +BASIC-SUCCESS: BOLT-INFO: 4 out of 7 functions in the binary (57.1%) have non-empty execution profile +CHECK-BASIC-NL: no_lbr cycles + +PERF2BOLT: 1 frame_dummy/1 1e 1 frame_dummy/1 0 0 1 +PERF2BOLT-NEXT: 1 main 451 1 SolveCubic 0 0 2 +PERF2BOLT-NEXT: 1 main 490 0 [unknown] 0 0 1 +PERF2BOLT-NEXT: 1 main 537 0 [unknown] 0 0 1 +PERF2BOLT-NEXT: 0 [unknown] 0 1 main 53c 0 2 +PERF2BOLT-NEXT: 1 usqrt a 1 usqrt 10 0 22 +PERF2BOLT-NEXT: 1 usqrt 30 1 usqrt 32 0 22 +PERF2BOLT-NEXT: 1 usqrt 30 1 usqrt 39 4 33 +PERF2BOLT-NEXT: 1 usqrt 35 1 usqrt 39 0 22 +PERF2BOLT-NEXT: 1 usqrt 3d 1 usqrt 10 0 58 +PERF2BOLT-NEXT: 1 usqrt 3d 1 usqrt 3f 0 22 NEWFORMAT: - name: 'frame_dummy/1' NEWFORMAT: fid: 3 diff --git a/external/llvm-project/bolt/test/X86/shrinkwrapping.test b/external/llvm-project/bolt/test/X86/shrinkwrapping.test index 8581d7e0c0f7..521b4561b3ba 100644 --- a/external/llvm-project/bolt/test/X86/shrinkwrapping.test +++ b/external/llvm-project/bolt/test/X86/shrinkwrapping.test @@ -8,6 +8,7 @@ REQUIRES: shell RUN: %clangxx %cxxflags -no-pie %S/Inputs/exc4sw.S -o %t.exe -Wl,-q RUN: llvm-bolt %t.exe -o %t --relocs --frame-opt=all \ +RUN: --print-only=main --print-cfg \ RUN: --data=%p/Inputs/exc4sw.fdata --reorder-blocks=cache 2>&1 | \ RUN: FileCheck %s --check-prefix=CHECK-BOLT @@ -19,6 +20,7 @@ RUN: llvm-objdump --dwarf=frames %t | grep -A20 -e \ RUN: `llvm-nm --numeric-sort %t | grep main | tail -n 1 | cut -f1 -d' ' | \ RUN: tail -c9` 2>&1 | FileCheck %s --check-prefix=CHECK-OUTPUT +CHECK-BOLT: Extern Entry Count: 100 CHECK-BOLT: Shrink wrapping moved 2 spills inserting load/stores and 0 spills inserting push/pops CHECK-INPUT: DW_CFA_advance_loc: 2 diff --git a/external/llvm-project/bolt/test/link_fdata.py b/external/llvm-project/bolt/test/link_fdata.py index bcf9a777922d..5a9752068bb9 100755 --- a/external/llvm-project/bolt/test/link_fdata.py +++ b/external/llvm-project/bolt/test/link_fdata.py @@ -33,12 +33,12 @@ # # # -fdata_pat = re.compile(r"([01].*) (?P\d+) (?P\d+)") +fdata_pat = re.compile(r"([01].*) (?P\d+) (?P\d+)") # Pre-aggregated profile: -# {T|B|F|f} [:] [:] [] -# [] -preagg_pat = re.compile(r"(?P[TBFf]) (?P.*)") +# {T|S|E|B|F|f} [] [] [] +# : [:] +preagg_pat = re.compile(r"(?P[TSBFf]) (?P.*)") # No-LBR profile: # @@ -61,7 +61,7 @@ preagg_match = preagg_pat.match(profile_line) nolbr_match = nolbr_pat.match(profile_line) if fdata_match: - src_dst, execnt, mispred = fdata_match.groups() + src_dst, mispred, execnt = fdata_match.groups() # Split by whitespaces not preceded by a backslash (negative lookbehind) chunks = re.split(r"(?&1 | FileCheck %s --check-prefix CHECK-ERROR - - .text - .align 4 - .global test - .type test, %function -test: - adr x2, Gvar - mov x0, xzr - ret - .size test, .-test - - .align 4 - .global main - .type main, %function -main: - adr x0, .CI - nop - adr x1, test - adr x2, Gvar2 - adr x3, br -br: - br x1 - .size main, .-main -.CI: - .word 0xff - - .data - .align 8 - .global Gvar -Gvar: .xword 0x0 - .global Gvar2 -Gvar2: .xword 0x42 - .balign 4 -jmptable: - .word 0 - .word test - jmptable - -# CHECK:
: -# CHECK-NEXT: adr x0, 0x{{[1-8a-f][0-9a-f]*}} -# CHECK-NEXT: adrp x1, 0x{{[1-8a-f][0-9a-f]*}} -# CHECK-NEXT: add x1, x1, #{{[1-8a-f][0-9a-f]*}} -# CHECK-NEXT: adrp x2, 0x{{[1-8a-f][0-9a-f]*}} -# CHECK-NEXT: add x2, x2, #{{[1-8a-f][0-9a-f]*}} -# CHECK-NEXT: adr x3, 0x{{[1-8a-f][0-9a-f]*}} -# CHECK-ERROR: BOLT-ERROR: Cannot relax adr in non-simple function diff --git a/external/llvm-project/clang-tools-extra/clang-doc/BitcodeReader.cpp b/external/llvm-project/clang-tools-extra/clang-doc/BitcodeReader.cpp index f8e338eb7c6e..35058abab066 100644 --- a/external/llvm-project/clang-tools-extra/clang-doc/BitcodeReader.cpp +++ b/external/llvm-project/clang-tools-extra/clang-doc/BitcodeReader.cpp @@ -9,6 +9,7 @@ #include "BitcodeReader.h" #include "llvm/ADT/IndexedMap.h" #include "llvm/Support/Error.h" +#include "llvm/Support/TimeProfiler.h" #include "llvm/Support/raw_ostream.h" #include @@ -53,10 +54,8 @@ static llvm::Error decodeRecord(const Record &R, AccessSpecifier &Field, case AS_none: Field = (AccessSpecifier)R[0]; return llvm::Error::success(); - default: - return llvm::createStringError(llvm::inconvertibleErrorCode(), - "invalid value for AccessSpecifier"); } + llvm_unreachable("invalid value for AccessSpecifier"); } static llvm::Error decodeRecord(const Record &R, TagTypeKind &Field, @@ -314,9 +313,13 @@ static llvm::Error parseRecord(const Record &R, unsigned ID, static llvm::Error parseRecord(const Record &R, unsigned ID, llvm::StringRef Blob, CommentInfo *I) { + llvm::SmallString<16> KindStr; switch (ID) { case COMMENT_KIND: - return decodeRecord(R, I->Kind, Blob); + if (llvm::Error Err = decodeRecord(R, KindStr, Blob)) + return Err; + I->Kind = stringToCommentKind(KindStr); + return llvm::Error::success(); case COMMENT_TEXT: return decodeRecord(R, I->Text, Blob); case COMMENT_NAME: @@ -672,6 +675,7 @@ llvm::Error ClangDocBitcodeReader::readRecord(unsigned ID, T I) { template <> llvm::Error ClangDocBitcodeReader::readRecord(unsigned ID, Reference *I) { + llvm::TimeTraceScope("Reducing infos", "readRecord"); Record R; llvm::StringRef Blob; llvm::Expected MaybeRecID = Stream.readRecord(ID, R, &Blob); @@ -683,6 +687,7 @@ llvm::Error ClangDocBitcodeReader::readRecord(unsigned ID, Reference *I) { // Read a block of records into a single info. template llvm::Error ClangDocBitcodeReader::readBlock(unsigned ID, T I) { + llvm::TimeTraceScope("Reducing infos", "readBlock"); if (llvm::Error Err = Stream.EnterSubBlock(ID)) return Err; @@ -713,6 +718,7 @@ llvm::Error ClangDocBitcodeReader::readBlock(unsigned ID, T I) { template llvm::Error ClangDocBitcodeReader::readSubBlock(unsigned ID, T I) { + llvm::TimeTraceScope("Reducing infos", "readSubBlock"); switch (ID) { // Blocks can only have certain types of sub blocks. case BI_COMMENT_BLOCK_ID: { @@ -819,6 +825,7 @@ llvm::Error ClangDocBitcodeReader::readSubBlock(unsigned ID, T I) { ClangDocBitcodeReader::Cursor ClangDocBitcodeReader::skipUntilRecordOrBlock(unsigned &BlockOrRecordID) { + llvm::TimeTraceScope("Reducing infos", "skipUntilRecordOrBlock"); BlockOrRecordID = 0; while (!Stream.AtEndOfStream()) { @@ -880,6 +887,7 @@ llvm::Error ClangDocBitcodeReader::validateStream() { } llvm::Error ClangDocBitcodeReader::readBlockInfoBlock() { + llvm::TimeTraceScope("Reducing infos", "readBlockInfoBlock"); Expected> MaybeBlockInfo = Stream.ReadBlockInfoBlock(); if (!MaybeBlockInfo) @@ -895,6 +903,7 @@ llvm::Error ClangDocBitcodeReader::readBlockInfoBlock() { template llvm::Expected> ClangDocBitcodeReader::createInfo(unsigned ID) { + llvm::TimeTraceScope("Reducing infos", "createInfo"); std::unique_ptr I = std::make_unique(); if (auto Err = readBlock(ID, static_cast(I.get()))) return std::move(Err); @@ -903,6 +912,7 @@ ClangDocBitcodeReader::createInfo(unsigned ID) { llvm::Expected> ClangDocBitcodeReader::readBlockToInfo(unsigned ID) { + llvm::TimeTraceScope("Reducing infos", "readBlockToInfo"); switch (ID) { case BI_NAMESPACE_BLOCK_ID: return createInfo(ID); diff --git a/external/llvm-project/clang-tools-extra/clang-doc/BitcodeWriter.cpp b/external/llvm-project/clang-tools-extra/clang-doc/BitcodeWriter.cpp index f0a445e606bf..f8a6859169b0 100644 --- a/external/llvm-project/clang-tools-extra/clang-doc/BitcodeWriter.cpp +++ b/external/llvm-project/clang-tools-extra/clang-doc/BitcodeWriter.cpp @@ -484,8 +484,9 @@ void ClangDocBitcodeWriter::emitBlock(const MemberTypeInfo &T) { void ClangDocBitcodeWriter::emitBlock(const CommentInfo &I) { StreamSubBlockGuard Block(Stream, BI_COMMENT_BLOCK_ID); + // Handle Kind (enum) separately, since it is not a string. + emitRecord(commentKindToString(I.Kind), COMMENT_KIND); for (const auto &L : std::vector>{ - {I.Kind, COMMENT_KIND}, {I.Text, COMMENT_TEXT}, {I.Name, COMMENT_NAME}, {I.Direction, COMMENT_DIRECTION}, @@ -663,7 +664,7 @@ bool ClangDocBitcodeWriter::dispatchInfoForWrite(Info *I) { case InfoType::IT_typedef: emitBlock(*static_cast(I)); break; - default: + case InfoType::IT_default: llvm::errs() << "Unexpected info, unable to write.\n"; return true; } diff --git a/external/llvm-project/clang-tools-extra/clang-doc/CMakeLists.txt b/external/llvm-project/clang-tools-extra/clang-doc/CMakeLists.txt index 79563c41435e..5989e5fe60cf 100644 --- a/external/llvm-project/clang-tools-extra/clang-doc/CMakeLists.txt +++ b/external/llvm-project/clang-tools-extra/clang-doc/CMakeLists.txt @@ -17,6 +17,7 @@ add_clang_library(clangDoc STATIC Serialize.cpp YAMLGenerator.cpp HTMLMustacheGenerator.cpp + JSONGenerator.cpp DEPENDS omp_gen diff --git a/external/llvm-project/clang-tools-extra/clang-doc/Generators.cpp b/external/llvm-project/clang-tools-extra/clang-doc/Generators.cpp index a3c2773412cf..3fb5b63c403a 100644 --- a/external/llvm-project/clang-tools-extra/clang-doc/Generators.cpp +++ b/external/llvm-project/clang-tools-extra/clang-doc/Generators.cpp @@ -105,5 +105,7 @@ static int LLVM_ATTRIBUTE_UNUSED HTMLGeneratorAnchorDest = HTMLGeneratorAnchorSource; static int LLVM_ATTRIBUTE_UNUSED MHTMLGeneratorAnchorDest = MHTMLGeneratorAnchorSource; +static int LLVM_ATTRIBUTE_UNUSED JSONGeneratorAnchorDest = + JSONGeneratorAnchorSource; } // namespace doc } // namespace clang diff --git a/external/llvm-project/clang-tools-extra/clang-doc/Generators.h b/external/llvm-project/clang-tools-extra/clang-doc/Generators.h index aee04b9d58d9..92d3006e6002 100644 --- a/external/llvm-project/clang-tools-extra/clang-doc/Generators.h +++ b/external/llvm-project/clang-tools-extra/clang-doc/Generators.h @@ -58,6 +58,7 @@ extern volatile int YAMLGeneratorAnchorSource; extern volatile int MDGeneratorAnchorSource; extern volatile int HTMLGeneratorAnchorSource; extern volatile int MHTMLGeneratorAnchorSource; +extern volatile int JSONGeneratorAnchorSource; } // namespace doc } // namespace clang diff --git a/external/llvm-project/clang-tools-extra/clang-doc/HTMLGenerator.cpp b/external/llvm-project/clang-tools-extra/clang-doc/HTMLGenerator.cpp index 93b9279462a8..7293a129177c 100644 --- a/external/llvm-project/clang-tools-extra/clang-doc/HTMLGenerator.cpp +++ b/external/llvm-project/clang-tools-extra/clang-doc/HTMLGenerator.cpp @@ -635,7 +635,8 @@ genHTML(const Index &Index, StringRef InfoPath, bool IsOutermostList) { } static std::unique_ptr genHTML(const CommentInfo &I) { - if (I.Kind == "FullComment") { + switch (I.Kind) { + case CommentKind::CK_FullComment: { auto FullComment = std::make_unique(HTMLTag::TAG_DIV); for (const auto &Child : I.Children) { std::unique_ptr Node = genHTML(*Child); @@ -645,7 +646,7 @@ static std::unique_ptr genHTML(const CommentInfo &I) { return std::move(FullComment); } - if (I.Kind == "ParagraphComment") { + case CommentKind::CK_ParagraphComment: { auto ParagraphComment = std::make_unique(HTMLTag::TAG_P); for (const auto &Child : I.Children) { std::unique_ptr Node = genHTML(*Child); @@ -657,7 +658,7 @@ static std::unique_ptr genHTML(const CommentInfo &I) { return std::move(ParagraphComment); } - if (I.Kind == "BlockCommandComment") { + case CommentKind::CK_BlockCommandComment: { auto BlockComment = std::make_unique(HTMLTag::TAG_DIV); BlockComment->Children.emplace_back( std::make_unique(HTMLTag::TAG_DIV, I.Name)); @@ -670,12 +671,26 @@ static std::unique_ptr genHTML(const CommentInfo &I) { return nullptr; return std::move(BlockComment); } - if (I.Kind == "TextComment") { - if (I.Text == "") + + case CommentKind::CK_TextComment: { + if (I.Text.empty()) return nullptr; return std::make_unique(I.Text); } - return nullptr; + + // For now, return nullptr for unsupported comment kinds + case CommentKind::CK_InlineCommandComment: + case CommentKind::CK_HTMLStartTagComment: + case CommentKind::CK_HTMLEndTagComment: + case CommentKind::CK_ParamCommandComment: + case CommentKind::CK_TParamCommandComment: + case CommentKind::CK_VerbatimBlockComment: + case CommentKind::CK_VerbatimBlockLineComment: + case CommentKind::CK_VerbatimLineComment: + case CommentKind::CK_Unknown: + return nullptr; + } + llvm_unreachable("Unhandled CommentKind"); } static std::unique_ptr genHTML(const std::vector &C) { diff --git a/external/llvm-project/clang-tools-extra/clang-doc/HTMLMustacheGenerator.cpp b/external/llvm-project/clang-tools-extra/clang-doc/HTMLMustacheGenerator.cpp index 65dc2e93582e..69c670b20844 100644 --- a/external/llvm-project/clang-tools-extra/clang-doc/HTMLMustacheGenerator.cpp +++ b/external/llvm-project/clang-tools-extra/clang-doc/HTMLMustacheGenerator.cpp @@ -19,6 +19,7 @@ #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Mustache.h" #include "llvm/Support/Path.h" +#include "llvm/Support/TimeProfiler.h" using namespace llvm; using namespace llvm::json; @@ -125,13 +126,18 @@ static Error setupTemplateFiles(const clang::doc::ClangDocContext &CDCtx) { Error MustacheHTMLGenerator::generateDocs( StringRef RootDir, StringMap> Infos, const clang::doc::ClangDocContext &CDCtx) { - if (auto Err = setupTemplateFiles(CDCtx)) - return Err; + { + llvm::TimeTraceScope TS("Setup Templates"); + if (auto Err = setupTemplateFiles(CDCtx)) + return Err; + } + // Track which directories we already tried to create. StringSet<> CreatedDirs; // Collect all output by file name and create the necessary directories. StringMap> FileToInfos; for (const auto &Group : Infos) { + llvm::TimeTraceScope TS("setup directories"); doc::Info *Info = Group.getValue().get(); SmallString<128> Path; @@ -148,15 +154,19 @@ Error MustacheHTMLGenerator::generateDocs( FileToInfos[Path].push_back(Info); } - for (const auto &Group : FileToInfos) { - std::error_code FileErr; - raw_fd_ostream InfoOS(Group.getKey(), FileErr, sys::fs::OF_None); - if (FileErr) - return createFileOpenError(Group.getKey(), FileErr); - - for (const auto &Info : Group.getValue()) - if (Error Err = generateDocForInfo(Info, InfoOS, CDCtx)) - return Err; + { + llvm::TimeTraceScope TS("Generate Docs"); + for (const auto &Group : FileToInfos) { + llvm::TimeTraceScope TS("Info to Doc"); + std::error_code FileErr; + raw_fd_ostream InfoOS(Group.getKey(), FileErr, sys::fs::OF_None); + if (FileErr) + return createFileOpenError(Group.getKey(), FileErr); + + for (const auto &Info : Group.getValue()) + if (Error Err = generateDocForInfo(Info, InfoOS, CDCtx)) + return Err; + } } return Error::success(); } @@ -198,37 +208,110 @@ static json::Value extractValue(const TypedefInfo &I) { } static json::Value extractValue(const CommentInfo &I) { - assert((I.Kind == "BlockCommandComment" || I.Kind == "FullComment" || - I.Kind == "ParagraphComment" || I.Kind == "TextComment") && - "Unknown Comment type in CommentInfo."); - Object Obj = Object(); - json::Value Child = Object(); - // TextComment has no children, so return it. - if (I.Kind == "TextComment") { - Obj.insert({"TextComment", I.Text}); - return Obj; - } + json::Value ChildVal = Object(); + Object &Child = *ChildVal.getAsObject(); - // BlockCommandComment needs to generate a Command key. - if (I.Kind == "BlockCommandComment") - Child.getAsObject()->insert({"Command", I.Name}); - - // Use the same handling for everything else. - // Only valid for: - // - BlockCommandComment - // - FullComment - // - ParagraphComment json::Value ChildArr = Array(); auto &CARef = *ChildArr.getAsArray(); CARef.reserve(I.Children.size()); for (const auto &C : I.Children) CARef.emplace_back(extractValue(*C)); - Child.getAsObject()->insert({"Children", ChildArr}); - Obj.insert({I.Kind, Child}); - return Obj; + switch (I.Kind) { + case CommentKind::CK_TextComment: { + Obj.insert({commentKindToString(I.Kind), I.Text}); + return Obj; + } + + case CommentKind::CK_BlockCommandComment: { + Child.insert({"Command", I.Name}); + Child.insert({"Children", ChildArr}); + Obj.insert({commentKindToString(I.Kind), ChildVal}); + return Obj; + } + + case CommentKind::CK_InlineCommandComment: { + json::Value ArgsArr = Array(); + auto &ARef = *ArgsArr.getAsArray(); + ARef.reserve(I.Args.size()); + for (const auto &Arg : I.Args) + ARef.emplace_back(Arg); + Child.insert({"Command", I.Name}); + Child.insert({"Args", ArgsArr}); + Child.insert({"Children", ChildArr}); + Obj.insert({commentKindToString(I.Kind), ChildVal}); + return Obj; + } + + case CommentKind::CK_ParamCommandComment: + case CommentKind::CK_TParamCommandComment: { + Child.insert({"ParamName", I.ParamName}); + Child.insert({"Direction", I.Direction}); + Child.insert({"Explicit", I.Explicit}); + Child.insert({"Children", ChildArr}); + Obj.insert({commentKindToString(I.Kind), ChildVal}); + return Obj; + } + + case CommentKind::CK_VerbatimBlockComment: { + Child.insert({"Text", I.Text}); + if (!I.CloseName.empty()) + Child.insert({"CloseName", I.CloseName}); + Child.insert({"Children", ChildArr}); + Obj.insert({commentKindToString(I.Kind), ChildVal}); + return Obj; + } + + case CommentKind::CK_VerbatimBlockLineComment: + case CommentKind::CK_VerbatimLineComment: { + Child.insert({"Text", I.Text}); + Child.insert({"Children", ChildArr}); + Obj.insert({commentKindToString(I.Kind), ChildVal}); + return Obj; + } + + case CommentKind::CK_HTMLStartTagComment: { + json::Value AttrKeysArray = json::Array(); + json::Value AttrValuesArray = json::Array(); + auto &KeyArr = *AttrKeysArray.getAsArray(); + auto &ValArr = *AttrValuesArray.getAsArray(); + KeyArr.reserve(I.AttrKeys.size()); + ValArr.reserve(I.AttrValues.size()); + for (const auto &K : I.AttrKeys) + KeyArr.emplace_back(K); + for (const auto &V : I.AttrValues) + ValArr.emplace_back(V); + Child.insert({"Name", I.Name}); + Child.insert({"SelfClosing", I.SelfClosing}); + Child.insert({"AttrKeys", AttrKeysArray}); + Child.insert({"AttrValues", AttrValuesArray}); + Child.insert({"Children", ChildArr}); + Obj.insert({commentKindToString(I.Kind), ChildVal}); + return Obj; + } + + case CommentKind::CK_HTMLEndTagComment: { + Child.insert({"Name", I.Name}); + Child.insert({"Children", ChildArr}); + Obj.insert({commentKindToString(I.Kind), ChildVal}); + return Obj; + } + + case CommentKind::CK_FullComment: + case CommentKind::CK_ParagraphComment: { + Child.insert({"Children", ChildArr}); + Obj.insert({commentKindToString(I.Kind), ChildVal}); + return Obj; + } + + case CommentKind::CK_Unknown: { + Obj.insert({commentKindToString(I.Kind), I.Text}); + return Obj; + } + } + llvm_unreachable("Unknown comment kind encountered."); } static void maybeInsertLocation(std::optional Loc, @@ -245,6 +328,7 @@ static void extractDescriptionFromInfo(ArrayRef Descriptions, return; json::Value DescArr = Array(); json::Array &DescARef = *DescArr.getAsArray(); + DescARef.reserve(Descriptions.size()); for (const CommentInfo &Child : Descriptions) DescARef.emplace_back(extractValue(Child)); EnumValObj.insert({"EnumValueComments", DescArr}); @@ -260,6 +344,7 @@ static json::Value extractValue(const FunctionInfo &I, StringRef ParentInfoDir, json::Value ParamArr = Array(); json::Array &ParamARef = *ParamArr.getAsArray(); + ParamARef.reserve(I.Params.size()); for (const auto Val : enumerate(I.Params)) { json::Value V = Object(); auto &VRef = *V.getAsObject(); @@ -279,14 +364,14 @@ static json::Value extractValue(const EnumInfo &I, Object Obj = Object(); std::string EnumType = I.Scoped ? "enum class " : "enum "; EnumType += I.Name; - bool HasComment = std::any_of( - I.Members.begin(), I.Members.end(), - [](const EnumValueInfo &M) { return !M.Description.empty(); }); + bool HasComment = llvm::any_of( + I.Members, [](const EnumValueInfo &M) { return !M.Description.empty(); }); Obj.insert({"EnumName", EnumType}); Obj.insert({"HasComment", HasComment}); Obj.insert({"ID", toHex(toStringRef(I.USR))}); json::Value EnumArr = Array(); json::Array &EnumARef = *EnumArr.getAsArray(); + EnumARef.reserve(I.Members.size()); for (const EnumValueInfo &M : I.Members) { json::Value EnumValue = Object(); auto &EnumValObj = *EnumValue.getAsObject(); @@ -312,6 +397,7 @@ static void extractScopeChildren(const ScopeChildren &S, Object &Obj, const ClangDocContext &CDCtx) { json::Value NamespaceArr = Array(); json::Array &NamespaceARef = *NamespaceArr.getAsArray(); + NamespaceARef.reserve(S.Namespaces.size()); for (const Reference &Child : S.Namespaces) NamespaceARef.emplace_back(extractValue(Child, ParentInfoDir)); @@ -320,6 +406,7 @@ static void extractScopeChildren(const ScopeChildren &S, Object &Obj, json::Value RecordArr = Array(); json::Array &RecordARef = *RecordArr.getAsArray(); + RecordARef.reserve(S.Records.size()); for (const Reference &Child : S.Records) RecordARef.emplace_back(extractValue(Child, ParentInfoDir)); @@ -328,12 +415,15 @@ static void extractScopeChildren(const ScopeChildren &S, Object &Obj, json::Value FunctionArr = Array(); json::Array &FunctionARef = *FunctionArr.getAsArray(); + FunctionARef.reserve(S.Functions.size()); json::Value PublicFunctionArr = Array(); json::Array &PublicFunctionARef = *PublicFunctionArr.getAsArray(); + PublicFunctionARef.reserve(S.Functions.size()); json::Value ProtectedFunctionArr = Array(); json::Array &ProtectedFunctionARef = *ProtectedFunctionArr.getAsArray(); + ProtectedFunctionARef.reserve(S.Functions.size()); for (const FunctionInfo &Child : S.Functions) { json::Value F = extractValue(Child, ParentInfoDir, CDCtx); @@ -357,6 +447,7 @@ static void extractScopeChildren(const ScopeChildren &S, Object &Obj, json::Value EnumArr = Array(); auto &EnumARef = *EnumArr.getAsArray(); + EnumARef.reserve(S.Enums.size()); for (const EnumInfo &Child : S.Enums) EnumARef.emplace_back(extractValue(Child, CDCtx)); @@ -365,6 +456,7 @@ static void extractScopeChildren(const ScopeChildren &S, Object &Obj, json::Value TypedefArr = Array(); auto &TypedefARef = *TypedefArr.getAsArray(); + TypedefARef.reserve(S.Typedefs.size()); for (const TypedefInfo &Child : S.Typedefs) TypedefARef.emplace_back(extractValue(Child)); @@ -401,10 +493,13 @@ static json::Value extractValue(const RecordInfo &I, extractScopeChildren(I.Children, RecordValue, BasePath, CDCtx); json::Value PublicMembers = Array(); json::Array &PubMemberRef = *PublicMembers.getAsArray(); + PubMemberRef.reserve(I.Members.size()); json::Value ProtectedMembers = Array(); json::Array &ProtMemberRef = *ProtectedMembers.getAsArray(); + ProtMemberRef.reserve(I.Members.size()); json::Value PrivateMembers = Array(); json::Array &PrivMemberRef = *PrivateMembers.getAsArray(); + PrivMemberRef.reserve(I.Members.size()); for (const MemberTypeInfo &Member : I.Members) { json::Value MemberValue = Object(); auto &MVRef = *MemberValue.getAsObject(); @@ -436,20 +531,25 @@ static Error setupTemplateValue(const ClangDocContext &CDCtx, json::Value &V, auto InfoPath = I->getRelativeFilePath(""); SmallString<128> RelativePath = computeRelativePath("", InfoPath); sys::path::native(RelativePath, sys::path::Style::posix); + + auto *SSA = StylesheetArr.getAsArray(); + SSA->reserve(CDCtx.UserStylesheets.size()); for (const auto &FilePath : CDCtx.UserStylesheets) { SmallString<128> StylesheetPath = RelativePath; sys::path::append(StylesheetPath, sys::path::Style::posix, sys::path::filename(FilePath)); - StylesheetArr.getAsArray()->emplace_back(StylesheetPath); + SSA->emplace_back(StylesheetPath); } V.getAsObject()->insert({"Stylesheets", StylesheetArr}); json::Value ScriptArr = Array(); + auto *SCA = ScriptArr.getAsArray(); + SCA->reserve(CDCtx.JsScripts.size()); for (auto Script : CDCtx.JsScripts) { SmallString<128> JsPath = RelativePath; sys::path::append(JsPath, sys::path::Style::posix, sys::path::filename(Script)); - ScriptArr.getAsArray()->emplace_back(JsPath); + SCA->emplace_back(JsPath); } V.getAsObject()->insert({"Scripts", ScriptArr}); return Error::success(); diff --git a/external/llvm-project/clang-tools-extra/clang-doc/JSONGenerator.cpp b/external/llvm-project/clang-tools-extra/clang-doc/JSONGenerator.cpp new file mode 100644 index 000000000000..0f7cbafcf513 --- /dev/null +++ b/external/llvm-project/clang-tools-extra/clang-doc/JSONGenerator.cpp @@ -0,0 +1,542 @@ +#include "Generators.h" +#include "clang/Basic/Specifiers.h" +#include "llvm/Support/JSON.h" + +using namespace llvm; +using namespace llvm::json; + +namespace clang { +namespace doc { + +class JSONGenerator : public Generator { +public: + static const char *Format; + + Error generateDocs(StringRef RootDir, + llvm::StringMap> Infos, + const ClangDocContext &CDCtx) override; + Error createResources(ClangDocContext &CDCtx) override; + Error generateDocForInfo(Info *I, llvm::raw_ostream &OS, + const ClangDocContext &CDCtx) override; +}; + +const char *JSONGenerator::Format = "json"; + +static void serializeInfo(const TypedefInfo &I, json::Object &Obj, + std::optional RepositoryUrl); +static void serializeInfo(const EnumInfo &I, json::Object &Obj, + std::optional RepositoryUrl); + +static json::Object serializeLocation(const Location &Loc, + std::optional RepositoryUrl) { + Object LocationObj = Object(); + LocationObj["LineNumber"] = Loc.StartLineNumber; + LocationObj["Filename"] = Loc.Filename; + + if (!Loc.IsFileInRootDir || !RepositoryUrl) + return LocationObj; + SmallString<128> FileURL(*RepositoryUrl); + sys::path::append(FileURL, sys::path::Style::posix, Loc.Filename); + FileURL += "#" + std::to_string(Loc.StartLineNumber); + LocationObj["FileURL"] = FileURL; + return LocationObj; +} + +static json::Value serializeComment(const CommentInfo &I) { + // taken from PR #142273 + Object Obj = Object(); + + json::Value ChildVal = Object(); + Object &Child = *ChildVal.getAsObject(); + + json::Value ChildArr = Array(); + auto &CARef = *ChildArr.getAsArray(); + CARef.reserve(I.Children.size()); + for (const auto &C : I.Children) + CARef.emplace_back(serializeComment(*C)); + + switch (I.Kind) { + case CommentKind::CK_TextComment: { + Obj.insert({commentKindToString(I.Kind), I.Text}); + return Obj; + } + + case CommentKind::CK_BlockCommandComment: { + Child.insert({"Command", I.Name}); + Child.insert({"Children", ChildArr}); + Obj.insert({commentKindToString(I.Kind), ChildVal}); + return Obj; + } + + case CommentKind::CK_InlineCommandComment: { + json::Value ArgsArr = Array(); + auto &ARef = *ArgsArr.getAsArray(); + ARef.reserve(I.Args.size()); + for (const auto &Arg : I.Args) + ARef.emplace_back(Arg); + Child.insert({"Command", I.Name}); + Child.insert({"Args", ArgsArr}); + Child.insert({"Children", ChildArr}); + Obj.insert({commentKindToString(I.Kind), ChildVal}); + return Obj; + } + + case CommentKind::CK_ParamCommandComment: + case CommentKind::CK_TParamCommandComment: { + Child.insert({"ParamName", I.ParamName}); + Child.insert({"Direction", I.Direction}); + Child.insert({"Explicit", I.Explicit}); + Child.insert({"Children", ChildArr}); + Obj.insert({commentKindToString(I.Kind), ChildVal}); + return Obj; + } + + case CommentKind::CK_VerbatimBlockComment: { + Child.insert({"Text", I.Text}); + if (!I.CloseName.empty()) + Child.insert({"CloseName", I.CloseName}); + Child.insert({"Children", ChildArr}); + Obj.insert({commentKindToString(I.Kind), ChildVal}); + return Obj; + } + + case CommentKind::CK_VerbatimBlockLineComment: + case CommentKind::CK_VerbatimLineComment: { + Child.insert({"Text", I.Text}); + Child.insert({"Children", ChildArr}); + Obj.insert({commentKindToString(I.Kind), ChildVal}); + return Obj; + } + + case CommentKind::CK_HTMLStartTagComment: { + json::Value AttrKeysArray = json::Array(); + json::Value AttrValuesArray = json::Array(); + auto &KeyArr = *AttrKeysArray.getAsArray(); + auto &ValArr = *AttrValuesArray.getAsArray(); + KeyArr.reserve(I.AttrKeys.size()); + ValArr.reserve(I.AttrValues.size()); + for (const auto &K : I.AttrKeys) + KeyArr.emplace_back(K); + for (const auto &V : I.AttrValues) + ValArr.emplace_back(V); + Child.insert({"Name", I.Name}); + Child.insert({"SelfClosing", I.SelfClosing}); + Child.insert({"AttrKeys", AttrKeysArray}); + Child.insert({"AttrValues", AttrValuesArray}); + Child.insert({"Children", ChildArr}); + Obj.insert({commentKindToString(I.Kind), ChildVal}); + return Obj; + } + + case CommentKind::CK_HTMLEndTagComment: { + Child.insert({"Name", I.Name}); + Child.insert({"Children", ChildArr}); + Obj.insert({commentKindToString(I.Kind), ChildVal}); + return Obj; + } + + case CommentKind::CK_FullComment: + case CommentKind::CK_ParagraphComment: { + Child.insert({"Children", ChildArr}); + Obj.insert({commentKindToString(I.Kind), ChildVal}); + return Obj; + } + + case CommentKind::CK_Unknown: { + Obj.insert({commentKindToString(I.Kind), I.Text}); + return Obj; + } + } + llvm_unreachable("Unknown comment kind encountered."); +} + +static void serializeCommonAttributes(const Info &I, json::Object &Obj, + std::optional RepositoryUrl) { + Obj["Name"] = I.Name; + Obj["USR"] = toHex(toStringRef(I.USR)); + + if (!I.Path.empty()) + Obj["Path"] = I.Path; + + if (!I.Namespace.empty()) { + Obj["Namespace"] = json::Array(); + for (const auto &NS : I.Namespace) + Obj["Namespace"].getAsArray()->push_back(NS.Name); + } + + if (!I.Description.empty()) { + json::Value DescArray = json::Array(); + auto &DescArrayRef = *DescArray.getAsArray(); + DescArrayRef.reserve(I.Description.size()); + for (const auto &Comment : I.Description) + DescArrayRef.push_back(serializeComment(Comment)); + Obj["Description"] = DescArray; + } + + // Namespaces aren't SymbolInfos, so they dont have a DefLoc + if (I.IT != InfoType::IT_namespace) { + const auto *Symbol = static_cast(&I); + if (Symbol->DefLoc) + Obj["Location"] = + serializeLocation(Symbol->DefLoc.value(), RepositoryUrl); + } +} + +static void serializeReference(const Reference &Ref, Object &ReferenceObj) { + ReferenceObj["Path"] = Ref.Path; + ReferenceObj["Name"] = Ref.Name; + ReferenceObj["QualName"] = Ref.QualName; + ReferenceObj["USR"] = toHex(toStringRef(Ref.USR)); +} + +static void serializeReference(const SmallVector &References, + Object &Obj, std::string Key) { + json::Value ReferencesArray = Array(); + json::Array &ReferencesArrayRef = *ReferencesArray.getAsArray(); + ReferencesArrayRef.reserve(References.size()); + for (const auto &Reference : References) { + json::Value ReferenceVal = Object(); + auto &ReferenceObj = *ReferenceVal.getAsObject(); + serializeReference(Reference, ReferenceObj); + ReferencesArrayRef.push_back(ReferenceVal); + } + Obj[Key] = ReferencesArray; +} + +// Although namespaces and records both have ScopeChildren, they serialize them +// differently. Only enums, records, and typedefs are handled here. +static void serializeCommonChildren(const ScopeChildren &Children, + json::Object &Obj, + std::optional RepositoryUrl) { + if (!Children.Enums.empty()) { + json::Value EnumsArray = Array(); + auto &EnumsArrayRef = *EnumsArray.getAsArray(); + EnumsArrayRef.reserve(Children.Enums.size()); + for (const auto &Enum : Children.Enums) { + json::Value EnumVal = Object(); + auto &EnumObj = *EnumVal.getAsObject(); + serializeInfo(Enum, EnumObj, RepositoryUrl); + EnumsArrayRef.push_back(EnumVal); + } + Obj["Enums"] = EnumsArray; + } + + if (!Children.Typedefs.empty()) { + json::Value TypedefsArray = Array(); + auto &TypedefsArrayRef = *TypedefsArray.getAsArray(); + TypedefsArrayRef.reserve(Children.Typedefs.size()); + for (const auto &Typedef : Children.Typedefs) { + json::Value TypedefVal = Object(); + auto &TypedefObj = *TypedefVal.getAsObject(); + serializeInfo(Typedef, TypedefObj, RepositoryUrl); + TypedefsArrayRef.push_back(TypedefVal); + } + Obj["Typedefs"] = TypedefsArray; + } + + if (!Children.Records.empty()) { + json::Value RecordsArray = Array(); + auto &RecordsArrayRef = *RecordsArray.getAsArray(); + RecordsArrayRef.reserve(Children.Records.size()); + for (const auto &Record : Children.Records) { + json::Value RecordVal = Object(); + auto &RecordObj = *RecordVal.getAsObject(); + serializeReference(Record, RecordObj); + RecordsArrayRef.push_back(RecordVal); + } + Obj["Records"] = RecordsArray; + } +} + +static void serializeInfo(const TemplateInfo &Template, Object &Obj) { + json::Value TemplateVal = Object(); + auto &TemplateObj = *TemplateVal.getAsObject(); + + if (Template.Specialization) { + json::Value TemplateSpecializationVal = Object(); + auto &TemplateSpecializationObj = *TemplateSpecializationVal.getAsObject(); + TemplateSpecializationObj["SpecializationOf"] = + toHex(toStringRef(Template.Specialization->SpecializationOf)); + if (!Template.Specialization->Params.empty()) { + json::Value ParamsArray = Array(); + auto &ParamsArrayRef = *ParamsArray.getAsArray(); + ParamsArrayRef.reserve(Template.Specialization->Params.size()); + for (const auto &Param : Template.Specialization->Params) + ParamsArrayRef.push_back(Param.Contents); + TemplateSpecializationObj["Parameters"] = ParamsArray; + } + TemplateObj["Specialization"] = TemplateSpecializationVal; + } + + if (!Template.Params.empty()) { + json::Value ParamsArray = Array(); + auto &ParamsArrayRef = *ParamsArray.getAsArray(); + ParamsArrayRef.reserve(Template.Params.size()); + for (const auto &Param : Template.Params) + ParamsArrayRef.push_back(Param.Contents); + TemplateObj["Parameters"] = ParamsArray; + } + + Obj["Template"] = TemplateVal; +} + +static void serializeInfo(const TypeInfo &I, Object &Obj) { + Obj["Name"] = I.Type.Name; + Obj["QualName"] = I.Type.QualName; + Obj["USR"] = toHex(toStringRef(I.Type.USR)); + Obj["IsTemplate"] = I.IsTemplate; + Obj["IsBuiltIn"] = I.IsBuiltIn; +} + +static void serializeInfo(const FunctionInfo &F, json::Object &Obj, + std::optional RepositoryURL) { + serializeCommonAttributes(F, Obj, RepositoryURL); + Obj["IsStatic"] = F.IsStatic; + + auto ReturnTypeObj = Object(); + serializeInfo(F.ReturnType, ReturnTypeObj); + Obj["ReturnType"] = std::move(ReturnTypeObj); + + if (!F.Params.empty()) { + json::Value ParamsArray = json::Array(); + auto &ParamsArrayRef = *ParamsArray.getAsArray(); + ParamsArrayRef.reserve(F.Params.size()); + for (const auto &Param : F.Params) { + json::Value ParamVal = Object(); + auto &ParamObj = *ParamVal.getAsObject(); + ParamObj["Name"] = Param.Name; + ParamObj["Type"] = Param.Type.Name; + ParamsArrayRef.push_back(ParamVal); + } + Obj["Params"] = ParamsArray; + } + + if (F.Template) + serializeInfo(F.Template.value(), Obj); +} + +static void serializeInfo(const EnumInfo &I, json::Object &Obj, + std::optional RepositoryUrl) { + serializeCommonAttributes(I, Obj, RepositoryUrl); + Obj["Scoped"] = I.Scoped; + + if (I.BaseType) { + json::Value BaseTypeVal = Object(); + auto &BaseTypeObj = *BaseTypeVal.getAsObject(); + BaseTypeObj["Name"] = I.BaseType->Type.Name; + BaseTypeObj["QualName"] = I.BaseType->Type.QualName; + BaseTypeObj["USR"] = toHex(toStringRef(I.BaseType->Type.USR)); + Obj["BaseType"] = BaseTypeVal; + } + + if (!I.Members.empty()) { + json::Value MembersArray = Array(); + auto &MembersArrayRef = *MembersArray.getAsArray(); + MembersArrayRef.reserve(I.Members.size()); + for (const auto &Member : I.Members) { + json::Value MemberVal = Object(); + auto &MemberObj = *MemberVal.getAsObject(); + MemberObj["Name"] = Member.Name; + if (!Member.ValueExpr.empty()) + MemberObj["ValueExpr"] = Member.ValueExpr; + else + MemberObj["Value"] = Member.Value; + MembersArrayRef.push_back(MemberVal); + } + Obj["Members"] = MembersArray; + } +} + +static void serializeInfo(const TypedefInfo &I, json::Object &Obj, + std::optional RepositoryUrl) { + serializeCommonAttributes(I, Obj, RepositoryUrl); + Obj["TypeDeclaration"] = I.TypeDeclaration; + Obj["IsUsing"] = I.IsUsing; + json::Value TypeVal = Object(); + auto &TypeObj = *TypeVal.getAsObject(); + serializeInfo(I.Underlying, TypeObj); + Obj["Underlying"] = TypeVal; +} + +static void serializeInfo(const RecordInfo &I, json::Object &Obj, + std::optional RepositoryUrl) { + serializeCommonAttributes(I, Obj, RepositoryUrl); + Obj["FullName"] = I.FullName; + Obj["TagType"] = getTagType(I.TagType); + Obj["IsTypedef"] = I.IsTypeDef; + + if (!I.Children.Functions.empty()) { + json::Value PubFunctionsArray = Array(); + json::Array &PubFunctionsArrayRef = *PubFunctionsArray.getAsArray(); + json::Value ProtFunctionsArray = Array(); + json::Array &ProtFunctionsArrayRef = *ProtFunctionsArray.getAsArray(); + + for (const auto &Function : I.Children.Functions) { + json::Value FunctionVal = Object(); + auto &FunctionObj = *FunctionVal.getAsObject(); + serializeInfo(Function, FunctionObj, RepositoryUrl); + AccessSpecifier Access = Function.Access; + if (Access == AccessSpecifier::AS_public) + PubFunctionsArrayRef.push_back(FunctionVal); + else if (Access == AccessSpecifier::AS_protected) + ProtFunctionsArrayRef.push_back(FunctionVal); + } + + if (!PubFunctionsArrayRef.empty()) + Obj["PublicFunctions"] = PubFunctionsArray; + if (!ProtFunctionsArrayRef.empty()) + Obj["ProtectedFunctions"] = ProtFunctionsArray; + } + + if (!I.Members.empty()) { + json::Value PublicMembersArray = Array(); + json::Array &PubMembersArrayRef = *PublicMembersArray.getAsArray(); + json::Value ProtectedMembersArray = Array(); + json::Array &ProtMembersArrayRef = *ProtectedMembersArray.getAsArray(); + + for (const MemberTypeInfo &Member : I.Members) { + json::Value MemberVal = Object(); + auto &MemberObj = *MemberVal.getAsObject(); + MemberObj["Name"] = Member.Name; + MemberObj["Type"] = Member.Type.Name; + + if (Member.Access == AccessSpecifier::AS_public) + PubMembersArrayRef.push_back(MemberVal); + else if (Member.Access == AccessSpecifier::AS_protected) + ProtMembersArrayRef.push_back(MemberVal); + } + + if (!PubMembersArrayRef.empty()) + Obj["PublicMembers"] = PublicMembersArray; + if (!ProtMembersArrayRef.empty()) + Obj["ProtectedMembers"] = ProtectedMembersArray; + } + + if (!I.Bases.empty()) { + json::Value BasesArray = Array(); + json::Array &BasesArrayRef = *BasesArray.getAsArray(); + BasesArrayRef.reserve(I.Bases.size()); + for (const auto &BaseInfo : I.Bases) { + json::Value BaseInfoVal = Object(); + auto &BaseInfoObj = *BaseInfoVal.getAsObject(); + serializeInfo(BaseInfo, BaseInfoObj, RepositoryUrl); + BaseInfoObj["IsVirtual"] = BaseInfo.IsVirtual; + BaseInfoObj["Access"] = getAccessSpelling(BaseInfo.Access); + BaseInfoObj["IsParent"] = BaseInfo.IsParent; + BasesArrayRef.push_back(BaseInfoVal); + } + Obj["Bases"] = BasesArray; + } + + if (!I.Parents.empty()) + serializeReference(I.Parents, Obj, "Parents"); + + if (!I.VirtualParents.empty()) + serializeReference(I.VirtualParents, Obj, "VirtualParents"); + + if (I.Template) + serializeInfo(I.Template.value(), Obj); + + serializeCommonChildren(I.Children, Obj, RepositoryUrl); +} + +static void serializeInfo(const NamespaceInfo &I, json::Object &Obj, + std::optional RepositoryUrl) { + serializeCommonAttributes(I, Obj, RepositoryUrl); + + if (!I.Children.Namespaces.empty()) { + json::Value NamespacesArray = Array(); + auto &NamespacesArrayRef = *NamespacesArray.getAsArray(); + NamespacesArrayRef.reserve(I.Children.Namespaces.size()); + for (auto &Namespace : I.Children.Namespaces) { + json::Value NamespaceVal = Object(); + auto &NamespaceObj = *NamespaceVal.getAsObject(); + serializeReference(Namespace, NamespaceObj); + NamespacesArrayRef.push_back(NamespaceVal); + } + Obj["Namespaces"] = NamespacesArray; + } + + if (!I.Children.Functions.empty()) { + json::Value FunctionsArray = Array(); + auto &FunctionsArrayRef = *FunctionsArray.getAsArray(); + FunctionsArrayRef.reserve(I.Children.Functions.size()); + for (const auto &Function : I.Children.Functions) { + json::Value FunctionVal = Object(); + auto &FunctionObj = *FunctionVal.getAsObject(); + serializeInfo(Function, FunctionObj, RepositoryUrl); + FunctionsArrayRef.push_back(FunctionVal); + } + Obj["Functions"] = FunctionsArray; + } + + serializeCommonChildren(I.Children, Obj, RepositoryUrl); +} + +Error JSONGenerator::generateDocs( + StringRef RootDir, llvm::StringMap> Infos, + const ClangDocContext &CDCtx) { + StringSet<> CreatedDirs; + StringMap> FileToInfos; + for (const auto &Group : Infos) { + Info *Info = Group.getValue().get(); + + SmallString<128> Path; + sys::path::native(RootDir, Path); + sys::path::append(Path, Info->getRelativeFilePath("")); + if (!CreatedDirs.contains(Path)) { + if (std::error_code Err = sys::fs::create_directories(Path); + Err != std::error_code()) + return createFileError(Twine(Path), Err); + CreatedDirs.insert(Path); + } + + sys::path::append(Path, Info->getFileBaseName() + ".json"); + FileToInfos[Path].push_back(Info); + } + + for (const auto &Group : FileToInfos) { + std::error_code FileErr; + raw_fd_ostream InfoOS(Group.getKey(), FileErr, sys::fs::OF_Text); + if (FileErr) + return createFileError("cannot open file " + Group.getKey(), FileErr); + + for (const auto &Info : Group.getValue()) + if (Error Err = generateDocForInfo(Info, InfoOS, CDCtx)) + return Err; + } + + return Error::success(); +} + +Error JSONGenerator::generateDocForInfo(Info *I, raw_ostream &OS, + const ClangDocContext &CDCtx) { + json::Object Obj = Object(); + + switch (I->IT) { + case InfoType::IT_namespace: + serializeInfo(*static_cast(I), Obj, CDCtx.RepositoryUrl); + break; + case InfoType::IT_record: + serializeInfo(*static_cast(I), Obj, CDCtx.RepositoryUrl); + break; + case InfoType::IT_enum: + case InfoType::IT_function: + case InfoType::IT_typedef: + break; + case InfoType::IT_default: + return createStringError(inconvertibleErrorCode(), "unexpected info type"); + } + OS << llvm::formatv("{0:2}", llvm::json::Value(std::move(Obj))); + return Error::success(); +} + +Error JSONGenerator::createResources(ClangDocContext &CDCtx) { + return Error::success(); +} + +static GeneratorRegistry::Add JSON(JSONGenerator::Format, + "Generator for JSON output."); +volatile int JSONGeneratorAnchorSource = 0; +} // namespace doc +} // namespace clang diff --git a/external/llvm-project/clang-tools-extra/clang-doc/MDGenerator.cpp b/external/llvm-project/clang-tools-extra/clang-doc/MDGenerator.cpp index ccd6175c96cb..2becccf8b07d 100644 --- a/external/llvm-project/clang-tools-extra/clang-doc/MDGenerator.cpp +++ b/external/llvm-project/clang-tools-extra/clang-doc/MDGenerator.cpp @@ -75,39 +75,49 @@ static void maybeWriteSourceFileRef(llvm::raw_ostream &OS, } static void writeDescription(const CommentInfo &I, raw_ostream &OS) { - if (I.Kind == "FullComment") { + switch (I.Kind) { + case CommentKind::CK_FullComment: for (const auto &Child : I.Children) writeDescription(*Child, OS); - } else if (I.Kind == "ParagraphComment") { + break; + + case CommentKind::CK_ParagraphComment: for (const auto &Child : I.Children) writeDescription(*Child, OS); writeNewLine(OS); - } else if (I.Kind == "BlockCommandComment") { + break; + + case CommentKind::CK_BlockCommandComment: OS << genEmphasis(I.Name); for (const auto &Child : I.Children) writeDescription(*Child, OS); - } else if (I.Kind == "InlineCommandComment") { + break; + + case CommentKind::CK_InlineCommandComment: OS << genEmphasis(I.Name) << " " << I.Text; - } else if (I.Kind == "ParamCommandComment") { - std::string Direction = I.Explicit ? (" " + I.Direction).str() : ""; - OS << genEmphasis(I.ParamName) << I.Text << Direction; - for (const auto &Child : I.Children) - writeDescription(*Child, OS); - } else if (I.Kind == "TParamCommandComment") { + break; + + case CommentKind::CK_ParamCommandComment: + case CommentKind::CK_TParamCommandComment: { std::string Direction = I.Explicit ? (" " + I.Direction).str() : ""; OS << genEmphasis(I.ParamName) << I.Text << Direction; for (const auto &Child : I.Children) writeDescription(*Child, OS); - } else if (I.Kind == "VerbatimBlockComment") { + break; + } + + case CommentKind::CK_VerbatimBlockComment: for (const auto &Child : I.Children) writeDescription(*Child, OS); - } else if (I.Kind == "VerbatimBlockLineComment") { - OS << I.Text; - writeNewLine(OS); - } else if (I.Kind == "VerbatimLineComment") { + break; + + case CommentKind::CK_VerbatimBlockLineComment: + case CommentKind::CK_VerbatimLineComment: OS << I.Text; writeNewLine(OS); - } else if (I.Kind == "HTMLStartTagComment") { + break; + + case CommentKind::CK_HTMLStartTagComment: { if (I.AttrKeys.size() != I.AttrValues.size()) return; std::string Buffer; @@ -117,12 +127,20 @@ static void writeDescription(const CommentInfo &I, raw_ostream &OS) { std::string CloseTag = I.SelfClosing ? "/>" : ">"; writeLine("<" + I.Name + Attrs.str() + CloseTag, OS); - } else if (I.Kind == "HTMLEndTagComment") { + break; + } + + case CommentKind::CK_HTMLEndTagComment: writeLine("", OS); - } else if (I.Kind == "TextComment") { + break; + + case CommentKind::CK_TextComment: OS << I.Text; - } else { - OS << "Unknown comment kind: " << I.Kind << ".\n\n"; + break; + + case CommentKind::CK_Unknown: + OS << "Unknown comment kind: " << static_cast(I.Kind) << ".\n\n"; + break; } } diff --git a/external/llvm-project/clang-tools-extra/clang-doc/Mapper.cpp b/external/llvm-project/clang-tools-extra/clang-doc/Mapper.cpp index a17645c3f3a3..9f640b5325da 100644 --- a/external/llvm-project/clang-tools-extra/clang-doc/Mapper.cpp +++ b/external/llvm-project/clang-tools-extra/clang-doc/Mapper.cpp @@ -7,13 +7,13 @@ //===----------------------------------------------------------------------===// #include "Mapper.h" -#include "BitcodeWriter.h" #include "Serialize.h" #include "clang/AST/Comment.h" #include "clang/Index/USRGeneration.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringSet.h" #include "llvm/Support/Mutex.h" +#include "llvm/Support/TimeProfiler.h" namespace clang { namespace doc { @@ -40,48 +40,66 @@ Location MapASTVisitor::getDeclLocation(const NamedDecl *D) const { } void MapASTVisitor::HandleTranslationUnit(ASTContext &Context) { + if (CDCtx.FTimeTrace) + llvm::timeTraceProfilerInitialize(200, "clang-doc"); TraverseDecl(Context.getTranslationUnitDecl()); + if (CDCtx.FTimeTrace) + llvm::timeTraceProfilerFinishThread(); } template bool MapASTVisitor::mapDecl(const T *D, bool IsDefinition) { - // If we're looking a decl not in user files, skip this decl. - if (D->getASTContext().getSourceManager().isInSystemHeader(D->getLocation())) - return true; + llvm::TimeTraceScope TS("Mapping declaration"); + { + llvm::TimeTraceScope TS("Preamble"); + // If we're looking a decl not in user files, skip this decl. + if (D->getASTContext().getSourceManager().isInSystemHeader( + D->getLocation())) + return true; - // Skip function-internal decls. - if (D->getParentFunctionOrMethod()) - return true; + // Skip function-internal decls. + if (D->getParentFunctionOrMethod()) + return true; + } + + std::pair, std::unique_ptr> CP; - llvm::SmallString<128> USR; - // If there is an error generating a USR for the decl, skip this decl. - if (index::generateUSRForDecl(D, USR)) - return true; - // Prevent Visiting USR twice { - llvm::sys::SmartScopedLock Guard(USRVisitedGuard); - StringRef Visited = USR.str(); - if (USRVisited.count(Visited) && !isTypedefAnonRecord(D)) + llvm::TimeTraceScope TS("emit info from astnode"); + llvm::SmallString<128> USR; + // If there is an error generating a USR for the decl, skip this decl. + if (index::generateUSRForDecl(D, USR)) return true; - // We considered a USR to be visited only when its defined - if (IsDefinition) - USRVisited.insert(Visited); + // Prevent Visiting USR twice + { + llvm::sys::SmartScopedLock Guard(USRVisitedGuard); + StringRef Visited = USR.str(); + if (USRVisited.count(Visited) && !isTypedefAnonRecord(D)) + return true; + // We considered a USR to be visited only when its defined + if (IsDefinition) + USRVisited.insert(Visited); + } + bool IsFileInRootDir; + llvm::SmallString<128> File = + getFile(D, D->getASTContext(), CDCtx.SourceRoot, IsFileInRootDir); + CP = serialize::emitInfo(D, getComment(D, D->getASTContext()), + getDeclLocation(D), CDCtx.PublicOnly); + } + + auto &[Child, Parent] = CP; + + { + llvm::TimeTraceScope TS("serialized info into bitcode"); + // A null in place of a valid Info indicates that the serializer is skipping + // this decl for some reason (e.g. we're only reporting public decls). + if (Child) + CDCtx.ECtx->reportResult(llvm::toHex(llvm::toStringRef(Child->USR)), + serialize::serialize(Child)); + if (Parent) + CDCtx.ECtx->reportResult(llvm::toHex(llvm::toStringRef(Parent->USR)), + serialize::serialize(Parent)); } - bool IsFileInRootDir; - llvm::SmallString<128> File = - getFile(D, D->getASTContext(), CDCtx.SourceRoot, IsFileInRootDir); - auto [Child, Parent] = - serialize::emitInfo(D, getComment(D, D->getASTContext()), - getDeclLocation(D), CDCtx.PublicOnly); - - // A null in place of a valid Info indicates that the serializer is skipping - // this decl for some reason (e.g. we're only reporting public decls). - if (Child) - CDCtx.ECtx->reportResult(llvm::toHex(llvm::toStringRef(Child->USR)), - serialize::serialize(Child)); - if (Parent) - CDCtx.ECtx->reportResult(llvm::toHex(llvm::toStringRef(Parent->USR)), - serialize::serialize(Parent)); return true; } diff --git a/external/llvm-project/clang-tools-extra/clang-doc/Representation.cpp b/external/llvm-project/clang-tools-extra/clang-doc/Representation.cpp index 9ab2f342d969..71a926f1c73e 100644 --- a/external/llvm-project/clang-tools-extra/clang-doc/Representation.cpp +++ b/external/llvm-project/clang-tools-extra/clang-doc/Representation.cpp @@ -20,12 +20,68 @@ // //===----------------------------------------------------------------------===// #include "Representation.h" +#include "llvm/ADT/StringMap.h" #include "llvm/Support/Error.h" #include "llvm/Support/Path.h" namespace clang { namespace doc { +CommentKind stringToCommentKind(llvm::StringRef KindStr) { + static const llvm::StringMap KindMap = { + {"FullComment", CommentKind::CK_FullComment}, + {"ParagraphComment", CommentKind::CK_ParagraphComment}, + {"TextComment", CommentKind::CK_TextComment}, + {"InlineCommandComment", CommentKind::CK_InlineCommandComment}, + {"HTMLStartTagComment", CommentKind::CK_HTMLStartTagComment}, + {"HTMLEndTagComment", CommentKind::CK_HTMLEndTagComment}, + {"BlockCommandComment", CommentKind::CK_BlockCommandComment}, + {"ParamCommandComment", CommentKind::CK_ParamCommandComment}, + {"TParamCommandComment", CommentKind::CK_TParamCommandComment}, + {"VerbatimBlockComment", CommentKind::CK_VerbatimBlockComment}, + {"VerbatimBlockLineComment", CommentKind::CK_VerbatimBlockLineComment}, + {"VerbatimLineComment", CommentKind::CK_VerbatimLineComment}, + }; + + auto It = KindMap.find(KindStr); + if (It != KindMap.end()) { + return It->second; + } + return CommentKind::CK_Unknown; +} + +llvm::StringRef commentKindToString(CommentKind Kind) { + switch (Kind) { + case CommentKind::CK_FullComment: + return "FullComment"; + case CommentKind::CK_ParagraphComment: + return "ParagraphComment"; + case CommentKind::CK_TextComment: + return "TextComment"; + case CommentKind::CK_InlineCommandComment: + return "InlineCommandComment"; + case CommentKind::CK_HTMLStartTagComment: + return "HTMLStartTagComment"; + case CommentKind::CK_HTMLEndTagComment: + return "HTMLEndTagComment"; + case CommentKind::CK_BlockCommandComment: + return "BlockCommandComment"; + case CommentKind::CK_ParamCommandComment: + return "ParamCommandComment"; + case CommentKind::CK_TParamCommandComment: + return "TParamCommandComment"; + case CommentKind::CK_VerbatimBlockComment: + return "VerbatimBlockComment"; + case CommentKind::CK_VerbatimBlockLineComment: + return "VerbatimBlockLineComment"; + case CommentKind::CK_VerbatimLineComment: + return "VerbatimLineComment"; + case CommentKind::CK_Unknown: + return "Unknown"; + } + llvm_unreachable("Unhandled CommentKind"); +} + namespace { const SymbolID EmptySID = SymbolID(); @@ -87,10 +143,11 @@ mergeInfos(std::vector> &Values) { return reduce(Values); case InfoType::IT_typedef: return reduce(Values); - default: + case InfoType::IT_default: return llvm::createStringError(llvm::inconvertibleErrorCode(), "unexpected info type"); } + llvm_unreachable("unhandled enumerator"); } bool CommentInfo::operator==(const CommentInfo &Other) const { @@ -369,9 +426,11 @@ ClangDocContext::ClangDocContext(tooling::ExecutionContext *ECtx, StringRef OutDirectory, StringRef SourceRoot, StringRef RepositoryUrl, StringRef RepositoryLinePrefix, StringRef Base, - std::vector UserStylesheets) + std::vector UserStylesheets, + bool FTimeTrace) : ECtx(ECtx), ProjectName(ProjectName), PublicOnly(PublicOnly), - OutDirectory(OutDirectory), UserStylesheets(UserStylesheets), Base(Base) { + FTimeTrace(FTimeTrace), OutDirectory(OutDirectory), + UserStylesheets(UserStylesheets), Base(Base) { llvm::SmallString<128> SourceRootDir(SourceRoot); if (SourceRoot.empty()) // If no SourceRoot was provided the current path is used as the default diff --git a/external/llvm-project/clang-tools-extra/clang-doc/Representation.h b/external/llvm-project/clang-tools-extra/clang-doc/Representation.h index a3a6217f76bb..75da50064581 100644 --- a/external/llvm-project/clang-tools-extra/clang-doc/Representation.h +++ b/external/llvm-project/clang-tools-extra/clang-doc/Representation.h @@ -45,6 +45,25 @@ enum class InfoType { IT_typedef }; +enum class CommentKind { + CK_FullComment, + CK_ParagraphComment, + CK_TextComment, + CK_InlineCommandComment, + CK_HTMLStartTagComment, + CK_HTMLEndTagComment, + CK_BlockCommandComment, + CK_ParamCommandComment, + CK_TParamCommandComment, + CK_VerbatimBlockComment, + CK_VerbatimBlockLineComment, + CK_VerbatimLineComment, + CK_Unknown +}; + +CommentKind stringToCommentKind(llvm::StringRef KindStr); +llvm::StringRef commentKindToString(CommentKind Kind); + // A representation of a parsed comment. struct CommentInfo { CommentInfo() = default; @@ -60,13 +79,13 @@ struct CommentInfo { // the vector. bool operator<(const CommentInfo &Other) const; - // TODO: The Kind field should be an enum, so we can switch on it easily. - SmallString<16> - Kind; // Kind of comment (FullComment, ParagraphComment, TextComment, - // InlineCommandComment, HTMLStartTagComment, HTMLEndTagComment, - // BlockCommandComment, ParamCommandComment, - // TParamCommandComment, VerbatimBlockComment, - // VerbatimBlockLineComment, VerbatimLineComment). + CommentKind Kind = CommentKind:: + CK_Unknown; // Kind of comment (FullComment, ParagraphComment, + // TextComment, InlineCommandComment, HTMLStartTagComment, + // HTMLEndTagComment, BlockCommandComment, + // ParamCommandComment, TParamCommandComment, + // VerbatimBlockComment, VerbatimBlockLineComment, + // VerbatimLineComment). SmallString<64> Text; // Text of the comment. SmallString<16> Name; // Name of the comment (for Verbatim and HTML). SmallString<8> Direction; // Parameter direction (for (T)ParamCommand). @@ -524,10 +543,13 @@ struct ClangDocContext { ClangDocContext(tooling::ExecutionContext *ECtx, StringRef ProjectName, bool PublicOnly, StringRef OutDirectory, StringRef SourceRoot, StringRef RepositoryUrl, StringRef RepositoryCodeLinePrefix, - StringRef Base, std::vector UserStylesheets); + StringRef Base, std::vector UserStylesheets, + bool FTimeTrace = false); tooling::ExecutionContext *ECtx; std::string ProjectName; // Name of project clang-doc is documenting. bool PublicOnly; // Indicates if only public declarations are documented. + bool FTimeTrace; // Indicates if ftime trace is turned on + int Granularity; // Granularity of ftime trace std::string OutDirectory; // Directory for outputting generated files. std::string SourceRoot; // Directory where processed files are stored. Links // to definition locations will only be generated if diff --git a/external/llvm-project/clang-tools-extra/clang-doc/Serialize.cpp b/external/llvm-project/clang-tools-extra/clang-doc/Serialize.cpp index 3932a939de97..820e8bfd8e64 100644 --- a/external/llvm-project/clang-tools-extra/clang-doc/Serialize.cpp +++ b/external/llvm-project/clang-tools-extra/clang-doc/Serialize.cpp @@ -270,7 +270,7 @@ class ClangDocCommentVisitor }; void ClangDocCommentVisitor::parseComment(const comments::Comment *C) { - CurrentCI.Kind = C->getCommentKindName(); + CurrentCI.Kind = stringToCommentKind(C->getCommentKindName()); ConstCommentVisitor::visit(C); for (comments::Comment *Child : llvm::make_range(C->child_begin(), C->child_end())) { @@ -388,9 +388,11 @@ std::string serialize(std::unique_ptr &I) { return serialize(*static_cast(I.get())); case InfoType::IT_function: return serialize(*static_cast(I.get())); - default: + case InfoType::IT_typedef: + case InfoType::IT_default: return ""; } + llvm_unreachable("unhandled enumerator"); } static void parseFullComment(const FullComment *C, CommentInfo &CI) { @@ -525,9 +527,13 @@ static std::unique_ptr makeAndInsertIntoParent(ChildType Child) { InsertChild(ParentRec->Children, std::forward(Child)); return ParentRec; } - default: - llvm_unreachable("Invalid reference type for parent namespace"); + case InfoType::IT_default: + case InfoType::IT_enum: + case InfoType::IT_function: + case InfoType::IT_typedef: + break; } + llvm_unreachable("Invalid reference type for parent namespace"); } // There are two uses for this function. @@ -742,6 +748,7 @@ static void populateFunctionInfo(FunctionInfo &I, const FunctionDecl *D, I.ReturnType = getTypeInfoForType(D->getReturnType(), LO); I.Prototype = getFunctionPrototype(D); parseParameters(I, D); + I.IsStatic = D->isStatic(); populateTemplateParameters(I.Template, D); diff --git a/external/llvm-project/clang-tools-extra/clang-doc/YAMLGenerator.cpp b/external/llvm-project/clang-tools-extra/clang-doc/YAMLGenerator.cpp index 8c110b34e8e2..897b5d5ae4c9 100644 --- a/external/llvm-project/clang-tools-extra/clang-doc/YAMLGenerator.cpp +++ b/external/llvm-project/clang-tools-extra/clang-doc/YAMLGenerator.cpp @@ -65,6 +65,34 @@ template <> struct ScalarEnumerationTraits { } }; +template <> struct ScalarEnumerationTraits { + static void enumeration(IO &IO, clang::doc::CommentKind &Value) { + IO.enumCase(Value, "FullComment", clang::doc::CommentKind::CK_FullComment); + IO.enumCase(Value, "ParagraphComment", + clang::doc::CommentKind::CK_ParagraphComment); + IO.enumCase(Value, "TextComment", clang::doc::CommentKind::CK_TextComment); + IO.enumCase(Value, "InlineCommandComment", + clang::doc::CommentKind::CK_InlineCommandComment); + IO.enumCase(Value, "HTMLStartTagComment", + clang::doc::CommentKind::CK_HTMLStartTagComment); + IO.enumCase(Value, "HTMLEndTagComment", + clang::doc::CommentKind::CK_HTMLEndTagComment); + IO.enumCase(Value, "BlockCommandComment", + clang::doc::CommentKind::CK_BlockCommandComment); + IO.enumCase(Value, "ParamCommandComment", + clang::doc::CommentKind::CK_ParamCommandComment); + IO.enumCase(Value, "TParamCommandComment", + clang::doc::CommentKind::CK_TParamCommandComment); + IO.enumCase(Value, "VerbatimBlockComment", + clang::doc::CommentKind::CK_VerbatimBlockComment); + IO.enumCase(Value, "VerbatimBlockLineComment", + clang::doc::CommentKind::CK_VerbatimBlockLineComment); + IO.enumCase(Value, "VerbatimLineComment", + clang::doc::CommentKind::CK_VerbatimLineComment); + IO.enumCase(Value, "Unknown", clang::doc::CommentKind::CK_Unknown); + } +}; + // Scalars to YAML output. template struct ScalarTraits> { @@ -149,7 +177,7 @@ static void recordInfoMapping(IO &IO, RecordInfo &I) { } static void commentInfoMapping(IO &IO, CommentInfo &I) { - IO.mapOptional("Kind", I.Kind, SmallString<16>()); + IO.mapOptional("Kind", I.Kind, CommentKind::CK_Unknown); IO.mapOptional("Text", I.Text, SmallString<64>()); IO.mapOptional("Name", I.Name, SmallString<16>()); IO.mapOptional("Direction", I.Direction, SmallString<8>()); diff --git a/external/llvm-project/clang-tools-extra/clang-doc/assets/namespace-template.mustache b/external/llvm-project/clang-tools-extra/clang-doc/assets/namespace-template.mustache index 12dc93069d1c..1a44ed3c3ccc 100644 --- a/external/llvm-project/clang-tools-extra/clang-doc/assets/namespace-template.mustache +++ b/external/llvm-project/clang-tools-extra/clang-doc/assets/namespace-template.mustache @@ -23,23 +23,79 @@
- Content + {{#Enums}} +
+

Enumerations

+
+ {{#Obj}} + {{>EnumPartial}} + {{/Obj}} +
+
+ {{/Enums}} + {{#Record}} +
+

Inner Classes

+ +
+ {{/Record}}
diff --git a/external/llvm-project/clang-tools-extra/clang-doc/tool/ClangDocMain.cpp b/external/llvm-project/clang-tools-extra/clang-doc/tool/ClangDocMain.cpp index 8253ef298db4..3bb67baf6573 100644 --- a/external/llvm-project/clang-tools-extra/clang-doc/tool/ClangDocMain.cpp +++ b/external/llvm-project/clang-tools-extra/clang-doc/tool/ClangDocMain.cpp @@ -35,6 +35,7 @@ #include "llvm/Support/Process.h" #include "llvm/Support/Signals.h" #include "llvm/Support/ThreadPool.h" +#include "llvm/Support/TimeProfiler.h" #include "llvm/Support/raw_ostream.h" #include #include @@ -104,7 +105,12 @@ static llvm::cl::opt RepositoryCodeLinePrefix( llvm::cl::desc("Prefix of line code for repository."), llvm::cl::cat(ClangDocCategory)); -enum OutputFormatTy { md, yaml, html, mustache }; +static llvm::cl::opt FTimeTrace("ftime-trace", llvm::cl::desc(R"( +Turn on time profiler. Generates clang-doc-tracing.json)"), + llvm::cl::init(false), + llvm::cl::cat(ClangDocCategory)); + +enum OutputFormatTy { md, yaml, html, mustache, json }; static llvm::cl::opt FormatEnum( "format", llvm::cl::desc("Format for outputted docs."), @@ -115,7 +121,9 @@ static llvm::cl::opt FormatEnum( clEnumValN(OutputFormatTy::html, "html", "Documentation in HTML format."), clEnumValN(OutputFormatTy::mustache, "mustache", - "Documentation in mustache HTML format")), + "Documentation in mustache HTML format"), + clEnumValN(OutputFormatTy::json, "json", + "Documentation in JSON format")), llvm::cl::init(OutputFormatTy::yaml), llvm::cl::cat(ClangDocCategory)); static llvm::ExitOnError ExitOnErr; @@ -130,6 +138,8 @@ static std::string getFormatString() { return "html"; case OutputFormatTy::mustache: return "mustache"; + case OutputFormatTy::json: + return "json"; } llvm_unreachable("Unknown OutputFormatTy"); } @@ -261,7 +271,8 @@ static llvm::Error handleMappingFailures(llvm::Error Err) { static llvm::Error createDirectories(llvm::StringRef OutDirectory) { if (std::error_code Err = llvm::sys::fs::create_directories(OutDirectory)) - return llvm::createFileError(OutDirectory, Err); + return llvm::createFileError(OutDirectory, Err, + "failed to create directory."); return llvm::Error::success(); } @@ -286,115 +297,162 @@ Example usage for a project using a compile commands database: auto Executor = ExitOnErr(clang::tooling::createExecutorFromCommandLineArgs( argc, argv, ClangDocCategory, Overview)); - // Fail early if an invalid format was provided. - std::string Format = getFormatString(); - llvm::outs() << "Emiting docs in " << Format << " format.\n"; - auto G = ExitOnErr(doc::findGeneratorByName(Format)); - - ArgumentsAdjuster ArgAdjuster; - if (!DoxygenOnly) - ArgAdjuster = combineAdjusters( - getInsertArgumentAdjuster("-fparse-all-comments", - tooling::ArgumentInsertPosition::END), - ArgAdjuster); - - clang::doc::ClangDocContext CDCtx = { - Executor->getExecutionContext(), - ProjectName, - PublicOnly, - OutDirectory, - SourceRoot, - RepositoryUrl, - RepositoryCodeLinePrefix, - BaseDirectory, - {UserStylesheets.begin(), UserStylesheets.end()}}; - - if (Format == "html") { - ExitOnErr(getHtmlAssetFiles(argv[0], CDCtx)); - } - - if (Format == "mustache") { - ExitOnErr(getMustacheHtmlFiles(argv[0], CDCtx)); - } - - // Mapping phase - llvm::outs() << "Mapping decls...\n"; - ExitOnErr(handleMappingFailures( - Executor->execute(doc::newMapperActionFactory(CDCtx), ArgAdjuster))); - - // Collect values into output by key. - // In ToolResults, the Key is the hashed USR and the value is the - // bitcode-encoded representation of the Info object. - llvm::outs() << "Collecting infos...\n"; - llvm::StringMap> USRToBitcode; - Executor->getToolResults()->forEachResult( - [&](StringRef Key, StringRef Value) { - USRToBitcode[Key].emplace_back(Value); - }); - - // Collects all Infos according to their unique USR value. This map is added - // to from the thread pool below and is protected by the USRToInfoMutex. - llvm::sys::Mutex USRToInfoMutex; - llvm::StringMap> USRToInfo; - - // First reducing phase (reduce all decls into one info per decl). - llvm::outs() << "Reducing " << USRToBitcode.size() << " infos...\n"; - std::atomic Error; - Error = false; - llvm::sys::Mutex IndexMutex; - // ExecutorConcurrency is a flag exposed by AllTUsExecution.h - llvm::DefaultThreadPool Pool(llvm::hardware_concurrency(ExecutorConcurrency)); - for (auto &Group : USRToBitcode) { - Pool.async([&]() { - std::vector> Infos; - for (auto &Bitcode : Group.getValue()) { - llvm::BitstreamCursor Stream(Bitcode); - doc::ClangDocBitcodeReader Reader(Stream); - auto ReadInfos = Reader.readBitcode(); - if (!ReadInfos) { - llvm::errs() << toString(ReadInfos.takeError()) << "\n"; - Error = true; - return; - } - std::move(ReadInfos->begin(), ReadInfos->end(), - std::back_inserter(Infos)); - } - - auto Reduced = doc::mergeInfos(Infos); - if (!Reduced) { - llvm::errs() << llvm::toString(Reduced.takeError()); - return; - } - - // Add a reference to this Info in the Index - { - std::lock_guard Guard(IndexMutex); - clang::doc::Generator::addInfoToIndex(CDCtx.Idx, Reduced.get().get()); - } + // turns on ftime trace profiling + if (FTimeTrace) + llvm::timeTraceProfilerInitialize(200, "clang-doc"); + { + llvm::TimeTraceScope("main"); + + // Fail early if an invalid format was provided. + std::string Format = getFormatString(); + llvm::outs() << "Emiting docs in " << Format << " format.\n"; + auto G = ExitOnErr(doc::findGeneratorByName(Format)); + + ArgumentsAdjuster ArgAdjuster; + if (!DoxygenOnly) + ArgAdjuster = combineAdjusters( + getInsertArgumentAdjuster("-fparse-all-comments", + tooling::ArgumentInsertPosition::END), + ArgAdjuster); + + clang::doc::ClangDocContext CDCtx = { + Executor->getExecutionContext(), + ProjectName, + PublicOnly, + OutDirectory, + SourceRoot, + RepositoryUrl, + RepositoryCodeLinePrefix, + BaseDirectory, + {UserStylesheets.begin(), UserStylesheets.end()}, + FTimeTrace}; + + if (Format == "html") { + ExitOnErr(getHtmlAssetFiles(argv[0], CDCtx)); + } else if (Format == "mustache") { + ExitOnErr(getMustacheHtmlFiles(argv[0], CDCtx)); + } - // Save in the result map (needs a lock due to threaded access). - { - std::lock_guard Guard(USRToInfoMutex); - USRToInfo[Group.getKey()] = std::move(Reduced.get()); + llvm::timeTraceProfilerBegin("Executor Launch", "total runtime"); + // Mapping phase + llvm::outs() << "Mapping decls...\n"; + ExitOnErr(handleMappingFailures( + Executor->execute(doc::newMapperActionFactory(CDCtx), ArgAdjuster))); + llvm::timeTraceProfilerEnd(); + + // Collect values into output by key. + // In ToolResults, the Key is the hashed USR and the value is the + // bitcode-encoded representation of the Info object. + llvm::timeTraceProfilerBegin("Collect Info", "total runtime"); + llvm::outs() << "Collecting infos...\n"; + llvm::StringMap> USRToBitcode; + Executor->getToolResults()->forEachResult( + [&](StringRef Key, StringRef Value) { + USRToBitcode[Key].emplace_back(Value); + }); + llvm::timeTraceProfilerEnd(); + + // Collects all Infos according to their unique USR value. This map is added + // to from the thread pool below and is protected by the USRToInfoMutex. + llvm::sys::Mutex USRToInfoMutex; + llvm::StringMap> USRToInfo; + + // First reducing phase (reduce all decls into one info per decl). + llvm::outs() << "Reducing " << USRToBitcode.size() << " infos...\n"; + std::atomic Error; + Error = false; + llvm::sys::Mutex IndexMutex; + // ExecutorConcurrency is a flag exposed by AllTUsExecution.h + llvm::DefaultThreadPool Pool( + llvm::hardware_concurrency(ExecutorConcurrency)); + { + llvm::TimeTraceScope TS("Reduce"); + for (auto &Group : USRToBitcode) { + Pool.async([&]() { // time trace decoding bitcode + if (FTimeTrace) + llvm::timeTraceProfilerInitialize(200, "clang-doc"); + + std::vector> Infos; + { + llvm::TimeTraceScope Red("decoding bitcode"); + for (auto &Bitcode : Group.getValue()) { + llvm::BitstreamCursor Stream(Bitcode); + doc::ClangDocBitcodeReader Reader(Stream); + auto ReadInfos = Reader.readBitcode(); + if (!ReadInfos) { + llvm::errs() << toString(ReadInfos.takeError()) << "\n"; + Error = true; + return; + } + std::move(ReadInfos->begin(), ReadInfos->end(), + std::back_inserter(Infos)); + } + } // time trace decoding bitcode + + std::unique_ptr Reduced; + + { + llvm::TimeTraceScope Merge("merging bitcode"); + auto ExpReduced = doc::mergeInfos(Infos); + + if (!ExpReduced) { + llvm::errs() << llvm::toString(ExpReduced.takeError()); + return; + } + Reduced = std::move(*ExpReduced); + } // time trace merging bitcode + + // Add a reference to this Info in the Index + { + llvm::TimeTraceScope Merge("addInfoToIndex"); + std::lock_guard Guard(IndexMutex); + clang::doc::Generator::addInfoToIndex(CDCtx.Idx, Reduced.get()); + } + // Save in the result map (needs a lock due to threaded access). + { + llvm::TimeTraceScope Merge("USRToInfo"); + std::lock_guard Guard(USRToInfoMutex); + USRToInfo[Group.getKey()] = std::move(Reduced); + } + + if (CDCtx.FTimeTrace) + llvm::timeTraceProfilerFinishThread(); + }); } - }); - } - Pool.wait(); + Pool.wait(); + } // time trace reduce - if (Error) - return 1; + if (Error) + return 1; - sortUsrToInfo(USRToInfo); - - // Ensure the root output directory exists. - ExitOnErr(createDirectories(OutDirectory)); - - // Run the generator. - llvm::outs() << "Generating docs...\n"; - ExitOnErr(G->generateDocs(OutDirectory, std::move(USRToInfo), CDCtx)); - llvm::outs() << "Generating assets for docs...\n"; - ExitOnErr(G->createResources(CDCtx)); + { + llvm::TimeTraceScope Sort("Sort USRToInfo"); + sortUsrToInfo(USRToInfo); + } + llvm::timeTraceProfilerBegin("Writing output", "total runtime"); + // Ensure the root output directory exists. + ExitOnErr(createDirectories(OutDirectory)); + + // Run the generator. + llvm::outs() << "Generating docs...\n"; + + ExitOnErr(G->generateDocs(OutDirectory, std::move(USRToInfo), CDCtx)); + llvm::outs() << "Generating assets for docs...\n"; + ExitOnErr(G->createResources(CDCtx)); + llvm::timeTraceProfilerEnd(); + } // time trace main + + if (FTimeTrace) { + std::error_code EC; + llvm::raw_fd_ostream OS("clang-doc-tracing.json", EC, + llvm::sys::fs::OF_Text); + if (!EC) { + llvm::timeTraceProfilerWrite(OS); + llvm::timeTraceProfilerCleanup(); + } else + return 1; + } return 0; } diff --git a/external/llvm-project/clang-tools-extra/clang-include-fixer/tool/ClangIncludeFixer.cpp b/external/llvm-project/clang-tools-extra/clang-include-fixer/tool/ClangIncludeFixer.cpp index 746ba7bcea01..9f73f4799805 100644 --- a/external/llvm-project/clang-tools-extra/clang-include-fixer/tool/ClangIncludeFixer.cpp +++ b/external/llvm-project/clang-tools-extra/clang-include-fixer/tool/ClangIncludeFixer.cpp @@ -167,13 +167,11 @@ createSymbolIndexManager(StringRef FilePath) { // Parse input and fill the database with it. // =
<, header...> // Multiple symbols can be given, separated by semicolons. - std::map> SymbolsMap; SmallVector SemicolonSplits; StringRef(Input).split(SemicolonSplits, ";"); std::vector Symbols; for (StringRef Pair : SemicolonSplits) { auto Split = Pair.split('='); - std::vector Headers; SmallVector CommaSplits; Split.second.split(CommaSplits, ","); for (size_t I = 0, E = CommaSplits.size(); I != E; ++I) diff --git a/external/llvm-project/clang-tools-extra/clang-move/Move.h b/external/llvm-project/clang-tools-extra/clang-move/Move.h index ea241bbbc4f8..ba613abc03e1 100644 --- a/external/llvm-project/clang-tools-extra/clang-move/Move.h +++ b/external/llvm-project/clang-tools-extra/clang-move/Move.h @@ -49,9 +49,7 @@ class DeclarationReporter { bool Templated = false; // Whether the declaration is templated. }; - const std::vector getDeclarationList() const { - return DeclarationList; - } + ArrayRef getDeclarationList() const { return DeclarationList; } private: std::vector DeclarationList; diff --git a/external/llvm-project/clang-tools-extra/clang-reorder-fields/ReorderFieldsAction.cpp b/external/llvm-project/clang-tools-extra/clang-reorder-fields/ReorderFieldsAction.cpp index ea0207619fb2..3b1cd18d8034 100644 --- a/external/llvm-project/clang-tools-extra/clang-reorder-fields/ReorderFieldsAction.cpp +++ b/external/llvm-project/clang-tools-extra/clang-reorder-fields/ReorderFieldsAction.cpp @@ -86,6 +86,10 @@ getNewFieldsOrder(const RecordDecl *Definition, static void addReplacement(SourceRange Old, SourceRange New, const ASTContext &Context, std::map &Replacements) { + if (Old.getBegin().isMacroID()) + Old = Context.getSourceManager().getExpansionRange(Old).getAsRange(); + if (New.getBegin().isMacroID()) + New = Context.getSourceManager().getExpansionRange(New).getAsRange(); StringRef NewText = Lexer::getSourceText(CharSourceRange::getTokenRange(New), Context.getSourceManager(), Context.getLangOpts()); diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/ClangTidy.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/ClangTidy.cpp index 38d58bc13774..f4ab93b51f4a 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/ClangTidy.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/ClangTidy.cpp @@ -419,8 +419,8 @@ ClangTidyASTConsumerFactory::createASTConsumer( std::unique_ptr Profiling; if (Context.getEnableProfiling()) { - Profiling = std::make_unique( - Context.getProfileStorageParams()); + Profiling = + std::make_unique(Context.getProfileStorageParams()); FinderOptions.CheckProfiling.emplace(Profiling->Records); } @@ -432,8 +432,8 @@ ClangTidyASTConsumerFactory::createASTConsumer( if (Context.canEnableModuleHeadersParsing() && Context.getLangOpts().Modules && OverlayFS != nullptr) { - auto ModuleExpander = std::make_unique( - &Compiler, OverlayFS); + auto ModuleExpander = + std::make_unique(&Compiler, OverlayFS); ModuleExpanderPP = ModuleExpander->getPreprocessor(); PP->addPPCallbacks(std::move(ModuleExpander)); } @@ -497,7 +497,7 @@ getCheckNames(const ClangTidyOptions &Options, bool AllowEnablingAnalyzerAlphaCheckers) { clang::tidy::ClangTidyContext Context( std::make_unique(ClangTidyGlobalOptions(), - Options), + Options), AllowEnablingAnalyzerAlphaCheckers); ClangTidyASTConsumerFactory Factory(Context); return Factory.getCheckNames(); @@ -508,7 +508,7 @@ getCheckOptions(const ClangTidyOptions &Options, bool AllowEnablingAnalyzerAlphaCheckers) { clang::tidy::ClangTidyContext Context( std::make_unique(ClangTidyGlobalOptions(), - Options), + Options), AllowEnablingAnalyzerAlphaCheckers); ClangTidyDiagnosticConsumer DiagConsumer(Context); auto DiagOpts = std::make_unique(); diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/ClangTidyCheck.h b/external/llvm-project/clang-tools-extra/clang-tidy/ClangTidyCheck.h index 037526a0bd9a..399d45911549 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/ClangTidyCheck.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/ClangTidyCheck.h @@ -530,7 +530,6 @@ void ClangTidyCheck::OptionsView::store( ClangTidyOptions::OptionMap &Options, StringRef LocalName, bool Value) const; - } // namespace tidy } // namespace clang diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h b/external/llvm-project/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h index bd7a1bf2c11c..a8851e794f24 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.h @@ -217,11 +217,10 @@ class ClangTidyContext { using DiagLevelAndFormatString = std::pair; DiagLevelAndFormatString getDiagLevelAndFormatString(unsigned DiagnosticID, SourceLocation Loc) { - return { - static_cast( - DiagEngine->getDiagnosticLevel(DiagnosticID, Loc)), - std::string( - DiagEngine->getDiagnosticIDs()->getDescription(DiagnosticID))}; + return {static_cast( + DiagEngine->getDiagnosticLevel(DiagnosticID, Loc)), + std::string( + DiagEngine->getDiagnosticIDs()->getDescription(DiagnosticID))}; } void setOptionsCollector(llvm::StringSet<> *Collector) { diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp index 1c480d107ae9..e59f157b468b 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/ClangTidyOptions.cpp @@ -70,7 +70,8 @@ struct NOptionMap { NOptionMap(IO &, const ClangTidyOptions::OptionMap &OptionMap) { Options.reserve(OptionMap.size()); for (const auto &KeyValue : OptionMap) - Options.emplace_back(std::string(KeyValue.getKey()), KeyValue.getValue().Value); + Options.emplace_back(std::string(KeyValue.getKey()), + KeyValue.getValue().Value); } ClangTidyOptions::OptionMap denormalize(IO &) { ClangTidyOptions::OptionMap Map; diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/ClangTidyOptions.h b/external/llvm-project/clang-tools-extra/clang-tidy/ClangTidyOptions.h index dd78c570d25d..6ddc5f9b9cf9 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/ClangTidyOptions.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/ClangTidyOptions.h @@ -204,7 +204,9 @@ class FileOptionsBaseProvider : public DefaultOptionsProvider { protected: // A pair of configuration file base name and a function parsing // configuration from text in the corresponding format. - using ConfigFileHandler = std::pair (llvm::MemoryBufferRef)>>; + using ConfigFileHandler = + std::pair( + llvm::MemoryBufferRef)>>; /// Configuration file handlers listed in the order of priority. /// diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/ExpandModularHeadersPPCallbacks.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/ExpandModularHeadersPPCallbacks.cpp index 6a84704434c3..2c17cd3b6e97 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/ExpandModularHeadersPPCallbacks.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/ExpandModularHeadersPPCallbacks.cpp @@ -49,8 +49,8 @@ class ExpandModularHeadersPPCallbacks::FileRecorder { FilesToRecord.erase(File); } - /// Makes sure we have contents for all the files we were interested in. Ideally - /// `FilesToRecord` should be empty. + /// Makes sure we have contents for all the files we were interested in. + /// Ideally `FilesToRecord` should be empty. void checkAllFilesRecorded() { LLVM_DEBUG({ for (auto FileEntry : FilesToRecord) diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/ExpandModularHeadersPPCallbacks.h b/external/llvm-project/clang-tools-extra/clang-tidy/ExpandModularHeadersPPCallbacks.h index c3478917ef49..e599bda92c25 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/ExpandModularHeadersPPCallbacks.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/ExpandModularHeadersPPCallbacks.h @@ -35,10 +35,10 @@ namespace tooling { /// including the contents of the modular headers and all their transitive /// includes. /// -/// This allows existing tools based on PPCallbacks to retain their functionality -/// when running with C++ modules enabled. This only works in the backwards -/// compatible modules mode, i.e. when code can still be parsed in non-modular -/// way. +/// This allows existing tools based on PPCallbacks to retain their +/// functionality when running with C++ modules enabled. This only works in the +/// backwards compatible modules mode, i.e. when code can still be parsed in +/// non-modular way. class ExpandModularHeadersPPCallbacks : public PPCallbacks { public: ExpandModularHeadersPPCallbacks( diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/abseil/AbseilTidyModule.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/abseil/AbseilTidyModule.cpp index 09a09e6c599b..78605d59b442 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/abseil/AbseilTidyModule.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/abseil/AbseilTidyModule.cpp @@ -59,14 +59,12 @@ class AbseilModule : public ClangTidyModule { CheckFactories.registerCheck("abseil-no-namespace"); CheckFactories.registerCheck( "abseil-redundant-strcat-calls"); - CheckFactories.registerCheck( - "abseil-str-cat-append"); + CheckFactories.registerCheck("abseil-str-cat-append"); CheckFactories.registerCheck( "abseil-string-find-startswith"); CheckFactories.registerCheck( "abseil-string-find-str-contains"); - CheckFactories.registerCheck( - "abseil-time-comparison"); + CheckFactories.registerCheck("abseil-time-comparison"); CheckFactories.registerCheck( "abseil-time-subtraction"); CheckFactories.registerCheck( @@ -82,6 +80,6 @@ static ClangTidyModuleRegistry::Add X("abseil-module", // This anchor is used to force the linker to link in the generated object file // and thus register the AbseilModule. -volatile int AbseilModuleAnchorSource = 0; +volatile int AbseilModuleAnchorSource = 0; // NOLINT(misc-use-internal-linkage) } // namespace clang::tidy diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/abseil/CleanupCtadCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/abseil/CleanupCtadCheck.cpp index 0819642be055..8063fc540cce 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/abseil/CleanupCtadCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/abseil/CleanupCtadCheck.cpp @@ -18,7 +18,7 @@ using namespace ::clang::transformer; namespace clang::tidy::abseil { -RewriteRuleWith cleanupCtadCheckImpl() { +static RewriteRuleWith cleanupCtadCheckImpl() { auto WarningMessage = cat("prefer absl::Cleanup's class template argument " "deduction pattern in C++17 and higher"); diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/abseil/DurationDivisionCheck.h b/external/llvm-project/clang-tools-extra/clang-tidy/abseil/DurationDivisionCheck.h index 6b194e3d2664..c8f259521b64 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/abseil/DurationDivisionCheck.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/abseil/DurationDivisionCheck.h @@ -15,7 +15,7 @@ namespace clang::tidy::abseil { // Find potential incorrect uses of integer division of absl::Duration objects. // -// For the user-facing documentation see: +// For the user-facing documentation see: // http://clang.llvm.org/extra/clang-tidy/checks/abseil/duration-division.html class DurationDivisionCheck : public ClangTidyCheck { diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/abseil/NoInternalDependenciesCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/abseil/NoInternalDependenciesCheck.cpp index edaa584a4d8e..19409d0616f0 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/abseil/NoInternalDependenciesCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/abseil/NoInternalDependenciesCheck.cpp @@ -27,7 +27,8 @@ void NoInternalDependenciesCheck::registerMatchers(MatchFinder *Finder) { this); } -void NoInternalDependenciesCheck::check(const MatchFinder::MatchResult &Result) { +void NoInternalDependenciesCheck::check( + const MatchFinder::MatchResult &Result) { const auto *InternalDependency = Result.Nodes.getNodeAs("InternalDep"); diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/abseil/NoInternalDependenciesCheck.h b/external/llvm-project/clang-tools-extra/clang-tidy/abseil/NoInternalDependenciesCheck.h index dfaa2cbf8f90..9c16524ff6b5 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/abseil/NoInternalDependenciesCheck.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/abseil/NoInternalDependenciesCheck.h @@ -1,4 +1,4 @@ -//===--- NoInternalDependenciesCheck.h - clang-tidy----------------------*- C++ -*-===// +//===--- NoInternalDependenciesCheck.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. diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/abseil/NoNamespaceCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/abseil/NoNamespaceCheck.cpp index b45a9c99d780..6c2baa4c4141 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/abseil/NoNamespaceCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/abseil/NoNamespaceCheck.cpp @@ -15,10 +15,9 @@ using namespace clang::ast_matchers; namespace clang::tidy::abseil { void NoNamespaceCheck::registerMatchers(MatchFinder *Finder) { - Finder->addMatcher( - namespaceDecl(hasName("::absl"), unless(isInAbseilFile())) - .bind("abslNamespace"), - this); + Finder->addMatcher(namespaceDecl(hasName("::absl"), unless(isInAbseilFile())) + .bind("abslNamespace"), + this); } void NoNamespaceCheck::check(const MatchFinder::MatchResult &Result) { diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/abseil/RedundantStrcatCallsCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/abseil/RedundantStrcatCallsCheck.cpp index 04ca00614350..ef26a8a76cb3 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/abseil/RedundantStrcatCallsCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/abseil/RedundantStrcatCallsCheck.cpp @@ -23,7 +23,7 @@ namespace clang::tidy::abseil { // - Make it work in macros if the outer and inner StrCats are both in the // argument. -void RedundantStrcatCallsCheck::registerMatchers(MatchFinder* Finder) { +void RedundantStrcatCallsCheck::registerMatchers(MatchFinder *Finder) { const auto CallToStrcat = callExpr(callee(functionDecl(hasName("::absl::StrCat")))); const auto CallToStrappend = @@ -62,7 +62,7 @@ const clang::CallExpr *processArgument(const Expr *Arg, const MatchFinder::MatchResult &Result, StrCatCheckResult *CheckResult) { const auto IsAlphanum = hasDeclaration(cxxMethodDecl(hasName("AlphaNum"))); - static const auto* const Strcat = new auto(hasName("::absl::StrCat")); + static const auto *const Strcat = new auto(hasName("::absl::StrCat")); const auto IsStrcat = cxxBindTemporaryExpr( has(callExpr(callee(functionDecl(*Strcat))).bind("StrCat"))); if (const auto *SubStrcatCall = selectFirst( @@ -81,18 +81,18 @@ const clang::CallExpr *processArgument(const Expr *Arg, StrCatCheckResult processCall(const CallExpr *RootCall, bool IsAppend, const MatchFinder::MatchResult &Result) { StrCatCheckResult CheckResult; - std::deque CallsToProcess = {RootCall}; + std::deque CallsToProcess = {RootCall}; while (!CallsToProcess.empty()) { ++CheckResult.NumCalls; - const CallExpr* CallExpr = CallsToProcess.front(); + const CallExpr *CallExpr = CallsToProcess.front(); CallsToProcess.pop_front(); int StartArg = CallExpr == RootCall && IsAppend; for (const auto *Arg : CallExpr->arguments()) { - if (StartArg-- > 0) - continue; + if (StartArg-- > 0) + continue; if (const clang::CallExpr *Sub = processArgument(Arg, Result, &CheckResult)) { CallsToProcess.push_back(Sub); @@ -101,18 +101,18 @@ StrCatCheckResult processCall(const CallExpr *RootCall, bool IsAppend, } return CheckResult; } -} // namespace +} // namespace -void RedundantStrcatCallsCheck::check(const MatchFinder::MatchResult& Result) { +void RedundantStrcatCallsCheck::check(const MatchFinder::MatchResult &Result) { bool IsAppend = false; const CallExpr *RootCall = nullptr; - if ((RootCall = Result.Nodes.getNodeAs("StrCat"))) - IsAppend = false; - else if ((RootCall = Result.Nodes.getNodeAs("StrAppend"))) - IsAppend = true; - else - return; + if ((RootCall = Result.Nodes.getNodeAs("StrCat"))) + IsAppend = false; + else if ((RootCall = Result.Nodes.getNodeAs("StrAppend"))) + IsAppend = true; + else + return; if (RootCall->getBeginLoc().isMacroID()) { // Ignore calls within macros. @@ -128,8 +128,8 @@ void RedundantStrcatCallsCheck::check(const MatchFinder::MatchResult& Result) { return; } - diag(RootCall->getBeginLoc(), - "multiple calls to 'absl::StrCat' can be flattened into a single call") + diag(RootCall->getBeginLoc(), + "multiple calls to 'absl::StrCat' can be flattened into a single call") << CheckResult.Hints; } diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/abseil/RedundantStrcatCallsCheck.h b/external/llvm-project/clang-tools-extra/clang-tidy/abseil/RedundantStrcatCallsCheck.h index 04c7c9cb4b78..a27899d3e821 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/abseil/RedundantStrcatCallsCheck.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/abseil/RedundantStrcatCallsCheck.h @@ -13,8 +13,8 @@ namespace clang::tidy::abseil { -/// Flags redundant calls to absl::StrCat when the result is being passed to -/// another call of absl::StrCat/absl::StrAppend. Also suggests a fix to +/// Flags redundant calls to absl::StrCat when the result is being passed to +/// another call of absl::StrCat/absl::StrAppend. Also suggests a fix to /// collapse the calls. /// Example: /// StrCat(1, StrCat(2, 3)) ==> StrCat(1, 2, 3) diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/abseil/StrCatAppendCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/abseil/StrCatAppendCheck.cpp index ab6ed701e59f..ced92590be02 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/abseil/StrCatAppendCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/abseil/StrCatAppendCheck.cpp @@ -17,7 +17,7 @@ namespace clang::tidy::abseil { namespace { // Skips any combination of temporary materialization, temporary binding and // implicit casting. -AST_MATCHER_P(Stmt, IgnoringTemporaries, ast_matchers::internal::Matcher, +AST_MATCHER_P(Stmt, ignoringTemporaries, ast_matchers::internal::Matcher, InnerMatcher) { const Stmt *E = &Node; while (true) { @@ -34,16 +34,16 @@ AST_MATCHER_P(Stmt, IgnoringTemporaries, ast_matchers::internal::Matcher, return InnerMatcher.matches(*E, Finder, Builder); } -} // namespace +} // namespace // TODO: str += StrCat(...) // str.append(StrCat(...)) void StrCatAppendCheck::registerMatchers(MatchFinder *Finder) { const auto StrCat = functionDecl(hasName("::absl::StrCat")); - // The arguments of absl::StrCat are implicitly converted to AlphaNum. This - // matches to the arguments because of that behavior. - const auto AlphaNum = IgnoringTemporaries(cxxConstructExpr( + // The arguments of absl::StrCat are implicitly converted to AlphaNum. This + // matches to the arguments because of that behavior. + const auto AlphaNum = ignoringTemporaries(cxxConstructExpr( argumentCountIs(1), hasType(cxxRecordDecl(hasName("::absl::AlphaNum"))), hasArgument(0, ignoringImpCasts(declRefExpr(to(equalsBoundNode("LHS")), expr().bind("Arg0")))))); @@ -62,7 +62,7 @@ void StrCatAppendCheck::registerMatchers(MatchFinder *Finder) { hasOverloadedOperatorName("="), hasArgument(0, declRefExpr(to(decl().bind("LHS")))), hasArgument( - 1, IgnoringTemporaries( + 1, ignoringTemporaries( callExpr(callee(StrCat), hasArgument(0, AlphaNum), unless(HasAnotherReferenceToLhs)) .bind("Call")))) @@ -73,7 +73,7 @@ void StrCatAppendCheck::registerMatchers(MatchFinder *Finder) { void StrCatAppendCheck::check(const MatchFinder::MatchResult &Result) { const auto *Op = Result.Nodes.getNodeAs("Op"); const auto *Call = Result.Nodes.getNodeAs("Call"); - assert(Op != nullptr && Call != nullptr && "Matcher does not work as expected"); + assert(Op && Call && "Matcher does not work as expected"); // Handles the case 'x = absl::StrCat(x)', which has no effect. if (Call->getNumArgs() == 1) { diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/abseil/StrCatAppendCheck.h b/external/llvm-project/clang-tools-extra/clang-tidy/abseil/StrCatAppendCheck.h index 22b55abfd83b..fcd9d4b6e188 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/abseil/StrCatAppendCheck.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/abseil/StrCatAppendCheck.h @@ -14,7 +14,7 @@ namespace clang::tidy::abseil { /// Flags uses of absl::StrCat to append to a string. Suggests absl::StrAppend -/// should be used instead. +/// should be used instead. /// /// For the user-facing documentation see: /// http://clang.llvm.org/extra/clang-tidy/checks/abseil/str-cat-append.html diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/abseil/StringFindStrContainsCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/abseil/StringFindStrContainsCheck.cpp index 6e89783bb51e..0c2fe285ce06 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/abseil/StringFindStrContainsCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/abseil/StringFindStrContainsCheck.cpp @@ -29,7 +29,9 @@ using ::clang::transformer::makeRule; using ::clang::transformer::node; using ::clang::transformer::RewriteRuleWith; +namespace { AST_MATCHER(Type, isCharType) { return Node.isCharType(); } +} // namespace static const char DefaultStringLikeClasses[] = "::std::basic_string;" "::std::basic_string_view;" diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/abseil/TimeSubtractionCheck.h b/external/llvm-project/clang-tools-extra/clang-tidy/abseil/TimeSubtractionCheck.h index 7e7dc7351181..c947f6bca7f3 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/abseil/TimeSubtractionCheck.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/abseil/TimeSubtractionCheck.h @@ -26,7 +26,7 @@ class TimeSubtractionCheck : public ClangTidyCheck { void check(const ast_matchers::MatchFinder::MatchResult &Result) override; private: - void emitDiagnostic(const Expr* Node, llvm::StringRef Replacement); + void emitDiagnostic(const Expr *Node, llvm::StringRef Replacement); }; } // namespace clang::tidy::abseil diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/abseil/UpgradeDurationConversionsCheck.h b/external/llvm-project/clang-tools-extra/clang-tidy/abseil/UpgradeDurationConversionsCheck.h index beb5479aa6aa..8e7d9829533d 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/abseil/UpgradeDurationConversionsCheck.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/abseil/UpgradeDurationConversionsCheck.h @@ -16,7 +16,8 @@ namespace clang::tidy::abseil { -/// Finds deprecated uses of `absl::Duration` arithmetic operators and factories. +/// Finds deprecated uses of `absl::Duration` arithmetic operators and +/// factories. /// /// For the user-facing documentation see: /// http://clang.llvm.org/extra/clang-tidy/checks/abseil/upgrade-duration-conversions.html diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/altera/AlteraTidyModule.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/altera/AlteraTidyModule.cpp index 21610c7d1ece..02a43ba86d7b 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/altera/AlteraTidyModule.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/altera/AlteraTidyModule.cpp @@ -43,6 +43,6 @@ static ClangTidyModuleRegistry::Add // This anchor is used to force the linker to link in the generated object file // and thus register the AlteraModule. -volatile int AlteraModuleAnchorSource = 0; +volatile int AlteraModuleAnchorSource = 0; // NOLINT(misc-use-internal-linkage) } // namespace clang::tidy diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/altera/SingleWorkItemBarrierCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/altera/SingleWorkItemBarrierCheck.cpp index c5da66a1f28b..c21b7cab1b8d 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/altera/SingleWorkItemBarrierCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/altera/SingleWorkItemBarrierCheck.cpp @@ -16,14 +16,14 @@ namespace clang::tidy::altera { void SingleWorkItemBarrierCheck::registerMatchers(MatchFinder *Finder) { // Find any function that calls barrier but does not call an ID function. - // hasAttr(attr::Kind::OpenCLKernel) restricts it to only kernel functions. + // hasAttr(attr::Kind::DeviceKernel) restricts it to only kernel functions. // FIXME: Have it accept all functions but check for a parameter that gets an // ID from one of the four ID functions. Finder->addMatcher( // Find function declarations... functionDecl( - // That are OpenCL kernels... - hasAttr(attr::Kind::OpenCLKernel), + // That are device kernels... + hasAttr(attr::Kind::DeviceKernel), // And call a barrier function (either 1.x or 2.x version)... forEachDescendant(callExpr(callee(functionDecl(hasAnyName( "barrier", "work_group_barrier")))) diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/altera/StructPackAlignCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/altera/StructPackAlignCheck.cpp index cdaedd440959..789327b196ab 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/altera/StructPackAlignCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/altera/StructPackAlignCheck.cpp @@ -47,7 +47,7 @@ void StructPackAlignCheck::check(const MatchFinder::MatchResult &Result) { // Do not trigger on templated struct declarations because the packing and // alignment requirements are unknown. if (Struct->isTemplated()) - return; + return; // Packing and alignment requirements for invalid decls are meaningless. if (Struct->isInvalidDecl()) diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/altera/StructPackAlignCheck.h b/external/llvm-project/clang-tools-extra/clang-tidy/altera/StructPackAlignCheck.h index 5edfd40ef77b..f360bcef4f14 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/altera/StructPackAlignCheck.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/altera/StructPackAlignCheck.h @@ -22,7 +22,7 @@ class StructPackAlignCheck : public ClangTidyCheck { public: StructPackAlignCheck(StringRef Name, ClangTidyContext *Context) : ClangTidyCheck(Name, Context), - MaxConfiguredAlignment(Options.get("MaxConfiguredAlignment", 128)) {} + MaxConfiguredAlignment(Options.get("MaxConfiguredAlignment", 128)) {} void registerMatchers(ast_matchers::MatchFinder *Finder) override; void check(const ast_matchers::MatchFinder::MatchResult &Result) override; void storeOptions(ClangTidyOptions::OptionMap &Opts) override; diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/altera/UnrollLoopsCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/altera/UnrollLoopsCheck.cpp index 532a43bad741..0bb9d6e4a7ce 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/altera/UnrollLoopsCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/altera/UnrollLoopsCheck.cpp @@ -247,8 +247,8 @@ bool UnrollLoopsCheck::extractValue(int &Value, const BinaryOperator *Op, return true; } -bool UnrollLoopsCheck::exprHasLargeNumIterations(const Expr *Expression, - const ASTContext *Context) const { +bool UnrollLoopsCheck::exprHasLargeNumIterations( + const Expr *Expression, const ASTContext *Context) const { Expr::EvalResult Result; if (Expression->EvaluateAsRValue(Result, *Context)) { if (!Result.Val.isInt()) diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/android/AndroidTidyModule.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/android/AndroidTidyModule.cpp index 4541e926e886..17efa10909d0 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/android/AndroidTidyModule.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/android/AndroidTidyModule.cpp @@ -34,7 +34,8 @@ namespace android { class AndroidModule : public ClangTidyModule { public: void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override { - CheckFactories.registerCheck("android-cloexec-accept4"); + CheckFactories.registerCheck( + "android-cloexec-accept4"); CheckFactories.registerCheck("android-cloexec-accept"); CheckFactories.registerCheck("android-cloexec-creat"); CheckFactories.registerCheck("android-cloexec-dup"); @@ -66,6 +67,6 @@ static ClangTidyModuleRegistry::Add // This anchor is used to force the linker to link in the generated object file // and thus register the AndroidModule. -volatile int AndroidModuleAnchorSource = 0; +volatile int AndroidModuleAnchorSource = 0; // NOLINT(misc-use-internal-linkage) } // namespace clang::tidy diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/android/CloexecAcceptCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/android/CloexecAcceptCheck.cpp index 8c34ecd6945c..c90fc7ba1bb0 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/android/CloexecAcceptCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/android/CloexecAcceptCheck.cpp @@ -26,11 +26,10 @@ void CloexecAcceptCheck::registerMatchers(MatchFinder *Finder) { } void CloexecAcceptCheck::check(const MatchFinder::MatchResult &Result) { - std::string ReplacementText = - (Twine("accept4(") + getSpellingArg(Result, 0) + ", " + - getSpellingArg(Result, 1) + ", " + getSpellingArg(Result, 2) + - ", SOCK_CLOEXEC)") - .str(); + std::string ReplacementText = (Twine("accept4(") + getSpellingArg(Result, 0) + + ", " + getSpellingArg(Result, 1) + ", " + + getSpellingArg(Result, 2) + ", SOCK_CLOEXEC)") + .str(); replaceFunc( Result, diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/android/CloexecCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/android/CloexecCheck.cpp index 39a0d74f3836..f4d657a7f4e9 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/android/CloexecCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/android/CloexecCheck.cpp @@ -36,7 +36,7 @@ std::string buildFixMsgForStringFlag(const Expr *Arg, const SourceManager &SM, const char *CloexecCheck::FuncDeclBindingStr = "funcDecl"; -const char *CloexecCheck::FuncBindingStr ="func"; +const char *CloexecCheck::FuncBindingStr = "func"; void CloexecCheck::registerMatchersImpl( MatchFinder *Finder, internal::Matcher Function) { diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/android/CloexecCreatCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/android/CloexecCreatCheck.cpp index ee270209e4fa..8d9f45c3567f 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/android/CloexecCreatCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/android/CloexecCreatCheck.cpp @@ -16,11 +16,10 @@ namespace clang::tidy::android { void CloexecCreatCheck::registerMatchers(MatchFinder *Finder) { auto CharPointerType = hasType(pointerType(pointee(isAnyCharacter()))); auto MODETType = hasType(namedDecl(hasName("mode_t"))); - registerMatchersImpl(Finder, - functionDecl(isExternC(), returns(isInteger()), - hasName("creat"), - hasParameter(0, CharPointerType), - hasParameter(1, MODETType))); + registerMatchersImpl(Finder, functionDecl(isExternC(), returns(isInteger()), + hasName("creat"), + hasParameter(0, CharPointerType), + hasParameter(1, MODETType))); } void CloexecCreatCheck::check(const MatchFinder::MatchResult &Result) { diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/android/CloexecFopenCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/android/CloexecFopenCheck.cpp index 153e7af82d15..bb9d0d2cb3da 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/android/CloexecFopenCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/android/CloexecFopenCheck.cpp @@ -15,11 +15,10 @@ namespace clang::tidy::android { void CloexecFopenCheck::registerMatchers(MatchFinder *Finder) { auto CharPointerType = hasType(pointerType(pointee(isAnyCharacter()))); - registerMatchersImpl(Finder, - functionDecl(isExternC(), returns(asString("FILE *")), - hasName("fopen"), - hasParameter(0, CharPointerType), - hasParameter(1, CharPointerType))); + registerMatchersImpl( + Finder, functionDecl(isExternC(), returns(asString("FILE *")), + hasName("fopen"), hasParameter(0, CharPointerType), + hasParameter(1, CharPointerType))); } void CloexecFopenCheck::check(const MatchFinder::MatchResult &Result) { diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/android/CloexecOpenCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/android/CloexecOpenCheck.cpp index 11807f95def4..623b6ab02e7b 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/android/CloexecOpenCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/android/CloexecOpenCheck.cpp @@ -20,12 +20,11 @@ void CloexecOpenCheck::registerMatchers(MatchFinder *Finder) { hasAnyName("open", "open64"), hasParameter(0, CharPointerType), hasParameter(1, hasType(isInteger())))); - registerMatchersImpl(Finder, - functionDecl(isExternC(), returns(isInteger()), - hasName("openat"), - hasParameter(0, hasType(isInteger())), - hasParameter(1, CharPointerType), - hasParameter(2, hasType(isInteger())))); + registerMatchersImpl( + Finder, functionDecl(isExternC(), returns(isInteger()), hasName("openat"), + hasParameter(0, hasType(isInteger())), + hasParameter(1, CharPointerType), + hasParameter(2, hasType(isInteger())))); } void CloexecOpenCheck::check(const MatchFinder::MatchResult &Result) { diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/android/CloexecPipe2Check.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/android/CloexecPipe2Check.cpp index 2798c80146e9..e32332bdfc95 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/android/CloexecPipe2Check.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/android/CloexecPipe2Check.cpp @@ -14,10 +14,10 @@ using namespace clang::ast_matchers; namespace clang::tidy::android { void CloexecPipe2Check::registerMatchers(MatchFinder *Finder) { - registerMatchersImpl(Finder, - functionDecl(returns(isInteger()), hasName("pipe2"), - hasParameter(0, hasType(pointsTo(isInteger()))), - hasParameter(1, hasType(isInteger())))); + registerMatchersImpl( + Finder, functionDecl(returns(isInteger()), hasName("pipe2"), + hasParameter(0, hasType(pointsTo(isInteger()))), + hasParameter(1, hasType(isInteger())))); } void CloexecPipe2Check::check(const MatchFinder::MatchResult &Result) { diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/android/CloexecPipeCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/android/CloexecPipeCheck.cpp index 9085be67b755..c59b127dc87a 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/android/CloexecPipeCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/android/CloexecPipeCheck.cpp @@ -14,19 +14,19 @@ using namespace clang::ast_matchers; namespace clang::tidy::android { void CloexecPipeCheck::registerMatchers(MatchFinder *Finder) { - registerMatchersImpl(Finder, - functionDecl(returns(isInteger()), hasName("pipe"), - hasParameter(0, hasType(pointsTo(isInteger()))))); + registerMatchersImpl( + Finder, functionDecl(returns(isInteger()), hasName("pipe"), + hasParameter(0, hasType(pointsTo(isInteger()))))); } void CloexecPipeCheck::check(const MatchFinder::MatchResult &Result) { std::string ReplacementText = (Twine("pipe2(") + getSpellingArg(Result, 0) + ", O_CLOEXEC)").str(); - replaceFunc( - Result, - "prefer pipe2() with O_CLOEXEC to avoid leaking file descriptors to child processes", - ReplacementText); + replaceFunc(Result, + "prefer pipe2() with O_CLOEXEC to avoid leaking file descriptors " + "to child processes", + ReplacementText); } } // namespace clang::tidy::android diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/android/CloexecSocketCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/android/CloexecSocketCheck.cpp index 65c6a82036cc..12b31a050c2c 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/android/CloexecSocketCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/android/CloexecSocketCheck.cpp @@ -14,12 +14,11 @@ using namespace clang::ast_matchers; namespace clang::tidy::android { void CloexecSocketCheck::registerMatchers(MatchFinder *Finder) { - registerMatchersImpl(Finder, - functionDecl(isExternC(), returns(isInteger()), - hasName("socket"), - hasParameter(0, hasType(isInteger())), - hasParameter(1, hasType(isInteger())), - hasParameter(2, hasType(isInteger())))); + registerMatchersImpl( + Finder, functionDecl(isExternC(), returns(isInteger()), hasName("socket"), + hasParameter(0, hasType(isInteger())), + hasParameter(1, hasType(isInteger())), + hasParameter(2, hasType(isInteger())))); } void CloexecSocketCheck::check(const MatchFinder::MatchResult &Result) { diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/boost/BoostTidyModule.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/boost/BoostTidyModule.cpp index 79d0e380e402..f414fe750d02 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/boost/BoostTidyModule.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/boost/BoostTidyModule.cpp @@ -32,6 +32,6 @@ static ClangTidyModuleRegistry::Add X("boost-module", // This anchor is used to force the linker to link in the generated object file // and thus register the BoostModule. -volatile int BoostModuleAnchorSource = 0; +volatile int BoostModuleAnchorSource = 0; // NOLINT(misc-use-internal-linkage) } // namespace clang::tidy diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/BranchCloneCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/BranchCloneCheck.cpp index 0b76cfb2ad8d..a6cd68edda55 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/BranchCloneCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/BranchCloneCheck.cpp @@ -62,6 +62,7 @@ static bool isFallthroughSwitchBranch(const SwitchBranch &Branch) { return true; // Ignore sub-switches } + // NOLINTNEXTLINE(readability-identifier-naming) - FIXME bool TraverseSwitchCase(SwitchCase *, DataRecursionQueue * = nullptr) { return true; // Ignore cases } diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp index 64f4a524daf0..ed1fd138d8f1 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp @@ -291,6 +291,7 @@ static ClangTidyModuleRegistry::Add // This anchor is used to force the linker to link in the generated object file // and thus register the BugproneModule. +// NOLINTNEXTLINE(misc-use-internal-linkage) volatile int BugproneModuleAnchorSource = 0; } // namespace clang::tidy diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/ChainedComparisonCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/ChainedComparisonCheck.cpp index c6bb5bdf5ce9..7378f1a24ffd 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/ChainedComparisonCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/ChainedComparisonCheck.cpp @@ -34,8 +34,7 @@ AST_MATCHER(BinaryOperator, AST_MATCHER(CXXOperatorCallExpr, hasCppOperatorAChildComparisonOperatorWithoutParen) { - return std::any_of(Node.arg_begin(), Node.arg_end(), - isExprAComparisonOperator); + return llvm::any_of(Node.arguments(), isExprAComparisonOperator); } struct ChainedComparisonData { diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/DynamicStaticInitializersCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/DynamicStaticInitializersCheck.cpp index 93f35cb2c1a3..3fe028b94771 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/DynamicStaticInitializersCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/DynamicStaticInitializersCheck.cpp @@ -15,6 +15,8 @@ using namespace clang::ast_matchers; namespace clang::tidy::bugprone { +namespace { + AST_MATCHER(clang::VarDecl, hasConstantDeclaration) { const Expr *Init = Node.getInit(); if (Init && !Init->isValueDependent()) { @@ -25,6 +27,8 @@ AST_MATCHER(clang::VarDecl, hasConstantDeclaration) { return false; } +} // namespace + DynamicStaticInitializersCheck::DynamicStaticInitializersCheck( StringRef Name, ClangTidyContext *Context) : ClangTidyCheck(Name, Context), @@ -36,16 +40,18 @@ void DynamicStaticInitializersCheck::registerMatchers(MatchFinder *Finder) { this); } -void DynamicStaticInitializersCheck::check(const MatchFinder::MatchResult &Result) { +void DynamicStaticInitializersCheck::check( + const MatchFinder::MatchResult &Result) { const auto *Var = Result.Nodes.getNodeAs("var"); SourceLocation Loc = Var->getLocation(); - if (!Loc.isValid() || !utils::isPresumedLocInHeaderFile(Loc, *Result.SourceManager, - HeaderFileExtensions)) + if (!Loc.isValid() || !utils::isPresumedLocInHeaderFile( + Loc, *Result.SourceManager, HeaderFileExtensions)) return; // If the initializer is a constant expression, then the compiler // doesn't have to dynamically initialize it. - diag(Loc, "static variable %0 may be dynamically initialized in this header file") - << Var; + diag(Loc, + "static variable %0 may be dynamically initialized in this header file") + << Var; } } // namespace clang::tidy::bugprone diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp index 10868129e76d..a179d4bf66b4 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/EasilySwappableParametersCheck.cpp @@ -1497,11 +1497,13 @@ static MixableParameterRange modelMixingRange( } // namespace model +namespace { /// Matches DeclRefExprs and their ignorable wrappers to ParmVarDecls. AST_MATCHER_FUNCTION(ast_matchers::internal::Matcher, paramRefExpr) { return expr(ignoringParenImpCasts(ignoringElidableConstructorCall( declRefExpr(to(parmVarDecl().bind("param")))))); } +} // namespace namespace filter { @@ -1574,8 +1576,8 @@ using ParamToSmallSetMap = /// Returns whether the sets mapped to the two elements in the map have at /// least one element in common. template -bool lazyMapOfSetsIntersectionExists(const MapTy &Map, const ElemTy &E1, - const ElemTy &E2) { +static bool lazyMapOfSetsIntersectionExists(const MapTy &Map, const ElemTy &E1, + const ElemTy &E2) { auto E1Iterator = Map.find(E1); auto E2Iterator = Map.find(E2); if (E1Iterator == Map.end() || E2Iterator == Map.end()) @@ -1882,6 +1884,8 @@ static bool prefixSuffixCoverUnderThreshold(std::size_t Threshold, } // namespace filter +namespace { + /// Matches functions that have at least the specified amount of parameters. AST_MATCHER_P(FunctionDecl, parameterCountGE, unsigned, N) { return Node.getNumParams() >= N; @@ -1904,6 +1908,8 @@ AST_MATCHER(FunctionDecl, isOverloadedUnaryOrBinaryOperator) { } } +} // namespace + /// Returns the DefaultMinimumLength if the Value of requested minimum length /// is less than 2. Minimum lengths of 0 or 1 are not accepted. static inline unsigned clampMinimumLength(const unsigned Value) { diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/InaccurateEraseCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/InaccurateEraseCheck.cpp index 7626bf89e694..92425890a0ea 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/InaccurateEraseCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/InaccurateEraseCheck.cpp @@ -18,9 +18,9 @@ void InaccurateEraseCheck::registerMatchers(MatchFinder *Finder) { const auto EndCall = callExpr( callee(functionDecl(hasAnyName("remove", "remove_if", "unique"))), - hasArgument( - 1, optionally(cxxMemberCallExpr(callee(cxxMethodDecl(hasName("end")))) - .bind("end")))) + hasArgument(1, optionally(cxxMemberCallExpr( + callee(cxxMethodDecl(hasName("end")))) + .bind("end")))) .bind("alg"); const auto DeclInStd = type(hasUnqualifiedDesugaredType( @@ -35,10 +35,8 @@ void InaccurateEraseCheck::registerMatchers(MatchFinder *Finder) { } void InaccurateEraseCheck::check(const MatchFinder::MatchResult &Result) { - const auto *MemberCall = - Result.Nodes.getNodeAs("erase"); - const auto *EndExpr = - Result.Nodes.getNodeAs("end"); + const auto *MemberCall = Result.Nodes.getNodeAs("erase"); + const auto *EndExpr = Result.Nodes.getNodeAs("end"); const SourceLocation Loc = MemberCall->getBeginLoc(); FixItHint Hint; diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/IncDecInConditionsCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/IncDecInConditionsCheck.cpp index 9b3b01eb0268..73bffe93146e 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/IncDecInConditionsCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/IncDecInConditionsCheck.cpp @@ -15,6 +15,8 @@ using namespace clang::ast_matchers; namespace clang::tidy::bugprone { +namespace { + AST_MATCHER(BinaryOperator, isLogicalOperator) { return Node.isLogicalOp(); } AST_MATCHER(UnaryOperator, isUnaryPrePostOperator) { @@ -26,6 +28,8 @@ AST_MATCHER(CXXOperatorCallExpr, isPrePostOperator) { Node.getOperator() == OO_MinusMinus; } +} // namespace + void IncDecInConditionsCheck::registerMatchers(MatchFinder *Finder) { auto OperatorMatcher = expr( anyOf(binaryOperator(anyOf(isComparisonOperator(), isLogicalOperator())), diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/IncorrectRoundingsCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/IncorrectRoundingsCheck.cpp index 2a8d36215cc7..c2b0732a3e7b 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/IncorrectRoundingsCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/IncorrectRoundingsCheck.cpp @@ -1,4 +1,4 @@ -//===--- IncorrectRoundingsCheck.cpp - clang-tidy ------------------------------===// +//===--- IncorrectRoundingsCheck.cpp - clang-tidy--------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/InfiniteLoopCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/InfiniteLoopCheck.cpp index b7f0c08b2a7d..07116a7ff15f 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/InfiniteLoopCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/InfiniteLoopCheck.cpp @@ -83,8 +83,8 @@ static bool isVarThatIsPossiblyChanged(const Decl *Func, const Stmt *LoopStmt, isChanged(LoopStmt, Var, Context); // FIXME: Track references. } - } else if (isa(Cond)) { + } else if (isa(Cond)) { // FIXME: Handle MemberExpr. return true; } else if (const auto *CE = dyn_cast(Cond)) { @@ -274,8 +274,7 @@ static bool hasRecursionOverStaticLoopCondVariables(const Expr *Cond, void InfiniteLoopCheck::registerMatchers(MatchFinder *Finder) { const auto LoopCondition = allOf( - hasCondition( - expr(forCallable(decl().bind("func"))).bind("condition")), + hasCondition(expr(forCallable(decl().bind("func"))).bind("condition")), unless(hasBody(hasDescendant( loopEndingStmt(forCallable(equalsBoundNode("func"))))))); @@ -324,7 +323,7 @@ void InfiniteLoopCheck::check(const MatchFinder::MatchResult &Result) { diag(LoopStmt->getBeginLoc(), "this loop is infinite; none of its condition variables (%0)" " are updated in the loop body") - << CondVarNames; + << CondVarNames; } } diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp index 32f5edddfe80..6d5c470616d1 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/LambdaFunctionNameCheck.cpp @@ -34,12 +34,11 @@ class MacroExpansionsWithFileAndLine : public PPCallbacks { LambdaFunctionNameCheck::SourceRangeSet *SME) : SuppressMacroExpansions(SME) {} - void MacroExpands(const Token &MacroNameTok, - const MacroDefinition &MD, SourceRange Range, - const MacroArgs *Args) override { + void MacroExpands(const Token &MacroNameTok, const MacroDefinition &MD, + SourceRange Range, const MacroArgs *Args) override { bool HasFile = false; bool HasLine = false; - for (const auto& T : MD.getMacroInfo()->tokens()) { + for (const Token &T : MD.getMacroInfo()->tokens()) { if (T.is(tok::identifier)) { StringRef IdentName = T.getIdentifierInfo()->getName(); if (IdentName == "__FILE__") { @@ -55,7 +54,7 @@ class MacroExpansionsWithFileAndLine : public PPCallbacks { } private: - LambdaFunctionNameCheck::SourceRangeSet* SuppressMacroExpansions; + LambdaFunctionNameCheck::SourceRangeSet *SuppressMacroExpansions; }; AST_MATCHER(CXXMethodDecl, isInLambda) { return Node.getParent()->isLambda(); } diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/MisplacedOperatorInStrlenInAllocCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/MisplacedOperatorInStrlenInAllocCheck.cpp index 40e4ab6c8b12..5b166b4b3a9b 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/MisplacedOperatorInStrlenInAllocCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/MisplacedOperatorInStrlenInAllocCheck.cpp @@ -74,7 +74,7 @@ void MisplacedOperatorInStrlenInAllocCheck::check( if (!Alloc) Alloc = Result.Nodes.getNodeAs("Alloc"); assert(Alloc && "Matched node bound by 'Alloc' should be either 'CallExpr'" - " or 'CXXNewExpr'"); + " or 'CXXNewExpr'"); const auto *StrLen = Result.Nodes.getNodeAs("StrLen"); const auto *BinOp = Result.Nodes.getNodeAs("BinOp"); diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/MisplacedOperatorInStrlenInAllocCheck.h b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/MisplacedOperatorInStrlenInAllocCheck.h index 3a09ddb4a6c0..93cf50d0b1c6 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/MisplacedOperatorInStrlenInAllocCheck.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/MisplacedOperatorInStrlenInAllocCheck.h @@ -21,7 +21,8 @@ namespace clang::tidy::bugprone { /// http://clang.llvm.org/extra/clang-tidy/checks/bugprone/misplaced-operator-in-strlen-in-alloc.html class MisplacedOperatorInStrlenInAllocCheck : public ClangTidyCheck { public: - MisplacedOperatorInStrlenInAllocCheck(StringRef Name, ClangTidyContext *Context) + MisplacedOperatorInStrlenInAllocCheck(StringRef Name, + ClangTidyContext *Context) : ClangTidyCheck(Name, Context) {} void registerMatchers(ast_matchers::MatchFinder *Finder) override; void check(const ast_matchers::MatchFinder::MatchResult &Result) override; diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/MisplacedPointerArithmeticInAllocCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/MisplacedPointerArithmeticInAllocCheck.cpp index b9129fa0811c..86785d36696d 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/MisplacedPointerArithmeticInAllocCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/MisplacedPointerArithmeticInAllocCheck.cpp @@ -76,8 +76,8 @@ void MisplacedPointerArithmeticInAllocCheck::check( } else { const auto *CtrE = New->getConstructExpr(); if (!CtrE || !CtrE->getArg(CtrE->getNumArgs() - 1) - ->getType() - ->isIntegralOrEnumerationType()) + ->getType() + ->isIntegralOrEnumerationType()) return; CallName = "operator new"; } diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/MultiLevelImplicitPointerConversionCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/MultiLevelImplicitPointerConversionCheck.cpp index 7a989b07119a..1a23473fdd22 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/MultiLevelImplicitPointerConversionCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/MultiLevelImplicitPointerConversionCheck.cpp @@ -57,6 +57,17 @@ AST_MATCHER(QualType, isPointerType) { } // namespace +MultiLevelImplicitPointerConversionCheck:: + MultiLevelImplicitPointerConversionCheck(StringRef Name, + ClangTidyContext *Context) + : ClangTidyCheck(Name, Context), EnableInC(Options.get("EnableInC", true)) { +} + +void MultiLevelImplicitPointerConversionCheck::storeOptions( + ClangTidyOptions::OptionMap &Opts) { + Options.store(Opts, "EnableInC", EnableInC); +} + void MultiLevelImplicitPointerConversionCheck::registerMatchers( MatchFinder *Finder) { Finder->addMatcher( diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/MultiLevelImplicitPointerConversionCheck.h b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/MultiLevelImplicitPointerConversionCheck.h index 13228145ff35..ef5f9f103c89 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/MultiLevelImplicitPointerConversionCheck.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/MultiLevelImplicitPointerConversionCheck.h @@ -21,11 +21,17 @@ namespace clang::tidy::bugprone { class MultiLevelImplicitPointerConversionCheck : public ClangTidyCheck { public: MultiLevelImplicitPointerConversionCheck(StringRef Name, - ClangTidyContext *Context) - : ClangTidyCheck(Name, Context) {} + ClangTidyContext *Context); + void storeOptions(ClangTidyOptions::OptionMap &Opts) override; void registerMatchers(ast_matchers::MatchFinder *Finder) override; void check(const ast_matchers::MatchFinder::MatchResult &Result) override; std::optional getCheckTraversalKind() const override; + bool isLanguageVersionSupported(const LangOptions &LangOpts) const override { + return EnableInC ? true : LangOpts.CPlusPlus; + } + +private: + bool const EnableInC; }; } // namespace clang::tidy::bugprone diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/MultipleNewInOneExpressionCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/MultipleNewInOneExpressionCheck.cpp index 41191a3cfed2..b68888cb5b92 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/MultipleNewInOneExpressionCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/MultipleNewInOneExpressionCheck.cpp @@ -49,8 +49,6 @@ bool isExprValueStored(const Expr *E, ASTContext &C) { return isa(ParentE); } -} // namespace - AST_MATCHER_P(CXXTryStmt, hasHandlerFor, ast_matchers::internal::Matcher, InnerMatcher) { for (unsigned NH = Node.getNumHandlers(), I = 0; I < NH; ++I) { @@ -74,6 +72,8 @@ AST_MATCHER(CXXNewExpr, mayThrow) { return !OperatorNew->getType()->castAs()->isNothrow(); } +} // namespace + void MultipleNewInOneExpressionCheck::registerMatchers(MatchFinder *Finder) { auto BadAllocType = recordType(hasDeclaration(cxxRecordDecl(hasName("::std::bad_alloc")))); @@ -95,16 +95,14 @@ void MultipleNewInOneExpressionCheck::registerMatchers(MatchFinder *Finder) { Finder->addMatcher( callExpr( - hasAnyArgument( - expr(HasNewExpr1).bind("arg1")), + hasAnyArgument(expr(HasNewExpr1).bind("arg1")), hasAnyArgument( expr(HasNewExpr2, unless(equalsBoundNode("arg1"))).bind("arg2")), hasAncestor(BadAllocCatchingTryBlock)), this); Finder->addMatcher( cxxConstructExpr( - hasAnyArgument( - expr(HasNewExpr1).bind("arg1")), + hasAnyArgument(expr(HasNewExpr1).bind("arg1")), hasAnyArgument( expr(HasNewExpr2, unless(equalsBoundNode("arg1"))).bind("arg2")), unless(isListInitialization()), diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp index 977241e91b9a..203170d55f69 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp @@ -677,7 +677,7 @@ void NotNullTerminatedResultCheck::registerMatchers(MatchFinder *Finder) { std::optional SourcePos, unsigned LengthPos, bool WithIncrease) : Name(Name), DestinationPos(DestinationPos), SourcePos(SourcePos), - LengthPos(LengthPos), WithIncrease(WithIncrease){}; + LengthPos(LengthPos), WithIncrease(WithIncrease) {}; StringRef Name; std::optional DestinationPos; @@ -702,17 +702,16 @@ void NotNullTerminatedResultCheck::registerMatchers(MatchFinder *Finder) { return hasArgument( CC.LengthPos, allOf( - anyOf( - ignoringImpCasts(integerLiteral().bind(WrongLengthExprName)), - allOf(unless(hasDefinition(SizeOfCharExpr)), - allOf(CC.WithIncrease - ? ignoringImpCasts(hasDefinition(HasIncOp)) - : ignoringImpCasts(allOf( - unless(hasDefinition(HasIncOp)), - anyOf(hasDefinition(binaryOperator().bind( - UnknownLengthName)), - hasDefinition(anything())))), - AnyOfWrongLengthInit))), + anyOf(ignoringImpCasts(integerLiteral().bind(WrongLengthExprName)), + allOf(unless(hasDefinition(SizeOfCharExpr)), + allOf(CC.WithIncrease + ? ignoringImpCasts(hasDefinition(HasIncOp)) + : ignoringImpCasts( + allOf(unless(hasDefinition(HasIncOp)), + hasDefinition(optionally( + binaryOperator().bind( + UnknownLengthName))))), + AnyOfWrongLengthInit))), expr().bind(LengthExprName))); }; diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/PosixReturnCheck.h b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/PosixReturnCheck.h index 254ae6c7f1ac..e9d2263b06bc 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/PosixReturnCheck.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/PosixReturnCheck.h @@ -13,7 +13,7 @@ namespace clang::tidy::bugprone { -class PosixReturnCheck: public ClangTidyCheck { +class PosixReturnCheck : public ClangTidyCheck { public: PosixReturnCheck(StringRef Name, ClangTidyContext *Context) : ClangTidyCheck(Name, Context) {} diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/RedundantBranchConditionCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/RedundantBranchConditionCheck.cpp index 95fbca2ad008..e717564847e4 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/RedundantBranchConditionCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/RedundantBranchConditionCheck.cpp @@ -1,4 +1,4 @@ -//===--- RedundantBranchConditionCheck.cpp - clang-tidy -------------------------===// +//===--- RedundantBranchConditionCheck.cpp - clang-tidy--------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. @@ -70,7 +70,8 @@ void RedundantBranchConditionCheck::registerMatchers(MatchFinder *Finder) { // FIXME: Handle longer conjunctive and disjunctive clauses. } -void RedundantBranchConditionCheck::check(const MatchFinder::MatchResult &Result) { +void RedundantBranchConditionCheck::check( + const MatchFinder::MatchResult &Result) { const auto *OuterIf = Result.Nodes.getNodeAs(OuterIfStr); const auto *InnerIf = Result.Nodes.getNodeAs(InnerIfStr); const auto *CondVar = Result.Nodes.getNodeAs(CondVarStr); diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp index c066b3e7b19a..d5cbb847eea9 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/SignalHandlerCheck.cpp @@ -22,7 +22,9 @@ constexpr llvm::StringLiteral MinimalConformingFunctions[] = { // mentioned POSIX specification was not updated after 'quick_exit' appeared // in the C11 standard. // Also, we want to keep the "minimal set" a subset of the "POSIX set". -// The list is repeated in bugprone-signal-handler.rst and should be kept up to date. +// The list is repeated in bugprone-signal-handler.rst and should be kept up to +// date. +// clang-format off constexpr llvm::StringLiteral POSIXConformingFunctions[] = { "_Exit", "_exit", @@ -215,7 +217,9 @@ constexpr llvm::StringLiteral POSIXConformingFunctions[] = { "wmemcpy", "wmemmove", "wmemset", - "write"}; + "write" +}; +// clang-format on using namespace clang::ast_matchers; @@ -322,12 +326,12 @@ SourceRange getSourceRangeOfStmt(const Stmt *S, ASTContext &Ctx) { return P.getSourceRange(); } -} // namespace - AST_MATCHER(FunctionDecl, isStandardFunction) { return isStandardFunction(&Node); } +} // namespace + SignalHandlerCheck::SignalHandlerCheck(StringRef Name, ClangTidyContext *Context) : ClangTidyCheck(Name, Context), diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp index f3d4c2255d86..9eeba867f521 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/SizeofExpressionCheck.cpp @@ -170,8 +170,6 @@ void SizeofExpressionCheck::registerMatchers(MatchFinder *Finder) { const auto PointerToStructType = hasUnqualifiedDesugaredType(pointerType(pointee(recordType()))); - const auto PointerToStructTypeWithBinding = - type(PointerToStructType).bind("struct-type"); const auto PointerToStructExpr = expr(hasType(hasCanonicalType(PointerToStructType))); @@ -188,12 +186,10 @@ void SizeofExpressionCheck::registerMatchers(MatchFinder *Finder) { ignoringParenImpCasts(unaryOperator(hasOperatorName("*"))); Finder->addMatcher( - expr(sizeOfExpr(anyOf(has(ignoringParenImpCasts( - expr(PointerToDetectedExpr, unless(DerefExpr), - unless(SubscriptExprWithZeroIndex), - unless(VarWithConstStrLiteralDecl), - unless(cxxThisExpr())))), - has(PointerToStructTypeWithBinding)))) + expr(sizeOfExpr(has(ignoringParenImpCasts(expr( + PointerToDetectedExpr, unless(DerefExpr), + unless(SubscriptExprWithZeroIndex), + unless(VarWithConstStrLiteralDecl), unless(cxxThisExpr())))))) .bind("sizeof-pointer"), this); } @@ -354,16 +350,9 @@ void SizeofExpressionCheck::check(const MatchFinder::MatchResult &Result) { "suspicious usage of 'sizeof(char*)'; do you mean 'strlen'?") << E->getSourceRange(); } else if (const auto *E = Result.Nodes.getNodeAs("sizeof-pointer")) { - if (Result.Nodes.getNodeAs("struct-type")) { - diag(E->getBeginLoc(), - "suspicious usage of 'sizeof(A*)' on pointer-to-aggregate type; did " - "you mean 'sizeof(A)'?") - << E->getSourceRange(); - } else { - diag(E->getBeginLoc(), "suspicious usage of 'sizeof()' on an expression " - "of pointer type") - << E->getSourceRange(); - } + diag(E->getBeginLoc(), "suspicious usage of 'sizeof()' on an expression " + "of pointer type") + << E->getSourceRange(); } else if (const auto *E = Result.Nodes.getNodeAs( "sizeof-compare-constant")) { diag(E->getOperatorLoc(), diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/SpuriouslyWakeUpFunctionsCheck.h b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/SpuriouslyWakeUpFunctionsCheck.h index 5e143411f9b6..098299aea7de 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/SpuriouslyWakeUpFunctionsCheck.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/SpuriouslyWakeUpFunctionsCheck.h @@ -13,9 +13,9 @@ namespace clang::tidy::bugprone { -/// Finds ``cnd_wait``, ``cnd_timedwait``, ``wait``, ``wait_for``, or -/// ``wait_until`` function calls when the function is not invoked from a loop -/// that checks whether a condition predicate holds or the function has a +/// Finds ``cnd_wait``, ``cnd_timedwait``, ``wait``, ``wait_for``, or +/// ``wait_until`` function calls when the function is not invoked from a loop +/// that checks whether a condition predicate holds or the function has a /// condition parameter. /// /// For the user-facing documentation see: diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/StandaloneEmptyCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/StandaloneEmptyCheck.cpp index 682478ecead0..5d9e91e0b82c 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/StandaloneEmptyCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/StandaloneEmptyCheck.cpp @@ -46,7 +46,8 @@ using ast_matchers::stmtExpr; using ast_matchers::unless; using ast_matchers::voidType; -const Expr *getCondition(const BoundNodes &Nodes, const StringRef NodeId) { +static const Expr *getCondition(const BoundNodes &Nodes, + const StringRef NodeId) { const auto *If = Nodes.getNodeAs(NodeId); if (If != nullptr) return If->getCond(); diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/StringLiteralWithEmbeddedNulCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/StringLiteralWithEmbeddedNulCheck.cpp index 72e680d25cb8..444f3081b704 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/StringLiteralWithEmbeddedNulCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/StringLiteralWithEmbeddedNulCheck.cpp @@ -47,8 +47,9 @@ void StringLiteralWithEmbeddedNulCheck::registerMatchers(MatchFinder *Finder) { // Detect passing a suspicious string literal to a string constructor. // example: std::string str = "abc\0def"; - Finder->addMatcher(traverse(TK_AsIs, - cxxConstructExpr(StringConstructorExpr, hasArgument(0, StrLitWithNul))), + Finder->addMatcher( + traverse(TK_AsIs, cxxConstructExpr(StringConstructorExpr, + hasArgument(0, StrLitWithNul))), this); // Detect passing a suspicious string literal through an overloaded operator. diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/StringviewNullptrCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/StringviewNullptrCheck.cpp index f944ae6c5b9e..20789b3123e2 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/StringviewNullptrCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/StringviewNullptrCheck.cpp @@ -33,7 +33,7 @@ AST_MATCHER(clang::VarDecl, isDirectInitialization) { } // namespace -RewriteRuleWith stringviewNullptrCheckImpl() { +static RewriteRuleWith stringviewNullptrCheckImpl() { auto ConstructionWarning = cat("constructing basic_string_view from null is undefined; replace with " "the default constructor"); diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/SuspiciousEnumUsageCheck.h b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/SuspiciousEnumUsageCheck.h index 63c4bea6e565..c8a70c5f0704 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/SuspiciousEnumUsageCheck.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/SuspiciousEnumUsageCheck.h @@ -1,4 +1,4 @@ -//===--- SuspiciousEnumUsageCheck.h - clang-tidy--------------------------*- C++ -*-===// +//===--- SuspiciousEnumUsageCheck.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. @@ -28,7 +28,7 @@ class SuspiciousEnumUsageCheck : public ClangTidyCheck { } private: - void checkSuspiciousBitmaskUsage(const Expr*, const EnumDecl*); + void checkSuspiciousBitmaskUsage(const Expr *, const EnumDecl *); const bool StrictMode; }; diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/SuspiciousMemsetUsageCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/SuspiciousMemsetUsageCheck.cpp index a488d35ca744..cc1bd622039b 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/SuspiciousMemsetUsageCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/SuspiciousMemsetUsageCheck.cpp @@ -21,8 +21,7 @@ void SuspiciousMemsetUsageCheck::registerMatchers(MatchFinder *Finder) { // Match the standard memset: // void *memset(void *buffer, int fill_char, size_t byte_count); auto MemsetDecl = - functionDecl(hasName("::memset"), - parameterCountIs(3), + functionDecl(hasName("::memset"), parameterCountIs(3), hasParameter(0, hasType(pointerType(pointee(voidType())))), hasParameter(1, hasType(isInteger())), hasParameter(2, hasType(isInteger()))); diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/SuspiciousSemicolonCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/SuspiciousSemicolonCheck.cpp index 92b772dd26d4..e93ba760f447 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/SuspiciousSemicolonCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/SuspiciousSemicolonCheck.cpp @@ -18,8 +18,7 @@ namespace clang::tidy::bugprone { void SuspiciousSemicolonCheck::registerMatchers(MatchFinder *Finder) { Finder->addMatcher( stmt(anyOf(ifStmt(hasThen(nullStmt().bind("semi")), - unless(hasElse(stmt())), - unless(isConstexpr())), + unless(hasElse(stmt())), unless(isConstexpr())), forStmt(hasBody(nullStmt().bind("semi"))), cxxForRangeStmt(hasBody(nullStmt().bind("semi"))), whileStmt(hasBody(nullStmt().bind("semi"))))) diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/UndelegatedConstructorCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/UndelegatedConstructorCheck.cpp index 9db14ab40ce5..a4c1fd53dfbe 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/UndelegatedConstructorCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/UndelegatedConstructorCheck.cpp @@ -1,4 +1,4 @@ -//===--- UndelegatedConstructorCheck.cpp - clang-tidy --------------------------===// +//===--- UndelegatedConstructorCheck.cpp - clang-tidy----------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/UnhandledExceptionAtNewCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/UnhandledExceptionAtNewCheck.cpp index ca4562aa9a44..5e220017c97f 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/UnhandledExceptionAtNewCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/UnhandledExceptionAtNewCheck.cpp @@ -12,6 +12,7 @@ using namespace clang::ast_matchers; namespace clang::tidy::bugprone { +namespace { AST_MATCHER_P(CXXTryStmt, hasHandlerFor, ast_matchers::internal::Matcher, InnerMatcher) { @@ -36,6 +37,8 @@ AST_MATCHER(CXXNewExpr, mayThrow) { return !OperatorNew->getType()->castAs()->isNothrow(); } +} // namespace + UnhandledExceptionAtNewCheck::UnhandledExceptionAtNewCheck( StringRef Name, ClangTidyContext *Context) : ClangTidyCheck(Name, Context) {} diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/UnusedRaiiCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/UnusedRaiiCheck.cpp index d96e7524172b..b17d3868dd76 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/UnusedRaiiCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/UnusedRaiiCheck.cpp @@ -37,8 +37,8 @@ void UnusedRaiiCheck::registerMatchers(MatchFinder *Finder) { } template -void reportDiagnostic(DiagnosticBuilder D, const T *Node, SourceRange SR, - bool DefaultConstruction) { +static void reportDiagnostic(DiagnosticBuilder D, const T *Node, SourceRange SR, + bool DefaultConstruction) { const char *Replacement = " give_me_a_name"; // If this is a default ctor we have to remove the parens or we'll introduce a diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp index 960133159dbb..1bcacf96a412 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/bugprone/UseAfterMoveCheck.cpp @@ -242,7 +242,7 @@ void UseAfterMoveFinder::getUsesAndReinits( }); } -bool isStandardSmartPointer(const ValueDecl *VD) { +static bool isStandardSmartPointer(const ValueDecl *VD) { const Type *TheType = VD->getType().getNonReferenceType().getTypePtrOrNull(); if (!TheType) return false; diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/cert/CERTTidyModule.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/cert/CERTTidyModule.cpp index cc092a9627c5..66fedabaf3ca 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/cert/CERTTidyModule.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/cert/CERTTidyModule.cpp @@ -250,8 +250,7 @@ class CERTModule : public ClangTidyModule { "cert-dcl51-cpp"); CheckFactories.registerCheck( "cert-dcl54-cpp"); - CheckFactories.registerCheck( - "cert-dcl58-cpp"); + CheckFactories.registerCheck("cert-dcl58-cpp"); CheckFactories.registerCheck( "cert-dcl59-cpp"); // ERR @@ -278,8 +277,7 @@ class CERTModule : public ClangTidyModule { "cert-oop54-cpp"); CheckFactories.registerCheck( "cert-oop57-cpp"); - CheckFactories.registerCheck( - "cert-oop58-cpp"); + CheckFactories.registerCheck("cert-oop58-cpp"); // C checkers // ARR @@ -360,6 +358,6 @@ static ClangTidyModuleRegistry::Add // This anchor is used to force the linker to link in the generated object file // and thus register the CERTModule. -volatile int CERTModuleAnchorSource = 0; +volatile int CERTModuleAnchorSource = 0; // NOLINT(misc-use-internal-linkage) } // namespace clang::tidy diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/concurrency/ConcurrencyTidyModule.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/concurrency/ConcurrencyTidyModule.cpp index a88ee46fc4ab..6c58c506dc90 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/concurrency/ConcurrencyTidyModule.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/concurrency/ConcurrencyTidyModule.cpp @@ -27,12 +27,14 @@ class ConcurrencyModule : public ClangTidyModule { } // namespace concurrency -// Register the ConcurrencyTidyModule using this statically initialized variable. +// Register the ConcurrencyTidyModule using this statically initialized +// variable. static ClangTidyModuleRegistry::Add X("concurrency-module", "Adds concurrency checks."); // This anchor is used to force the linker to link in the generated object file // and thus register the ConcurrencyModule. +// NOLINTNEXTLINE(misc-use-internal-linkage) volatile int ConcurrencyModuleAnchorSource = 0; } // namespace clang::tidy diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/cppcoreguidelines/CppCoreGuidelinesTidyModule.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/cppcoreguidelines/CppCoreGuidelinesTidyModule.cpp index 6adef0426434..4dd9b0904f07 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/cppcoreguidelines/CppCoreGuidelinesTidyModule.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/cppcoreguidelines/CppCoreGuidelinesTidyModule.cpp @@ -156,6 +156,7 @@ static ClangTidyModuleRegistry::Add // This anchor is used to force the linker to link in the generated object file // and thus register the CppCoreGuidelinesModule. +// NOLINTNEXTLINE(misc-use-internal-linkage) volatile int CppCoreGuidelinesModuleAnchorSource = 0; } // namespace clang::tidy diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp index d665c47d12bb..aaaaf6b66b51 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/cppcoreguidelines/ProTypeMemberInitCheck.cpp @@ -433,21 +433,22 @@ void ProTypeMemberInitCheck::checkMissingMemberInitializer( // Gather all fields (direct and indirect) that need to be initialized. SmallPtrSet FieldsToInit; bool AnyMemberHasInitPerUnion = false; - forEachFieldWithFilter(ClassDecl, ClassDecl.fields(), - AnyMemberHasInitPerUnion, [&](const FieldDecl *F) { - if (IgnoreArrays && F->getType()->isArrayType()) - return; - if (F->hasInClassInitializer() && F->getParent()->isUnion()) { - AnyMemberHasInitPerUnion = true; - removeFieldInitialized(F, FieldsToInit); - } - if (!F->hasInClassInitializer() && - utils::type_traits::isTriviallyDefaultConstructible(F->getType(), - Context) && - !isEmpty(Context, F->getType()) && !F->isUnnamedBitField() && - !AnyMemberHasInitPerUnion) - FieldsToInit.insert(F); - }); + forEachFieldWithFilter( + ClassDecl, ClassDecl.fields(), AnyMemberHasInitPerUnion, + [&](const FieldDecl *F) { + if (IgnoreArrays && F->getType()->isArrayType()) + return; + if (F->hasInClassInitializer() && F->getParent()->isUnion()) { + AnyMemberHasInitPerUnion = true; + removeFieldInitialized(F, FieldsToInit); + } + if (!F->hasInClassInitializer() && + utils::type_traits::isTriviallyDefaultConstructible(F->getType(), + Context) && + !isEmpty(Context, F->getType()) && !F->isUnnamedBitField() && + !AnyMemberHasInitPerUnion) + FieldsToInit.insert(F); + }); if (FieldsToInit.empty()) return; @@ -500,17 +501,18 @@ void ProTypeMemberInitCheck::checkMissingMemberInitializer( AnyMemberHasInitPerUnion = false; forEachFieldWithFilter(ClassDecl, ClassDecl.fields(), AnyMemberHasInitPerUnion, [&](const FieldDecl *F) { - if (!FieldsToInit.count(F)) - return; - // Don't suggest fixes for enums because we don't know a good default. - // Don't suggest fixes for bitfields because in-class initialization is not - // possible until C++20. - if (F->getType()->isEnumeralType() || - (!getLangOpts().CPlusPlus20 && F->isBitField())) - return; - FieldsToFix.insert(F); - AnyMemberHasInitPerUnion = true; - }); + if (!FieldsToInit.count(F)) + return; + // Don't suggest fixes for enums because we don't + // know a good default. Don't suggest fixes for + // bitfields because in-class initialization is not + // possible until C++20. + if (F->getType()->isEnumeralType() || + (!getLangOpts().CPlusPlus20 && F->isBitField())) + return; + FieldsToFix.insert(F); + AnyMemberHasInitPerUnion = true; + }); if (FieldsToFix.empty()) return; diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/cppcoreguidelines/SlicingCheck.h b/external/llvm-project/clang-tools-extra/clang-tidy/cppcoreguidelines/SlicingCheck.h index 00f6e93fec20..02bfaf1205f4 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/cppcoreguidelines/SlicingCheck.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/cppcoreguidelines/SlicingCheck.h @@ -14,11 +14,7 @@ namespace clang::tidy::cppcoreguidelines { /// Flags slicing (incomplete copying of an object's state) of member variables -/// or vtable. See: -/// - https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es63-dont-slice -/// for the former, and -/// - https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c145-access-polymorphic-objects-through-pointers-and-references -/// for the latter +/// or vtable. /// /// For the user-facing documentation see: /// http://clang.llvm.org/extra/clang-tidy/checks/cppcoreguidelines/slicing.html diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.cpp index b1da3b9861c6..0de143dbb1b8 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.cpp @@ -116,7 +116,8 @@ void SpecialMemberFunctionsCheck::check( if (!MatchedDecl) return; - ClassDefId ID(MatchedDecl->getLocation(), std::string(MatchedDecl->getName())); + ClassDefId ID(MatchedDecl->getLocation(), + std::string(MatchedDecl->getName())); auto StoreMember = [this, &ID](SpecialMemberFunctionData Data) { llvm::SmallVectorImpl &Members = diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.h b/external/llvm-project/clang-tools-extra/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.h index 9ebc03ed2fa1..dee01cb5a9fd 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/cppcoreguidelines/SpecialMemberFunctionsCheck.h @@ -84,13 +84,12 @@ struct DenseMapInfo< clang::tidy::cppcoreguidelines::SpecialMemberFunctionsCheck::ClassDefId; static inline ClassDefId getEmptyKey() { - return {DenseMapInfo::getEmptyKey(), - "EMPTY"}; + return {DenseMapInfo::getEmptyKey(), "EMPTY"}; } static inline ClassDefId getTombstoneKey() { return {DenseMapInfo::getTombstoneKey(), - "TOMBSTONE"}; + "TOMBSTONE"}; } static unsigned getHashValue(ClassDefId Val) { diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/cppcoreguidelines/VirtualClassDestructorCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/cppcoreguidelines/VirtualClassDestructorCheck.cpp index aa70b3896f16..e31d04656567 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/cppcoreguidelines/VirtualClassDestructorCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/cppcoreguidelines/VirtualClassDestructorCheck.cpp @@ -18,6 +18,8 @@ using namespace clang::ast_matchers; namespace clang::tidy::cppcoreguidelines { +namespace { + AST_MATCHER(CXXRecordDecl, hasPublicVirtualOrProtectedNonVirtualDestructor) { // We need to call Node.getDestructor() instead of matching a // CXXDestructorDecl. Otherwise, tests will fail for class templates, since @@ -33,6 +35,8 @@ AST_MATCHER(CXXRecordDecl, hasPublicVirtualOrProtectedNonVirtualDestructor) { !Destructor->isVirtual())); } +} // namespace + void VirtualClassDestructorCheck::registerMatchers(MatchFinder *Finder) { ast_matchers::internal::Matcher InheritsVirtualMethod = hasAnyBase(hasType(cxxRecordDecl(has(cxxMethodDecl(isVirtual()))))); diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/darwin/AvoidSpinlockCheck.h b/external/llvm-project/clang-tools-extra/clang-tidy/darwin/AvoidSpinlockCheck.h index 727878b258b2..5b5285710c3b 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/darwin/AvoidSpinlockCheck.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/darwin/AvoidSpinlockCheck.h @@ -19,7 +19,7 @@ namespace clang::tidy::darwin { /// For the user-facing documentation see: /// http://clang.llvm.org/extra/clang-tidy/checks/darwin/avoid-spinlock.html class AvoidSpinlockCheck : public ClangTidyCheck { - public: +public: AvoidSpinlockCheck(StringRef Name, ClangTidyContext *Context) : ClangTidyCheck(Name, Context) {} void registerMatchers(ast_matchers::MatchFinder *Finder) override; @@ -28,4 +28,4 @@ class AvoidSpinlockCheck : public ClangTidyCheck { } // namespace clang::tidy::darwin -#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_DARWIN_AVOIDSPINLOCKCHECK_H +#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_DARWIN_AVOIDSPINLOCKCHECK_H diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/darwin/DarwinTidyModule.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/darwin/DarwinTidyModule.cpp index 3475deada499..bc8c91a9ed41 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/darwin/DarwinTidyModule.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/darwin/DarwinTidyModule.cpp @@ -18,8 +18,7 @@ namespace darwin { class DarwinModule : public ClangTidyModule { public: void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override { - CheckFactories.registerCheck( - "darwin-avoid-spinlock"); + CheckFactories.registerCheck("darwin-avoid-spinlock"); CheckFactories.registerCheck( "darwin-dispatch-once-nonstatic"); } @@ -33,6 +32,6 @@ static ClangTidyModuleRegistry::Add // This anchor is used to force the linker to link in the generated object file // and thus register the DarwinModule. -volatile int DarwinModuleAnchorSource = 0; +volatile int DarwinModuleAnchorSource = 0; // NOLINT(misc-use-internal-linkage) } // namespace clang::tidy diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/fuchsia/FuchsiaTidyModule.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/fuchsia/FuchsiaTidyModule.cpp index 45a79b75e093..d7a70b39bdc5 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/fuchsia/FuchsiaTidyModule.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/fuchsia/FuchsiaTidyModule.cpp @@ -52,6 +52,6 @@ static ClangTidyModuleRegistry::Add // This anchor is used to force the linker to link in the generated object file // and thus register the FuchsiaModule. -volatile int FuchsiaModuleAnchorSource = 0; +volatile int FuchsiaModuleAnchorSource = 0; // NOLINT(misc-use-internal-linkage) } // namespace clang::tidy diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/fuchsia/MultipleInheritanceCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/fuchsia/MultipleInheritanceCheck.cpp index b5ce23ae8fed..80ff97a76213 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/fuchsia/MultipleInheritanceCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/fuchsia/MultipleInheritanceCheck.cpp @@ -49,7 +49,8 @@ bool MultipleInheritanceCheck::getInterfaceStatus(const CXXRecordDecl *Node, bool MultipleInheritanceCheck::isCurrentClassInterface( const CXXRecordDecl *Node) const { // Interfaces should have no fields. - if (!Node->field_empty()) return false; + if (!Node->field_empty()) + return false; // Interfaces should have exclusively pure methods. return llvm::none_of(Node->methods(), [](const CXXMethodDecl *M) { @@ -68,11 +69,14 @@ bool MultipleInheritanceCheck::isInterface(const CXXRecordDecl *Node) { // To be an interface, all base classes must be interfaces as well. for (const auto &I : Node->bases()) { - if (I.isVirtual()) continue; + if (I.isVirtual()) + continue; const auto *Ty = I.getType()->getAs(); - if (!Ty) continue; + if (!Ty) + continue; const RecordDecl *D = Ty->getDecl()->getDefinition(); - if (!D) continue; + if (!D) + continue; const auto *Base = cast(D); if (!isInterface(Base)) { addNodeToInterfaceMap(Node, false); @@ -97,20 +101,25 @@ void MultipleInheritanceCheck::check(const MatchFinder::MatchResult &Result) { // concrete classes unsigned NumConcrete = 0; for (const auto &I : D->bases()) { - if (I.isVirtual()) continue; + if (I.isVirtual()) + continue; const auto *Ty = I.getType()->getAs(); - if (!Ty) continue; + if (!Ty) + continue; const auto *Base = cast(Ty->getDecl()->getDefinition()); - if (!isInterface(Base)) NumConcrete++; + if (!isInterface(Base)) + NumConcrete++; } // Check virtual bases to see if there is more than one concrete // non-virtual base. for (const auto &V : D->vbases()) { const auto *Ty = V.getType()->getAs(); - if (!Ty) continue; + if (!Ty) + continue; const auto *Base = cast(Ty->getDecl()->getDefinition()); - if (!isInterface(Base)) NumConcrete++; + if (!isInterface(Base)) + NumConcrete++; } if (NumConcrete > 1) { diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/fuchsia/StaticallyConstructedObjectsCheck.h b/external/llvm-project/clang-tools-extra/clang-tidy/fuchsia/StaticallyConstructedObjectsCheck.h index fc18273ad73b..6c65c8cfeb22 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/fuchsia/StaticallyConstructedObjectsCheck.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/fuchsia/StaticallyConstructedObjectsCheck.h @@ -14,7 +14,7 @@ namespace clang::tidy::fuchsia { /// Constructing global, non-trivial objects with static storage is -/// disallowed, unless the object is statically initialized with a constexpr +/// disallowed, unless the object is statically initialized with a constexpr /// constructor or has no explicit constructor. /// /// For the user-facing documentation see: diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/fuchsia/TrailingReturnCheck.h b/external/llvm-project/clang-tools-extra/clang-tidy/fuchsia/TrailingReturnCheck.h index 2ba8e27d00bf..70551844898f 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/fuchsia/TrailingReturnCheck.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/fuchsia/TrailingReturnCheck.h @@ -13,8 +13,8 @@ namespace clang::tidy::fuchsia { -/// Functions that have trailing returns are disallowed, except for those -/// using decltype specifiers and lambda with otherwise unutterable +/// Functions that have trailing returns are disallowed, except for those +/// using decltype specifiers and lambda with otherwise unutterable /// return types. /// /// For the user-facing documentation see: diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/fuchsia/VirtualInheritanceCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/fuchsia/VirtualInheritanceCheck.cpp index 9c367423fdb5..20bd036fb265 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/fuchsia/VirtualInheritanceCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/fuchsia/VirtualInheritanceCheck.cpp @@ -16,10 +16,13 @@ namespace clang::tidy::fuchsia { namespace { AST_MATCHER(CXXRecordDecl, hasDirectVirtualBaseClass) { - if (!Node.hasDefinition()) return false; - if (!Node.getNumVBases()) return false; + if (!Node.hasDefinition()) + return false; + if (!Node.getNumVBases()) + return false; for (const CXXBaseSpecifier &Base : Node.bases()) - if (Base.isVirtual()) return true; + if (Base.isVirtual()) + return true; return false; } } // namespace diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/fuchsia/VirtualInheritanceCheck.h b/external/llvm-project/clang-tools-extra/clang-tidy/fuchsia/VirtualInheritanceCheck.h index d109bd52a1a6..426d89d046a6 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/fuchsia/VirtualInheritanceCheck.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/fuchsia/VirtualInheritanceCheck.h @@ -18,7 +18,7 @@ namespace clang::tidy::fuchsia { /// For the user-facing documentation see: /// http://clang.llvm.org/extra/clang-tidy/checks/fuchsia/virtual-inheritance.html class VirtualInheritanceCheck : public ClangTidyCheck { - public: +public: VirtualInheritanceCheck(StringRef Name, ClangTidyContext *Context) : ClangTidyCheck(Name, Context) {} void registerMatchers(ast_matchers::MatchFinder *Finder) override; @@ -27,4 +27,4 @@ class VirtualInheritanceCheck : public ClangTidyCheck { } // namespace clang::tidy::fuchsia -#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_FUCHSIA_VIRTUAL_INHERITANCE_H +#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_FUCHSIA_VIRTUAL_INHERITANCE_H diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/google/AvoidCStyleCastsCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/google/AvoidCStyleCastsCheck.cpp index 3109bbb3724c..e076b39b5d97 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/google/AvoidCStyleCastsCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/google/AvoidCStyleCastsCheck.cpp @@ -120,8 +120,8 @@ void AvoidCStyleCastsCheck::check(const MatchFinder::MatchResult &Result) { IsFunction(SourceTypeAsWritten) && IsFunction(DestTypeAsWritten); const bool ConstructorCast = !CastExpr->getTypeAsWritten().hasQualifiers() && - DestTypeAsWritten->isRecordType() && - !DestTypeAsWritten->isElaboratedTypeSpecifier(); + DestTypeAsWritten->isRecordType() && + !DestTypeAsWritten->isElaboratedTypeSpecifier(); if (CastExpr->getCastKind() == CK_NoOp && !FnToFnCast) { // Function pointer/reference casts may be needed to resolve ambiguities in diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/google/AvoidThrowingObjCExceptionCheck.h b/external/llvm-project/clang-tools-extra/clang-tidy/google/AvoidThrowingObjCExceptionCheck.h index f8b191a37620..58b46e0a075a 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/google/AvoidThrowingObjCExceptionCheck.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/google/AvoidThrowingObjCExceptionCheck.h @@ -20,7 +20,7 @@ namespace clang::tidy::google::objc { /// For the user-facing documentation see: /// http://clang.llvm.org/extra/clang-tidy/checks/google/objc-avoid-throwing-exception.html class AvoidThrowingObjCExceptionCheck : public ClangTidyCheck { - public: +public: AvoidThrowingObjCExceptionCheck(StringRef Name, ClangTidyContext *Context) : ClangTidyCheck(Name, Context) {} bool isLanguageVersionSupported(const LangOptions &LangOpts) const override { @@ -32,4 +32,4 @@ class AvoidThrowingObjCExceptionCheck : public ClangTidyCheck { } // namespace clang::tidy::google::objc -#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_GOOGLE_OBJC_AVOID_THROWING_EXCEPTION_H +#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_GOOGLE_OBJC_AVOID_THROWING_EXCEPTION_H diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/google/ExplicitConstructorCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/google/ExplicitConstructorCheck.cpp index 6f26de988135..3deea0620514 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/google/ExplicitConstructorCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/google/ExplicitConstructorCheck.cpp @@ -85,7 +85,7 @@ void ExplicitConstructorCheck::check(const MatchFinder::MatchResult &Result) { "%0 explicit expression evaluates to 'false'"; if (const auto *Conversion = - Result.Nodes.getNodeAs("conversion")) { + Result.Nodes.getNodeAs("conversion")) { if (Conversion->isOutOfLine()) return; SourceLocation Loc = Conversion->getLocation(); diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/google/GlobalNamesInHeadersCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/google/GlobalNamesInHeadersCheck.cpp index cba8d71ab6a3..459dee124752 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/google/GlobalNamesInHeadersCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/google/GlobalNamesInHeadersCheck.cpp @@ -1,4 +1,4 @@ -//===--- GlobalNamesInHeadersCheck.cpp - clang-tidy -----------------*- C++ -*-===// +//===--- GlobalNamesInHeadersCheck.cpp - 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. diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/google/GlobalVariableDeclarationCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/google/GlobalVariableDeclarationCheck.cpp index 018d49fa5a22..9082c9368d87 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/google/GlobalVariableDeclarationCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/google/GlobalVariableDeclarationCheck.cpp @@ -52,7 +52,7 @@ FixItHint generateFixItHint(const VarDecl *Decl, bool IsConst) { CharSourceRange::getTokenRange(SourceRange(Decl->getLocation())), llvm::StringRef(NewName)); } -} // namespace +} // namespace void GlobalVariableDeclarationCheck::registerMatchers(MatchFinder *Finder) { // need to add two matchers since we need to bind different ids to distinguish diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/google/GlobalVariableDeclarationCheck.h b/external/llvm-project/clang-tools-extra/clang-tidy/google/GlobalVariableDeclarationCheck.h index 550224b26d14..19e6c5dbc8e2 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/google/GlobalVariableDeclarationCheck.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/google/GlobalVariableDeclarationCheck.h @@ -20,7 +20,7 @@ namespace clang::tidy::google::objc { /// For the user-facing documentation see: /// http://clang.llvm.org/extra/clang-tidy/checks/google/objc-global-variable-declaration.html class GlobalVariableDeclarationCheck : public ClangTidyCheck { - public: +public: GlobalVariableDeclarationCheck(StringRef Name, ClangTidyContext *Context) : ClangTidyCheck(Name, Context) {} bool isLanguageVersionSupported(const LangOptions &LangOpts) const override { @@ -32,4 +32,4 @@ class GlobalVariableDeclarationCheck : public ClangTidyCheck { } // namespace clang::tidy::google::objc -#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_GOOGLE_OBJC_GLOBAL_VARIABLE_DECLARATION_H +#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_GOOGLE_OBJC_GLOBAL_VARIABLE_DECLARATION_H diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/google/GoogleTidyModule.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/google/GoogleTidyModule.cpp index 830a37af1acc..5343e2b3a597 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/google/GoogleTidyModule.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/google/GoogleTidyModule.cpp @@ -35,7 +35,7 @@ namespace clang::tidy { namespace google { class GoogleModule : public ClangTidyModule { - public: +public: void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override { CheckFactories.registerCheck( "google-build-explicit-make-pair"); @@ -96,10 +96,10 @@ class GoogleModule : public ClangTidyModule { static ClangTidyModuleRegistry::Add X("google-module", "Adds Google lint checks."); -} // namespace google +} // namespace google // This anchor is used to force the linker to link in the generated object file // and thus register the GoogleModule. -volatile int GoogleModuleAnchorSource = 0; +volatile int GoogleModuleAnchorSource = 0; // NOLINT(misc-use-internal-linkage) } // namespace clang::tidy diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/google/IntegerTypesCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/google/IntegerTypesCheck.cpp index 359d8efd100b..711444fa9bcd 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/google/IntegerTypesCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/google/IntegerTypesCheck.cpp @@ -172,8 +172,8 @@ void IntegerTypesCheck::check(const MatchFinder::MatchResult &Result) { // We don't add a fix-it as changing the type can easily break code, // e.g. when a function requires a 'long' argument on all platforms. // QualTypes are printed with implicit quotes. - diag(Loc, "consider replacing %0 with '%1'") << BuiltinLoc.getType() - << Replacement; + diag(Loc, "consider replacing %0 with '%1'") + << BuiltinLoc.getType() << Replacement; } } // namespace tidy::google::runtime diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/google/UnnamedNamespaceInHeaderCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/google/UnnamedNamespaceInHeaderCheck.cpp index 3db27868fcca..c1e421308d77 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/google/UnnamedNamespaceInHeaderCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/google/UnnamedNamespaceInHeaderCheck.cpp @@ -21,8 +21,8 @@ UnnamedNamespaceInHeaderCheck::UnnamedNamespaceInHeaderCheck( void UnnamedNamespaceInHeaderCheck::registerMatchers( ast_matchers::MatchFinder *Finder) { - Finder->addMatcher(namespaceDecl(isAnonymous()).bind("anonymousNamespace"), - this); + Finder->addMatcher(namespaceDecl(isAnonymous()).bind("anonymousNamespace"), + this); } void UnnamedNamespaceInHeaderCheck::check( diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/google/UsingNamespaceDirectiveCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/google/UsingNamespaceDirectiveCheck.cpp index e9734e54a13e..26d27c19f489 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/google/UsingNamespaceDirectiveCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/google/UsingNamespaceDirectiveCheck.cpp @@ -16,7 +16,7 @@ namespace clang::tidy::google::build { void UsingNamespaceDirectiveCheck::registerMatchers( ast_matchers::MatchFinder *Finder) { - Finder->addMatcher(usingDirectiveDecl().bind("usingNamespace"), this); + Finder->addMatcher(usingDirectiveDecl().bind("usingNamespace"), this); } void UsingNamespaceDirectiveCheck::check( diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/hicpp/ExceptionBaseclassCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/hicpp/ExceptionBaseclassCheck.cpp index 2b2acfdf5b08..ed39568ea554 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/hicpp/ExceptionBaseclassCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/hicpp/ExceptionBaseclassCheck.cpp @@ -24,14 +24,12 @@ void ExceptionBaseclassCheck::registerMatchers(MatchFinder *Finder) { isSameOrDerivedFrom(hasName("::std::exception")))))))))), // This condition is always true, but will bind to the // template value if the thrown type is templated. - anyOf(has(expr( - hasType(substTemplateTypeParmType().bind("templ_type")))), - anything()), + optionally(has( + expr(hasType(substTemplateTypeParmType().bind("templ_type"))))), // Bind to the declaration of the type of the value that - // is thrown. 'anything()' is necessary to always succeed - // in the 'eachOf' because builtin types are not - // 'namedDecl'. - eachOf(has(expr(hasType(namedDecl().bind("decl")))), anything())) + // is thrown. 'optionally' is necessary because builtin types + // are not 'namedDecl'. + optionally(has(expr(hasType(namedDecl().bind("decl")))))) .bind("bad_throw"), this); } diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/hicpp/ExceptionBaseclassCheck.h b/external/llvm-project/clang-tools-extra/clang-tidy/hicpp/ExceptionBaseclassCheck.h index 036db35a2290..79d8cf925d1b 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/hicpp/ExceptionBaseclassCheck.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/hicpp/ExceptionBaseclassCheck.h @@ -13,7 +13,8 @@ namespace clang::tidy::hicpp { -/// Check for thrown exceptions and enforce they are all derived from std::exception. +/// Check for thrown exceptions and enforce they are all derived from +/// std::exception. /// /// For the user-facing documentation see: /// http://clang.llvm.org/extra/clang-tidy/checks/hicpp/exception-baseclass.html diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/hicpp/HICPPTidyModule.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/hicpp/HICPPTidyModule.cpp index 38f3ab5ae85d..65a56be3e5a0 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/hicpp/HICPPTidyModule.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/hicpp/HICPPTidyModule.cpp @@ -119,6 +119,6 @@ static ClangTidyModuleRegistry::Add // This anchor is used to force the linker to link in the generated object file // and thus register the HICPPModule. -volatile int HICPPModuleAnchorSource = 0; +volatile int HICPPModuleAnchorSource = 0; // NOLINT(misc-use-internal-linkage) } // namespace clang::tidy diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/hicpp/MultiwayPathsCoveredCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/hicpp/MultiwayPathsCoveredCheck.cpp index 7028c3958f10..3f5cd4b47390 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/hicpp/MultiwayPathsCoveredCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/hicpp/MultiwayPathsCoveredCheck.cpp @@ -113,7 +113,7 @@ void MultiwayPathsCoveredCheck::check(const MatchFinder::MatchResult &Result) { } // Warns for degenerated 'switch' statements that neither define a case nor // a default label. - // FIXME: Evaluate, if emitting a fix-it to simplify that statement is + // FIXME: Evaluate, if emitting a fix-it to simplify that statement is // reasonable. if (!SwitchHasDefault && SwitchCaseCount == 0) { diag(Switch->getBeginLoc(), diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/linuxkernel/LinuxKernelTidyModule.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/linuxkernel/LinuxKernelTidyModule.cpp index e6d64ff61d26..b8b75b7ccaef 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/linuxkernel/LinuxKernelTidyModule.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/linuxkernel/LinuxKernelTidyModule.cpp @@ -30,6 +30,7 @@ static ClangTidyModuleRegistry::Add // This anchor is used to force the linker to link in the generated object file // and thus register the LinuxKernelModule. +// NOLINTNEXTLINE(misc-use-internal-linkage) volatile int LinuxKernelModuleAnchorSource = 0; } // namespace clang::tidy diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/linuxkernel/MustCheckErrsCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/linuxkernel/MustCheckErrsCheck.cpp index 149d0a94eaa5..ce501ac2acca 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/linuxkernel/MustCheckErrsCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/linuxkernel/MustCheckErrsCheck.cpp @@ -19,8 +19,7 @@ void MustCheckErrsCheck::registerMatchers(MatchFinder *Finder) { "ERR_CAST", "PTR_ERR_OR_ZERO")); auto NonCheckingStmts = stmt(anyOf(compoundStmt(), labelStmt())); Finder->addMatcher( - callExpr(callee(ErrFn), hasParent(NonCheckingStmts)).bind("call"), - this); + callExpr(callee(ErrFn), hasParent(NonCheckingStmts)).bind("call"), this); auto ReturnToCheck = returnStmt(hasReturnValue(callExpr(callee(ErrFn)))); auto ReturnsErrFn = functionDecl(hasDescendant(ReturnToCheck)); diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/llvm/LLVMTidyModule.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/llvm/LLVMTidyModule.cpp index e749163699b3..ceebde1595e7 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/llvm/LLVMTidyModule.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/llvm/LLVMTidyModule.cpp @@ -57,6 +57,6 @@ static ClangTidyModuleRegistry::Add X("llvm-module", // This anchor is used to force the linker to link in the generated object file // and thus register the LLVMModule. -volatile int LLVMModuleAnchorSource = 0; +volatile int LLVMModuleAnchorSource = 0; // NOLINT(misc-use-internal-linkage) } // namespace clang::tidy diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/llvm/PreferIsaOrDynCastInConditionalsCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/llvm/PreferIsaOrDynCastInConditionalsCheck.cpp index 933333777770..4c138bcc564d 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/llvm/PreferIsaOrDynCastInConditionalsCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/llvm/PreferIsaOrDynCastInConditionalsCheck.cpp @@ -14,12 +14,11 @@ using namespace clang::ast_matchers; -namespace clang { -namespace ast_matchers { -AST_MATCHER(Expr, isMacroID) { return Node.getExprLoc().isMacroID(); } -} // namespace ast_matchers +namespace clang::tidy::llvm_check { -namespace tidy::llvm_check { +namespace { +AST_MATCHER(Expr, isMacroID) { return Node.getExprLoc().isMacroID(); } +} // namespace void PreferIsaOrDynCastInConditionalsCheck::registerMatchers( MatchFinder *Finder) { @@ -125,5 +124,4 @@ void PreferIsaOrDynCastInConditionalsCheck::check( } } -} // namespace tidy::llvm_check -} // namespace clang +} // namespace clang::tidy::llvm_check diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/llvm/PreferIsaOrDynCastInConditionalsCheck.h b/external/llvm-project/clang-tools-extra/clang-tidy/llvm/PreferIsaOrDynCastInConditionalsCheck.h index dd9c5fec6af5..5b611096c25f 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/llvm/PreferIsaOrDynCastInConditionalsCheck.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/llvm/PreferIsaOrDynCastInConditionalsCheck.h @@ -15,8 +15,9 @@ namespace clang::tidy::llvm_check { /// Looks at conditionals and finds and replaces cases of ``cast<>``, which will /// assert rather than return a null pointer, and ``dyn_cast<>`` where -/// the return value is not captured. Additionally, finds and replaces cases that match the -/// pattern ``var && isa(var)``, where ``var`` is evaluated twice. +/// the return value is not captured. Additionally, finds and replaces cases +/// that match the pattern ``var && isa(var)``, where ``var`` is evaluated +/// twice. /// /// Finds cases like these: /// \code diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/llvmlibc/CalleeNamespaceCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/llvmlibc/CalleeNamespaceCheck.cpp index d14cd2721d9a..4bc4d5a4691f 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/llvmlibc/CalleeNamespaceCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/llvmlibc/CalleeNamespaceCheck.cpp @@ -19,7 +19,7 @@ namespace clang::tidy::llvm_libc { // Gets the outermost namespace of a DeclContext, right under the Translation // Unit. -const DeclContext *getOutermostNamespace(const DeclContext *Decl) { +static const DeclContext *getOutermostNamespace(const DeclContext *Decl) { const DeclContext *Parent = Decl->getParent(); if (Parent->isTranslationUnit()) return Decl; diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/llvmlibc/LLVMLibcTidyModule.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/llvmlibc/LLVMLibcTidyModule.cpp index 7f26840be737..562d71a0891c 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/llvmlibc/LLVMLibcTidyModule.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/llvmlibc/LLVMLibcTidyModule.cpp @@ -39,6 +39,7 @@ static ClangTidyModuleRegistry::Add // This anchor is used to force the linker to link in the generated object file // and thus register the LLVMLibcModule. +// NOLINTNEXTLINE(misc-use-internal-linkage) volatile int LLVMLibcModuleAnchorSource = 0; } // namespace clang::tidy diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/misc/MiscTidyModule.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/misc/MiscTidyModule.cpp index 54bcebca7e18..6ddebcbc0e15 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/misc/MiscTidyModule.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/misc/MiscTidyModule.cpp @@ -92,6 +92,6 @@ static ClangTidyModuleRegistry::Add // This anchor is used to force the linker to link in the generated object file // and thus register the MiscModule. -volatile int MiscModuleAnchorSource = 0; +volatile int MiscModuleAnchorSource = 0; // NOLINT(misc-use-internal-linkage) } // namespace clang::tidy diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/misc/StaticAssertCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/misc/StaticAssertCheck.cpp index faff1c17fc61..37fbd8c0d725 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/misc/StaticAssertCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/misc/StaticAssertCheck.cpp @@ -38,8 +38,7 @@ void StaticAssertCheck::registerMatchers(MatchFinder *Finder) { binaryOperator( hasAnyOperatorName("&&", "=="), hasEitherOperand(ignoringImpCasts(stringLiteral().bind("assertMSG"))), - anyOf(binaryOperator(hasEitherOperand(IsAlwaysFalseWithCast)), - anything())) + optionally(binaryOperator(hasEitherOperand(IsAlwaysFalseWithCast)))) .bind("assertExprRoot"), IsAlwaysFalse); auto NonConstexprFunctionCall = @@ -52,12 +51,10 @@ void StaticAssertCheck::registerMatchers(MatchFinder *Finder) { auto NonConstexprCode = expr(anyOf(NonConstexprFunctionCall, NonConstexprVariableReference)); auto AssertCondition = - expr( - anyOf(expr(ignoringParenCasts(anyOf( - AssertExprRoot, unaryOperator(hasUnaryOperand( - ignoringParenCasts(AssertExprRoot)))))), - anything()), - unless(NonConstexprCode), unless(hasDescendant(NonConstexprCode))) + expr(optionally(expr(ignoringParenCasts(anyOf( + AssertExprRoot, unaryOperator(hasUnaryOperand( + ignoringParenCasts(AssertExprRoot))))))), + unless(NonConstexprCode), unless(hasDescendant(NonConstexprCode))) .bind("condition"); auto Condition = anyOf(ignoringParenImpCasts(callExpr( diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/misc/ThrowByValueCatchByReferenceCheck.h b/external/llvm-project/clang-tools-extra/clang-tidy/misc/ThrowByValueCatchByReferenceCheck.h index 0d4df97c7bdf..e3cc4c5e6cd4 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/misc/ThrowByValueCatchByReferenceCheck.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/misc/ThrowByValueCatchByReferenceCheck.h @@ -13,7 +13,7 @@ namespace clang::tidy::misc { -///checks for locations that do not throw by value +/// Checks for locations that do not throw by value // or catch by reference. // The check is C++ only. It checks that all throw locations // throw by value and not by pointer. Additionally it diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/AvoidBindCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/AvoidBindCheck.cpp index a41524af5680..c9477327742d 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/AvoidBindCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/AvoidBindCheck.cpp @@ -452,8 +452,8 @@ static bool isFixitSupported(const CallableInfo &Callee, return true; } -const FunctionDecl *getCallOperator(const CXXRecordDecl *Callable, - size_t NumArgs) { +static const FunctionDecl *getCallOperator(const CXXRecordDecl *Callable, + size_t NumArgs) { std::vector Candidates = findCandidateCallOperators(Callable, NumArgs); if (Candidates.size() != 1) @@ -462,7 +462,7 @@ const FunctionDecl *getCallOperator(const CXXRecordDecl *Callable, return Candidates.front(); } -const FunctionDecl * +static const FunctionDecl * getCallMethodDecl(const MatchFinder::MatchResult &Result, CallableType Type, CallableMaterializationKind Materialization) { diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/DeprecatedIosBaseAliasesCheck.h b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/DeprecatedIosBaseAliasesCheck.h index eb791ec12814..09cfebef48d4 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/DeprecatedIosBaseAliasesCheck.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/DeprecatedIosBaseAliasesCheck.h @@ -13,8 +13,8 @@ namespace clang::tidy::modernize { -/// This check warns the uses of the deprecated member types of ``std::ios_base`` -/// and replaces those that have a non-deprecated equivalent. +/// This check warns the uses of the deprecated member types of +/// ``std::ios_base`` and replaces those that have a non-deprecated equivalent. /// /// For the user-facing documentation see: /// http://clang.llvm.org/extra/clang-tidy/checks/modernize/deprecated-ios-base-aliases.html diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp index eb11ae616202..6c6c626ec4fe 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/LoopConvertCheck.cpp @@ -114,7 +114,7 @@ arrayConditionMatcher(internal::Matcher LimitExpr) { /// Client code will need to make sure that: /// - The index variable is only used as an array index. /// - All arrays indexed by the loop are the same. -StatementMatcher makeArrayLoopMatcher() { +static StatementMatcher makeArrayLoopMatcher() { StatementMatcher ArrayBoundMatcher = expr(hasType(isInteger())).bind(ConditionBoundName); @@ -155,7 +155,7 @@ StatementMatcher makeArrayLoopMatcher() { /// /// Client code will need to make sure that: /// - The two containers on which 'begin' and 'end' are called are the same. -StatementMatcher makeIteratorLoopMatcher(bool IsReverse) { +static StatementMatcher makeIteratorLoopMatcher(bool IsReverse) { auto BeginNameMatcher = IsReverse ? hasAnyName("rbegin", "crbegin") : hasAnyName("begin", "cbegin"); @@ -267,7 +267,7 @@ StatementMatcher makeIteratorLoopMatcher(bool IsReverse) { /// - The index variable is only used in overloaded operator[] or /// container.at(). /// - The container's iterators would not be invalidated during the loop. -StatementMatcher makePseudoArrayLoopMatcher() { +static StatementMatcher makePseudoArrayLoopMatcher() { // Test that the incoming type has a record declaration that has methods // called 'begin' and 'end'. If the incoming type is const, then make sure // these methods are also marked const. diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.cpp index 93c231b0bdf0..3d0a1f01725f 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/LoopConvertUtils.cpp @@ -688,9 +688,8 @@ bool ForLoopIndexUseVisitor::TraverseArraySubscriptExpr(ArraySubscriptExpr *E) { if (!isIndexInSubscriptExpr(E->getIdx(), IndexVar)) return VisitorBase::TraverseArraySubscriptExpr(E); - if ((ContainerExpr && - !areSameExpr(Context, Arr->IgnoreParenImpCasts(), - ContainerExpr->IgnoreParenImpCasts())) || + if ((ContainerExpr && !areSameExpr(Context, Arr->IgnoreParenImpCasts(), + ContainerExpr->IgnoreParenImpCasts())) || !arrayMatchesBoundExpr(Context, Arr->IgnoreImpCasts()->getType(), ArrayBoundExpr)) { // If we have already discovered the array being indexed and this isn't it diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp index ae88ec2abaf7..c2db858f72e3 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/MacroToEnumCheck.cpp @@ -161,7 +161,7 @@ class MacroToEnumCallbacks : public PPCallbacks { checkName(MacroNameTok); } void Elifdef(SourceLocation Loc, SourceRange ConditionRange, - SourceLocation IfLoc) override { + SourceLocation IfLoc) override { PPCallbacks::Elifdef(Loc, ConditionRange, IfLoc); } void Elifndef(SourceLocation Loc, const Token &MacroNameTok, @@ -169,7 +169,7 @@ class MacroToEnumCallbacks : public PPCallbacks { checkName(MacroNameTok); } void Elifndef(SourceLocation Loc, SourceRange ConditionRange, - SourceLocation IfLoc) override { + SourceLocation IfLoc) override { PPCallbacks::Elifndef(Loc, ConditionRange, IfLoc); } void Endif(SourceLocation Loc, SourceLocation IfLoc) override; @@ -316,8 +316,7 @@ void MacroToEnumCallbacks::FileChanged(SourceLocation Loc, CurrentFile = &Files.back(); } -bool MacroToEnumCallbacks::isInitializer(ArrayRef MacroTokens) -{ +bool MacroToEnumCallbacks::isInitializer(ArrayRef MacroTokens) { IntegralLiteralExpressionMatcher Matcher(MacroTokens, LangOpts.C99 == 0); bool Matched = Matcher.match(); bool IsC = !LangOpts.CPlusPlus; @@ -328,7 +327,6 @@ bool MacroToEnumCallbacks::isInitializer(ArrayRef MacroTokens) return Matched; } - // Any defined but rejected macro is scanned for identifiers that // are to be excluded as enums. void MacroToEnumCallbacks::MacroDefined(const Token &MacroNameTok, @@ -444,8 +442,8 @@ void MacroToEnumCallbacks::invalidateExpressionNames() { } void MacroToEnumCallbacks::EndOfMainFile() { - invalidateExpressionNames(); - issueDiagnostics(); + invalidateExpressionNames(); + issueDiagnostics(); } void MacroToEnumCallbacks::invalidateRange(SourceRange Range) { @@ -517,7 +515,8 @@ void MacroToEnumCallbacks::fixEnumMacro(const MacroList &MacroList) const { void MacroToEnumCheck::registerPPCallbacks(const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) { - auto Callback = std::make_unique(this, getLangOpts(), SM); + auto Callback = + std::make_unique(this, getLangOpts(), SM); PPCallback = Callback.get(); PP->addPPCallbacks(std::move(Callback)); } @@ -540,7 +539,7 @@ void MacroToEnumCheck::check( const ast_matchers::MatchFinder::MatchResult &Result) { auto *TLDecl = Result.Nodes.getNodeAs("top"); if (TLDecl == nullptr) - return; + return; SourceRange Range = TLDecl->getSourceRange(); if (auto *TemplateFn = Result.Nodes.getNodeAs("top")) { diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/MakeSmartPtrCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/MakeSmartPtrCheck.cpp index d1d7e9dcfa9c..deef3586628c 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/MakeSmartPtrCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/MakeSmartPtrCheck.cpp @@ -361,8 +361,7 @@ bool MakeSmartPtrCheck::replaceNew(DiagnosticBuilder &Diag, Diag << FixItHint::CreateRemoval( SourceRange(NewStart, InitRange.getBegin())); Diag << FixItHint::CreateRemoval(SourceRange(InitRange.getEnd(), NewEnd)); - } - else { + } else { // New array expression with default/value initialization: // smart_ptr(new int[5]()); // smart_ptr(new Foo[5]()); diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp index fc46c72982fd..0cf59b6e0216 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp @@ -110,11 +110,11 @@ class ModernizeModule : public ClangTidyModule { CheckFactories.registerCheck( "modernize-use-default-member-init"); CheckFactories.registerCheck("modernize-use-emplace"); - CheckFactories.registerCheck("modernize-use-equals-default"); + CheckFactories.registerCheck( + "modernize-use-equals-default"); CheckFactories.registerCheck( "modernize-use-equals-delete"); - CheckFactories.registerCheck( - "modernize-use-nodiscard"); + CheckFactories.registerCheck("modernize-use-nodiscard"); CheckFactories.registerCheck("modernize-use-noexcept"); CheckFactories.registerCheck("modernize-use-nullptr"); CheckFactories.registerCheck("modernize-use-override"); @@ -136,6 +136,7 @@ static ClangTidyModuleRegistry::Add X("modernize-module", // This anchor is used to force the linker to link in the generated object file // and thus register the ModernizeModule. +// NOLINTNEXTLINE(misc-use-internal-linkage) volatile int ModernizeModuleAnchorSource = 0; } // namespace clang::tidy diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/RedundantVoidArgCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/RedundantVoidArgCheck.cpp index 53447c2b960f..5eebccc366fd 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/RedundantVoidArgCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/RedundantVoidArgCheck.cpp @@ -112,7 +112,8 @@ void RedundantVoidArgCheck::processFunctionDecl( "function declaration"); } -bool isMacroIdentifier(const IdentifierTable &Idents, const Token &ProtoToken) { +static bool isMacroIdentifier(const IdentifierTable &Idents, + const Token &ProtoToken) { if (!ProtoToken.is(tok::TokenKind::raw_identifier)) return false; diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/ReplaceAutoPtrCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/ReplaceAutoPtrCheck.cpp index 4587b0867078..1ad31d315dc2 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/ReplaceAutoPtrCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/ReplaceAutoPtrCheck.cpp @@ -141,8 +141,7 @@ void ReplaceAutoPtrCheck::check(const MatchFinder::MatchResult &Result) { "auto_ptr") return; - SourceLocation EndLoc = - AutoPtrLoc.getLocWithOffset(strlen("auto_ptr") - 1); + SourceLocation EndLoc = AutoPtrLoc.getLocWithOffset(strlen("auto_ptr") - 1); diag(AutoPtrLoc, "auto_ptr is deprecated, use unique_ptr instead") << FixItHint::CreateReplacement(SourceRange(AutoPtrLoc, EndLoc), "unique_ptr"); diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp index 7a2d804e173c..f4b63087b723 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseAutoCheck.cpp @@ -38,12 +38,11 @@ size_t getTypeNameLength(bool RemoveStars, StringRef Text) { else if (C == '>') --TemplateTypenameCntr; const CharType NextChar = - isAlphanumeric(C) - ? Alpha - : (isWhitespace(C) || - (!RemoveStars && TemplateTypenameCntr == 0 && C == '*')) - ? Space - : Punctuation; + isAlphanumeric(C) ? Alpha + : (isWhitespace(C) || + (!RemoveStars && TemplateTypenameCntr == 0 && C == '*')) + ? Space + : Punctuation; if (NextChar != Space) { ++NumChars; // Count the non-space character. if (LastChar == Space && NextChar == Alpha && BeforeSpace == Alpha) @@ -444,10 +443,10 @@ void UseAutoCheck::check(const MatchFinder::MatchResult &Result) { replaceIterators(Decl, Result.Context); } else if (const auto *Decl = Result.Nodes.getNodeAs(DeclWithNewId)) { - replaceExpr(Decl, Result.Context, - [](const Expr *Expr) { return Expr->getType(); }, - "use auto when initializing with new to avoid " - "duplicating the type name"); + replaceExpr( + Decl, Result.Context, [](const Expr *Expr) { return Expr->getType(); }, + "use auto when initializing with new to avoid " + "duplicating the type name"); } else if (const auto *Decl = Result.Nodes.getNodeAs(DeclWithCastId)) { replaceExpr( diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseBoolLiteralsCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseBoolLiteralsCheck.cpp index c8e6bf47bb82..339462093a6d 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseBoolLiteralsCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseBoolLiteralsCheck.cpp @@ -26,13 +26,12 @@ void UseBoolLiteralsCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) { void UseBoolLiteralsCheck::registerMatchers(MatchFinder *Finder) { Finder->addMatcher( - traverse( - TK_AsIs, - implicitCastExpr( - has(ignoringParenImpCasts(integerLiteral().bind("literal"))), - hasImplicitDestinationType(qualType(booleanType())), - unless(isInTemplateInstantiation()), - anyOf(hasParent(explicitCastExpr().bind("cast")), anything()))), + traverse(TK_AsIs, + implicitCastExpr( + has(ignoringParenImpCasts(integerLiteral().bind("literal"))), + hasImplicitDestinationType(qualType(booleanType())), + unless(isInTemplateInstantiation()), + optionally(hasParent(explicitCastExpr().bind("cast"))))), this); Finder->addMatcher( diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseConstraintsCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseConstraintsCheck.cpp index 6040cddf0e52..9e4d184c4b6e 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseConstraintsCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseConstraintsCheck.cpp @@ -279,7 +279,7 @@ findInsertionForConstraint(const FunctionDecl *Function, ASTContext &Context) { return Body->getBeginLoc(); } -bool isPrimaryExpression(const Expr *Expression) { +static bool isPrimaryExpression(const Expr *Expression) { // This function is an incomplete approximation of checking whether // an Expr is a primary expression. In particular, if this function // returns true, the expression is a primary expression. The converse diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp index 430455a38f39..aaf24eaa33c1 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseEmplaceCheck.cpp @@ -98,8 +98,8 @@ auto hasWantedType(llvm::ArrayRef TypeNames) { // Matches member call expressions of the named method on the listed container // types. -auto cxxMemberCallExprOnContainer( - StringRef MethodName, llvm::ArrayRef ContainerNames) { +auto cxxMemberCallExprOnContainer(StringRef MethodName, + llvm::ArrayRef ContainerNames) { return cxxMemberCallExpr( hasDeclaration(functionDecl(hasName(MethodName))), on(hasTypeOrPointeeType(hasWantedType(ContainerNames)))); diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp index 93151024064b..b361ae445653 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.cpp @@ -48,8 +48,8 @@ static std::set getAllDirectBases(const CXXRecordDecl *Record) { /// Returns a matcher that matches member expressions where the base is /// the variable declared as \p Var and the accessed member is the one declared /// as \p Field. -internal::Matcher accessToFieldInVar(const FieldDecl *Field, - const ValueDecl *Var) { +static internal::Matcher accessToFieldInVar(const FieldDecl *Field, + const ValueDecl *Var) { return ignoringImpCasts( memberExpr(hasObjectExpression(declRefExpr(to(varDecl(equalsNode(Var))))), member(fieldDecl(equalsNode(Field))))); diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.h b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.h index 44f26c2bcfc5..04c2177704fb 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseEqualsDefaultCheck.h @@ -1,4 +1,4 @@ -//===--- UseEqualsDefaultCheck.h - clang-tidy--------------------------*- C++ -*-===// +//===--- UseEqualsDefaultCheck.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. diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseEqualsDeleteCheck.h b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseEqualsDeleteCheck.h index 8545aa2a6396..64f60351c065 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseEqualsDeleteCheck.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseEqualsDeleteCheck.h @@ -1,4 +1,4 @@ -//===--- UseEqualsDeleteCheck.h - clang-tidy---------------------------*- C++ -*-===// +//===--- UseEqualsDeleteCheck.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. diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.cpp index a6b00be75abf..c38fb3a01d28 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseNullptrCheck.cpp @@ -229,7 +229,7 @@ class CastSequenceVisitor : public RecursiveASTVisitor { return true; } - auto* CastSubExpr = C->getSubExpr()->IgnoreParens(); + auto *CastSubExpr = C->getSubExpr()->IgnoreParens(); // Ignore cast expressions which cast nullptr literal. if (isa(CastSubExpr)) { return true; diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp index 2e059f24d47b..2af67f7ccb4c 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp @@ -33,6 +33,8 @@ static bool isNegativeComparison(const Expr *ComparisonExpr) { return false; } +namespace { + struct NotLengthExprForStringNode { NotLengthExprForStringNode(std::string ID, DynTypedNode Node, ASTContext *Context) @@ -91,6 +93,8 @@ AST_MATCHER_P(Expr, lengthExprForStringNode, std::string, ID) { ID, DynTypedNode::create(Node), &(Finder->getASTContext()))); } +} // namespace + UseStartsEndsWithCheck::UseStartsEndsWithCheck(StringRef Name, ClangTidyContext *Context) : ClangTidyCheck(Name, Context) {} diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp index 4e5c6a798be9..ced4825f79a9 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp @@ -17,6 +17,30 @@ #include #include +namespace clang::tidy { + +template <> +struct OptionEnumMapping< + modernize::UseTrailingReturnTypeCheck::TransformLambda> { + static llvm::ArrayRef> + getEnumMapping() { + static constexpr std::pair< + modernize::UseTrailingReturnTypeCheck::TransformLambda, StringRef> + Mapping[] = { + {modernize::UseTrailingReturnTypeCheck::TransformLambda::All, + "all"}, + {modernize::UseTrailingReturnTypeCheck::TransformLambda:: + AllExceptAuto, + "all_except_auto"}, + {modernize::UseTrailingReturnTypeCheck::TransformLambda::None, + "none"}}; + return Mapping; + } +}; + +} // namespace clang::tidy + using namespace clang::ast_matchers; namespace clang::tidy::modernize { @@ -111,10 +135,17 @@ struct UnqualNameVisitor : public RecursiveASTVisitor { private: const FunctionDecl &F; }; + +AST_MATCHER(LambdaExpr, hasExplicitResultType) { + return Node.hasExplicitResultType(); +} + } // namespace constexpr llvm::StringLiteral ErrorMessageOnFunction = "use a trailing return type for this function"; +constexpr llvm::StringLiteral ErrorMessageOnLambda = + "use a trailing return type for this lambda"; static SourceLocation expandIfMacroId(SourceLocation Loc, const SourceManager &SM) { @@ -285,7 +316,6 @@ findReturnTypeAndCVSourceRange(const FunctionDecl &F, const TypeLoc &ReturnLoc, return {}; } - // If the return type has no local qualifiers, it's source range is accurate. if (!hasAnyNestedLocalQualifiers(F.getReturnType())) return ReturnTypeRange; @@ -329,6 +359,48 @@ findReturnTypeAndCVSourceRange(const FunctionDecl &F, const TypeLoc &ReturnLoc, return ReturnTypeRange; } +static SourceLocation findLambdaTrailingReturnInsertLoc( + const CXXMethodDecl *Method, const SourceManager &SM, + const LangOptions &LangOpts, const ASTContext &Ctx) { + // 'requires' keyword is present in lambda declaration + if (Method->getTrailingRequiresClause()) { + SourceLocation ParamEndLoc; + if (Method->param_empty()) + ParamEndLoc = Method->getBeginLoc(); + else + ParamEndLoc = Method->getParametersSourceRange().getEnd(); + + std::pair ParamEndLocInfo = + SM.getDecomposedLoc(ParamEndLoc); + StringRef Buffer = SM.getBufferData(ParamEndLocInfo.first); + + Lexer Lexer(SM.getLocForStartOfFile(ParamEndLocInfo.first), LangOpts, + Buffer.begin(), Buffer.data() + ParamEndLocInfo.second, + Buffer.end()); + + Token Token; + while (!Lexer.LexFromRawLexer(Token)) { + if (Token.is(tok::raw_identifier)) { + IdentifierInfo &Info = Ctx.Idents.get(StringRef( + SM.getCharacterData(Token.getLocation()), Token.getLength())); + Token.setIdentifierInfo(&Info); + Token.setKind(Info.getTokenID()); + } + + if (Token.is(tok::kw_requires)) + return Token.getLocation().getLocWithOffset(-1); + } + + return {}; + } + + // If no requires clause, insert before the body + if (const Stmt *Body = Method->getBody()) + return Body->getBeginLoc().getLocWithOffset(-1); + + return {}; +} + static void keepSpecifiers(std::string &ReturnType, std::string &Auto, SourceRange ReturnTypeCVRange, const FunctionDecl &F, const FriendDecl *Fr, const ASTContext &Ctx, @@ -382,14 +454,43 @@ static void keepSpecifiers(std::string &ReturnType, std::string &Auto, } } +UseTrailingReturnTypeCheck::UseTrailingReturnTypeCheck( + StringRef Name, ClangTidyContext *Context) + : ClangTidyCheck(Name, Context), + TransformFunctions(Options.get("TransformFunctions", true)), + TransformLambdas(Options.get("TransformLambdas", TransformLambda::All)) { + + if (TransformFunctions == false && TransformLambdas == TransformLambda::None) + this->configurationDiag( + "The check 'modernize-use-trailing-return-type' will not perform any " + "analysis because 'TransformFunctions' and 'TransformLambdas' are " + "disabled."); +} + +void UseTrailingReturnTypeCheck::storeOptions( + ClangTidyOptions::OptionMap &Opts) { + Options.store(Opts, "TransformFunctions", TransformFunctions); + Options.store(Opts, "TransformLambdas", TransformLambdas); +} + void UseTrailingReturnTypeCheck::registerMatchers(MatchFinder *Finder) { - auto F = functionDecl( - unless(anyOf(hasTrailingReturn(), returns(voidType()), - cxxConversionDecl(), cxxMethodDecl(isImplicit())))) - .bind("Func"); + auto F = + functionDecl( + unless(anyOf( + hasTrailingReturn(), returns(voidType()), cxxConversionDecl(), + cxxMethodDecl( + anyOf(isImplicit(), + hasParent(cxxRecordDecl(hasParent(lambdaExpr())))))))) + .bind("Func"); + + if (TransformFunctions) { + Finder->addMatcher(F, this); + Finder->addMatcher(friendDecl(hasDescendant(F)).bind("Friend"), this); + } - Finder->addMatcher(F, this); - Finder->addMatcher(friendDecl(hasDescendant(F)).bind("Friend"), this); + if (TransformLambdas != TransformLambda::None) + Finder->addMatcher( + lambdaExpr(unless(hasExplicitResultType())).bind("Lambda"), this); } void UseTrailingReturnTypeCheck::registerPPCallbacks( @@ -401,8 +502,13 @@ void UseTrailingReturnTypeCheck::check(const MatchFinder::MatchResult &Result) { assert(PP && "Expected registerPPCallbacks() to have been called before so " "preprocessor is available"); - const auto *F = Result.Nodes.getNodeAs("Func"); + if (const auto *Lambda = Result.Nodes.getNodeAs("Lambda")) { + diagOnLambda(Lambda, Result); + return; + } + const auto *Fr = Result.Nodes.getNodeAs("Friend"); + const auto *F = Result.Nodes.getNodeAs("Func"); assert(F && "Matcher is expected to find only FunctionDecls"); // Three-way comparison operator<=> is syntactic sugar and generates implicit @@ -495,4 +601,41 @@ void UseTrailingReturnTypeCheck::check(const MatchFinder::MatchResult &Result) { << FixItHint::CreateInsertion(InsertionLoc, " -> " + ReturnType); } +void UseTrailingReturnTypeCheck::diagOnLambda( + const LambdaExpr *Lambda, + const ast_matchers::MatchFinder::MatchResult &Result) { + + const CXXMethodDecl *Method = Lambda->getCallOperator(); + if (!Method || Lambda->hasExplicitResultType()) + return; + + const ASTContext *Ctx = Result.Context; + const QualType ReturnType = Method->getReturnType(); + + // We can't write 'auto' in C++11 mode, try to write generic msg and bail out. + if (ReturnType->isDependentType() && + Ctx->getLangOpts().LangStd == LangStandard::lang_cxx11) { + if (TransformLambdas == TransformLambda::All) + diag(Lambda->getBeginLoc(), ErrorMessageOnLambda); + return; + } + + if (ReturnType->isUndeducedAutoType() && + TransformLambdas == TransformLambda::AllExceptAuto) + return; + + const SourceLocation TrailingReturnInsertLoc = + findLambdaTrailingReturnInsertLoc(Method, *Result.SourceManager, + getLangOpts(), *Result.Context); + + if (TrailingReturnInsertLoc.isValid()) + diag(Lambda->getBeginLoc(), "use a trailing return type for this lambda") + << FixItHint::CreateInsertion( + TrailingReturnInsertLoc, + " -> " + + ReturnType.getAsString(Result.Context->getPrintingPolicy())); + else + diag(Lambda->getBeginLoc(), ErrorMessageOnLambda); +} + } // namespace clang::tidy::modernize diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.h b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.h index 7f20674d15a5..91369919c5d3 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.h @@ -26,18 +26,25 @@ struct ClassifiedToken { /// http://clang.llvm.org/extra/clang-tidy/checks/modernize/use-trailing-return-type.html class UseTrailingReturnTypeCheck : public ClangTidyCheck { public: - UseTrailingReturnTypeCheck(StringRef Name, ClangTidyContext *Context) - : ClangTidyCheck(Name, Context) {} + UseTrailingReturnTypeCheck(StringRef Name, ClangTidyContext *Context); bool isLanguageVersionSupported(const LangOptions &LangOpts) const override { return LangOpts.CPlusPlus11; } + void storeOptions(ClangTidyOptions::OptionMap &Opts) override; void registerMatchers(ast_matchers::MatchFinder *Finder) override; void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) override; void check(const ast_matchers::MatchFinder::MatchResult &Result) override; + enum TransformLambda { All, AllExceptAuto, None }; + private: Preprocessor *PP = nullptr; + const bool TransformFunctions; + const TransformLambda TransformLambdas; + + void diagOnLambda(const LambdaExpr *Lambda, + const ast_matchers::MatchFinder::MatchResult &Result); }; } // namespace clang::tidy::modernize diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseTransparentFunctorsCheck.h b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseTransparentFunctorsCheck.h index 6f02becc9f9d..80f022159c67 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseTransparentFunctorsCheck.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseTransparentFunctorsCheck.h @@ -26,6 +26,7 @@ class UseTransparentFunctorsCheck : public ClangTidyCheck { void registerMatchers(ast_matchers::MatchFinder *Finder) override; void check(const ast_matchers::MatchFinder::MatchResult &Result) override; void storeOptions(ClangTidyOptions::OptionMap &Opts) override; + private: const bool SafeMode; }; diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseUncaughtExceptionsCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseUncaughtExceptionsCheck.cpp index 109d701395cc..1e0a0a551339 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseUncaughtExceptionsCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseUncaughtExceptionsCheck.cpp @@ -39,10 +39,10 @@ void UseUncaughtExceptionsCheck::registerMatchers(MatchFinder *Finder) { this); // CallExpr in initialisation list: warning, fix-it with avoiding narrowing // conversions. - Finder->addMatcher(callExpr(DirectCallToUncaughtException, - hasAncestor(initListExpr())) - .bind("init_call_expr"), - this); + Finder->addMatcher( + callExpr(DirectCallToUncaughtException, hasAncestor(initListExpr())) + .bind("init_call_expr"), + this); } void UseUncaughtExceptionsCheck::check(const MatchFinder::MatchResult &Result) { diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseUncaughtExceptionsCheck.h b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseUncaughtExceptionsCheck.h index 79b475c4f850..48677521181f 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseUncaughtExceptionsCheck.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/modernize/UseUncaughtExceptionsCheck.h @@ -13,9 +13,10 @@ namespace clang::tidy::modernize { -/// This check will warn on calls to std::uncaught_exception and replace them with calls to -/// std::uncaught_exceptions, since std::uncaught_exception was deprecated in C++17. In case of -/// macro ID there will be only a warning without fixits. +/// This check will warn on calls to std::uncaught_exception and replace them +/// with calls to std::uncaught_exceptions, since std::uncaught_exception was +/// deprecated in C++17. In case of macro ID there will be only a warning +/// without fixits. /// /// For the user-facing documentation see: /// http://clang.llvm.org/extra/clang-tidy/checks/modernize/use-uncaught-exceptions.html diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/mpi/MPITidyModule.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/mpi/MPITidyModule.cpp index 166d71e130db..67ae101c18cb 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/mpi/MPITidyModule.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/mpi/MPITidyModule.cpp @@ -31,6 +31,6 @@ static ClangTidyModuleRegistry::Add // This anchor is used to force the linker to link in the generated object file // and thus register the MPIModule. -volatile int MPIModuleAnchorSource = 0; +volatile int MPIModuleAnchorSource = 0; // NOLINT(misc-use-internal-linkage) } // namespace clang::tidy diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/objc/AvoidNSErrorInitCheck.h b/external/llvm-project/clang-tools-extra/clang-tidy/objc/AvoidNSErrorInitCheck.h index 72a6c6512f62..b343cb0c4fa8 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/objc/AvoidNSErrorInitCheck.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/objc/AvoidNSErrorInitCheck.h @@ -19,7 +19,7 @@ namespace clang::tidy::objc { /// For the user-facing documentation see: /// http://clang.llvm.org/extra/clang-tidy/checks/objc/avoid-nserror-init.html class AvoidNSErrorInitCheck : public ClangTidyCheck { - public: +public: AvoidNSErrorInitCheck(StringRef Name, ClangTidyContext *Context) : ClangTidyCheck(Name, Context) {} bool isLanguageVersionSupported(const LangOptions &LangOpts) const override { @@ -31,4 +31,4 @@ class AvoidNSErrorInitCheck : public ClangTidyCheck { } // namespace clang::tidy::objc -#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_OBJC_AVOIDNSERRORINITCHECK_H +#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_OBJC_AVOIDNSERRORINITCHECK_H diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/objc/ForbiddenSubclassingCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/objc/ForbiddenSubclassingCheck.cpp index 579aa2965071..089538d4c65a 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/objc/ForbiddenSubclassingCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/objc/ForbiddenSubclassingCheck.cpp @@ -35,14 +35,11 @@ constexpr char DefaultForbiddenSuperClassNames[] = } // namespace -ForbiddenSubclassingCheck::ForbiddenSubclassingCheck( - StringRef Name, - ClangTidyContext *Context) +ForbiddenSubclassingCheck::ForbiddenSubclassingCheck(StringRef Name, + ClangTidyContext *Context) : ClangTidyCheck(Name, Context), - ForbiddenSuperClassNames( - utils::options::parseStringList( - Options.get("ClassNames", DefaultForbiddenSuperClassNames))) { -} + ForbiddenSuperClassNames(utils::options::parseStringList( + Options.get("ClassNames", DefaultForbiddenSuperClassNames))) {} void ForbiddenSubclassingCheck::registerMatchers(MatchFinder *Finder) { Finder->addMatcher( @@ -53,27 +50,22 @@ void ForbiddenSubclassingCheck::registerMatchers(MatchFinder *Finder) { this); } -void ForbiddenSubclassingCheck::check( - const MatchFinder::MatchResult &Result) { - const auto *SubClass = Result.Nodes.getNodeAs( - "subclass"); +void ForbiddenSubclassingCheck::check(const MatchFinder::MatchResult &Result) { + const auto *SubClass = Result.Nodes.getNodeAs("subclass"); assert(SubClass != nullptr); - const auto *SuperClass = Result.Nodes.getNodeAs( - "superclass"); + const auto *SuperClass = + Result.Nodes.getNodeAs("superclass"); assert(SuperClass != nullptr); diag(SubClass->getLocation(), "Objective-C interface %0 subclasses %1, which is not " "intended to be subclassed") - << SubClass - << SuperClass; + << SubClass << SuperClass; } void ForbiddenSubclassingCheck::storeOptions( ClangTidyOptions::OptionMap &Opts) { - Options.store( - Opts, - "ForbiddenSuperClassNames", - utils::options::serializeStringList(ForbiddenSuperClassNames)); + Options.store(Opts, "ForbiddenSuperClassNames", + utils::options::serializeStringList(ForbiddenSuperClassNames)); } } // namespace clang::tidy::objc diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/objc/NSDateFormatterCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/objc/NSDateFormatterCheck.cpp index 5438c9c892e2..79e9d97d9594 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/objc/NSDateFormatterCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/objc/NSDateFormatterCheck.cpp @@ -34,7 +34,7 @@ static char ValidDatePatternChars[] = { // A string pattern is valid if all the letters(a-z, A-Z) in it belong to the // set of reserved characters. See: // https://www.unicode.org/reports/tr35/tr35.html#Invalid_Patterns -bool isValidDatePattern(StringRef Pattern) { +static bool isValidDatePattern(StringRef Pattern) { return llvm::all_of(Pattern, [](const auto &PatternChar) { return !isalpha(PatternChar) || llvm::is_contained(ValidDatePatternChars, PatternChar); diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/objc/ObjCTidyModule.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/objc/ObjCTidyModule.cpp index b6f8888ed389..56ccf33a6362 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/objc/ObjCTidyModule.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/objc/ObjCTidyModule.cpp @@ -35,27 +35,24 @@ class ObjCModule : public ClangTidyModule { "objc-dealloc-in-category"); CheckFactories.registerCheck( "objc-forbidden-subclassing"); - CheckFactories.registerCheck( - "objc-missing-hash"); + CheckFactories.registerCheck("objc-missing-hash"); CheckFactories.registerCheck("objc-nsdate-formatter"); CheckFactories.registerCheck( "objc-nsinvocation-argument-lifetime"); CheckFactories.registerCheck( "objc-property-declaration"); - CheckFactories.registerCheck( - "objc-super-self"); + CheckFactories.registerCheck("objc-super-self"); } }; // Register the ObjCTidyModule using this statically initialized variable. -static ClangTidyModuleRegistry::Add X( - "objc-module", - "Adds Objective-C lint checks."); +static ClangTidyModuleRegistry::Add + X("objc-module", "Adds Objective-C lint checks."); } // namespace objc // This anchor is used to force the linker to link in the generated object file // and thus register the ObjCModule. -volatile int ObjCModuleAnchorSource = 0; +volatile int ObjCModuleAnchorSource = 0; // NOLINT(misc-use-internal-linkage) } // namespace clang::tidy diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/objc/PropertyDeclarationCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/objc/PropertyDeclarationCheck.cpp index cda24de49186..3b847f51d217 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/objc/PropertyDeclarationCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/objc/PropertyDeclarationCheck.cpp @@ -88,7 +88,7 @@ bool prefixedPropertyNameValid(llvm::StringRef PropertyName) { auto RegexExp = llvm::Regex(llvm::StringRef(validPropertyNameRegex(false))); return RegexExp.match(PropertyName.substr(Start + 1)); } -} // namespace +} // namespace void PropertyDeclarationCheck::registerMatchers(MatchFinder *Finder) { Finder->addMatcher(objcPropertyDecl( diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/openmp/ExceptionEscapeCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/openmp/ExceptionEscapeCheck.cpp index 603d0954e1b1..42fb95bf1052 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/openmp/ExceptionEscapeCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/openmp/ExceptionEscapeCheck.cpp @@ -20,8 +20,7 @@ ExceptionEscapeCheck::ExceptionEscapeCheck(StringRef Name, ClangTidyContext *Context) : ClangTidyCheck(Name, Context), RawIgnoredExceptions(Options.get("IgnoredExceptions", "")) { - llvm::SmallVector FunctionsThatShouldNotThrowVec, - IgnoredExceptionsVec; + llvm::SmallVector IgnoredExceptionsVec; llvm::StringSet<> IgnoredExceptions; StringRef(RawIgnoredExceptions).split(IgnoredExceptionsVec, ",", -1, false); diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/openmp/OpenMPTidyModule.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/openmp/OpenMPTidyModule.cpp index 37092f49b25d..d9c9d9067340 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/openmp/OpenMPTidyModule.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/openmp/OpenMPTidyModule.cpp @@ -34,6 +34,6 @@ static ClangTidyModuleRegistry::Add // This anchor is used to force the linker to link in the generated object file // and thus register the OpenMPModule. -volatile int OpenMPModuleAnchorSource = 0; +volatile int OpenMPModuleAnchorSource = 0; // NOLINT(misc-use-internal-linkage) } // namespace clang::tidy diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/performance/FasterStringFindCheck.h b/external/llvm-project/clang-tools-extra/clang-tidy/performance/FasterStringFindCheck.h index 93ed32e5b878..83af95cd6954 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/performance/FasterStringFindCheck.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/performance/FasterStringFindCheck.h @@ -25,7 +25,7 @@ namespace clang::tidy::performance { class FasterStringFindCheck : public ClangTidyCheck { public: FasterStringFindCheck(StringRef Name, ClangTidyContext *Context); - bool isLanguageVersionSupported(const LangOptions &LangOpts) const override{ + bool isLanguageVersionSupported(const LangOptions &LangOpts) const override { return LangOpts.CPlusPlus; } void registerMatchers(ast_matchers::MatchFinder *Finder) override; diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.h b/external/llvm-project/clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.h index ab9b89d31f93..8fabbfa2ae7b 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.h @@ -20,7 +20,7 @@ namespace clang::tidy::performance { class ForRangeCopyCheck : public ClangTidyCheck { public: ForRangeCopyCheck(StringRef Name, ClangTidyContext *Context); - bool isLanguageVersionSupported(const LangOptions &LangOpts) const override{ + bool isLanguageVersionSupported(const LangOptions &LangOpts) const override { return LangOpts.CPlusPlus11; } void storeOptions(ClangTidyOptions::OptionMap &Opts) override; diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/performance/ImplicitConversionInLoopCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/performance/ImplicitConversionInLoopCheck.cpp index 86fca0722dcd..1ecf1e14957a 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/performance/ImplicitConversionInLoopCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/performance/ImplicitConversionInLoopCheck.cpp @@ -65,8 +65,7 @@ void ImplicitConversionInLoopCheck::check( const MatchFinder::MatchResult &Result) { const auto *VD = Result.Nodes.getNodeAs("faulty-var"); const auto *Init = Result.Nodes.getNodeAs("init"); - const auto *OperatorCall = - Result.Nodes.getNodeAs("operator-call"); + const auto *OperatorCall = Result.Nodes.getNodeAs("operator-call"); if (const auto *Cleanup = dyn_cast(Init)) Init = Cleanup->getSubExpr(); diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/performance/ImplicitConversionInLoopCheck.h b/external/llvm-project/clang-tools-extra/clang-tidy/performance/ImplicitConversionInLoopCheck.h index 2f3c9ae8f2db..d1764070bd4d 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/performance/ImplicitConversionInLoopCheck.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/performance/ImplicitConversionInLoopCheck.h @@ -20,9 +20,9 @@ class ImplicitConversionInLoopCheck : public ClangTidyCheck { public: ImplicitConversionInLoopCheck(StringRef Name, ClangTidyContext *Context) : ClangTidyCheck(Name, Context) {} - bool isLanguageVersionSupported(const LangOptions &LangOpts) const override{ - return LangOpts.CPlusPlus11; - } + bool isLanguageVersionSupported(const LangOptions &LangOpts) const override { + return LangOpts.CPlusPlus11; + } void registerMatchers(ast_matchers::MatchFinder *Finder) override; void check(const ast_matchers::MatchFinder::MatchResult &Result) override; diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/performance/InefficientVectorOperationCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/performance/InefficientVectorOperationCheck.cpp index 94cb7ec38087..9692fcb0c1de 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/performance/InefficientVectorOperationCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/performance/InefficientVectorOperationCheck.cpp @@ -126,15 +126,14 @@ void InefficientVectorOperationCheck::addMatcher( // // FIXME: Support more types of counter-based loops like decrement loops. Finder->addMatcher( - forStmt( - hasLoopInit(LoopVarInit), - hasCondition(binaryOperator( - hasOperatorName("<"), hasLHS(RefersToLoopVar), - hasRHS(expr(unless(hasDescendant(expr(RefersToLoopVar)))) - .bind(LoopEndExprName)))), - hasIncrement(unaryOperator(hasOperatorName("++"), - hasUnaryOperand(RefersToLoopVar))), - HasInterestingLoopBody, InInterestingCompoundStmt) + forStmt(hasLoopInit(LoopVarInit), + hasCondition(binaryOperator( + hasOperatorName("<"), hasLHS(RefersToLoopVar), + hasRHS(expr(unless(hasDescendant(expr(RefersToLoopVar)))) + .bind(LoopEndExprName)))), + hasIncrement(unaryOperator(hasOperatorName("++"), + hasUnaryOperand(RefersToLoopVar))), + HasInterestingLoopBody, InInterestingCompoundStmt) .bind(LoopCounterName), this); @@ -179,7 +178,7 @@ void InefficientVectorOperationCheck::registerMatchers(MatchFinder *Finder) { void InefficientVectorOperationCheck::check( const MatchFinder::MatchResult &Result) { - auto* Context = Result.Context; + auto *Context = Result.Context; if (Context->getDiagnostics().hasUncompilableErrorOccurred()) return; diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/performance/InefficientVectorOperationCheck.h b/external/llvm-project/clang-tools-extra/clang-tidy/performance/InefficientVectorOperationCheck.h index 7a2745f7ae5f..4f45ff490633 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/performance/InefficientVectorOperationCheck.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/performance/InefficientVectorOperationCheck.h @@ -24,7 +24,7 @@ namespace clang::tidy::performance { class InefficientVectorOperationCheck : public ClangTidyCheck { public: InefficientVectorOperationCheck(StringRef Name, ClangTidyContext *Context); - bool isLanguageVersionSupported(const LangOptions &LangOpts) const override{ + bool isLanguageVersionSupported(const LangOptions &LangOpts) const override { return LangOpts.CPlusPlus; } void registerMatchers(ast_matchers::MatchFinder *Finder) override; diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/performance/MoveConstArgCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/performance/MoveConstArgCheck.cpp index 75ef7a697031..f458e26d964b 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/performance/MoveConstArgCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/performance/MoveConstArgCheck.cpp @@ -78,9 +78,9 @@ void MoveConstArgCheck::registerMatchers(MatchFinder *Finder) { this); } -bool isRValueReferenceParam(const Expr *Invocation, - const QualType *InvocationParmType, - const Expr *Arg) { +static bool isRValueReferenceParam(const Expr *Invocation, + const QualType *InvocationParmType, + const Expr *Arg) { if (Invocation && (*InvocationParmType)->isRValueReferenceType() && Arg->isLValue()) { if (!Invocation->getType()->isRecordType()) diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/performance/PerformanceTidyModule.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/performance/PerformanceTidyModule.cpp index 9e0fa6f88b36..10ad9ec6fef4 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/performance/PerformanceTidyModule.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/performance/PerformanceTidyModule.cpp @@ -81,6 +81,7 @@ static ClangTidyModuleRegistry::Add // This anchor is used to force the linker to link in the generated object file // and thus register the PerformanceModule. +// NOLINTNEXTLINE(misc-use-internal-linkage) volatile int PerformanceModuleAnchorSource = 0; } // namespace clang::tidy diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp index ce360dded863..b6f19811f5e5 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.cpp @@ -111,10 +111,11 @@ AST_MATCHER_FUNCTION(StatementMatcher, isConstRefReturningFunctionCall) { // an alias to one of its arguments and the arguments need to be checked // for const use as well. return callExpr(argumentCountIs(0), - callee(functionDecl(returns(hasCanonicalType(matchers::isReferenceToConst())), + callee(functionDecl(returns(hasCanonicalType( + matchers::isReferenceToConst())), unless(cxxMethodDecl(unless(isStatic())))) - .bind(FunctionDeclId))) - .bind(InitFunctionCallId); + .bind(FunctionDeclId))) + .bind(InitFunctionCallId); } AST_MATCHER_FUNCTION_P(StatementMatcher, initializerReturnsReferenceToConst, @@ -234,12 +235,14 @@ UnnecessaryCopyInitialization::UnnecessaryCopyInitialization( Options.get("ExcludedContainerTypes", ""))) {} void UnnecessaryCopyInitialization::registerMatchers(MatchFinder *Finder) { - auto LocalVarCopiedFrom = [this](const ast_matchers::internal::Matcher &CopyCtorArg) { - return compoundStmt( - forEachDescendant( - declStmt( - unless(has(decompositionDecl())), - has(varDecl(hasLocalStorage(), + auto LocalVarCopiedFrom = + [this](const ast_matchers::internal::Matcher &CopyCtorArg) { + return compoundStmt( + forEachDescendant( + declStmt( + unless(has(decompositionDecl())), + has(varDecl( + hasLocalStorage(), hasType(qualType( hasCanonicalType(allOf( matchers::isExpensiveToCopy(), @@ -256,10 +259,10 @@ void UnnecessaryCopyInitialization::registerMatchers(MatchFinder *Finder) { isCopyConstructor())), hasArgument(0, CopyCtorArg)) .bind("ctorCall")))) - .bind("newVarDecl"))) - .bind("declStmt"))) - .bind("blockStmt"); - }; + .bind("newVarDecl"))) + .bind("declStmt"))) + .bind("blockStmt"); + }; Finder->addMatcher( LocalVarCopiedFrom(anyOf( diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.h b/external/llvm-project/clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.h index ab0f1ecf6106..38f756f9b452 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/performance/UnnecessaryCopyInitialization.h @@ -25,7 +25,7 @@ namespace clang::tidy::performance { class UnnecessaryCopyInitialization : public ClangTidyCheck { public: UnnecessaryCopyInitialization(StringRef Name, ClangTidyContext *Context); - bool isLanguageVersionSupported(const LangOptions &LangOpts) const override{ + bool isLanguageVersionSupported(const LangOptions &LangOpts) const override { return LangOpts.CPlusPlus; } void registerMatchers(ast_matchers::MatchFinder *Finder) override; diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/plugin/ClangTidyPlugin.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/plugin/ClangTidyPlugin.cpp index 3caa222b9fa4..651a63b3aa97 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/plugin/ClangTidyPlugin.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/plugin/ClangTidyPlugin.cpp @@ -78,6 +78,7 @@ class ClangTidyPluginAction : public PluginASTAction { // This anchor is used to force the linker to link in the generated object file // and thus register the clang-tidy plugin. +// NOLINTNEXTLINE(misc-use-internal-linkage) volatile int ClangTidyPluginAnchorSource = 0; static clang::FrontendPluginRegistry::Add diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/portability/PortabilityTidyModule.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/portability/PortabilityTidyModule.cpp index a15cb36dfdaf..98853556588b 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/portability/PortabilityTidyModule.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/portability/PortabilityTidyModule.cpp @@ -42,6 +42,7 @@ static ClangTidyModuleRegistry::Add // This anchor is used to force the linker to link in the generated object file // and thus register the PortabilityModule. +// NOLINTNEXTLINE(misc-use-internal-linkage) volatile int PortabilityModuleAnchorSource = 0; } // namespace clang::tidy diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/portability/SIMDIntrinsicsCheck.h b/external/llvm-project/clang-tools-extra/clang-tidy/portability/SIMDIntrinsicsCheck.h index c254a374ee9d..92fc0af98a25 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/portability/SIMDIntrinsicsCheck.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/portability/SIMDIntrinsicsCheck.h @@ -30,7 +30,7 @@ class SIMDIntrinsicsCheck : public ClangTidyCheck { void registerMatchers(ast_matchers::MatchFinder *Finder) override; void check(const ast_matchers::MatchFinder::MatchResult &Result) override; - private: +private: llvm::SmallString<32> Std; const bool Suggest; }; diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/readability/ConstReturnTypeCheck.h b/external/llvm-project/clang-tools-extra/clang-tidy/readability/ConstReturnTypeCheck.h index c3d779eafecb..e329b3d8496a 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/readability/ConstReturnTypeCheck.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/readability/ConstReturnTypeCheck.h @@ -19,16 +19,16 @@ namespace clang::tidy::readability { /// For the user-facing documentation see: /// http://clang.llvm.org/extra/clang-tidy/checks/readability/const-return-type.html class ConstReturnTypeCheck : public ClangTidyCheck { - public: - ConstReturnTypeCheck(StringRef Name, ClangTidyContext *Context) - : ClangTidyCheck(Name, Context), - IgnoreMacros(Options.getLocalOrGlobal("IgnoreMacros", true)) {} - void storeOptions(ClangTidyOptions::OptionMap &Opts) override; - void registerMatchers(ast_matchers::MatchFinder *Finder) override; - void check(const ast_matchers::MatchFinder::MatchResult &Result) override; +public: + ConstReturnTypeCheck(StringRef Name, ClangTidyContext *Context) + : ClangTidyCheck(Name, Context), + IgnoreMacros(Options.getLocalOrGlobal("IgnoreMacros", true)) {} + void storeOptions(ClangTidyOptions::OptionMap &Opts) override; + void registerMatchers(ast_matchers::MatchFinder *Finder) override; + void check(const ast_matchers::MatchFinder::MatchResult &Result) override; - private: - const bool IgnoreMacros; +private: + const bool IgnoreMacros; }; } // namespace clang::tidy::readability diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp index bf7a847dff10..ce736a8d1602 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/readability/ContainerSizeEmptyCheck.cpp @@ -16,29 +16,31 @@ using namespace clang::ast_matchers; -namespace clang { -namespace ast_matchers { +namespace clang::tidy::readability { + +namespace { AST_POLYMORPHIC_MATCHER_P2(hasAnyArgumentWithParam, AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr, CXXConstructExpr), - internal::Matcher, ArgMatcher, - internal::Matcher, ParamMatcher) { - BoundNodesTreeBuilder Result; + ast_matchers::internal::Matcher, ArgMatcher, + ast_matchers::internal::Matcher, + ParamMatcher) { + ast_matchers::internal::BoundNodesTreeBuilder Result; // The first argument of an overloaded member operator is the implicit object // argument of the method which should not be matched against a parameter, so // we skip over it here. - BoundNodesTreeBuilder Matches; + ast_matchers::internal::BoundNodesTreeBuilder Matches; unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl())) .matches(Node, Finder, &Matches) ? 1 : 0; int ParamIndex = 0; for (; ArgIndex < Node.getNumArgs(); ++ArgIndex) { - BoundNodesTreeBuilder ArgMatches(*Builder); + ast_matchers::internal::BoundNodesTreeBuilder ArgMatches(*Builder); if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()), Finder, &ArgMatches)) { - BoundNodesTreeBuilder ParamMatches(ArgMatches); + ast_matchers::internal::BoundNodesTreeBuilder ParamMatches(ArgMatches); if (expr(anyOf(cxxConstructExpr(hasDeclaration(cxxConstructorDecl( hasParameter(ParamIndex, ParamMatcher)))), callExpr(callee(functionDecl( @@ -80,9 +82,10 @@ AST_MATCHER(Expr, usedInBooleanContext) { binaryOperator(hasAnyOperatorName("&&", "||")), unaryOperator(hasOperatorName("!")).bind("NegOnSize")))))) .matches(Node, Finder, Builder); - Builder->removeBindings([ExprName](const BoundNodesMap &Nodes) { - return Nodes.getNode(ExprName).getNodeKind().isNone(); - }); + Builder->removeBindings( + [ExprName](const ast_matchers::internal::BoundNodesMap &Nodes) { + return Nodes.getNode(ExprName).getNodeKind().isNone(); + }); return Result; } @@ -107,8 +110,7 @@ AST_MATCHER_P(UserDefinedLiteral, hasLiteral, return false; } -} // namespace ast_matchers -namespace tidy::readability { +} // namespace using utils::isBinaryOrTernary; @@ -407,5 +409,4 @@ void ContainerSizeEmptyCheck::check(const MatchFinder::MatchResult &Result) { << Container; } -} // namespace tidy::readability -} // namespace clang +} // namespace clang::tidy::readability diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/readability/ConvertMemberFunctionsToStatic.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/readability/ConvertMemberFunctionsToStatic.cpp index 1284df6bd99c..30df40bda57d 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/readability/ConvertMemberFunctionsToStatic.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/readability/ConvertMemberFunctionsToStatic.cpp @@ -18,6 +18,8 @@ using namespace clang::ast_matchers; namespace clang::tidy::readability { +namespace { + AST_MATCHER(CXXMethodDecl, isStatic) { return Node.isStatic(); } AST_MATCHER(CXXMethodDecl, hasTrivialBody) { return Node.hasTrivialBody(); } @@ -74,6 +76,8 @@ AST_MATCHER(CXXMethodDecl, usesThis) { return UsageOfThis.Used; } +} // namespace + void ConvertMemberFunctionsToStatic::registerMatchers(MatchFinder *Finder) { Finder->addMatcher( cxxMethodDecl( @@ -81,7 +85,8 @@ void ConvertMemberFunctionsToStatic::registerMatchers(MatchFinder *Finder) { unless(anyOf( isExpansionInSystemHeader(), isVirtual(), isStatic(), hasTrivialBody(), isOverloadedOperator(), cxxConstructorDecl(), - cxxDestructorDecl(), cxxConversionDecl(), isTemplate(), + cxxDestructorDecl(), cxxConversionDecl(), + isExplicitObjectMemberFunction(), isTemplate(), isDependentContext(), ofClass(anyOf( isLambda(), diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp index f9fd1d903e23..20c73299915a 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp @@ -348,8 +348,8 @@ void ImplicitBoolConversionCheck::registerMatchers(MatchFinder *Finder) { implicitCastExpr().bind("implicitCastFromBool"), unless(hasParent(BitfieldConstruct)), // Check also for nested casts, for example: bool -> int -> float. - anyOf(hasParent(implicitCastExpr().bind("furtherImplicitCast")), - anything()), + optionally( + hasParent(implicitCastExpr().bind("furtherImplicitCast"))), unless(isInTemplateInstantiation()), unless(IsInCompilerGeneratedFunction))), this); diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/readability/InconsistentDeclarationParameterNameCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/readability/InconsistentDeclarationParameterNameCheck.cpp index 5cc22a22b1f5..10aa779117bb 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/readability/InconsistentDeclarationParameterNameCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/readability/InconsistentDeclarationParameterNameCheck.cpp @@ -131,8 +131,8 @@ findDifferingParamsInDeclaration(const FunctionDecl *ParameterSourceDeclaration, InconsistentDeclarationsContainer findInconsistentDeclarations(const FunctionDecl *OriginalDeclaration, - const FunctionDecl *ParameterSourceDeclaration, - SourceManager &SM, bool Strict) { + const FunctionDecl *ParameterSourceDeclaration, + SourceManager &SM, bool Strict) { InconsistentDeclarationsContainer InconsistentDeclarations; SourceLocation ParameterSourceLocation = ParameterSourceDeclaration->getLocation(); diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.h b/external/llvm-project/clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.h index 79787845de61..70a17889d244 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.h @@ -43,11 +43,12 @@ class MagicNumbersCheck : public ClangTidyCheck { bool isBitFieldWidth(const clang::ast_matchers::MatchFinder::MatchResult &, const FloatingLiteral &) const { - return false; + return false; } - bool isBitFieldWidth(const clang::ast_matchers::MatchFinder::MatchResult &Result, - const IntegerLiteral &Literal) const; + bool + isBitFieldWidth(const clang::ast_matchers::MatchFinder::MatchResult &Result, + const IntegerLiteral &Literal) const; bool isUserDefinedLiteral( const clang::ast_matchers::MatchFinder::MatchResult &Result, diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/readability/MakeMemberFunctionConstCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/readability/MakeMemberFunctionConstCheck.cpp index d42fcba70e81..85852c2c829a 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/readability/MakeMemberFunctionConstCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/readability/MakeMemberFunctionConstCheck.cpp @@ -17,6 +17,8 @@ using namespace clang::ast_matchers; namespace clang::tidy::readability { +namespace { + AST_MATCHER(CXXMethodDecl, isStatic) { return Node.isStatic(); } AST_MATCHER(CXXMethodDecl, hasTrivialBody) { return Node.hasTrivialBody(); } @@ -214,6 +216,8 @@ AST_MATCHER(CXXMethodDecl, usesThisAsConst) { return UsageOfThis.Usage == Const; } +} // namespace + void MakeMemberFunctionConstCheck::registerMatchers(MatchFinder *Finder) { Finder->addMatcher( traverse( diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/readability/MathMissingParenthesesCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/readability/MathMissingParenthesesCheck.cpp index 64ce94e3fc1d..1d5c6cca5a82 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/readability/MathMissingParenthesesCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/readability/MathMissingParenthesesCheck.cpp @@ -16,13 +16,15 @@ using namespace clang::ast_matchers; namespace clang::tidy::readability { void MathMissingParenthesesCheck::registerMatchers(MatchFinder *Finder) { - Finder->addMatcher(binaryOperator(unless(hasParent(binaryOperator())), - unless(isAssignmentOperator()), - unless(isComparisonOperator()), - unless(hasAnyOperatorName("&&", "||")), - hasDescendant(binaryOperator())) - .bind("binOp"), - this); + Finder->addMatcher( + binaryOperator( + unless(hasParent(binaryOperator(unless(isAssignmentOperator()), + unless(isComparisonOperator())))), + unless(isAssignmentOperator()), unless(isComparisonOperator()), + unless(hasAnyOperatorName("&&", "||")), + hasDescendant(binaryOperator())) + .bind("binOp"), + this); } static int getPrecedence(const BinaryOperator *BinOp) { @@ -88,10 +90,6 @@ static void addParantheses(const BinaryOperator *BinOp, void MathMissingParenthesesCheck::check( const MatchFinder::MatchResult &Result) { const auto *BinOp = Result.Nodes.getNodeAs("binOp"); - std::vector< - std::pair>> - Insertions; const SourceManager &SM = *Result.SourceManager; const clang::LangOptions &LO = Result.Context->getLangOpts(); addParantheses(BinOp, nullptr, this, SM, LO); diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/readability/NamespaceCommentCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/readability/NamespaceCommentCheck.cpp index 64dc941569a9..c04bf361c40c 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/readability/NamespaceCommentCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/readability/NamespaceCommentCheck.cpp @@ -27,11 +27,15 @@ NamespaceCommentCheck::NamespaceCommentCheck(StringRef Name, "namespace( +(((inline )|([a-zA-Z0-9_:]))+))?\\.? *(\\*/)?$", llvm::Regex::IgnoreCase), ShortNamespaceLines(Options.get("ShortNamespaceLines", 1U)), - SpacesBeforeComments(Options.get("SpacesBeforeComments", 1U)) {} + SpacesBeforeComments(Options.get("SpacesBeforeComments", 1U)), + AllowOmittingNamespaceComments( + Options.get("AllowOmittingNamespaceComments", false)) {} void NamespaceCommentCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) { Options.store(Opts, "ShortNamespaceLines", ShortNamespaceLines); Options.store(Opts, "SpacesBeforeComments", SpacesBeforeComments); + Options.store(Opts, "AllowOmittingNamespaceComments", + AllowOmittingNamespaceComments); } void NamespaceCommentCheck::registerMatchers(MatchFinder *Finder) { @@ -106,7 +110,7 @@ void NamespaceCommentCheck::check(const MatchFinder::MatchResult &Result) { // Currently for nested namespace (n1::n2::...) the AST matcher will match foo // then bar instead of a single match. So if we got a nested namespace we have // to skip the next ones. - for (const auto &EndOfNameLocation : Ends) { + for (const SourceLocation &EndOfNameLocation : Ends) { if (Sources.isBeforeInTranslationUnit(ND->getLocation(), EndOfNameLocation)) return; } @@ -140,6 +144,7 @@ void NamespaceCommentCheck::check(const MatchFinder::MatchResult &Result) { SourceRange OldCommentRange(AfterRBrace, AfterRBrace); std::string Message = "%0 not terminated with a closing comment"; + bool HasComment = false; // Try to find existing namespace closing comment on the same line. if (Tok.is(tok::comment) && NextTokenIsOnSameLine) { @@ -158,6 +163,8 @@ void NamespaceCommentCheck::check(const MatchFinder::MatchResult &Result) { return; } + HasComment = true; + // Otherwise we need to fix the comment. NeedLineBreak = Comment.starts_with("/*"); OldCommentRange = @@ -180,8 +187,13 @@ void NamespaceCommentCheck::check(const MatchFinder::MatchResult &Result) { } std::string NamespaceNameForDiag = - ND->isAnonymousNamespace() ? "anonymous namespace" - : ("namespace '" + *NamespaceNameAsWritten + "'"); + ND->isAnonymousNamespace() + ? "anonymous namespace" + : ("namespace '" + *NamespaceNameAsWritten + "'"); + + // If no namespace comment is allowed + if (!HasComment && AllowOmittingNamespaceComments) + return; std::string Fix(SpacesBeforeComments, ' '); Fix.append("// namespace"); diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/readability/NamespaceCommentCheck.h b/external/llvm-project/clang-tools-extra/clang-tidy/readability/NamespaceCommentCheck.h index 7607d37b1b2f..8edd77213f77 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/readability/NamespaceCommentCheck.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/readability/NamespaceCommentCheck.h @@ -34,6 +34,7 @@ class NamespaceCommentCheck : public ClangTidyCheck { llvm::Regex NamespaceCommentPattern; const unsigned ShortNamespaceLines; const unsigned SpacesBeforeComments; + const bool AllowOmittingNamespaceComments; llvm::SmallVector Ends; }; diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/readability/QualifiedAutoCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/readability/QualifiedAutoCheck.cpp index 00999ee8310c..91a08b9d8de6 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/readability/QualifiedAutoCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/readability/QualifiedAutoCheck.cpp @@ -50,10 +50,9 @@ std::optional findQualToken(const VarDecl *Decl, Qualifier Qual, if (FileRange.isInvalid()) return std::nullopt; - tok::TokenKind Tok = - Qual == Qualifier::Const - ? tok::kw_const - : Qual == Qualifier::Volatile ? tok::kw_volatile : tok::kw_restrict; + tok::TokenKind Tok = Qual == Qualifier::Const ? tok::kw_const + : Qual == Qualifier::Volatile ? tok::kw_volatile + : tok::kw_restrict; return utils::lexer::getQualifyingToken(Tok, FileRange, *Result.Context, *Result.SourceManager); diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp index 4c0812f0e679..d59b0312673b 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp @@ -186,6 +186,7 @@ static ClangTidyModuleRegistry::Add // This anchor is used to force the linker to link in the generated object file // and thus register the ReadabilityModule. +// NOLINTNEXTLINE(misc-use-internal-linkage) volatile int ReadabilityModuleAnchorSource = 0; } // namespace clang::tidy diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/readability/RedundantDeclarationCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/readability/RedundantDeclarationCheck.cpp index 7850a6f29995..053892dffc7b 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/readability/RedundantDeclarationCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/readability/RedundantDeclarationCheck.cpp @@ -15,10 +15,14 @@ using namespace clang::ast_matchers; namespace clang::tidy::readability { +namespace { + AST_MATCHER(FunctionDecl, doesDeclarationForceExternallyVisibleDefinition) { return Node.doesDeclarationForceExternallyVisibleDefinition(); } +} // namespace + RedundantDeclarationCheck::RedundantDeclarationCheck(StringRef Name, ClangTidyContext *Context) : ClangTidyCheck(Name, Context), diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/readability/RedundantFunctionPtrDereferenceCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/readability/RedundantFunctionPtrDereferenceCheck.cpp index 44053ebd21dc..a70719fd8a04 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/readability/RedundantFunctionPtrDereferenceCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/readability/RedundantFunctionPtrDereferenceCheck.cpp @@ -13,7 +13,8 @@ using namespace clang::ast_matchers; namespace clang::tidy::readability { -void RedundantFunctionPtrDereferenceCheck::registerMatchers(MatchFinder *Finder) { +void RedundantFunctionPtrDereferenceCheck::registerMatchers( + MatchFinder *Finder) { Finder->addMatcher( traverse(TK_AsIs, unaryOperator(hasOperatorName("*"), has(implicitCastExpr(hasCastKind( @@ -22,7 +23,8 @@ void RedundantFunctionPtrDereferenceCheck::registerMatchers(MatchFinder *Finder) this); } -void RedundantFunctionPtrDereferenceCheck::check(const MatchFinder::MatchResult &Result) { +void RedundantFunctionPtrDereferenceCheck::check( + const MatchFinder::MatchResult &Result) { const auto *Operator = Result.Nodes.getNodeAs("op"); diag(Operator->getOperatorLoc(), "redundant repeated dereference of function pointer") diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/readability/RedundantFunctionPtrDereferenceCheck.h b/external/llvm-project/clang-tools-extra/clang-tidy/readability/RedundantFunctionPtrDereferenceCheck.h index fdcf821bcf60..a04e9c165bc0 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/readability/RedundantFunctionPtrDereferenceCheck.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/readability/RedundantFunctionPtrDereferenceCheck.h @@ -19,7 +19,8 @@ namespace clang::tidy::readability { /// http://clang.llvm.org/extra/clang-tidy/checks/readability/redundant-function-ptr-dereference.html class RedundantFunctionPtrDereferenceCheck : public ClangTidyCheck { public: - RedundantFunctionPtrDereferenceCheck(StringRef Name, ClangTidyContext *Context) + RedundantFunctionPtrDereferenceCheck(StringRef Name, + ClangTidyContext *Context) : ClangTidyCheck(Name, Context) {} void registerMatchers(ast_matchers::MatchFinder *Finder) override; void check(const ast_matchers::MatchFinder::MatchResult &Result) override; diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/readability/RedundantInlineSpecifierCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/readability/RedundantInlineSpecifierCheck.cpp index 1693e5c5e9cd..969bf2d1add6 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/readability/RedundantInlineSpecifierCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/readability/RedundantInlineSpecifierCheck.cpp @@ -38,8 +38,8 @@ AST_POLYMORPHIC_MATCHER(isInlineSpecified, AST_POLYMORPHIC_MATCHER_P(isInternalLinkage, AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl), - bool, strictMode) { - if (!strictMode) + bool, StrictMode) { + if (!StrictMode) return false; if (const auto *FD = dyn_cast(&Node)) return FD->getStorageClass() == SC_Static || FD->isInAnonymousNamespace(); diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/readability/RedundantStringCStrCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/readability/RedundantStringCStrCheck.cpp index 57f13db07802..c90d1521e6b8 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/readability/RedundantStringCStrCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/readability/RedundantStringCStrCheck.cpp @@ -52,12 +52,11 @@ void RedundantStringCStrCheck::registerMatchers( const auto StringConstructorExpr = expr(anyOf( cxxConstructExpr(argumentCountIs(1), hasDeclaration(cxxMethodDecl(hasName("basic_string")))), - cxxConstructExpr( - argumentCountIs(2), - hasDeclaration(cxxMethodDecl(hasName("basic_string"))), - // If present, the second argument is the alloc object which must not - // be present explicitly. - hasArgument(1, cxxDefaultArgExpr())))); + cxxConstructExpr(argumentCountIs(2), + hasDeclaration(cxxMethodDecl(hasName("basic_string"))), + // If present, the second argument is the alloc object + // which must not be present explicitly. + hasArgument(1, cxxDefaultArgExpr())))); // Match string constructor. const auto StringViewConstructorExpr = cxxConstructExpr( @@ -105,8 +104,9 @@ void RedundantStringCStrCheck::registerMatchers( // Detect: 'dst.append(str.c_str())' -> 'dst.append(str)' Finder->addMatcher( - cxxMemberCallExpr(on(StringExpr), callee(decl(cxxMethodDecl(hasAnyName( - "append", "assign", "compare")))), + cxxMemberCallExpr(on(StringExpr), + callee(decl(cxxMethodDecl( + hasAnyName("append", "assign", "compare")))), argumentCountIs(1), hasArgument(0, StringCStrCallExpr)), this); diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/readability/SimplifySubscriptExprCheck.h b/external/llvm-project/clang-tools-extra/clang-tidy/readability/SimplifySubscriptExprCheck.h index 83bab16b2f7a..deffb09f5db2 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/readability/SimplifySubscriptExprCheck.h +++ b/external/llvm-project/clang-tools-extra/clang-tidy/readability/SimplifySubscriptExprCheck.h @@ -25,7 +25,7 @@ class SimplifySubscriptExprCheck : public ClangTidyCheck { } void registerMatchers(ast_matchers::MatchFinder *Finder) override; void check(const ast_matchers::MatchFinder::MatchResult &Result) override; - void storeOptions(ClangTidyOptions::OptionMap& Opts) override; + void storeOptions(ClangTidyOptions::OptionMap &Opts) override; std::optional getCheckTraversalKind() const override { return TK_IgnoreUnlessSpelledInSource; } diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp index 7c3aee29c146..4336c723bd7c 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp @@ -337,8 +337,7 @@ Allow empty enabled checks. This suppresses the "no checks enabled" error when disabling all of the checks. )"), - cl::init(false), - cl::cat(ClangTidyCategory)); + cl::init(false), cl::cat(ClangTidyCategory)); namespace clang::tidy { @@ -370,8 +369,8 @@ static void printStats(const ClangTidyStats &Stats) { } } -static std::unique_ptr createOptionsProvider( - llvm::IntrusiveRefCntPtr FS) { +static std::unique_ptr +createOptionsProvider(llvm::IntrusiveRefCntPtr FS) { ClangTidyGlobalOptions GlobalOptions; if (std::error_code Err = parseLineFilter(LineFilter, GlobalOptions)) { llvm::errs() << "Invalid LineFilter: " << Err.message() << "\n\nUsage:\n"; @@ -448,7 +447,7 @@ static std::unique_ptr createOptionsProvider( std::move(OverrideOptions), std::move(FS)); } -llvm::IntrusiveRefCntPtr +static llvm::IntrusiveRefCntPtr getVfsFromFile(const std::string &OverlayFile, llvm::IntrusiveRefCntPtr BaseFS) { llvm::ErrorOr> Buffer = diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/utils/IncludeSorter.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/utils/IncludeSorter.cpp index 83248e131948..db1ea1bb514f 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/utils/IncludeSorter.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/utils/IncludeSorter.cpp @@ -48,8 +48,7 @@ StringRef makeCanonicalName(StringRef Str, IncludeSorter::IncludeStyle Style) { if (StartIndex == StringRef::npos) { StartIndex = 0; } - return Canonical.substr( - 0, Canonical.find_first_of('+', StartIndex)); + return Canonical.substr(0, Canonical.find_first_of('+', StartIndex)); } return removeFirstSuffix( removeFirstSuffix(Str, {".cc", ".cpp", ".c", ".h", ".hpp"}), diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/utils/NamespaceAliaser.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/utils/NamespaceAliaser.cpp index 4703ce126981..22cf23fb2446 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/utils/NamespaceAliaser.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/utils/NamespaceAliaser.cpp @@ -16,15 +16,16 @@ namespace clang::tidy::utils { using namespace ast_matchers; +namespace { +AST_MATCHER_P(NamespaceAliasDecl, hasTargetNamespace, + ast_matchers::internal::Matcher, InnerMatcher) { + return InnerMatcher.matches(*Node.getNamespace(), Finder, Builder); +} +} // namespace NamespaceAliaser::NamespaceAliaser(const SourceManager &SourceMgr) : SourceMgr(SourceMgr) {} -AST_MATCHER_P(NamespaceAliasDecl, hasTargetNamespace, - ast_matchers::internal::Matcher, innerMatcher) { - return innerMatcher.matches(*Node.getNamespace(), Finder, Builder); -} - std::optional NamespaceAliaser::createAlias(ASTContext &Context, const Stmt &Statement, StringRef Namespace, diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp index a40433e38a04..7d84a4a9331b 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/utils/TransformerClangTidyCheck.cpp @@ -30,7 +30,7 @@ static void verifyRule(const RewriteRuleWith &Rule) { // If a string unintentionally containing '%' is passed as a diagnostic, Clang // will claim the string is ill-formed and assert-fail. This function escapes // such strings so they can be safely used in diagnostics. -std::string escapeForDiagnostic(std::string ToEscape) { +static std::string escapeForDiagnostic(std::string ToEscape) { // Optimize for the common case that the string does not contain `%` at the // cost of an extra scan over the string in the slow case. auto Pos = ToEscape.find('%'); diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/utils/TypeTraits.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/utils/TypeTraits.cpp index 68574d22d15f..44db0c2aed60 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/utils/TypeTraits.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/utils/TypeTraits.cpp @@ -41,8 +41,7 @@ std::optional isExpensiveToCopy(QualType Type, return std::nullopt; return !Type.isTriviallyCopyableType(Context) && !classHasTrivialCopyAndDestroy(Type) && - !hasDeletedCopyConstructor(Type) && - !Type->isObjCLifetimeType(); + !hasDeletedCopyConstructor(Type) && !Type->isObjCLifetimeType(); } bool recordIsTriviallyDefaultConstructible(const RecordDecl &RecordDecl, diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/zircon/TemporaryObjectsCheck.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/zircon/TemporaryObjectsCheck.cpp index bb2976081a69..bb2c71913193 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/zircon/TemporaryObjectsCheck.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/zircon/TemporaryObjectsCheck.cpp @@ -17,11 +17,15 @@ using namespace clang::ast_matchers; namespace clang::tidy::zircon { +namespace { + AST_MATCHER_P(CXXRecordDecl, matchesAnyName, ArrayRef, Names) { std::string QualifiedName = Node.getQualifiedNameAsString(); return llvm::is_contained(Names, QualifiedName); } +} // namespace + void TemporaryObjectsCheck::registerMatchers(MatchFinder *Finder) { // Matcher for default constructors. Finder->addMatcher( diff --git a/external/llvm-project/clang-tools-extra/clang-tidy/zircon/ZirconTidyModule.cpp b/external/llvm-project/clang-tools-extra/clang-tidy/zircon/ZirconTidyModule.cpp index 000680455d61..0eb5683a94e4 100644 --- a/external/llvm-project/clang-tools-extra/clang-tidy/zircon/ZirconTidyModule.cpp +++ b/external/llvm-project/clang-tools-extra/clang-tidy/zircon/ZirconTidyModule.cpp @@ -32,6 +32,6 @@ static ClangTidyModuleRegistry::Add // This anchor is used to force the linker to link in the generated object file // and thus register the ZirconModule. -volatile int ZirconModuleAnchorSource = 0; +volatile int ZirconModuleAnchorSource = 0; // NOLINT(misc-use-internal-linkage) } // namespace clang::tidy diff --git a/external/llvm-project/clang-tools-extra/clangd/IncludeCleaner.cpp b/external/llvm-project/clang-tools-extra/clangd/IncludeCleaner.cpp index dc4c8fc498b1..382ea3ffe342 100644 --- a/external/llvm-project/clang-tools-extra/clangd/IncludeCleaner.cpp +++ b/external/llvm-project/clang-tools-extra/clangd/IncludeCleaner.cpp @@ -117,7 +117,9 @@ bool mayConsiderUnused(const Inclusion &Inc, ParsedAST &AST, std::vector generateMissingIncludeDiagnostics( ParsedAST &AST, llvm::ArrayRef MissingIncludes, - llvm::StringRef Code, HeaderFilter IgnoreHeaders, const ThreadsafeFS &TFS) { + llvm::StringRef Code, HeaderFilter IgnoreHeaders, + HeaderFilter AngledHeaders, HeaderFilter QuotedHeaders, + const ThreadsafeFS &TFS) { std::vector Result; const SourceManager &SM = AST.getSourceManager(); const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID()); @@ -141,7 +143,18 @@ std::vector generateMissingIncludeDiagnostics( AST.getPreprocessor().getHeaderSearchInfo(), MainFile}); llvm::StringRef HeaderRef{Spelling}; + bool Angled = HeaderRef.starts_with("<"); + if (SymbolWithMissingInclude.Providers.front().kind() == + include_cleaner::Header::Kind::Physical) { + for (auto &Filter : Angled ? QuotedHeaders : AngledHeaders) { + if (Filter(ResolvedPath)) { + Angled = !Angled; + break; + } + } + } + // We might suggest insertion of an existing include in edge cases, e.g., // include is present in a PP-disabled region, or spelling of the header // turns out to be the same as one of the unresolved includes in the @@ -151,6 +164,11 @@ std::vector generateMissingIncludeDiagnostics( if (!Replacement.has_value()) continue; + if (Angled != (Spelling.front() == '<')) { + Spelling.front() = Angled ? '<' : '"'; + Spelling.back() = Angled ? '>' : '"'; + } + Diag &D = Result.emplace_back(); D.Message = llvm::formatv("No header providing \"{0}\" is directly included", @@ -481,18 +499,19 @@ bool isPreferredProvider(const Inclusion &Inc, return false; // no header provides the symbol } -std::vector -issueIncludeCleanerDiagnostics(ParsedAST &AST, llvm::StringRef Code, - const IncludeCleanerFindings &Findings, - const ThreadsafeFS &TFS, - HeaderFilter IgnoreHeaders) { +std::vector issueIncludeCleanerDiagnostics( + ParsedAST &AST, llvm::StringRef Code, + const IncludeCleanerFindings &Findings, const ThreadsafeFS &TFS, + HeaderFilter IgnoreHeaders, HeaderFilter AngledHeaders, + HeaderFilter QuotedHeaders) { trace::Span Tracer("IncludeCleaner::issueIncludeCleanerDiagnostics"); std::vector UnusedIncludes = generateUnusedIncludeDiagnostics( AST.tuPath(), Findings.UnusedIncludes, Code, IgnoreHeaders); std::optional RemoveAllUnused = removeAllUnusedIncludes(UnusedIncludes); std::vector MissingIncludeDiags = generateMissingIncludeDiagnostics( - AST, Findings.MissingIncludes, Code, IgnoreHeaders, TFS); + AST, Findings.MissingIncludes, Code, IgnoreHeaders, AngledHeaders, + QuotedHeaders, TFS); std::optional AddAllMissing = addAllMissingIncludes(MissingIncludeDiags); std::optional FixAll; diff --git a/external/llvm-project/clang-tools-extra/clangd/IncludeCleaner.h b/external/llvm-project/clang-tools-extra/clangd/IncludeCleaner.h index 3f6e3b2fd45b..9439eeed6a3e 100644 --- a/external/llvm-project/clang-tools-extra/clangd/IncludeCleaner.h +++ b/external/llvm-project/clang-tools-extra/clangd/IncludeCleaner.h @@ -57,11 +57,11 @@ IncludeCleanerFindings computeIncludeCleanerFindings(ParsedAST &AST, bool AnalyzeAngledIncludes = false); -std::vector -issueIncludeCleanerDiagnostics(ParsedAST &AST, llvm::StringRef Code, - const IncludeCleanerFindings &Findings, - const ThreadsafeFS &TFS, - HeaderFilter IgnoreHeader = {}); +std::vector issueIncludeCleanerDiagnostics( + ParsedAST &AST, llvm::StringRef Code, + const IncludeCleanerFindings &Findings, const ThreadsafeFS &TFS, + HeaderFilter IgnoreHeader = {}, HeaderFilter AngledHeaders = {}, + HeaderFilter QuotedHeaders = {}); /// Converts the clangd include representation to include-cleaner /// include representation. diff --git a/external/llvm-project/clang-tools-extra/clangd/InlayHints.cpp b/external/llvm-project/clang-tools-extra/clangd/InlayHints.cpp index bdab2b8a9f37..20a238612a7e 100644 --- a/external/llvm-project/clang-tools-extra/clangd/InlayHints.cpp +++ b/external/llvm-project/clang-tools-extra/clangd/InlayHints.cpp @@ -33,6 +33,7 @@ #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/Twine.h" +#include "llvm/ADT/identity.h" #include "llvm/Support/Casting.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/FormatVariadic.h" @@ -375,7 +376,11 @@ static FunctionProtoTypeLoc getPrototypeLoc(Expr *Fn) { } if (auto F = Target.getAs()) { - return F; + // In some edge cases the AST can contain a "trivial" FunctionProtoTypeLoc + // which has null parameters. Avoid these as they don't contain useful + // information. + if (llvm::all_of(F.getParams(), llvm::identity())) + return F; } return {}; diff --git a/external/llvm-project/clang-tools-extra/clangd/ModulesBuilder.cpp b/external/llvm-project/clang-tools-extra/clangd/ModulesBuilder.cpp index bf77f43bd28b..d88aa01aad05 100644 --- a/external/llvm-project/clang-tools-extra/clangd/ModulesBuilder.cpp +++ b/external/llvm-project/clang-tools-extra/clangd/ModulesBuilder.cpp @@ -430,10 +430,10 @@ class CachingProjectModules : public ProjectModules { /// Collect the directly and indirectly required module names for \param /// ModuleName in topological order. The \param ModuleName is guaranteed to /// be the last element in \param ModuleNames. -llvm::SmallVector getAllRequiredModules(PathRef RequiredSource, - CachingProjectModules &MDB, - StringRef ModuleName) { - llvm::SmallVector ModuleNames; +llvm::SmallVector getAllRequiredModules(PathRef RequiredSource, + CachingProjectModules &MDB, + StringRef ModuleName) { + llvm::SmallVector ModuleNames; llvm::StringSet<> ModuleNamesSet; auto VisitDeps = [&](StringRef ModuleName, auto Visitor) -> void { @@ -444,7 +444,7 @@ llvm::SmallVector getAllRequiredModules(PathRef RequiredSource, if (ModuleNamesSet.insert(RequiredModuleName).second) Visitor(RequiredModuleName, Visitor); - ModuleNames.push_back(ModuleName); + ModuleNames.push_back(ModuleName.str()); }; VisitDeps(ModuleName, VisitDeps); @@ -494,13 +494,13 @@ llvm::Error ModulesBuilder::ModulesBuilderImpl::getOrBuildModuleFile( // Get Required modules in topological order. auto ReqModuleNames = getAllRequiredModules(RequiredSource, MDB, ModuleName); for (llvm::StringRef ReqModuleName : ReqModuleNames) { - if (BuiltModuleFiles.isModuleUnitBuilt(ModuleName)) + if (BuiltModuleFiles.isModuleUnitBuilt(ReqModuleName)) continue; if (auto Cached = Cache.getModule(ReqModuleName)) { if (IsModuleFileUpToDate(Cached->getModuleFilePath(), BuiltModuleFiles, TFS.view(std::nullopt))) { - log("Reusing module {0} from {1}", ModuleName, + log("Reusing module {0} from {1}", ReqModuleName, Cached->getModuleFilePath()); BuiltModuleFiles.addModuleFile(std::move(Cached)); continue; @@ -508,14 +508,16 @@ llvm::Error ModulesBuilder::ModulesBuilderImpl::getOrBuildModuleFile( Cache.remove(ReqModuleName); } + std::string ReqFileName = + MDB.getSourceForModuleName(ReqModuleName, RequiredSource); llvm::Expected MF = buildModuleFile( - ModuleName, ModuleUnitFileName, getCDB(), TFS, BuiltModuleFiles); + ReqModuleName, ReqFileName, getCDB(), TFS, BuiltModuleFiles); if (llvm::Error Err = MF.takeError()) return Err; - log("Built module {0} to {1}", ModuleName, MF->getModuleFilePath()); + log("Built module {0} to {1}", ReqModuleName, MF->getModuleFilePath()); auto BuiltModuleFile = std::make_shared(std::move(*MF)); - Cache.add(ModuleName, BuiltModuleFile); + Cache.add(ReqModuleName, BuiltModuleFile); BuiltModuleFiles.addModuleFile(std::move(BuiltModuleFile)); } diff --git a/external/llvm-project/clang-tools-extra/clangd/ParsedAST.cpp b/external/llvm-project/clang-tools-extra/clangd/ParsedAST.cpp index 9e1f6bb97722..48896e5f4ff8 100644 --- a/external/llvm-project/clang-tools-extra/clangd/ParsedAST.cpp +++ b/external/llvm-project/clang-tools-extra/clangd/ParsedAST.cpp @@ -381,8 +381,9 @@ std::vector getIncludeCleanerDiags(ParsedAST &AST, llvm::StringRef Code, Findings.MissingIncludes.clear(); if (SuppressUnused) Findings.UnusedIncludes.clear(); - return issueIncludeCleanerDiagnostics(AST, Code, Findings, TFS, - Cfg.Diagnostics.Includes.IgnoreHeader); + return issueIncludeCleanerDiagnostics( + AST, Code, Findings, TFS, Cfg.Diagnostics.Includes.IgnoreHeader, + Cfg.Style.AngledHeaders, Cfg.Style.QuotedHeaders); } tidy::ClangTidyCheckFactories diff --git a/external/llvm-project/clang-tools-extra/clangd/refactor/Rename.cpp b/external/llvm-project/clang-tools-extra/clangd/refactor/Rename.cpp index d9b73b83e902..c56375b1a98d 100644 --- a/external/llvm-project/clang-tools-extra/clangd/refactor/Rename.cpp +++ b/external/llvm-project/clang-tools-extra/clangd/refactor/Rename.cpp @@ -1308,7 +1308,7 @@ getMappedRanges(ArrayRef Indexed, ArrayRef Lexed) { return std::nullopt; } // Fast check for the special subset case. - if (std::includes(Indexed.begin(), Indexed.end(), Lexed.begin(), Lexed.end())) + if (llvm::includes(Indexed, Lexed)) return Lexed.vec(); std::vector Best; diff --git a/external/llvm-project/clang-tools-extra/clangd/test/module_dependencies.test b/external/llvm-project/clang-tools-extra/clangd/test/module_dependencies.test new file mode 100644 index 000000000000..79306a73da43 --- /dev/null +++ b/external/llvm-project/clang-tools-extra/clangd/test/module_dependencies.test @@ -0,0 +1,95 @@ +# A smoke test to check that a simple dependency chain for modules can work. +# +# FIXME: The test fails on Windows; see comments on https://github.com/llvm/llvm-project/pull/142828 +# UNSUPPORTED: system-windows +# +# RUN: rm -fr %t +# RUN: mkdir -p %t +# RUN: split-file %s %t +# +# RUN: sed -e "s|DIR|%/t|g" %t/compile_commands.json.tmpl > %t/compile_commands.json.tmp +# RUN: sed -e "s|CLANG_CC|%clang|g" %t/compile_commands.json.tmp > %t/compile_commands.json +# RUN: sed -e "s|DIR|%/t|g" %t/definition.jsonrpc.tmpl > %t/definition.jsonrpc.tmp +# +# On Windows, we need the URI in didOpen to look like "uri":"file:///C:/..." +# (with the extra slash in the front), so we add it here. +# RUN: sed -E -e 's|"file://([A-Z]):/|"file:///\1:/|g' %/t/definition.jsonrpc.tmp > %/t/definition.jsonrpc +# +# RUN: clangd -experimental-modules-support -lit-test < %t/definition.jsonrpc \ +# RUN: | FileCheck -strict-whitespace %t/definition.jsonrpc + +#--- A-frag.cppm +export module A:frag; +export void printA() {} + +#--- A.cppm +export module A; +export import :frag; + +#--- Use.cpp +import A; +void foo() { + print +} + +#--- compile_commands.json.tmpl +[ + { + "directory": "DIR", + "command": "CLANG_CC -fprebuilt-module-path=DIR -std=c++20 -o DIR/main.cpp.o -c DIR/Use.cpp", + "file": "DIR/Use.cpp" + }, + { + "directory": "DIR", + "command": "CLANG_CC -std=c++20 DIR/A.cppm --precompile -o DIR/A.pcm", + "file": "DIR/A.cppm" + }, + { + "directory": "DIR", + "command": "CLANG_CC -std=c++20 DIR/A-frag.cppm --precompile -o DIR/A-frag.pcm", + "file": "DIR/A-frag.cppm" + } +] + +#--- definition.jsonrpc.tmpl +{ + "jsonrpc": "2.0", + "id": 0, + "method": "initialize", + "params": { + "processId": 123, + "rootPath": "clangd", + "capabilities": { + "textDocument": { + "completion": { + "completionItem": { + "snippetSupport": true + } + } + } + }, + "trace": "off" + } +} +--- +{ + "jsonrpc": "2.0", + "method": "textDocument/didOpen", + "params": { + "textDocument": { + "uri": "file://DIR/Use.cpp", + "languageId": "cpp", + "version": 1, + "text": "import A;\nvoid foo() {\n print\n}\n" + } + } +} + +# CHECK: "message"{{.*}}printA{{.*}}(fix available) + +--- +{"jsonrpc":"2.0","id":1,"method":"textDocument/completion","params":{"textDocument":{"uri":"file://DIR/Use.cpp"},"context":{"triggerKind":1},"position":{"line":2,"character":6}}} +--- +{"jsonrpc":"2.0","id":2,"method":"shutdown"} +--- +{"jsonrpc":"2.0","method":"exit"} diff --git a/external/llvm-project/clang-tools-extra/clangd/tool/ClangdMain.cpp b/external/llvm-project/clang-tools-extra/clangd/tool/ClangdMain.cpp index 4bd256d6be22..b11d194da04d 100644 --- a/external/llvm-project/clang-tools-extra/clangd/tool/ClangdMain.cpp +++ b/external/llvm-project/clang-tools-extra/clangd/tool/ClangdMain.cpp @@ -913,7 +913,6 @@ clangd accepts flags on the commandline, and in the CLANGD_FLAGS environment var if (!ResourceDir.empty()) Opts.ResourceDir = ResourceDir; Opts.BuildDynamicSymbolIndex = true; - std::vector> IdxStack; #if CLANGD_ENABLE_REMOTE if (RemoteIndexAddress.empty() != ProjectRoot.empty()) { llvm::errs() << "remote-index-address and project-path have to be " diff --git a/external/llvm-project/clang-tools-extra/clangd/unittests/HoverTests.cpp b/external/llvm-project/clang-tools-extra/clangd/unittests/HoverTests.cpp index 69f6df46c87c..775278ccf694 100644 --- a/external/llvm-project/clang-tools-extra/clangd/unittests/HoverTests.cpp +++ b/external/llvm-project/clang-tools-extra/clangd/unittests/HoverTests.cpp @@ -974,7 +974,7 @@ class Foo final {})cpp"; HI.Name = "abc"; HI.Kind = index::SymbolKind::Variable; HI.NamespaceScope = ""; - HI.Definition = "int abc = ()"; + HI.Definition = "int abc"; HI.Type = "int"; HI.AccessSpecifier = "public"; }}, diff --git a/external/llvm-project/clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp b/external/llvm-project/clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp index 0ee748c1ed2d..ec733cbe9c42 100644 --- a/external/llvm-project/clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp +++ b/external/llvm-project/clang-tools-extra/clangd/unittests/IncludeCleanerTests.cpp @@ -220,13 +220,16 @@ TEST(IncludeCleaner, ComputeMissingHeaders) { TEST(IncludeCleaner, GenerateMissingHeaderDiags) { Annotations MainFile(R"cpp( #include "a.h" +#include "angled_wrapper.h" #include "all.h" $insert_b[[]]#include "baz.h" #include "dir/c.h" $insert_d[[]]$insert_foo[[]]#include "fuzz.h" #include "header.h" -$insert_foobar[[]]#include -$insert_f[[]]$insert_vector[[]] +$insert_foobar[[]]$insert_quoted[[]]$insert_quoted2[[]]#include "quoted_wrapper.h" +$insert_angled[[]]#include +$insert_f[[]]#include +$insert_vector[[]] #define DEF(X) const Foo *X; #define BAZ(X) const X x @@ -237,6 +240,9 @@ TEST(IncludeCleaner, GenerateMissingHeaderDiags) { void foo() { $b[[b]](); + $angled[[angled]](); + $quoted[[quoted]](); + $quoted2[[quoted2]](); ns::$bar[[Bar]] bar; bar.d(); @@ -263,12 +269,22 @@ TEST(IncludeCleaner, GenerateMissingHeaderDiags) { TU.AdditionalFiles["a.h"] = guard("#include \"b.h\""); TU.AdditionalFiles["b.h"] = guard("void b();"); + TU.AdditionalFiles["angled_wrapper.h"] = guard("#include "); + TU.AdditionalFiles["angled.h"] = guard("void angled();"); + TU.ExtraArgs.push_back("-I" + testPath(".")); + + TU.AdditionalFiles["quoted_wrapper.h"] = guard("#include \"quoted.h\""); + TU.AdditionalFiles["quoted.h"] = guard("void quoted();"); + TU.AdditionalFiles["dir/c.h"] = guard("#include \"d.h\""); TU.AdditionalFiles["dir/d.h"] = guard("namespace ns { struct Bar { void d(); }; }"); TU.AdditionalFiles["system/e.h"] = guard("#include "); TU.AdditionalFiles["system/f.h"] = guard("void f();"); + TU.AdditionalFiles["system/quoted2_wrapper.h"] = + guard("#include "); + TU.AdditionalFiles["system/quoted2.h"] = guard("void quoted2();"); TU.ExtraArgs.push_back("-isystem" + testPath("system")); TU.AdditionalFiles["fuzz.h"] = guard("#include \"buzz.h\""); @@ -297,7 +313,15 @@ TEST(IncludeCleaner, GenerateMissingHeaderDiags) { Findings.UnusedIncludes.clear(); std::vector Diags = issueIncludeCleanerDiagnostics( AST, TU.Code, Findings, MockFS(), - {[](llvm::StringRef Header) { return Header.ends_with("buzz.h"); }}); + /*IgnoreHeaders=*/{[](llvm::StringRef Header) { + return Header.ends_with("buzz.h"); + }}, + /*AngledHeaders=*/{[](llvm::StringRef Header) { + return Header.contains("angled.h"); + }}, + /*QuotedHeaders=*/{[](llvm::StringRef Header) { + return Header.contains("quoted.h") || Header.contains("quoted2.h"); + }}); EXPECT_THAT( Diags, UnorderedElementsAre( @@ -306,6 +330,23 @@ TEST(IncludeCleaner, GenerateMissingHeaderDiags) { withFix({Fix(MainFile.range("insert_b"), "#include \"b.h\"\n", "#include \"b.h\""), FixMessage("add all missing includes")})), + AllOf(Diag(MainFile.range("angled"), + "No header providing \"angled\" is directly included"), + withFix({Fix(MainFile.range("insert_angled"), + "#include \n", "#include "), + FixMessage("add all missing includes")})), + AllOf( + Diag(MainFile.range("quoted"), + "No header providing \"quoted\" is directly included"), + withFix({Fix(MainFile.range("insert_quoted"), + "#include \"quoted.h\"\n", "#include \"quoted.h\""), + FixMessage("add all missing includes")})), + AllOf(Diag(MainFile.range("quoted2"), + "No header providing \"quoted2\" is directly included"), + withFix( + {Fix(MainFile.range("insert_quoted2"), + "#include \"quoted2.h\"\n", "#include \"quoted2.h\""), + FixMessage("add all missing includes")})), AllOf(Diag(MainFile.range("bar"), "No header providing \"ns::Bar\" is directly included"), withFix({Fix(MainFile.range("insert_d"), diff --git a/external/llvm-project/clang-tools-extra/clangd/unittests/InlayHintTests.cpp b/external/llvm-project/clang-tools-extra/clangd/unittests/InlayHintTests.cpp index c3331d20730f..e0cd955bb1c9 100644 --- a/external/llvm-project/clang-tools-extra/clangd/unittests/InlayHintTests.cpp +++ b/external/llvm-project/clang-tools-extra/clangd/unittests/InlayHintTests.cpp @@ -1011,11 +1011,16 @@ TEST(ParameterHints, FunctionPointer) { f3_t f3; using f4_t = void(__stdcall *)(int param); f4_t f4; + __attribute__((noreturn)) f4_t f5; void bar() { f1($f1[[42]]); f2($f2[[42]]); f3($f3[[42]]); f4($f4[[42]]); + // This one runs into an edge case in clang's type model + // and we can't extract the parameter name. But at least + // we shouldn't crash. + f5(42); } )cpp", ExpectedHint{"param: ", "f1"}, ExpectedHint{"param: ", "f2"}, diff --git a/external/llvm-project/clang-tools-extra/clangd/unittests/PrerequisiteModulesTest.cpp b/external/llvm-project/clang-tools-extra/clangd/unittests/PrerequisiteModulesTest.cpp index 03e65768c26a..ae2d98ce90d8 100644 --- a/external/llvm-project/clang-tools-extra/clangd/unittests/PrerequisiteModulesTest.cpp +++ b/external/llvm-project/clang-tools-extra/clangd/unittests/PrerequisiteModulesTest.cpp @@ -247,13 +247,11 @@ import Dep; ProjectModules->getRequiredModules(getFullPath("M.cppm")).empty()); // Set the mangler to filter out the invalid flag - ProjectModules->setCommandMangler( - [](tooling::CompileCommand &Command, PathRef) { - auto const It = - std::find(Command.CommandLine.begin(), Command.CommandLine.end(), - "-invalid-unknown-flag"); - Command.CommandLine.erase(It); - }); + ProjectModules->setCommandMangler([](tooling::CompileCommand &Command, + PathRef) { + auto const It = llvm::find(Command.CommandLine, "-invalid-unknown-flag"); + Command.CommandLine.erase(It); + }); // And now it returns a non-empty list of required modules since the // compilation succeeded diff --git a/external/llvm-project/clang-tools-extra/clangd/unittests/XRefsTests.cpp b/external/llvm-project/clang-tools-extra/clangd/unittests/XRefsTests.cpp index 1892f87c8e82..b04d6431f89f 100644 --- a/external/llvm-project/clang-tools-extra/clangd/unittests/XRefsTests.cpp +++ b/external/llvm-project/clang-tools-extra/clangd/unittests/XRefsTests.cpp @@ -2311,6 +2311,14 @@ TEST(FindReferences, WithinAST) { $(S::deleteObject)[[de^lete]] S; } }; + )cpp", + // Array designators + R"cpp( + const int $def[[F^oo]] = 0; + int Bar[] = { + [$(Bar)[[F^oo]]...$(Bar)[[Fo^o]] + 1] = 0, + [$(Bar)[[^Foo]] + 2] = 1 + }; )cpp"}; for (const char *Test : Tests) checkFindRefs(Test); diff --git a/external/llvm-project/clang-tools-extra/docs/ReleaseNotes.rst b/external/llvm-project/clang-tools-extra/docs/ReleaseNotes.rst index e0f81a032c38..19ccd1790e75 100644 --- a/external/llvm-project/clang-tools-extra/docs/ReleaseNotes.rst +++ b/external/llvm-project/clang-tools-extra/docs/ReleaseNotes.rst @@ -159,6 +159,10 @@ Changes in existing checks false positives on deleted constructors that cannot be used to construct objects, even if they have public or protected access. +- Added an option to :doc:`bugprone-multi-level-implicit-pointer-conversion + ` to + choose whether to enable the check in C code or not. + - Improved :doc:`bugprone-optional-value-conversion ` check to detect conversion in argument of ``std::make_optional``. @@ -187,6 +191,16 @@ Changes in existing checks ` check by fixing a false positive where ``strerror`` was flagged as MT-unsafe. +- Improved :doc:`google-readability-namespace-comments + ` check by adding + the option `AllowOmittingNamespaceComments` to accept if a namespace comment + is omitted entirely. + +- Improved :doc:`llvm-namespace-comment + ` check by adding the option + `AllowOmittingNamespaceComments` to accept if a namespace comment is omitted + entirely. + - Improved :doc:`misc-const-correctness ` check by adding the option `AllowedTypes`, that excludes specified types from const-correctness @@ -236,6 +250,13 @@ Changes in existing checks ` check to support math functions of different precisions. +- Improved :doc:`modernize-use-trailing-return-type + ` check by adding + support to modernize lambda signatures to use trailing return type and adding + two new options: `TransformFunctions` and `TransformLambdas` to control + whether function declarations and lambdas should be transformed by the check. + Fixed false positives when lambda was matched as a function in C++11 mode. + - Improved :doc:`performance-move-const-arg ` check by fixing false negatives on ternary operators calling ``std::move``. @@ -245,6 +266,15 @@ Changes in existing checks tolerating fix-it breaking compilation when functions is used as pointers to avoid matching usage of functions within the current compilation unit. +- Improved :doc:`readability-convert-member-functions-to-static + ` check by + fixing false positives on member functions with an explicit object parameter. + +- Improved :doc:`readability-math-missing-parentheses + ` check by fixing + false negatives where math expressions are the operand of assignment operators + or comparison operators. + - Improved :doc:`readability-qualified-auto ` check by adding the option `AllowedTypes`, that excludes specified types from adding qualifiers. diff --git a/external/llvm-project/clang-tools-extra/docs/clang-tidy/checks/bugprone/multi-level-implicit-pointer-conversion.rst b/external/llvm-project/clang-tools-extra/docs/clang-tidy/checks/bugprone/multi-level-implicit-pointer-conversion.rst index e6dc5c13aa02..14df6bd9ccea 100644 --- a/external/llvm-project/clang-tools-extra/docs/clang-tidy/checks/bugprone/multi-level-implicit-pointer-conversion.rst +++ b/external/llvm-project/clang-tools-extra/docs/clang-tidy/checks/bugprone/multi-level-implicit-pointer-conversion.rst @@ -42,3 +42,11 @@ Additionally, it is recommended that developers thoroughly check and verify the safety of the conversion before using an explicit cast. This extra level of caution can help catch potential issues early on in the development process, improving the overall reliability and maintainability of the code. + +Options +------- + +.. option:: EnableInC + + If `true`, enables the check in C code (it is always enabled in C++ code). + Default is `true`. diff --git a/external/llvm-project/clang-tools-extra/docs/clang-tidy/checks/bugprone/return-const-ref-from-parameter.rst b/external/llvm-project/clang-tools-extra/docs/clang-tidy/checks/bugprone/return-const-ref-from-parameter.rst index ba47399914de..325a0a2aa9cc 100644 --- a/external/llvm-project/clang-tools-extra/docs/clang-tidy/checks/bugprone/return-const-ref-from-parameter.rst +++ b/external/llvm-project/clang-tools-extra/docs/clang-tidy/checks/bugprone/return-const-ref-from-parameter.rst @@ -42,7 +42,7 @@ on the control flow of the function, an overload where all problematic This issue can also be resolved by adding ``[[clang::lifetimebound]]``. Clang enable ``-Wdangling`` warning by default which can detect mis-uses of the -annotated function. See `lifetimebound attribute `_ +annotated function. See `lifetimebound attribute `_ for details. .. code-block:: c++ diff --git a/external/llvm-project/clang-tools-extra/docs/clang-tidy/checks/llvm/namespace-comment.rst b/external/llvm-project/clang-tools-extra/docs/clang-tidy/checks/llvm/namespace-comment.rst index be90260be73a..23673c9b4cfd 100644 --- a/external/llvm-project/clang-tools-extra/docs/clang-tidy/checks/llvm/namespace-comment.rst +++ b/external/llvm-project/clang-tools-extra/docs/clang-tidy/checks/llvm/namespace-comment.rst @@ -39,3 +39,9 @@ Options An unsigned integer specifying the number of spaces before the comment closing a namespace definition. Default is `1U`. + +.. option:: AllowOmittingNamespaceComments + + When `true`, the check will accept if no namespace comment is present. + The check will only fail if the specified namespace comment is different + than expected. Default is `false`. diff --git a/external/llvm-project/clang-tools-extra/docs/clang-tidy/checks/modernize/deprecated-headers.rst b/external/llvm-project/clang-tools-extra/docs/clang-tidy/checks/modernize/deprecated-headers.rst index 298243fc3ced..6c35cd4e53d8 100644 --- a/external/llvm-project/clang-tools-extra/docs/clang-tidy/checks/modernize/deprecated-headers.rst +++ b/external/llvm-project/clang-tools-extra/docs/clang-tidy/checks/modernize/deprecated-headers.rst @@ -79,5 +79,5 @@ Options analyzed C++ source file is not included by any other C source files. Hence, to omit false-positives and wrong fixit-hints, we ignore emitting reports into header files. One can set this option to `true` if they know - that the header files in the project are only used by C++ source file. + that the header files in the project are only used by C++ source files. Default is `false`. diff --git a/external/llvm-project/clang-tools-extra/docs/clang-tidy/checks/modernize/use-trailing-return-type.rst b/external/llvm-project/clang-tools-extra/docs/clang-tidy/checks/modernize/use-trailing-return-type.rst index 0593a35326aa..2dac7cc76f41 100644 --- a/external/llvm-project/clang-tools-extra/docs/clang-tidy/checks/modernize/use-trailing-return-type.rst +++ b/external/llvm-project/clang-tools-extra/docs/clang-tidy/checks/modernize/use-trailing-return-type.rst @@ -3,7 +3,7 @@ modernize-use-trailing-return-type ================================== -Rewrites function signatures to use a trailing return type +Rewrites function and lambda signatures to use a trailing return type (introduced in C++11). This transformation is purely stylistic. The return type before the function name is replaced by ``auto`` and inserted after the function parameter list (and qualifiers). @@ -16,6 +16,7 @@ Example int f1(); inline int f2(int arg) noexcept; virtual float f3() const && = delete; + auto lambda = []() {}; transforms to: @@ -24,6 +25,7 @@ transforms to: auto f1() -> int; inline auto f2(int arg) -> int noexcept; virtual auto f3() const && -> float = delete; + auto lambda = []() -> void {}; Known Limitations ----------------- @@ -66,3 +68,25 @@ a careless rewrite would produce the following output: This code fails to compile because the S in the context of f refers to the equally named function parameter. Similarly, the S in the context of m refers to the equally named class member. The check can currently only detect and avoid a clash with a function parameter name. + +Options +------- + +.. option:: TransformFunctions + + When set to `true`, function declarations will be transformed to use trailing + return. Default is `true`. + +.. option:: TransformLambdas + + Controls how lambda expressions are transformed to use trailing + return type. Possible values are: + + * `all` - Transform all lambda expressions without an explicit return type + to use trailing return type. If type can not be deduced, ``auto`` will be + used since C++14 and generic message will be emitted otherwise. + * `all_except_auto` - Transform all lambda expressions except those whose return + type can not be deduced. + * `none` - Do not transform any lambda expressions. + + Default is `all`. diff --git a/external/llvm-project/clang-tools-extra/modularize/CoverageChecker.cpp b/external/llvm-project/clang-tools-extra/modularize/CoverageChecker.cpp index fe6711398ab7..1345a6ef8f48 100644 --- a/external/llvm-project/clang-tools-extra/modularize/CoverageChecker.cpp +++ b/external/llvm-project/clang-tools-extra/modularize/CoverageChecker.cpp @@ -329,10 +329,8 @@ bool CoverageChecker::collectFileSystemHeaders() { else { // Otherwise we only look at the sub-trees specified by the // include paths. - for (std::vector::const_iterator I = IncludePaths.begin(), - E = IncludePaths.end(); - I != E; ++I) { - if (!collectFileSystemHeaders(*I)) + for (const std::string &IncludePath : IncludePaths) { + if (!collectFileSystemHeaders(IncludePath)) return false; } } diff --git a/external/llvm-project/clang-tools-extra/modularize/Modularize.cpp b/external/llvm-project/clang-tools-extra/modularize/Modularize.cpp index 7f8a19280b11..2a90c5e3f678 100644 --- a/external/llvm-project/clang-tools-extra/modularize/Modularize.cpp +++ b/external/llvm-project/clang-tools-extra/modularize/Modularize.cpp @@ -339,8 +339,8 @@ static std::string findInputFile(const CommandLineArguments &CLArgs) { llvm::opt::Visibility VisibilityMask(options::CC1Option); unsigned MissingArgIndex, MissingArgCount; SmallVector Argv; - for (auto I = CLArgs.begin(), E = CLArgs.end(); I != E; ++I) - Argv.push_back(I->c_str()); + for (const std::string &CLArg : CLArgs) + Argv.push_back(CLArg.c_str()); InputArgList Args = getDriverOptTable().ParseArgs( Argv, MissingArgIndex, MissingArgCount, VisibilityMask); std::vector Inputs = Args.getAllArgValues(OPT_INPUT); diff --git a/external/llvm-project/clang-tools-extra/modularize/ModularizeUtilities.cpp b/external/llvm-project/clang-tools-extra/modularize/ModularizeUtilities.cpp index 9ad1731915a8..8a24f21d658d 100644 --- a/external/llvm-project/clang-tools-extra/modularize/ModularizeUtilities.cpp +++ b/external/llvm-project/clang-tools-extra/modularize/ModularizeUtilities.cpp @@ -69,8 +69,7 @@ ModularizeUtilities *ModularizeUtilities::createModularizeUtilities( // Load all header lists and dependencies. std::error_code ModularizeUtilities::loadAllHeaderListsAndDependencies() { // For each input file. - for (auto I = InputFilePaths.begin(), E = InputFilePaths.end(); I != E; ++I) { - llvm::StringRef InputPath = *I; + for (llvm::StringRef InputPath : InputFilePaths) { // If it's a module map. if (InputPath.ends_with(".modulemap")) { // Load the module map. diff --git a/external/llvm-project/clang-tools-extra/test/clang-doc/DR-141990.cpp b/external/llvm-project/clang-tools-extra/test/clang-doc/DR-141990.cpp new file mode 100644 index 000000000000..019afb0654c2 --- /dev/null +++ b/external/llvm-project/clang-tools-extra/test/clang-doc/DR-141990.cpp @@ -0,0 +1,18 @@ +// RUN: rm -rf %t && mkdir -p %t +// RUN: clang-doc -output=%t %s 2>&1 | FileCheck %s --implicit-check-not="{{warning|error}}" + +// COM: This case triggered an assertion before #141990: +// COM: clang-doc: llvm-project/clang/lib/AST/Decl.cpp:2985: +// COM: Expr *clang::ParmVarDecl::getDefaultArg(): Assertion `!hasUninstantiatedDefaultArg() +// COM: && "Default argument is not yet instantiated!"' failed. + +template +class c; +int e; + +template +class c { +public: + void f(int n = e); +}; +class B : c<> {}; diff --git a/external/llvm-project/clang-tools-extra/test/clang-doc/invalid-options.cpp b/external/llvm-project/clang-tools-extra/test/clang-doc/invalid-options.cpp index c8a4cef8364e..15e098ad4c78 100644 --- a/external/llvm-project/clang-tools-extra/test/clang-doc/invalid-options.cpp +++ b/external/llvm-project/clang-tools-extra/test/clang-doc/invalid-options.cpp @@ -2,7 +2,7 @@ // RUN: rm -rf %t && touch %t // RUN: not clang-doc %s -output=%t/subdir 2>&1 | FileCheck %s --check-prefix=OUTPUT-FAIL // OUTPUT-FAIL: clang-doc error: -// OUTPUT-FAIL: {{(Not a directory|no such file or directory)}} +// OUTPUT-FAIL-SAME: failed to create directory. /// Invalid format option. // RUN: rm -rf %t && mkdir %t && touch %t/file diff --git a/external/llvm-project/clang-tools-extra/test/clang-doc/json/class-template.cpp b/external/llvm-project/clang-tools-extra/test/clang-doc/json/class-template.cpp new file mode 100644 index 000000000000..e3ca086d1d9a --- /dev/null +++ b/external/llvm-project/clang-tools-extra/test/clang-doc/json/class-template.cpp @@ -0,0 +1,29 @@ +// RUN: rm -rf %t && mkdir -p %t +// RUN: clang-doc --output=%t --format=json --executor=standalone %s +// RUN: FileCheck %s < %t/GlobalNamespace/MyClass.json + +template struct MyClass { + T MemberTemplate; + T method(T Param); +}; + +// CHECK: "Name": "MyClass", +// CHECK: "Name": "method", +// CHECK: "Params": [ +// CHECK-NEXT: { +// CHECK-NEXT: "Name": "Param", +// CHECK-NEXT: "Type": "T" +// CHECK-NEXT: } +// CHECK-NEXT: ], +// CHECK-NEXT: "ReturnType": { +// CHECK-NEXT: "IsBuiltIn": false, +// CHECK-NEXT: "IsTemplate": false, +// CHECK-NEXT: "Name": "T", +// CHECK-NEXT: "QualName": "T" +// CHECK-NEXT: "USR": "0000000000000000000000000000000000000000" +// CHECK: "Name": "MemberTemplate", +// CHECK: "Type": "T" +// CHECK: "Template": { +// CHECK-NEXT: "Parameters": [ +// CHECK-NEXT: "typename T" +// CHECK-NEXT: ] diff --git a/external/llvm-project/clang-tools-extra/test/clang-doc/json/class.cpp b/external/llvm-project/clang-tools-extra/test/clang-doc/json/class.cpp new file mode 100644 index 000000000000..9ae1f14e2d2a --- /dev/null +++ b/external/llvm-project/clang-tools-extra/test/clang-doc/json/class.cpp @@ -0,0 +1,193 @@ +// RUN: rm -rf %t && mkdir -p %t +// RUN: clang-doc --output=%t --format=json --executor=standalone %s +// RUN: FileCheck %s < %t/GlobalNamespace/MyClass.json + +struct Foo; + +// This is a nice class. +// It has some nice methods and fields. +// @brief This is a brief description. +struct MyClass { + int PublicField; + + int myMethod(int MyParam); + static void staticMethod(); + const int& getConst(); + + enum Color { + RED, + GREEN, + BLUE = 5 + }; + + typedef int MyTypedef; + + class NestedClass; +protected: + int protectedMethod(); + + int ProtectedField; +}; + +// CHECK: { +// CHECK-NEXT: "Description": [ +// CHECK-NEXT: { +// CHECK-NEXT: "FullComment": { +// CHECK-NEXT: "Children": [ +// CHECK-NEXT: { +// CHECK-NEXT: "ParagraphComment": { +// CHECK-NEXT: "Children": [ +// CHECK-NEXT: { +// CHECK-NEXT: "TextComment": " This is a nice class." +// CHECK-NEXT: }, +// CHECK-NEXT: { +// CHECK-NEXT: "TextComment": " It has some nice methods and fields." +// CHECK-NEXT: }, +// CHECK-NEXT: { +// CHECK-NEXT: "TextComment": "" +// CHECK-NEXT: } +// CHECK-NEXT: ] +// CHECK: { +// CHECK-NEXT: "BlockCommandComment": { +// CHECK-NEXT: "Children": [ +// CHECK-NEXT: { +// CHECK-NEXT: "ParagraphComment": { +// CHECK-NEXT: "Children": [ +// CHECK-NEXT: { +// CHECK-NEXT: "TextComment": " This is a brief description." +// CHECK-NEXT: } +// CHECK: "Command": "brief" +// CHECK: "Enums": [ +// CHECK-NEXT: { +// CHECK-NEXT: "Location": { +// CHECK-NEXT: "Filename": "{{.*}}class.cpp", +// CHECK-NEXT: "LineNumber": 17 +// CHECK-NEXT: }, +// CHECK-NEXT: "Members": [ +// CHECK-NEXT: { +// CHECK-NEXT: "Name": "RED", +// CHECK-NEXT: "Value": "0" +// CHECK-NEXT: }, +// CHECK-NEXT: { +// CHECK-NEXT: "Name": "GREEN", +// CHECK-NEXT: "Value": "1" +// CHECK-NEXT: }, +// CHECK-NEXT: { +// CHECK-NEXT: "Name": "BLUE", +// CHECK-NEXT: "ValueExpr": "5" +// CHECK-NEXT: } +// CHECK-NEXT: ], +// CHECK-NEXT: "Name": "Color", +// CHECK-NEXT: "Namespace": [ +// CHECK-NEXT: "MyClass", +// CHECK-NEXT: "GlobalNamespace" +// CHECK-NEXT: ], +// CHECK-NEXT: "Scoped": false, +// CHECK-NEXT: "USR": "{{[0-9A-F]*}}" +// CHECK-NEXT: } +// CHECK-NEXT: ], +// COM: FIXME: FullName is not emitted correctly. +// CHECK-NEXT: "FullName": "", +// CHECK-NEXT: "IsTypedef": false, +// CHECK-NEXT: "Location": { +// CHECK-NEXT: "Filename": "{{.*}}class.cpp", +// CHECK-NEXT: "LineNumber": 10 +// CHECK-NEXT: }, +// CHECK-NEXT: "Name": "MyClass", +// CHECK-NEXT: "Namespace": [ +// CHECK-NEXT: "GlobalNamespace" +// CHECK-NEXT: ], +// CHECK-NEXT: "Path": "GlobalNamespace", +// CHECK-NEXT: "ProtectedFunctions": [ +// CHECK-NEXT: { +// CHECK-NEXT: "IsStatic": false, +// CHECK-NEXT: "Name": "protectedMethod", +// CHECK-NEXT: "Namespace": [ +// CHECK-NEXT: "MyClass", +// CHECK-NEXT: "GlobalNamespace" +// CHECK-NEXT: ], +// CHECK-NEXT: "ReturnType": { +// CHECK-NEXT: "IsBuiltIn": false, +// CHECK-NEXT: "IsTemplate": false, +// CHECK-NEXT: "Name": "int", +// CHECK-NEXT: "QualName": "int", +// CHECK-NEXT: "USR": "{{[0-9A-F]*}}" +// CHECK-NEXT: }, +// CHECK-NEXT: "USR": "{{[0-9A-F]*}}" +// CHECK-NEXT: } +// CHECK-NEXT: ], +// CHECK-NEXT: "ProtectedMembers": [ +// CHECK-NEXT: { +// CHECK-NEXT: "Name": "ProtectedField", +// CHECK-NEXT: "Type": "int" +// CHECK-NEXT: } +// CHECK-NEXT: ], +// CHECK-NEXT: "PublicFunctions": [ +// CHECK-NEXT: { +// CHECK-NEXT: "IsStatic": false, +// CHECK-NEXT: "Name": "myMethod", +// CHECK-NEXT: "Namespace": [ +// CHECK-NEXT: "MyClass", +// CHECK-NEXT: "GlobalNamespace" +// CHECK-NEXT: ], +// CHECK-NEXT: "Params": [ +// CHECK-NEXT: { +// CHECK-NEXT: "Name": "MyParam", +// CHECK-NEXT: "Type": "int" +// CHECK-NEXT: } +// CHECK-NEXT: ], +// CHECK-NEXT: "ReturnType": { +// CHECK-NEXT: "IsBuiltIn": false, +// CHECK-NEXT: "IsTemplate": false, +// CHECK-NEXT: "Name": "int", +// CHECK-NEXT: "QualName": "int", +// CHECK-NEXT: "USR": "{{[0-9A-F]*}}" +// CHECK-NEXT: }, +// CHECK-NEXT: "USR": "{{[0-9A-F]*}}" +// CHECK-NEXT: }, +// CHECK: "IsStatic": true, +// CHECK: "Name": "getConst", +// CHECK: "ReturnType": { +// CHECK-NEXT: "IsBuiltIn": false, +// CHECK-NEXT: "IsTemplate": false, +// CHECK-NEXT: "Name": "const int &", +// CHECK-NEXT: "QualName": "const int &", +// CHECK-NEXT: "USR": "{{[0-9A-F]*}}" +// CHECK-NEXT: }, +// CHECK: "PublicMembers": [ +// CHECK-NEXT: { +// CHECK-NEXT: "Name": "PublicField", +// CHECK-NEXT: "Type": "int" +// CHECK-NEXT: } +// CHECK-NEXT: ], +// CHECK-NEXT: "Records": [ +// CHECK-NEXT: { +// CHECK-NEXT: "Name": "NestedClass", +// CHECK-NEXT: "Path": "GlobalNamespace{{[\/]+}}MyClass", +// CHECK-NEXT: "QualName": "NestedClass", +// CHECK-NEXT: "USR": "{{[0-9A-F]*}}" +// CHECK-NEXT: } +// CHECK-NEXT: ] +// CHECK-NEXT: "TagType": "struct", +// CHECK-NEXT: "Typedefs": [ +// CHECK-NEXT: { +// CHECK-NEXT: "IsUsing": false, +// CHECK-NEXT: "Location": { +// CHECK-NEXT: "Filename": "{{.*}}class.cpp", +// CHECK-NEXT: "LineNumber": 23 +// CHECK-NEXT: }, +// CHECK-NEXT: "Name": "MyTypedef", +// CHECK-NEXT: "Namespace": [ +// CHECK-NEXT: "MyClass", +// CHECK-NEXT: "GlobalNamespace" +// CHECK-NEXT: ], +// CHECK-NEXT: "TypeDeclaration": "", +// CHECK-NEXT: "USR": "{{[0-9A-F]*}}", +// CHECK-NEXT: "Underlying": { +// CHECK-NEXT: "IsBuiltIn": false, +// CHECK-NEXT: "IsTemplate": false, +// CHECK-NEXT: "Name": "int", +// CHECK-NEXT: "QualName": "int", +// CHECK-NEXT: "USR": "0000000000000000000000000000000000000000" +// CHECK: "USR": "{{[0-9A-F]*}}" +// CHECK-NEXT: } diff --git a/external/llvm-project/clang-tools-extra/test/clang-doc/json/function-specifiers.cpp b/external/llvm-project/clang-tools-extra/test/clang-doc/json/function-specifiers.cpp new file mode 100644 index 000000000000..7005fb7b3e66 --- /dev/null +++ b/external/llvm-project/clang-tools-extra/test/clang-doc/json/function-specifiers.cpp @@ -0,0 +1,25 @@ +// RUN: rm -rf %t && mkdir -p %t +// RUN: clang-doc --output=%t --format=json --executor=standalone %s +// RUN: FileCheck %s < %t/GlobalNamespace/index.json + +static void myFunction() {} + +void noExceptFunction() noexcept {} + +inline void inlineFunction() {} + +extern void externFunction() {} + +constexpr void constexprFunction() {} + +// CHECK: "Functions": [ +// CHECK-NEXT: { +// CHECK: "IsStatic": true, +// COM: FIXME: Emit ExceptionSpecificationType +// CHECK-NOT: "ExceptionSpecifcation" : "noexcept", +// COM: FIXME: Emit inline +// CHECK-NOT: "IsInline": true, +// COM: FIXME: Emit extern +// CHECK-NOT: "IsExtern": true, +// COM: FIXME: Emit constexpr +// CHECK-NOT: "IsConstexpr": true, diff --git a/external/llvm-project/clang-tools-extra/test/clang-doc/json/method-template.cpp b/external/llvm-project/clang-tools-extra/test/clang-doc/json/method-template.cpp new file mode 100644 index 000000000000..c51a2706d1c2 --- /dev/null +++ b/external/llvm-project/clang-tools-extra/test/clang-doc/json/method-template.cpp @@ -0,0 +1,40 @@ +// RUN: rm -rf %t && mkdir -p %t +// RUN: clang-doc --output=%t --format=json --executor=standalone %s +// RUN: FileCheck %s < %t/GlobalNamespace/MyClass.json + +struct MyClass { + template T methodTemplate(T param) { + } +}; + +// CHECK: "PublicFunctions": [ +// CHECK-NEXT: { +// CHECK-NEXT: "IsStatic": false, +// CHECK-NEXT: "Location": { +// CHECK-NEXT: "Filename": "{{.*}}method-template.cpp", +// CHECK-NEXT: "LineNumber": 6 +// CHECK-NEXT: }, +// CHECK-NEXT: "Name": "methodTemplate", +// CHECK-NEXT: "Namespace": [ +// CHECK-NEXT: "MyClass", +// CHECK-NEXT: "GlobalNamespace" +// CHECK-NEXT: ], +// CHECK-NEXT: "Params": [ +// CHECK-NEXT: { +// CHECK-NEXT: "Name": "param", +// CHECK-NEXT: "Type": "T" +// CHECK-NEXT: } +// CHECK-NEXT: ], +// CHECK-NEXT: "ReturnType": { +// CHECK-NEXT: "IsBuiltIn": false, +// CHECK-NEXT: "IsTemplate": false, +// CHECK-NEXT: "Name": "T", +// CHECK-NEXT: "QualName": "T", +// CHECK-NEXT: "USR": "0000000000000000000000000000000000000000" +// CHECK-NEXT: }, +// CHECK-NEXT: "Template": { +// CHECK-NEXT: "Parameters": [ +// CHECK-NEXT: "class T" +// CHECK-NEXT: ] +// CHECK-NEXT: }, +// CHECK-NEXT: "USR": "{{[0-9A-F]*}}" diff --git a/external/llvm-project/clang-tools-extra/test/clang-doc/json/namespace.cpp b/external/llvm-project/clang-tools-extra/test/clang-doc/json/namespace.cpp new file mode 100644 index 000000000000..928864be1feb --- /dev/null +++ b/external/llvm-project/clang-tools-extra/test/clang-doc/json/namespace.cpp @@ -0,0 +1,107 @@ +// RUN: rm -rf %t && mkdir -p %t +// RUN: clang-doc --output=%t --format=json --executor=standalone %s +// RUN: FileCheck %s < %t/GlobalNamespace/index.json + +class MyClass {}; + +void myFunction(int Param); + +namespace NestedNamespace { +} // namespace NestedNamespace + +// FIXME: Global variables are not mapped or serialized. +static int Global; + +enum Color { + RED, + GREEN, + BLUE = 5 +}; + +typedef int MyTypedef; + +// CHECK: { +// CHECK-NEXT: "Enums": [ +// CHECK-NEXT: { +// CHECK-NEXT: "Location": { +// CHECK-NEXT: "Filename": "{{.*}}namespace.cpp", +// CHECK-NEXT: "LineNumber": 15 +// CHECK-NEXT: }, +// CHECK-NEXT: "Members": [ +// CHECK-NEXT: { +// CHECK-NEXT: "Name": "RED", +// CHECK-NEXT: "Value": "0" +// CHECK-NEXT: }, +// CHECK-NEXT: { +// CHECK-NEXT: "Name": "GREEN", +// CHECK-NEXT: "Value": "1" +// CHECK-NEXT: }, +// CHECK-NEXT: { +// CHECK-NEXT: "Name": "BLUE", +// CHECK-NEXT: "ValueExpr": "5" +// CHECK-NEXT: } +// CHECK-NEXT: ], +// CHECK-NEXT: "Name": "Color", +// CHECK-NEXT: "Scoped": false, +// CHECK-NEXT: "USR": "{{[0-9A-F]*}}" +// CHECK-NEXT: } +// CHECK-NEXT: ], +// CHECK-NEXT: "Functions": [ +// CHECK-NEXT: { +// CHECK-NEXT: "IsStatic": false, +// CHECK-NEXT: "Name": "myFunction", +// CHECK-NEXT: "Params": [ +// CHECK-NEXT: { +// CHECK-NEXT: "Name": "Param", +// CHECK-NEXT: "Type": "int" +// CHECK-NEXT: } +// CHECK-NEXT: ], +// CHECK-NEXT: "ReturnType": { +// CHECK-NEXT: "IsBuiltIn": false, +// CHECK-NEXT: "IsTemplate": false, +// CHECK-NEXT: "Name": "void", +// CHECK-NEXT: "QualName": "void", +// CHECK-NEXT: "USR": "0000000000000000000000000000000000000000" +// CHECK-NEXT: }, +// CHECK-NEXT: "USR": "{{[0-9A-F]*}}" +// CHECK-NEXT: } +// CHECK-NEXT: ], +// CHECK-NEXT: "Name": "", +// CHECK-NEXT: "Namespaces": [ +// CHECK-NEXT: { +// CHECK-NEXT: "Name": "NestedNamespace", +// CHECK-NEXT: "Path": "", +// CHECK-NEXT: "QualName": "NestedNamespace", +// CHECK-NEXT: "USR": "{{[0-9A-F]*}}" +// CHECK-NEXT: } +// CHECK-NEXT: ], +// CHECK-NEXT: "Records": [ +// CHECK-NEXT: { +// CHECK-NEXT: "Name": "MyClass", +// CHECK-NEXT: "Path": "GlobalNamespace", +// CHECK-NEXT: "QualName": "MyClass", +// CHECK-NEXT: "USR": "{{[0-9A-F]*}}" +// CHECK-NEXT: } +// CHECK-NEXT: ], +// CHECK-NEXT: "Typedefs": [ +// CHECK-NEXT: { +// CHECK-NEXT: "IsUsing": false, +// CHECK-NEXT: "Location": { +// CHECK-NEXT: "Filename": "{{.*}}namespace.cpp", +// CHECK-NEXT: "LineNumber": 21 +// CHECK-NEXT: }, +// CHECK-NEXT: "Name": "MyTypedef", +// CHECK-NEXT: "TypeDeclaration": "", +// CHECK-NEXT: "USR": "{{[0-9A-F]*}}", +// CHECK-NEXT: "Underlying": { +// CHECK-NEXT: "IsBuiltIn": false, +// CHECK-NEXT: "IsTemplate": false, +// CHECK-NEXT: "Name": "int", +// CHECK-NEXT: "QualName": "int", +// CHECK-NEXT: "USR": "0000000000000000000000000000000000000000" +// CHECK-NEXT: } +// CHECK-NEXT: } +// CHECK-NEXT: ], +// CHECK-NEXT: "USR": "0000000000000000000000000000000000000000" +// CHECK-NOT: "Variables": [ +// CHECK-NEXT: } diff --git a/external/llvm-project/clang-tools-extra/test/clang-doc/mustache-index.cpp b/external/llvm-project/clang-tools-extra/test/clang-doc/mustache-index.cpp new file mode 100644 index 000000000000..cad4cc8b6931 --- /dev/null +++ b/external/llvm-project/clang-tools-extra/test/clang-doc/mustache-index.cpp @@ -0,0 +1,75 @@ +// RUN: rm -rf %t && mkdir -p %t +// RUN: clang-doc --format=mustache --output=%t --executor=standalone %s +// RUN: FileCheck %s < %t/GlobalNamespace/index.html + +enum Color { + RED, + BLUE, + GREEN +}; + +class Foo; + +// CHECK: +// CHECK-NEXT:
    +// CHECK-NEXT: +// CHECK-NEXT:
+// CHECK: +// CHECK-NEXT:
    +// CHECK-NEXT: +// CHECK-NEXT:
+ +// CHECK:
+// CHECK-NEXT:

Enumerations

+// CHECK-NEXT:
+// CHECK-NEXT:
+// CHECK-NEXT:
+// CHECK-NEXT:
+// CHECK-NEXT:                      
+// CHECK-NEXT:                          enum Color
+// CHECK-NEXT:                      
+// CHECK-NEXT:                  
+// CHECK-NEXT:
+// CHECK-NEXT: +// CHECK-NEXT: +// CHECK-NEXT: +// CHECK-NEXT: +// CHECK-NEXT: +// CHECK: +// CHECK-NEXT: +// CHECK-NEXT: +// CHECK-NEXT: +// CHECK: +// CHECK-NEXT: +// CHECK-NEXT: +// CHECK-NEXT: +// CHECK: +// CHECK-NEXT: +// CHECK-NEXT: +// CHECK-NEXT: +// CHECK: +// CHECK-NEXT: +// CHECK-NEXT:
NameValue
RED0
BLUE1
GREEN2
+// CHECK-NEXT:
+// CHECK-NEXT: Defined at line 5 of file {{.*}}mustache-index.cpp +// CHECK-NEXT:
+// CHECK-NEXT:
+// CHECK-NEXT:
+// CHECK-NEXT:
+ +// CHECK:
+// CHECK-NEXT:

Inner Classes

+// CHECK-NEXT:
    +// CHECK-NEXT:
  • +// CHECK-NEXT:
    class Foo
    +// CHECK-NEXT:
  • +// CHECK-NEXT:
+// CHECK-NEXT:
diff --git a/external/llvm-project/clang-tools-extra/test/clang-doc/mustache-separate-namespace.cpp b/external/llvm-project/clang-tools-extra/test/clang-doc/mustache-separate-namespace.cpp new file mode 100644 index 000000000000..ec29b2449169 --- /dev/null +++ b/external/llvm-project/clang-tools-extra/test/clang-doc/mustache-separate-namespace.cpp @@ -0,0 +1,13 @@ +// RUN: rm -rf %t && mkdir -p %t +// RUN: clang-doc --format=mustache --output=%t --executor=standalone %s +// RUN: FileCheck %s < %t/MyNamespace/index.html + +namespace MyNamespace { + class Foo; +} + +// CHECK:
    +// CHECK-NEXT:
  • +// CHECK-NEXT:
    class Foo
    +// CHECK-NEXT:
  • +// CHECK-NEXT:
diff --git a/external/llvm-project/clang-tools-extra/test/clang-doc/templates.cpp b/external/llvm-project/clang-tools-extra/test/clang-doc/templates.cpp index 426a0b16befd..abe03a7d2d0e 100644 --- a/external/llvm-project/clang-tools-extra/test/clang-doc/templates.cpp +++ b/external/llvm-project/clang-tools-extra/test/clang-doc/templates.cpp @@ -112,22 +112,22 @@ tuple func_with_tuple_param(tuple t) { return t; // YAML-NEXT: - USR: '{{([0-9A-F]{40})}}' // YAML-NEXT: Name: 'func_with_tuple_param' // YAML-NEXT: Description: -// YAML-NEXT: - Kind: 'FullComment' +// YAML-NEXT: - Kind: FullComment // YAML-NEXT: Children: -// YAML-NEXT: - Kind: 'ParagraphComment' +// YAML-NEXT: - Kind: ParagraphComment // YAML-NEXT: Children: -// YAML-NEXT: - Kind: 'TextComment' +// YAML-NEXT: - Kind: TextComment // YAML-NEXT: Text: ' A function with a tuple parameter' -// YAML-NEXT: - Kind: 'ParagraphComment' +// YAML-NEXT: - Kind: ParagraphComment // YAML-NEXT: Children: -// YAML-NEXT: - Kind: 'TextComment' -// YAML-NEXT: - Kind: 'ParamCommandComment' +// YAML-NEXT: - Kind: TextComment +// YAML-NEXT: - Kind: ParamCommandComment // YAML-NEXT: Direction: '[in]' // YAML-NEXT: ParamName: 't' // YAML-NEXT: Children: -// YAML-NEXT: - Kind: 'ParagraphComment' +// YAML-NEXT: - Kind: ParagraphComment // YAML-NEXT: Children: -// YAML-NEXT: - Kind: 'TextComment' +// YAML-NEXT: - Kind: TextComment // YAML-NEXT: Text: ' The input to func_with_tuple_param' // YAML-NEXT: DefLocation: // YAML-NEXT: LineNumber: [[# @LINE - 23]] diff --git a/external/llvm-project/clang-tools-extra/test/clang-reorder-fields/MacroExpansionField.cpp b/external/llvm-project/clang-tools-extra/test/clang-reorder-fields/MacroExpansionField.cpp new file mode 100644 index 000000000000..a4c3cbc1e12f --- /dev/null +++ b/external/llvm-project/clang-tools-extra/test/clang-reorder-fields/MacroExpansionField.cpp @@ -0,0 +1,24 @@ +// RUN: clang-reorder-fields -record-name ::bar::Foo -fields-order z,y,x %s -- | FileCheck %s + +namespace bar { + +#define INT_DECL(NAME) int NAME // CHECK: {{^#define INT_DECL\(NAME\) int NAME}} +#define MACRO_DECL int x; // CHECK-NEXT: {{^#define MACRO_DECL int x;}} + +struct Foo { + MACRO_DECL // CHECK: {{^ INT_DECL\(z\);}} + int y; // CHECK-NEXT: {{^ int y;}} + INT_DECL(z); // CHECK-NEXT: {{^ MACRO_DECL}} +}; + +#define FOO 0 // CHECK: {{^#define FOO 0}} +#define BAR 1 // CHECK-NEXT: {{^#define BAR 1}} +#define BAZ 2 // CHECK-NEXT: {{^#define BAZ 2}} + +struct Foo foo = { + FOO, // CHECK: {{^ BAZ,}} + BAR, // CHECK-NEXT: {{^ BAR,}} + BAZ, // CHECK-NEXT: {{^ FOO,}} +}; + +} // end namespace bar diff --git a/external/llvm-project/clang-tools-extra/test/clang-tidy/checkers/bugprone/multi-level-implicit-pointer-conversion.c b/external/llvm-project/clang-tools-extra/test/clang-tidy/checkers/bugprone/multi-level-implicit-pointer-conversion.c new file mode 100644 index 000000000000..9dc5dae5c80f --- /dev/null +++ b/external/llvm-project/clang-tools-extra/test/clang-tidy/checkers/bugprone/multi-level-implicit-pointer-conversion.c @@ -0,0 +1,11 @@ +// RUN: %check_clang_tidy -check-suffixes=ENABLE-IN-C %s bugprone-multi-level-implicit-pointer-conversion %t -- -config="{CheckOptions: {bugprone-multi-level-implicit-pointer-conversion.EnableInC: true}}" +// RUN: %check_clang_tidy -check-suffixes=DISABLE-IN-C %s bugprone-multi-level-implicit-pointer-conversion %t -- -config="{CheckOptions: {bugprone-multi-level-implicit-pointer-conversion.EnableInC: false}}" + +void free(void*); + +void test() { + char **p; + free(p); + // CHECK-MESSAGES-ENABLE-IN-C: :[[@LINE-1]]:8: warning: multilevel pointer conversion from 'char **' to 'void *', please use explicit cast [bugprone-multi-level-implicit-pointer-conversion] + free((void *)p); +} diff --git a/external/llvm-project/clang-tools-extra/test/clang-tidy/checkers/google/readability-namespace-comments-missing-nested-namespaces.cpp b/external/llvm-project/clang-tools-extra/test/clang-tidy/checkers/google/readability-namespace-comments-missing-nested-namespaces.cpp new file mode 100644 index 000000000000..de42df30cb79 --- /dev/null +++ b/external/llvm-project/clang-tools-extra/test/clang-tidy/checkers/google/readability-namespace-comments-missing-nested-namespaces.cpp @@ -0,0 +1,32 @@ +// RUN: %check_clang_tidy %s google-readability-namespace-comments %t -std=c++20 \ +// RUN: '-config={CheckOptions: { \ +// RUN: google-readability-namespace-comments.AllowOmittingNamespaceComments: true, \ +// RUN: google-readability-namespace-comments.ShortNamespaceLines: 0, \ +// RUN: }}' + +// accept if namespace comments are fully omitted +namespace n1::n2 { +namespace /*comment1*/n3/*comment2*/::/*comment3*/inline/*comment4*/n4/*comment5*/ { +void f(); +}} + +namespace n5::inline n6 { +void f(); +} + +namespace n7::inline n8 { +void f(); +} + +// accept if namespace comments are partly omitted (e.g. only for nested namespace) +namespace n1::n2 { +namespace n3::n4 { +void f(); +} +} // namespace n1::n2 + +// fail if namespace comment is different than expected +namespace n9::inline n10 { +void f(); +} // namespace n9::n10 +// CHECK-MESSAGES: :[[@LINE-1]]:2: warning: namespace 'n9::inline n10' ends with a comment that refers to a wrong namespace 'n9::n10' [google-readability-namespace-comments] diff --git a/external/llvm-project/clang-tools-extra/test/clang-tidy/checkers/google/readability-namespace-comments-missing.cpp b/external/llvm-project/clang-tools-extra/test/clang-tidy/checkers/google/readability-namespace-comments-missing.cpp new file mode 100644 index 000000000000..019add1ed06d --- /dev/null +++ b/external/llvm-project/clang-tools-extra/test/clang-tidy/checkers/google/readability-namespace-comments-missing.cpp @@ -0,0 +1,40 @@ +// RUN: %check_clang_tidy %s google-readability-namespace-comments %t \ +// RUN: -config='{CheckOptions: { \ +// RUN: google-readability-namespace-comments.AllowOmittingNamespaceComments: true, \ +// RUN: google-readability-namespace-comments.ShortNamespaceLines: 0, \ +// RUN: }}' + +// accept if namespace comments are fully omitted +namespace n1 { +namespace /* a comment */ n2 /* another comment */ { +void f(); +}} + +#define MACRO macro_expansion +namespace MACRO { +void f(); +} + +namespace [[deprecated("foo")]] namespace_with_attr { +inline namespace inline_namespace { +void f(); +} +} + +namespace [[]] { +void f(); +} + +// accept if namespace comments are partly omitted (e.g. only for nested namespace) +namespace n3 { +namespace n4 { +void f(); +} // n4 +} + +// fail if namespace comment is different than expected +namespace n1 { +void f(); +} // namespace n2 +// CHECK-MESSAGES: :[[@LINE-1]]:2: warning: namespace 'n1' ends with a comment that refers to a wrong namespace 'n2' [google-readability-namespace-comments] + diff --git a/external/llvm-project/clang-tools-extra/test/clang-tidy/checkers/modernize/use-trailing-return-type-transform-lambdas-cxx14.cpp b/external/llvm-project/clang-tools-extra/test/clang-tidy/checkers/modernize/use-trailing-return-type-transform-lambdas-cxx14.cpp new file mode 100644 index 000000000000..33051c63e4f1 --- /dev/null +++ b/external/llvm-project/clang-tools-extra/test/clang-tidy/checkers/modernize/use-trailing-return-type-transform-lambdas-cxx14.cpp @@ -0,0 +1,24 @@ +// RUN: %check_clang_tidy -std=c++14-or-later %s modernize-use-trailing-return-type %t -- -- -fno-delayed-template-parsing + +namespace std { + template + class vector {}; + + class string {}; +} // namespace std + +void test_lambda_positive() { + auto l1 = [](auto x) { return x; }; + // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: use a trailing return type for this lambda [modernize-use-trailing-return-type] + // CHECK-FIXES: {{^}} auto l1 = [](auto x) -> auto { return x; };{{$}} +} + +template