clang-tools  10.0.0git
PreferRegisterOverUnsignedCheck.cpp
Go to the documentation of this file.
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 
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12 
13 using namespace clang::ast_matchers;
14 
15 namespace clang {
16 namespace tidy {
17 namespace llvm_check {
18 
19 void PreferRegisterOverUnsignedCheck::registerMatchers(MatchFinder *Finder) {
20  auto RegisterClassMatch = hasType(
21  cxxRecordDecl(hasName("::llvm::Register")).bind("registerClassDecl"));
22 
23  Finder->addMatcher(
24  valueDecl(allOf(
25  hasType(qualType(isUnsignedInteger()).bind("varType")),
26  varDecl(hasInitializer(exprWithCleanups(has(implicitCastExpr(has(
27  cxxMemberCallExpr(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  StringRef Replacement = "llvm::Register";
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  Replacement = "Register";
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  Replacement = "Register";
51  }
52  Context = Context->getParent();
53  }
54  diag(UserVarDecl->getLocation(),
55  "variable %0 declared as %1; use '%2' instead")
56  << UserVarDecl << *VarType << Replacement
57  << FixItHint::CreateReplacement(
58  UserVarDecl->getTypeSourceInfo()->getTypeLoc().getSourceRange(),
59  Replacement);
60 }
61 
62 } // namespace llvm_check
63 } // namespace tidy
64 } // namespace clang
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//