CodeGenPGO.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882
  1. //===--- CodeGenPGO.cpp - PGO Instrumentation for LLVM CodeGen --*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // Instrumentation-based profile-guided optimization
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CodeGenPGO.h"
  14. #include "CodeGenFunction.h"
  15. #include "CoverageMappingGen.h"
  16. #include "clang/AST/RecursiveASTVisitor.h"
  17. #include "clang/AST/StmtVisitor.h"
  18. #include "llvm/IR/Intrinsics.h"
  19. #include "llvm/IR/MDBuilder.h"
  20. #include "llvm/ProfileData/InstrProfReader.h"
  21. #include "llvm/Support/Endian.h"
  22. #include "llvm/Support/FileSystem.h"
  23. #include "llvm/Support/MD5.h"
  24. using namespace clang;
  25. using namespace CodeGen;
  26. void CodeGenPGO::setFuncName(StringRef Name,
  27. llvm::GlobalValue::LinkageTypes Linkage) {
  28. StringRef RawFuncName = Name;
  29. // Function names may be prefixed with a binary '1' to indicate
  30. // that the backend should not modify the symbols due to any platform
  31. // naming convention. Do not include that '1' in the PGO profile name.
  32. if (RawFuncName[0] == '\1')
  33. RawFuncName = RawFuncName.substr(1);
  34. FuncName = RawFuncName;
  35. if (llvm::GlobalValue::isLocalLinkage(Linkage)) {
  36. // For local symbols, prepend the main file name to distinguish them.
  37. // Do not include the full path in the file name since there's no guarantee
  38. // that it will stay the same, e.g., if the files are checked out from
  39. // version control in different locations.
  40. if (CGM.getCodeGenOpts().MainFileName.empty())
  41. FuncName = FuncName.insert(0, "<unknown>:");
  42. else
  43. FuncName = FuncName.insert(0, CGM.getCodeGenOpts().MainFileName + ":");
  44. }
  45. // If we're generating a profile, create a variable for the name.
  46. if (CGM.getCodeGenOpts().ProfileInstrGenerate)
  47. createFuncNameVar(Linkage);
  48. }
  49. void CodeGenPGO::setFuncName(llvm::Function *Fn) {
  50. setFuncName(Fn->getName(), Fn->getLinkage());
  51. }
  52. void CodeGenPGO::createFuncNameVar(llvm::GlobalValue::LinkageTypes Linkage) {
  53. // We generally want to match the function's linkage, but available_externally
  54. // and extern_weak both have the wrong semantics, and anything that doesn't
  55. // need to link across compilation units doesn't need to be visible at all.
  56. if (Linkage == llvm::GlobalValue::ExternalWeakLinkage)
  57. Linkage = llvm::GlobalValue::LinkOnceAnyLinkage;
  58. else if (Linkage == llvm::GlobalValue::AvailableExternallyLinkage)
  59. Linkage = llvm::GlobalValue::LinkOnceODRLinkage;
  60. else if (Linkage == llvm::GlobalValue::InternalLinkage ||
  61. Linkage == llvm::GlobalValue::ExternalLinkage)
  62. Linkage = llvm::GlobalValue::PrivateLinkage;
  63. auto *Value =
  64. llvm::ConstantDataArray::getString(CGM.getLLVMContext(), FuncName, false);
  65. FuncNameVar =
  66. new llvm::GlobalVariable(CGM.getModule(), Value->getType(), true, Linkage,
  67. Value, "__llvm_profile_name_" + FuncName);
  68. // Hide the symbol so that we correctly get a copy for each executable.
  69. if (!llvm::GlobalValue::isLocalLinkage(FuncNameVar->getLinkage()))
  70. FuncNameVar->setVisibility(llvm::GlobalValue::HiddenVisibility);
  71. }
  72. namespace {
  73. /// \brief Stable hasher for PGO region counters.
  74. ///
  75. /// PGOHash produces a stable hash of a given function's control flow.
  76. ///
  77. /// Changing the output of this hash will invalidate all previously generated
  78. /// profiles -- i.e., don't do it.
  79. ///
  80. /// \note When this hash does eventually change (years?), we still need to
  81. /// support old hashes. We'll need to pull in the version number from the
  82. /// profile data format and use the matching hash function.
  83. class PGOHash {
  84. uint64_t Working;
  85. unsigned Count;
  86. llvm::MD5 MD5;
  87. static const int NumBitsPerType = 6;
  88. static const unsigned NumTypesPerWord = sizeof(uint64_t) * 8 / NumBitsPerType;
  89. static const unsigned TooBig = 1u << NumBitsPerType;
  90. public:
  91. /// \brief Hash values for AST nodes.
  92. ///
  93. /// Distinct values for AST nodes that have region counters attached.
  94. ///
  95. /// These values must be stable. All new members must be added at the end,
  96. /// and no members should be removed. Changing the enumeration value for an
  97. /// AST node will affect the hash of every function that contains that node.
  98. enum HashType : unsigned char {
  99. None = 0,
  100. LabelStmt = 1,
  101. WhileStmt,
  102. DoStmt,
  103. ForStmt,
  104. CXXForRangeStmt,
  105. ObjCForCollectionStmt,
  106. SwitchStmt,
  107. CaseStmt,
  108. DefaultStmt,
  109. IfStmt,
  110. CXXTryStmt,
  111. CXXCatchStmt,
  112. ConditionalOperator,
  113. BinaryOperatorLAnd,
  114. BinaryOperatorLOr,
  115. BinaryConditionalOperator,
  116. // Keep this last. It's for the static assert that follows.
  117. LastHashType
  118. };
  119. static_assert(LastHashType <= TooBig, "Too many types in HashType");
  120. // TODO: When this format changes, take in a version number here, and use the
  121. // old hash calculation for file formats that used the old hash.
  122. PGOHash() : Working(0), Count(0) {}
  123. void combine(HashType Type);
  124. uint64_t finalize();
  125. };
  126. const int PGOHash::NumBitsPerType;
  127. const unsigned PGOHash::NumTypesPerWord;
  128. const unsigned PGOHash::TooBig;
  129. /// A RecursiveASTVisitor that fills a map of statements to PGO counters.
  130. struct MapRegionCounters : public RecursiveASTVisitor<MapRegionCounters> {
  131. /// The next counter value to assign.
  132. unsigned NextCounter;
  133. /// The function hash.
  134. PGOHash Hash;
  135. /// The map of statements to counters.
  136. llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
  137. MapRegionCounters(llvm::DenseMap<const Stmt *, unsigned> &CounterMap)
  138. : NextCounter(0), CounterMap(CounterMap) {}
  139. // Blocks and lambdas are handled as separate functions, so we need not
  140. // traverse them in the parent context.
  141. bool TraverseBlockExpr(BlockExpr *BE) { return true; }
  142. bool TraverseLambdaBody(LambdaExpr *LE) { return true; }
  143. bool TraverseCapturedStmt(CapturedStmt *CS) { return true; }
  144. bool VisitDecl(const Decl *D) {
  145. switch (D->getKind()) {
  146. default:
  147. break;
  148. case Decl::Function:
  149. case Decl::CXXMethod:
  150. case Decl::CXXConstructor:
  151. case Decl::CXXDestructor:
  152. case Decl::CXXConversion:
  153. case Decl::ObjCMethod:
  154. case Decl::Block:
  155. case Decl::Captured:
  156. CounterMap[D->getBody()] = NextCounter++;
  157. break;
  158. }
  159. return true;
  160. }
  161. bool VisitStmt(const Stmt *S) {
  162. auto Type = getHashType(S);
  163. if (Type == PGOHash::None)
  164. return true;
  165. CounterMap[S] = NextCounter++;
  166. Hash.combine(Type);
  167. return true;
  168. }
  169. PGOHash::HashType getHashType(const Stmt *S) {
  170. switch (S->getStmtClass()) {
  171. default:
  172. break;
  173. case Stmt::LabelStmtClass:
  174. return PGOHash::LabelStmt;
  175. case Stmt::WhileStmtClass:
  176. return PGOHash::WhileStmt;
  177. case Stmt::DoStmtClass:
  178. return PGOHash::DoStmt;
  179. case Stmt::ForStmtClass:
  180. return PGOHash::ForStmt;
  181. case Stmt::CXXForRangeStmtClass:
  182. return PGOHash::CXXForRangeStmt;
  183. case Stmt::ObjCForCollectionStmtClass:
  184. return PGOHash::ObjCForCollectionStmt;
  185. case Stmt::SwitchStmtClass:
  186. return PGOHash::SwitchStmt;
  187. case Stmt::CaseStmtClass:
  188. return PGOHash::CaseStmt;
  189. case Stmt::DefaultStmtClass:
  190. return PGOHash::DefaultStmt;
  191. case Stmt::IfStmtClass:
  192. return PGOHash::IfStmt;
  193. case Stmt::CXXTryStmtClass:
  194. return PGOHash::CXXTryStmt;
  195. case Stmt::CXXCatchStmtClass:
  196. return PGOHash::CXXCatchStmt;
  197. case Stmt::ConditionalOperatorClass:
  198. return PGOHash::ConditionalOperator;
  199. case Stmt::BinaryConditionalOperatorClass:
  200. return PGOHash::BinaryConditionalOperator;
  201. case Stmt::BinaryOperatorClass: {
  202. const BinaryOperator *BO = cast<BinaryOperator>(S);
  203. if (BO->getOpcode() == BO_LAnd)
  204. return PGOHash::BinaryOperatorLAnd;
  205. if (BO->getOpcode() == BO_LOr)
  206. return PGOHash::BinaryOperatorLOr;
  207. break;
  208. }
  209. }
  210. return PGOHash::None;
  211. }
  212. };
  213. /// A StmtVisitor that propagates the raw counts through the AST and
  214. /// records the count at statements where the value may change.
  215. struct ComputeRegionCounts : public ConstStmtVisitor<ComputeRegionCounts> {
  216. /// PGO state.
  217. CodeGenPGO &PGO;
  218. /// A flag that is set when the current count should be recorded on the
  219. /// next statement, such as at the exit of a loop.
  220. bool RecordNextStmtCount;
  221. /// The count at the current location in the traversal.
  222. uint64_t CurrentCount;
  223. /// The map of statements to count values.
  224. llvm::DenseMap<const Stmt *, uint64_t> &CountMap;
  225. /// BreakContinueStack - Keep counts of breaks and continues inside loops.
  226. struct BreakContinue {
  227. uint64_t BreakCount;
  228. uint64_t ContinueCount;
  229. BreakContinue() : BreakCount(0), ContinueCount(0) {}
  230. };
  231. SmallVector<BreakContinue, 8> BreakContinueStack;
  232. ComputeRegionCounts(llvm::DenseMap<const Stmt *, uint64_t> &CountMap,
  233. CodeGenPGO &PGO)
  234. : PGO(PGO), RecordNextStmtCount(false), CountMap(CountMap) {}
  235. void RecordStmtCount(const Stmt *S) {
  236. if (RecordNextStmtCount) {
  237. CountMap[S] = CurrentCount;
  238. RecordNextStmtCount = false;
  239. }
  240. }
  241. /// Set and return the current count.
  242. uint64_t setCount(uint64_t Count) {
  243. CurrentCount = Count;
  244. return Count;
  245. }
  246. void VisitStmt(const Stmt *S) {
  247. RecordStmtCount(S);
  248. for (const Stmt *Child : S->children())
  249. if (Child)
  250. this->Visit(Child);
  251. }
  252. void VisitFunctionDecl(const FunctionDecl *D) {
  253. // Counter tracks entry to the function body.
  254. uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
  255. CountMap[D->getBody()] = BodyCount;
  256. Visit(D->getBody());
  257. }
  258. // Skip lambda expressions. We visit these as FunctionDecls when we're
  259. // generating them and aren't interested in the body when generating a
  260. // parent context.
  261. void VisitLambdaExpr(const LambdaExpr *LE) {}
  262. void VisitCapturedDecl(const CapturedDecl *D) {
  263. // Counter tracks entry to the capture body.
  264. uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
  265. CountMap[D->getBody()] = BodyCount;
  266. Visit(D->getBody());
  267. }
  268. void VisitObjCMethodDecl(const ObjCMethodDecl *D) {
  269. // Counter tracks entry to the method body.
  270. uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
  271. CountMap[D->getBody()] = BodyCount;
  272. Visit(D->getBody());
  273. }
  274. void VisitBlockDecl(const BlockDecl *D) {
  275. // Counter tracks entry to the block body.
  276. uint64_t BodyCount = setCount(PGO.getRegionCount(D->getBody()));
  277. CountMap[D->getBody()] = BodyCount;
  278. Visit(D->getBody());
  279. }
  280. void VisitReturnStmt(const ReturnStmt *S) {
  281. RecordStmtCount(S);
  282. if (S->getRetValue())
  283. Visit(S->getRetValue());
  284. CurrentCount = 0;
  285. RecordNextStmtCount = true;
  286. }
  287. void VisitCXXThrowExpr(const CXXThrowExpr *E) {
  288. RecordStmtCount(E);
  289. if (E->getSubExpr())
  290. Visit(E->getSubExpr());
  291. CurrentCount = 0;
  292. RecordNextStmtCount = true;
  293. }
  294. void VisitGotoStmt(const GotoStmt *S) {
  295. RecordStmtCount(S);
  296. CurrentCount = 0;
  297. RecordNextStmtCount = true;
  298. }
  299. void VisitLabelStmt(const LabelStmt *S) {
  300. RecordNextStmtCount = false;
  301. // Counter tracks the block following the label.
  302. uint64_t BlockCount = setCount(PGO.getRegionCount(S));
  303. CountMap[S] = BlockCount;
  304. Visit(S->getSubStmt());
  305. }
  306. void VisitBreakStmt(const BreakStmt *S) {
  307. RecordStmtCount(S);
  308. assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
  309. BreakContinueStack.back().BreakCount += CurrentCount;
  310. CurrentCount = 0;
  311. RecordNextStmtCount = true;
  312. }
  313. void VisitContinueStmt(const ContinueStmt *S) {
  314. RecordStmtCount(S);
  315. assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
  316. BreakContinueStack.back().ContinueCount += CurrentCount;
  317. CurrentCount = 0;
  318. RecordNextStmtCount = true;
  319. }
  320. void VisitWhileStmt(const WhileStmt *S) {
  321. RecordStmtCount(S);
  322. uint64_t ParentCount = CurrentCount;
  323. BreakContinueStack.push_back(BreakContinue());
  324. // Visit the body region first so the break/continue adjustments can be
  325. // included when visiting the condition.
  326. uint64_t BodyCount = setCount(PGO.getRegionCount(S));
  327. CountMap[S->getBody()] = CurrentCount;
  328. Visit(S->getBody());
  329. uint64_t BackedgeCount = CurrentCount;
  330. // ...then go back and propagate counts through the condition. The count
  331. // at the start of the condition is the sum of the incoming edges,
  332. // the backedge from the end of the loop body, and the edges from
  333. // continue statements.
  334. BreakContinue BC = BreakContinueStack.pop_back_val();
  335. uint64_t CondCount =
  336. setCount(ParentCount + BackedgeCount + BC.ContinueCount);
  337. CountMap[S->getCond()] = CondCount;
  338. Visit(S->getCond());
  339. setCount(BC.BreakCount + CondCount - BodyCount);
  340. RecordNextStmtCount = true;
  341. }
  342. void VisitDoStmt(const DoStmt *S) {
  343. RecordStmtCount(S);
  344. uint64_t LoopCount = PGO.getRegionCount(S);
  345. BreakContinueStack.push_back(BreakContinue());
  346. // The count doesn't include the fallthrough from the parent scope. Add it.
  347. uint64_t BodyCount = setCount(LoopCount + CurrentCount);
  348. CountMap[S->getBody()] = BodyCount;
  349. Visit(S->getBody());
  350. uint64_t BackedgeCount = CurrentCount;
  351. BreakContinue BC = BreakContinueStack.pop_back_val();
  352. // The count at the start of the condition is equal to the count at the
  353. // end of the body, plus any continues.
  354. uint64_t CondCount = setCount(BackedgeCount + BC.ContinueCount);
  355. CountMap[S->getCond()] = CondCount;
  356. Visit(S->getCond());
  357. setCount(BC.BreakCount + CondCount - LoopCount);
  358. RecordNextStmtCount = true;
  359. }
  360. void VisitForStmt(const ForStmt *S) {
  361. RecordStmtCount(S);
  362. if (S->getInit())
  363. Visit(S->getInit());
  364. uint64_t ParentCount = CurrentCount;
  365. BreakContinueStack.push_back(BreakContinue());
  366. // Visit the body region first. (This is basically the same as a while
  367. // loop; see further comments in VisitWhileStmt.)
  368. uint64_t BodyCount = setCount(PGO.getRegionCount(S));
  369. CountMap[S->getBody()] = BodyCount;
  370. Visit(S->getBody());
  371. uint64_t BackedgeCount = CurrentCount;
  372. BreakContinue BC = BreakContinueStack.pop_back_val();
  373. // The increment is essentially part of the body but it needs to include
  374. // the count for all the continue statements.
  375. if (S->getInc()) {
  376. uint64_t IncCount = setCount(BackedgeCount + BC.ContinueCount);
  377. CountMap[S->getInc()] = IncCount;
  378. Visit(S->getInc());
  379. }
  380. // ...then go back and propagate counts through the condition.
  381. uint64_t CondCount =
  382. setCount(ParentCount + BackedgeCount + BC.ContinueCount);
  383. if (S->getCond()) {
  384. CountMap[S->getCond()] = CondCount;
  385. Visit(S->getCond());
  386. }
  387. setCount(BC.BreakCount + CondCount - BodyCount);
  388. RecordNextStmtCount = true;
  389. }
  390. void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
  391. RecordStmtCount(S);
  392. Visit(S->getLoopVarStmt());
  393. Visit(S->getRangeStmt());
  394. Visit(S->getBeginEndStmt());
  395. uint64_t ParentCount = CurrentCount;
  396. BreakContinueStack.push_back(BreakContinue());
  397. // Visit the body region first. (This is basically the same as a while
  398. // loop; see further comments in VisitWhileStmt.)
  399. uint64_t BodyCount = setCount(PGO.getRegionCount(S));
  400. CountMap[S->getBody()] = BodyCount;
  401. Visit(S->getBody());
  402. uint64_t BackedgeCount = CurrentCount;
  403. BreakContinue BC = BreakContinueStack.pop_back_val();
  404. // The increment is essentially part of the body but it needs to include
  405. // the count for all the continue statements.
  406. uint64_t IncCount = setCount(BackedgeCount + BC.ContinueCount);
  407. CountMap[S->getInc()] = IncCount;
  408. Visit(S->getInc());
  409. // ...then go back and propagate counts through the condition.
  410. uint64_t CondCount =
  411. setCount(ParentCount + BackedgeCount + BC.ContinueCount);
  412. CountMap[S->getCond()] = CondCount;
  413. Visit(S->getCond());
  414. setCount(BC.BreakCount + CondCount - BodyCount);
  415. RecordNextStmtCount = true;
  416. }
  417. void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
  418. RecordStmtCount(S);
  419. Visit(S->getElement());
  420. uint64_t ParentCount = CurrentCount;
  421. BreakContinueStack.push_back(BreakContinue());
  422. // Counter tracks the body of the loop.
  423. uint64_t BodyCount = setCount(PGO.getRegionCount(S));
  424. CountMap[S->getBody()] = BodyCount;
  425. Visit(S->getBody());
  426. uint64_t BackedgeCount = CurrentCount;
  427. BreakContinue BC = BreakContinueStack.pop_back_val();
  428. setCount(BC.BreakCount + ParentCount + BackedgeCount + BC.ContinueCount -
  429. BodyCount);
  430. RecordNextStmtCount = true;
  431. }
  432. void VisitSwitchStmt(const SwitchStmt *S) {
  433. RecordStmtCount(S);
  434. Visit(S->getCond());
  435. CurrentCount = 0;
  436. BreakContinueStack.push_back(BreakContinue());
  437. Visit(S->getBody());
  438. // If the switch is inside a loop, add the continue counts.
  439. BreakContinue BC = BreakContinueStack.pop_back_val();
  440. if (!BreakContinueStack.empty())
  441. BreakContinueStack.back().ContinueCount += BC.ContinueCount;
  442. // Counter tracks the exit block of the switch.
  443. setCount(PGO.getRegionCount(S));
  444. RecordNextStmtCount = true;
  445. }
  446. void VisitSwitchCase(const SwitchCase *S) {
  447. RecordNextStmtCount = false;
  448. // Counter for this particular case. This counts only jumps from the
  449. // switch header and does not include fallthrough from the case before
  450. // this one.
  451. uint64_t CaseCount = PGO.getRegionCount(S);
  452. setCount(CurrentCount + CaseCount);
  453. // We need the count without fallthrough in the mapping, so it's more useful
  454. // for branch probabilities.
  455. CountMap[S] = CaseCount;
  456. RecordNextStmtCount = true;
  457. Visit(S->getSubStmt());
  458. }
  459. void VisitIfStmt(const IfStmt *S) {
  460. RecordStmtCount(S);
  461. uint64_t ParentCount = CurrentCount;
  462. Visit(S->getCond());
  463. // Counter tracks the "then" part of an if statement. The count for
  464. // the "else" part, if it exists, will be calculated from this counter.
  465. uint64_t ThenCount = setCount(PGO.getRegionCount(S));
  466. CountMap[S->getThen()] = ThenCount;
  467. Visit(S->getThen());
  468. uint64_t OutCount = CurrentCount;
  469. uint64_t ElseCount = ParentCount - ThenCount;
  470. if (S->getElse()) {
  471. setCount(ElseCount);
  472. CountMap[S->getElse()] = ElseCount;
  473. Visit(S->getElse());
  474. OutCount += CurrentCount;
  475. } else
  476. OutCount += ElseCount;
  477. setCount(OutCount);
  478. RecordNextStmtCount = true;
  479. }
  480. void VisitCXXTryStmt(const CXXTryStmt *S) {
  481. RecordStmtCount(S);
  482. Visit(S->getTryBlock());
  483. for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
  484. Visit(S->getHandler(I));
  485. // Counter tracks the continuation block of the try statement.
  486. setCount(PGO.getRegionCount(S));
  487. RecordNextStmtCount = true;
  488. }
  489. void VisitCXXCatchStmt(const CXXCatchStmt *S) {
  490. RecordNextStmtCount = false;
  491. // Counter tracks the catch statement's handler block.
  492. uint64_t CatchCount = setCount(PGO.getRegionCount(S));
  493. CountMap[S] = CatchCount;
  494. Visit(S->getHandlerBlock());
  495. }
  496. void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
  497. RecordStmtCount(E);
  498. uint64_t ParentCount = CurrentCount;
  499. Visit(E->getCond());
  500. // Counter tracks the "true" part of a conditional operator. The
  501. // count in the "false" part will be calculated from this counter.
  502. uint64_t TrueCount = setCount(PGO.getRegionCount(E));
  503. CountMap[E->getTrueExpr()] = TrueCount;
  504. Visit(E->getTrueExpr());
  505. uint64_t OutCount = CurrentCount;
  506. uint64_t FalseCount = setCount(ParentCount - TrueCount);
  507. CountMap[E->getFalseExpr()] = FalseCount;
  508. Visit(E->getFalseExpr());
  509. OutCount += CurrentCount;
  510. setCount(OutCount);
  511. RecordNextStmtCount = true;
  512. }
  513. void VisitBinLAnd(const BinaryOperator *E) {
  514. RecordStmtCount(E);
  515. uint64_t ParentCount = CurrentCount;
  516. Visit(E->getLHS());
  517. // Counter tracks the right hand side of a logical and operator.
  518. uint64_t RHSCount = setCount(PGO.getRegionCount(E));
  519. CountMap[E->getRHS()] = RHSCount;
  520. Visit(E->getRHS());
  521. setCount(ParentCount + RHSCount - CurrentCount);
  522. RecordNextStmtCount = true;
  523. }
  524. void VisitBinLOr(const BinaryOperator *E) {
  525. RecordStmtCount(E);
  526. uint64_t ParentCount = CurrentCount;
  527. Visit(E->getLHS());
  528. // Counter tracks the right hand side of a logical or operator.
  529. uint64_t RHSCount = setCount(PGO.getRegionCount(E));
  530. CountMap[E->getRHS()] = RHSCount;
  531. Visit(E->getRHS());
  532. setCount(ParentCount + RHSCount - CurrentCount);
  533. RecordNextStmtCount = true;
  534. }
  535. };
  536. }
  537. void PGOHash::combine(HashType Type) {
  538. // Check that we never combine 0 and only have six bits.
  539. assert(Type && "Hash is invalid: unexpected type 0");
  540. assert(unsigned(Type) < TooBig && "Hash is invalid: too many types");
  541. // Pass through MD5 if enough work has built up.
  542. if (Count && Count % NumTypesPerWord == 0) {
  543. using namespace llvm::support;
  544. uint64_t Swapped = endian::byte_swap<uint64_t, little>(Working);
  545. MD5.update(llvm::makeArrayRef((uint8_t *)&Swapped, sizeof(Swapped)));
  546. Working = 0;
  547. }
  548. // Accumulate the current type.
  549. ++Count;
  550. Working = Working << NumBitsPerType | Type;
  551. }
  552. uint64_t PGOHash::finalize() {
  553. // Use Working as the hash directly if we never used MD5.
  554. if (Count <= NumTypesPerWord)
  555. // No need to byte swap here, since none of the math was endian-dependent.
  556. // This number will be byte-swapped as required on endianness transitions,
  557. // so we will see the same value on the other side.
  558. return Working;
  559. // Check for remaining work in Working.
  560. if (Working)
  561. MD5.update(Working);
  562. // Finalize the MD5 and return the hash.
  563. llvm::MD5::MD5Result Result;
  564. MD5.final(Result);
  565. using namespace llvm::support;
  566. return endian::read<uint64_t, little, unaligned>(Result);
  567. }
  568. void CodeGenPGO::checkGlobalDecl(GlobalDecl GD) {
  569. // Make sure we only emit coverage mapping for one constructor/destructor.
  570. // Clang emits several functions for the constructor and the destructor of
  571. // a class. Every function is instrumented, but we only want to provide
  572. // coverage for one of them. Because of that we only emit the coverage mapping
  573. // for the base constructor/destructor.
  574. if ((isa<CXXConstructorDecl>(GD.getDecl()) &&
  575. GD.getCtorType() != Ctor_Base) ||
  576. (isa<CXXDestructorDecl>(GD.getDecl()) &&
  577. GD.getDtorType() != Dtor_Base)) {
  578. SkipCoverageMapping = true;
  579. }
  580. }
  581. void CodeGenPGO::assignRegionCounters(const Decl *D, llvm::Function *Fn) {
  582. bool InstrumentRegions = CGM.getCodeGenOpts().ProfileInstrGenerate;
  583. llvm::IndexedInstrProfReader *PGOReader = CGM.getPGOReader();
  584. if (!InstrumentRegions && !PGOReader)
  585. return;
  586. if (D->isImplicit())
  587. return;
  588. CGM.ClearUnusedCoverageMapping(D);
  589. setFuncName(Fn);
  590. mapRegionCounters(D);
  591. if (CGM.getCodeGenOpts().CoverageMapping)
  592. emitCounterRegionMapping(D);
  593. if (PGOReader) {
  594. SourceManager &SM = CGM.getContext().getSourceManager();
  595. loadRegionCounts(PGOReader, SM.isInMainFile(D->getLocation()));
  596. computeRegionCounts(D);
  597. applyFunctionAttributes(PGOReader, Fn);
  598. }
  599. }
  600. void CodeGenPGO::mapRegionCounters(const Decl *D) {
  601. RegionCounterMap.reset(new llvm::DenseMap<const Stmt *, unsigned>);
  602. MapRegionCounters Walker(*RegionCounterMap);
  603. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  604. Walker.TraverseDecl(const_cast<FunctionDecl *>(FD));
  605. else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
  606. Walker.TraverseDecl(const_cast<ObjCMethodDecl *>(MD));
  607. else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D))
  608. Walker.TraverseDecl(const_cast<BlockDecl *>(BD));
  609. else if (const CapturedDecl *CD = dyn_cast_or_null<CapturedDecl>(D))
  610. Walker.TraverseDecl(const_cast<CapturedDecl *>(CD));
  611. assert(Walker.NextCounter > 0 && "no entry counter mapped for decl");
  612. NumRegionCounters = Walker.NextCounter;
  613. FunctionHash = Walker.Hash.finalize();
  614. }
  615. void CodeGenPGO::emitCounterRegionMapping(const Decl *D) {
  616. if (SkipCoverageMapping)
  617. return;
  618. // Don't map the functions inside the system headers
  619. auto Loc = D->getBody()->getLocStart();
  620. if (CGM.getContext().getSourceManager().isInSystemHeader(Loc))
  621. return;
  622. std::string CoverageMapping;
  623. llvm::raw_string_ostream OS(CoverageMapping);
  624. CoverageMappingGen MappingGen(*CGM.getCoverageMapping(),
  625. CGM.getContext().getSourceManager(),
  626. CGM.getLangOpts(), RegionCounterMap.get());
  627. MappingGen.emitCounterMapping(D, OS);
  628. OS.flush();
  629. if (CoverageMapping.empty())
  630. return;
  631. CGM.getCoverageMapping()->addFunctionMappingRecord(
  632. FuncNameVar, FuncName, FunctionHash, CoverageMapping);
  633. }
  634. void
  635. CodeGenPGO::emitEmptyCounterMapping(const Decl *D, StringRef Name,
  636. llvm::GlobalValue::LinkageTypes Linkage) {
  637. if (SkipCoverageMapping)
  638. return;
  639. // Don't map the functions inside the system headers
  640. auto Loc = D->getBody()->getLocStart();
  641. if (CGM.getContext().getSourceManager().isInSystemHeader(Loc))
  642. return;
  643. std::string CoverageMapping;
  644. llvm::raw_string_ostream OS(CoverageMapping);
  645. CoverageMappingGen MappingGen(*CGM.getCoverageMapping(),
  646. CGM.getContext().getSourceManager(),
  647. CGM.getLangOpts());
  648. MappingGen.emitEmptyMapping(D, OS);
  649. OS.flush();
  650. if (CoverageMapping.empty())
  651. return;
  652. setFuncName(Name, Linkage);
  653. CGM.getCoverageMapping()->addFunctionMappingRecord(
  654. FuncNameVar, FuncName, FunctionHash, CoverageMapping);
  655. }
  656. void CodeGenPGO::computeRegionCounts(const Decl *D) {
  657. StmtCountMap.reset(new llvm::DenseMap<const Stmt *, uint64_t>);
  658. ComputeRegionCounts Walker(*StmtCountMap, *this);
  659. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  660. Walker.VisitFunctionDecl(FD);
  661. else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
  662. Walker.VisitObjCMethodDecl(MD);
  663. else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D))
  664. Walker.VisitBlockDecl(BD);
  665. else if (const CapturedDecl *CD = dyn_cast_or_null<CapturedDecl>(D))
  666. Walker.VisitCapturedDecl(const_cast<CapturedDecl *>(CD));
  667. }
  668. void
  669. CodeGenPGO::applyFunctionAttributes(llvm::IndexedInstrProfReader *PGOReader,
  670. llvm::Function *Fn) {
  671. if (!haveRegionCounts())
  672. return;
  673. uint64_t MaxFunctionCount = PGOReader->getMaximumFunctionCount();
  674. uint64_t FunctionCount = getRegionCount(0);
  675. if (FunctionCount >= (uint64_t)(0.3 * (double)MaxFunctionCount))
  676. // Turn on InlineHint attribute for hot functions.
  677. // FIXME: 30% is from preliminary tuning on SPEC, it may not be optimal.
  678. Fn->addFnAttr(llvm::Attribute::InlineHint);
  679. else if (FunctionCount <= (uint64_t)(0.01 * (double)MaxFunctionCount))
  680. // Turn on Cold attribute for cold functions.
  681. // FIXME: 1% is from preliminary tuning on SPEC, it may not be optimal.
  682. Fn->addFnAttr(llvm::Attribute::Cold);
  683. Fn->setEntryCount(FunctionCount);
  684. }
  685. void CodeGenPGO::emitCounterIncrement(CGBuilderTy &Builder, const Stmt *S) {
  686. if (!CGM.getCodeGenOpts().ProfileInstrGenerate || !RegionCounterMap)
  687. return;
  688. if (!Builder.GetInsertPoint())
  689. return;
  690. unsigned Counter = (*RegionCounterMap)[S];
  691. auto *I8PtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
  692. Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::instrprof_increment),
  693. {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
  694. Builder.getInt64(FunctionHash),
  695. Builder.getInt32(NumRegionCounters),
  696. Builder.getInt32(Counter)});
  697. }
  698. void CodeGenPGO::loadRegionCounts(llvm::IndexedInstrProfReader *PGOReader,
  699. bool IsInMainFile) {
  700. CGM.getPGOStats().addVisited(IsInMainFile);
  701. RegionCounts.clear();
  702. if (std::error_code EC =
  703. PGOReader->getFunctionCounts(FuncName, FunctionHash, RegionCounts)) {
  704. if (EC == llvm::instrprof_error::unknown_function)
  705. CGM.getPGOStats().addMissing(IsInMainFile);
  706. else if (EC == llvm::instrprof_error::hash_mismatch)
  707. CGM.getPGOStats().addMismatched(IsInMainFile);
  708. else if (EC == llvm::instrprof_error::malformed)
  709. // TODO: Consider a more specific warning for this case.
  710. CGM.getPGOStats().addMismatched(IsInMainFile);
  711. RegionCounts.clear();
  712. }
  713. }
  714. /// \brief Calculate what to divide by to scale weights.
  715. ///
  716. /// Given the maximum weight, calculate a divisor that will scale all the
  717. /// weights to strictly less than UINT32_MAX.
  718. static uint64_t calculateWeightScale(uint64_t MaxWeight) {
  719. return MaxWeight < UINT32_MAX ? 1 : MaxWeight / UINT32_MAX + 1;
  720. }
  721. /// \brief Scale an individual branch weight (and add 1).
  722. ///
  723. /// Scale a 64-bit weight down to 32-bits using \c Scale.
  724. ///
  725. /// According to Laplace's Rule of Succession, it is better to compute the
  726. /// weight based on the count plus 1, so universally add 1 to the value.
  727. ///
  728. /// \pre \c Scale was calculated by \a calculateWeightScale() with a weight no
  729. /// greater than \c Weight.
  730. static uint32_t scaleBranchWeight(uint64_t Weight, uint64_t Scale) {
  731. assert(Scale && "scale by 0?");
  732. uint64_t Scaled = Weight / Scale + 1;
  733. assert(Scaled <= UINT32_MAX && "overflow 32-bits");
  734. return Scaled;
  735. }
  736. llvm::MDNode *CodeGenFunction::createProfileWeights(uint64_t TrueCount,
  737. uint64_t FalseCount) {
  738. // Check for empty weights.
  739. if (!TrueCount && !FalseCount)
  740. return nullptr;
  741. // Calculate how to scale down to 32-bits.
  742. uint64_t Scale = calculateWeightScale(std::max(TrueCount, FalseCount));
  743. llvm::MDBuilder MDHelper(CGM.getLLVMContext());
  744. return MDHelper.createBranchWeights(scaleBranchWeight(TrueCount, Scale),
  745. scaleBranchWeight(FalseCount, Scale));
  746. }
  747. llvm::MDNode *
  748. CodeGenFunction::createProfileWeights(ArrayRef<uint64_t> Weights) {
  749. // We need at least two elements to create meaningful weights.
  750. if (Weights.size() < 2)
  751. return nullptr;
  752. // Check for empty weights.
  753. uint64_t MaxWeight = *std::max_element(Weights.begin(), Weights.end());
  754. if (MaxWeight == 0)
  755. return nullptr;
  756. // Calculate how to scale down to 32-bits.
  757. uint64_t Scale = calculateWeightScale(MaxWeight);
  758. SmallVector<uint32_t, 16> ScaledWeights;
  759. ScaledWeights.reserve(Weights.size());
  760. for (uint64_t W : Weights)
  761. ScaledWeights.push_back(scaleBranchWeight(W, Scale));
  762. llvm::MDBuilder MDHelper(CGM.getLLVMContext());
  763. return MDHelper.createBranchWeights(ScaledWeights);
  764. }
  765. llvm::MDNode *CodeGenFunction::createProfileWeightsForLoop(const Stmt *Cond,
  766. uint64_t LoopCount) {
  767. if (!PGO.haveRegionCounts())
  768. return nullptr;
  769. Optional<uint64_t> CondCount = PGO.getStmtCount(Cond);
  770. assert(CondCount.hasValue() && "missing expected loop condition count");
  771. if (*CondCount == 0)
  772. return nullptr;
  773. return createProfileWeights(LoopCount,
  774. std::max(*CondCount, LoopCount) - LoopCount);
  775. }