SampleProfile.cpp 104 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693
  1. //===- SampleProfile.cpp - Incorporate sample profiles into the IR --------===//
  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 implements the SampleProfileLoader transformation. This pass
  10. // reads a profile file generated by a sampling profiler (e.g. Linux Perf -
  11. // http://perf.wiki.kernel.org/) and generates IR metadata to reflect the
  12. // profile information in the given profile.
  13. //
  14. // This pass generates branch weight annotations on the IR:
  15. //
  16. // - prof: Represents branch weights. This annotation is added to branches
  17. // to indicate the weights of each edge coming out of the branch.
  18. // The weight of each edge is the weight of the target block for
  19. // that edge. The weight of a block B is computed as the maximum
  20. // number of samples found in B.
  21. //
  22. //===----------------------------------------------------------------------===//
  23. #include "llvm/Transforms/IPO/SampleProfile.h"
  24. #include "llvm/ADT/ArrayRef.h"
  25. #include "llvm/ADT/DenseMap.h"
  26. #include "llvm/ADT/DenseSet.h"
  27. #include "llvm/ADT/None.h"
  28. #include "llvm/ADT/PriorityQueue.h"
  29. #include "llvm/ADT/SCCIterator.h"
  30. #include "llvm/ADT/SmallPtrSet.h"
  31. #include "llvm/ADT/SmallSet.h"
  32. #include "llvm/ADT/SmallVector.h"
  33. #include "llvm/ADT/Statistic.h"
  34. #include "llvm/ADT/StringMap.h"
  35. #include "llvm/ADT/StringRef.h"
  36. #include "llvm/ADT/Twine.h"
  37. #include "llvm/Analysis/AssumptionCache.h"
  38. #include "llvm/Analysis/CallGraph.h"
  39. #include "llvm/Analysis/CallGraphSCCPass.h"
  40. #include "llvm/Analysis/InlineAdvisor.h"
  41. #include "llvm/Analysis/InlineCost.h"
  42. #include "llvm/Analysis/LoopInfo.h"
  43. #include "llvm/Analysis/OptimizationRemarkEmitter.h"
  44. #include "llvm/Analysis/PostDominators.h"
  45. #include "llvm/Analysis/ProfileSummaryInfo.h"
  46. #include "llvm/Analysis/ReplayInlineAdvisor.h"
  47. #include "llvm/Analysis/TargetLibraryInfo.h"
  48. #include "llvm/Analysis/TargetTransformInfo.h"
  49. #include "llvm/IR/BasicBlock.h"
  50. #include "llvm/IR/CFG.h"
  51. #include "llvm/IR/DebugInfoMetadata.h"
  52. #include "llvm/IR/DebugLoc.h"
  53. #include "llvm/IR/DiagnosticInfo.h"
  54. #include "llvm/IR/Dominators.h"
  55. #include "llvm/IR/Function.h"
  56. #include "llvm/IR/GlobalValue.h"
  57. #include "llvm/IR/InstrTypes.h"
  58. #include "llvm/IR/Instruction.h"
  59. #include "llvm/IR/Instructions.h"
  60. #include "llvm/IR/IntrinsicInst.h"
  61. #include "llvm/IR/LLVMContext.h"
  62. #include "llvm/IR/MDBuilder.h"
  63. #include "llvm/IR/Module.h"
  64. #include "llvm/IR/PassManager.h"
  65. #include "llvm/IR/ValueSymbolTable.h"
  66. #include "llvm/InitializePasses.h"
  67. #include "llvm/Pass.h"
  68. #include "llvm/ProfileData/InstrProf.h"
  69. #include "llvm/ProfileData/SampleProf.h"
  70. #include "llvm/ProfileData/SampleProfReader.h"
  71. #include "llvm/Support/Casting.h"
  72. #include "llvm/Support/CommandLine.h"
  73. #include "llvm/Support/Debug.h"
  74. #include "llvm/Support/ErrorHandling.h"
  75. #include "llvm/Support/ErrorOr.h"
  76. #include "llvm/Support/GenericDomTree.h"
  77. #include "llvm/Support/raw_ostream.h"
  78. #include "llvm/Transforms/IPO.h"
  79. #include "llvm/Transforms/IPO/SampleContextTracker.h"
  80. #include "llvm/Transforms/IPO/SampleProfileProbe.h"
  81. #include "llvm/Transforms/Instrumentation.h"
  82. #include "llvm/Transforms/Utils/CallPromotionUtils.h"
  83. #include "llvm/Transforms/Utils/Cloning.h"
  84. #include <algorithm>
  85. #include <cassert>
  86. #include <cstdint>
  87. #include <functional>
  88. #include <limits>
  89. #include <map>
  90. #include <memory>
  91. #include <queue>
  92. #include <string>
  93. #include <system_error>
  94. #include <utility>
  95. #include <vector>
  96. using namespace llvm;
  97. using namespace sampleprof;
  98. using ProfileCount = Function::ProfileCount;
  99. #define DEBUG_TYPE "sample-profile"
  100. #define CSINLINE_DEBUG DEBUG_TYPE "-inline"
  101. STATISTIC(NumCSInlined,
  102. "Number of functions inlined with context sensitive profile");
  103. STATISTIC(NumCSNotInlined,
  104. "Number of functions not inlined with context sensitive profile");
  105. STATISTIC(NumMismatchedProfile,
  106. "Number of functions with CFG mismatched profile");
  107. STATISTIC(NumMatchedProfile, "Number of functions with CFG matched profile");
  108. STATISTIC(NumDuplicatedInlinesite,
  109. "Number of inlined callsites with a partial distribution factor");
  110. STATISTIC(NumCSInlinedHitMinLimit,
  111. "Number of functions with FDO inline stopped due to min size limit");
  112. STATISTIC(NumCSInlinedHitMaxLimit,
  113. "Number of functions with FDO inline stopped due to max size limit");
  114. STATISTIC(
  115. NumCSInlinedHitGrowthLimit,
  116. "Number of functions with FDO inline stopped due to growth size limit");
  117. // Command line option to specify the file to read samples from. This is
  118. // mainly used for debugging.
  119. static cl::opt<std::string> SampleProfileFile(
  120. "sample-profile-file", cl::init(""), cl::value_desc("filename"),
  121. cl::desc("Profile file loaded by -sample-profile"), cl::Hidden);
  122. // The named file contains a set of transformations that may have been applied
  123. // to the symbol names between the program from which the sample data was
  124. // collected and the current program's symbols.
  125. static cl::opt<std::string> SampleProfileRemappingFile(
  126. "sample-profile-remapping-file", cl::init(""), cl::value_desc("filename"),
  127. cl::desc("Profile remapping file loaded by -sample-profile"), cl::Hidden);
  128. static cl::opt<unsigned> SampleProfileMaxPropagateIterations(
  129. "sample-profile-max-propagate-iterations", cl::init(100),
  130. cl::desc("Maximum number of iterations to go through when propagating "
  131. "sample block/edge weights through the CFG."));
  132. static cl::opt<unsigned> SampleProfileRecordCoverage(
  133. "sample-profile-check-record-coverage", cl::init(0), cl::value_desc("N"),
  134. cl::desc("Emit a warning if less than N% of records in the input profile "
  135. "are matched to the IR."));
  136. static cl::opt<unsigned> SampleProfileSampleCoverage(
  137. "sample-profile-check-sample-coverage", cl::init(0), cl::value_desc("N"),
  138. cl::desc("Emit a warning if less than N% of samples in the input profile "
  139. "are matched to the IR."));
  140. static cl::opt<bool> NoWarnSampleUnused(
  141. "no-warn-sample-unused", cl::init(false), cl::Hidden,
  142. cl::desc("Use this option to turn off/on warnings about function with "
  143. "samples but without debug information to use those samples. "));
  144. static cl::opt<bool> ProfileSampleAccurate(
  145. "profile-sample-accurate", cl::Hidden, cl::init(false),
  146. cl::desc("If the sample profile is accurate, we will mark all un-sampled "
  147. "callsite and function as having 0 samples. Otherwise, treat "
  148. "un-sampled callsites and functions conservatively as unknown. "));
  149. static cl::opt<bool> ProfileAccurateForSymsInList(
  150. "profile-accurate-for-symsinlist", cl::Hidden, cl::ZeroOrMore,
  151. cl::init(true),
  152. cl::desc("For symbols in profile symbol list, regard their profiles to "
  153. "be accurate. It may be overriden by profile-sample-accurate. "));
  154. static cl::opt<bool> ProfileMergeInlinee(
  155. "sample-profile-merge-inlinee", cl::Hidden, cl::init(true),
  156. cl::desc("Merge past inlinee's profile to outline version if sample "
  157. "profile loader decided not to inline a call site. It will "
  158. "only be enabled when top-down order of profile loading is "
  159. "enabled. "));
  160. static cl::opt<bool> ProfileTopDownLoad(
  161. "sample-profile-top-down-load", cl::Hidden, cl::init(true),
  162. cl::desc("Do profile annotation and inlining for functions in top-down "
  163. "order of call graph during sample profile loading. It only "
  164. "works for new pass manager. "));
  165. static cl::opt<bool> UseProfileIndirectCallEdges(
  166. "use-profile-indirect-call-edges", cl::init(true), cl::Hidden,
  167. cl::desc("Considering indirect call samples from profile when top-down "
  168. "processing functions. Only CSSPGO is supported."));
  169. static cl::opt<bool> UseProfileTopDownOrder(
  170. "use-profile-top-down-order", cl::init(false), cl::Hidden,
  171. cl::desc("Process functions in one SCC in a top-down order "
  172. "based on the input profile."));
  173. static cl::opt<bool> ProfileSizeInline(
  174. "sample-profile-inline-size", cl::Hidden, cl::init(false),
  175. cl::desc("Inline cold call sites in profile loader if it's beneficial "
  176. "for code size."));
  177. static cl::opt<int> ProfileInlineGrowthLimit(
  178. "sample-profile-inline-growth-limit", cl::Hidden, cl::init(12),
  179. cl::desc("The size growth ratio limit for proirity-based sample profile "
  180. "loader inlining."));
  181. static cl::opt<int> ProfileInlineLimitMin(
  182. "sample-profile-inline-limit-min", cl::Hidden, cl::init(100),
  183. cl::desc("The lower bound of size growth limit for "
  184. "proirity-based sample profile loader inlining."));
  185. static cl::opt<int> ProfileInlineLimitMax(
  186. "sample-profile-inline-limit-max", cl::Hidden, cl::init(10000),
  187. cl::desc("The upper bound of size growth limit for "
  188. "proirity-based sample profile loader inlining."));
  189. static cl::opt<int> ProfileICPThreshold(
  190. "sample-profile-icp-threshold", cl::Hidden, cl::init(5),
  191. cl::desc(
  192. "Relative hotness threshold for indirect "
  193. "call promotion in proirity-based sample profile loader inlining."));
  194. static cl::opt<int> SampleHotCallSiteThreshold(
  195. "sample-profile-hot-inline-threshold", cl::Hidden, cl::init(3000),
  196. cl::desc("Hot callsite threshold for proirity-based sample profile loader "
  197. "inlining."));
  198. static cl::opt<bool> CallsitePrioritizedInline(
  199. "sample-profile-prioritized-inline", cl::Hidden, cl::ZeroOrMore,
  200. cl::init(false),
  201. cl::desc("Use call site prioritized inlining for sample profile loader."
  202. "Currently only CSSPGO is supported."));
  203. static cl::opt<int> SampleColdCallSiteThreshold(
  204. "sample-profile-cold-inline-threshold", cl::Hidden, cl::init(45),
  205. cl::desc("Threshold for inlining cold callsites"));
  206. static cl::opt<std::string> ProfileInlineReplayFile(
  207. "sample-profile-inline-replay", cl::init(""), cl::value_desc("filename"),
  208. cl::desc(
  209. "Optimization remarks file containing inline remarks to be replayed "
  210. "by inlining from sample profile loader."),
  211. cl::Hidden);
  212. namespace {
  213. using BlockWeightMap = DenseMap<const BasicBlock *, uint64_t>;
  214. using EquivalenceClassMap = DenseMap<const BasicBlock *, const BasicBlock *>;
  215. using Edge = std::pair<const BasicBlock *, const BasicBlock *>;
  216. using EdgeWeightMap = DenseMap<Edge, uint64_t>;
  217. using BlockEdgeMap =
  218. DenseMap<const BasicBlock *, SmallVector<const BasicBlock *, 8>>;
  219. class SampleProfileLoader;
  220. class SampleCoverageTracker {
  221. public:
  222. SampleCoverageTracker(SampleProfileLoader &SPL) : SPLoader(SPL){};
  223. bool markSamplesUsed(const FunctionSamples *FS, uint32_t LineOffset,
  224. uint32_t Discriminator, uint64_t Samples);
  225. unsigned computeCoverage(unsigned Used, unsigned Total) const;
  226. unsigned countUsedRecords(const FunctionSamples *FS,
  227. ProfileSummaryInfo *PSI) const;
  228. unsigned countBodyRecords(const FunctionSamples *FS,
  229. ProfileSummaryInfo *PSI) const;
  230. uint64_t getTotalUsedSamples() const { return TotalUsedSamples; }
  231. uint64_t countBodySamples(const FunctionSamples *FS,
  232. ProfileSummaryInfo *PSI) const;
  233. void clear() {
  234. SampleCoverage.clear();
  235. TotalUsedSamples = 0;
  236. }
  237. private:
  238. using BodySampleCoverageMap = std::map<LineLocation, unsigned>;
  239. using FunctionSamplesCoverageMap =
  240. DenseMap<const FunctionSamples *, BodySampleCoverageMap>;
  241. /// Coverage map for sampling records.
  242. ///
  243. /// This map keeps a record of sampling records that have been matched to
  244. /// an IR instruction. This is used to detect some form of staleness in
  245. /// profiles (see flag -sample-profile-check-coverage).
  246. ///
  247. /// Each entry in the map corresponds to a FunctionSamples instance. This is
  248. /// another map that counts how many times the sample record at the
  249. /// given location has been used.
  250. FunctionSamplesCoverageMap SampleCoverage;
  251. /// Number of samples used from the profile.
  252. ///
  253. /// When a sampling record is used for the first time, the samples from
  254. /// that record are added to this accumulator. Coverage is later computed
  255. /// based on the total number of samples available in this function and
  256. /// its callsites.
  257. ///
  258. /// Note that this accumulator tracks samples used from a single function
  259. /// and all the inlined callsites. Strictly, we should have a map of counters
  260. /// keyed by FunctionSamples pointers, but these stats are cleared after
  261. /// every function, so we just need to keep a single counter.
  262. uint64_t TotalUsedSamples = 0;
  263. SampleProfileLoader &SPLoader;
  264. };
  265. class GUIDToFuncNameMapper {
  266. public:
  267. GUIDToFuncNameMapper(Module &M, SampleProfileReader &Reader,
  268. DenseMap<uint64_t, StringRef> &GUIDToFuncNameMap)
  269. : CurrentReader(Reader), CurrentModule(M),
  270. CurrentGUIDToFuncNameMap(GUIDToFuncNameMap) {
  271. if (!CurrentReader.useMD5())
  272. return;
  273. for (const auto &F : CurrentModule) {
  274. StringRef OrigName = F.getName();
  275. CurrentGUIDToFuncNameMap.insert(
  276. {Function::getGUID(OrigName), OrigName});
  277. // Local to global var promotion used by optimization like thinlto
  278. // will rename the var and add suffix like ".llvm.xxx" to the
  279. // original local name. In sample profile, the suffixes of function
  280. // names are all stripped. Since it is possible that the mapper is
  281. // built in post-thin-link phase and var promotion has been done,
  282. // we need to add the substring of function name without the suffix
  283. // into the GUIDToFuncNameMap.
  284. StringRef CanonName = FunctionSamples::getCanonicalFnName(F);
  285. if (CanonName != OrigName)
  286. CurrentGUIDToFuncNameMap.insert(
  287. {Function::getGUID(CanonName), CanonName});
  288. }
  289. // Update GUIDToFuncNameMap for each function including inlinees.
  290. SetGUIDToFuncNameMapForAll(&CurrentGUIDToFuncNameMap);
  291. }
  292. ~GUIDToFuncNameMapper() {
  293. if (!CurrentReader.useMD5())
  294. return;
  295. CurrentGUIDToFuncNameMap.clear();
  296. // Reset GUIDToFuncNameMap for of each function as they're no
  297. // longer valid at this point.
  298. SetGUIDToFuncNameMapForAll(nullptr);
  299. }
  300. private:
  301. void SetGUIDToFuncNameMapForAll(DenseMap<uint64_t, StringRef> *Map) {
  302. std::queue<FunctionSamples *> FSToUpdate;
  303. for (auto &IFS : CurrentReader.getProfiles()) {
  304. FSToUpdate.push(&IFS.second);
  305. }
  306. while (!FSToUpdate.empty()) {
  307. FunctionSamples *FS = FSToUpdate.front();
  308. FSToUpdate.pop();
  309. FS->GUIDToFuncNameMap = Map;
  310. for (const auto &ICS : FS->getCallsiteSamples()) {
  311. const FunctionSamplesMap &FSMap = ICS.second;
  312. for (auto &IFS : FSMap) {
  313. FunctionSamples &FS = const_cast<FunctionSamples &>(IFS.second);
  314. FSToUpdate.push(&FS);
  315. }
  316. }
  317. }
  318. }
  319. SampleProfileReader &CurrentReader;
  320. Module &CurrentModule;
  321. DenseMap<uint64_t, StringRef> &CurrentGUIDToFuncNameMap;
  322. };
  323. // Inline candidate used by iterative callsite prioritized inliner
  324. struct InlineCandidate {
  325. CallBase *CallInstr;
  326. const FunctionSamples *CalleeSamples;
  327. // Prorated callsite count, which will be used to guide inlining. For example,
  328. // if a callsite is duplicated in LTO prelink, then in LTO postlink the two
  329. // copies will get their own distribution factors and their prorated counts
  330. // will be used to decide if they should be inlined independently.
  331. uint64_t CallsiteCount;
  332. // Call site distribution factor to prorate the profile samples for a
  333. // duplicated callsite. Default value is 1.0.
  334. float CallsiteDistribution;
  335. };
  336. // Inline candidate comparer using call site weight
  337. struct CandidateComparer {
  338. bool operator()(const InlineCandidate &LHS, const InlineCandidate &RHS) {
  339. if (LHS.CallsiteCount != RHS.CallsiteCount)
  340. return LHS.CallsiteCount < RHS.CallsiteCount;
  341. // Tie breaker using GUID so we have stable/deterministic inlining order
  342. assert(LHS.CalleeSamples && RHS.CalleeSamples &&
  343. "Expect non-null FunctionSamples");
  344. return LHS.CalleeSamples->getGUID(LHS.CalleeSamples->getName()) <
  345. RHS.CalleeSamples->getGUID(RHS.CalleeSamples->getName());
  346. }
  347. };
  348. using CandidateQueue =
  349. PriorityQueue<InlineCandidate, std::vector<InlineCandidate>,
  350. CandidateComparer>;
  351. /// Sample profile pass.
  352. ///
  353. /// This pass reads profile data from the file specified by
  354. /// -sample-profile-file and annotates every affected function with the
  355. /// profile information found in that file.
  356. class SampleProfileLoader {
  357. public:
  358. SampleProfileLoader(
  359. StringRef Name, StringRef RemapName, ThinOrFullLTOPhase LTOPhase,
  360. std::function<AssumptionCache &(Function &)> GetAssumptionCache,
  361. std::function<TargetTransformInfo &(Function &)> GetTargetTransformInfo,
  362. std::function<const TargetLibraryInfo &(Function &)> GetTLI)
  363. : GetAC(std::move(GetAssumptionCache)),
  364. GetTTI(std::move(GetTargetTransformInfo)), GetTLI(std::move(GetTLI)),
  365. CoverageTracker(*this), Filename(std::string(Name)),
  366. RemappingFilename(std::string(RemapName)), LTOPhase(LTOPhase) {}
  367. bool doInitialization(Module &M, FunctionAnalysisManager *FAM = nullptr);
  368. bool runOnModule(Module &M, ModuleAnalysisManager *AM,
  369. ProfileSummaryInfo *_PSI, CallGraph *CG);
  370. void dump() { Reader->dump(); }
  371. protected:
  372. friend class SampleCoverageTracker;
  373. bool runOnFunction(Function &F, ModuleAnalysisManager *AM);
  374. unsigned getFunctionLoc(Function &F);
  375. bool emitAnnotations(Function &F);
  376. ErrorOr<uint64_t> getInstWeight(const Instruction &I);
  377. ErrorOr<uint64_t> getProbeWeight(const Instruction &I);
  378. ErrorOr<uint64_t> getBlockWeight(const BasicBlock *BB);
  379. const FunctionSamples *findCalleeFunctionSamples(const CallBase &I) const;
  380. std::vector<const FunctionSamples *>
  381. findIndirectCallFunctionSamples(const Instruction &I, uint64_t &Sum) const;
  382. mutable DenseMap<const DILocation *, const FunctionSamples *> DILocation2SampleMap;
  383. const FunctionSamples *findFunctionSamples(const Instruction &I) const;
  384. // Attempt to promote indirect call and also inline the promoted call
  385. bool tryPromoteAndInlineCandidate(
  386. Function &F, InlineCandidate &Candidate, uint64_t SumOrigin,
  387. uint64_t &Sum, DenseSet<Instruction *> &PromotedInsns,
  388. SmallVector<CallBase *, 8> *InlinedCallSites = nullptr);
  389. bool inlineHotFunctions(Function &F,
  390. DenseSet<GlobalValue::GUID> &InlinedGUIDs);
  391. InlineCost shouldInlineCandidate(InlineCandidate &Candidate);
  392. bool getInlineCandidate(InlineCandidate *NewCandidate, CallBase *CB);
  393. bool
  394. tryInlineCandidate(InlineCandidate &Candidate,
  395. SmallVector<CallBase *, 8> *InlinedCallSites = nullptr);
  396. bool
  397. inlineHotFunctionsWithPriority(Function &F,
  398. DenseSet<GlobalValue::GUID> &InlinedGUIDs);
  399. // Inline cold/small functions in addition to hot ones
  400. bool shouldInlineColdCallee(CallBase &CallInst);
  401. void emitOptimizationRemarksForInlineCandidates(
  402. const SmallVectorImpl<CallBase *> &Candidates, const Function &F,
  403. bool Hot);
  404. void printEdgeWeight(raw_ostream &OS, Edge E);
  405. void printBlockWeight(raw_ostream &OS, const BasicBlock *BB) const;
  406. void printBlockEquivalence(raw_ostream &OS, const BasicBlock *BB);
  407. bool computeBlockWeights(Function &F);
  408. void findEquivalenceClasses(Function &F);
  409. template <bool IsPostDom>
  410. void findEquivalencesFor(BasicBlock *BB1, ArrayRef<BasicBlock *> Descendants,
  411. DominatorTreeBase<BasicBlock, IsPostDom> *DomTree);
  412. void propagateWeights(Function &F);
  413. uint64_t visitEdge(Edge E, unsigned *NumUnknownEdges, Edge *UnknownEdge);
  414. void buildEdges(Function &F);
  415. std::vector<Function *> buildFunctionOrder(Module &M, CallGraph *CG);
  416. void addCallGraphEdges(CallGraph &CG, const FunctionSamples &Samples);
  417. void replaceCallGraphEdges(CallGraph &CG, StringMap<Function *> &SymbolMap);
  418. bool propagateThroughEdges(Function &F, bool UpdateBlockCount);
  419. void computeDominanceAndLoopInfo(Function &F);
  420. void clearFunctionData();
  421. bool callsiteIsHot(const FunctionSamples *CallsiteFS,
  422. ProfileSummaryInfo *PSI);
  423. /// Map basic blocks to their computed weights.
  424. ///
  425. /// The weight of a basic block is defined to be the maximum
  426. /// of all the instruction weights in that block.
  427. BlockWeightMap BlockWeights;
  428. /// Map edges to their computed weights.
  429. ///
  430. /// Edge weights are computed by propagating basic block weights in
  431. /// SampleProfile::propagateWeights.
  432. EdgeWeightMap EdgeWeights;
  433. /// Set of visited blocks during propagation.
  434. SmallPtrSet<const BasicBlock *, 32> VisitedBlocks;
  435. /// Set of visited edges during propagation.
  436. SmallSet<Edge, 32> VisitedEdges;
  437. /// Equivalence classes for block weights.
  438. ///
  439. /// Two blocks BB1 and BB2 are in the same equivalence class if they
  440. /// dominate and post-dominate each other, and they are in the same loop
  441. /// nest. When this happens, the two blocks are guaranteed to execute
  442. /// the same number of times.
  443. EquivalenceClassMap EquivalenceClass;
  444. /// Map from function name to Function *. Used to find the function from
  445. /// the function name. If the function name contains suffix, additional
  446. /// entry is added to map from the stripped name to the function if there
  447. /// is one-to-one mapping.
  448. StringMap<Function *> SymbolMap;
  449. /// Dominance, post-dominance and loop information.
  450. std::unique_ptr<DominatorTree> DT;
  451. std::unique_ptr<PostDominatorTree> PDT;
  452. std::unique_ptr<LoopInfo> LI;
  453. std::function<AssumptionCache &(Function &)> GetAC;
  454. std::function<TargetTransformInfo &(Function &)> GetTTI;
  455. std::function<const TargetLibraryInfo &(Function &)> GetTLI;
  456. /// Predecessors for each basic block in the CFG.
  457. BlockEdgeMap Predecessors;
  458. /// Successors for each basic block in the CFG.
  459. BlockEdgeMap Successors;
  460. SampleCoverageTracker CoverageTracker;
  461. /// Profile reader object.
  462. std::unique_ptr<SampleProfileReader> Reader;
  463. /// Profile tracker for different context.
  464. std::unique_ptr<SampleContextTracker> ContextTracker;
  465. /// Samples collected for the body of this function.
  466. FunctionSamples *Samples = nullptr;
  467. /// Name of the profile file to load.
  468. std::string Filename;
  469. /// Name of the profile remapping file to load.
  470. std::string RemappingFilename;
  471. /// Flag indicating whether the profile input loaded successfully.
  472. bool ProfileIsValid = false;
  473. /// Flag indicating whether input profile is context-sensitive
  474. bool ProfileIsCS = false;
  475. /// Flag indicating which LTO/ThinLTO phase the pass is invoked in.
  476. ///
  477. /// We need to know the LTO phase because for example in ThinLTOPrelink
  478. /// phase, in annotation, we should not promote indirect calls. Instead,
  479. /// we will mark GUIDs that needs to be annotated to the function.
  480. ThinOrFullLTOPhase LTOPhase;
  481. /// Profile Summary Info computed from sample profile.
  482. ProfileSummaryInfo *PSI = nullptr;
  483. /// Profle Symbol list tells whether a function name appears in the binary
  484. /// used to generate the current profile.
  485. std::unique_ptr<ProfileSymbolList> PSL;
  486. /// Total number of samples collected in this profile.
  487. ///
  488. /// This is the sum of all the samples collected in all the functions executed
  489. /// at runtime.
  490. uint64_t TotalCollectedSamples = 0;
  491. /// Optimization Remark Emitter used to emit diagnostic remarks.
  492. OptimizationRemarkEmitter *ORE = nullptr;
  493. // Information recorded when we declined to inline a call site
  494. // because we have determined it is too cold is accumulated for
  495. // each callee function. Initially this is just the entry count.
  496. struct NotInlinedProfileInfo {
  497. uint64_t entryCount;
  498. };
  499. DenseMap<Function *, NotInlinedProfileInfo> notInlinedCallInfo;
  500. // GUIDToFuncNameMap saves the mapping from GUID to the symbol name, for
  501. // all the function symbols defined or declared in current module.
  502. DenseMap<uint64_t, StringRef> GUIDToFuncNameMap;
  503. // All the Names used in FunctionSamples including outline function
  504. // names, inline instance names and call target names.
  505. StringSet<> NamesInProfile;
  506. // For symbol in profile symbol list, whether to regard their profiles
  507. // to be accurate. It is mainly decided by existance of profile symbol
  508. // list and -profile-accurate-for-symsinlist flag, but it can be
  509. // overriden by -profile-sample-accurate or profile-sample-accurate
  510. // attribute.
  511. bool ProfAccForSymsInList;
  512. // External inline advisor used to replay inline decision from remarks.
  513. std::unique_ptr<ReplayInlineAdvisor> ExternalInlineAdvisor;
  514. // A pseudo probe helper to correlate the imported sample counts.
  515. std::unique_ptr<PseudoProbeManager> ProbeManager;
  516. };
  517. class SampleProfileLoaderLegacyPass : public ModulePass {
  518. public:
  519. // Class identification, replacement for typeinfo
  520. static char ID;
  521. SampleProfileLoaderLegacyPass(
  522. StringRef Name = SampleProfileFile,
  523. ThinOrFullLTOPhase LTOPhase = ThinOrFullLTOPhase::None)
  524. : ModulePass(ID), SampleLoader(
  525. Name, SampleProfileRemappingFile, LTOPhase,
  526. [&](Function &F) -> AssumptionCache & {
  527. return ACT->getAssumptionCache(F);
  528. },
  529. [&](Function &F) -> TargetTransformInfo & {
  530. return TTIWP->getTTI(F);
  531. },
  532. [&](Function &F) -> TargetLibraryInfo & {
  533. return TLIWP->getTLI(F);
  534. }) {
  535. initializeSampleProfileLoaderLegacyPassPass(
  536. *PassRegistry::getPassRegistry());
  537. }
  538. void dump() { SampleLoader.dump(); }
  539. bool doInitialization(Module &M) override {
  540. return SampleLoader.doInitialization(M);
  541. }
  542. StringRef getPassName() const override { return "Sample profile pass"; }
  543. bool runOnModule(Module &M) override;
  544. void getAnalysisUsage(AnalysisUsage &AU) const override {
  545. AU.addRequired<AssumptionCacheTracker>();
  546. AU.addRequired<TargetTransformInfoWrapperPass>();
  547. AU.addRequired<TargetLibraryInfoWrapperPass>();
  548. AU.addRequired<ProfileSummaryInfoWrapperPass>();
  549. }
  550. private:
  551. SampleProfileLoader SampleLoader;
  552. AssumptionCacheTracker *ACT = nullptr;
  553. TargetTransformInfoWrapperPass *TTIWP = nullptr;
  554. TargetLibraryInfoWrapperPass *TLIWP = nullptr;
  555. };
  556. } // end anonymous namespace
  557. /// Return true if the given callsite is hot wrt to hot cutoff threshold.
  558. ///
  559. /// Functions that were inlined in the original binary will be represented
  560. /// in the inline stack in the sample profile. If the profile shows that
  561. /// the original inline decision was "good" (i.e., the callsite is executed
  562. /// frequently), then we will recreate the inline decision and apply the
  563. /// profile from the inlined callsite.
  564. ///
  565. /// To decide whether an inlined callsite is hot, we compare the callsite
  566. /// sample count with the hot cutoff computed by ProfileSummaryInfo, it is
  567. /// regarded as hot if the count is above the cutoff value.
  568. ///
  569. /// When ProfileAccurateForSymsInList is enabled and profile symbol list
  570. /// is present, functions in the profile symbol list but without profile will
  571. /// be regarded as cold and much less inlining will happen in CGSCC inlining
  572. /// pass, so we tend to lower the hot criteria here to allow more early
  573. /// inlining to happen for warm callsites and it is helpful for performance.
  574. bool SampleProfileLoader::callsiteIsHot(const FunctionSamples *CallsiteFS,
  575. ProfileSummaryInfo *PSI) {
  576. if (!CallsiteFS)
  577. return false; // The callsite was not inlined in the original binary.
  578. assert(PSI && "PSI is expected to be non null");
  579. uint64_t CallsiteTotalSamples = CallsiteFS->getTotalSamples();
  580. if (ProfAccForSymsInList)
  581. return !PSI->isColdCount(CallsiteTotalSamples);
  582. else
  583. return PSI->isHotCount(CallsiteTotalSamples);
  584. }
  585. /// Mark as used the sample record for the given function samples at
  586. /// (LineOffset, Discriminator).
  587. ///
  588. /// \returns true if this is the first time we mark the given record.
  589. bool SampleCoverageTracker::markSamplesUsed(const FunctionSamples *FS,
  590. uint32_t LineOffset,
  591. uint32_t Discriminator,
  592. uint64_t Samples) {
  593. LineLocation Loc(LineOffset, Discriminator);
  594. unsigned &Count = SampleCoverage[FS][Loc];
  595. bool FirstTime = (++Count == 1);
  596. if (FirstTime)
  597. TotalUsedSamples += Samples;
  598. return FirstTime;
  599. }
  600. /// Return the number of sample records that were applied from this profile.
  601. ///
  602. /// This count does not include records from cold inlined callsites.
  603. unsigned
  604. SampleCoverageTracker::countUsedRecords(const FunctionSamples *FS,
  605. ProfileSummaryInfo *PSI) const {
  606. auto I = SampleCoverage.find(FS);
  607. // The size of the coverage map for FS represents the number of records
  608. // that were marked used at least once.
  609. unsigned Count = (I != SampleCoverage.end()) ? I->second.size() : 0;
  610. // If there are inlined callsites in this function, count the samples found
  611. // in the respective bodies. However, do not bother counting callees with 0
  612. // total samples, these are callees that were never invoked at runtime.
  613. for (const auto &I : FS->getCallsiteSamples())
  614. for (const auto &J : I.second) {
  615. const FunctionSamples *CalleeSamples = &J.second;
  616. if (SPLoader.callsiteIsHot(CalleeSamples, PSI))
  617. Count += countUsedRecords(CalleeSamples, PSI);
  618. }
  619. return Count;
  620. }
  621. /// Return the number of sample records in the body of this profile.
  622. ///
  623. /// This count does not include records from cold inlined callsites.
  624. unsigned
  625. SampleCoverageTracker::countBodyRecords(const FunctionSamples *FS,
  626. ProfileSummaryInfo *PSI) const {
  627. unsigned Count = FS->getBodySamples().size();
  628. // Only count records in hot callsites.
  629. for (const auto &I : FS->getCallsiteSamples())
  630. for (const auto &J : I.second) {
  631. const FunctionSamples *CalleeSamples = &J.second;
  632. if (SPLoader.callsiteIsHot(CalleeSamples, PSI))
  633. Count += countBodyRecords(CalleeSamples, PSI);
  634. }
  635. return Count;
  636. }
  637. /// Return the number of samples collected in the body of this profile.
  638. ///
  639. /// This count does not include samples from cold inlined callsites.
  640. uint64_t
  641. SampleCoverageTracker::countBodySamples(const FunctionSamples *FS,
  642. ProfileSummaryInfo *PSI) const {
  643. uint64_t Total = 0;
  644. for (const auto &I : FS->getBodySamples())
  645. Total += I.second.getSamples();
  646. // Only count samples in hot callsites.
  647. for (const auto &I : FS->getCallsiteSamples())
  648. for (const auto &J : I.second) {
  649. const FunctionSamples *CalleeSamples = &J.second;
  650. if (SPLoader.callsiteIsHot(CalleeSamples, PSI))
  651. Total += countBodySamples(CalleeSamples, PSI);
  652. }
  653. return Total;
  654. }
  655. /// Return the fraction of sample records used in this profile.
  656. ///
  657. /// The returned value is an unsigned integer in the range 0-100 indicating
  658. /// the percentage of sample records that were used while applying this
  659. /// profile to the associated function.
  660. unsigned SampleCoverageTracker::computeCoverage(unsigned Used,
  661. unsigned Total) const {
  662. assert(Used <= Total &&
  663. "number of used records cannot exceed the total number of records");
  664. return Total > 0 ? Used * 100 / Total : 100;
  665. }
  666. /// Clear all the per-function data used to load samples and propagate weights.
  667. void SampleProfileLoader::clearFunctionData() {
  668. BlockWeights.clear();
  669. EdgeWeights.clear();
  670. VisitedBlocks.clear();
  671. VisitedEdges.clear();
  672. EquivalenceClass.clear();
  673. DT = nullptr;
  674. PDT = nullptr;
  675. LI = nullptr;
  676. Predecessors.clear();
  677. Successors.clear();
  678. CoverageTracker.clear();
  679. }
  680. #ifndef NDEBUG
  681. /// Print the weight of edge \p E on stream \p OS.
  682. ///
  683. /// \param OS Stream to emit the output to.
  684. /// \param E Edge to print.
  685. void SampleProfileLoader::printEdgeWeight(raw_ostream &OS, Edge E) {
  686. OS << "weight[" << E.first->getName() << "->" << E.second->getName()
  687. << "]: " << EdgeWeights[E] << "\n";
  688. }
  689. /// Print the equivalence class of block \p BB on stream \p OS.
  690. ///
  691. /// \param OS Stream to emit the output to.
  692. /// \param BB Block to print.
  693. void SampleProfileLoader::printBlockEquivalence(raw_ostream &OS,
  694. const BasicBlock *BB) {
  695. const BasicBlock *Equiv = EquivalenceClass[BB];
  696. OS << "equivalence[" << BB->getName()
  697. << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n";
  698. }
  699. /// Print the weight of block \p BB on stream \p OS.
  700. ///
  701. /// \param OS Stream to emit the output to.
  702. /// \param BB Block to print.
  703. void SampleProfileLoader::printBlockWeight(raw_ostream &OS,
  704. const BasicBlock *BB) const {
  705. const auto &I = BlockWeights.find(BB);
  706. uint64_t W = (I == BlockWeights.end() ? 0 : I->second);
  707. OS << "weight[" << BB->getName() << "]: " << W << "\n";
  708. }
  709. #endif
  710. /// Get the weight for an instruction.
  711. ///
  712. /// The "weight" of an instruction \p Inst is the number of samples
  713. /// collected on that instruction at runtime. To retrieve it, we
  714. /// need to compute the line number of \p Inst relative to the start of its
  715. /// function. We use HeaderLineno to compute the offset. We then
  716. /// look up the samples collected for \p Inst using BodySamples.
  717. ///
  718. /// \param Inst Instruction to query.
  719. ///
  720. /// \returns the weight of \p Inst.
  721. ErrorOr<uint64_t> SampleProfileLoader::getInstWeight(const Instruction &Inst) {
  722. if (FunctionSamples::ProfileIsProbeBased)
  723. return getProbeWeight(Inst);
  724. const DebugLoc &DLoc = Inst.getDebugLoc();
  725. if (!DLoc)
  726. return std::error_code();
  727. const FunctionSamples *FS = findFunctionSamples(Inst);
  728. if (!FS)
  729. return std::error_code();
  730. // Ignore all intrinsics, phinodes and branch instructions.
  731. // Branch and phinodes instruction usually contains debug info from sources outside of
  732. // the residing basic block, thus we ignore them during annotation.
  733. if (isa<BranchInst>(Inst) || isa<IntrinsicInst>(Inst) || isa<PHINode>(Inst))
  734. return std::error_code();
  735. // If a direct call/invoke instruction is inlined in profile
  736. // (findCalleeFunctionSamples returns non-empty result), but not inlined here,
  737. // it means that the inlined callsite has no sample, thus the call
  738. // instruction should have 0 count.
  739. if (!ProfileIsCS)
  740. if (const auto *CB = dyn_cast<CallBase>(&Inst))
  741. if (!CB->isIndirectCall() && findCalleeFunctionSamples(*CB))
  742. return 0;
  743. const DILocation *DIL = DLoc;
  744. uint32_t LineOffset = FunctionSamples::getOffset(DIL);
  745. uint32_t Discriminator = DIL->getBaseDiscriminator();
  746. ErrorOr<uint64_t> R = FS->findSamplesAt(LineOffset, Discriminator);
  747. if (R) {
  748. bool FirstMark =
  749. CoverageTracker.markSamplesUsed(FS, LineOffset, Discriminator, R.get());
  750. if (FirstMark) {
  751. ORE->emit([&]() {
  752. OptimizationRemarkAnalysis Remark(DEBUG_TYPE, "AppliedSamples", &Inst);
  753. Remark << "Applied " << ore::NV("NumSamples", *R);
  754. Remark << " samples from profile (offset: ";
  755. Remark << ore::NV("LineOffset", LineOffset);
  756. if (Discriminator) {
  757. Remark << ".";
  758. Remark << ore::NV("Discriminator", Discriminator);
  759. }
  760. Remark << ")";
  761. return Remark;
  762. });
  763. }
  764. LLVM_DEBUG(dbgs() << " " << DLoc.getLine() << "."
  765. << DIL->getBaseDiscriminator() << ":" << Inst
  766. << " (line offset: " << LineOffset << "."
  767. << DIL->getBaseDiscriminator() << " - weight: " << R.get()
  768. << ")\n");
  769. }
  770. return R;
  771. }
  772. ErrorOr<uint64_t> SampleProfileLoader::getProbeWeight(const Instruction &Inst) {
  773. assert(FunctionSamples::ProfileIsProbeBased &&
  774. "Profile is not pseudo probe based");
  775. Optional<PseudoProbe> Probe = extractProbe(Inst);
  776. if (!Probe)
  777. return std::error_code();
  778. const FunctionSamples *FS = findFunctionSamples(Inst);
  779. if (!FS)
  780. return std::error_code();
  781. // If a direct call/invoke instruction is inlined in profile
  782. // (findCalleeFunctionSamples returns non-empty result), but not inlined here,
  783. // it means that the inlined callsite has no sample, thus the call
  784. // instruction should have 0 count.
  785. if (const auto *CB = dyn_cast<CallBase>(&Inst))
  786. if (!CB->isIndirectCall() && findCalleeFunctionSamples(*CB))
  787. return 0;
  788. const ErrorOr<uint64_t> &R = FS->findSamplesAt(Probe->Id, 0);
  789. if (R) {
  790. uint64_t Samples = R.get() * Probe->Factor;
  791. bool FirstMark = CoverageTracker.markSamplesUsed(FS, Probe->Id, 0, Samples);
  792. if (FirstMark) {
  793. ORE->emit([&]() {
  794. OptimizationRemarkAnalysis Remark(DEBUG_TYPE, "AppliedSamples", &Inst);
  795. Remark << "Applied " << ore::NV("NumSamples", Samples);
  796. Remark << " samples from profile (ProbeId=";
  797. Remark << ore::NV("ProbeId", Probe->Id);
  798. Remark << ", Factor=";
  799. Remark << ore::NV("Factor", Probe->Factor);
  800. Remark << ", OriginalSamples=";
  801. Remark << ore::NV("OriginalSamples", R.get());
  802. Remark << ")";
  803. return Remark;
  804. });
  805. }
  806. LLVM_DEBUG(dbgs() << " " << Probe->Id << ":" << Inst
  807. << " - weight: " << R.get() << " - factor: "
  808. << format("%0.2f", Probe->Factor) << ")\n");
  809. return Samples;
  810. }
  811. return R;
  812. }
  813. /// Compute the weight of a basic block.
  814. ///
  815. /// The weight of basic block \p BB is the maximum weight of all the
  816. /// instructions in BB.
  817. ///
  818. /// \param BB The basic block to query.
  819. ///
  820. /// \returns the weight for \p BB.
  821. ErrorOr<uint64_t> SampleProfileLoader::getBlockWeight(const BasicBlock *BB) {
  822. uint64_t Max = 0;
  823. bool HasWeight = false;
  824. for (auto &I : BB->getInstList()) {
  825. const ErrorOr<uint64_t> &R = getInstWeight(I);
  826. if (R) {
  827. Max = std::max(Max, R.get());
  828. HasWeight = true;
  829. }
  830. }
  831. return HasWeight ? ErrorOr<uint64_t>(Max) : std::error_code();
  832. }
  833. /// Compute and store the weights of every basic block.
  834. ///
  835. /// This populates the BlockWeights map by computing
  836. /// the weights of every basic block in the CFG.
  837. ///
  838. /// \param F The function to query.
  839. bool SampleProfileLoader::computeBlockWeights(Function &F) {
  840. bool Changed = false;
  841. LLVM_DEBUG(dbgs() << "Block weights\n");
  842. for (const auto &BB : F) {
  843. ErrorOr<uint64_t> Weight = getBlockWeight(&BB);
  844. if (Weight) {
  845. BlockWeights[&BB] = Weight.get();
  846. VisitedBlocks.insert(&BB);
  847. Changed = true;
  848. }
  849. LLVM_DEBUG(printBlockWeight(dbgs(), &BB));
  850. }
  851. return Changed;
  852. }
  853. /// Get the FunctionSamples for a call instruction.
  854. ///
  855. /// The FunctionSamples of a call/invoke instruction \p Inst is the inlined
  856. /// instance in which that call instruction is calling to. It contains
  857. /// all samples that resides in the inlined instance. We first find the
  858. /// inlined instance in which the call instruction is from, then we
  859. /// traverse its children to find the callsite with the matching
  860. /// location.
  861. ///
  862. /// \param Inst Call/Invoke instruction to query.
  863. ///
  864. /// \returns The FunctionSamples pointer to the inlined instance.
  865. const FunctionSamples *
  866. SampleProfileLoader::findCalleeFunctionSamples(const CallBase &Inst) const {
  867. const DILocation *DIL = Inst.getDebugLoc();
  868. if (!DIL) {
  869. return nullptr;
  870. }
  871. StringRef CalleeName;
  872. if (Function *Callee = Inst.getCalledFunction())
  873. CalleeName = FunctionSamples::getCanonicalFnName(*Callee);
  874. if (ProfileIsCS)
  875. return ContextTracker->getCalleeContextSamplesFor(Inst, CalleeName);
  876. const FunctionSamples *FS = findFunctionSamples(Inst);
  877. if (FS == nullptr)
  878. return nullptr;
  879. return FS->findFunctionSamplesAt(FunctionSamples::getCallSiteIdentifier(DIL),
  880. CalleeName, Reader->getRemapper());
  881. }
  882. /// Returns a vector of FunctionSamples that are the indirect call targets
  883. /// of \p Inst. The vector is sorted by the total number of samples. Stores
  884. /// the total call count of the indirect call in \p Sum.
  885. std::vector<const FunctionSamples *>
  886. SampleProfileLoader::findIndirectCallFunctionSamples(
  887. const Instruction &Inst, uint64_t &Sum) const {
  888. const DILocation *DIL = Inst.getDebugLoc();
  889. std::vector<const FunctionSamples *> R;
  890. if (!DIL) {
  891. return R;
  892. }
  893. auto FSCompare = [](const FunctionSamples *L, const FunctionSamples *R) {
  894. assert(L && R && "Expect non-null FunctionSamples");
  895. if (L->getEntrySamples() != R->getEntrySamples())
  896. return L->getEntrySamples() > R->getEntrySamples();
  897. return FunctionSamples::getGUID(L->getName()) <
  898. FunctionSamples::getGUID(R->getName());
  899. };
  900. if (ProfileIsCS) {
  901. auto CalleeSamples =
  902. ContextTracker->getIndirectCalleeContextSamplesFor(DIL);
  903. if (CalleeSamples.empty())
  904. return R;
  905. // For CSSPGO, we only use target context profile's entry count
  906. // as that already includes both inlined callee and non-inlined ones..
  907. Sum = 0;
  908. for (const auto *const FS : CalleeSamples) {
  909. Sum += FS->getEntrySamples();
  910. R.push_back(FS);
  911. }
  912. llvm::sort(R, FSCompare);
  913. return R;
  914. }
  915. const FunctionSamples *FS = findFunctionSamples(Inst);
  916. if (FS == nullptr)
  917. return R;
  918. auto CallSite = FunctionSamples::getCallSiteIdentifier(DIL);
  919. auto T = FS->findCallTargetMapAt(CallSite);
  920. Sum = 0;
  921. if (T)
  922. for (const auto &T_C : T.get())
  923. Sum += T_C.second;
  924. if (const FunctionSamplesMap *M = FS->findFunctionSamplesMapAt(CallSite)) {
  925. if (M->empty())
  926. return R;
  927. for (const auto &NameFS : *M) {
  928. Sum += NameFS.second.getEntrySamples();
  929. R.push_back(&NameFS.second);
  930. }
  931. llvm::sort(R, FSCompare);
  932. }
  933. return R;
  934. }
  935. /// Get the FunctionSamples for an instruction.
  936. ///
  937. /// The FunctionSamples of an instruction \p Inst is the inlined instance
  938. /// in which that instruction is coming from. We traverse the inline stack
  939. /// of that instruction, and match it with the tree nodes in the profile.
  940. ///
  941. /// \param Inst Instruction to query.
  942. ///
  943. /// \returns the FunctionSamples pointer to the inlined instance.
  944. const FunctionSamples *
  945. SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const {
  946. if (FunctionSamples::ProfileIsProbeBased) {
  947. Optional<PseudoProbe> Probe = extractProbe(Inst);
  948. if (!Probe)
  949. return nullptr;
  950. }
  951. const DILocation *DIL = Inst.getDebugLoc();
  952. if (!DIL)
  953. return Samples;
  954. auto it = DILocation2SampleMap.try_emplace(DIL,nullptr);
  955. if (it.second) {
  956. if (ProfileIsCS)
  957. it.first->second = ContextTracker->getContextSamplesFor(DIL);
  958. else
  959. it.first->second =
  960. Samples->findFunctionSamples(DIL, Reader->getRemapper());
  961. }
  962. return it.first->second;
  963. }
  964. /// Attempt to promote indirect call and also inline the promoted call.
  965. ///
  966. /// \param F Caller function.
  967. /// \param Candidate ICP and inline candidate.
  968. /// \param Sum Sum of target counts for indirect call.
  969. /// \param PromotedInsns Map to keep track of indirect call already processed.
  970. /// \param Candidate ICP and inline candidate.
  971. /// \param InlinedCallSite Output vector for new call sites exposed after
  972. /// inlining.
  973. bool SampleProfileLoader::tryPromoteAndInlineCandidate(
  974. Function &F, InlineCandidate &Candidate, uint64_t SumOrigin, uint64_t &Sum,
  975. DenseSet<Instruction *> &PromotedInsns,
  976. SmallVector<CallBase *, 8> *InlinedCallSite) {
  977. const char *Reason = "Callee function not available";
  978. // R->getValue() != &F is to prevent promoting a recursive call.
  979. // If it is a recursive call, we do not inline it as it could bloat
  980. // the code exponentially. There is way to better handle this, e.g.
  981. // clone the caller first, and inline the cloned caller if it is
  982. // recursive. As llvm does not inline recursive calls, we will
  983. // simply ignore it instead of handling it explicitly.
  984. auto R = SymbolMap.find(Candidate.CalleeSamples->getFuncName());
  985. if (R != SymbolMap.end() && R->getValue() &&
  986. !R->getValue()->isDeclaration() && R->getValue()->getSubprogram() &&
  987. R->getValue()->hasFnAttribute("use-sample-profile") &&
  988. R->getValue() != &F &&
  989. isLegalToPromote(*Candidate.CallInstr, R->getValue(), &Reason)) {
  990. auto *DI =
  991. &pgo::promoteIndirectCall(*Candidate.CallInstr, R->getValue(),
  992. Candidate.CallsiteCount, Sum, false, ORE);
  993. if (DI) {
  994. Sum -= Candidate.CallsiteCount;
  995. // Prorate the indirect callsite distribution.
  996. // Do not update the promoted direct callsite distribution at this
  997. // point since the original distribution combined with the callee
  998. // profile will be used to prorate callsites from the callee if
  999. // inlined. Once not inlined, the direct callsite distribution should
  1000. // be prorated so that the it will reflect the real callsite counts.
  1001. setProbeDistributionFactor(*Candidate.CallInstr,
  1002. Candidate.CallsiteDistribution * Sum /
  1003. SumOrigin);
  1004. PromotedInsns.insert(Candidate.CallInstr);
  1005. Candidate.CallInstr = DI;
  1006. if (isa<CallInst>(DI) || isa<InvokeInst>(DI)) {
  1007. bool Inlined = tryInlineCandidate(Candidate, InlinedCallSite);
  1008. if (!Inlined) {
  1009. // Prorate the direct callsite distribution so that it reflects real
  1010. // callsite counts.
  1011. setProbeDistributionFactor(*DI, Candidate.CallsiteDistribution *
  1012. Candidate.CallsiteCount /
  1013. SumOrigin);
  1014. }
  1015. return Inlined;
  1016. }
  1017. }
  1018. } else {
  1019. LLVM_DEBUG(dbgs() << "\nFailed to promote indirect call to "
  1020. << Candidate.CalleeSamples->getFuncName() << " because "
  1021. << Reason << "\n");
  1022. }
  1023. return false;
  1024. }
  1025. bool SampleProfileLoader::shouldInlineColdCallee(CallBase &CallInst) {
  1026. if (!ProfileSizeInline)
  1027. return false;
  1028. Function *Callee = CallInst.getCalledFunction();
  1029. if (Callee == nullptr)
  1030. return false;
  1031. InlineCost Cost = getInlineCost(CallInst, getInlineParams(), GetTTI(*Callee),
  1032. GetAC, GetTLI);
  1033. if (Cost.isNever())
  1034. return false;
  1035. if (Cost.isAlways())
  1036. return true;
  1037. return Cost.getCost() <= SampleColdCallSiteThreshold;
  1038. }
  1039. void SampleProfileLoader::emitOptimizationRemarksForInlineCandidates(
  1040. const SmallVectorImpl<CallBase *> &Candidates, const Function &F,
  1041. bool Hot) {
  1042. for (auto I : Candidates) {
  1043. Function *CalledFunction = I->getCalledFunction();
  1044. if (CalledFunction) {
  1045. ORE->emit(OptimizationRemarkAnalysis(CSINLINE_DEBUG, "InlineAttempt",
  1046. I->getDebugLoc(), I->getParent())
  1047. << "previous inlining reattempted for "
  1048. << (Hot ? "hotness: '" : "size: '")
  1049. << ore::NV("Callee", CalledFunction) << "' into '"
  1050. << ore::NV("Caller", &F) << "'");
  1051. }
  1052. }
  1053. }
  1054. /// Iteratively inline hot callsites of a function.
  1055. ///
  1056. /// Iteratively traverse all callsites of the function \p F, and find if
  1057. /// the corresponding inlined instance exists and is hot in profile. If
  1058. /// it is hot enough, inline the callsites and adds new callsites of the
  1059. /// callee into the caller. If the call is an indirect call, first promote
  1060. /// it to direct call. Each indirect call is limited with a single target.
  1061. ///
  1062. /// \param F function to perform iterative inlining.
  1063. /// \param InlinedGUIDs a set to be updated to include all GUIDs that are
  1064. /// inlined in the profiled binary.
  1065. ///
  1066. /// \returns True if there is any inline happened.
  1067. bool SampleProfileLoader::inlineHotFunctions(
  1068. Function &F, DenseSet<GlobalValue::GUID> &InlinedGUIDs) {
  1069. DenseSet<Instruction *> PromotedInsns;
  1070. // ProfAccForSymsInList is used in callsiteIsHot. The assertion makes sure
  1071. // Profile symbol list is ignored when profile-sample-accurate is on.
  1072. assert((!ProfAccForSymsInList ||
  1073. (!ProfileSampleAccurate &&
  1074. !F.hasFnAttribute("profile-sample-accurate"))) &&
  1075. "ProfAccForSymsInList should be false when profile-sample-accurate "
  1076. "is enabled");
  1077. DenseMap<CallBase *, const FunctionSamples *> LocalNotInlinedCallSites;
  1078. bool Changed = false;
  1079. bool LocalChanged = true;
  1080. while (LocalChanged) {
  1081. LocalChanged = false;
  1082. SmallVector<CallBase *, 10> CIS;
  1083. for (auto &BB : F) {
  1084. bool Hot = false;
  1085. SmallVector<CallBase *, 10> AllCandidates;
  1086. SmallVector<CallBase *, 10> ColdCandidates;
  1087. for (auto &I : BB.getInstList()) {
  1088. const FunctionSamples *FS = nullptr;
  1089. if (auto *CB = dyn_cast<CallBase>(&I)) {
  1090. if (!isa<IntrinsicInst>(I) && (FS = findCalleeFunctionSamples(*CB))) {
  1091. assert((!FunctionSamples::UseMD5 || FS->GUIDToFuncNameMap) &&
  1092. "GUIDToFuncNameMap has to be populated");
  1093. AllCandidates.push_back(CB);
  1094. if (FS->getEntrySamples() > 0 || ProfileIsCS)
  1095. LocalNotInlinedCallSites.try_emplace(CB, FS);
  1096. if (callsiteIsHot(FS, PSI))
  1097. Hot = true;
  1098. else if (shouldInlineColdCallee(*CB))
  1099. ColdCandidates.push_back(CB);
  1100. }
  1101. }
  1102. }
  1103. if (Hot || ExternalInlineAdvisor) {
  1104. CIS.insert(CIS.begin(), AllCandidates.begin(), AllCandidates.end());
  1105. emitOptimizationRemarksForInlineCandidates(AllCandidates, F, true);
  1106. } else {
  1107. CIS.insert(CIS.begin(), ColdCandidates.begin(), ColdCandidates.end());
  1108. emitOptimizationRemarksForInlineCandidates(ColdCandidates, F, false);
  1109. }
  1110. }
  1111. for (CallBase *I : CIS) {
  1112. Function *CalledFunction = I->getCalledFunction();
  1113. InlineCandidate Candidate = {
  1114. I,
  1115. LocalNotInlinedCallSites.count(I) ? LocalNotInlinedCallSites[I]
  1116. : nullptr,
  1117. 0 /* dummy count */, 1.0 /* dummy distribution factor */};
  1118. // Do not inline recursive calls.
  1119. if (CalledFunction == &F)
  1120. continue;
  1121. if (I->isIndirectCall()) {
  1122. if (PromotedInsns.count(I))
  1123. continue;
  1124. uint64_t Sum;
  1125. for (const auto *FS : findIndirectCallFunctionSamples(*I, Sum)) {
  1126. uint64_t SumOrigin = Sum;
  1127. if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
  1128. FS->findInlinedFunctions(InlinedGUIDs, F.getParent(),
  1129. PSI->getOrCompHotCountThreshold());
  1130. continue;
  1131. }
  1132. if (!callsiteIsHot(FS, PSI))
  1133. continue;
  1134. Candidate = {I, FS, FS->getEntrySamples(), 1.0};
  1135. if (tryPromoteAndInlineCandidate(F, Candidate, SumOrigin, Sum,
  1136. PromotedInsns)) {
  1137. LocalNotInlinedCallSites.erase(I);
  1138. LocalChanged = true;
  1139. }
  1140. }
  1141. } else if (CalledFunction && CalledFunction->getSubprogram() &&
  1142. !CalledFunction->isDeclaration()) {
  1143. if (tryInlineCandidate(Candidate)) {
  1144. LocalNotInlinedCallSites.erase(I);
  1145. LocalChanged = true;
  1146. }
  1147. } else if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
  1148. findCalleeFunctionSamples(*I)->findInlinedFunctions(
  1149. InlinedGUIDs, F.getParent(), PSI->getOrCompHotCountThreshold());
  1150. }
  1151. }
  1152. Changed |= LocalChanged;
  1153. }
  1154. // For CS profile, profile for not inlined context will be merged when
  1155. // base profile is being trieved
  1156. if (ProfileIsCS)
  1157. return Changed;
  1158. // Accumulate not inlined callsite information into notInlinedSamples
  1159. for (const auto &Pair : LocalNotInlinedCallSites) {
  1160. CallBase *I = Pair.getFirst();
  1161. Function *Callee = I->getCalledFunction();
  1162. if (!Callee || Callee->isDeclaration())
  1163. continue;
  1164. ORE->emit(OptimizationRemarkAnalysis(CSINLINE_DEBUG, "NotInline",
  1165. I->getDebugLoc(), I->getParent())
  1166. << "previous inlining not repeated: '"
  1167. << ore::NV("Callee", Callee) << "' into '"
  1168. << ore::NV("Caller", &F) << "'");
  1169. ++NumCSNotInlined;
  1170. const FunctionSamples *FS = Pair.getSecond();
  1171. if (FS->getTotalSamples() == 0 && FS->getEntrySamples() == 0) {
  1172. continue;
  1173. }
  1174. if (ProfileMergeInlinee) {
  1175. // A function call can be replicated by optimizations like callsite
  1176. // splitting or jump threading and the replicates end up sharing the
  1177. // sample nested callee profile instead of slicing the original inlinee's
  1178. // profile. We want to do merge exactly once by filtering out callee
  1179. // profiles with a non-zero head sample count.
  1180. if (FS->getHeadSamples() == 0) {
  1181. // Use entry samples as head samples during the merge, as inlinees
  1182. // don't have head samples.
  1183. const_cast<FunctionSamples *>(FS)->addHeadSamples(
  1184. FS->getEntrySamples());
  1185. // Note that we have to do the merge right after processing function.
  1186. // This allows OutlineFS's profile to be used for annotation during
  1187. // top-down processing of functions' annotation.
  1188. FunctionSamples *OutlineFS = Reader->getOrCreateSamplesFor(*Callee);
  1189. OutlineFS->merge(*FS);
  1190. }
  1191. } else {
  1192. auto pair =
  1193. notInlinedCallInfo.try_emplace(Callee, NotInlinedProfileInfo{0});
  1194. pair.first->second.entryCount += FS->getEntrySamples();
  1195. }
  1196. }
  1197. return Changed;
  1198. }
  1199. bool SampleProfileLoader::tryInlineCandidate(
  1200. InlineCandidate &Candidate, SmallVector<CallBase *, 8> *InlinedCallSites) {
  1201. CallBase &CB = *Candidate.CallInstr;
  1202. Function *CalledFunction = CB.getCalledFunction();
  1203. assert(CalledFunction && "Expect a callee with definition");
  1204. DebugLoc DLoc = CB.getDebugLoc();
  1205. BasicBlock *BB = CB.getParent();
  1206. InlineCost Cost = shouldInlineCandidate(Candidate);
  1207. if (Cost.isNever()) {
  1208. ORE->emit(OptimizationRemarkAnalysis(CSINLINE_DEBUG, "InlineFail", DLoc, BB)
  1209. << "incompatible inlining");
  1210. return false;
  1211. }
  1212. if (!Cost)
  1213. return false;
  1214. InlineFunctionInfo IFI(nullptr, GetAC);
  1215. if (InlineFunction(CB, IFI).isSuccess()) {
  1216. // The call to InlineFunction erases I, so we can't pass it here.
  1217. emitInlinedInto(*ORE, DLoc, BB, *CalledFunction, *BB->getParent(), Cost,
  1218. true, CSINLINE_DEBUG);
  1219. // Now populate the list of newly exposed call sites.
  1220. if (InlinedCallSites) {
  1221. InlinedCallSites->clear();
  1222. for (auto &I : IFI.InlinedCallSites)
  1223. InlinedCallSites->push_back(I);
  1224. }
  1225. if (ProfileIsCS)
  1226. ContextTracker->markContextSamplesInlined(Candidate.CalleeSamples);
  1227. ++NumCSInlined;
  1228. // Prorate inlined probes for a duplicated inlining callsite which probably
  1229. // has a distribution less than 100%. Samples for an inlinee should be
  1230. // distributed among the copies of the original callsite based on each
  1231. // callsite's distribution factor for counts accuracy. Note that an inlined
  1232. // probe may come with its own distribution factor if it has been duplicated
  1233. // in the inlinee body. The two factor are multiplied to reflect the
  1234. // aggregation of duplication.
  1235. if (Candidate.CallsiteDistribution < 1) {
  1236. for (auto &I : IFI.InlinedCallSites) {
  1237. if (Optional<PseudoProbe> Probe = extractProbe(*I))
  1238. setProbeDistributionFactor(*I, Probe->Factor *
  1239. Candidate.CallsiteDistribution);
  1240. }
  1241. NumDuplicatedInlinesite++;
  1242. }
  1243. return true;
  1244. }
  1245. return false;
  1246. }
  1247. bool SampleProfileLoader::getInlineCandidate(InlineCandidate *NewCandidate,
  1248. CallBase *CB) {
  1249. assert(CB && "Expect non-null call instruction");
  1250. if (isa<IntrinsicInst>(CB))
  1251. return false;
  1252. // Find the callee's profile. For indirect call, find hottest target profile.
  1253. const FunctionSamples *CalleeSamples = findCalleeFunctionSamples(*CB);
  1254. if (!CalleeSamples)
  1255. return false;
  1256. float Factor = 1.0;
  1257. if (Optional<PseudoProbe> Probe = extractProbe(*CB))
  1258. Factor = Probe->Factor;
  1259. uint64_t CallsiteCount = 0;
  1260. ErrorOr<uint64_t> Weight = getBlockWeight(CB->getParent());
  1261. if (Weight)
  1262. CallsiteCount = Weight.get();
  1263. if (CalleeSamples)
  1264. CallsiteCount = std::max(
  1265. CallsiteCount, uint64_t(CalleeSamples->getEntrySamples() * Factor));
  1266. *NewCandidate = {CB, CalleeSamples, CallsiteCount, Factor};
  1267. return true;
  1268. }
  1269. InlineCost
  1270. SampleProfileLoader::shouldInlineCandidate(InlineCandidate &Candidate) {
  1271. std::unique_ptr<InlineAdvice> Advice = nullptr;
  1272. if (ExternalInlineAdvisor) {
  1273. Advice = ExternalInlineAdvisor->getAdvice(*Candidate.CallInstr);
  1274. if (!Advice->isInliningRecommended()) {
  1275. Advice->recordUnattemptedInlining();
  1276. return InlineCost::getNever("not previously inlined");
  1277. }
  1278. Advice->recordInlining();
  1279. return InlineCost::getAlways("previously inlined");
  1280. }
  1281. // Adjust threshold based on call site hotness, only do this for callsite
  1282. // prioritized inliner because otherwise cost-benefit check is done earlier.
  1283. int SampleThreshold = SampleColdCallSiteThreshold;
  1284. if (CallsitePrioritizedInline) {
  1285. if (Candidate.CallsiteCount > PSI->getHotCountThreshold())
  1286. SampleThreshold = SampleHotCallSiteThreshold;
  1287. else if (!ProfileSizeInline)
  1288. return InlineCost::getNever("cold callsite");
  1289. }
  1290. Function *Callee = Candidate.CallInstr->getCalledFunction();
  1291. assert(Callee && "Expect a definition for inline candidate of direct call");
  1292. InlineParams Params = getInlineParams();
  1293. Params.ComputeFullInlineCost = true;
  1294. // Checks if there is anything in the reachable portion of the callee at
  1295. // this callsite that makes this inlining potentially illegal. Need to
  1296. // set ComputeFullInlineCost, otherwise getInlineCost may return early
  1297. // when cost exceeds threshold without checking all IRs in the callee.
  1298. // The acutal cost does not matter because we only checks isNever() to
  1299. // see if it is legal to inline the callsite.
  1300. InlineCost Cost = getInlineCost(*Candidate.CallInstr, Callee, Params,
  1301. GetTTI(*Callee), GetAC, GetTLI);
  1302. // Honor always inline and never inline from call analyzer
  1303. if (Cost.isNever() || Cost.isAlways())
  1304. return Cost;
  1305. // For old FDO inliner, we inline the call site as long as cost is not
  1306. // "Never". The cost-benefit check is done earlier.
  1307. if (!CallsitePrioritizedInline) {
  1308. return InlineCost::get(Cost.getCost(), INT_MAX);
  1309. }
  1310. // Otherwise only use the cost from call analyzer, but overwite threshold with
  1311. // Sample PGO threshold.
  1312. return InlineCost::get(Cost.getCost(), SampleThreshold);
  1313. }
  1314. bool SampleProfileLoader::inlineHotFunctionsWithPriority(
  1315. Function &F, DenseSet<GlobalValue::GUID> &InlinedGUIDs) {
  1316. DenseSet<Instruction *> PromotedInsns;
  1317. assert(ProfileIsCS && "Prioritiy based inliner only works with CSSPGO now");
  1318. // ProfAccForSymsInList is used in callsiteIsHot. The assertion makes sure
  1319. // Profile symbol list is ignored when profile-sample-accurate is on.
  1320. assert((!ProfAccForSymsInList ||
  1321. (!ProfileSampleAccurate &&
  1322. !F.hasFnAttribute("profile-sample-accurate"))) &&
  1323. "ProfAccForSymsInList should be false when profile-sample-accurate "
  1324. "is enabled");
  1325. // Populating worklist with initial call sites from root inliner, along
  1326. // with call site weights.
  1327. CandidateQueue CQueue;
  1328. InlineCandidate NewCandidate;
  1329. for (auto &BB : F) {
  1330. for (auto &I : BB.getInstList()) {
  1331. auto *CB = dyn_cast<CallBase>(&I);
  1332. if (!CB)
  1333. continue;
  1334. if (getInlineCandidate(&NewCandidate, CB))
  1335. CQueue.push(NewCandidate);
  1336. }
  1337. }
  1338. // Cap the size growth from profile guided inlining. This is needed even
  1339. // though cost of each inline candidate already accounts for callee size,
  1340. // because with top-down inlining, we can grow inliner size significantly
  1341. // with large number of smaller inlinees each pass the cost check.
  1342. assert(ProfileInlineLimitMax >= ProfileInlineLimitMin &&
  1343. "Max inline size limit should not be smaller than min inline size "
  1344. "limit.");
  1345. unsigned SizeLimit = F.getInstructionCount() * ProfileInlineGrowthLimit;
  1346. SizeLimit = std::min(SizeLimit, (unsigned)ProfileInlineLimitMax);
  1347. SizeLimit = std::max(SizeLimit, (unsigned)ProfileInlineLimitMin);
  1348. if (ExternalInlineAdvisor)
  1349. SizeLimit = std::numeric_limits<unsigned>::max();
  1350. // Perform iterative BFS call site prioritized inlining
  1351. bool Changed = false;
  1352. while (!CQueue.empty() && F.getInstructionCount() < SizeLimit) {
  1353. InlineCandidate Candidate = CQueue.top();
  1354. CQueue.pop();
  1355. CallBase *I = Candidate.CallInstr;
  1356. Function *CalledFunction = I->getCalledFunction();
  1357. if (CalledFunction == &F)
  1358. continue;
  1359. if (I->isIndirectCall()) {
  1360. if (PromotedInsns.count(I))
  1361. continue;
  1362. uint64_t Sum;
  1363. auto CalleeSamples = findIndirectCallFunctionSamples(*I, Sum);
  1364. uint64_t SumOrigin = Sum;
  1365. Sum *= Candidate.CallsiteDistribution;
  1366. for (const auto *FS : CalleeSamples) {
  1367. // TODO: Consider disable pre-lTO ICP for MonoLTO as well
  1368. if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
  1369. FS->findInlinedFunctions(InlinedGUIDs, F.getParent(),
  1370. PSI->getOrCompHotCountThreshold());
  1371. continue;
  1372. }
  1373. uint64_t EntryCountDistributed =
  1374. FS->getEntrySamples() * Candidate.CallsiteDistribution;
  1375. // In addition to regular inline cost check, we also need to make sure
  1376. // ICP isn't introducing excessive speculative checks even if individual
  1377. // target looks beneficial to promote and inline. That means we should
  1378. // only do ICP when there's a small number dominant targets.
  1379. if (EntryCountDistributed < SumOrigin / ProfileICPThreshold)
  1380. break;
  1381. // TODO: Fix CallAnalyzer to handle all indirect calls.
  1382. // For indirect call, we don't run CallAnalyzer to get InlineCost
  1383. // before actual inlining. This is because we could see two different
  1384. // types from the same definition, which makes CallAnalyzer choke as
  1385. // it's expecting matching parameter type on both caller and callee
  1386. // side. See example from PR18962 for the triggering cases (the bug was
  1387. // fixed, but we generate different types).
  1388. if (!PSI->isHotCount(EntryCountDistributed))
  1389. break;
  1390. SmallVector<CallBase *, 8> InlinedCallSites;
  1391. // Attach function profile for promoted indirect callee, and update
  1392. // call site count for the promoted inline candidate too.
  1393. Candidate = {I, FS, EntryCountDistributed,
  1394. Candidate.CallsiteDistribution};
  1395. if (tryPromoteAndInlineCandidate(F, Candidate, SumOrigin, Sum,
  1396. PromotedInsns, &InlinedCallSites)) {
  1397. for (auto *CB : InlinedCallSites) {
  1398. if (getInlineCandidate(&NewCandidate, CB))
  1399. CQueue.emplace(NewCandidate);
  1400. }
  1401. Changed = true;
  1402. }
  1403. }
  1404. } else if (CalledFunction && CalledFunction->getSubprogram() &&
  1405. !CalledFunction->isDeclaration()) {
  1406. SmallVector<CallBase *, 8> InlinedCallSites;
  1407. if (tryInlineCandidate(Candidate, &InlinedCallSites)) {
  1408. for (auto *CB : InlinedCallSites) {
  1409. if (getInlineCandidate(&NewCandidate, CB))
  1410. CQueue.emplace(NewCandidate);
  1411. }
  1412. Changed = true;
  1413. }
  1414. } else if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
  1415. findCalleeFunctionSamples(*I)->findInlinedFunctions(
  1416. InlinedGUIDs, F.getParent(), PSI->getOrCompHotCountThreshold());
  1417. }
  1418. }
  1419. if (!CQueue.empty()) {
  1420. if (SizeLimit == (unsigned)ProfileInlineLimitMax)
  1421. ++NumCSInlinedHitMaxLimit;
  1422. else if (SizeLimit == (unsigned)ProfileInlineLimitMin)
  1423. ++NumCSInlinedHitMinLimit;
  1424. else
  1425. ++NumCSInlinedHitGrowthLimit;
  1426. }
  1427. return Changed;
  1428. }
  1429. /// Find equivalence classes for the given block.
  1430. ///
  1431. /// This finds all the blocks that are guaranteed to execute the same
  1432. /// number of times as \p BB1. To do this, it traverses all the
  1433. /// descendants of \p BB1 in the dominator or post-dominator tree.
  1434. ///
  1435. /// A block BB2 will be in the same equivalence class as \p BB1 if
  1436. /// the following holds:
  1437. ///
  1438. /// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2
  1439. /// is a descendant of \p BB1 in the dominator tree, then BB2 should
  1440. /// dominate BB1 in the post-dominator tree.
  1441. ///
  1442. /// 2- Both BB2 and \p BB1 must be in the same loop.
  1443. ///
  1444. /// For every block BB2 that meets those two requirements, we set BB2's
  1445. /// equivalence class to \p BB1.
  1446. ///
  1447. /// \param BB1 Block to check.
  1448. /// \param Descendants Descendants of \p BB1 in either the dom or pdom tree.
  1449. /// \param DomTree Opposite dominator tree. If \p Descendants is filled
  1450. /// with blocks from \p BB1's dominator tree, then
  1451. /// this is the post-dominator tree, and vice versa.
  1452. template <bool IsPostDom>
  1453. void SampleProfileLoader::findEquivalencesFor(
  1454. BasicBlock *BB1, ArrayRef<BasicBlock *> Descendants,
  1455. DominatorTreeBase<BasicBlock, IsPostDom> *DomTree) {
  1456. const BasicBlock *EC = EquivalenceClass[BB1];
  1457. uint64_t Weight = BlockWeights[EC];
  1458. for (const auto *BB2 : Descendants) {
  1459. bool IsDomParent = DomTree->dominates(BB2, BB1);
  1460. bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2);
  1461. if (BB1 != BB2 && IsDomParent && IsInSameLoop) {
  1462. EquivalenceClass[BB2] = EC;
  1463. // If BB2 is visited, then the entire EC should be marked as visited.
  1464. if (VisitedBlocks.count(BB2)) {
  1465. VisitedBlocks.insert(EC);
  1466. }
  1467. // If BB2 is heavier than BB1, make BB2 have the same weight
  1468. // as BB1.
  1469. //
  1470. // Note that we don't worry about the opposite situation here
  1471. // (when BB2 is lighter than BB1). We will deal with this
  1472. // during the propagation phase. Right now, we just want to
  1473. // make sure that BB1 has the largest weight of all the
  1474. // members of its equivalence set.
  1475. Weight = std::max(Weight, BlockWeights[BB2]);
  1476. }
  1477. }
  1478. if (EC == &EC->getParent()->getEntryBlock()) {
  1479. BlockWeights[EC] = Samples->getHeadSamples() + 1;
  1480. } else {
  1481. BlockWeights[EC] = Weight;
  1482. }
  1483. }
  1484. /// Find equivalence classes.
  1485. ///
  1486. /// Since samples may be missing from blocks, we can fill in the gaps by setting
  1487. /// the weights of all the blocks in the same equivalence class to the same
  1488. /// weight. To compute the concept of equivalence, we use dominance and loop
  1489. /// information. Two blocks B1 and B2 are in the same equivalence class if B1
  1490. /// dominates B2, B2 post-dominates B1 and both are in the same loop.
  1491. ///
  1492. /// \param F The function to query.
  1493. void SampleProfileLoader::findEquivalenceClasses(Function &F) {
  1494. SmallVector<BasicBlock *, 8> DominatedBBs;
  1495. LLVM_DEBUG(dbgs() << "\nBlock equivalence classes\n");
  1496. // Find equivalence sets based on dominance and post-dominance information.
  1497. for (auto &BB : F) {
  1498. BasicBlock *BB1 = &BB;
  1499. // Compute BB1's equivalence class once.
  1500. if (EquivalenceClass.count(BB1)) {
  1501. LLVM_DEBUG(printBlockEquivalence(dbgs(), BB1));
  1502. continue;
  1503. }
  1504. // By default, blocks are in their own equivalence class.
  1505. EquivalenceClass[BB1] = BB1;
  1506. // Traverse all the blocks dominated by BB1. We are looking for
  1507. // every basic block BB2 such that:
  1508. //
  1509. // 1- BB1 dominates BB2.
  1510. // 2- BB2 post-dominates BB1.
  1511. // 3- BB1 and BB2 are in the same loop nest.
  1512. //
  1513. // If all those conditions hold, it means that BB2 is executed
  1514. // as many times as BB1, so they are placed in the same equivalence
  1515. // class by making BB2's equivalence class be BB1.
  1516. DominatedBBs.clear();
  1517. DT->getDescendants(BB1, DominatedBBs);
  1518. findEquivalencesFor(BB1, DominatedBBs, PDT.get());
  1519. LLVM_DEBUG(printBlockEquivalence(dbgs(), BB1));
  1520. }
  1521. // Assign weights to equivalence classes.
  1522. //
  1523. // All the basic blocks in the same equivalence class will execute
  1524. // the same number of times. Since we know that the head block in
  1525. // each equivalence class has the largest weight, assign that weight
  1526. // to all the blocks in that equivalence class.
  1527. LLVM_DEBUG(
  1528. dbgs() << "\nAssign the same weight to all blocks in the same class\n");
  1529. for (auto &BI : F) {
  1530. const BasicBlock *BB = &BI;
  1531. const BasicBlock *EquivBB = EquivalenceClass[BB];
  1532. if (BB != EquivBB)
  1533. BlockWeights[BB] = BlockWeights[EquivBB];
  1534. LLVM_DEBUG(printBlockWeight(dbgs(), BB));
  1535. }
  1536. }
  1537. /// Visit the given edge to decide if it has a valid weight.
  1538. ///
  1539. /// If \p E has not been visited before, we copy to \p UnknownEdge
  1540. /// and increment the count of unknown edges.
  1541. ///
  1542. /// \param E Edge to visit.
  1543. /// \param NumUnknownEdges Current number of unknown edges.
  1544. /// \param UnknownEdge Set if E has not been visited before.
  1545. ///
  1546. /// \returns E's weight, if known. Otherwise, return 0.
  1547. uint64_t SampleProfileLoader::visitEdge(Edge E, unsigned *NumUnknownEdges,
  1548. Edge *UnknownEdge) {
  1549. if (!VisitedEdges.count(E)) {
  1550. (*NumUnknownEdges)++;
  1551. *UnknownEdge = E;
  1552. return 0;
  1553. }
  1554. return EdgeWeights[E];
  1555. }
  1556. /// Propagate weights through incoming/outgoing edges.
  1557. ///
  1558. /// If the weight of a basic block is known, and there is only one edge
  1559. /// with an unknown weight, we can calculate the weight of that edge.
  1560. ///
  1561. /// Similarly, if all the edges have a known count, we can calculate the
  1562. /// count of the basic block, if needed.
  1563. ///
  1564. /// \param F Function to process.
  1565. /// \param UpdateBlockCount Whether we should update basic block counts that
  1566. /// has already been annotated.
  1567. ///
  1568. /// \returns True if new weights were assigned to edges or blocks.
  1569. bool SampleProfileLoader::propagateThroughEdges(Function &F,
  1570. bool UpdateBlockCount) {
  1571. bool Changed = false;
  1572. LLVM_DEBUG(dbgs() << "\nPropagation through edges\n");
  1573. for (const auto &BI : F) {
  1574. const BasicBlock *BB = &BI;
  1575. const BasicBlock *EC = EquivalenceClass[BB];
  1576. // Visit all the predecessor and successor edges to determine
  1577. // which ones have a weight assigned already. Note that it doesn't
  1578. // matter that we only keep track of a single unknown edge. The
  1579. // only case we are interested in handling is when only a single
  1580. // edge is unknown (see setEdgeOrBlockWeight).
  1581. for (unsigned i = 0; i < 2; i++) {
  1582. uint64_t TotalWeight = 0;
  1583. unsigned NumUnknownEdges = 0, NumTotalEdges = 0;
  1584. Edge UnknownEdge, SelfReferentialEdge, SingleEdge;
  1585. if (i == 0) {
  1586. // First, visit all predecessor edges.
  1587. NumTotalEdges = Predecessors[BB].size();
  1588. for (auto *Pred : Predecessors[BB]) {
  1589. Edge E = std::make_pair(Pred, BB);
  1590. TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
  1591. if (E.first == E.second)
  1592. SelfReferentialEdge = E;
  1593. }
  1594. if (NumTotalEdges == 1) {
  1595. SingleEdge = std::make_pair(Predecessors[BB][0], BB);
  1596. }
  1597. } else {
  1598. // On the second round, visit all successor edges.
  1599. NumTotalEdges = Successors[BB].size();
  1600. for (auto *Succ : Successors[BB]) {
  1601. Edge E = std::make_pair(BB, Succ);
  1602. TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
  1603. }
  1604. if (NumTotalEdges == 1) {
  1605. SingleEdge = std::make_pair(BB, Successors[BB][0]);
  1606. }
  1607. }
  1608. // After visiting all the edges, there are three cases that we
  1609. // can handle immediately:
  1610. //
  1611. // - All the edge weights are known (i.e., NumUnknownEdges == 0).
  1612. // In this case, we simply check that the sum of all the edges
  1613. // is the same as BB's weight. If not, we change BB's weight
  1614. // to match. Additionally, if BB had not been visited before,
  1615. // we mark it visited.
  1616. //
  1617. // - Only one edge is unknown and BB has already been visited.
  1618. // In this case, we can compute the weight of the edge by
  1619. // subtracting the total block weight from all the known
  1620. // edge weights. If the edges weight more than BB, then the
  1621. // edge of the last remaining edge is set to zero.
  1622. //
  1623. // - There exists a self-referential edge and the weight of BB is
  1624. // known. In this case, this edge can be based on BB's weight.
  1625. // We add up all the other known edges and set the weight on
  1626. // the self-referential edge as we did in the previous case.
  1627. //
  1628. // In any other case, we must continue iterating. Eventually,
  1629. // all edges will get a weight, or iteration will stop when
  1630. // it reaches SampleProfileMaxPropagateIterations.
  1631. if (NumUnknownEdges <= 1) {
  1632. uint64_t &BBWeight = BlockWeights[EC];
  1633. if (NumUnknownEdges == 0) {
  1634. if (!VisitedBlocks.count(EC)) {
  1635. // If we already know the weight of all edges, the weight of the
  1636. // basic block can be computed. It should be no larger than the sum
  1637. // of all edge weights.
  1638. if (TotalWeight > BBWeight) {
  1639. BBWeight = TotalWeight;
  1640. Changed = true;
  1641. LLVM_DEBUG(dbgs() << "All edge weights for " << BB->getName()
  1642. << " known. Set weight for block: ";
  1643. printBlockWeight(dbgs(), BB););
  1644. }
  1645. } else if (NumTotalEdges == 1 &&
  1646. EdgeWeights[SingleEdge] < BlockWeights[EC]) {
  1647. // If there is only one edge for the visited basic block, use the
  1648. // block weight to adjust edge weight if edge weight is smaller.
  1649. EdgeWeights[SingleEdge] = BlockWeights[EC];
  1650. Changed = true;
  1651. }
  1652. } else if (NumUnknownEdges == 1 && VisitedBlocks.count(EC)) {
  1653. // If there is a single unknown edge and the block has been
  1654. // visited, then we can compute E's weight.
  1655. if (BBWeight >= TotalWeight)
  1656. EdgeWeights[UnknownEdge] = BBWeight - TotalWeight;
  1657. else
  1658. EdgeWeights[UnknownEdge] = 0;
  1659. const BasicBlock *OtherEC;
  1660. if (i == 0)
  1661. OtherEC = EquivalenceClass[UnknownEdge.first];
  1662. else
  1663. OtherEC = EquivalenceClass[UnknownEdge.second];
  1664. // Edge weights should never exceed the BB weights it connects.
  1665. if (VisitedBlocks.count(OtherEC) &&
  1666. EdgeWeights[UnknownEdge] > BlockWeights[OtherEC])
  1667. EdgeWeights[UnknownEdge] = BlockWeights[OtherEC];
  1668. VisitedEdges.insert(UnknownEdge);
  1669. Changed = true;
  1670. LLVM_DEBUG(dbgs() << "Set weight for edge: ";
  1671. printEdgeWeight(dbgs(), UnknownEdge));
  1672. }
  1673. } else if (VisitedBlocks.count(EC) && BlockWeights[EC] == 0) {
  1674. // If a block Weights 0, all its in/out edges should weight 0.
  1675. if (i == 0) {
  1676. for (auto *Pred : Predecessors[BB]) {
  1677. Edge E = std::make_pair(Pred, BB);
  1678. EdgeWeights[E] = 0;
  1679. VisitedEdges.insert(E);
  1680. }
  1681. } else {
  1682. for (auto *Succ : Successors[BB]) {
  1683. Edge E = std::make_pair(BB, Succ);
  1684. EdgeWeights[E] = 0;
  1685. VisitedEdges.insert(E);
  1686. }
  1687. }
  1688. } else if (SelfReferentialEdge.first && VisitedBlocks.count(EC)) {
  1689. uint64_t &BBWeight = BlockWeights[BB];
  1690. // We have a self-referential edge and the weight of BB is known.
  1691. if (BBWeight >= TotalWeight)
  1692. EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight;
  1693. else
  1694. EdgeWeights[SelfReferentialEdge] = 0;
  1695. VisitedEdges.insert(SelfReferentialEdge);
  1696. Changed = true;
  1697. LLVM_DEBUG(dbgs() << "Set self-referential edge weight to: ";
  1698. printEdgeWeight(dbgs(), SelfReferentialEdge));
  1699. }
  1700. if (UpdateBlockCount && !VisitedBlocks.count(EC) && TotalWeight > 0) {
  1701. BlockWeights[EC] = TotalWeight;
  1702. VisitedBlocks.insert(EC);
  1703. Changed = true;
  1704. }
  1705. }
  1706. }
  1707. return Changed;
  1708. }
  1709. /// Build in/out edge lists for each basic block in the CFG.
  1710. ///
  1711. /// We are interested in unique edges. If a block B1 has multiple
  1712. /// edges to another block B2, we only add a single B1->B2 edge.
  1713. void SampleProfileLoader::buildEdges(Function &F) {
  1714. for (auto &BI : F) {
  1715. BasicBlock *B1 = &BI;
  1716. // Add predecessors for B1.
  1717. SmallPtrSet<BasicBlock *, 16> Visited;
  1718. if (!Predecessors[B1].empty())
  1719. llvm_unreachable("Found a stale predecessors list in a basic block.");
  1720. for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) {
  1721. BasicBlock *B2 = *PI;
  1722. if (Visited.insert(B2).second)
  1723. Predecessors[B1].push_back(B2);
  1724. }
  1725. // Add successors for B1.
  1726. Visited.clear();
  1727. if (!Successors[B1].empty())
  1728. llvm_unreachable("Found a stale successors list in a basic block.");
  1729. for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) {
  1730. BasicBlock *B2 = *SI;
  1731. if (Visited.insert(B2).second)
  1732. Successors[B1].push_back(B2);
  1733. }
  1734. }
  1735. }
  1736. /// Returns the sorted CallTargetMap \p M by count in descending order.
  1737. static SmallVector<InstrProfValueData, 2> GetSortedValueDataFromCallTargets(
  1738. const SampleRecord::CallTargetMap & M) {
  1739. SmallVector<InstrProfValueData, 2> R;
  1740. for (const auto &I : SampleRecord::SortCallTargets(M)) {
  1741. R.emplace_back(InstrProfValueData{FunctionSamples::getGUID(I.first), I.second});
  1742. }
  1743. return R;
  1744. }
  1745. /// Propagate weights into edges
  1746. ///
  1747. /// The following rules are applied to every block BB in the CFG:
  1748. ///
  1749. /// - If BB has a single predecessor/successor, then the weight
  1750. /// of that edge is the weight of the block.
  1751. ///
  1752. /// - If all incoming or outgoing edges are known except one, and the
  1753. /// weight of the block is already known, the weight of the unknown
  1754. /// edge will be the weight of the block minus the sum of all the known
  1755. /// edges. If the sum of all the known edges is larger than BB's weight,
  1756. /// we set the unknown edge weight to zero.
  1757. ///
  1758. /// - If there is a self-referential edge, and the weight of the block is
  1759. /// known, the weight for that edge is set to the weight of the block
  1760. /// minus the weight of the other incoming edges to that block (if
  1761. /// known).
  1762. void SampleProfileLoader::propagateWeights(Function &F) {
  1763. bool Changed = true;
  1764. unsigned I = 0;
  1765. // If BB weight is larger than its corresponding loop's header BB weight,
  1766. // use the BB weight to replace the loop header BB weight.
  1767. for (auto &BI : F) {
  1768. BasicBlock *BB = &BI;
  1769. Loop *L = LI->getLoopFor(BB);
  1770. if (!L) {
  1771. continue;
  1772. }
  1773. BasicBlock *Header = L->getHeader();
  1774. if (Header && BlockWeights[BB] > BlockWeights[Header]) {
  1775. BlockWeights[Header] = BlockWeights[BB];
  1776. }
  1777. }
  1778. // Before propagation starts, build, for each block, a list of
  1779. // unique predecessors and successors. This is necessary to handle
  1780. // identical edges in multiway branches. Since we visit all blocks and all
  1781. // edges of the CFG, it is cleaner to build these lists once at the start
  1782. // of the pass.
  1783. buildEdges(F);
  1784. // Propagate until we converge or we go past the iteration limit.
  1785. while (Changed && I++ < SampleProfileMaxPropagateIterations) {
  1786. Changed = propagateThroughEdges(F, false);
  1787. }
  1788. // The first propagation propagates BB counts from annotated BBs to unknown
  1789. // BBs. The 2nd propagation pass resets edges weights, and use all BB weights
  1790. // to propagate edge weights.
  1791. VisitedEdges.clear();
  1792. Changed = true;
  1793. while (Changed && I++ < SampleProfileMaxPropagateIterations) {
  1794. Changed = propagateThroughEdges(F, false);
  1795. }
  1796. // The 3rd propagation pass allows adjust annotated BB weights that are
  1797. // obviously wrong.
  1798. Changed = true;
  1799. while (Changed && I++ < SampleProfileMaxPropagateIterations) {
  1800. Changed = propagateThroughEdges(F, true);
  1801. }
  1802. // Generate MD_prof metadata for every branch instruction using the
  1803. // edge weights computed during propagation.
  1804. LLVM_DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
  1805. LLVMContext &Ctx = F.getContext();
  1806. MDBuilder MDB(Ctx);
  1807. for (auto &BI : F) {
  1808. BasicBlock *BB = &BI;
  1809. if (BlockWeights[BB]) {
  1810. for (auto &I : BB->getInstList()) {
  1811. if (!isa<CallInst>(I) && !isa<InvokeInst>(I))
  1812. continue;
  1813. if (!cast<CallBase>(I).getCalledFunction()) {
  1814. const DebugLoc &DLoc = I.getDebugLoc();
  1815. if (!DLoc)
  1816. continue;
  1817. const DILocation *DIL = DLoc;
  1818. const FunctionSamples *FS = findFunctionSamples(I);
  1819. if (!FS)
  1820. continue;
  1821. auto CallSite = FunctionSamples::getCallSiteIdentifier(DIL);
  1822. auto T = FS->findCallTargetMapAt(CallSite);
  1823. if (!T || T.get().empty())
  1824. continue;
  1825. // Prorate the callsite counts to reflect what is already done to the
  1826. // callsite, such as ICP or calliste cloning.
  1827. if (FunctionSamples::ProfileIsProbeBased) {
  1828. if (Optional<PseudoProbe> Probe = extractProbe(I)) {
  1829. if (Probe->Factor < 1)
  1830. T = SampleRecord::adjustCallTargets(T.get(), Probe->Factor);
  1831. }
  1832. }
  1833. SmallVector<InstrProfValueData, 2> SortedCallTargets =
  1834. GetSortedValueDataFromCallTargets(T.get());
  1835. uint64_t Sum;
  1836. findIndirectCallFunctionSamples(I, Sum);
  1837. annotateValueSite(*I.getParent()->getParent()->getParent(), I,
  1838. SortedCallTargets, Sum, IPVK_IndirectCallTarget,
  1839. SortedCallTargets.size());
  1840. } else if (!isa<IntrinsicInst>(&I)) {
  1841. I.setMetadata(LLVMContext::MD_prof,
  1842. MDB.createBranchWeights(
  1843. {static_cast<uint32_t>(BlockWeights[BB])}));
  1844. }
  1845. }
  1846. }
  1847. Instruction *TI = BB->getTerminator();
  1848. if (TI->getNumSuccessors() == 1)
  1849. continue;
  1850. if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
  1851. continue;
  1852. DebugLoc BranchLoc = TI->getDebugLoc();
  1853. LLVM_DEBUG(dbgs() << "\nGetting weights for branch at line "
  1854. << ((BranchLoc) ? Twine(BranchLoc.getLine())
  1855. : Twine("<UNKNOWN LOCATION>"))
  1856. << ".\n");
  1857. SmallVector<uint32_t, 4> Weights;
  1858. uint32_t MaxWeight = 0;
  1859. Instruction *MaxDestInst;
  1860. for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
  1861. BasicBlock *Succ = TI->getSuccessor(I);
  1862. Edge E = std::make_pair(BB, Succ);
  1863. uint64_t Weight = EdgeWeights[E];
  1864. LLVM_DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
  1865. // Use uint32_t saturated arithmetic to adjust the incoming weights,
  1866. // if needed. Sample counts in profiles are 64-bit unsigned values,
  1867. // but internally branch weights are expressed as 32-bit values.
  1868. if (Weight > std::numeric_limits<uint32_t>::max()) {
  1869. LLVM_DEBUG(dbgs() << " (saturated due to uint32_t overflow)");
  1870. Weight = std::numeric_limits<uint32_t>::max();
  1871. }
  1872. // Weight is added by one to avoid propagation errors introduced by
  1873. // 0 weights.
  1874. Weights.push_back(static_cast<uint32_t>(Weight + 1));
  1875. if (Weight != 0) {
  1876. if (Weight > MaxWeight) {
  1877. MaxWeight = Weight;
  1878. MaxDestInst = Succ->getFirstNonPHIOrDbgOrLifetime();
  1879. }
  1880. }
  1881. }
  1882. uint64_t TempWeight;
  1883. // Only set weights if there is at least one non-zero weight.
  1884. // In any other case, let the analyzer set weights.
  1885. // Do not set weights if the weights are present. In ThinLTO, the profile
  1886. // annotation is done twice. If the first annotation already set the
  1887. // weights, the second pass does not need to set it.
  1888. if (MaxWeight > 0 && !TI->extractProfTotalWeight(TempWeight)) {
  1889. LLVM_DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
  1890. TI->setMetadata(LLVMContext::MD_prof,
  1891. MDB.createBranchWeights(Weights));
  1892. ORE->emit([&]() {
  1893. return OptimizationRemark(DEBUG_TYPE, "PopularDest", MaxDestInst)
  1894. << "most popular destination for conditional branches at "
  1895. << ore::NV("CondBranchesLoc", BranchLoc);
  1896. });
  1897. } else {
  1898. LLVM_DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
  1899. }
  1900. }
  1901. }
  1902. /// Get the line number for the function header.
  1903. ///
  1904. /// This looks up function \p F in the current compilation unit and
  1905. /// retrieves the line number where the function is defined. This is
  1906. /// line 0 for all the samples read from the profile file. Every line
  1907. /// number is relative to this line.
  1908. ///
  1909. /// \param F Function object to query.
  1910. ///
  1911. /// \returns the line number where \p F is defined. If it returns 0,
  1912. /// it means that there is no debug information available for \p F.
  1913. unsigned SampleProfileLoader::getFunctionLoc(Function &F) {
  1914. if (DISubprogram *S = F.getSubprogram())
  1915. return S->getLine();
  1916. if (NoWarnSampleUnused)
  1917. return 0;
  1918. // If the start of \p F is missing, emit a diagnostic to inform the user
  1919. // about the missed opportunity.
  1920. F.getContext().diagnose(DiagnosticInfoSampleProfile(
  1921. "No debug information found in function " + F.getName() +
  1922. ": Function profile not used",
  1923. DS_Warning));
  1924. return 0;
  1925. }
  1926. void SampleProfileLoader::computeDominanceAndLoopInfo(Function &F) {
  1927. DT.reset(new DominatorTree);
  1928. DT->recalculate(F);
  1929. PDT.reset(new PostDominatorTree(F));
  1930. LI.reset(new LoopInfo);
  1931. LI->analyze(*DT);
  1932. }
  1933. /// Generate branch weight metadata for all branches in \p F.
  1934. ///
  1935. /// Branch weights are computed out of instruction samples using a
  1936. /// propagation heuristic. Propagation proceeds in 3 phases:
  1937. ///
  1938. /// 1- Assignment of block weights. All the basic blocks in the function
  1939. /// are initial assigned the same weight as their most frequently
  1940. /// executed instruction.
  1941. ///
  1942. /// 2- Creation of equivalence classes. Since samples may be missing from
  1943. /// blocks, we can fill in the gaps by setting the weights of all the
  1944. /// blocks in the same equivalence class to the same weight. To compute
  1945. /// the concept of equivalence, we use dominance and loop information.
  1946. /// Two blocks B1 and B2 are in the same equivalence class if B1
  1947. /// dominates B2, B2 post-dominates B1 and both are in the same loop.
  1948. ///
  1949. /// 3- Propagation of block weights into edges. This uses a simple
  1950. /// propagation heuristic. The following rules are applied to every
  1951. /// block BB in the CFG:
  1952. ///
  1953. /// - If BB has a single predecessor/successor, then the weight
  1954. /// of that edge is the weight of the block.
  1955. ///
  1956. /// - If all the edges are known except one, and the weight of the
  1957. /// block is already known, the weight of the unknown edge will
  1958. /// be the weight of the block minus the sum of all the known
  1959. /// edges. If the sum of all the known edges is larger than BB's weight,
  1960. /// we set the unknown edge weight to zero.
  1961. ///
  1962. /// - If there is a self-referential edge, and the weight of the block is
  1963. /// known, the weight for that edge is set to the weight of the block
  1964. /// minus the weight of the other incoming edges to that block (if
  1965. /// known).
  1966. ///
  1967. /// Since this propagation is not guaranteed to finalize for every CFG, we
  1968. /// only allow it to proceed for a limited number of iterations (controlled
  1969. /// by -sample-profile-max-propagate-iterations).
  1970. ///
  1971. /// FIXME: Try to replace this propagation heuristic with a scheme
  1972. /// that is guaranteed to finalize. A work-list approach similar to
  1973. /// the standard value propagation algorithm used by SSA-CCP might
  1974. /// work here.
  1975. ///
  1976. /// Once all the branch weights are computed, we emit the MD_prof
  1977. /// metadata on BB using the computed values for each of its branches.
  1978. ///
  1979. /// \param F The function to query.
  1980. ///
  1981. /// \returns true if \p F was modified. Returns false, otherwise.
  1982. bool SampleProfileLoader::emitAnnotations(Function &F) {
  1983. bool Changed = false;
  1984. if (FunctionSamples::ProfileIsProbeBased) {
  1985. if (!ProbeManager->profileIsValid(F, *Samples)) {
  1986. LLVM_DEBUG(
  1987. dbgs() << "Profile is invalid due to CFG mismatch for Function "
  1988. << F.getName());
  1989. ++NumMismatchedProfile;
  1990. return false;
  1991. }
  1992. ++NumMatchedProfile;
  1993. } else {
  1994. if (getFunctionLoc(F) == 0)
  1995. return false;
  1996. LLVM_DEBUG(dbgs() << "Line number for the first instruction in "
  1997. << F.getName() << ": " << getFunctionLoc(F) << "\n");
  1998. }
  1999. DenseSet<GlobalValue::GUID> InlinedGUIDs;
  2000. if (ProfileIsCS && CallsitePrioritizedInline)
  2001. Changed |= inlineHotFunctionsWithPriority(F, InlinedGUIDs);
  2002. else
  2003. Changed |= inlineHotFunctions(F, InlinedGUIDs);
  2004. // Compute basic block weights.
  2005. Changed |= computeBlockWeights(F);
  2006. if (Changed) {
  2007. // Add an entry count to the function using the samples gathered at the
  2008. // function entry.
  2009. // Sets the GUIDs that are inlined in the profiled binary. This is used
  2010. // for ThinLink to make correct liveness analysis, and also make the IR
  2011. // match the profiled binary before annotation.
  2012. F.setEntryCount(
  2013. ProfileCount(Samples->getHeadSamples() + 1, Function::PCT_Real),
  2014. &InlinedGUIDs);
  2015. // Compute dominance and loop info needed for propagation.
  2016. computeDominanceAndLoopInfo(F);
  2017. // Find equivalence classes.
  2018. findEquivalenceClasses(F);
  2019. // Propagate weights to all edges.
  2020. propagateWeights(F);
  2021. }
  2022. // If coverage checking was requested, compute it now.
  2023. if (SampleProfileRecordCoverage) {
  2024. unsigned Used = CoverageTracker.countUsedRecords(Samples, PSI);
  2025. unsigned Total = CoverageTracker.countBodyRecords(Samples, PSI);
  2026. unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
  2027. if (Coverage < SampleProfileRecordCoverage) {
  2028. F.getContext().diagnose(DiagnosticInfoSampleProfile(
  2029. F.getSubprogram()->getFilename(), getFunctionLoc(F),
  2030. Twine(Used) + " of " + Twine(Total) + " available profile records (" +
  2031. Twine(Coverage) + "%) were applied",
  2032. DS_Warning));
  2033. }
  2034. }
  2035. if (SampleProfileSampleCoverage) {
  2036. uint64_t Used = CoverageTracker.getTotalUsedSamples();
  2037. uint64_t Total = CoverageTracker.countBodySamples(Samples, PSI);
  2038. unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
  2039. if (Coverage < SampleProfileSampleCoverage) {
  2040. F.getContext().diagnose(DiagnosticInfoSampleProfile(
  2041. F.getSubprogram()->getFilename(), getFunctionLoc(F),
  2042. Twine(Used) + " of " + Twine(Total) + " available profile samples (" +
  2043. Twine(Coverage) + "%) were applied",
  2044. DS_Warning));
  2045. }
  2046. }
  2047. return Changed;
  2048. }
  2049. char SampleProfileLoaderLegacyPass::ID = 0;
  2050. INITIALIZE_PASS_BEGIN(SampleProfileLoaderLegacyPass, "sample-profile",
  2051. "Sample Profile loader", false, false)
  2052. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  2053. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  2054. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  2055. INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
  2056. INITIALIZE_PASS_END(SampleProfileLoaderLegacyPass, "sample-profile",
  2057. "Sample Profile loader", false, false)
  2058. // Add inlined profile call edges to the call graph.
  2059. void SampleProfileLoader::addCallGraphEdges(CallGraph &CG,
  2060. const FunctionSamples &Samples) {
  2061. Function *Caller = SymbolMap.lookup(Samples.getFuncName());
  2062. if (!Caller || Caller->isDeclaration())
  2063. return;
  2064. // Skip non-inlined call edges which are not important since top down inlining
  2065. // for non-CS profile is to get more precise profile matching, not to enable
  2066. // more inlining.
  2067. for (const auto &CallsiteSamples : Samples.getCallsiteSamples()) {
  2068. for (const auto &InlinedSamples : CallsiteSamples.second) {
  2069. Function *Callee = SymbolMap.lookup(InlinedSamples.first);
  2070. if (Callee && !Callee->isDeclaration())
  2071. CG[Caller]->addCalledFunction(nullptr, CG[Callee]);
  2072. addCallGraphEdges(CG, InlinedSamples.second);
  2073. }
  2074. }
  2075. }
  2076. // Replace call graph edges with dynamic call edges from the profile.
  2077. void SampleProfileLoader::replaceCallGraphEdges(
  2078. CallGraph &CG, StringMap<Function *> &SymbolMap) {
  2079. // Remove static call edges from the call graph except for the ones from the
  2080. // root which make the call graph connected.
  2081. for (const auto &Node : CG)
  2082. if (Node.second.get() != CG.getExternalCallingNode())
  2083. Node.second->removeAllCalledFunctions();
  2084. // Add profile call edges to the call graph.
  2085. if (ProfileIsCS) {
  2086. ContextTracker->addCallGraphEdges(CG, SymbolMap);
  2087. } else {
  2088. for (const auto &Samples : Reader->getProfiles())
  2089. addCallGraphEdges(CG, Samples.second);
  2090. }
  2091. }
  2092. std::vector<Function *>
  2093. SampleProfileLoader::buildFunctionOrder(Module &M, CallGraph *CG) {
  2094. std::vector<Function *> FunctionOrderList;
  2095. FunctionOrderList.reserve(M.size());
  2096. if (!ProfileTopDownLoad || CG == nullptr) {
  2097. if (ProfileMergeInlinee) {
  2098. // Disable ProfileMergeInlinee if profile is not loaded in top down order,
  2099. // because the profile for a function may be used for the profile
  2100. // annotation of its outline copy before the profile merging of its
  2101. // non-inlined inline instances, and that is not the way how
  2102. // ProfileMergeInlinee is supposed to work.
  2103. ProfileMergeInlinee = false;
  2104. }
  2105. for (Function &F : M)
  2106. if (!F.isDeclaration() && F.hasFnAttribute("use-sample-profile"))
  2107. FunctionOrderList.push_back(&F);
  2108. return FunctionOrderList;
  2109. }
  2110. assert(&CG->getModule() == &M);
  2111. // Add indirect call edges from profile to augment the static call graph.
  2112. // Functions will be processed in a top-down order defined by the static call
  2113. // graph. Adjusting the order by considering indirect call edges from the
  2114. // profile (which don't exist in the static call graph) can enable the
  2115. // inlining of indirect call targets by processing the caller before them.
  2116. // TODO: enable this for non-CS profile and fix the counts returning logic to
  2117. // have a full support for indirect calls.
  2118. if (UseProfileIndirectCallEdges && ProfileIsCS) {
  2119. for (auto &Entry : *CG) {
  2120. const auto *F = Entry.first;
  2121. if (!F || F->isDeclaration() || !F->hasFnAttribute("use-sample-profile"))
  2122. continue;
  2123. auto &AllContexts = ContextTracker->getAllContextSamplesFor(F->getName());
  2124. if (AllContexts.empty())
  2125. continue;
  2126. for (const auto &BB : *F) {
  2127. for (const auto &I : BB.getInstList()) {
  2128. const auto *CB = dyn_cast<CallBase>(&I);
  2129. if (!CB || !CB->isIndirectCall())
  2130. continue;
  2131. const DebugLoc &DLoc = I.getDebugLoc();
  2132. if (!DLoc)
  2133. continue;
  2134. auto CallSite = FunctionSamples::getCallSiteIdentifier(DLoc);
  2135. for (FunctionSamples *Samples : AllContexts) {
  2136. if (auto CallTargets = Samples->findCallTargetMapAt(CallSite)) {
  2137. for (const auto &Target : CallTargets.get()) {
  2138. Function *Callee = SymbolMap.lookup(Target.first());
  2139. if (Callee && !Callee->isDeclaration())
  2140. Entry.second->addCalledFunction(nullptr, (*CG)[Callee]);
  2141. }
  2142. }
  2143. }
  2144. }
  2145. }
  2146. }
  2147. }
  2148. // Compute a top-down order the profile which is used to sort functions in
  2149. // one SCC later. The static processing order computed for an SCC may not
  2150. // reflect the call contexts in the context-sensitive profile, thus may cause
  2151. // potential inlining to be overlooked. The function order in one SCC is being
  2152. // adjusted to a top-down order based on the profile to favor more inlining.
  2153. DenseMap<Function *, uint64_t> ProfileOrderMap;
  2154. if (UseProfileTopDownOrder ||
  2155. (ProfileIsCS && !UseProfileTopDownOrder.getNumOccurrences())) {
  2156. // Create a static call graph. The call edges are not important since they
  2157. // will be replaced by dynamic edges from the profile.
  2158. CallGraph ProfileCG(M);
  2159. replaceCallGraphEdges(ProfileCG, SymbolMap);
  2160. scc_iterator<CallGraph *> CGI = scc_begin(&ProfileCG);
  2161. uint64_t I = 0;
  2162. while (!CGI.isAtEnd()) {
  2163. for (CallGraphNode *Node : *CGI) {
  2164. if (auto *F = Node->getFunction())
  2165. ProfileOrderMap[F] = ++I;
  2166. }
  2167. ++CGI;
  2168. }
  2169. }
  2170. scc_iterator<CallGraph *> CGI = scc_begin(CG);
  2171. while (!CGI.isAtEnd()) {
  2172. uint64_t Start = FunctionOrderList.size();
  2173. for (CallGraphNode *Node : *CGI) {
  2174. auto *F = Node->getFunction();
  2175. if (F && !F->isDeclaration() && F->hasFnAttribute("use-sample-profile"))
  2176. FunctionOrderList.push_back(F);
  2177. }
  2178. // Sort nodes in SCC based on the profile top-down order.
  2179. if (!ProfileOrderMap.empty()) {
  2180. std::stable_sort(FunctionOrderList.begin() + Start,
  2181. FunctionOrderList.end(),
  2182. [&ProfileOrderMap](Function *Left, Function *Right) {
  2183. return ProfileOrderMap[Left] < ProfileOrderMap[Right];
  2184. });
  2185. }
  2186. ++CGI;
  2187. }
  2188. LLVM_DEBUG({
  2189. dbgs() << "Function processing order:\n";
  2190. for (auto F : reverse(FunctionOrderList)) {
  2191. dbgs() << F->getName() << "\n";
  2192. }
  2193. });
  2194. std::reverse(FunctionOrderList.begin(), FunctionOrderList.end());
  2195. return FunctionOrderList;
  2196. }
  2197. bool SampleProfileLoader::doInitialization(Module &M,
  2198. FunctionAnalysisManager *FAM) {
  2199. auto &Ctx = M.getContext();
  2200. auto ReaderOrErr =
  2201. SampleProfileReader::create(Filename, Ctx, RemappingFilename);
  2202. if (std::error_code EC = ReaderOrErr.getError()) {
  2203. std::string Msg = "Could not open profile: " + EC.message();
  2204. Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
  2205. return false;
  2206. }
  2207. Reader = std::move(ReaderOrErr.get());
  2208. Reader->setSkipFlatProf(LTOPhase == ThinOrFullLTOPhase::ThinLTOPostLink);
  2209. Reader->collectFuncsFrom(M);
  2210. if (std::error_code EC = Reader->read()) {
  2211. std::string Msg = "profile reading failed: " + EC.message();
  2212. Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
  2213. return false;
  2214. }
  2215. PSL = Reader->getProfileSymbolList();
  2216. // While profile-sample-accurate is on, ignore symbol list.
  2217. ProfAccForSymsInList =
  2218. ProfileAccurateForSymsInList && PSL && !ProfileSampleAccurate;
  2219. if (ProfAccForSymsInList) {
  2220. NamesInProfile.clear();
  2221. if (auto NameTable = Reader->getNameTable())
  2222. NamesInProfile.insert(NameTable->begin(), NameTable->end());
  2223. }
  2224. if (FAM && !ProfileInlineReplayFile.empty()) {
  2225. ExternalInlineAdvisor = std::make_unique<ReplayInlineAdvisor>(
  2226. M, *FAM, Ctx, /*OriginalAdvisor=*/nullptr, ProfileInlineReplayFile,
  2227. /*EmitRemarks=*/false);
  2228. if (!ExternalInlineAdvisor->areReplayRemarksLoaded())
  2229. ExternalInlineAdvisor.reset();
  2230. }
  2231. // Apply tweaks if context-sensitive profile is available.
  2232. if (Reader->profileIsCS()) {
  2233. ProfileIsCS = true;
  2234. FunctionSamples::ProfileIsCS = true;
  2235. // Enable priority-base inliner and size inline by default for CSSPGO.
  2236. if (!ProfileSizeInline.getNumOccurrences())
  2237. ProfileSizeInline = true;
  2238. if (!CallsitePrioritizedInline.getNumOccurrences())
  2239. CallsitePrioritizedInline = true;
  2240. // Tracker for profiles under different context
  2241. ContextTracker =
  2242. std::make_unique<SampleContextTracker>(Reader->getProfiles());
  2243. }
  2244. // Load pseudo probe descriptors for probe-based function samples.
  2245. if (Reader->profileIsProbeBased()) {
  2246. ProbeManager = std::make_unique<PseudoProbeManager>(M);
  2247. if (!ProbeManager->moduleIsProbed(M)) {
  2248. const char *Msg =
  2249. "Pseudo-probe-based profile requires SampleProfileProbePass";
  2250. Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
  2251. return false;
  2252. }
  2253. }
  2254. return true;
  2255. }
  2256. ModulePass *llvm::createSampleProfileLoaderPass() {
  2257. return new SampleProfileLoaderLegacyPass();
  2258. }
  2259. ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) {
  2260. return new SampleProfileLoaderLegacyPass(Name);
  2261. }
  2262. bool SampleProfileLoader::runOnModule(Module &M, ModuleAnalysisManager *AM,
  2263. ProfileSummaryInfo *_PSI, CallGraph *CG) {
  2264. GUIDToFuncNameMapper Mapper(M, *Reader, GUIDToFuncNameMap);
  2265. PSI = _PSI;
  2266. if (M.getProfileSummary(/* IsCS */ false) == nullptr) {
  2267. M.setProfileSummary(Reader->getSummary().getMD(M.getContext()),
  2268. ProfileSummary::PSK_Sample);
  2269. PSI->refresh();
  2270. }
  2271. // Compute the total number of samples collected in this profile.
  2272. for (const auto &I : Reader->getProfiles())
  2273. TotalCollectedSamples += I.second.getTotalSamples();
  2274. auto Remapper = Reader->getRemapper();
  2275. // Populate the symbol map.
  2276. for (const auto &N_F : M.getValueSymbolTable()) {
  2277. StringRef OrigName = N_F.getKey();
  2278. Function *F = dyn_cast<Function>(N_F.getValue());
  2279. if (F == nullptr)
  2280. continue;
  2281. SymbolMap[OrigName] = F;
  2282. auto pos = OrigName.find('.');
  2283. if (pos != StringRef::npos) {
  2284. StringRef NewName = OrigName.substr(0, pos);
  2285. auto r = SymbolMap.insert(std::make_pair(NewName, F));
  2286. // Failiing to insert means there is already an entry in SymbolMap,
  2287. // thus there are multiple functions that are mapped to the same
  2288. // stripped name. In this case of name conflicting, set the value
  2289. // to nullptr to avoid confusion.
  2290. if (!r.second)
  2291. r.first->second = nullptr;
  2292. OrigName = NewName;
  2293. }
  2294. // Insert the remapped names into SymbolMap.
  2295. if (Remapper) {
  2296. if (auto MapName = Remapper->lookUpNameInProfile(OrigName)) {
  2297. if (*MapName == OrigName)
  2298. continue;
  2299. SymbolMap.insert(std::make_pair(*MapName, F));
  2300. }
  2301. }
  2302. }
  2303. bool retval = false;
  2304. for (auto F : buildFunctionOrder(M, CG)) {
  2305. assert(!F->isDeclaration());
  2306. clearFunctionData();
  2307. retval |= runOnFunction(*F, AM);
  2308. }
  2309. // Account for cold calls not inlined....
  2310. if (!ProfileIsCS)
  2311. for (const std::pair<Function *, NotInlinedProfileInfo> &pair :
  2312. notInlinedCallInfo)
  2313. updateProfileCallee(pair.first, pair.second.entryCount);
  2314. return retval;
  2315. }
  2316. bool SampleProfileLoaderLegacyPass::runOnModule(Module &M) {
  2317. ACT = &getAnalysis<AssumptionCacheTracker>();
  2318. TTIWP = &getAnalysis<TargetTransformInfoWrapperPass>();
  2319. TLIWP = &getAnalysis<TargetLibraryInfoWrapperPass>();
  2320. ProfileSummaryInfo *PSI =
  2321. &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
  2322. return SampleLoader.runOnModule(M, nullptr, PSI, nullptr);
  2323. }
  2324. bool SampleProfileLoader::runOnFunction(Function &F, ModuleAnalysisManager *AM) {
  2325. LLVM_DEBUG(dbgs() << "\n\nProcessing Function " << F.getName() << "\n");
  2326. DILocation2SampleMap.clear();
  2327. // By default the entry count is initialized to -1, which will be treated
  2328. // conservatively by getEntryCount as the same as unknown (None). This is
  2329. // to avoid newly added code to be treated as cold. If we have samples
  2330. // this will be overwritten in emitAnnotations.
  2331. uint64_t initialEntryCount = -1;
  2332. ProfAccForSymsInList = ProfileAccurateForSymsInList && PSL;
  2333. if (ProfileSampleAccurate || F.hasFnAttribute("profile-sample-accurate")) {
  2334. // initialize all the function entry counts to 0. It means all the
  2335. // functions without profile will be regarded as cold.
  2336. initialEntryCount = 0;
  2337. // profile-sample-accurate is a user assertion which has a higher precedence
  2338. // than symbol list. When profile-sample-accurate is on, ignore symbol list.
  2339. ProfAccForSymsInList = false;
  2340. }
  2341. // PSL -- profile symbol list include all the symbols in sampled binary.
  2342. // If ProfileAccurateForSymsInList is enabled, PSL is used to treat
  2343. // old functions without samples being cold, without having to worry
  2344. // about new and hot functions being mistakenly treated as cold.
  2345. if (ProfAccForSymsInList) {
  2346. // Initialize the entry count to 0 for functions in the list.
  2347. if (PSL->contains(F.getName()))
  2348. initialEntryCount = 0;
  2349. // Function in the symbol list but without sample will be regarded as
  2350. // cold. To minimize the potential negative performance impact it could
  2351. // have, we want to be a little conservative here saying if a function
  2352. // shows up in the profile, no matter as outline function, inline instance
  2353. // or call targets, treat the function as not being cold. This will handle
  2354. // the cases such as most callsites of a function are inlined in sampled
  2355. // binary but not inlined in current build (because of source code drift,
  2356. // imprecise debug information, or the callsites are all cold individually
  2357. // but not cold accumulatively...), so the outline function showing up as
  2358. // cold in sampled binary will actually not be cold after current build.
  2359. StringRef CanonName = FunctionSamples::getCanonicalFnName(F);
  2360. if (NamesInProfile.count(CanonName))
  2361. initialEntryCount = -1;
  2362. }
  2363. // Initialize entry count when the function has no existing entry
  2364. // count value.
  2365. if (!F.getEntryCount().hasValue())
  2366. F.setEntryCount(ProfileCount(initialEntryCount, Function::PCT_Real));
  2367. std::unique_ptr<OptimizationRemarkEmitter> OwnedORE;
  2368. if (AM) {
  2369. auto &FAM =
  2370. AM->getResult<FunctionAnalysisManagerModuleProxy>(*F.getParent())
  2371. .getManager();
  2372. ORE = &FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
  2373. } else {
  2374. OwnedORE = std::make_unique<OptimizationRemarkEmitter>(&F);
  2375. ORE = OwnedORE.get();
  2376. }
  2377. if (ProfileIsCS)
  2378. Samples = ContextTracker->getBaseSamplesFor(F);
  2379. else
  2380. Samples = Reader->getSamplesFor(F);
  2381. if (Samples && !Samples->empty())
  2382. return emitAnnotations(F);
  2383. return false;
  2384. }
  2385. PreservedAnalyses SampleProfileLoaderPass::run(Module &M,
  2386. ModuleAnalysisManager &AM) {
  2387. FunctionAnalysisManager &FAM =
  2388. AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
  2389. auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & {
  2390. return FAM.getResult<AssumptionAnalysis>(F);
  2391. };
  2392. auto GetTTI = [&](Function &F) -> TargetTransformInfo & {
  2393. return FAM.getResult<TargetIRAnalysis>(F);
  2394. };
  2395. auto GetTLI = [&](Function &F) -> const TargetLibraryInfo & {
  2396. return FAM.getResult<TargetLibraryAnalysis>(F);
  2397. };
  2398. SampleProfileLoader SampleLoader(
  2399. ProfileFileName.empty() ? SampleProfileFile : ProfileFileName,
  2400. ProfileRemappingFileName.empty() ? SampleProfileRemappingFile
  2401. : ProfileRemappingFileName,
  2402. LTOPhase, GetAssumptionCache, GetTTI, GetTLI);
  2403. if (!SampleLoader.doInitialization(M, &FAM))
  2404. return PreservedAnalyses::all();
  2405. ProfileSummaryInfo *PSI = &AM.getResult<ProfileSummaryAnalysis>(M);
  2406. CallGraph &CG = AM.getResult<CallGraphAnalysis>(M);
  2407. if (!SampleLoader.runOnModule(M, &AM, PSI, &CG))
  2408. return PreservedAnalyses::all();
  2409. return PreservedAnalyses::none();
  2410. }