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