| 1 |
//===--- PreferRegisterOverUnsignedCheck.cpp - clang-tidy -----------------===// |
| 2 |
// |
| 3 |
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 |
// See https://llvm.org/LICENSE.txt for license information. |
| 5 |
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 |
// |
| 7 |
//===----------------------------------------------------------------------===// |
| 8 |
|
| 9 |
#include "PreferRegisterOverUnsignedCheck.h" |
| 10 |
#include "clang/AST/ASTContext.h" |
| 11 |
#include "clang/ASTMatchers/ASTMatchFinder.h" |
| 12 |
|
| 13 |
using namespace clang::ast_matchers; |
| 14 |
|
| 15 |
namespace clang::tidy::llvm_check { |
| 16 |
|
| 17 |
void PreferRegisterOverUnsignedCheck::registerMatchers(MatchFinder *Finder) { |
| 18 |
auto RegisterClassMatch = hasType( |
| 19 |
cxxRecordDecl(hasName("::llvm::Register")).bind("registerClassDecl")); |
| 20 |
|
| 21 |
Finder->addMatcher( |
| 22 |
traverse(TK_AsIs, |
| 23 |
valueDecl(allOf( |
| 24 |
hasType(qualType(isUnsignedInteger()).bind("varType")), |
| 25 |
varDecl(hasInitializer(exprWithCleanups( |
| 26 |
has(implicitCastExpr(has(cxxMemberCallExpr( |
| 27 |
allOf(on(RegisterClassMatch), |
| 28 |
has(memberExpr(hasDeclaration( |
| 29 |
cxxConversionDecl()))))))))))) |
| 30 |
.bind("var")))), |
| 31 |
this); |
| 32 |
} |
| 33 |
|
| 34 |
void PreferRegisterOverUnsignedCheck::check( |
| 35 |
const MatchFinder::MatchResult &Result) { |
| 36 |
const auto *VarType = Result.Nodes.getNodeAs<QualType>("varType"); |
| 37 |
const auto *UserVarDecl = Result.Nodes.getNodeAs<VarDecl>("var"); |
| 38 |
|
| 39 |
bool NeedsQualification = true; |
| 40 |
const DeclContext *Context = UserVarDecl->getDeclContext(); |
| 41 |
while (Context) { |
| 42 |
if (const auto *Namespace = dyn_cast<NamespaceDecl>(Context)) |
| 43 |
if (isa<TranslationUnitDecl>(Namespace->getDeclContext()) && |
| 44 |
Namespace->getName() == "llvm") |
| 45 |
NeedsQualification = false; |
| 46 |
for (const auto *UsingDirective : Context->using_directives()) { |
| 47 |
const NamespaceDecl *Namespace = UsingDirective->getNominatedNamespace(); |
| 48 |
if (isa<TranslationUnitDecl>(Namespace->getDeclContext()) && |
| 49 |
Namespace->getName() == "llvm") |
| 50 |
NeedsQualification = false; |
| 51 |
} |
| 52 |
Context = Context->getParent(); |
| 53 |
} |
| 54 |
diag(UserVarDecl->getLocation(), |
| 55 |
"variable %0 declared as %1; use '%select{|llvm::}2Register' instead") |
| 56 |
<< UserVarDecl << *VarType << NeedsQualification |
| 57 |
<< FixItHint::CreateReplacement( |
| 58 |
UserVarDecl->getTypeSourceInfo()->getTypeLoc().getSourceRange(), |
| 59 |
NeedsQualification ? "llvm::Register" : "Register"); |
| 60 |
} |
| 61 |
|
| 62 |
} // namespace clang::tidy::llvm_check |