[clang-tools-extra] [clang-tidy] Add portability-avoid-platform-specific-fundamental-types (PR #146970)
JJ Marr via cfe-commits
cfe-commits at lists.llvm.org
Sat Jul 5 16:01:02 PDT 2025
================
@@ -0,0 +1,246 @@
+//===--- AvoidPlatformSpecificFundamentalTypesCheck.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.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "AvoidPlatformSpecificFundamentalTypesCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Basic/TargetInfo.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::portability {
+
+AvoidPlatformSpecificFundamentalTypesCheck::
+ AvoidPlatformSpecificFundamentalTypesCheck(StringRef Name,
+ ClangTidyContext *Context)
+ : ClangTidyCheck(Name, Context),
+ WarnOnFloats(Options.get("WarnOnFloats", false)),
+ IncludeInserter(Options.getLocalOrGlobal("IncludeStyle",
+ utils::IncludeSorter::IS_LLVM),
+ areDiagsSelfContained()) {}
+
+void AvoidPlatformSpecificFundamentalTypesCheck::registerPPCallbacks(
+ const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) {
+ IncludeInserter.registerPreprocessor(PP);
+}
+
+void AvoidPlatformSpecificFundamentalTypesCheck::storeOptions(
+ ClangTidyOptions::OptionMap &Opts) {
+ Options.store(Opts, "WarnOnFloats", WarnOnFloats);
+ Options.store(Opts, "IncludeStyle", IncludeInserter.getStyle());
+}
+
+std::string AvoidPlatformSpecificFundamentalTypesCheck::getFloatReplacement(
+ const BuiltinType *BT, ASTContext &Context) const {
+ const TargetInfo &Target = Context.getTargetInfo();
+
+ auto GetReplacementType = [](unsigned Width) {
+ switch (Width) {
+ // This is ambiguous by default since it could be bfloat16 or float16
+ case 16U:
+ return "";
+ case 32U:
+ return "float32_t";
+ case 64U:
+ return "float64_t";
+ case 128U:
+ return "float128_t";
+ default:
+ return "";
+ }
+ };
+
+ switch (BT->getKind()) {
+ // Not an ambiguous type
+ case BuiltinType::BFloat16:
+ return "bfloat16_t";
+ case BuiltinType::Half:
+ return GetReplacementType(Target.getHalfWidth());
+ case BuiltinType::Float:
+ return GetReplacementType(Target.getFloatWidth());
+ case BuiltinType::Double:
+ return GetReplacementType(Target.getDoubleWidth());
+ default:
+ return "";
+ }
+}
+
+void AvoidPlatformSpecificFundamentalTypesCheck::registerMatchers(
+ MatchFinder *Finder) {
+ // Build the list of type strings to match
+ std::vector<std::string> TypeStrings = {"short",
----------------
jj-marr wrote:
warn on int should also be a config option.
https://github.com/llvm/llvm-project/pull/146970
More information about the cfe-commits
mailing list