Version 6.1.0.2, tag libreoffice-6.1.0.2
[LibreOffice.git] / compilerplugins / clang / oncevar.cxx
bloba8a56f5a7e333525b462934856c13c2b9b000d92
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 */
10 #include <cassert>
11 #include <string>
12 #include <iostream>
13 #include <unordered_map>
14 #include <unordered_set>
16 #include "plugin.hxx"
17 #include "check.hxx"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/StmtVisitor.h"
21 // Original idea from tml.
22 // Look for variables that are (a) initialised from zero or one constants. (b) only used in one spot.
23 // In which case, we might as well inline it.
25 namespace
28 bool startsWith(const std::string& rStr, const char* pSubStr) {
29 return rStr.compare(0, strlen(pSubStr), pSubStr) == 0;
32 Expr const * lookThroughInitListExpr(Expr const * expr) {
33 if (auto const ile = dyn_cast<InitListExpr>(expr->IgnoreParenImpCasts())) {
34 if (ile->getNumInits() == 1) {
35 return ile->getInit(0);
38 return expr;
41 class ConstantValueDependentExpressionVisitor:
42 public ConstStmtVisitor<ConstantValueDependentExpressionVisitor, bool>
44 ASTContext const & context_;
46 public:
47 ConstantValueDependentExpressionVisitor(ASTContext const & context):
48 context_(context) {}
50 bool Visit(Stmt const * stmt) {
51 assert(isa<Expr>(stmt));
52 auto const expr = cast<Expr>(stmt);
53 if (!expr->isValueDependent()) {
54 return expr->isEvaluatable(context_);
56 return ConstStmtVisitor::Visit(stmt);
59 bool VisitParenExpr(ParenExpr const * expr)
60 { return Visit(expr->getSubExpr()); }
62 bool VisitCastExpr(CastExpr const * expr) {
63 return Visit(expr->getSubExpr());
66 bool VisitUnaryOperator(UnaryOperator const * expr)
67 { return Visit(expr->getSubExpr()); }
69 bool VisitBinaryOperator(BinaryOperator const * expr) {
70 return Visit(expr->getLHS()) && Visit(expr->getRHS());
73 bool VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr const *) {
74 return true;
78 class OnceVar:
79 public RecursiveASTVisitor<OnceVar>, public loplugin::Plugin
81 public:
82 explicit OnceVar(loplugin::InstantiationData const & data): Plugin(data) {}
84 virtual void run() override {
85 // ignore some files with problematic macros
86 std::string fn( compiler.getSourceManager().getFileEntryForID(
87 compiler.getSourceManager().getMainFileID())->getName() );
88 loplugin::normalizeDotDotInFilePath(fn);
89 // platform-specific stuff
90 if (fn == SRCDIR "/sal/osl/unx/thread.cxx"
91 || fn == SRCDIR "/sot/source/base/formats.cxx"
92 || fn == SRCDIR "/svl/source/config/languageoptions.cxx"
93 || fn == SRCDIR "/sfx2/source/appl/appdde.cxx"
94 || fn == SRCDIR "/configmgr/source/components.cxx"
95 || fn == SRCDIR "/embeddedobj/source/msole/oleembed.cxx")
96 return;
97 // some of this is necessary
98 if (startsWith( fn, SRCDIR "/sal/qa/"))
99 return;
100 if (startsWith( fn, SRCDIR "/comphelper/qa/"))
101 return;
102 // TODO need to check calls via function pointer
103 if (fn == SRCDIR "/i18npool/source/textconversion/textconversion_zh.cxx"
104 || fn == SRCDIR "/i18npool/source/localedata/localedata.cxx")
105 return;
106 // debugging stuff
107 if (fn == SRCDIR "/sc/source/core/data/dpcache.cxx"
108 || fn == SRCDIR "/sw/source/core/layout/dbg_lay.cxx"
109 || fn == SRCDIR "/sw/source/core/layout/ftnfrm.cxx")
110 return;
111 // TODO taking local reference to variable
112 if (fn == SRCDIR "/sc/source/filter/excel/xechart.cxx")
113 return;
114 // macros managing to generate to a valid warning
115 if (fn == SRCDIR "/solenv/bin/concat-deps.c")
116 return;
117 // TODO bug in the plugin
118 if (fn == SRCDIR "/vcl/unx/generic/app/saldisp.cxx")
119 return;
121 TraverseDecl(compiler.getASTContext().getTranslationUnitDecl());
123 for (auto const & varDecl : maVarDeclSet)
125 if (maVarDeclToIgnoreSet.find(varDecl) != maVarDeclToIgnoreSet.end())
126 continue;
127 int noUses = 0;
128 auto it = maVarUsesMap.find(varDecl);
129 if (it != maVarUsesMap.end())
130 noUses = it->second;
131 if (noUses > 1)
132 continue;
133 report(DiagnosticsEngine::Warning,
134 "var used only once, should be inlined or declared const",
135 varDecl->getLocation())
136 << varDecl->getSourceRange();
137 if (it != maVarUsesMap.end())
138 report(DiagnosticsEngine::Note,
139 "used here",
140 maVarUseSourceRangeMap[varDecl].getBegin())
141 << maVarUseSourceRangeMap[varDecl];
145 bool VisitMemberExpr(MemberExpr const * expr) {
146 // ignore cases like:
147 // const OUString("xxx") xxx;
148 // rtl_something(xxx.pData);
149 // where we cannot inline the declaration.
150 if (isa<FieldDecl>(expr->getMemberDecl())) {
151 recordIgnore(expr);
153 return true;
156 bool VisitUnaryOperator(UnaryOperator const * expr) {
157 // if we take the address of it, or we modify it, ignore it
158 UnaryOperator::Opcode op = expr->getOpcode();
159 if (op == UO_AddrOf || op == UO_PreInc || op == UO_PostInc
160 || op == UO_PreDec || op == UO_PostDec)
162 recordIgnore(expr->getSubExpr());
164 return true;
167 bool VisitBinaryOperator(BinaryOperator const * expr) {
168 // if we assign it another value, or modify it, ignore it
169 BinaryOperator::Opcode op = expr->getOpcode();
170 if (op == BO_Assign || op == BO_PtrMemD || op == BO_PtrMemI || op == BO_MulAssign
171 || op == BO_DivAssign || op == BO_RemAssign || op == BO_AddAssign
172 || op == BO_SubAssign || op == BO_ShlAssign || op == BO_ShrAssign
173 || op == BO_AndAssign || op == BO_XorAssign || op == BO_OrAssign)
175 recordIgnore(expr->getLHS());
177 return true;
180 bool VisitCallExpr(CallExpr const * expr) {
181 unsigned firstArg = 0;
182 if (auto const cmce = dyn_cast<CXXMemberCallExpr>(expr)) {
183 if (auto const e1 = cmce->getMethodDecl()) {
184 if (!(e1->isConst() || e1->isStatic())) {
185 recordIgnore(cmce->getImplicitObjectArgument());
187 } else if (auto const e2 = dyn_cast<BinaryOperator>(
188 cmce->getCallee()->IgnoreParenImpCasts()))
190 switch (e2->getOpcode()) {
191 case BO_PtrMemD:
192 case BO_PtrMemI:
193 if (!e2->getRHS()->getType()->getAs<MemberPointerType>()
194 ->getPointeeType()->getAs<FunctionProtoType>()
195 ->isConst())
197 recordIgnore(e2->getLHS());
199 break;
200 default:
201 break;
204 } else if (auto const coce = dyn_cast<CXXOperatorCallExpr>(expr)) {
205 if (auto const cmd = dyn_cast_or_null<CXXMethodDecl>(
206 coce->getDirectCallee()))
208 if (!cmd->isStatic()) {
209 assert(coce->getNumArgs() != 0);
210 if (!cmd->isConst()) {
211 recordIgnore(coce->getArg(0));
213 firstArg = 1;
217 // ignore those ones we are passing by reference
218 const FunctionDecl* calleeFunctionDecl = expr->getDirectCallee();
219 if (calleeFunctionDecl) {
220 for (unsigned i = firstArg; i < expr->getNumArgs(); ++i) {
221 if (i < calleeFunctionDecl->getNumParams()) {
222 QualType qt { calleeFunctionDecl->getParamDecl(i)->getType() };
223 if (loplugin::TypeCheck(qt).LvalueReference().NonConst()) {
224 recordIgnore(expr->getArg(i));
226 if (loplugin::TypeCheck(qt).Pointer().NonConst()) {
227 recordIgnore(expr->getArg(i));
232 return true;
235 bool VisitCXXConstructExpr(CXXConstructExpr const * expr) {
236 // ignore those ones we are passing by reference
237 const CXXConstructorDecl* cxxConstructorDecl = expr->getConstructor();
238 for (unsigned i = 0; i < expr->getNumArgs(); ++i) {
239 if (i < cxxConstructorDecl->getNumParams()) {
240 QualType qt { cxxConstructorDecl->getParamDecl(i)->getType() };
241 if (loplugin::TypeCheck(qt).LvalueReference().NonConst()) {
242 recordIgnore(expr->getArg(i));
244 if (loplugin::TypeCheck(qt).Pointer().NonConst()) {
245 recordIgnore(expr->getArg(i));
249 return true;
252 bool VisitDeclRefExpr( const DeclRefExpr* );
253 bool VisitVarDecl( const VarDecl* );
254 bool TraverseFunctionDecl( FunctionDecl* functionDecl );
256 private:
257 std::unordered_set<VarDecl const *> maVarDeclSet;
258 std::unordered_set<VarDecl const *> maVarDeclToIgnoreSet;
259 std::unordered_map<VarDecl const *, int> maVarUsesMap;
260 std::unordered_map<VarDecl const *, SourceRange> maVarUseSourceRangeMap;
262 bool isConstantValueDependentExpression(Expr const * expr) {
263 return ConstantValueDependentExpressionVisitor(compiler.getASTContext())
264 .Visit(expr);
267 void recordIgnore(Expr const * expr) {
268 for (;;) {
269 expr = expr->IgnoreParenImpCasts();
270 if (auto const e = dyn_cast<MemberExpr>(expr)) {
271 if (isa<FieldDecl>(e->getMemberDecl())) {
272 expr = e->getBase();
273 continue;
276 if (auto const e = dyn_cast<ArraySubscriptExpr>(expr)) {
277 expr = e->getBase();
278 continue;
280 if (auto const e = dyn_cast<BinaryOperator>(expr)) {
281 if (e->getOpcode() == BO_PtrMemD) {
282 expr = e->getLHS();
283 continue;
286 break;
288 auto const dre = dyn_cast<DeclRefExpr>(expr);
289 if (dre == nullptr) {
290 return;
292 auto const var = dyn_cast<VarDecl>(dre->getDecl());
293 if (var == nullptr) {
294 return;
296 maVarDeclToIgnoreSet.insert(var);
300 bool OnceVar::TraverseFunctionDecl( FunctionDecl* functionDecl )
302 // Ignore functions that contains #ifdef-ery, can be quite tricky
303 // to make useful changes when this plugin fires in such functions
304 if (containsPreprocessingConditionalInclusion(
305 functionDecl->getSourceRange()))
306 return true;
307 return RecursiveASTVisitor::TraverseFunctionDecl(functionDecl);
310 bool OnceVar::VisitVarDecl( const VarDecl* varDecl )
312 if (ignoreLocation(varDecl)) {
313 return true;
315 if (auto const init = varDecl->getInit()) {
316 recordIgnore(lookThroughInitListExpr(init));
318 if (varDecl->isExceptionVariable() || isa<ParmVarDecl>(varDecl)) {
319 return true;
321 // ignore stuff in header files (which should really not be there, but anyhow)
322 if (!compiler.getSourceManager().isInMainFile(varDecl->getLocation())) {
323 return true;
325 // Ignore macros like FD_ZERO
326 if (compiler.getSourceManager().isMacroBodyExpansion(varDecl->getLocStart())) {
327 return true;
329 if (varDecl->hasGlobalStorage()) {
330 return true;
332 auto const tc = loplugin::TypeCheck(varDecl->getType());
333 if (!varDecl->getType().isCXX11PODType(compiler.getASTContext())
334 && !tc.Class("OString").Namespace("rtl").GlobalNamespace()
335 && !tc.Class("OUString").Namespace("rtl").GlobalNamespace()
336 && !tc.Class("OStringBuffer").Namespace("rtl").GlobalNamespace()
337 && !tc.Class("OUStringBuffer").Namespace("rtl").GlobalNamespace()
338 && !tc.Class("Color").GlobalNamespace()
339 && !tc.Class("Pair").GlobalNamespace()
340 && !tc.Class("Point").GlobalNamespace()
341 && !tc.Class("Size").GlobalNamespace()
342 && !tc.Class("Range").GlobalNamespace()
343 && !tc.Class("Selection").GlobalNamespace()
344 && !tc.Class("Rectangle").Namespace("tools").GlobalNamespace())
346 return true;
348 if (varDecl->getType()->isPointerType())
349 return true;
350 // if it's declared const, ignore it, it's there to make the code easier to read
351 if (tc.Const())
352 return true;
354 if (!varDecl->hasInit())
355 return true;
357 // check for string or scalar literals
358 bool foundStringLiteral = false;
359 const Expr * initExpr = varDecl->getInit();
360 if (auto e = dyn_cast<ExprWithCleanups>(initExpr)) {
361 initExpr = e->getSubExpr();
363 if (isa<clang::StringLiteral>(initExpr)) {
364 foundStringLiteral = true;
365 } else if (auto constructExpr = dyn_cast<CXXConstructExpr>(initExpr)) {
366 if (constructExpr->getNumArgs() == 0) {
367 foundStringLiteral = true; // i.e., empty string
368 } else {
369 auto stringLit2 = dyn_cast<clang::StringLiteral>(constructExpr->getArg(0));
370 foundStringLiteral = stringLit2 != nullptr;
373 if (!foundStringLiteral) {
374 auto const init = varDecl->getInit();
375 if (!(init->isValueDependent()
376 ? isConstantValueDependentExpression(init)
377 : init->isConstantInitializer(
378 compiler.getASTContext(), false/*ForRef*/)))
380 return true;
384 maVarDeclSet.insert(varDecl);
386 return true;
389 bool OnceVar::VisitDeclRefExpr( const DeclRefExpr* declRefExpr )
391 if (ignoreLocation(declRefExpr)) {
392 return true;
394 const Decl* decl = declRefExpr->getDecl();
395 if (!isa<VarDecl>(decl) || isa<ParmVarDecl>(decl)) {
396 return true;
398 const VarDecl * varDecl = dyn_cast<VarDecl>(decl)->getCanonicalDecl();
399 // ignore stuff in header files (which should really not be there, but anyhow)
400 if (!compiler.getSourceManager().isInMainFile(varDecl->getLocation())) {
401 return true;
404 if (maVarUsesMap.find(varDecl) == maVarUsesMap.end()) {
405 maVarUsesMap[varDecl] = 1;
406 maVarUseSourceRangeMap[varDecl] = declRefExpr->getSourceRange();
407 } else {
408 maVarUsesMap[varDecl]++;
411 return true;
414 loplugin::Plugin::Registration< OnceVar > X("oncevar", false);
418 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */