summaryrefslogtreecommitdiff
path: root/compilerplugins/clang/casttovoid.cxx
blob: e6da5b6d7445f4e791480ebd9842155ca68e0f62 (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
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */
/*
 * 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 <algorithm>
#include <cassert>
#include <map>
#include <stack>

#include "clang/AST/Attr.h"

#include "check.hxx"
#include "compat.hxx"
#include "plugin.hxx"

namespace {

bool isWarnUnusedType(QualType type) {
    if (auto const t = type->getAs<TypedefType>()) {
        if (t->getDecl()->hasAttr<WarnUnusedAttr>()) {
            return true;
        }
    }
    if (auto const t = type->getAs<RecordType>()) {
        if (t->getDecl()->hasAttr<WarnUnusedAttr>()) {
            return true;
        }
    }
    return loplugin::isExtraWarnUnusedType(type);
}

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 CastToVoid final:
    public loplugin::FilteringPlugin<CastToVoid>
{
public:
    explicit CastToVoid(loplugin::InstantiationData const & data):
        FilteringPlugin(data) {}

    bool TraverseCStyleCastExpr(CStyleCastExpr * expr) {
        auto const dre = checkCast(expr);
        if (dre != nullptr) {
            castToVoid_.push({expr, dre});
        }
        auto const ret = RecursiveASTVisitor::TraverseCStyleCastExpr(expr);
        if (dre != nullptr) {
            assert(!castToVoid_.empty());
            assert(castToVoid_.top().cast == expr);
            assert(castToVoid_.top().sub == dre);
            castToVoid_.pop();
        }
        return ret;
    }

    bool TraverseCXXStaticCastExpr(CXXStaticCastExpr * expr) {
        auto const dre = checkCast(expr);
        if (dre != nullptr) {
            castToVoid_.push({expr, dre});
        }
        auto const ret = RecursiveASTVisitor::TraverseCXXStaticCastExpr(expr);
        if (dre != nullptr) {
            assert(!castToVoid_.empty());
            assert(castToVoid_.top().cast == expr);
            assert(castToVoid_.top().sub == dre);
            castToVoid_.pop();
        }
        return ret;
    }

    bool TraverseCXXFunctionalCastExpr(CXXFunctionalCastExpr * expr) {
        auto const dre = checkCast(expr);
        if (dre != nullptr) {
            castToVoid_.push({expr, dre});
        }
        auto const ret = RecursiveASTVisitor::TraverseCXXFunctionalCastExpr(
            expr);
        if (dre != nullptr) {
            assert(!castToVoid_.empty());
            assert(castToVoid_.top().cast == expr);
            assert(castToVoid_.top().sub == dre);
            castToVoid_.pop();
        }
        return ret;
    }

    bool TraverseFunctionDecl(FunctionDecl * decl) {
        returnTypes_.push(decl->getReturnType());
        auto const ret = RecursiveASTVisitor::TraverseFunctionDecl(decl);
        assert(!returnTypes_.empty());
        assert(returnTypes_.top() == decl->getReturnType());
        returnTypes_.pop();
        return ret;
    }

    bool TraverseCXXDeductionGuideDecl(CXXDeductionGuideDecl * decl) {
        returnTypes_.push(decl->getReturnType());
        auto const ret = RecursiveASTVisitor::TraverseCXXDeductionGuideDecl(
            decl);
        assert(!returnTypes_.empty());
        assert(returnTypes_.top() == decl->getReturnType());
        returnTypes_.pop();
        return ret;
    }

    bool TraverseCXXMethodDecl(CXXMethodDecl * decl) {
        returnTypes_.push(decl->getReturnType());
        auto const ret = RecursiveASTVisitor::TraverseCXXMethodDecl(decl);
        assert(!returnTypes_.empty());
        assert(returnTypes_.top() == decl->getReturnType());
        returnTypes_.pop();
        return ret;
    }

    bool TraverseCXXConstructorDecl(CXXConstructorDecl * decl) {
        returnTypes_.push(decl->getReturnType());
        auto const ret = RecursiveASTVisitor::TraverseCXXConstructorDecl(decl);
        assert(!returnTypes_.empty());
        assert(returnTypes_.top() == decl->getReturnType());
        returnTypes_.pop();
        return ret;
    }

    bool TraverseCXXDestructorDecl(CXXDestructorDecl * decl) {
        returnTypes_.push(decl->getReturnType());
        auto const ret = RecursiveASTVisitor::TraverseCXXDestructorDecl(decl);
        assert(!returnTypes_.empty());
        assert(returnTypes_.top() == decl->getReturnType());
        returnTypes_.pop();
        return ret;
    }

    bool TraverseCXXConversionDecl(CXXConversionDecl * decl) {
        returnTypes_.push(decl->getReturnType());
        auto const ret = RecursiveASTVisitor::TraverseCXXConversionDecl(decl);
        assert(!returnTypes_.empty());
        assert(returnTypes_.top() == decl->getReturnType());
        returnTypes_.pop();
        return ret;
    }

    bool TraverseObjCMethodDecl(ObjCMethodDecl * decl) {
        returnTypes_.push(decl->getReturnType());
        auto const ret = RecursiveASTVisitor::TraverseObjCMethodDecl(decl);
        assert(!returnTypes_.empty());
        assert(returnTypes_.top() == decl->getReturnType());
        returnTypes_.pop();
        return ret;
    }

    bool TraverseConstructorInitializer(CXXCtorInitializer * init) {
        if (auto const field = init->getAnyMember()) {
            if (loplugin::TypeCheck(field->getType()).LvalueReference()) {
                recordConsumption(lookThroughInitListExpr(init->getInit()));
            }
        }
        return RecursiveASTVisitor::TraverseConstructorInitializer(init);
    }

    bool VisitDeclRefExpr(DeclRefExpr const * expr) {
        if (ignoreLocation(expr)) {
            return true;
        }
        auto const var = dyn_cast<VarDecl>(expr->getDecl());
        if (var == nullptr) {
            return true;
        }
        auto & usage = vars_[var->getCanonicalDecl()];
        if (!castToVoid_.empty() && castToVoid_.top().sub == expr) {
            usage.castToVoid.push_back(castToVoid_.top().cast);
        } else {
            usage.mentioned = true;
        }
        return true;
    }

    bool VisitImplicitCastExpr(ImplicitCastExpr const * expr) {
        if (ignoreLocation(expr)) {
            return true;
        }
        if (expr->getCastKind() != CK_LValueToRValue) {
            return true;
        }
        recordConsumption(expr->getSubExpr());
        return true;
    }

    bool VisitCallExpr(CallExpr const * expr) {
        if (ignoreLocation(expr)) {
            return true;
        }
        unsigned firstArg = 0;
        if (auto const cmce = dyn_cast<CXXMemberCallExpr>(expr)) {
            if (auto const e1 = cmce->getMethodDecl()) {
                if (e1->isConst() || e1->isStatic()) {
                    recordConsumption(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())
                    {
                        recordConsumption(e2->getLHS());
                    }
                    break;
                default:
                    break;
                }
            }
        } else if (isa<CXXOperatorCallExpr>(expr)) {
            if (auto const cmd = dyn_cast_or_null<CXXMethodDecl>(
                    expr->getDirectCallee()))
            {
                if (!cmd->isStatic()) {
                    assert(expr->getNumArgs() != 0);
                    if (cmd->isConst()) {
                        recordConsumption(expr->getArg(0));
                    }
                    firstArg = 1;
                }
            }
        }
        auto fun = expr->getDirectCallee();
        if (fun == nullptr) {
            return true;
        }
        unsigned const n = std::min(fun->getNumParams(), expr->getNumArgs());
        for (unsigned i = firstArg; i < n; ++i) {
            if (!loplugin::TypeCheck(fun->getParamDecl(i)->getType())
                .LvalueReference().Const())
            {
                continue;
            }
            recordConsumption(lookThroughInitListExpr(expr->getArg(i)));
        }
        return true;
    }

    bool VisitCXXConstructExpr(CXXConstructExpr const * expr) {
        if (ignoreLocation(expr)) {
            return true;
        }
        auto const ctor = expr->getConstructor();
        unsigned const n = std::min(ctor->getNumParams(), expr->getNumArgs());
        for (unsigned i = 0; i != n; ++i) {
            if (!loplugin::TypeCheck(ctor->getParamDecl(i)->getType())
                .LvalueReference().Const())
            {
                continue;
            }
            recordConsumption(lookThroughInitListExpr(expr->getArg(i)));
        }
        return true;
    }

    bool VisitReturnStmt(ReturnStmt const * stmt) {
        if (ignoreLocation(stmt)) {
            return true;
        }
        assert(!returnTypes_.empty());
        if (!loplugin::TypeCheck(returnTypes_.top()).LvalueReference().Const())
        {
            return true;
        }
        auto const ret = stmt->getRetValue();
        if (ret == nullptr) {
            return true;
        }
        recordConsumption(lookThroughInitListExpr(ret));
        return true;
    }

    bool VisitVarDecl(VarDecl const * decl) {
        if (ignoreLocation(decl)) {
            return true;
        }
        if (!loplugin::TypeCheck(decl->getType()).LvalueReference()) {
            return true;
        }
        auto const init = decl->getInit();
        if (init == nullptr) {
            return true;
        }
        recordConsumption(lookThroughInitListExpr(init));
        return true;
    }

    bool VisitFieldDecl(FieldDecl const * decl) {
        if (ignoreLocation(decl)) {
            return true;
        }
        if (!loplugin::TypeCheck(decl->getType()).LvalueReference()) {
            return true;
        }
        auto const init = decl->getInClassInitializer();
        if (init == nullptr) {
            return true;
        }
        recordConsumption(lookThroughInitListExpr(init));
        return true;
    }

private:
    struct Usage {
        std::vector<ExplicitCastExpr const *> castToVoid;
        bool mentioned = false;
        DeclRefExpr const * firstConsumption = nullptr;
    };

    struct Cast {
        ExplicitCastExpr const * cast;
        DeclRefExpr const * sub;
    };

    std::map<VarDecl const *, Usage> vars_;
    std::stack<Cast> castToVoid_;
    std::stack<QualType> returnTypes_;

    void run() override {
        if (compiler.getPreprocessor().getIdentifierInfo("NDEBUG")->hasMacroDefinition()) {
            return;
        }
        if (!TraverseDecl(compiler.getASTContext().getTranslationUnitDecl())) {
            return;
        }
        for (auto const & i: vars_) {
            if (i.second.firstConsumption == nullptr) {
                if (i.second.mentioned) {
                    continue;
                }
                if (isa<ParmVarDecl>(i.first)) {
                    if (!compiler.getLangOpts().CPlusPlus
                        || isSharedCAndCppCode(i.first))
                    {
                        continue;
                    }
                    auto const ctxt = i.first->getDeclContext();
                    if (dyn_cast_or_null<ObjCMethodDecl>(ctxt) != nullptr) {
                        continue;
                    }
                    auto const fun = dyn_cast_or_null<FunctionDecl>(ctxt);
                    assert(fun != nullptr);
                    if (containsPreprocessingConditionalInclusion(
                            fun->getSourceRange()))
                    {
                        continue;
                    }
                    auto const meth = dyn_cast<CXXMethodDecl>(fun);
                    report(
                        DiagnosticsEngine::Warning,
                        "unused%select{| virtual function}0 parameter name",
                        i.first->getLocation())
                        << (meth != nullptr && meth->isVirtual())
                        << i.first->getSourceRange();
                    for (auto const j: i.second.castToVoid) {
                        report(
                            DiagnosticsEngine::Note, "cast to void here",
                            j->getExprLoc())
                            << j->getSourceRange();
                    }
                } else if (!i.second.castToVoid.empty()
                           && !isWarnUnusedType(i.first->getType()))
                {
                    auto const fun = dyn_cast_or_null<FunctionDecl>(i.first->getDeclContext());
                    assert(fun != nullptr);
                    if (containsPreprocessingConditionalInclusion(fun->getSourceRange())) {
                        continue;
                    }
                    report(
                        DiagnosticsEngine::Warning,
                        "unused variable %select{declaration|name}0",
                        i.first->getLocation())
                        << i.first->isExceptionVariable()
                        << i.first->getSourceRange();
                    for (auto const j: i.second.castToVoid) {
                        report(
                            DiagnosticsEngine::Note, "cast to void here",
                            j->getExprLoc())
                            << j->getSourceRange();
                    }
                }
            } else {
                for (auto const j: i.second.castToVoid) {
                    report(
                        DiagnosticsEngine::Warning, "unnecessary cast to void",
                        j->getExprLoc())
                        << j->getSourceRange();
                    report(
                        DiagnosticsEngine::Note, "first consumption is here",
                        i.second.firstConsumption->getExprLoc())
                        << i.second.firstConsumption->getSourceRange();
                }
            }
        }
    }

    bool isFromCIncludeFile(SourceLocation spellingLocation) const {
        return !compiler.getSourceManager().isInMainFile(spellingLocation)
            && (StringRef(
                    compiler.getSourceManager().getPresumedLoc(spellingLocation)
                    .getFilename())
                .endswith(".h"));
    }

    bool isSharedCAndCppCode(VarDecl const * decl) const {
        auto loc = decl->getLocation();
        while (compiler.getSourceManager().isMacroArgExpansion(loc)) {
            loc = compiler.getSourceManager().getImmediateMacroCallerLoc(loc);
        }
        // Assume that code is intended to be shared between C and C++ if it
        // comes from an include file ending in .h, and is either in an extern
        // "C" context or the body of a macro definition:
        return
            isFromCIncludeFile(compiler.getSourceManager().getSpellingLoc(loc))
            && (decl->isInExternCContext()
                || compiler.getSourceManager().isMacroBodyExpansion(loc));
    }

    DeclRefExpr const * checkCast(ExplicitCastExpr const * expr) {
        if (!loplugin::TypeCheck(expr->getTypeAsWritten()).Void()) {
            return nullptr;
        }
        if (compiler.getSourceManager().isMacroBodyExpansion(
                compat::getBeginLoc(expr)))
        {
            return nullptr;
        }
        return dyn_cast<DeclRefExpr>(expr->getSubExpr()->IgnoreParenImpCasts());
    }

    void recordConsumption(Expr const * expr) {
        for (;;) {
            expr = expr->IgnoreParenImpCasts();
            if (auto const e = dyn_cast<MemberExpr>(expr)) {
                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;
        }
        // In C (but not in C++)
        //
        //   (void) x
        //
        // contains an implicit lvalue-to-rvalue cast, so VisitImplicitCastExpr
        // would record that as a consumption if we didn't filter it out here:
        if (!castToVoid_.empty() && castToVoid_.top().sub == dre) {
            return;
        }
        auto const var = dyn_cast<VarDecl>(dre->getDecl());
        if (var == nullptr) {
            return;
        }
        auto & usage = vars_[var->getCanonicalDecl()];
        if (usage.firstConsumption != nullptr) {
            return;
        }
        auto const loc = compat::getBeginLoc(dre);
        if (compiler.getSourceManager().isMacroArgExpansion(loc)
            && (Lexer::getImmediateMacroNameForDiagnostics(
                    loc, compiler.getSourceManager(), compiler.getLangOpts())
                == "assert"))
        {
            return;
        }
        usage.firstConsumption = dre;
    }
};

static loplugin::Plugin::Registration<CastToVoid> reg("casttovoid");

}

/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */