1 //===--- DefaultOperatorNewCheck.cpp - clang-tidy --------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "DefaultOperatorNewAlignmentCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12 
13 using namespace clang::ast_matchers;
14 
15 namespace clang {
16 namespace tidy {
17 namespace cert {
18 
19 void DefaultOperatorNewAlignmentCheck::registerMatchers(MatchFinder *Finder) {
20   Finder->addMatcher(
21       cxxNewExpr(unless(hasAnyPlacementArg(anything()))).bind("new"), this);
22 }
23 
24 void DefaultOperatorNewAlignmentCheck::check(
25     const MatchFinder::MatchResult &Result) {
26   // Get the found 'new' expression.
27   const auto *NewExpr = Result.Nodes.getNodeAs<CXXNewExpr>("new");
28 
29   QualType T = NewExpr->getAllocatedType();
30   // Dependent types do not have fixed alignment.
31   if (T->isDependentType())
32     return;
33   const TagDecl *D = T->getAsTagDecl();
34   // Alignment can not be obtained for undefined type.
35   if (!D || !D->getDefinition() || !D->isCompleteDefinition())
36     return;
37 
38   ASTContext &Context = D->getASTContext();
39 
40   // Check if no alignment was specified for the type.
41   if (!Context.isAlignmentRequired(T))
42     return;
43 
44   // The user-specified alignment (in bits).
45   unsigned SpecifiedAlignment = D->getMaxAlignment();
46   // Double-check if no alignment was specified.
47   if (!SpecifiedAlignment)
48     return;
49   // The alignment used by default 'operator new' (in bits).
50   unsigned DefaultNewAlignment = Context.getTargetInfo().getNewAlign();
51 
52   bool OverAligned = SpecifiedAlignment > DefaultNewAlignment;
53   bool HasDefaultOperatorNew =
54       !NewExpr->getOperatorNew() || NewExpr->getOperatorNew()->isImplicit();
55 
56   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
57   if (HasDefaultOperatorNew && OverAligned)
58     diag(NewExpr->getBeginLoc(),
59          "allocation function returns a pointer with alignment %0 but the "
60          "over-aligned type being allocated requires alignment %1")
61         << (DefaultNewAlignment / CharWidth)
62         << (SpecifiedAlignment / CharWidth);
63 }
64 
65 } // namespace cert
66 } // namespace tidy
67 } // namespace clang
68