1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 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
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
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
409
410
411
412
413
/* -*- 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/.
 */

#include <cassert>
#include <string>
#include <iostream>
#include <unordered_map>
#include <unordered_set>

#include "plugin.hxx"
#include "check.hxx"
#include "clang/AST/CXXInheritance.h"
#include "clang/AST/StmtVisitor.h"

// 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
{

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;
}

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)<--- The function 'VisitParenExpr' is never used.
    { return Visit(expr->getSubExpr()); }

    bool VisitCastExpr(CastExpr const * expr) {<--- The function 'VisitCastExpr' is never used.
        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 *) {<--- The function 'VisitUnaryExprOrTypeTraitExpr' is never used.
        return true;
    }
};

class OnceVar:
    public loplugin::FilteringPlugin<OnceVar>
{
public:
    explicit OnceVar(loplugin::InstantiationData const & data): FilteringPlugin(data) {}

    virtual void run() override {
        // ignore some files with problematic macros
        std::string fn(handler.getMainFileName());
        loplugin::normalizeDotDotInFilePath(fn);
        // 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
        if (loplugin::hasPathnamePrefix( fn, SRCDIR "/sal/qa/"))
             return;
        if (loplugin::hasPathnamePrefix( fn, SRCDIR "/comphelper/qa/"))
             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")<--- If condition 'fn==SRCDIR' is true, the function will return/exit
             return;
        // macros managing to generate to a valid warning
        if (fn == SRCDIR "/solenv/bin/concat-deps.c")<--- Testing identical condition 'fn==SRCDIR'<--- If condition 'fn==SRCDIR' is true, the function will return/exit
             return;
        // TODO bug in the plugin
        if (fn == SRCDIR "/vcl/unx/generic/app/saldisp.cxx")<--- Testing identical condition 'fn==SRCDIR'
            return;

        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];
        }
    }

    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));
                    }
                    if (loplugin::TypeCheck(qt).Pointer().NonConst()) {
                        recordIgnore(expr->getArg(i));
                    }
                }
            }
        }
        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));
                }
                if (loplugin::TypeCheck(qt).Pointer().NonConst()) {
                    recordIgnore(expr->getArg(i));
                }
            }
        }
        return true;
    }

    bool VisitDeclRefExpr( const DeclRefExpr* );
    bool VisitVarDecl( const VarDecl* );
    bool TraverseFunctionDecl( FunctionDecl* functionDecl );

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;

    bool isConstantValueDependentExpression(Expr const * expr) {
        return ConstantValueDependentExpressionVisitor(compiler.getASTContext())
            .Visit(expr);
    }

    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);
    }
};

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);
}

bool OnceVar::VisitVarDecl( const VarDecl* varDecl )
{
    if (ignoreLocation(varDecl)) {
        return true;
    }
    if (auto const init = varDecl->getInit()) {
        recordIgnore(lookThroughInitListExpr(init));
    }
    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
    if (compiler.getSourceManager().isMacroBodyExpansion(compat::getBeginLoc(varDecl))) {
        return true;
    }
    if (varDecl->hasGlobalStorage()) {
        return true;
    }
    auto const tc = loplugin::TypeCheck(varDecl->getType());
    if (!varDecl->getType().isCXX11PODType(compiler.getASTContext())
        && !tc.Class("OString").Namespace("rtl").GlobalNamespace()
        && !tc.Class("OUString").Namespace("rtl").GlobalNamespace()
        && !tc.Class("OStringBuffer").Namespace("rtl").GlobalNamespace()
        && !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())
    {
        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();
    }
    if (isa<clang::StringLiteral>(initExpr)) {
        foundStringLiteral = true;
    } else if (auto constructExpr = dyn_cast<CXXConstructExpr>(initExpr)) {
        if (constructExpr->getNumArgs() == 0) {
            foundStringLiteral = true; // i.e., empty string
        } else {
            auto stringLit2 = dyn_cast<clang::StringLiteral>(constructExpr->getArg(0));
            foundStringLiteral = stringLit2 != nullptr;
        }
    }
    if (!foundStringLiteral) {
        auto const init = varDecl->getInit();
        if (!(init->isValueDependent()
              ? isConstantValueDependentExpression(init)
              : init->isConstantInitializer(
                  compiler.getASTContext(), false/*ForRef*/)))
        {
            return true;
        }
    }

    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;
}

loplugin::Plugin::Registration< OnceVar > X("oncevar", false);

}

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