oncevar.cxx 14.5 KB
Newer Older
Noel Grandin's avatar
Noel Grandin committed
1 2 3 4 5 6 7 8 9
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

10
#include <cassert>
Noel Grandin's avatar
Noel Grandin committed
11 12 13 14 15 16 17 18
#include <string>
#include <iostream>
#include <unordered_map>
#include <unordered_set>

#include "plugin.hxx"
#include "check.hxx"
#include "clang/AST/CXXInheritance.h"
19
#include "clang/AST/StmtVisitor.h"
Noel Grandin's avatar
Noel Grandin committed
20 21 22 23 24 25 26 27

// Original idea from tml.
// Look for variables that are (a) initialised from zero or one constants. (b) only used in one spot.
// In which case, we might as well inline it.

namespace
{

28 29 30 31 32 33 34 35 36
Expr const * lookThroughInitListExpr(Expr const * expr) {
    if (auto const ile = dyn_cast<InitListExpr>(expr->IgnoreParenImpCasts())) {
        if (ile->getNumInits() == 1) {
            return ile->getInit(0);
        }
    }
    return expr;
}

37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
class ConstantValueDependentExpressionVisitor:
    public ConstStmtVisitor<ConstantValueDependentExpressionVisitor, bool>
{
    ASTContext const & context_;

public:
    ConstantValueDependentExpressionVisitor(ASTContext const & context):
        context_(context) {}

    bool Visit(Stmt const * stmt) {
        assert(isa<Expr>(stmt));
        auto const expr = cast<Expr>(stmt);
        if (!expr->isValueDependent()) {
            return expr->isEvaluatable(context_);
        }
        return ConstStmtVisitor::Visit(stmt);
    }

    bool VisitParenExpr(ParenExpr const * expr)
    { return Visit(expr->getSubExpr()); }

    bool VisitCastExpr(CastExpr const * expr) {
        return Visit(expr->getSubExpr());
    }

    bool VisitUnaryOperator(UnaryOperator const * expr)
    { return Visit(expr->getSubExpr()); }

    bool VisitBinaryOperator(BinaryOperator const * expr) {
        return Visit(expr->getLHS()) && Visit(expr->getRHS());
    }

    bool VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr const *) {
        return true;
    }
};

Noel Grandin's avatar
Noel Grandin committed
74
class OnceVar:
75
    public loplugin::FilteringPlugin<OnceVar>
Noel Grandin's avatar
Noel Grandin committed
76 77
{
public:
78
    explicit OnceVar(loplugin::InstantiationData const & data): FilteringPlugin(data) {}
Noel Grandin's avatar
Noel Grandin committed
79 80 81

    virtual void run() override {
        // ignore some files with problematic macros
82
        std::string fn(handler.getMainFileName());
83
        loplugin::normalizeDotDotInFilePath(fn);
Noel Grandin's avatar
Noel Grandin committed
84 85 86 87 88 89 90 91 92
        // platform-specific stuff
        if (fn == SRCDIR "/sal/osl/unx/thread.cxx"
            || fn == SRCDIR "/sot/source/base/formats.cxx"
            || fn == SRCDIR "/svl/source/config/languageoptions.cxx"
            || fn == SRCDIR "/sfx2/source/appl/appdde.cxx"
            || fn == SRCDIR "/configmgr/source/components.cxx"
            || fn == SRCDIR "/embeddedobj/source/msole/oleembed.cxx")
             return;
        // some of this is necessary
Noel Grandin's avatar
Noel Grandin committed
93
        if (loplugin::hasPathnamePrefix( fn, SRCDIR "/sal/qa/"))
Noel Grandin's avatar
Noel Grandin committed
94
             return;
Noel Grandin's avatar
Noel Grandin committed
95
        if (loplugin::hasPathnamePrefix( fn, SRCDIR "/comphelper/qa/"))
Noel Grandin's avatar
Noel Grandin committed
96 97 98 99 100 101 102 103 104 105 106 107 108
             return;
        // TODO need to check calls via function pointer
        if (fn == SRCDIR "/i18npool/source/textconversion/textconversion_zh.cxx"
            || fn == SRCDIR "/i18npool/source/localedata/localedata.cxx")
             return;
        // debugging stuff
        if (fn == SRCDIR "/sc/source/core/data/dpcache.cxx"
            || fn == SRCDIR "/sw/source/core/layout/dbg_lay.cxx"
            || fn == SRCDIR "/sw/source/core/layout/ftnfrm.cxx")
             return;
        // TODO taking local reference to variable
        if (fn == SRCDIR "/sc/source/filter/excel/xechart.cxx")
             return;
Noel Grandin's avatar
Noel Grandin committed
109 110 111
        // macros managing to generate to a valid warning
        if (fn == SRCDIR "/solenv/bin/concat-deps.c")
             return;
Noel Grandin's avatar
Noel Grandin committed
112 113 114
        // TODO bug in the plugin
        if (fn == SRCDIR "/vcl/unx/generic/app/saldisp.cxx")
            return;
Noel Grandin's avatar
Noel Grandin committed
115

Noel Grandin's avatar
Noel Grandin committed
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
        TraverseDecl(compiler.getASTContext().getTranslationUnitDecl());

        for (auto const & varDecl : maVarDeclSet)
        {
            if (maVarDeclToIgnoreSet.find(varDecl) != maVarDeclToIgnoreSet.end())
                continue;
            int noUses = 0;
            auto it = maVarUsesMap.find(varDecl);
            if (it != maVarUsesMap.end())
                noUses = it->second;
            if (noUses > 1)
                continue;
            report(DiagnosticsEngine::Warning,
                   "var used only once, should be inlined or declared const",
                   varDecl->getLocation())
                << varDecl->getSourceRange();
            if (it != maVarUsesMap.end())
                report(DiagnosticsEngine::Note,
                       "used here",
                       maVarUseSourceRangeMap[varDecl].getBegin())
                    << maVarUseSourceRangeMap[varDecl];
        }
    }

140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
    bool VisitMemberExpr(MemberExpr const * expr) {
        // ignore cases like:
        //     const OUString("xxx") xxx;
        //     rtl_something(xxx.pData);
        // where we cannot inline the declaration.
        if (isa<FieldDecl>(expr->getMemberDecl())) {
            recordIgnore(expr);
        }
        return true;
    }

    bool VisitUnaryOperator(UnaryOperator const * expr) {
        // if we take the address of it, or we modify it, ignore it
        UnaryOperator::Opcode op = expr->getOpcode();
        if (op == UO_AddrOf || op == UO_PreInc || op == UO_PostInc
            || op == UO_PreDec || op == UO_PostDec)
        {
            recordIgnore(expr->getSubExpr());
        }
        return true;
    }

    bool VisitBinaryOperator(BinaryOperator const * expr) {
        // if we assign it another value, or modify it, ignore it
        BinaryOperator::Opcode op = expr->getOpcode();
        if (op == BO_Assign || op == BO_PtrMemD || op == BO_PtrMemI || op == BO_MulAssign
            || op == BO_DivAssign || op == BO_RemAssign || op == BO_AddAssign
            || op == BO_SubAssign || op == BO_ShlAssign || op == BO_ShrAssign
            || op == BO_AndAssign || op == BO_XorAssign || op == BO_OrAssign)
        {
            recordIgnore(expr->getLHS());
        }
        return true;
    }

    bool VisitCallExpr(CallExpr const * expr) {
        unsigned firstArg = 0;
        if (auto const cmce = dyn_cast<CXXMemberCallExpr>(expr)) {
            if (auto const e1 = cmce->getMethodDecl()) {
                if (!(e1->isConst() || e1->isStatic())) {
                    recordIgnore(cmce->getImplicitObjectArgument());
                }
            } else if (auto const e2 = dyn_cast<BinaryOperator>(
                           cmce->getCallee()->IgnoreParenImpCasts()))
            {
                switch (e2->getOpcode()) {
                case BO_PtrMemD:
                case BO_PtrMemI:
                    if (!e2->getRHS()->getType()->getAs<MemberPointerType>()
                        ->getPointeeType()->getAs<FunctionProtoType>()
                        ->isConst())
                    {
                        recordIgnore(e2->getLHS());
                    }
                    break;
                default:
                    break;
                }
            }
        } else if (auto const coce = dyn_cast<CXXOperatorCallExpr>(expr)) {
            if (auto const cmd = dyn_cast_or_null<CXXMethodDecl>(
                    coce->getDirectCallee()))
            {
                if (!cmd->isStatic()) {
                    assert(coce->getNumArgs() != 0);
                    if (!cmd->isConst()) {
                        recordIgnore(coce->getArg(0));
                    }
                    firstArg = 1;
                }
            }
        }
        // ignore those ones we are passing by reference
        const FunctionDecl* calleeFunctionDecl = expr->getDirectCallee();
        if (calleeFunctionDecl) {
            for (unsigned i = firstArg; i < expr->getNumArgs(); ++i) {
                if (i < calleeFunctionDecl->getNumParams()) {
                    QualType qt { calleeFunctionDecl->getParamDecl(i)->getType() };
                    if (loplugin::TypeCheck(qt).LvalueReference().NonConst()) {
                        recordIgnore(expr->getArg(i));
                    }
Noel Grandin's avatar
Noel Grandin committed
221 222 223
                    if (loplugin::TypeCheck(qt).Pointer().NonConst()) {
                        recordIgnore(expr->getArg(i));
                    }
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
                }
            }
        }
        return true;
    }

    bool VisitCXXConstructExpr(CXXConstructExpr const * expr) {
        // ignore those ones we are passing by reference
        const CXXConstructorDecl* cxxConstructorDecl = expr->getConstructor();
        for (unsigned i = 0; i < expr->getNumArgs(); ++i) {
            if (i < cxxConstructorDecl->getNumParams()) {
                QualType qt { cxxConstructorDecl->getParamDecl(i)->getType() };
                if (loplugin::TypeCheck(qt).LvalueReference().NonConst()) {
                    recordIgnore(expr->getArg(i));
                }
Noel Grandin's avatar
Noel Grandin committed
239 240 241
                if (loplugin::TypeCheck(qt).Pointer().NonConst()) {
                    recordIgnore(expr->getArg(i));
                }
242 243 244 245 246
            }
        }
        return true;
    }

Noel Grandin's avatar
Noel Grandin committed
247 248
    bool VisitDeclRefExpr( const DeclRefExpr* );
    bool VisitVarDecl( const VarDecl* );
249
    bool TraverseFunctionDecl( FunctionDecl* functionDecl );
Noel Grandin's avatar
Noel Grandin committed
250 251 252 253 254 255

private:
    std::unordered_set<VarDecl const *> maVarDeclSet;
    std::unordered_set<VarDecl const *> maVarDeclToIgnoreSet;
    std::unordered_map<VarDecl const *, int> maVarUsesMap;
    std::unordered_map<VarDecl const *, SourceRange> maVarUseSourceRangeMap;
256 257 258 259 260

    bool isConstantValueDependentExpression(Expr const * expr) {
        return ConstantValueDependentExpressionVisitor(compiler.getASTContext())
            .Visit(expr);
    }
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292

    void recordIgnore(Expr const * expr) {
        for (;;) {
            expr = expr->IgnoreParenImpCasts();
            if (auto const e = dyn_cast<MemberExpr>(expr)) {
                if (isa<FieldDecl>(e->getMemberDecl())) {
                    expr = e->getBase();
                    continue;
                }
            }
            if (auto const e = dyn_cast<ArraySubscriptExpr>(expr)) {
                expr = e->getBase();
                continue;
            }
            if (auto const e = dyn_cast<BinaryOperator>(expr)) {
                if (e->getOpcode() == BO_PtrMemD) {
                    expr = e->getLHS();
                    continue;
                }
            }
            break;
        }
        auto const dre = dyn_cast<DeclRefExpr>(expr);
        if (dre == nullptr) {
            return;
        }
        auto const var = dyn_cast<VarDecl>(dre->getDecl());
        if (var == nullptr) {
            return;
        }
        maVarDeclToIgnoreSet.insert(var);
    }
Noel Grandin's avatar
Noel Grandin committed
293 294
};

295 296 297 298 299 300 301 302 303 304
bool OnceVar::TraverseFunctionDecl( FunctionDecl* functionDecl )
{
    // Ignore functions that contains #ifdef-ery, can be quite tricky
    // to make useful changes when this plugin fires in such functions
    if (containsPreprocessingConditionalInclusion(
            functionDecl->getSourceRange()))
        return true;
    return RecursiveASTVisitor::TraverseFunctionDecl(functionDecl);
}

Noel Grandin's avatar
Noel Grandin committed
305 306 307 308 309
bool OnceVar::VisitVarDecl( const VarDecl* varDecl )
{
    if (ignoreLocation(varDecl)) {
        return true;
    }
310 311 312
    if (auto const init = varDecl->getInit()) {
        recordIgnore(lookThroughInitListExpr(init));
    }
Noel Grandin's avatar
Noel Grandin committed
313 314 315 316 317 318 319 320
    if (varDecl->isExceptionVariable() || isa<ParmVarDecl>(varDecl)) {
        return true;
    }
    // ignore stuff in header files (which should really not be there, but anyhow)
    if (!compiler.getSourceManager().isInMainFile(varDecl->getLocation())) {
        return true;
    }
    // Ignore macros like FD_ZERO
321
    if (compiler.getSourceManager().isMacroBodyExpansion(compat::getBeginLoc(varDecl))) {
Noel Grandin's avatar
Noel Grandin committed
322 323 324 325 326 327
        return true;
    }
    if (varDecl->hasGlobalStorage()) {
        return true;
    }
    auto const tc = loplugin::TypeCheck(varDecl->getType());
Noel Grandin's avatar
Noel Grandin committed
328
    if (!varDecl->getType().isCXX11PODType(compiler.getASTContext())
Noel Grandin's avatar
Noel Grandin committed
329 330 331
        && !tc.Class("OString").Namespace("rtl").GlobalNamespace()
        && !tc.Class("OUString").Namespace("rtl").GlobalNamespace()
        && !tc.Class("OStringBuffer").Namespace("rtl").GlobalNamespace()
332 333 334 335 336 337 338 339
        && !tc.Class("OUStringBuffer").Namespace("rtl").GlobalNamespace()
        && !tc.Class("Color").GlobalNamespace()
        && !tc.Class("Pair").GlobalNamespace()
        && !tc.Class("Point").GlobalNamespace()
        && !tc.Class("Size").GlobalNamespace()
        && !tc.Class("Range").GlobalNamespace()
        && !tc.Class("Selection").GlobalNamespace()
        && !tc.Class("Rectangle").Namespace("tools").GlobalNamespace())
Noel Grandin's avatar
Noel Grandin committed
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
    {
        return true;
    }
    if (varDecl->getType()->isPointerType())
        return true;
    // if it's declared const, ignore it, it's there to make the code easier to read
    if (tc.Const())
        return true;

    if (!varDecl->hasInit())
        return true;

    // check for string or scalar literals
    bool foundStringLiteral = false;
    const Expr * initExpr = varDecl->getInit();
    if (auto e = dyn_cast<ExprWithCleanups>(initExpr)) {
        initExpr = e->getSubExpr();
    }
Noel Grandin's avatar
Noel Grandin committed
358
    if (isa<clang::StringLiteral>(initExpr)) {
Noel Grandin's avatar
Noel Grandin committed
359 360
        foundStringLiteral = true;
    } else if (auto constructExpr = dyn_cast<CXXConstructExpr>(initExpr)) {
361 362 363
        if (constructExpr->getNumArgs() == 0) {
            foundStringLiteral = true; // i.e., empty string
        } else {
Noel Grandin's avatar
Noel Grandin committed
364 365 366 367
            auto stringLit2 = dyn_cast<clang::StringLiteral>(constructExpr->getArg(0));
            foundStringLiteral = stringLit2 != nullptr;
        }
    }
368 369
    if (!foundStringLiteral) {
        auto const init = varDecl->getInit();
370 371 372 373
        if (!(init->isValueDependent()
              ? isConstantValueDependentExpression(init)
              : init->isConstantInitializer(
                  compiler.getASTContext(), false/*ForRef*/)))
374 375 376
        {
            return true;
        }
Noel Grandin's avatar
Noel Grandin committed
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
    }

    maVarDeclSet.insert(varDecl);

    return true;
}

bool OnceVar::VisitDeclRefExpr( const DeclRefExpr* declRefExpr )
{
    if (ignoreLocation(declRefExpr)) {
        return true;
    }
    const Decl* decl = declRefExpr->getDecl();
    if (!isa<VarDecl>(decl) || isa<ParmVarDecl>(decl)) {
        return true;
    }
    const VarDecl * varDecl = dyn_cast<VarDecl>(decl)->getCanonicalDecl();
    // ignore stuff in header files (which should really not be there, but anyhow)
    if (!compiler.getSourceManager().isInMainFile(varDecl->getLocation())) {
        return true;
    }

    if (maVarUsesMap.find(varDecl) == maVarUsesMap.end()) {
        maVarUsesMap[varDecl] = 1;
        maVarUseSourceRangeMap[varDecl] = declRefExpr->getSourceRange();
    } else {
        maVarUsesMap[varDecl]++;
    }

    return true;
}

409
loplugin::Plugin::Registration< OnceVar > X("oncevar", false);
Noel Grandin's avatar
Noel Grandin committed
410 411 412 413

}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */