clang-tools  5.0.0
NonConstParameterCheck.cpp
Go to the documentation of this file.
1 //===--- NonConstParameterCheck.cpp - clang-tidy---------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "NonConstParameterCheck.h"
11 #include "clang/AST/ASTContext.h"
12 #include "clang/ASTMatchers/ASTMatchFinder.h"
13 
14 using namespace clang::ast_matchers;
15 
16 namespace clang {
17 namespace tidy {
18 namespace readability {
19 
20 void NonConstParameterCheck::registerMatchers(MatchFinder *Finder) {
21  // Add parameters to Parameters.
22  Finder->addMatcher(parmVarDecl(unless(isInstantiated())).bind("Parm"), this);
23 
24  // C++ constructor.
25  Finder->addMatcher(cxxConstructorDecl().bind("Ctor"), this);
26 
27  // Track unused parameters, there is Wunused-parameter about unused
28  // parameters.
29  Finder->addMatcher(declRefExpr().bind("Ref"), this);
30 
31  // Analyse parameter usage in function.
32  Finder->addMatcher(stmt(anyOf(unaryOperator(anyOf(hasOperatorName("++"),
33  hasOperatorName("--"))),
34  binaryOperator(), callExpr(), returnStmt(),
35  cxxConstructExpr()))
36  .bind("Mark"),
37  this);
38  Finder->addMatcher(varDecl(hasInitializer(anything())).bind("Mark"), this);
39 }
40 
41 void NonConstParameterCheck::check(const MatchFinder::MatchResult &Result) {
42  if (const auto *Parm = Result.Nodes.getNodeAs<ParmVarDecl>("Parm")) {
43  if (const DeclContext *D = Parm->getParentFunctionOrMethod()) {
44  if (const auto *M = dyn_cast<CXXMethodDecl>(D)) {
45  if (M->isVirtual() || M->size_overridden_methods() != 0)
46  return;
47  }
48  }
49  addParm(Parm);
50  } else if (const auto *Ctor =
51  Result.Nodes.getNodeAs<CXXConstructorDecl>("Ctor")) {
52  for (const auto *Parm : Ctor->parameters())
53  addParm(Parm);
54  for (const auto *Init : Ctor->inits())
55  markCanNotBeConst(Init->getInit(), true);
56  } else if (const auto *Ref = Result.Nodes.getNodeAs<DeclRefExpr>("Ref")) {
57  setReferenced(Ref);
58  } else if (const auto *S = Result.Nodes.getNodeAs<Stmt>("Mark")) {
59  if (const auto *B = dyn_cast<BinaryOperator>(S)) {
60  if (B->isAssignmentOp())
61  markCanNotBeConst(B, false);
62  } else if (const auto *CE = dyn_cast<CallExpr>(S)) {
63  // Typically, if a parameter is const then it is fine to make the data
64  // const. But sometimes the data is written even though the parameter
65  // is const. Mark all data passed by address to the function.
66  for (const auto *Arg : CE->arguments()) {
67  markCanNotBeConst(Arg->IgnoreParenCasts(), true);
68  }
69 
70  // Data passed by nonconst reference should not be made const.
71  if (const FunctionDecl *FD = CE->getDirectCallee()) {
72  unsigned ArgNr = 0U;
73  for (const auto *Par : FD->parameters()) {
74  if (ArgNr >= CE->getNumArgs())
75  break;
76  const Expr *Arg = CE->getArg(ArgNr++);
77  // Is this a non constant reference parameter?
78  const Type *ParType = Par->getType().getTypePtr();
79  if (!ParType->isReferenceType() || Par->getType().isConstQualified())
80  continue;
81  markCanNotBeConst(Arg->IgnoreParenCasts(), false);
82  }
83  }
84  } else if (const auto *CE = dyn_cast<CXXConstructExpr>(S)) {
85  for (const auto *Arg : CE->arguments()) {
86  markCanNotBeConst(Arg->IgnoreParenCasts(), true);
87  }
88  } else if (const auto *R = dyn_cast<ReturnStmt>(S)) {
89  markCanNotBeConst(R->getRetValue(), true);
90  } else if (const auto *U = dyn_cast<UnaryOperator>(S)) {
91  markCanNotBeConst(U, true);
92  }
93  } else if (const auto *VD = Result.Nodes.getNodeAs<VarDecl>("Mark")) {
94  const QualType T = VD->getType();
95  if ((T->isPointerType() && !T->getPointeeType().isConstQualified()) ||
96  T->isArrayType())
97  markCanNotBeConst(VD->getInit(), true);
98  }
99 }
100 
101 void NonConstParameterCheck::addParm(const ParmVarDecl *Parm) {
102  // Only add nonconst integer/float pointer parameters.
103  const QualType T = Parm->getType();
104  if (!T->isPointerType() || T->getPointeeType().isConstQualified() ||
105  !(T->getPointeeType()->isIntegerType() ||
106  T->getPointeeType()->isFloatingType()))
107  return;
108 
109  if (Parameters.find(Parm) != Parameters.end())
110  return;
111 
112  ParmInfo PI;
113  PI.IsReferenced = false;
114  PI.CanBeConst = true;
115  Parameters[Parm] = PI;
116 }
117 
118 void NonConstParameterCheck::setReferenced(const DeclRefExpr *Ref) {
119  auto It = Parameters.find(dyn_cast<ParmVarDecl>(Ref->getDecl()));
120  if (It != Parameters.end())
121  It->second.IsReferenced = true;
122 }
123 
124 void NonConstParameterCheck::onEndOfTranslationUnit() {
125  diagnoseNonConstParameters();
126 }
127 
128 void NonConstParameterCheck::diagnoseNonConstParameters() {
129  for (const auto &It : Parameters) {
130  const ParmVarDecl *Par = It.first;
131  const ParmInfo &ParamInfo = It.second;
132 
133  // Unused parameter => there are other warnings about this.
134  if (!ParamInfo.IsReferenced)
135  continue;
136 
137  // Parameter can't be const.
138  if (!ParamInfo.CanBeConst)
139  continue;
140 
141  diag(Par->getLocation(), "pointer parameter '%0' can be pointer to const")
142  << Par->getName()
143  << FixItHint::CreateInsertion(Par->getLocStart(), "const ");
144  }
145 }
146 
147 void NonConstParameterCheck::markCanNotBeConst(const Expr *E,
148  bool CanNotBeConst) {
149  if (!E)
150  return;
151 
152  if (const auto *Cast = dyn_cast<ImplicitCastExpr>(E)) {
153  // If expression is const then ignore usage.
154  const QualType T = Cast->getType();
155  if (T->isPointerType() && T->getPointeeType().isConstQualified())
156  return;
157  }
158 
159  E = E->IgnoreParenCasts();
160 
161  if (const auto *B = dyn_cast<BinaryOperator>(E)) {
162  if (B->isAdditiveOp()) {
163  // p + 2
164  markCanNotBeConst(B->getLHS(), CanNotBeConst);
165  markCanNotBeConst(B->getRHS(), CanNotBeConst);
166  } else if (B->isAssignmentOp()) {
167  markCanNotBeConst(B->getLHS(), false);
168 
169  // If LHS is not const then RHS can't be const.
170  const QualType T = B->getLHS()->getType();
171  if (T->isPointerType() && !T->getPointeeType().isConstQualified())
172  markCanNotBeConst(B->getRHS(), true);
173  }
174  } else if (const auto *C = dyn_cast<ConditionalOperator>(E)) {
175  markCanNotBeConst(C->getTrueExpr(), CanNotBeConst);
176  markCanNotBeConst(C->getFalseExpr(), CanNotBeConst);
177  } else if (const auto *U = dyn_cast<UnaryOperator>(E)) {
178  if (U->getOpcode() == UO_PreInc || U->getOpcode() == UO_PreDec ||
179  U->getOpcode() == UO_PostInc || U->getOpcode() == UO_PostDec) {
180  if (const auto *SubU =
181  dyn_cast<UnaryOperator>(U->getSubExpr()->IgnoreParenCasts()))
182  markCanNotBeConst(SubU->getSubExpr(), true);
183  markCanNotBeConst(U->getSubExpr(), CanNotBeConst);
184  } else if (U->getOpcode() == UO_Deref) {
185  if (!CanNotBeConst)
186  markCanNotBeConst(U->getSubExpr(), true);
187  } else {
188  markCanNotBeConst(U->getSubExpr(), CanNotBeConst);
189  }
190  } else if (const auto *A = dyn_cast<ArraySubscriptExpr>(E)) {
191  markCanNotBeConst(A->getBase(), true);
192  } else if (const auto *CLE = dyn_cast<CompoundLiteralExpr>(E)) {
193  markCanNotBeConst(CLE->getInitializer(), true);
194  } else if (const auto *Constr = dyn_cast<CXXConstructExpr>(E)) {
195  for (const auto *Arg : Constr->arguments()) {
196  if (const auto *M = dyn_cast<MaterializeTemporaryExpr>(Arg))
197  markCanNotBeConst(cast<Expr>(M->getTemporary()), CanNotBeConst);
198  }
199  } else if (const auto *ILE = dyn_cast<InitListExpr>(E)) {
200  for (unsigned I = 0U; I < ILE->getNumInits(); ++I)
201  markCanNotBeConst(ILE->getInit(I), true);
202  } else if (CanNotBeConst) {
203  // Referencing parameter.
204  if (const auto *D = dyn_cast<DeclRefExpr>(E)) {
205  auto It = Parameters.find(dyn_cast<ParmVarDecl>(D->getDecl()));
206  if (It != Parameters.end())
207  It->second.CanBeConst = false;
208  }
209  }
210 }
211 
212 } // namespace readability
213 } // namespace tidy
214 } // namespace clang
std::unique_ptr< ast_matchers::MatchFinder > Finder
Definition: ClangTidy.cpp:275