clang 24.0.0git
PaddingChecker.cpp
Go to the documentation of this file.
1//=======- PaddingChecker.cpp ------------------------------------*- C++ -*-==//
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// This file defines a checker that checks for padding that could be
10// removed by re-ordering members.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/CharUnits.h"
24#include "llvm/ADT/SmallVectorExtras.h"
25#include "llvm/Support/MathExtras.h"
26#include "llvm/Support/raw_ostream.h"
27
28using namespace clang;
29using namespace ento;
30
31namespace {
32class PaddingChecker : public Checker<check::ASTDecl<TranslationUnitDecl>> {
33private:
34 const BugType PaddingBug{this, "Excessive Padding", "Performance"};
35 mutable BugReporter *BR;
36
37public:
38 int64_t AllowedPad;
39
40 void checkASTDecl(const TranslationUnitDecl *TUD, AnalysisManager &MGR,
41 BugReporter &BRArg) const {
42 BR = &BRArg;
43
44 // The calls to checkAST* from AnalysisConsumer don't
45 // visit template instantiations or lambda classes. We
46 // want to visit those, so we make our own RecursiveASTVisitor.
47 struct LocalVisitor : DynamicRecursiveASTVisitor {
48 const PaddingChecker *Checker;
49 explicit LocalVisitor(const PaddingChecker *Checker) : Checker(Checker) {
50 ShouldVisitTemplateInstantiations = true;
51 ShouldVisitImplicitCode = true;
52 }
53 bool VisitRecordDecl(RecordDecl *RD) override {
54 Checker->visitRecord(RD);
55 return true;
56 }
57 bool VisitVarDecl(VarDecl *VD) override {
58 Checker->visitVariable(VD);
59 return true;
60 }
61 // TODO: Visit array new and mallocs for arrays.
62 };
63
64 LocalVisitor visitor(this);
65 visitor.TraverseDecl(const_cast<TranslationUnitDecl *>(TUD));
66 }
67
68 /// Look for records of overly padded types. If padding *
69 /// PadMultiplier exceeds AllowedPad, then generate a report.
70 /// PadMultiplier is used to share code with the array padding
71 /// checker.
72 void visitRecord(const RecordDecl *RD, uint64_t PadMultiplier = 1) const {
73 if (shouldSkipDecl(RD))
74 return;
75
76 // TODO: Figure out why we are going through declarations and not only
77 // definitions.
78 if (!(RD = RD->getDefinition()))
79 return;
80
81 if (RD->isInvalidDecl())
82 return;
83
84 // This is the simplest correct case: a class with no fields and one base
85 // class. Other cases are more complicated because of how the base classes
86 // & fields might interact, so we don't bother dealing with them.
87 // TODO: Support other combinations of base classes and fields.
88 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
89 if (CXXRD->field_empty() && CXXRD->getNumBases() == 1)
90 return visitRecord(CXXRD->bases().begin()->getType()->getAsRecordDecl(),
91 PadMultiplier);
92
93 auto &ASTContext = RD->getASTContext();
94 const ASTRecordLayout &RL = ASTContext.getASTRecordLayout(RD);
95 assert(llvm::isPowerOf2_64(RL.getAlignment().getQuantity()));
96
97 CharUnits BaselinePad = calculateBaselinePad(RD, ASTContext, RL);
98 if (BaselinePad.isZero())
99 return;
100
101 CharUnits OptimalPad;
102 SmallVector<const FieldDecl *, 20> OptimalFieldsOrder;
103 std::tie(OptimalPad, OptimalFieldsOrder) =
104 calculateOptimalPad(RD, ASTContext, RL);
105
106 CharUnits DiffPad = PadMultiplier * (BaselinePad - OptimalPad);
107 if (DiffPad.getQuantity() <= AllowedPad) {
108 assert(!DiffPad.isNegative() && "DiffPad should not be negative");
109 // There is not enough excess padding to trigger a warning.
110 return;
111 }
112 reportRecord(ASTContext, RD, BaselinePad, OptimalPad, OptimalFieldsOrder);
113 }
114
115 /// Look for arrays of overly padded types. If the padding of the
116 /// array type exceeds AllowedPad, then generate a report.
117 void visitVariable(const VarDecl *VD) const {
118 const ArrayType *ArrTy = VD->getType()->getAsArrayTypeUnsafe();
119 if (ArrTy == nullptr)
120 return;
121 uint64_t Elts = 0;
122 if (const ConstantArrayType *CArrTy = dyn_cast<ConstantArrayType>(ArrTy))
123 Elts = CArrTy->getZExtSize();
124 if (Elts == 0)
125 return;
126 const auto *RD = ArrTy->getElementType()->getAsRecordDecl();
127 if (!RD)
128 return;
129
130 // TODO: Recurse into the fields to see if they have excess padding.
131 visitRecord(RD, Elts);
132 }
133
134 bool shouldSkipDecl(const RecordDecl *RD) const {
135 // TODO: Figure out why we are going through declarations and not only
136 // definitions.
137 if (!(RD = RD->getDefinition()))
138 return true;
139 auto Location = RD->getLocation();
140 // If the construct doesn't have a source file, then it's not something
141 // we want to diagnose.
142 if (!Location.isValid())
143 return true;
145 BR->getSourceManager().getFileCharacteristic(Location);
146 // Throw out all records that come from system headers.
147 if (Kind != SrcMgr::C_User)
148 return true;
149
150 // Not going to attempt to optimize unions.
151 if (RD->isUnion())
152 return true;
153 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
154 // Tail padding with base classes ends up being very complicated.
155 // We will skip objects with base classes for now, unless they do not
156 // have fields.
157 // TODO: Handle more base class scenarios.
158 if (!CXXRD->field_empty() && CXXRD->getNumBases() != 0)
159 return true;
160 if (CXXRD->field_empty() && CXXRD->getNumBases() != 1)
161 return true;
162 // Virtual bases are complicated, skipping those for now.
163 if (CXXRD->getNumVBases() != 0)
164 return true;
165 // Can't layout a template, so skip it. We do still layout the
166 // instantiations though.
167 if (CXXRD->isDependentType())
168 return true;
169 }
170 // How do you reorder fields if you haven't got any?
171 else if (RD->field_empty())
172 return true;
173
174 auto IsTrickyField = [](const FieldDecl *FD) -> bool {
175 // Bitfield layout is hard.
176 if (FD->isBitField())
177 return true;
178
179 // Variable length arrays are tricky too.
180 QualType Ty = FD->getType();
181 if (Ty->isIncompleteArrayType())
182 return true;
183
184 // Defensive backstop: a lambda closure type can be left non-dependent due
185 // to a bug, leaving the closure with a field of a bare dependent type
186 // whose layout cannot be computed. This workaround is temporary and
187 // should be removed together with the related FIXME in
188 // Sema::ActOnLambdaExpressionAfterIntroducer once the bug is fixed. See:
189 // * https://github.com/llvm/llvm-project/issues/232874
190 // * https://github.com/llvm/llvm-project/issues/233102
191 if (Ty->isDependentType())
192 return true;
193
194 return false;
195 };
196
197 if (llvm::any_of(RD->fields(), IsTrickyField))
198 return true;
199 return false;
200 }
201
202 static CharUnits calculateBaselinePad(const RecordDecl *RD,
203 const ASTContext &ASTContext,
204 const ASTRecordLayout &RL) {
205 CharUnits PaddingSum;
206 CharUnits Offset = ASTContext.toCharUnitsFromBits(RL.getFieldOffset(0));
207 for (const FieldDecl *FD : RD->fields()) {
208 // Skip field that is a subobject of zero size, marked with
209 // [[no_unique_address]] or an empty bitfield, because its address can be
210 // set the same as the other fields addresses.
211 if (FD->isZeroSize(ASTContext))
212 continue;
213 // This checker only cares about the padded size of the
214 // field, and not the data size. If the field is a record
215 // with tail padding, then we won't put that number in our
216 // total because reordering fields won't fix that problem.
217 CharUnits FieldSize = ASTContext.getTypeSizeInChars(FD->getType());
218 auto FieldOffsetBits = RL.getFieldOffset(FD->getFieldIndex());
219 CharUnits FieldOffset = ASTContext.toCharUnitsFromBits(FieldOffsetBits);
220 PaddingSum += (FieldOffset - Offset);
221 Offset = FieldOffset + FieldSize;
222 }
223 PaddingSum += RL.getSize() - Offset;
224 return PaddingSum;
225 }
226
227 /// Optimal padding overview:
228 /// 1. Find a close approximation to where we can place our first field.
229 /// This will usually be at offset 0.
230 /// 2. Try to find the best field that can legally be placed at the current
231 /// offset.
232 /// a. "Best" is the largest alignment that is legal, but smallest size.
233 /// This is to account for overly aligned types.
234 /// 3. If no fields can fit, pad by rounding the current offset up to the
235 /// smallest alignment requirement of our fields. Measure and track the
236 // amount of padding added. Go back to 2.
237 /// 4. Increment the current offset by the size of the chosen field.
238 /// 5. Remove the chosen field from the set of future possibilities.
239 /// 6. Go back to 2 if there are still unplaced fields.
240 /// 7. Add tail padding by rounding the current offset up to the structure
241 /// alignment. Track the amount of padding added.
242
243 static std::pair<CharUnits, SmallVector<const FieldDecl *, 20>>
244 calculateOptimalPad(const RecordDecl *RD, const ASTContext &ASTContext,
245 const ASTRecordLayout &RL) {
246 struct FieldInfo {
247 CharUnits Align;
248 CharUnits Size;
249 const FieldDecl *Field;
250 bool operator<(const FieldInfo &RHS) const {
251 // Order from small alignments to large alignments,
252 // then large sizes to small sizes.
253 // then large field indices to small field indices
254 return std::make_tuple(Align, -Size,
255 Field ? -static_cast<int>(Field->getFieldIndex())
256 : 0) <
257 std::make_tuple(
258 RHS.Align, -RHS.Size,
259 RHS.Field ? -static_cast<int>(RHS.Field->getFieldIndex())
260 : 0);
261 }
262 };
263 auto GatherSizesAndAlignments = [](const FieldDecl *FD) {
264 FieldInfo RetVal;
265 RetVal.Field = FD;
266 auto &Ctx = FD->getASTContext();
267 auto Info = Ctx.getTypeInfoInChars(FD->getType());
268 RetVal.Size = FD->isZeroSize(Ctx) ? CharUnits::Zero() : Info.Width;
269 RetVal.Align = Info.Align;
270 assert(llvm::isPowerOf2_64(RetVal.Align.getQuantity()));
271 if (auto Max = FD->getMaxAlignment())
272 RetVal.Align = std::max(Ctx.toCharUnitsFromBits(Max), RetVal.Align);
273 return RetVal;
274 };
275 SmallVector<FieldInfo, 20> Fields =
276 llvm::map_to_vector<20>(RD->fields(), GatherSizesAndAlignments);
277 llvm::sort(Fields);
278 // This lets us skip over vptrs and non-virtual bases,
279 // so that we can just worry about the fields in our object.
280 // Note that this does cause us to miss some cases where we
281 // could pack more bytes in to a base class's tail padding.
282 CharUnits NewOffset = ASTContext.toCharUnitsFromBits(RL.getFieldOffset(0));
283 CharUnits NewPad;
284 SmallVector<const FieldDecl *, 20> OptimalFieldsOrder;
285 while (!Fields.empty()) {
286 unsigned TrailingZeros =
287 llvm::countr_zero((unsigned long long)NewOffset.getQuantity());
288 // If NewOffset is zero, then countTrailingZeros will be 64. Shifting
289 // 64 will overflow our unsigned long long. Shifting 63 will turn
290 // our long long (and CharUnits internal type) negative. So shift 62.
291 long long CurAlignmentBits = 1ull << (std::min)(TrailingZeros, 62u);
292 CharUnits CurAlignment = CharUnits::fromQuantity(CurAlignmentBits);
293 FieldInfo InsertPoint = {CurAlignment, CharUnits::Zero(), nullptr};
294
295 // In the typical case, this will find the last element
296 // of the vector. We won't find a middle element unless
297 // we started on a poorly aligned address or have an overly
298 // aligned field.
299 auto Iter = llvm::upper_bound(Fields, InsertPoint);
300 if (Iter != Fields.begin()) {
301 // We found a field that we can layout with the current alignment.
302 --Iter;
303 NewOffset += Iter->Size;
304 OptimalFieldsOrder.push_back(Iter->Field);
305 Fields.erase(Iter);
306 } else {
307 // We are poorly aligned, and we need to pad in order to layout another
308 // field. Round up to at least the smallest field alignment that we
309 // currently have.
310 CharUnits NextOffset = NewOffset.alignTo(Fields[0].Align);
311 NewPad += NextOffset - NewOffset;
312 NewOffset = NextOffset;
313 }
314 }
315 // Calculate tail padding.
316 CharUnits NewSize = NewOffset.alignTo(RL.getAlignment());
317 NewPad += NewSize - NewOffset;
318 return {NewPad, std::move(OptimalFieldsOrder)};
319 }
320
321 void reportRecord(
322 const ASTContext &Ctx, const RecordDecl *RD, CharUnits BaselinePad,
323 CharUnits OptimalPad,
324 const SmallVector<const FieldDecl *, 20> &OptimalFieldsOrder) const {
325 SmallString<100> Buf;
326 llvm::raw_svector_ostream Os(Buf);
327 Os << "Excessive padding in '";
328 QualType(Ctx.getCanonicalTagType(RD)).print(Os, LangOptions());
329 Os << "'";
330
331 if (auto *TSD = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
332 // TODO: make this show up better in the console output and in
333 // the HTML. Maybe just make it show up in HTML like the path
334 // diagnostics show.
335 SourceLocation ILoc = TSD->getPointOfInstantiation();
336 if (ILoc.isValid())
337 Os << " instantiated here: "
338 << ILoc.printToString(BR->getSourceManager());
339 }
340
341 Os << " (" << BaselinePad.getQuantity() << " padding bytes, where "
342 << OptimalPad.getQuantity() << " is optimal), "
343 << "optimal fields order: ";
344 for (const auto *FD : OptimalFieldsOrder)
345 Os << FD->getName() << ", ";
346 Os << "consider reordering the fields or adding explicit padding "
347 "members";
348
349 PathDiagnosticLocation CELoc =
350 PathDiagnosticLocation::create(RD, BR->getSourceManager());
351 auto Report = std::make_unique<BasicBugReport>(PaddingBug, Os.str(), CELoc);
352 Report->setDeclWithIssue(RD);
353 Report->addRange(RD->getSourceRange());
354 BR->emitReport(std::move(Report));
355 }
356};
357} // namespace
358
359void ento::registerPaddingChecker(CheckerManager &Mgr) {
360 auto *Checker = Mgr.registerChecker<PaddingChecker>();
361 Checker->AllowedPad = Mgr.getAnalyzerOptions()
362 .getCheckerIntegerOption(Checker, "AllowedPad");
363 if (Checker->AllowedPad < 0)
365 Checker, "AllowedPad", "a non-negative value");
366}
367
368bool ento::shouldRegisterPaddingChecker(const CheckerManager &mgr) {
369 return true;
370}
Defines the C++ template declaration subclasses.
Defines the SourceManager interface.
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType getCanonicalTagType(const TagDecl *TD) const
CharUnits getAlignment() const
getAlignment - Get the record alignment in characters.
CharUnits getSize() const
getSize - Get the record size in characters.
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
int getCheckerIntegerOption(StringRef CheckerName, StringRef OptionName, bool SearchInParents=false) const
Interprets an option's string value as a boolean.
QualType getElementType() const
Definition TypeBase.h:3833
bool isNegative() const
Test whether the quantity is less than zero.
Definition CharUnits.h:110
bool isZero() const
Test whether the quantity equals zero.
Definition CharUnits.h:101
CharUnits alignTo(CharUnits Align) const
Returns the next integer (mod 2**64) that is greater than or equal to this quantity and is a multiple...
Definition CharUnits.h:171
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Definition CharUnits.h:155
static constexpr CharUnits fromQuantity(QuantityType Quantity)
Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:58
static CharUnits Zero()
Construct a CharUnits quantity of zero.
Definition CharUnits.h:52
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
bool isInvalidDecl() const
Definition DeclBase.h:598
SourceLocation getLocation() const
Definition DeclBase.h:449
field_range fields() const
Definition Decl.h:4715
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4696
bool field_empty() const
Definition Decl.h:4723
std::string printToString(const SourceManager &SM) const
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:5015
bool isUnion() const
Definition Decl.h:4115
bool isIncompleteArrayType() const
Definition TypeBase.h:9024
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2864
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9590
QualType getType() const
Definition Decl.h:725
const AnalyzerOptions & getAnalyzerOptions() const
CHECKER * registerChecker(AT &&...Args)
Register a single-part checker (derived from Checker): construct its singleton instance,...
void reportInvalidCheckerOptionValue(const CheckerFrontend *Checker, StringRef OptionName, StringRef ExpectedValueDesc) const
Emits an error through a DiagnosticsEngine about an invalid user supplied checker option value.
Simple checker classes that implement one frontend (i.e.
Definition Checker.h:565
static PathDiagnosticLocation create(const Decl *D, const SourceManager &SM)
Create a location corresponding to the given declaration.
CharacteristicKind
Indicates whether a file or directory holds normal user code, system code, or system code which is im...
Top level wrappers for InstallAPI frontend operations.
bool operator<(DeclarationName LHS, DeclarationName RHS)
Ordering on two declaration names.
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t int64_t
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t