xref: /aosp_15_r20/external/clang/lib/StaticAnalyzer/Checkers/PaddingChecker.cpp (revision 67e74705e28f6214e480b399dd47ea732279e315)
1*67e74705SXin Li //=======- PaddingChecker.cpp ------------------------------------*- C++ -*-==//
2*67e74705SXin Li //
3*67e74705SXin Li //                     The LLVM Compiler Infrastructure
4*67e74705SXin Li //
5*67e74705SXin Li // This file is distributed under the University of Illinois Open Source
6*67e74705SXin Li // License. See LICENSE.TXT for details.
7*67e74705SXin Li //
8*67e74705SXin Li //===----------------------------------------------------------------------===//
9*67e74705SXin Li //
10*67e74705SXin Li //  This file defines a checker that checks for padding that could be
11*67e74705SXin Li //  removed by re-ordering members.
12*67e74705SXin Li //
13*67e74705SXin Li //===----------------------------------------------------------------------===//
14*67e74705SXin Li 
15*67e74705SXin Li #include "ClangSACheckers.h"
16*67e74705SXin Li #include "clang/AST/CharUnits.h"
17*67e74705SXin Li #include "clang/AST/DeclTemplate.h"
18*67e74705SXin Li #include "clang/AST/RecordLayout.h"
19*67e74705SXin Li #include "clang/AST/RecursiveASTVisitor.h"
20*67e74705SXin Li #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
21*67e74705SXin Li #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
22*67e74705SXin Li #include "clang/StaticAnalyzer/Core/Checker.h"
23*67e74705SXin Li #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
24*67e74705SXin Li #include "llvm/ADT/SmallString.h"
25*67e74705SXin Li #include "llvm/Support/MathExtras.h"
26*67e74705SXin Li #include "llvm/Support/raw_ostream.h"
27*67e74705SXin Li #include <numeric>
28*67e74705SXin Li 
29*67e74705SXin Li using namespace clang;
30*67e74705SXin Li using namespace ento;
31*67e74705SXin Li 
32*67e74705SXin Li namespace {
33*67e74705SXin Li class PaddingChecker : public Checker<check::ASTDecl<TranslationUnitDecl>> {
34*67e74705SXin Li private:
35*67e74705SXin Li   mutable std::unique_ptr<BugType> PaddingBug;
36*67e74705SXin Li   mutable int64_t AllowedPad;
37*67e74705SXin Li   mutable BugReporter *BR;
38*67e74705SXin Li 
39*67e74705SXin Li public:
checkASTDecl(const TranslationUnitDecl * TUD,AnalysisManager & MGR,BugReporter & BRArg) const40*67e74705SXin Li   void checkASTDecl(const TranslationUnitDecl *TUD, AnalysisManager &MGR,
41*67e74705SXin Li                     BugReporter &BRArg) const {
42*67e74705SXin Li     BR = &BRArg;
43*67e74705SXin Li     AllowedPad =
44*67e74705SXin Li         MGR.getAnalyzerOptions().getOptionAsInteger("AllowedPad", 24, this);
45*67e74705SXin Li     assert(AllowedPad >= 0 && "AllowedPad option should be non-negative");
46*67e74705SXin Li 
47*67e74705SXin Li     // The calls to checkAST* from AnalysisConsumer don't
48*67e74705SXin Li     // visit template instantiations or lambda classes. We
49*67e74705SXin Li     // want to visit those, so we make our own RecursiveASTVisitor.
50*67e74705SXin Li     struct LocalVisitor : public RecursiveASTVisitor<LocalVisitor> {
51*67e74705SXin Li       const PaddingChecker *Checker;
52*67e74705SXin Li       bool shouldVisitTemplateInstantiations() const { return true; }
53*67e74705SXin Li       bool shouldVisitImplicitCode() const { return true; }
54*67e74705SXin Li       explicit LocalVisitor(const PaddingChecker *Checker) : Checker(Checker) {}
55*67e74705SXin Li       bool VisitRecordDecl(const RecordDecl *RD) {
56*67e74705SXin Li         Checker->visitRecord(RD);
57*67e74705SXin Li         return true;
58*67e74705SXin Li       }
59*67e74705SXin Li       bool VisitVarDecl(const VarDecl *VD) {
60*67e74705SXin Li         Checker->visitVariable(VD);
61*67e74705SXin Li         return true;
62*67e74705SXin Li       }
63*67e74705SXin Li       // TODO: Visit array new and mallocs for arrays.
64*67e74705SXin Li     };
65*67e74705SXin Li 
66*67e74705SXin Li     LocalVisitor visitor(this);
67*67e74705SXin Li     visitor.TraverseDecl(const_cast<TranslationUnitDecl *>(TUD));
68*67e74705SXin Li   }
69*67e74705SXin Li 
70*67e74705SXin Li   /// \brief Look for records of overly padded types. If padding *
71*67e74705SXin Li   /// PadMultiplier exceeds AllowedPad, then generate a report.
72*67e74705SXin Li   /// PadMultiplier is used to share code with the array padding
73*67e74705SXin Li   /// checker.
visitRecord(const RecordDecl * RD,uint64_t PadMultiplier=1) const74*67e74705SXin Li   void visitRecord(const RecordDecl *RD, uint64_t PadMultiplier = 1) const {
75*67e74705SXin Li     if (shouldSkipDecl(RD))
76*67e74705SXin Li       return;
77*67e74705SXin Li 
78*67e74705SXin Li     auto &ASTContext = RD->getASTContext();
79*67e74705SXin Li     const ASTRecordLayout &RL = ASTContext.getASTRecordLayout(RD);
80*67e74705SXin Li     assert(llvm::isPowerOf2_64(RL.getAlignment().getQuantity()));
81*67e74705SXin Li 
82*67e74705SXin Li     CharUnits BaselinePad = calculateBaselinePad(RD, ASTContext, RL);
83*67e74705SXin Li     if (BaselinePad.isZero())
84*67e74705SXin Li       return;
85*67e74705SXin Li     CharUnits OptimalPad = calculateOptimalPad(RD, ASTContext, RL);
86*67e74705SXin Li 
87*67e74705SXin Li     CharUnits DiffPad = PadMultiplier * (BaselinePad - OptimalPad);
88*67e74705SXin Li     if (DiffPad.getQuantity() <= AllowedPad) {
89*67e74705SXin Li       assert(!DiffPad.isNegative() && "DiffPad should not be negative");
90*67e74705SXin Li       // There is not enough excess padding to trigger a warning.
91*67e74705SXin Li       return;
92*67e74705SXin Li     }
93*67e74705SXin Li     reportRecord(RD, BaselinePad, OptimalPad);
94*67e74705SXin Li   }
95*67e74705SXin Li 
96*67e74705SXin Li   /// \brief Look for arrays of overly padded types. If the padding of the
97*67e74705SXin Li   /// array type exceeds AllowedPad, then generate a report.
visitVariable(const VarDecl * VD) const98*67e74705SXin Li   void visitVariable(const VarDecl *VD) const {
99*67e74705SXin Li     const ArrayType *ArrTy = VD->getType()->getAsArrayTypeUnsafe();
100*67e74705SXin Li     if (ArrTy == nullptr)
101*67e74705SXin Li       return;
102*67e74705SXin Li     uint64_t Elts = 0;
103*67e74705SXin Li     if (const ConstantArrayType *CArrTy = dyn_cast<ConstantArrayType>(ArrTy))
104*67e74705SXin Li       Elts = CArrTy->getSize().getZExtValue();
105*67e74705SXin Li     if (Elts == 0)
106*67e74705SXin Li       return;
107*67e74705SXin Li     const RecordType *RT = ArrTy->getElementType()->getAs<RecordType>();
108*67e74705SXin Li     if (RT == nullptr)
109*67e74705SXin Li       return;
110*67e74705SXin Li 
111*67e74705SXin Li     // TODO: Recurse into the fields and base classes to see if any
112*67e74705SXin Li     // of those have excess padding.
113*67e74705SXin Li     visitRecord(RT->getDecl(), Elts);
114*67e74705SXin Li   }
115*67e74705SXin Li 
shouldSkipDecl(const RecordDecl * RD) const116*67e74705SXin Li   bool shouldSkipDecl(const RecordDecl *RD) const {
117*67e74705SXin Li     auto Location = RD->getLocation();
118*67e74705SXin Li     // If the construct doesn't have a source file, then it's not something
119*67e74705SXin Li     // we want to diagnose.
120*67e74705SXin Li     if (!Location.isValid())
121*67e74705SXin Li       return true;
122*67e74705SXin Li     SrcMgr::CharacteristicKind Kind =
123*67e74705SXin Li         BR->getSourceManager().getFileCharacteristic(Location);
124*67e74705SXin Li     // Throw out all records that come from system headers.
125*67e74705SXin Li     if (Kind != SrcMgr::C_User)
126*67e74705SXin Li       return true;
127*67e74705SXin Li 
128*67e74705SXin Li     // Not going to attempt to optimize unions.
129*67e74705SXin Li     if (RD->isUnion())
130*67e74705SXin Li       return true;
131*67e74705SXin Li     // How do you reorder fields if you haven't got any?
132*67e74705SXin Li     if (RD->field_empty())
133*67e74705SXin Li       return true;
134*67e74705SXin Li     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
135*67e74705SXin Li       // Tail padding with base classes ends up being very complicated.
136*67e74705SXin Li       // We will skip objects with base classes for now.
137*67e74705SXin Li       if (CXXRD->getNumBases() != 0)
138*67e74705SXin Li         return true;
139*67e74705SXin Li       // Virtual bases are complicated, skipping those for now.
140*67e74705SXin Li       if (CXXRD->getNumVBases() != 0)
141*67e74705SXin Li         return true;
142*67e74705SXin Li       // Can't layout a template, so skip it. We do still layout the
143*67e74705SXin Li       // instantiations though.
144*67e74705SXin Li       if (CXXRD->getTypeForDecl()->isDependentType())
145*67e74705SXin Li         return true;
146*67e74705SXin Li       if (CXXRD->getTypeForDecl()->isInstantiationDependentType())
147*67e74705SXin Li         return true;
148*67e74705SXin Li     }
149*67e74705SXin Li     auto IsTrickyField = [](const FieldDecl *FD) -> bool {
150*67e74705SXin Li       // Bitfield layout is hard.
151*67e74705SXin Li       if (FD->isBitField())
152*67e74705SXin Li         return true;
153*67e74705SXin Li 
154*67e74705SXin Li       // Variable length arrays are tricky too.
155*67e74705SXin Li       QualType Ty = FD->getType();
156*67e74705SXin Li       if (Ty->isIncompleteArrayType())
157*67e74705SXin Li         return true;
158*67e74705SXin Li       return false;
159*67e74705SXin Li     };
160*67e74705SXin Li 
161*67e74705SXin Li     if (std::any_of(RD->field_begin(), RD->field_end(), IsTrickyField))
162*67e74705SXin Li       return true;
163*67e74705SXin Li     return false;
164*67e74705SXin Li   }
165*67e74705SXin Li 
calculateBaselinePad(const RecordDecl * RD,const ASTContext & ASTContext,const ASTRecordLayout & RL)166*67e74705SXin Li   static CharUnits calculateBaselinePad(const RecordDecl *RD,
167*67e74705SXin Li                                         const ASTContext &ASTContext,
168*67e74705SXin Li                                         const ASTRecordLayout &RL) {
169*67e74705SXin Li     CharUnits PaddingSum;
170*67e74705SXin Li     CharUnits Offset = ASTContext.toCharUnitsFromBits(RL.getFieldOffset(0));
171*67e74705SXin Li     for (const FieldDecl *FD : RD->fields()) {
172*67e74705SXin Li       // This checker only cares about the padded size of the
173*67e74705SXin Li       // field, and not the data size. If the field is a record
174*67e74705SXin Li       // with tail padding, then we won't put that number in our
175*67e74705SXin Li       // total because reordering fields won't fix that problem.
176*67e74705SXin Li       CharUnits FieldSize = ASTContext.getTypeSizeInChars(FD->getType());
177*67e74705SXin Li       auto FieldOffsetBits = RL.getFieldOffset(FD->getFieldIndex());
178*67e74705SXin Li       CharUnits FieldOffset = ASTContext.toCharUnitsFromBits(FieldOffsetBits);
179*67e74705SXin Li       PaddingSum += (FieldOffset - Offset);
180*67e74705SXin Li       Offset = FieldOffset + FieldSize;
181*67e74705SXin Li     }
182*67e74705SXin Li     PaddingSum += RL.getSize() - Offset;
183*67e74705SXin Li     return PaddingSum;
184*67e74705SXin Li   }
185*67e74705SXin Li 
186*67e74705SXin Li   /// Optimal padding overview:
187*67e74705SXin Li   /// 1.  Find a close approximation to where we can place our first field.
188*67e74705SXin Li   ///     This will usually be at offset 0.
189*67e74705SXin Li   /// 2.  Try to find the best field that can legally be placed at the current
190*67e74705SXin Li   ///     offset.
191*67e74705SXin Li   ///   a.  "Best" is the largest alignment that is legal, but smallest size.
192*67e74705SXin Li   ///       This is to account for overly aligned types.
193*67e74705SXin Li   /// 3.  If no fields can fit, pad by rounding the current offset up to the
194*67e74705SXin Li   ///     smallest alignment requirement of our fields. Measure and track the
195*67e74705SXin Li   //      amount of padding added. Go back to 2.
196*67e74705SXin Li   /// 4.  Increment the current offset by the size of the chosen field.
197*67e74705SXin Li   /// 5.  Remove the chosen field from the set of future possibilities.
198*67e74705SXin Li   /// 6.  Go back to 2 if there are still unplaced fields.
199*67e74705SXin Li   /// 7.  Add tail padding by rounding the current offset up to the structure
200*67e74705SXin Li   ///     alignment. Track the amount of padding added.
201*67e74705SXin Li 
calculateOptimalPad(const RecordDecl * RD,const ASTContext & ASTContext,const ASTRecordLayout & RL)202*67e74705SXin Li   static CharUnits calculateOptimalPad(const RecordDecl *RD,
203*67e74705SXin Li                                        const ASTContext &ASTContext,
204*67e74705SXin Li                                        const ASTRecordLayout &RL) {
205*67e74705SXin Li     struct CharUnitPair {
206*67e74705SXin Li       CharUnits Align;
207*67e74705SXin Li       CharUnits Size;
208*67e74705SXin Li       bool operator<(const CharUnitPair &RHS) const {
209*67e74705SXin Li         // Order from small alignments to large alignments,
210*67e74705SXin Li         // then large sizes to small sizes.
211*67e74705SXin Li         return std::make_pair(Align, -Size) <
212*67e74705SXin Li                std::make_pair(RHS.Align, -RHS.Size);
213*67e74705SXin Li       }
214*67e74705SXin Li     };
215*67e74705SXin Li     SmallVector<CharUnitPair, 20> Fields;
216*67e74705SXin Li     auto GatherSizesAndAlignments = [](const FieldDecl *FD) {
217*67e74705SXin Li       CharUnitPair RetVal;
218*67e74705SXin Li       auto &Ctx = FD->getASTContext();
219*67e74705SXin Li       std::tie(RetVal.Size, RetVal.Align) =
220*67e74705SXin Li           Ctx.getTypeInfoInChars(FD->getType());
221*67e74705SXin Li       assert(llvm::isPowerOf2_64(RetVal.Align.getQuantity()));
222*67e74705SXin Li       if (auto Max = FD->getMaxAlignment())
223*67e74705SXin Li         RetVal.Align = std::max(Ctx.toCharUnitsFromBits(Max), RetVal.Align);
224*67e74705SXin Li       return RetVal;
225*67e74705SXin Li     };
226*67e74705SXin Li     std::transform(RD->field_begin(), RD->field_end(),
227*67e74705SXin Li                    std::back_inserter(Fields), GatherSizesAndAlignments);
228*67e74705SXin Li     std::sort(Fields.begin(), Fields.end());
229*67e74705SXin Li 
230*67e74705SXin Li     // This lets us skip over vptrs and non-virtual bases,
231*67e74705SXin Li     // so that we can just worry about the fields in our object.
232*67e74705SXin Li     // Note that this does cause us to miss some cases where we
233*67e74705SXin Li     // could pack more bytes in to a base class's tail padding.
234*67e74705SXin Li     CharUnits NewOffset = ASTContext.toCharUnitsFromBits(RL.getFieldOffset(0));
235*67e74705SXin Li     CharUnits NewPad;
236*67e74705SXin Li 
237*67e74705SXin Li     while (!Fields.empty()) {
238*67e74705SXin Li       unsigned TrailingZeros =
239*67e74705SXin Li           llvm::countTrailingZeros((unsigned long long)NewOffset.getQuantity());
240*67e74705SXin Li       // If NewOffset is zero, then countTrailingZeros will be 64. Shifting
241*67e74705SXin Li       // 64 will overflow our unsigned long long. Shifting 63 will turn
242*67e74705SXin Li       // our long long (and CharUnits internal type) negative. So shift 62.
243*67e74705SXin Li       long long CurAlignmentBits = 1ull << (std::min)(TrailingZeros, 62u);
244*67e74705SXin Li       CharUnits CurAlignment = CharUnits::fromQuantity(CurAlignmentBits);
245*67e74705SXin Li       CharUnitPair InsertPoint = {CurAlignment, CharUnits::Zero()};
246*67e74705SXin Li       auto CurBegin = Fields.begin();
247*67e74705SXin Li       auto CurEnd = Fields.end();
248*67e74705SXin Li 
249*67e74705SXin Li       // In the typical case, this will find the last element
250*67e74705SXin Li       // of the vector. We won't find a middle element unless
251*67e74705SXin Li       // we started on a poorly aligned address or have an overly
252*67e74705SXin Li       // aligned field.
253*67e74705SXin Li       auto Iter = std::upper_bound(CurBegin, CurEnd, InsertPoint);
254*67e74705SXin Li       if (Iter != CurBegin) {
255*67e74705SXin Li         // We found a field that we can layout with the current alignment.
256*67e74705SXin Li         --Iter;
257*67e74705SXin Li         NewOffset += Iter->Size;
258*67e74705SXin Li         Fields.erase(Iter);
259*67e74705SXin Li       } else {
260*67e74705SXin Li         // We are poorly aligned, and we need to pad in order to layout another
261*67e74705SXin Li         // field. Round up to at least the smallest field alignment that we
262*67e74705SXin Li         // currently have.
263*67e74705SXin Li         CharUnits NextOffset = NewOffset.alignTo(Fields[0].Align);
264*67e74705SXin Li         NewPad += NextOffset - NewOffset;
265*67e74705SXin Li         NewOffset = NextOffset;
266*67e74705SXin Li       }
267*67e74705SXin Li     }
268*67e74705SXin Li     // Calculate tail padding.
269*67e74705SXin Li     CharUnits NewSize = NewOffset.alignTo(RL.getAlignment());
270*67e74705SXin Li     NewPad += NewSize - NewOffset;
271*67e74705SXin Li     return NewPad;
272*67e74705SXin Li   }
273*67e74705SXin Li 
reportRecord(const RecordDecl * RD,CharUnits BaselinePad,CharUnits TargetPad) const274*67e74705SXin Li   void reportRecord(const RecordDecl *RD, CharUnits BaselinePad,
275*67e74705SXin Li                     CharUnits TargetPad) const {
276*67e74705SXin Li     if (!PaddingBug)
277*67e74705SXin Li       PaddingBug =
278*67e74705SXin Li           llvm::make_unique<BugType>(this, "Excessive Padding", "Performance");
279*67e74705SXin Li 
280*67e74705SXin Li     SmallString<100> Buf;
281*67e74705SXin Li     llvm::raw_svector_ostream Os(Buf);
282*67e74705SXin Li 
283*67e74705SXin Li     Os << "Excessive padding in '";
284*67e74705SXin Li     Os << QualType::getAsString(RD->getTypeForDecl(), Qualifiers()) << "'";
285*67e74705SXin Li 
286*67e74705SXin Li     if (auto *TSD = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
287*67e74705SXin Li       // TODO: make this show up better in the console output and in
288*67e74705SXin Li       // the HTML. Maybe just make it show up in HTML like the path
289*67e74705SXin Li       // diagnostics show.
290*67e74705SXin Li       SourceLocation ILoc = TSD->getPointOfInstantiation();
291*67e74705SXin Li       if (ILoc.isValid())
292*67e74705SXin Li         Os << " instantiated here: "
293*67e74705SXin Li            << ILoc.printToString(BR->getSourceManager());
294*67e74705SXin Li     }
295*67e74705SXin Li 
296*67e74705SXin Li     Os << " (" << BaselinePad.getQuantity() << " padding bytes, where "
297*67e74705SXin Li        << TargetPad.getQuantity() << " is optimal). Consider reordering "
298*67e74705SXin Li        << "the fields or adding explicit padding members.";
299*67e74705SXin Li 
300*67e74705SXin Li     PathDiagnosticLocation CELoc =
301*67e74705SXin Li         PathDiagnosticLocation::create(RD, BR->getSourceManager());
302*67e74705SXin Li 
303*67e74705SXin Li     auto Report = llvm::make_unique<BugReport>(*PaddingBug, Os.str(), CELoc);
304*67e74705SXin Li     Report->setDeclWithIssue(RD);
305*67e74705SXin Li     Report->addRange(RD->getSourceRange());
306*67e74705SXin Li 
307*67e74705SXin Li     BR->emitReport(std::move(Report));
308*67e74705SXin Li   }
309*67e74705SXin Li };
310*67e74705SXin Li }
311*67e74705SXin Li 
registerPaddingChecker(CheckerManager & Mgr)312*67e74705SXin Li void ento::registerPaddingChecker(CheckerManager &Mgr) {
313*67e74705SXin Li   Mgr.registerChecker<PaddingChecker>();
314*67e74705SXin Li }
315