[clang-tools-extra] [clang-tidy] add modernize-use-constexpr check (PR #162741)

Baranov Victor via cfe-commits cfe-commits at lists.llvm.org
Sat Oct 11 08:12:58 PDT 2025


================
@@ -0,0 +1,517 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 "UseConstexprCheck.h"
+#include "../utils/ASTUtils.h"
+#include "../utils/LexerUtils.h"
+#include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallPtrSet.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::modernize {
+
+namespace {
+AST_MATCHER(FunctionDecl, locationPermitsConstexpr) {
+  const bool IsInMainFile =
+      Finder->getASTContext().getSourceManager().isInMainFile(
+          Node.getLocation());
+
+  if (IsInMainFile && Node.hasExternalFormalLinkage())
+    return false;
+  if (!IsInMainFile && !Node.isInlined())
+    return false;
+
+  return true;
+}
+
+AST_MATCHER(Expr, isCXX11ConstantExpr) {
+  return !Node.isValueDependent() &&
+         Node.isCXX11ConstantExpr(Finder->getASTContext());
+}
+
+AST_MATCHER(DeclaratorDecl, isInMacro) {
+  const SourceRange R =
+      SourceRange(Node.getTypeSpecStartLoc(), Node.getLocation());
+
+  return Node.getLocation().isMacroID() || Node.getEndLoc().isMacroID() ||
+         utils::rangeContainsMacroExpansion(
+             R, &Finder->getASTContext().getSourceManager()) ||
+         utils::rangeIsEntirelyWithinMacroArgument(
+             R, &Finder->getASTContext().getSourceManager());
+}
+
+AST_MATCHER(Decl, hasNoRedecl) {
+  // There is always the actual declaration
+  return !Node.redecls().empty() &&
+         std::next(Node.redecls_begin()) == Node.redecls_end();
+}
+
+AST_MATCHER(Decl, allRedeclsInSameFile) {
+  const SourceManager &SM = Finder->getASTContext().getSourceManager();
+  const SourceLocation L = Node.getLocation();
+  for (const Decl *ReDecl : Node.redecls()) {
+    if (!SM.isWrittenInSameFile(L, ReDecl->getLocation()))
+      return false;
+  }
+  return true;
+}
+} // namespace
+
+static bool
+satisfiesConstructorPropertiesUntil20(const CXXConstructorDecl *Ctor,
+                                      ASTContext &Ctx) {
+  const CXXRecordDecl *Rec = Ctor->getParent();
+  llvm::SmallPtrSet<const RecordDecl *, 8> Bases{};
+  for (const CXXBaseSpecifier Base : Rec->bases())
+    Bases.insert(Base.getType()->getAsRecordDecl());
+
+  llvm::SmallPtrSet<const FieldDecl *, 8> Fields{Rec->field_begin(),
+                                                 Rec->field_end()};
+  llvm::SmallPtrSet<const FieldDecl *, 4> Indirects{};
+
+  for (const CXXCtorInitializer *const Init : Ctor->inits()) {
+    const Type *InitType = Init->getBaseClass();
+    if (InitType && InitType->isRecordType()) {
+      const auto *ConstructingInit =
+          llvm::dyn_cast<CXXConstructExpr>(Init->getInit());
+      if (ConstructingInit &&
+          !ConstructingInit->getConstructor()->isConstexprSpecified())
+        return false;
+    }
+
+    if (Init->isBaseInitializer()) {
+      Bases.erase(Init->getBaseClass()->getAsRecordDecl());
+      continue;
+    }
+
+    if (Init->isMemberInitializer()) {
+      const FieldDecl *Field = Init->getMember();
+
+      if (Field->isAnonymousStructOrUnion())
+        Indirects.insert(Field);
+
+      Fields.erase(Field);
+      continue;
+    }
+  }
+
+  for (const auto &Match :
+       match(cxxRecordDecl(forEach(indirectFieldDecl().bind("indirect"))), *Rec,
+             Ctx)) {
+    const auto *IField = Match.getNodeAs<IndirectFieldDecl>("indirect");
+
+    size_t NumInitializations = false;
+    for (const NamedDecl *ND : IField->chain())
+      NumInitializations += Indirects.erase(llvm::dyn_cast<FieldDecl>(ND));
+
+    if (NumInitializations != 1)
+      return false;
+
+    for (const NamedDecl *ND : IField->chain())
+      Fields.erase(llvm::dyn_cast<FieldDecl>(ND));
+  }
+
+  if (!Fields.empty())
+    return false;
+
+  return true;
+}
+
+static bool isLiteralType(QualType QT, const ASTContext &Ctx,
+                          bool ConservativeLiteralType);
+
+static bool isLiteralType(const Type *T, const ASTContext &Ctx,
+                          const bool ConservativeLiteralType) {
+  if (!T)
+    return false;
+
+  if (!T->isLiteralType(Ctx))
+    return false;
+
+  if (!ConservativeLiteralType)
+    return T->isLiteralType(Ctx) && !T->isVoidType();
+
+  if (T->isIncompleteType() || T->isIncompleteArrayType())
+    return false;
+
+  T = utils::unwrapPointee(T);
+  if (!T)
+    return false;
+
+  assert(!T->isPointerOrReferenceType());
+
+  if (T->isIncompleteType() || T->isIncompleteArrayType())
+    return false;
+
+  if (T->isLiteralType(Ctx))
+    return true;
+
+  if (const CXXRecordDecl *Rec = T->getAsCXXRecordDecl()) {
+    if (llvm::any_of(Rec->ctors(), [](const CXXConstructorDecl *Ctor) {
+          return !Ctor->isCopyOrMoveConstructor() &&
+                 Ctor->isConstexprSpecified();
+        }))
+      return false;
+
+    for (const CXXBaseSpecifier Base : Rec->bases()) {
+      if (!isLiteralType(Base.getType(), Ctx, ConservativeLiteralType))
+        return false;
+    }
+  }
+
+  if (const Type *ArrayElementType = T->getArrayElementTypeNoTypeQual())
+    return isLiteralType(ArrayElementType, Ctx, ConservativeLiteralType);
+
+  return false;
+}
+
+static bool isLiteralType(QualType QT, const ASTContext &Ctx,
+                          const bool ConservativeLiteralType) {
+  return !QT.isVolatileQualified() &&
+         isLiteralType(QT.getTypePtr(), Ctx, ConservativeLiteralType);
+}
+
+static bool satisfiesProperties11(
+    const FunctionDecl *FDecl, ASTContext &Ctx,
+    const bool ConservativeLiteralType,
+    const bool AddConstexprToMethodOfClassWithoutConstexprConstructor) {
+  if (FDecl->isConstexprSpecified())
+    return true;
+
+  const LangOptions LO = Ctx.getLangOpts();
+  const auto *Method = llvm::dyn_cast<CXXMethodDecl>(FDecl);
+  if (Method && !Method->isStatic() &&
+      !Method->getParent()->hasConstexprNonCopyMoveConstructor() &&
+      !AddConstexprToMethodOfClassWithoutConstexprConstructor)
+    return false;
+
+  if (Method &&
+      (Method->isVirtual() ||
+       !match(cxxMethodDecl(hasBody(cxxTryStmt())), *Method, Ctx).empty()))
+    return false;
+
+  if (const auto *Ctor = llvm::dyn_cast<CXXConstructorDecl>(FDecl);
+      Ctor && (!satisfiesConstructorPropertiesUntil20(Ctor, Ctx) ||
+               llvm::any_of(Ctor->getParent()->bases(),
+                            [](const CXXBaseSpecifier &Base) {
+                              return Base.isVirtual();
+                            })))
+    return false;
+
+  if (const auto *Dtor = llvm::dyn_cast<CXXDestructorDecl>(FDecl);
+      Dtor && !Dtor->isTrivial())
+    return false;
+
+  if (!isLiteralType(FDecl->getReturnType(), Ctx, ConservativeLiteralType))
+    return false;
+
+  for (const ParmVarDecl *Param : FDecl->parameters())
+    if (!isLiteralType(Param->getType(), Ctx, ConservativeLiteralType))
+      return false;
+
+  class Visitor11 : public clang::RecursiveASTVisitor<Visitor11> {
----------------
vbvictor wrote:

Based on https://github.com/llvm/llvm-project/pull/115144, I guess we should almost always use DRAM

https://github.com/llvm/llvm-project/pull/162741


More information about the cfe-commits mailing list