PaddingChecker.cpp 15 KB

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