summaryrefslogtreecommitdiffstats
path: root/compilerplugins/clang/moveit.cxx
blob: 353359e284050440ddef005ab62009ec20d48887 (plain)
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
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * Based on LLVM/Clang.
 *
 * This file is distributed under the University of Illinois Open Source
 * License. See LICENSE.TXT for details.
 *
 */

#include <cassert>
#include <string>
#include <iostream>
#include <fstream>
#include "config_clang.h"
#include "plugin.hxx"
#include "check.hxx"

/*
Look for local variables that can be std::move'd into parameters.

TODO
(*) Ideally we would use a proper data-flow analysis, to detect that the var is dead after this point,
     like the one in clang at include/clang/Analysis/CFG.h
(*) we could expand the set of approved/interesting types
*/

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

    virtual bool preRun() override
    {
        std::string fn(handler.getMainFileName());
        loplugin::normalizeDotDotInFilePath(fn);
        // false +
        if (loplugin::hasPathnamePrefix(fn, SRCDIR "/basic/source/classes/sbunoobj.cxx"))
            return false;
        if (loplugin::hasPathnamePrefix(fn, SRCDIR "/svx/source/svdraw/textchainflow.cxx"))
            return false;
        if (loplugin::hasPathnamePrefix(fn, SRCDIR "/svx/source/unodraw/unoshtxt.cxx"))
            return false;
        if (loplugin::hasPathnamePrefix(fn,
                                        SRCDIR "/connectivity/source/drivers/dbase/dindexnode.cxx"))
            return false;
        if (loplugin::hasPathnamePrefix(fn, SRCDIR "/basctl/source/basicide/moduldlg.cxx"))
            return false;
        if (loplugin::hasPathnamePrefix(fn, SRCDIR "/sw/source/core/SwNumberTree/SwNumberTree.cxx"))
            return false;
        if (loplugin::hasPathnamePrefix(fn, SRCDIR "/sc/source/core/tool/scmatrix.cxx"))
            return false;
        if (loplugin::hasPathnamePrefix(fn, SRCDIR "/sw/source/core/bastyp/calc.cxx"))
            return false;
        if (loplugin::hasPathnamePrefix(fn, SRCDIR "/sw/source/core/edit/edattr.cxx"))
            return false;
        if (loplugin::hasPathnamePrefix(fn, SRCDIR "/sw/source/core/fields/expfld.cxx"))
            return false;
        if (loplugin::hasPathnamePrefix(fn, SRCDIR "/sw/source/uibase/docvw/edtwin.cxx"))
            return false;
        if (loplugin::hasPathnamePrefix(fn, SRCDIR "/sw/source/uibase/uiview/viewling.cxx"))
            return false;
        if (loplugin::hasPathnamePrefix(
                fn, SRCDIR "/writerfilter/source/dmapper/DomainMapperTableHandler.cxx"))
            return false;
        return true;
    }

    virtual void run() override
    {
        if (preRun())
            TraverseDecl(compiler.getASTContext().getTranslationUnitDecl());
    }

    bool VisitCXXMemberCallExpr(const CXXMemberCallExpr*);
    bool VisitCXXConstructExpr(const CXXConstructExpr*);

private:
    bool isInterestingType(QualType);
};

bool MoveIt::VisitCXXMemberCallExpr(const CXXMemberCallExpr* topExpr)
{
    if (ignoreLocation(topExpr))
        return true;
    const CXXMethodDecl* methodDecl = topExpr->getMethodDecl();
    if (!methodDecl)
        return true;

    unsigned len = std::min(topExpr->getNumArgs(), methodDecl->getNumParams());
    for (unsigned i = 0; i < len; ++i)
    {
        // check if the parameter is a moveable type
        const ParmVarDecl* parmVarDecl = methodDecl->getParamDecl(i);
        if (!parmVarDecl->getType()->isRecordType())
            continue;
        const CXXRecordDecl* recordDecl
            = dyn_cast<CXXRecordDecl>(parmVarDecl->getType()->getAsRecordDecl());
        if (!recordDecl || !recordDecl->hasMoveConstructor() || recordDecl->isTriviallyCopyable())
            continue;
        if (!isInterestingType(parmVarDecl->getType()))
            continue;

        // check if (a) we're making a copy to pass to the param and (b) we're making a copy of a local var
        const Expr* argExpr = topExpr->getArg(i);
        if (!argExpr)
            continue;
        const CXXConstructExpr* argSubExpr = dyn_cast<CXXConstructExpr>(argExpr->IgnoreImplicit());
        if (!argSubExpr || argSubExpr->getNumArgs() == 0)
            continue;
        const DeclRefExpr* dre = dyn_cast<DeclRefExpr>(argSubExpr->getArg(0)->IgnoreImplicit());
        if (!dre)
            continue;
        const VarDecl* localVarDecl = dyn_cast<VarDecl>(dre->getDecl());
        if (!localVarDecl || localVarDecl->getType()->isReferenceType()
            || localVarDecl->getType()->isPointerType() || !localVarDecl->hasLocalStorage())
            continue;
        // because sometimes the parameter type is some obscured STL thing
        if (!isInterestingType(localVarDecl->getType()))
            continue;

        report(DiagnosticsEngine::Warning, "can std::move this var into this param",
               argExpr->getBeginLoc());
        report(DiagnosticsEngine::Note, "passing to this param", parmVarDecl->getBeginLoc());
        report(DiagnosticsEngine::Note, "local var declared here", localVarDecl->getBeginLoc());
        report(DiagnosticsEngine::Note, "type declared here", recordDecl->getBeginLoc());
        //        parmVarDecl->getType()->dump();
    }

    //    StringRef aFileName = getFilenameOfLocation(
    //        compiler.getSourceManager().getSpellingLoc(parmVarDecl->getBeginLoc()));
    //    if (loplugin::hasPathnamePrefix(aFileName,
    //                                    SRCDIR "/svx/source/sidebar/line/LineWidthValueSet.cxx"))
    //        return true;

    return true;
}

bool MoveIt::VisitCXXConstructExpr(const CXXConstructExpr* topExpr)
{
    if (ignoreLocation(topExpr))
        return true;
    if (isa<CXXTemporaryObjectExpr>(topExpr))
        return true;
    const CXXConstructorDecl* methodDecl = topExpr->getConstructor();
    if (!methodDecl)
        return true;

    unsigned len = std::min(topExpr->getNumArgs(), methodDecl->getNumParams());
    for (unsigned i = 0; i < len; ++i)
    {
        // check if the parameter is a moveable type
        const ParmVarDecl* parmVarDecl = methodDecl->getParamDecl(i);
        if (!parmVarDecl->getType()->isRecordType())
            continue;
        const CXXRecordDecl* recordDecl
            = dyn_cast<CXXRecordDecl>(parmVarDecl->getType()->getAsRecordDecl());
        if (!recordDecl || !recordDecl->hasMoveConstructor() || recordDecl->isTriviallyCopyable())
            continue;
        if (!isInterestingType(parmVarDecl->getType()))
            continue;

        // check if (a) we're making a copy to pass to the param and (b) we're making a copy of a local var
        const Expr* argExpr = topExpr->getArg(i);
        if (!argExpr)
            continue;
        const CXXConstructExpr* argSubExpr = dyn_cast<CXXConstructExpr>(argExpr->IgnoreImplicit());
        if (!argSubExpr || argSubExpr->getNumArgs() == 0)
            continue;
        const DeclRefExpr* dre = dyn_cast<DeclRefExpr>(argSubExpr->getArg(0)->IgnoreImplicit());
        if (!dre)
            continue;
        const VarDecl* localVarDecl = dyn_cast<VarDecl>(dre->getDecl());
        if (!localVarDecl || localVarDecl->getType()->isReferenceType()
            || localVarDecl->getType()->isPointerType() || !localVarDecl->hasLocalStorage())
            continue;
        // because sometimes the parameter type is some obscured STL thing
        if (!isInterestingType(localVarDecl->getType()))
            continue;

        report(DiagnosticsEngine::Warning, "can std::move this var into this param",
               argExpr->getBeginLoc());
        report(DiagnosticsEngine::Note, "passing to this param", parmVarDecl->getBeginLoc());
        report(DiagnosticsEngine::Note, "local var declared here", localVarDecl->getBeginLoc());
        report(DiagnosticsEngine::Note, "type declared here", recordDecl->getBeginLoc());
        //        parmVarDecl->getType()->dump();
    }

    //    StringRef aFileName = getFilenameOfLocation(
    //        compiler.getSourceManager().getSpellingLoc(parmVarDecl->getBeginLoc()));
    //    if (loplugin::hasPathnamePrefix(aFileName,
    //                                    SRCDIR "/svx/source/sidebar/line/LineWidthValueSet.cxx"))
    //        return true;

    return true;
}

/// Exclude boring types, so that we don't generate too many low-value conversions.
/// e.g. for now I ignore ref-counted types like Sequence and OUString and css::uno::Reference,
/// because that generates too many changes
bool MoveIt::isInterestingType(QualType qt)
{
    if (qt->isEnumeralType())
        return false;
    if (!qt->isRecordType())
        return false;

    auto tc = loplugin::TypeCheck(qt);

    // clang-format off
    return !tc.ClassOrStruct("iterator")
           && !tc.ClassOrStruct("const_iterator")
           && !tc.Typedef("iterator")
           && !tc.Typedef("const_iterator")
           && !tc.Class("_Safe_iterator")
           && !tc.Typedef("string")
           && !tc.ClassOrStruct("shared_ptr").StdNamespace()
           && !tc.ClassOrStruct("shared_ptr").Namespace("boost")
           && !tc.Class("B2DHomMatrix").Namespace("basegfx").GlobalNamespace()
           && !tc.Class("Pipe").Namespace("osl")
           && !tc.Class("Any").Namespace("uno")
           && !tc.Class("TypeDescription").Namespace("uno")
           && !tc.Class("UnoInterfaceReference").Namespace("uno")
           && !tc.Class("ByteSequence").Namespace("rtl").GlobalNamespace()
           && !tc.Class("OUString").Namespace("rtl").GlobalNamespace()
           && !tc.Class("OString").Namespace("rtl").GlobalNamespace()
           && !tc.Class("BinaryAny")
           && !tc.Class("Reference")
           && !tc.Class("SvRef").Namespace("tools").GlobalNamespace()
           && !tc.ClassOrStruct("sk_sp") // skia shared pointer
           && !tc.ClassOrStruct("VclPtr")
           && !tc.Typedef("IterString") // SalInstanceTreeView::IterString
           && !tc.Typedef("svtree_render_args")
           && !tc.Typedef("render_args") // weld::ComboBox::render_args
           ;
    // clang-format on
}

/// off by default because each warning needs to be hand checked to ensure it is not a false+
loplugin::Plugin::Registration<MoveIt> moveit("moveit", false);

} // namespace

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