unnecessaryvirtual.cxx 7.26 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
/* -*- 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>
13
#include <set>
14
#include <unordered_set>
15
#include "plugin.hxx"
16
#include <fstream>
17 18 19 20 21

/**
Dump a list of virtual methods and a list of methods overriding virtual methods.
Then we will post-process the 2 lists and find the set of virtual methods which don't need to be virtual.

22 23 24
Also, we look for virtual methods where the bodies of all the overrides are empty i.e. this is leftover code
that no longer has a purpose.

25 26
The process goes something like this:
  $ make check
27
  $ make FORCE_COMPILE_ALL=1 COMPILER_PLUGIN_TOOL='unnecessaryvirtual' check
28
  $ ./compilerplugins/clang/unnecessaryvirtual.py
29
  $ for dir in *; do make FORCE_COMPILE_ALL=1 UPDATE_FILES=$dir COMPILER_PLUGIN_TOOL='removevirtuals' $dir; done
30 31 32

Note that the actual process may involve a fair amount of undoing, hand editing, and general messing around
to get it to work :-)
33 34

TODO some boost bind stuff appears to confuse it, notably in the xmloff module
35 36 37 38
*/

namespace {

39 40 41 42 43 44 45 46 47 48 49
struct MyFuncInfo
{
    std::string name;
    std::string sourceLocation;

};
bool operator < (const MyFuncInfo &lhs, const MyFuncInfo &rhs)
{
    return lhs.name < rhs.name;
}

50
// try to limit the voluminous output a little
51
static std::set<MyFuncInfo> definitionSet;
52 53
static std::unordered_set<std::string> overridingSet;
static std::unordered_set<std::string> nonEmptySet;
54

55 56 57 58
class UnnecessaryVirtual:
    public RecursiveASTVisitor<UnnecessaryVirtual>, public loplugin::Plugin
{
public:
59 60
    explicit UnnecessaryVirtual(loplugin::InstantiationData const & data):
        Plugin(data) {}
61

62 63 64 65 66 67 68
    virtual void run() override
    {
        TraverseDecl(compiler.getASTContext().getTranslationUnitDecl());

        // dump all our output in one write call - this is to try and limit IO "crosstalk" between multiple processes
        // writing to the same logfile
        std::string output;
69 70
        for (const MyFuncInfo & s : definitionSet)
            output += "definition:\t" + s.name + "\t" + s.sourceLocation + "\n";
71 72
        for (const std::string & s : overridingSet)
            output += "overriding:\t" + s + "\n";
73 74
        for (const std::string & s : nonEmptySet)
            output += "nonempty:\t" + s + "\n";
75
        std::ofstream myfile;
76
        myfile.open( WORKDIR "/loplugin.unnecessaryvirtual.log", std::ios::app | std::ios::out);
77 78 79 80
        myfile << output;
        myfile.close();
    }
    bool shouldVisitTemplateInstantiations () const { return true; }
81
    bool shouldVisitImplicitCode() const { return true; }
82

83
    bool VisitCXXMethodDecl( const CXXMethodDecl* decl );
84
private:
85
    void MarkRootOverridesNonEmpty( const CXXMethodDecl* methodDecl );
86
    std::string toString(SourceLocation loc);
87 88
};

89
std::string niceName(const CXXMethodDecl* cxxMethodDecl)
90
{
91 92 93 94 95 96
    while (cxxMethodDecl->getTemplateInstantiationPattern())
        cxxMethodDecl = dyn_cast<CXXMethodDecl>(cxxMethodDecl->getTemplateInstantiationPattern());
    while (cxxMethodDecl->getInstantiatedFromMemberFunction())
        cxxMethodDecl = dyn_cast<CXXMethodDecl>(cxxMethodDecl->getInstantiatedFromMemberFunction());
    std::string s = cxxMethodDecl->getReturnType().getCanonicalType().getAsString()
        + " " + cxxMethodDecl->getQualifiedNameAsString() + "(";
97
    for (const ParmVarDecl *pParmVarDecl : cxxMethodDecl->parameters()) {
98
        s += pParmVarDecl->getType().getCanonicalType().getAsString();
99 100 101
        s += ",";
    }
    s += ")";
102
    if (cxxMethodDecl->isConst()) {
103 104 105 106 107
        s += "const";
    }
    return s;
}

108
bool UnnecessaryVirtual::VisitCXXMethodDecl( const CXXMethodDecl* methodDecl )
109
{
110 111 112
    if (ignoreLocation(methodDecl)) {
        return true;
    }
113
    if (!methodDecl->isVirtual() || methodDecl->isDeleted()) {
114 115 116
        return true;
    }
    // ignore stuff that forms part of the stable URE interface
117
    if (isInUnoIncludeFile(methodDecl->getCanonicalDecl())) {
118 119
        return true;
    }
120

121 122 123 124 125 126 127 128 129 130 131 132 133
    auto body = methodDecl->getBody();
    if (body) {
        auto compoundStmt = dyn_cast<CompoundStmt>(body);
        if (!compoundStmt)
            MarkRootOverridesNonEmpty(methodDecl->getCanonicalDecl());
        else if (compoundStmt->size() > 0)
            MarkRootOverridesNonEmpty(methodDecl->getCanonicalDecl());
    }

    if (!methodDecl->isThisDeclarationADefinition())
        return true;

    methodDecl = methodDecl->getCanonicalDecl();
134
    std::string aNiceName = niceName(methodDecl);
135 136

    // for destructors, we need to check if any of the superclass' destructors are virtual
137
    if (isa<CXXDestructorDecl>(methodDecl)) {
138 139 140 141
        const CXXRecordDecl* cxxRecordDecl = methodDecl->getParent();
        if (cxxRecordDecl->getNumBases() == 0) {
            definitionSet.insert( { aNiceName, toString( methodDecl->getLocation() ) } );
            return true;
142
        }
143 144
        for(auto baseSpecifier = cxxRecordDecl->bases_begin();
            baseSpecifier != cxxRecordDecl->bases_end(); ++baseSpecifier)
145 146 147
        {
            if (baseSpecifier->getType()->isRecordType())
            {
148 149 150
                const CXXRecordDecl* superclassCXXRecordDecl = baseSpecifier->getType()->getAsCXXRecordDecl();
                std::string aOverriddenNiceName = niceName(superclassCXXRecordDecl->getDestructor());
                overridingSet.insert(aOverriddenNiceName);
151 152
            }
        }
153 154
        return true;
    }
155

156
    if (methodDecl->size_overridden_methods() == 0) {
157
        definitionSet.insert( { aNiceName, toString( methodDecl->getLocation() ) } );
158
    } else {
159 160
       for (auto iter = methodDecl->begin_overridden_methods();
            iter != methodDecl->end_overridden_methods(); ++iter)
161
       {
162
           const CXXMethodDecl *overriddenMethod = *iter;
163
           // we only care about the first level override to establish that a virtual qualifier was useful.
164 165
           if (overriddenMethod->isPure() || overriddenMethod->size_overridden_methods() == 0)
           {
166 167
               std::string aOverriddenNiceName = niceName(overriddenMethod);
               overridingSet.insert(aOverriddenNiceName);
168
           }
169
        }
170 171 172 173
    }
    return true;
}

174 175 176 177 178 179 180 181 182 183 184 185 186
void UnnecessaryVirtual::MarkRootOverridesNonEmpty( const CXXMethodDecl* methodDecl )
{
    if (methodDecl->size_overridden_methods() == 0) {
        nonEmptySet.insert(niceName(methodDecl));
        return;
    }
    for (auto iter = methodDecl->begin_overridden_methods();
          iter != methodDecl->end_overridden_methods(); ++iter)
    {
        MarkRootOverridesNonEmpty(*iter);
    }
}

187
std::string UnnecessaryVirtual::toString(SourceLocation loc)
188
{
189 190 191
    SourceLocation expansionLoc = compiler.getSourceManager().getExpansionLoc( loc );
    StringRef name = compiler.getSourceManager().getFilename(expansionLoc);
    std::string sourceLocation = std::string(name.substr(strlen(SRCDIR)+1)) + ":" + std::to_string(compiler.getSourceManager().getSpellingLineNumber(expansionLoc));
192
    loplugin::normalizeDotDotInFilePath(sourceLocation);
193
    return sourceLocation;
194 195
}

196 197 198 199 200 201

loplugin::Plugin::Registration< UnnecessaryVirtual > X("unnecessaryvirtual", false);

}

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