File indexing completed on 2024-05-12 05:41:01
0001 /* 0002 SPDX-FileCopyrightText: 2019 Sergio Martins <smartins@kde.org> 0003 0004 SPDX-License-Identifier: LGPL-2.0-or-later 0005 */ 0006 0007 #include "heap-allocated-small-trivial-type.h" 0008 #include "ClazyContext.h" 0009 #include "QtUtils.h" 0010 #include "StmtBodyRange.h" 0011 #include "TypeUtils.h" 0012 #include "Utils.h" 0013 0014 #include <clang/AST/AST.h> 0015 0016 using namespace clang; 0017 0018 HeapAllocatedSmallTrivialType::HeapAllocatedSmallTrivialType(const std::string &name, ClazyContext *context) 0019 : CheckBase(name, context) 0020 { 0021 } 0022 0023 void HeapAllocatedSmallTrivialType::VisitDecl(clang::Decl *decl) 0024 { 0025 auto *varDecl = dyn_cast<VarDecl>(decl); 0026 if (!varDecl) { 0027 return; 0028 } 0029 0030 Expr *init = varDecl->getInit(); 0031 if (!init) { 0032 return; 0033 } 0034 0035 auto *newExpr = dyn_cast<CXXNewExpr>(init); 0036 if (!newExpr || newExpr->getNumPlacementArgs() > 0) { // Placement new, user probably knows what he's doing 0037 return; 0038 } 0039 0040 if (newExpr->isArray()) { 0041 return; 0042 } 0043 0044 DeclContext *context = varDecl->getDeclContext(); 0045 FunctionDecl *fDecl = context ? dyn_cast<FunctionDecl>(context) : nullptr; 0046 if (!fDecl) { 0047 return; 0048 } 0049 0050 QualType qualType = newExpr->getType()->getPointeeType(); 0051 if (clazy::isSmallTrivial(m_context, qualType)) { 0052 if (clazy::contains(qualType.getAsString(), "Private")) { 0053 // Possibly a pimpl, forward declared in header 0054 return; 0055 } 0056 0057 auto *body = fDecl->getBody(); 0058 if (Utils::isAssignedTo(body, varDecl) || Utils::isPassedToFunction(StmtBodyRange(body), varDecl, false) || Utils::isReturned(body, varDecl)) { 0059 return; 0060 } 0061 0062 emitWarning(init, "Don't heap-allocate small trivially copyable/destructible types: " + qualType.getAsString(lo())); 0063 } 0064 }