PGOInstrumentation.cpp 90 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413
  1. //===- PGOInstrumentation.cpp - MST-based PGO Instrumentation -------------===//
  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 PGO instrumentation using a minimum spanning tree based
  10. // on the following paper:
  11. // [1] Donald E. Knuth, Francis R. Stevenson. Optimal measurement of points
  12. // for program frequency counts. BIT Numerical Mathematics 1973, Volume 13,
  13. // Issue 3, pp 313-322
  14. // The idea of the algorithm based on the fact that for each node (except for
  15. // the entry and exit), the sum of incoming edge counts equals the sum of
  16. // outgoing edge counts. The count of edge on spanning tree can be derived from
  17. // those edges not on the spanning tree. Knuth proves this method instruments
  18. // the minimum number of edges.
  19. //
  20. // The minimal spanning tree here is actually a maximum weight tree -- on-tree
  21. // edges have higher frequencies (more likely to execute). The idea is to
  22. // instrument those less frequently executed edges to reduce the runtime
  23. // overhead of instrumented binaries.
  24. //
  25. // This file contains two passes:
  26. // (1) Pass PGOInstrumentationGen which instruments the IR to generate edge
  27. // count profile, and generates the instrumentation for indirect call
  28. // profiling.
  29. // (2) Pass PGOInstrumentationUse which reads the edge count profile and
  30. // annotates the branch weights. It also reads the indirect call value
  31. // profiling records and annotate the indirect call instructions.
  32. //
  33. // To get the precise counter information, These two passes need to invoke at
  34. // the same compilation point (so they see the same IR). For pass
  35. // PGOInstrumentationGen, the real work is done in instrumentOneFunc(). For
  36. // pass PGOInstrumentationUse, the real work in done in class PGOUseFunc and
  37. // the profile is opened in module level and passed to each PGOUseFunc instance.
  38. // The shared code for PGOInstrumentationGen and PGOInstrumentationUse is put
  39. // in class FuncPGOInstrumentation.
  40. //
  41. // Class PGOEdge represents a CFG edge and some auxiliary information. Class
  42. // BBInfo contains auxiliary information for each BB. These two classes are used
  43. // in pass PGOInstrumentationGen. Class PGOUseEdge and UseBBInfo are the derived
  44. // class of PGOEdge and BBInfo, respectively. They contains extra data structure
  45. // used in populating profile counters.
  46. // The MST implementation is in Class CFGMST (CFGMST.h).
  47. //
  48. //===----------------------------------------------------------------------===//
  49. #include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
  50. #include "CFGMST.h"
  51. #include "ValueProfileCollector.h"
  52. #include "llvm/ADT/APInt.h"
  53. #include "llvm/ADT/ArrayRef.h"
  54. #include "llvm/ADT/STLExtras.h"
  55. #include "llvm/ADT/SmallVector.h"
  56. #include "llvm/ADT/Statistic.h"
  57. #include "llvm/ADT/StringRef.h"
  58. #include "llvm/ADT/Triple.h"
  59. #include "llvm/ADT/Twine.h"
  60. #include "llvm/ADT/iterator.h"
  61. #include "llvm/ADT/iterator_range.h"
  62. #include "llvm/Analysis/BlockFrequencyInfo.h"
  63. #include "llvm/Analysis/BranchProbabilityInfo.h"
  64. #include "llvm/Analysis/CFG.h"
  65. #include "llvm/Analysis/EHPersonalities.h"
  66. #include "llvm/Analysis/LoopInfo.h"
  67. #include "llvm/Analysis/MemoryBuiltins.h"
  68. #include "llvm/Analysis/MemoryProfileInfo.h"
  69. #include "llvm/Analysis/OptimizationRemarkEmitter.h"
  70. #include "llvm/Analysis/ProfileSummaryInfo.h"
  71. #include "llvm/Analysis/TargetLibraryInfo.h"
  72. #include "llvm/IR/Attributes.h"
  73. #include "llvm/IR/BasicBlock.h"
  74. #include "llvm/IR/CFG.h"
  75. #include "llvm/IR/Comdat.h"
  76. #include "llvm/IR/Constant.h"
  77. #include "llvm/IR/Constants.h"
  78. #include "llvm/IR/DiagnosticInfo.h"
  79. #include "llvm/IR/Dominators.h"
  80. #include "llvm/IR/Function.h"
  81. #include "llvm/IR/GlobalAlias.h"
  82. #include "llvm/IR/GlobalValue.h"
  83. #include "llvm/IR/GlobalVariable.h"
  84. #include "llvm/IR/IRBuilder.h"
  85. #include "llvm/IR/InstVisitor.h"
  86. #include "llvm/IR/InstrTypes.h"
  87. #include "llvm/IR/Instruction.h"
  88. #include "llvm/IR/Instructions.h"
  89. #include "llvm/IR/IntrinsicInst.h"
  90. #include "llvm/IR/Intrinsics.h"
  91. #include "llvm/IR/LLVMContext.h"
  92. #include "llvm/IR/MDBuilder.h"
  93. #include "llvm/IR/Module.h"
  94. #include "llvm/IR/PassManager.h"
  95. #include "llvm/IR/ProfDataUtils.h"
  96. #include "llvm/IR/ProfileSummary.h"
  97. #include "llvm/IR/Type.h"
  98. #include "llvm/IR/Value.h"
  99. #include "llvm/ProfileData/InstrProf.h"
  100. #include "llvm/ProfileData/InstrProfReader.h"
  101. #include "llvm/Support/BLAKE3.h"
  102. #include "llvm/Support/BranchProbability.h"
  103. #include "llvm/Support/CRC.h"
  104. #include "llvm/Support/Casting.h"
  105. #include "llvm/Support/CommandLine.h"
  106. #include "llvm/Support/DOTGraphTraits.h"
  107. #include "llvm/Support/Debug.h"
  108. #include "llvm/Support/Error.h"
  109. #include "llvm/Support/ErrorHandling.h"
  110. #include "llvm/Support/GraphWriter.h"
  111. #include "llvm/Support/HashBuilder.h"
  112. #include "llvm/Support/raw_ostream.h"
  113. #include "llvm/Transforms/Instrumentation.h"
  114. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  115. #include "llvm/Transforms/Utils/MisExpect.h"
  116. #include "llvm/Transforms/Utils/ModuleUtils.h"
  117. #include <algorithm>
  118. #include <cassert>
  119. #include <cstdint>
  120. #include <map>
  121. #include <memory>
  122. #include <numeric>
  123. #include <optional>
  124. #include <set>
  125. #include <string>
  126. #include <unordered_map>
  127. #include <utility>
  128. #include <vector>
  129. using namespace llvm;
  130. using namespace llvm::memprof;
  131. using ProfileCount = Function::ProfileCount;
  132. using VPCandidateInfo = ValueProfileCollector::CandidateInfo;
  133. #define DEBUG_TYPE "pgo-instrumentation"
  134. STATISTIC(NumOfPGOInstrument, "Number of edges instrumented.");
  135. STATISTIC(NumOfPGOSelectInsts, "Number of select instruction instrumented.");
  136. STATISTIC(NumOfPGOMemIntrinsics, "Number of mem intrinsics instrumented.");
  137. STATISTIC(NumOfPGOEdge, "Number of edges.");
  138. STATISTIC(NumOfPGOBB, "Number of basic-blocks.");
  139. STATISTIC(NumOfPGOSplit, "Number of critical edge splits.");
  140. STATISTIC(NumOfPGOFunc, "Number of functions having valid profile counts.");
  141. STATISTIC(NumOfPGOMismatch, "Number of functions having mismatch profile.");
  142. STATISTIC(NumOfPGOMissing, "Number of functions without profile.");
  143. STATISTIC(NumOfMemProfMissing, "Number of functions without memory profile.");
  144. STATISTIC(NumOfPGOICall, "Number of indirect call value instrumentations.");
  145. STATISTIC(NumOfCSPGOInstrument, "Number of edges instrumented in CSPGO.");
  146. STATISTIC(NumOfCSPGOSelectInsts,
  147. "Number of select instruction instrumented in CSPGO.");
  148. STATISTIC(NumOfCSPGOMemIntrinsics,
  149. "Number of mem intrinsics instrumented in CSPGO.");
  150. STATISTIC(NumOfCSPGOEdge, "Number of edges in CSPGO.");
  151. STATISTIC(NumOfCSPGOBB, "Number of basic-blocks in CSPGO.");
  152. STATISTIC(NumOfCSPGOSplit, "Number of critical edge splits in CSPGO.");
  153. STATISTIC(NumOfCSPGOFunc,
  154. "Number of functions having valid profile counts in CSPGO.");
  155. STATISTIC(NumOfCSPGOMismatch,
  156. "Number of functions having mismatch profile in CSPGO.");
  157. STATISTIC(NumOfCSPGOMissing, "Number of functions without profile in CSPGO.");
  158. // Command line option to specify the file to read profile from. This is
  159. // mainly used for testing.
  160. static cl::opt<std::string>
  161. PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden,
  162. cl::value_desc("filename"),
  163. cl::desc("Specify the path of profile data file. This is"
  164. "mainly for test purpose."));
  165. static cl::opt<std::string> PGOTestProfileRemappingFile(
  166. "pgo-test-profile-remapping-file", cl::init(""), cl::Hidden,
  167. cl::value_desc("filename"),
  168. cl::desc("Specify the path of profile remapping file. This is mainly for "
  169. "test purpose."));
  170. // Command line option to disable value profiling. The default is false:
  171. // i.e. value profiling is enabled by default. This is for debug purpose.
  172. static cl::opt<bool> DisableValueProfiling("disable-vp", cl::init(false),
  173. cl::Hidden,
  174. cl::desc("Disable Value Profiling"));
  175. // Command line option to set the maximum number of VP annotations to write to
  176. // the metadata for a single indirect call callsite.
  177. static cl::opt<unsigned> MaxNumAnnotations(
  178. "icp-max-annotations", cl::init(3), cl::Hidden,
  179. cl::desc("Max number of annotations for a single indirect "
  180. "call callsite"));
  181. // Command line option to set the maximum number of value annotations
  182. // to write to the metadata for a single memop intrinsic.
  183. static cl::opt<unsigned> MaxNumMemOPAnnotations(
  184. "memop-max-annotations", cl::init(4), cl::Hidden,
  185. cl::desc("Max number of preicise value annotations for a single memop"
  186. "intrinsic"));
  187. // Command line option to control appending FunctionHash to the name of a COMDAT
  188. // function. This is to avoid the hash mismatch caused by the preinliner.
  189. static cl::opt<bool> DoComdatRenaming(
  190. "do-comdat-renaming", cl::init(false), cl::Hidden,
  191. cl::desc("Append function hash to the name of COMDAT function to avoid "
  192. "function hash mismatch due to the preinliner"));
  193. // Command line option to enable/disable the warning about missing profile
  194. // information.
  195. static cl::opt<bool>
  196. PGOWarnMissing("pgo-warn-missing-function", cl::init(false), cl::Hidden,
  197. cl::desc("Use this option to turn on/off "
  198. "warnings about missing profile data for "
  199. "functions."));
  200. namespace llvm {
  201. // Command line option to enable/disable the warning about a hash mismatch in
  202. // the profile data.
  203. cl::opt<bool>
  204. NoPGOWarnMismatch("no-pgo-warn-mismatch", cl::init(false), cl::Hidden,
  205. cl::desc("Use this option to turn off/on "
  206. "warnings about profile cfg mismatch."));
  207. } // namespace llvm
  208. // Command line option to enable/disable the warning about a hash mismatch in
  209. // the profile data for Comdat functions, which often turns out to be false
  210. // positive due to the pre-instrumentation inline.
  211. static cl::opt<bool> NoPGOWarnMismatchComdatWeak(
  212. "no-pgo-warn-mismatch-comdat-weak", cl::init(true), cl::Hidden,
  213. cl::desc("The option is used to turn on/off "
  214. "warnings about hash mismatch for comdat "
  215. "or weak functions."));
  216. // Command line option to enable/disable select instruction instrumentation.
  217. static cl::opt<bool>
  218. PGOInstrSelect("pgo-instr-select", cl::init(true), cl::Hidden,
  219. cl::desc("Use this option to turn on/off SELECT "
  220. "instruction instrumentation. "));
  221. // Command line option to turn on CFG dot or text dump of raw profile counts
  222. static cl::opt<PGOViewCountsType> PGOViewRawCounts(
  223. "pgo-view-raw-counts", cl::Hidden,
  224. cl::desc("A boolean option to show CFG dag or text "
  225. "with raw profile counts from "
  226. "profile data. See also option "
  227. "-pgo-view-counts. To limit graph "
  228. "display to only one function, use "
  229. "filtering option -view-bfi-func-name."),
  230. cl::values(clEnumValN(PGOVCT_None, "none", "do not show."),
  231. clEnumValN(PGOVCT_Graph, "graph", "show a graph."),
  232. clEnumValN(PGOVCT_Text, "text", "show in text.")));
  233. // Command line option to enable/disable memop intrinsic call.size profiling.
  234. static cl::opt<bool>
  235. PGOInstrMemOP("pgo-instr-memop", cl::init(true), cl::Hidden,
  236. cl::desc("Use this option to turn on/off "
  237. "memory intrinsic size profiling."));
  238. // Emit branch probability as optimization remarks.
  239. static cl::opt<bool>
  240. EmitBranchProbability("pgo-emit-branch-prob", cl::init(false), cl::Hidden,
  241. cl::desc("When this option is on, the annotated "
  242. "branch probability will be emitted as "
  243. "optimization remarks: -{Rpass|"
  244. "pass-remarks}=pgo-instrumentation"));
  245. static cl::opt<bool> PGOInstrumentEntry(
  246. "pgo-instrument-entry", cl::init(false), cl::Hidden,
  247. cl::desc("Force to instrument function entry basicblock."));
  248. static cl::opt<bool> PGOFunctionEntryCoverage(
  249. "pgo-function-entry-coverage", cl::Hidden,
  250. cl::desc(
  251. "Use this option to enable function entry coverage instrumentation."));
  252. static cl::opt<bool>
  253. PGOFixEntryCount("pgo-fix-entry-count", cl::init(true), cl::Hidden,
  254. cl::desc("Fix function entry count in profile use."));
  255. static cl::opt<bool> PGOVerifyHotBFI(
  256. "pgo-verify-hot-bfi", cl::init(false), cl::Hidden,
  257. cl::desc("Print out the non-match BFI count if a hot raw profile count "
  258. "becomes non-hot, or a cold raw profile count becomes hot. "
  259. "The print is enabled under -Rpass-analysis=pgo, or "
  260. "internal option -pass-remakrs-analysis=pgo."));
  261. static cl::opt<bool> PGOVerifyBFI(
  262. "pgo-verify-bfi", cl::init(false), cl::Hidden,
  263. cl::desc("Print out mismatched BFI counts after setting profile metadata "
  264. "The print is enabled under -Rpass-analysis=pgo, or "
  265. "internal option -pass-remakrs-analysis=pgo."));
  266. static cl::opt<unsigned> PGOVerifyBFIRatio(
  267. "pgo-verify-bfi-ratio", cl::init(2), cl::Hidden,
  268. cl::desc("Set the threshold for pgo-verify-bfi: only print out "
  269. "mismatched BFI if the difference percentage is greater than "
  270. "this value (in percentage)."));
  271. static cl::opt<unsigned> PGOVerifyBFICutoff(
  272. "pgo-verify-bfi-cutoff", cl::init(5), cl::Hidden,
  273. cl::desc("Set the threshold for pgo-verify-bfi: skip the counts whose "
  274. "profile count value is below."));
  275. static cl::opt<std::string> PGOTraceFuncHash(
  276. "pgo-trace-func-hash", cl::init("-"), cl::Hidden,
  277. cl::value_desc("function name"),
  278. cl::desc("Trace the hash of the function with this name."));
  279. static cl::opt<unsigned> PGOFunctionSizeThreshold(
  280. "pgo-function-size-threshold", cl::Hidden,
  281. cl::desc("Do not instrument functions smaller than this threshold."));
  282. static cl::opt<bool> MatchMemProf(
  283. "pgo-match-memprof", cl::init(true), cl::Hidden,
  284. cl::desc("Perform matching and annotation of memprof profiles."));
  285. static cl::opt<unsigned> PGOFunctionCriticalEdgeThreshold(
  286. "pgo-critical-edge-threshold", cl::init(20000), cl::Hidden,
  287. cl::desc("Do not instrument functions with the number of critical edges "
  288. " greater than this threshold."));
  289. namespace llvm {
  290. // Command line option to turn on CFG dot dump after profile annotation.
  291. // Defined in Analysis/BlockFrequencyInfo.cpp: -pgo-view-counts
  292. extern cl::opt<PGOViewCountsType> PGOViewCounts;
  293. // Command line option to specify the name of the function for CFG dump
  294. // Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name=
  295. extern cl::opt<std::string> ViewBlockFreqFuncName;
  296. extern cl::opt<bool> DebugInfoCorrelate;
  297. } // namespace llvm
  298. static cl::opt<bool>
  299. PGOOldCFGHashing("pgo-instr-old-cfg-hashing", cl::init(false), cl::Hidden,
  300. cl::desc("Use the old CFG function hashing"));
  301. // Return a string describing the branch condition that can be
  302. // used in static branch probability heuristics:
  303. static std::string getBranchCondString(Instruction *TI) {
  304. BranchInst *BI = dyn_cast<BranchInst>(TI);
  305. if (!BI || !BI->isConditional())
  306. return std::string();
  307. Value *Cond = BI->getCondition();
  308. ICmpInst *CI = dyn_cast<ICmpInst>(Cond);
  309. if (!CI)
  310. return std::string();
  311. std::string result;
  312. raw_string_ostream OS(result);
  313. OS << CmpInst::getPredicateName(CI->getPredicate()) << "_";
  314. CI->getOperand(0)->getType()->print(OS, true);
  315. Value *RHS = CI->getOperand(1);
  316. ConstantInt *CV = dyn_cast<ConstantInt>(RHS);
  317. if (CV) {
  318. if (CV->isZero())
  319. OS << "_Zero";
  320. else if (CV->isOne())
  321. OS << "_One";
  322. else if (CV->isMinusOne())
  323. OS << "_MinusOne";
  324. else
  325. OS << "_Const";
  326. }
  327. OS.flush();
  328. return result;
  329. }
  330. static const char *ValueProfKindDescr[] = {
  331. #define VALUE_PROF_KIND(Enumerator, Value, Descr) Descr,
  332. #include "llvm/ProfileData/InstrProfData.inc"
  333. };
  334. // Create a COMDAT variable INSTR_PROF_RAW_VERSION_VAR to make the runtime
  335. // aware this is an ir_level profile so it can set the version flag.
  336. static GlobalVariable *createIRLevelProfileFlagVar(Module &M, bool IsCS) {
  337. const StringRef VarName(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR));
  338. Type *IntTy64 = Type::getInt64Ty(M.getContext());
  339. uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF);
  340. if (IsCS)
  341. ProfileVersion |= VARIANT_MASK_CSIR_PROF;
  342. if (PGOInstrumentEntry)
  343. ProfileVersion |= VARIANT_MASK_INSTR_ENTRY;
  344. if (DebugInfoCorrelate)
  345. ProfileVersion |= VARIANT_MASK_DBG_CORRELATE;
  346. if (PGOFunctionEntryCoverage)
  347. ProfileVersion |=
  348. VARIANT_MASK_BYTE_COVERAGE | VARIANT_MASK_FUNCTION_ENTRY_ONLY;
  349. auto IRLevelVersionVariable = new GlobalVariable(
  350. M, IntTy64, true, GlobalValue::WeakAnyLinkage,
  351. Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)), VarName);
  352. IRLevelVersionVariable->setVisibility(GlobalValue::HiddenVisibility);
  353. Triple TT(M.getTargetTriple());
  354. if (TT.supportsCOMDAT()) {
  355. IRLevelVersionVariable->setLinkage(GlobalValue::ExternalLinkage);
  356. IRLevelVersionVariable->setComdat(M.getOrInsertComdat(VarName));
  357. }
  358. return IRLevelVersionVariable;
  359. }
  360. namespace {
  361. /// The select instruction visitor plays three roles specified
  362. /// by the mode. In \c VM_counting mode, it simply counts the number of
  363. /// select instructions. In \c VM_instrument mode, it inserts code to count
  364. /// the number times TrueValue of select is taken. In \c VM_annotate mode,
  365. /// it reads the profile data and annotate the select instruction with metadata.
  366. enum VisitMode { VM_counting, VM_instrument, VM_annotate };
  367. class PGOUseFunc;
  368. /// Instruction Visitor class to visit select instructions.
  369. struct SelectInstVisitor : public InstVisitor<SelectInstVisitor> {
  370. Function &F;
  371. unsigned NSIs = 0; // Number of select instructions instrumented.
  372. VisitMode Mode = VM_counting; // Visiting mode.
  373. unsigned *CurCtrIdx = nullptr; // Pointer to current counter index.
  374. unsigned TotalNumCtrs = 0; // Total number of counters
  375. GlobalVariable *FuncNameVar = nullptr;
  376. uint64_t FuncHash = 0;
  377. PGOUseFunc *UseFunc = nullptr;
  378. SelectInstVisitor(Function &Func) : F(Func) {}
  379. void countSelects(Function &Func) {
  380. NSIs = 0;
  381. Mode = VM_counting;
  382. visit(Func);
  383. }
  384. // Visit the IR stream and instrument all select instructions. \p
  385. // Ind is a pointer to the counter index variable; \p TotalNC
  386. // is the total number of counters; \p FNV is the pointer to the
  387. // PGO function name var; \p FHash is the function hash.
  388. void instrumentSelects(Function &Func, unsigned *Ind, unsigned TotalNC,
  389. GlobalVariable *FNV, uint64_t FHash) {
  390. Mode = VM_instrument;
  391. CurCtrIdx = Ind;
  392. TotalNumCtrs = TotalNC;
  393. FuncHash = FHash;
  394. FuncNameVar = FNV;
  395. visit(Func);
  396. }
  397. // Visit the IR stream and annotate all select instructions.
  398. void annotateSelects(Function &Func, PGOUseFunc *UF, unsigned *Ind) {
  399. Mode = VM_annotate;
  400. UseFunc = UF;
  401. CurCtrIdx = Ind;
  402. visit(Func);
  403. }
  404. void instrumentOneSelectInst(SelectInst &SI);
  405. void annotateOneSelectInst(SelectInst &SI);
  406. // Visit \p SI instruction and perform tasks according to visit mode.
  407. void visitSelectInst(SelectInst &SI);
  408. // Return the number of select instructions. This needs be called after
  409. // countSelects().
  410. unsigned getNumOfSelectInsts() const { return NSIs; }
  411. };
  412. } // end anonymous namespace
  413. namespace {
  414. /// An MST based instrumentation for PGO
  415. ///
  416. /// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO
  417. /// in the function level.
  418. struct PGOEdge {
  419. // This class implements the CFG edges. Note the CFG can be a multi-graph.
  420. // So there might be multiple edges with same SrcBB and DestBB.
  421. const BasicBlock *SrcBB;
  422. const BasicBlock *DestBB;
  423. uint64_t Weight;
  424. bool InMST = false;
  425. bool Removed = false;
  426. bool IsCritical = false;
  427. PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, uint64_t W = 1)
  428. : SrcBB(Src), DestBB(Dest), Weight(W) {}
  429. // Return the information string of an edge.
  430. std::string infoString() const {
  431. return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") +
  432. (IsCritical ? "c" : " ") + " W=" + Twine(Weight)).str();
  433. }
  434. };
  435. // This class stores the auxiliary information for each BB.
  436. struct BBInfo {
  437. BBInfo *Group;
  438. uint32_t Index;
  439. uint32_t Rank = 0;
  440. BBInfo(unsigned IX) : Group(this), Index(IX) {}
  441. // Return the information string of this object.
  442. std::string infoString() const {
  443. return (Twine("Index=") + Twine(Index)).str();
  444. }
  445. // Empty function -- only applicable to UseBBInfo.
  446. void addOutEdge(PGOEdge *E LLVM_ATTRIBUTE_UNUSED) {}
  447. // Empty function -- only applicable to UseBBInfo.
  448. void addInEdge(PGOEdge *E LLVM_ATTRIBUTE_UNUSED) {}
  449. };
  450. // This class implements the CFG edges. Note the CFG can be a multi-graph.
  451. template <class Edge, class BBInfo> class FuncPGOInstrumentation {
  452. private:
  453. Function &F;
  454. // Is this is context-sensitive instrumentation.
  455. bool IsCS;
  456. // A map that stores the Comdat group in function F.
  457. std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers;
  458. ValueProfileCollector VPC;
  459. void computeCFGHash();
  460. void renameComdatFunction();
  461. public:
  462. const TargetLibraryInfo &TLI;
  463. std::vector<std::vector<VPCandidateInfo>> ValueSites;
  464. SelectInstVisitor SIVisitor;
  465. std::string FuncName;
  466. GlobalVariable *FuncNameVar;
  467. // CFG hash value for this function.
  468. uint64_t FunctionHash = 0;
  469. // The Minimum Spanning Tree of function CFG.
  470. CFGMST<Edge, BBInfo> MST;
  471. // Collect all the BBs that will be instrumented, and store them in
  472. // InstrumentBBs.
  473. void getInstrumentBBs(std::vector<BasicBlock *> &InstrumentBBs);
  474. // Give an edge, find the BB that will be instrumented.
  475. // Return nullptr if there is no BB to be instrumented.
  476. BasicBlock *getInstrBB(Edge *E);
  477. // Return the auxiliary BB information.
  478. BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); }
  479. // Return the auxiliary BB information if available.
  480. BBInfo *findBBInfo(const BasicBlock *BB) const { return MST.findBBInfo(BB); }
  481. // Dump edges and BB information.
  482. void dumpInfo(std::string Str = "") const {
  483. MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName + " Hash: " +
  484. Twine(FunctionHash) + "\t" + Str);
  485. }
  486. FuncPGOInstrumentation(
  487. Function &Func, TargetLibraryInfo &TLI,
  488. std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
  489. bool CreateGlobalVar = false, BranchProbabilityInfo *BPI = nullptr,
  490. BlockFrequencyInfo *BFI = nullptr, bool IsCS = false,
  491. bool InstrumentFuncEntry = true)
  492. : F(Func), IsCS(IsCS), ComdatMembers(ComdatMembers), VPC(Func, TLI),
  493. TLI(TLI), ValueSites(IPVK_Last + 1), SIVisitor(Func),
  494. MST(F, InstrumentFuncEntry, BPI, BFI) {
  495. // This should be done before CFG hash computation.
  496. SIVisitor.countSelects(Func);
  497. ValueSites[IPVK_MemOPSize] = VPC.get(IPVK_MemOPSize);
  498. if (!IsCS) {
  499. NumOfPGOSelectInsts += SIVisitor.getNumOfSelectInsts();
  500. NumOfPGOMemIntrinsics += ValueSites[IPVK_MemOPSize].size();
  501. NumOfPGOBB += MST.BBInfos.size();
  502. ValueSites[IPVK_IndirectCallTarget] = VPC.get(IPVK_IndirectCallTarget);
  503. } else {
  504. NumOfCSPGOSelectInsts += SIVisitor.getNumOfSelectInsts();
  505. NumOfCSPGOMemIntrinsics += ValueSites[IPVK_MemOPSize].size();
  506. NumOfCSPGOBB += MST.BBInfos.size();
  507. }
  508. FuncName = getPGOFuncName(F);
  509. computeCFGHash();
  510. if (!ComdatMembers.empty())
  511. renameComdatFunction();
  512. LLVM_DEBUG(dumpInfo("after CFGMST"));
  513. for (auto &E : MST.AllEdges) {
  514. if (E->Removed)
  515. continue;
  516. IsCS ? NumOfCSPGOEdge++ : NumOfPGOEdge++;
  517. if (!E->InMST)
  518. IsCS ? NumOfCSPGOInstrument++ : NumOfPGOInstrument++;
  519. }
  520. if (CreateGlobalVar)
  521. FuncNameVar = createPGOFuncNameVar(F, FuncName);
  522. }
  523. };
  524. } // end anonymous namespace
  525. // Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
  526. // value of each BB in the CFG. The higher 32 bits are the CRC32 of the numbers
  527. // of selects, indirect calls, mem ops and edges.
  528. template <class Edge, class BBInfo>
  529. void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() {
  530. std::vector<uint8_t> Indexes;
  531. JamCRC JC;
  532. for (auto &BB : F) {
  533. const Instruction *TI = BB.getTerminator();
  534. for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
  535. BasicBlock *Succ = TI->getSuccessor(I);
  536. auto BI = findBBInfo(Succ);
  537. if (BI == nullptr)
  538. continue;
  539. uint32_t Index = BI->Index;
  540. for (int J = 0; J < 4; J++)
  541. Indexes.push_back((uint8_t)(Index >> (J * 8)));
  542. }
  543. }
  544. JC.update(Indexes);
  545. JamCRC JCH;
  546. if (PGOOldCFGHashing) {
  547. // Hash format for context sensitive profile. Reserve 4 bits for other
  548. // information.
  549. FunctionHash = (uint64_t)SIVisitor.getNumOfSelectInsts() << 56 |
  550. (uint64_t)ValueSites[IPVK_IndirectCallTarget].size() << 48 |
  551. //(uint64_t)ValueSites[IPVK_MemOPSize].size() << 40 |
  552. (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC();
  553. } else {
  554. // The higher 32 bits.
  555. auto updateJCH = [&JCH](uint64_t Num) {
  556. uint8_t Data[8];
  557. support::endian::write64le(Data, Num);
  558. JCH.update(Data);
  559. };
  560. updateJCH((uint64_t)SIVisitor.getNumOfSelectInsts());
  561. updateJCH((uint64_t)ValueSites[IPVK_IndirectCallTarget].size());
  562. updateJCH((uint64_t)ValueSites[IPVK_MemOPSize].size());
  563. updateJCH((uint64_t)MST.AllEdges.size());
  564. // Hash format for context sensitive profile. Reserve 4 bits for other
  565. // information.
  566. FunctionHash = (((uint64_t)JCH.getCRC()) << 28) + JC.getCRC();
  567. }
  568. // Reserve bit 60-63 for other information purpose.
  569. FunctionHash &= 0x0FFFFFFFFFFFFFFF;
  570. if (IsCS)
  571. NamedInstrProfRecord::setCSFlagInHash(FunctionHash);
  572. LLVM_DEBUG(dbgs() << "Function Hash Computation for " << F.getName() << ":\n"
  573. << " CRC = " << JC.getCRC()
  574. << ", Selects = " << SIVisitor.getNumOfSelectInsts()
  575. << ", Edges = " << MST.AllEdges.size() << ", ICSites = "
  576. << ValueSites[IPVK_IndirectCallTarget].size());
  577. if (!PGOOldCFGHashing) {
  578. LLVM_DEBUG(dbgs() << ", Memops = " << ValueSites[IPVK_MemOPSize].size()
  579. << ", High32 CRC = " << JCH.getCRC());
  580. }
  581. LLVM_DEBUG(dbgs() << ", Hash = " << FunctionHash << "\n";);
  582. if (PGOTraceFuncHash != "-" && F.getName().contains(PGOTraceFuncHash))
  583. dbgs() << "Funcname=" << F.getName() << ", Hash=" << FunctionHash
  584. << " in building " << F.getParent()->getSourceFileName() << "\n";
  585. }
  586. // Check if we can safely rename this Comdat function.
  587. static bool canRenameComdat(
  588. Function &F,
  589. std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
  590. if (!DoComdatRenaming || !canRenameComdatFunc(F, true))
  591. return false;
  592. // FIXME: Current only handle those Comdat groups that only containing one
  593. // function.
  594. // (1) For a Comdat group containing multiple functions, we need to have a
  595. // unique postfix based on the hashes for each function. There is a
  596. // non-trivial code refactoring to do this efficiently.
  597. // (2) Variables can not be renamed, so we can not rename Comdat function in a
  598. // group including global vars.
  599. Comdat *C = F.getComdat();
  600. for (auto &&CM : make_range(ComdatMembers.equal_range(C))) {
  601. assert(!isa<GlobalAlias>(CM.second));
  602. Function *FM = dyn_cast<Function>(CM.second);
  603. if (FM != &F)
  604. return false;
  605. }
  606. return true;
  607. }
  608. // Append the CFGHash to the Comdat function name.
  609. template <class Edge, class BBInfo>
  610. void FuncPGOInstrumentation<Edge, BBInfo>::renameComdatFunction() {
  611. if (!canRenameComdat(F, ComdatMembers))
  612. return;
  613. std::string OrigName = F.getName().str();
  614. std::string NewFuncName =
  615. Twine(F.getName() + "." + Twine(FunctionHash)).str();
  616. F.setName(Twine(NewFuncName));
  617. GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigName, &F);
  618. FuncName = Twine(FuncName + "." + Twine(FunctionHash)).str();
  619. Comdat *NewComdat;
  620. Module *M = F.getParent();
  621. // For AvailableExternallyLinkage functions, change the linkage to
  622. // LinkOnceODR and put them into comdat. This is because after renaming, there
  623. // is no backup external copy available for the function.
  624. if (!F.hasComdat()) {
  625. assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage);
  626. NewComdat = M->getOrInsertComdat(StringRef(NewFuncName));
  627. F.setLinkage(GlobalValue::LinkOnceODRLinkage);
  628. F.setComdat(NewComdat);
  629. return;
  630. }
  631. // This function belongs to a single function Comdat group.
  632. Comdat *OrigComdat = F.getComdat();
  633. std::string NewComdatName =
  634. Twine(OrigComdat->getName() + "." + Twine(FunctionHash)).str();
  635. NewComdat = M->getOrInsertComdat(StringRef(NewComdatName));
  636. NewComdat->setSelectionKind(OrigComdat->getSelectionKind());
  637. for (auto &&CM : make_range(ComdatMembers.equal_range(OrigComdat))) {
  638. // Must be a function.
  639. cast<Function>(CM.second)->setComdat(NewComdat);
  640. }
  641. }
  642. // Collect all the BBs that will be instruments and return them in
  643. // InstrumentBBs and setup InEdges/OutEdge for UseBBInfo.
  644. template <class Edge, class BBInfo>
  645. void FuncPGOInstrumentation<Edge, BBInfo>::getInstrumentBBs(
  646. std::vector<BasicBlock *> &InstrumentBBs) {
  647. // Use a worklist as we will update the vector during the iteration.
  648. std::vector<Edge *> EdgeList;
  649. EdgeList.reserve(MST.AllEdges.size());
  650. for (auto &E : MST.AllEdges)
  651. EdgeList.push_back(E.get());
  652. for (auto &E : EdgeList) {
  653. BasicBlock *InstrBB = getInstrBB(E);
  654. if (InstrBB)
  655. InstrumentBBs.push_back(InstrBB);
  656. }
  657. // Set up InEdges/OutEdges for all BBs.
  658. for (auto &E : MST.AllEdges) {
  659. if (E->Removed)
  660. continue;
  661. const BasicBlock *SrcBB = E->SrcBB;
  662. const BasicBlock *DestBB = E->DestBB;
  663. BBInfo &SrcInfo = getBBInfo(SrcBB);
  664. BBInfo &DestInfo = getBBInfo(DestBB);
  665. SrcInfo.addOutEdge(E.get());
  666. DestInfo.addInEdge(E.get());
  667. }
  668. }
  669. // Given a CFG E to be instrumented, find which BB to place the instrumented
  670. // code. The function will split the critical edge if necessary.
  671. template <class Edge, class BBInfo>
  672. BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) {
  673. if (E->InMST || E->Removed)
  674. return nullptr;
  675. BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);
  676. BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);
  677. // For a fake edge, instrument the real BB.
  678. if (SrcBB == nullptr)
  679. return DestBB;
  680. if (DestBB == nullptr)
  681. return SrcBB;
  682. auto canInstrument = [](BasicBlock *BB) -> BasicBlock * {
  683. // There are basic blocks (such as catchswitch) cannot be instrumented.
  684. // If the returned first insertion point is the end of BB, skip this BB.
  685. if (BB->getFirstInsertionPt() == BB->end())
  686. return nullptr;
  687. return BB;
  688. };
  689. // Instrument the SrcBB if it has a single successor,
  690. // otherwise, the DestBB if this is not a critical edge.
  691. Instruction *TI = SrcBB->getTerminator();
  692. if (TI->getNumSuccessors() <= 1)
  693. return canInstrument(SrcBB);
  694. if (!E->IsCritical)
  695. return canInstrument(DestBB);
  696. // Some IndirectBr critical edges cannot be split by the previous
  697. // SplitIndirectBrCriticalEdges call. Bail out.
  698. unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
  699. BasicBlock *InstrBB =
  700. isa<IndirectBrInst>(TI) ? nullptr : SplitCriticalEdge(TI, SuccNum);
  701. if (!InstrBB) {
  702. LLVM_DEBUG(
  703. dbgs() << "Fail to split critical edge: not instrument this edge.\n");
  704. return nullptr;
  705. }
  706. // For a critical edge, we have to split. Instrument the newly
  707. // created BB.
  708. IsCS ? NumOfCSPGOSplit++ : NumOfPGOSplit++;
  709. LLVM_DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index
  710. << " --> " << getBBInfo(DestBB).Index << "\n");
  711. // Need to add two new edges. First one: Add new edge of SrcBB->InstrBB.
  712. MST.addEdge(SrcBB, InstrBB, 0);
  713. // Second one: Add new edge of InstrBB->DestBB.
  714. Edge &NewEdge1 = MST.addEdge(InstrBB, DestBB, 0);
  715. NewEdge1.InMST = true;
  716. E->Removed = true;
  717. return canInstrument(InstrBB);
  718. }
  719. // When generating value profiling calls on Windows routines that make use of
  720. // handler funclets for exception processing an operand bundle needs to attached
  721. // to the called function. This routine will set \p OpBundles to contain the
  722. // funclet information, if any is needed, that should be placed on the generated
  723. // value profiling call for the value profile candidate call.
  724. static void
  725. populateEHOperandBundle(VPCandidateInfo &Cand,
  726. DenseMap<BasicBlock *, ColorVector> &BlockColors,
  727. SmallVectorImpl<OperandBundleDef> &OpBundles) {
  728. auto *OrigCall = dyn_cast<CallBase>(Cand.AnnotatedInst);
  729. if (!OrigCall)
  730. return;
  731. if (!isa<IntrinsicInst>(OrigCall)) {
  732. // The instrumentation call should belong to the same funclet as a
  733. // non-intrinsic call, so just copy the operand bundle, if any exists.
  734. std::optional<OperandBundleUse> ParentFunclet =
  735. OrigCall->getOperandBundle(LLVMContext::OB_funclet);
  736. if (ParentFunclet)
  737. OpBundles.emplace_back(OperandBundleDef(*ParentFunclet));
  738. } else {
  739. // Intrinsics or other instructions do not get funclet information from the
  740. // front-end. Need to use the BlockColors that was computed by the routine
  741. // colorEHFunclets to determine whether a funclet is needed.
  742. if (!BlockColors.empty()) {
  743. const ColorVector &CV = BlockColors.find(OrigCall->getParent())->second;
  744. assert(CV.size() == 1 && "non-unique color for block!");
  745. Instruction *EHPad = CV.front()->getFirstNonPHI();
  746. if (EHPad->isEHPad())
  747. OpBundles.emplace_back("funclet", EHPad);
  748. }
  749. }
  750. }
  751. // Visit all edge and instrument the edges not in MST, and do value profiling.
  752. // Critical edges will be split.
  753. static void instrumentOneFunc(
  754. Function &F, Module *M, TargetLibraryInfo &TLI, BranchProbabilityInfo *BPI,
  755. BlockFrequencyInfo *BFI,
  756. std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
  757. bool IsCS) {
  758. // Split indirectbr critical edges here before computing the MST rather than
  759. // later in getInstrBB() to avoid invalidating it.
  760. SplitIndirectBrCriticalEdges(F, /*IgnoreBlocksWithoutPHI=*/false, BPI, BFI);
  761. FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(
  762. F, TLI, ComdatMembers, true, BPI, BFI, IsCS, PGOInstrumentEntry);
  763. Type *I8PtrTy = Type::getInt8PtrTy(M->getContext());
  764. auto Name = ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy);
  765. auto CFGHash = ConstantInt::get(Type::getInt64Ty(M->getContext()),
  766. FuncInfo.FunctionHash);
  767. if (PGOFunctionEntryCoverage) {
  768. auto &EntryBB = F.getEntryBlock();
  769. IRBuilder<> Builder(&EntryBB, EntryBB.getFirstInsertionPt());
  770. // llvm.instrprof.cover(i8* <name>, i64 <hash>, i32 <num-counters>,
  771. // i32 <index>)
  772. Builder.CreateCall(
  773. Intrinsic::getDeclaration(M, Intrinsic::instrprof_cover),
  774. {Name, CFGHash, Builder.getInt32(1), Builder.getInt32(0)});
  775. return;
  776. }
  777. std::vector<BasicBlock *> InstrumentBBs;
  778. FuncInfo.getInstrumentBBs(InstrumentBBs);
  779. unsigned NumCounters =
  780. InstrumentBBs.size() + FuncInfo.SIVisitor.getNumOfSelectInsts();
  781. uint32_t I = 0;
  782. for (auto *InstrBB : InstrumentBBs) {
  783. IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt());
  784. assert(Builder.GetInsertPoint() != InstrBB->end() &&
  785. "Cannot get the Instrumentation point");
  786. // llvm.instrprof.increment(i8* <name>, i64 <hash>, i32 <num-counters>,
  787. // i32 <index>)
  788. Builder.CreateCall(
  789. Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment),
  790. {Name, CFGHash, Builder.getInt32(NumCounters), Builder.getInt32(I++)});
  791. }
  792. // Now instrument select instructions:
  793. FuncInfo.SIVisitor.instrumentSelects(F, &I, NumCounters, FuncInfo.FuncNameVar,
  794. FuncInfo.FunctionHash);
  795. assert(I == NumCounters);
  796. if (DisableValueProfiling)
  797. return;
  798. NumOfPGOICall += FuncInfo.ValueSites[IPVK_IndirectCallTarget].size();
  799. // Intrinsic function calls do not have funclet operand bundles needed for
  800. // Windows exception handling attached to them. However, if value profiling is
  801. // inserted for one of these calls, then a funclet value will need to be set
  802. // on the instrumentation call based on the funclet coloring.
  803. DenseMap<BasicBlock *, ColorVector> BlockColors;
  804. if (F.hasPersonalityFn() &&
  805. isFuncletEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
  806. BlockColors = colorEHFunclets(F);
  807. // For each VP Kind, walk the VP candidates and instrument each one.
  808. for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) {
  809. unsigned SiteIndex = 0;
  810. if (Kind == IPVK_MemOPSize && !PGOInstrMemOP)
  811. continue;
  812. for (VPCandidateInfo Cand : FuncInfo.ValueSites[Kind]) {
  813. LLVM_DEBUG(dbgs() << "Instrument one VP " << ValueProfKindDescr[Kind]
  814. << " site: CallSite Index = " << SiteIndex << "\n");
  815. IRBuilder<> Builder(Cand.InsertPt);
  816. assert(Builder.GetInsertPoint() != Cand.InsertPt->getParent()->end() &&
  817. "Cannot get the Instrumentation point");
  818. Value *ToProfile = nullptr;
  819. if (Cand.V->getType()->isIntegerTy())
  820. ToProfile = Builder.CreateZExtOrTrunc(Cand.V, Builder.getInt64Ty());
  821. else if (Cand.V->getType()->isPointerTy())
  822. ToProfile = Builder.CreatePtrToInt(Cand.V, Builder.getInt64Ty());
  823. assert(ToProfile && "value profiling Value is of unexpected type");
  824. SmallVector<OperandBundleDef, 1> OpBundles;
  825. populateEHOperandBundle(Cand, BlockColors, OpBundles);
  826. Builder.CreateCall(
  827. Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile),
  828. {ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),
  829. Builder.getInt64(FuncInfo.FunctionHash), ToProfile,
  830. Builder.getInt32(Kind), Builder.getInt32(SiteIndex++)},
  831. OpBundles);
  832. }
  833. } // IPVK_First <= Kind <= IPVK_Last
  834. }
  835. namespace {
  836. // This class represents a CFG edge in profile use compilation.
  837. struct PGOUseEdge : public PGOEdge {
  838. bool CountValid = false;
  839. uint64_t CountValue = 0;
  840. PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, uint64_t W = 1)
  841. : PGOEdge(Src, Dest, W) {}
  842. // Set edge count value
  843. void setEdgeCount(uint64_t Value) {
  844. CountValue = Value;
  845. CountValid = true;
  846. }
  847. // Return the information string for this object.
  848. std::string infoString() const {
  849. if (!CountValid)
  850. return PGOEdge::infoString();
  851. return (Twine(PGOEdge::infoString()) + " Count=" + Twine(CountValue))
  852. .str();
  853. }
  854. };
  855. using DirectEdges = SmallVector<PGOUseEdge *, 2>;
  856. // This class stores the auxiliary information for each BB.
  857. struct UseBBInfo : public BBInfo {
  858. uint64_t CountValue = 0;
  859. bool CountValid;
  860. int32_t UnknownCountInEdge = 0;
  861. int32_t UnknownCountOutEdge = 0;
  862. DirectEdges InEdges;
  863. DirectEdges OutEdges;
  864. UseBBInfo(unsigned IX) : BBInfo(IX), CountValid(false) {}
  865. UseBBInfo(unsigned IX, uint64_t C)
  866. : BBInfo(IX), CountValue(C), CountValid(true) {}
  867. // Set the profile count value for this BB.
  868. void setBBInfoCount(uint64_t Value) {
  869. CountValue = Value;
  870. CountValid = true;
  871. }
  872. // Return the information string of this object.
  873. std::string infoString() const {
  874. if (!CountValid)
  875. return BBInfo::infoString();
  876. return (Twine(BBInfo::infoString()) + " Count=" + Twine(CountValue)).str();
  877. }
  878. // Add an OutEdge and update the edge count.
  879. void addOutEdge(PGOUseEdge *E) {
  880. OutEdges.push_back(E);
  881. UnknownCountOutEdge++;
  882. }
  883. // Add an InEdge and update the edge count.
  884. void addInEdge(PGOUseEdge *E) {
  885. InEdges.push_back(E);
  886. UnknownCountInEdge++;
  887. }
  888. };
  889. } // end anonymous namespace
  890. // Sum up the count values for all the edges.
  891. static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) {
  892. uint64_t Total = 0;
  893. for (const auto &E : Edges) {
  894. if (E->Removed)
  895. continue;
  896. Total += E->CountValue;
  897. }
  898. return Total;
  899. }
  900. namespace {
  901. class PGOUseFunc {
  902. public:
  903. PGOUseFunc(Function &Func, Module *Modu, TargetLibraryInfo &TLI,
  904. std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
  905. BranchProbabilityInfo *BPI, BlockFrequencyInfo *BFIin,
  906. ProfileSummaryInfo *PSI, bool IsCS, bool InstrumentFuncEntry)
  907. : F(Func), M(Modu), BFI(BFIin), PSI(PSI),
  908. FuncInfo(Func, TLI, ComdatMembers, false, BPI, BFIin, IsCS,
  909. InstrumentFuncEntry),
  910. FreqAttr(FFA_Normal), IsCS(IsCS) {}
  911. // Read counts for the instrumented BB from profile.
  912. bool readCounters(IndexedInstrProfReader *PGOReader, bool &AllZeros,
  913. InstrProfRecord::CountPseudoKind &PseudoKind);
  914. // Read memprof data for the instrumented function from profile.
  915. bool readMemprof(IndexedInstrProfReader *PGOReader);
  916. // Populate the counts for all BBs.
  917. void populateCounters();
  918. // Set the branch weights based on the count values.
  919. void setBranchWeights();
  920. // Annotate the value profile call sites for all value kind.
  921. void annotateValueSites();
  922. // Annotate the value profile call sites for one value kind.
  923. void annotateValueSites(uint32_t Kind);
  924. // Annotate the irreducible loop header weights.
  925. void annotateIrrLoopHeaderWeights();
  926. // The hotness of the function from the profile count.
  927. enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot };
  928. // Return the function hotness from the profile.
  929. FuncFreqAttr getFuncFreqAttr() const { return FreqAttr; }
  930. // Return the function hash.
  931. uint64_t getFuncHash() const { return FuncInfo.FunctionHash; }
  932. // Return the profile record for this function;
  933. InstrProfRecord &getProfileRecord() { return ProfileRecord; }
  934. // Return the auxiliary BB information.
  935. UseBBInfo &getBBInfo(const BasicBlock *BB) const {
  936. return FuncInfo.getBBInfo(BB);
  937. }
  938. // Return the auxiliary BB information if available.
  939. UseBBInfo *findBBInfo(const BasicBlock *BB) const {
  940. return FuncInfo.findBBInfo(BB);
  941. }
  942. Function &getFunc() const { return F; }
  943. void dumpInfo(std::string Str = "") const {
  944. FuncInfo.dumpInfo(Str);
  945. }
  946. uint64_t getProgramMaxCount() const { return ProgramMaxCount; }
  947. private:
  948. Function &F;
  949. Module *M;
  950. BlockFrequencyInfo *BFI;
  951. ProfileSummaryInfo *PSI;
  952. // This member stores the shared information with class PGOGenFunc.
  953. FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo;
  954. // The maximum count value in the profile. This is only used in PGO use
  955. // compilation.
  956. uint64_t ProgramMaxCount;
  957. // Position of counter that remains to be read.
  958. uint32_t CountPosition = 0;
  959. // Total size of the profile count for this function.
  960. uint32_t ProfileCountSize = 0;
  961. // ProfileRecord for this function.
  962. InstrProfRecord ProfileRecord;
  963. // Function hotness info derived from profile.
  964. FuncFreqAttr FreqAttr;
  965. // Is to use the context sensitive profile.
  966. bool IsCS;
  967. // Find the Instrumented BB and set the value. Return false on error.
  968. bool setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile);
  969. // Set the edge counter value for the unknown edge -- there should be only
  970. // one unknown edge.
  971. void setEdgeCount(DirectEdges &Edges, uint64_t Value);
  972. // Return FuncName string;
  973. std::string getFuncName() const { return FuncInfo.FuncName; }
  974. // Set the hot/cold inline hints based on the count values.
  975. // FIXME: This function should be removed once the functionality in
  976. // the inliner is implemented.
  977. void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {
  978. if (PSI->isHotCount(EntryCount))
  979. FreqAttr = FFA_Hot;
  980. else if (PSI->isColdCount(MaxCount))
  981. FreqAttr = FFA_Cold;
  982. }
  983. };
  984. } // end anonymous namespace
  985. // Visit all the edges and assign the count value for the instrumented
  986. // edges and the BB. Return false on error.
  987. bool PGOUseFunc::setInstrumentedCounts(
  988. const std::vector<uint64_t> &CountFromProfile) {
  989. std::vector<BasicBlock *> InstrumentBBs;
  990. FuncInfo.getInstrumentBBs(InstrumentBBs);
  991. unsigned NumCounters =
  992. InstrumentBBs.size() + FuncInfo.SIVisitor.getNumOfSelectInsts();
  993. // The number of counters here should match the number of counters
  994. // in profile. Return if they mismatch.
  995. if (NumCounters != CountFromProfile.size()) {
  996. return false;
  997. }
  998. auto *FuncEntry = &*F.begin();
  999. // Set the profile count to the Instrumented BBs.
  1000. uint32_t I = 0;
  1001. for (BasicBlock *InstrBB : InstrumentBBs) {
  1002. uint64_t CountValue = CountFromProfile[I++];
  1003. UseBBInfo &Info = getBBInfo(InstrBB);
  1004. // If we reach here, we know that we have some nonzero count
  1005. // values in this function. The entry count should not be 0.
  1006. // Fix it if necessary.
  1007. if (InstrBB == FuncEntry && CountValue == 0)
  1008. CountValue = 1;
  1009. Info.setBBInfoCount(CountValue);
  1010. }
  1011. ProfileCountSize = CountFromProfile.size();
  1012. CountPosition = I;
  1013. // Set the edge count and update the count of unknown edges for BBs.
  1014. auto setEdgeCount = [this](PGOUseEdge *E, uint64_t Value) -> void {
  1015. E->setEdgeCount(Value);
  1016. this->getBBInfo(E->SrcBB).UnknownCountOutEdge--;
  1017. this->getBBInfo(E->DestBB).UnknownCountInEdge--;
  1018. };
  1019. // Set the profile count the Instrumented edges. There are BBs that not in
  1020. // MST but not instrumented. Need to set the edge count value so that we can
  1021. // populate the profile counts later.
  1022. for (auto &E : FuncInfo.MST.AllEdges) {
  1023. if (E->Removed || E->InMST)
  1024. continue;
  1025. const BasicBlock *SrcBB = E->SrcBB;
  1026. UseBBInfo &SrcInfo = getBBInfo(SrcBB);
  1027. // If only one out-edge, the edge profile count should be the same as BB
  1028. // profile count.
  1029. if (SrcInfo.CountValid && SrcInfo.OutEdges.size() == 1)
  1030. setEdgeCount(E.get(), SrcInfo.CountValue);
  1031. else {
  1032. const BasicBlock *DestBB = E->DestBB;
  1033. UseBBInfo &DestInfo = getBBInfo(DestBB);
  1034. // If only one in-edge, the edge profile count should be the same as BB
  1035. // profile count.
  1036. if (DestInfo.CountValid && DestInfo.InEdges.size() == 1)
  1037. setEdgeCount(E.get(), DestInfo.CountValue);
  1038. }
  1039. if (E->CountValid)
  1040. continue;
  1041. // E's count should have been set from profile. If not, this meenas E skips
  1042. // the instrumentation. We set the count to 0.
  1043. setEdgeCount(E.get(), 0);
  1044. }
  1045. return true;
  1046. }
  1047. // Set the count value for the unknown edge. There should be one and only one
  1048. // unknown edge in Edges vector.
  1049. void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) {
  1050. for (auto &E : Edges) {
  1051. if (E->CountValid)
  1052. continue;
  1053. E->setEdgeCount(Value);
  1054. getBBInfo(E->SrcBB).UnknownCountOutEdge--;
  1055. getBBInfo(E->DestBB).UnknownCountInEdge--;
  1056. return;
  1057. }
  1058. llvm_unreachable("Cannot find the unknown count edge");
  1059. }
  1060. // Emit function metadata indicating PGO profile mismatch.
  1061. static void annotateFunctionWithHashMismatch(Function &F,
  1062. LLVMContext &ctx) {
  1063. const char MetadataName[] = "instr_prof_hash_mismatch";
  1064. SmallVector<Metadata *, 2> Names;
  1065. // If this metadata already exists, ignore.
  1066. auto *Existing = F.getMetadata(LLVMContext::MD_annotation);
  1067. if (Existing) {
  1068. MDTuple *Tuple = cast<MDTuple>(Existing);
  1069. for (const auto &N : Tuple->operands()) {
  1070. if (cast<MDString>(N.get())->getString() == MetadataName)
  1071. return;
  1072. Names.push_back(N.get());
  1073. }
  1074. }
  1075. MDBuilder MDB(ctx);
  1076. Names.push_back(MDB.createString(MetadataName));
  1077. MDNode *MD = MDTuple::get(ctx, Names);
  1078. F.setMetadata(LLVMContext::MD_annotation, MD);
  1079. }
  1080. static void addCallsiteMetadata(Instruction &I,
  1081. std::vector<uint64_t> &InlinedCallStack,
  1082. LLVMContext &Ctx) {
  1083. I.setMetadata(LLVMContext::MD_callsite,
  1084. buildCallstackMetadata(InlinedCallStack, Ctx));
  1085. }
  1086. static uint64_t computeStackId(GlobalValue::GUID Function, uint32_t LineOffset,
  1087. uint32_t Column) {
  1088. llvm::HashBuilder<llvm::TruncatedBLAKE3<8>, llvm::support::endianness::little>
  1089. HashBuilder;
  1090. HashBuilder.add(Function, LineOffset, Column);
  1091. llvm::BLAKE3Result<8> Hash = HashBuilder.final();
  1092. uint64_t Id;
  1093. std::memcpy(&Id, Hash.data(), sizeof(Hash));
  1094. return Id;
  1095. }
  1096. static uint64_t computeStackId(const memprof::Frame &Frame) {
  1097. return computeStackId(Frame.Function, Frame.LineOffset, Frame.Column);
  1098. }
  1099. static void addCallStack(CallStackTrie &AllocTrie,
  1100. const AllocationInfo *AllocInfo) {
  1101. SmallVector<uint64_t> StackIds;
  1102. for (auto StackFrame : AllocInfo->CallStack)
  1103. StackIds.push_back(computeStackId(StackFrame));
  1104. auto AllocType = getAllocType(AllocInfo->Info.getMaxAccessCount(),
  1105. AllocInfo->Info.getMinSize(),
  1106. AllocInfo->Info.getMinLifetime());
  1107. AllocTrie.addCallStack(AllocType, StackIds);
  1108. }
  1109. // Helper to compare the InlinedCallStack computed from an instruction's debug
  1110. // info to a list of Frames from profile data (either the allocation data or a
  1111. // callsite). For callsites, the StartIndex to use in the Frame array may be
  1112. // non-zero.
  1113. static bool
  1114. stackFrameIncludesInlinedCallStack(ArrayRef<Frame> ProfileCallStack,
  1115. ArrayRef<uint64_t> InlinedCallStack,
  1116. unsigned StartIndex = 0) {
  1117. auto StackFrame = ProfileCallStack.begin() + StartIndex;
  1118. auto InlCallStackIter = InlinedCallStack.begin();
  1119. for (; StackFrame != ProfileCallStack.end() &&
  1120. InlCallStackIter != InlinedCallStack.end();
  1121. ++StackFrame, ++InlCallStackIter) {
  1122. uint64_t StackId = computeStackId(*StackFrame);
  1123. if (StackId != *InlCallStackIter)
  1124. return false;
  1125. }
  1126. // Return true if we found and matched all stack ids from the call
  1127. // instruction.
  1128. return InlCallStackIter == InlinedCallStack.end();
  1129. }
  1130. bool PGOUseFunc::readMemprof(IndexedInstrProfReader *PGOReader) {
  1131. if (!MatchMemProf)
  1132. return true;
  1133. auto &Ctx = M->getContext();
  1134. auto FuncGUID = Function::getGUID(FuncInfo.FuncName);
  1135. Expected<memprof::MemProfRecord> MemProfResult =
  1136. PGOReader->getMemProfRecord(FuncGUID);
  1137. if (Error E = MemProfResult.takeError()) {
  1138. handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
  1139. auto Err = IPE.get();
  1140. bool SkipWarning = false;
  1141. LLVM_DEBUG(dbgs() << "Error in reading profile for Func "
  1142. << FuncInfo.FuncName << ": ");
  1143. if (Err == instrprof_error::unknown_function) {
  1144. NumOfMemProfMissing++;
  1145. SkipWarning = !PGOWarnMissing;
  1146. LLVM_DEBUG(dbgs() << "unknown function");
  1147. } else if (Err == instrprof_error::hash_mismatch) {
  1148. SkipWarning =
  1149. NoPGOWarnMismatch ||
  1150. (NoPGOWarnMismatchComdatWeak &&
  1151. (F.hasComdat() ||
  1152. F.getLinkage() == GlobalValue::AvailableExternallyLinkage));
  1153. LLVM_DEBUG(dbgs() << "hash mismatch (skip=" << SkipWarning << ")");
  1154. }
  1155. if (SkipWarning)
  1156. return;
  1157. std::string Msg =
  1158. (IPE.message() + Twine(" ") + F.getName().str() + Twine(" Hash = ") +
  1159. std::to_string(FuncInfo.FunctionHash))
  1160. .str();
  1161. Ctx.diagnose(
  1162. DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
  1163. });
  1164. return false;
  1165. }
  1166. // Build maps of the location hash to all profile data with that leaf location
  1167. // (allocation info and the callsites).
  1168. std::map<uint64_t, std::set<const AllocationInfo *>> LocHashToAllocInfo;
  1169. // For the callsites we need to record the index of the associated frame in
  1170. // the frame array (see comments below where the map entries are added).
  1171. std::map<uint64_t, std::set<std::pair<const SmallVector<Frame> *, unsigned>>>
  1172. LocHashToCallSites;
  1173. const auto MemProfRec = std::move(MemProfResult.get());
  1174. for (auto &AI : MemProfRec.AllocSites) {
  1175. // Associate the allocation info with the leaf frame. The later matching
  1176. // code will match any inlined call sequences in the IR with a longer prefix
  1177. // of call stack frames.
  1178. uint64_t StackId = computeStackId(AI.CallStack[0]);
  1179. LocHashToAllocInfo[StackId].insert(&AI);
  1180. }
  1181. for (auto &CS : MemProfRec.CallSites) {
  1182. // Need to record all frames from leaf up to and including this function,
  1183. // as any of these may or may not have been inlined at this point.
  1184. unsigned Idx = 0;
  1185. for (auto &StackFrame : CS) {
  1186. uint64_t StackId = computeStackId(StackFrame);
  1187. LocHashToCallSites[StackId].insert(std::make_pair(&CS, Idx++));
  1188. // Once we find this function, we can stop recording.
  1189. if (StackFrame.Function == FuncGUID)
  1190. break;
  1191. }
  1192. assert(Idx <= CS.size() && CS[Idx - 1].Function == FuncGUID);
  1193. }
  1194. auto GetOffset = [](const DILocation *DIL) {
  1195. return (DIL->getLine() - DIL->getScope()->getSubprogram()->getLine()) &
  1196. 0xffff;
  1197. };
  1198. // Now walk the instructions, looking up the associated profile data using
  1199. // dbug locations.
  1200. for (auto &BB : F) {
  1201. for (auto &I : BB) {
  1202. if (I.isDebugOrPseudoInst())
  1203. continue;
  1204. // We are only interested in calls (allocation or interior call stack
  1205. // context calls).
  1206. auto *CI = dyn_cast<CallBase>(&I);
  1207. if (!CI)
  1208. continue;
  1209. auto *CalledFunction = CI->getCalledFunction();
  1210. if (CalledFunction && CalledFunction->isIntrinsic())
  1211. continue;
  1212. // List of call stack ids computed from the location hashes on debug
  1213. // locations (leaf to inlined at root).
  1214. std::vector<uint64_t> InlinedCallStack;
  1215. // Was the leaf location found in one of the profile maps?
  1216. bool LeafFound = false;
  1217. // If leaf was found in a map, iterators pointing to its location in both
  1218. // of the maps. It might exist in neither, one, or both (the latter case
  1219. // can happen because we don't currently have discriminators to
  1220. // distinguish the case when a single line/col maps to both an allocation
  1221. // and another callsite).
  1222. std::map<uint64_t, std::set<const AllocationInfo *>>::iterator
  1223. AllocInfoIter;
  1224. std::map<uint64_t, std::set<std::pair<const SmallVector<Frame> *,
  1225. unsigned>>>::iterator CallSitesIter;
  1226. for (const DILocation *DIL = I.getDebugLoc(); DIL != nullptr;
  1227. DIL = DIL->getInlinedAt()) {
  1228. // Use C++ linkage name if possible. Need to compile with
  1229. // -fdebug-info-for-profiling to get linkage name.
  1230. StringRef Name = DIL->getScope()->getSubprogram()->getLinkageName();
  1231. if (Name.empty())
  1232. Name = DIL->getScope()->getSubprogram()->getName();
  1233. auto CalleeGUID = Function::getGUID(Name);
  1234. auto StackId =
  1235. computeStackId(CalleeGUID, GetOffset(DIL), DIL->getColumn());
  1236. // LeafFound will only be false on the first iteration, since we either
  1237. // set it true or break out of the loop below.
  1238. if (!LeafFound) {
  1239. AllocInfoIter = LocHashToAllocInfo.find(StackId);
  1240. CallSitesIter = LocHashToCallSites.find(StackId);
  1241. // Check if the leaf is in one of the maps. If not, no need to look
  1242. // further at this call.
  1243. if (AllocInfoIter == LocHashToAllocInfo.end() &&
  1244. CallSitesIter == LocHashToCallSites.end())
  1245. break;
  1246. LeafFound = true;
  1247. }
  1248. InlinedCallStack.push_back(StackId);
  1249. }
  1250. // If leaf not in either of the maps, skip inst.
  1251. if (!LeafFound)
  1252. continue;
  1253. // First add !memprof metadata from allocation info, if we found the
  1254. // instruction's leaf location in that map, and if the rest of the
  1255. // instruction's locations match the prefix Frame locations on an
  1256. // allocation context with the same leaf.
  1257. if (AllocInfoIter != LocHashToAllocInfo.end()) {
  1258. // Only consider allocations via new, to reduce unnecessary metadata,
  1259. // since those are the only allocations that will be targeted initially.
  1260. if (!isNewLikeFn(CI, &FuncInfo.TLI))
  1261. continue;
  1262. // We may match this instruction's location list to multiple MIB
  1263. // contexts. Add them to a Trie specialized for trimming the contexts to
  1264. // the minimal needed to disambiguate contexts with unique behavior.
  1265. CallStackTrie AllocTrie;
  1266. for (auto *AllocInfo : AllocInfoIter->second) {
  1267. // Check the full inlined call stack against this one.
  1268. // If we found and thus matched all frames on the call, include
  1269. // this MIB.
  1270. if (stackFrameIncludesInlinedCallStack(AllocInfo->CallStack,
  1271. InlinedCallStack))
  1272. addCallStack(AllocTrie, AllocInfo);
  1273. }
  1274. // We might not have matched any to the full inlined call stack.
  1275. // But if we did, create and attach metadata, or a function attribute if
  1276. // all contexts have identical profiled behavior.
  1277. if (!AllocTrie.empty()) {
  1278. // MemprofMDAttached will be false if a function attribute was
  1279. // attached.
  1280. bool MemprofMDAttached = AllocTrie.buildAndAttachMIBMetadata(CI);
  1281. assert(MemprofMDAttached == I.hasMetadata(LLVMContext::MD_memprof));
  1282. if (MemprofMDAttached) {
  1283. // Add callsite metadata for the instruction's location list so that
  1284. // it simpler later on to identify which part of the MIB contexts
  1285. // are from this particular instruction (including during inlining,
  1286. // when the callsite metdata will be updated appropriately).
  1287. // FIXME: can this be changed to strip out the matching stack
  1288. // context ids from the MIB contexts and not add any callsite
  1289. // metadata here to save space?
  1290. addCallsiteMetadata(I, InlinedCallStack, Ctx);
  1291. }
  1292. }
  1293. continue;
  1294. }
  1295. // Otherwise, add callsite metadata. If we reach here then we found the
  1296. // instruction's leaf location in the callsites map and not the allocation
  1297. // map.
  1298. assert(CallSitesIter != LocHashToCallSites.end());
  1299. for (auto CallStackIdx : CallSitesIter->second) {
  1300. // If we found and thus matched all frames on the call, create and
  1301. // attach call stack metadata.
  1302. if (stackFrameIncludesInlinedCallStack(
  1303. *CallStackIdx.first, InlinedCallStack, CallStackIdx.second)) {
  1304. addCallsiteMetadata(I, InlinedCallStack, Ctx);
  1305. // Only need to find one with a matching call stack and add a single
  1306. // callsite metadata.
  1307. break;
  1308. }
  1309. }
  1310. }
  1311. }
  1312. return true;
  1313. }
  1314. // Read the profile from ProfileFileName and assign the value to the
  1315. // instrumented BB and the edges. This function also updates ProgramMaxCount.
  1316. // Return true if the profile are successfully read, and false on errors.
  1317. bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader, bool &AllZeros,
  1318. InstrProfRecord::CountPseudoKind &PseudoKind) {
  1319. auto &Ctx = M->getContext();
  1320. uint64_t MismatchedFuncSum = 0;
  1321. Expected<InstrProfRecord> Result = PGOReader->getInstrProfRecord(
  1322. FuncInfo.FuncName, FuncInfo.FunctionHash, &MismatchedFuncSum);
  1323. if (Error E = Result.takeError()) {
  1324. handleAllErrors(std::move(E), [&](const InstrProfError &IPE) {
  1325. auto Err = IPE.get();
  1326. bool SkipWarning = false;
  1327. LLVM_DEBUG(dbgs() << "Error in reading profile for Func "
  1328. << FuncInfo.FuncName << ": ");
  1329. if (Err == instrprof_error::unknown_function) {
  1330. IsCS ? NumOfCSPGOMissing++ : NumOfPGOMissing++;
  1331. SkipWarning = !PGOWarnMissing;
  1332. LLVM_DEBUG(dbgs() << "unknown function");
  1333. } else if (Err == instrprof_error::hash_mismatch ||
  1334. Err == instrprof_error::malformed) {
  1335. IsCS ? NumOfCSPGOMismatch++ : NumOfPGOMismatch++;
  1336. SkipWarning =
  1337. NoPGOWarnMismatch ||
  1338. (NoPGOWarnMismatchComdatWeak &&
  1339. (F.hasComdat() || F.getLinkage() == GlobalValue::WeakAnyLinkage ||
  1340. F.getLinkage() == GlobalValue::AvailableExternallyLinkage));
  1341. LLVM_DEBUG(dbgs() << "hash mismatch (hash= " << FuncInfo.FunctionHash
  1342. << " skip=" << SkipWarning << ")");
  1343. // Emit function metadata indicating PGO profile mismatch.
  1344. annotateFunctionWithHashMismatch(F, M->getContext());
  1345. }
  1346. LLVM_DEBUG(dbgs() << " IsCS=" << IsCS << "\n");
  1347. if (SkipWarning)
  1348. return;
  1349. std::string Msg =
  1350. IPE.message() + std::string(" ") + F.getName().str() +
  1351. std::string(" Hash = ") + std::to_string(FuncInfo.FunctionHash) +
  1352. std::string(" up to ") + std::to_string(MismatchedFuncSum) +
  1353. std::string(" count discarded");
  1354. Ctx.diagnose(
  1355. DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
  1356. });
  1357. return false;
  1358. }
  1359. ProfileRecord = std::move(Result.get());
  1360. PseudoKind = ProfileRecord.getCountPseudoKind();
  1361. if (PseudoKind != InstrProfRecord::NotPseudo) {
  1362. return true;
  1363. }
  1364. std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
  1365. IsCS ? NumOfCSPGOFunc++ : NumOfPGOFunc++;
  1366. LLVM_DEBUG(dbgs() << CountFromProfile.size() << " counts\n");
  1367. uint64_t ValueSum = 0;
  1368. for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) {
  1369. LLVM_DEBUG(dbgs() << " " << I << ": " << CountFromProfile[I] << "\n");
  1370. ValueSum += CountFromProfile[I];
  1371. }
  1372. AllZeros = (ValueSum == 0);
  1373. LLVM_DEBUG(dbgs() << "SUM = " << ValueSum << "\n");
  1374. getBBInfo(nullptr).UnknownCountOutEdge = 2;
  1375. getBBInfo(nullptr).UnknownCountInEdge = 2;
  1376. if (!setInstrumentedCounts(CountFromProfile)) {
  1377. LLVM_DEBUG(
  1378. dbgs() << "Inconsistent number of counts, skipping this function");
  1379. Ctx.diagnose(DiagnosticInfoPGOProfile(
  1380. M->getName().data(),
  1381. Twine("Inconsistent number of counts in ") + F.getName().str()
  1382. + Twine(": the profile may be stale or there is a function name collision."),
  1383. DS_Warning));
  1384. return false;
  1385. }
  1386. ProgramMaxCount = PGOReader->getMaximumFunctionCount(IsCS);
  1387. return true;
  1388. }
  1389. // Populate the counters from instrumented BBs to all BBs.
  1390. // In the end of this operation, all BBs should have a valid count value.
  1391. void PGOUseFunc::populateCounters() {
  1392. bool Changes = true;
  1393. unsigned NumPasses = 0;
  1394. while (Changes) {
  1395. NumPasses++;
  1396. Changes = false;
  1397. // For efficient traversal, it's better to start from the end as most
  1398. // of the instrumented edges are at the end.
  1399. for (auto &BB : reverse(F)) {
  1400. UseBBInfo *Count = findBBInfo(&BB);
  1401. if (Count == nullptr)
  1402. continue;
  1403. if (!Count->CountValid) {
  1404. if (Count->UnknownCountOutEdge == 0) {
  1405. Count->CountValue = sumEdgeCount(Count->OutEdges);
  1406. Count->CountValid = true;
  1407. Changes = true;
  1408. } else if (Count->UnknownCountInEdge == 0) {
  1409. Count->CountValue = sumEdgeCount(Count->InEdges);
  1410. Count->CountValid = true;
  1411. Changes = true;
  1412. }
  1413. }
  1414. if (Count->CountValid) {
  1415. if (Count->UnknownCountOutEdge == 1) {
  1416. uint64_t Total = 0;
  1417. uint64_t OutSum = sumEdgeCount(Count->OutEdges);
  1418. // If the one of the successor block can early terminate (no-return),
  1419. // we can end up with situation where out edge sum count is larger as
  1420. // the source BB's count is collected by a post-dominated block.
  1421. if (Count->CountValue > OutSum)
  1422. Total = Count->CountValue - OutSum;
  1423. setEdgeCount(Count->OutEdges, Total);
  1424. Changes = true;
  1425. }
  1426. if (Count->UnknownCountInEdge == 1) {
  1427. uint64_t Total = 0;
  1428. uint64_t InSum = sumEdgeCount(Count->InEdges);
  1429. if (Count->CountValue > InSum)
  1430. Total = Count->CountValue - InSum;
  1431. setEdgeCount(Count->InEdges, Total);
  1432. Changes = true;
  1433. }
  1434. }
  1435. }
  1436. }
  1437. LLVM_DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n");
  1438. (void) NumPasses;
  1439. #ifndef NDEBUG
  1440. // Assert every BB has a valid counter.
  1441. for (auto &BB : F) {
  1442. auto BI = findBBInfo(&BB);
  1443. if (BI == nullptr)
  1444. continue;
  1445. assert(BI->CountValid && "BB count is not valid");
  1446. }
  1447. #endif
  1448. uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue;
  1449. uint64_t FuncMaxCount = FuncEntryCount;
  1450. for (auto &BB : F) {
  1451. auto BI = findBBInfo(&BB);
  1452. if (BI == nullptr)
  1453. continue;
  1454. FuncMaxCount = std::max(FuncMaxCount, BI->CountValue);
  1455. }
  1456. // Fix the obviously inconsistent entry count.
  1457. if (FuncMaxCount > 0 && FuncEntryCount == 0)
  1458. FuncEntryCount = 1;
  1459. F.setEntryCount(ProfileCount(FuncEntryCount, Function::PCT_Real));
  1460. markFunctionAttributes(FuncEntryCount, FuncMaxCount);
  1461. // Now annotate select instructions
  1462. FuncInfo.SIVisitor.annotateSelects(F, this, &CountPosition);
  1463. assert(CountPosition == ProfileCountSize);
  1464. LLVM_DEBUG(FuncInfo.dumpInfo("after reading profile."));
  1465. }
  1466. // Assign the scaled count values to the BB with multiple out edges.
  1467. void PGOUseFunc::setBranchWeights() {
  1468. // Generate MD_prof metadata for every branch instruction.
  1469. LLVM_DEBUG(dbgs() << "\nSetting branch weights for func " << F.getName()
  1470. << " IsCS=" << IsCS << "\n");
  1471. for (auto &BB : F) {
  1472. Instruction *TI = BB.getTerminator();
  1473. if (TI->getNumSuccessors() < 2)
  1474. continue;
  1475. if (!(isa<BranchInst>(TI) || isa<SwitchInst>(TI) ||
  1476. isa<IndirectBrInst>(TI) || isa<InvokeInst>(TI) ||
  1477. isa<CallBrInst>(TI)))
  1478. continue;
  1479. if (getBBInfo(&BB).CountValue == 0)
  1480. continue;
  1481. // We have a non-zero Branch BB.
  1482. const UseBBInfo &BBCountInfo = getBBInfo(&BB);
  1483. unsigned Size = BBCountInfo.OutEdges.size();
  1484. SmallVector<uint64_t, 2> EdgeCounts(Size, 0);
  1485. uint64_t MaxCount = 0;
  1486. for (unsigned s = 0; s < Size; s++) {
  1487. const PGOUseEdge *E = BBCountInfo.OutEdges[s];
  1488. const BasicBlock *SrcBB = E->SrcBB;
  1489. const BasicBlock *DestBB = E->DestBB;
  1490. if (DestBB == nullptr)
  1491. continue;
  1492. unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
  1493. uint64_t EdgeCount = E->CountValue;
  1494. if (EdgeCount > MaxCount)
  1495. MaxCount = EdgeCount;
  1496. EdgeCounts[SuccNum] = EdgeCount;
  1497. }
  1498. if (MaxCount)
  1499. setProfMetadata(M, TI, EdgeCounts, MaxCount);
  1500. else {
  1501. // A zero MaxCount can come about when we have a BB with a positive
  1502. // count, and whose successor blocks all have 0 count. This can happen
  1503. // when there is no exit block and the code exits via a noreturn function.
  1504. auto &Ctx = M->getContext();
  1505. Ctx.diagnose(DiagnosticInfoPGOProfile(
  1506. M->getName().data(),
  1507. Twine("Profile in ") + F.getName().str() +
  1508. Twine(" partially ignored") +
  1509. Twine(", possibly due to the lack of a return path."),
  1510. DS_Warning));
  1511. }
  1512. }
  1513. }
  1514. static bool isIndirectBrTarget(BasicBlock *BB) {
  1515. for (BasicBlock *Pred : predecessors(BB)) {
  1516. if (isa<IndirectBrInst>(Pred->getTerminator()))
  1517. return true;
  1518. }
  1519. return false;
  1520. }
  1521. void PGOUseFunc::annotateIrrLoopHeaderWeights() {
  1522. LLVM_DEBUG(dbgs() << "\nAnnotating irreducible loop header weights.\n");
  1523. // Find irr loop headers
  1524. for (auto &BB : F) {
  1525. // As a heuristic also annotate indrectbr targets as they have a high chance
  1526. // to become an irreducible loop header after the indirectbr tail
  1527. // duplication.
  1528. if (BFI->isIrrLoopHeader(&BB) || isIndirectBrTarget(&BB)) {
  1529. Instruction *TI = BB.getTerminator();
  1530. const UseBBInfo &BBCountInfo = getBBInfo(&BB);
  1531. setIrrLoopHeaderMetadata(M, TI, BBCountInfo.CountValue);
  1532. }
  1533. }
  1534. }
  1535. void SelectInstVisitor::instrumentOneSelectInst(SelectInst &SI) {
  1536. if (PGOFunctionEntryCoverage)
  1537. return;
  1538. Module *M = F.getParent();
  1539. IRBuilder<> Builder(&SI);
  1540. Type *Int64Ty = Builder.getInt64Ty();
  1541. Type *I8PtrTy = Builder.getInt8PtrTy();
  1542. auto *Step = Builder.CreateZExt(SI.getCondition(), Int64Ty);
  1543. Builder.CreateCall(
  1544. Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment_step),
  1545. {ConstantExpr::getBitCast(FuncNameVar, I8PtrTy),
  1546. Builder.getInt64(FuncHash), Builder.getInt32(TotalNumCtrs),
  1547. Builder.getInt32(*CurCtrIdx), Step});
  1548. ++(*CurCtrIdx);
  1549. }
  1550. void SelectInstVisitor::annotateOneSelectInst(SelectInst &SI) {
  1551. std::vector<uint64_t> &CountFromProfile = UseFunc->getProfileRecord().Counts;
  1552. assert(*CurCtrIdx < CountFromProfile.size() &&
  1553. "Out of bound access of counters");
  1554. uint64_t SCounts[2];
  1555. SCounts[0] = CountFromProfile[*CurCtrIdx]; // True count
  1556. ++(*CurCtrIdx);
  1557. uint64_t TotalCount = 0;
  1558. auto BI = UseFunc->findBBInfo(SI.getParent());
  1559. if (BI != nullptr)
  1560. TotalCount = BI->CountValue;
  1561. // False Count
  1562. SCounts[1] = (TotalCount > SCounts[0] ? TotalCount - SCounts[0] : 0);
  1563. uint64_t MaxCount = std::max(SCounts[0], SCounts[1]);
  1564. if (MaxCount)
  1565. setProfMetadata(F.getParent(), &SI, SCounts, MaxCount);
  1566. }
  1567. void SelectInstVisitor::visitSelectInst(SelectInst &SI) {
  1568. if (!PGOInstrSelect)
  1569. return;
  1570. // FIXME: do not handle this yet.
  1571. if (SI.getCondition()->getType()->isVectorTy())
  1572. return;
  1573. switch (Mode) {
  1574. case VM_counting:
  1575. NSIs++;
  1576. return;
  1577. case VM_instrument:
  1578. instrumentOneSelectInst(SI);
  1579. return;
  1580. case VM_annotate:
  1581. annotateOneSelectInst(SI);
  1582. return;
  1583. }
  1584. llvm_unreachable("Unknown visiting mode");
  1585. }
  1586. // Traverse all valuesites and annotate the instructions for all value kind.
  1587. void PGOUseFunc::annotateValueSites() {
  1588. if (DisableValueProfiling)
  1589. return;
  1590. // Create the PGOFuncName meta data.
  1591. createPGOFuncNameMetadata(F, FuncInfo.FuncName);
  1592. for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
  1593. annotateValueSites(Kind);
  1594. }
  1595. // Annotate the instructions for a specific value kind.
  1596. void PGOUseFunc::annotateValueSites(uint32_t Kind) {
  1597. assert(Kind <= IPVK_Last);
  1598. unsigned ValueSiteIndex = 0;
  1599. auto &ValueSites = FuncInfo.ValueSites[Kind];
  1600. unsigned NumValueSites = ProfileRecord.getNumValueSites(Kind);
  1601. if (NumValueSites != ValueSites.size()) {
  1602. auto &Ctx = M->getContext();
  1603. Ctx.diagnose(DiagnosticInfoPGOProfile(
  1604. M->getName().data(),
  1605. Twine("Inconsistent number of value sites for ") +
  1606. Twine(ValueProfKindDescr[Kind]) +
  1607. Twine(" profiling in \"") + F.getName().str() +
  1608. Twine("\", possibly due to the use of a stale profile."),
  1609. DS_Warning));
  1610. return;
  1611. }
  1612. for (VPCandidateInfo &I : ValueSites) {
  1613. LLVM_DEBUG(dbgs() << "Read one value site profile (kind = " << Kind
  1614. << "): Index = " << ValueSiteIndex << " out of "
  1615. << NumValueSites << "\n");
  1616. annotateValueSite(*M, *I.AnnotatedInst, ProfileRecord,
  1617. static_cast<InstrProfValueKind>(Kind), ValueSiteIndex,
  1618. Kind == IPVK_MemOPSize ? MaxNumMemOPAnnotations
  1619. : MaxNumAnnotations);
  1620. ValueSiteIndex++;
  1621. }
  1622. }
  1623. // Collect the set of members for each Comdat in module M and store
  1624. // in ComdatMembers.
  1625. static void collectComdatMembers(
  1626. Module &M,
  1627. std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
  1628. if (!DoComdatRenaming)
  1629. return;
  1630. for (Function &F : M)
  1631. if (Comdat *C = F.getComdat())
  1632. ComdatMembers.insert(std::make_pair(C, &F));
  1633. for (GlobalVariable &GV : M.globals())
  1634. if (Comdat *C = GV.getComdat())
  1635. ComdatMembers.insert(std::make_pair(C, &GV));
  1636. for (GlobalAlias &GA : M.aliases())
  1637. if (Comdat *C = GA.getComdat())
  1638. ComdatMembers.insert(std::make_pair(C, &GA));
  1639. }
  1640. // Don't perform PGO instrumeatnion / profile-use.
  1641. static bool skipPGO(const Function &F) {
  1642. if (F.isDeclaration())
  1643. return true;
  1644. if (F.hasFnAttribute(llvm::Attribute::NoProfile))
  1645. return true;
  1646. if (F.hasFnAttribute(llvm::Attribute::SkipProfile))
  1647. return true;
  1648. if (F.getInstructionCount() < PGOFunctionSizeThreshold)
  1649. return true;
  1650. // If there are too many critical edges, PGO might cause
  1651. // compiler time problem. Skip PGO if the number of
  1652. // critical edges execeed the threshold.
  1653. unsigned NumCriticalEdges = 0;
  1654. for (auto &BB : F) {
  1655. const Instruction *TI = BB.getTerminator();
  1656. for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
  1657. if (isCriticalEdge(TI, I))
  1658. NumCriticalEdges++;
  1659. }
  1660. }
  1661. if (NumCriticalEdges > PGOFunctionCriticalEdgeThreshold) {
  1662. LLVM_DEBUG(dbgs() << "In func " << F.getName()
  1663. << ", NumCriticalEdges=" << NumCriticalEdges
  1664. << " exceed the threshold. Skip PGO.\n");
  1665. return true;
  1666. }
  1667. return false;
  1668. }
  1669. static bool InstrumentAllFunctions(
  1670. Module &M, function_ref<TargetLibraryInfo &(Function &)> LookupTLI,
  1671. function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
  1672. function_ref<BlockFrequencyInfo *(Function &)> LookupBFI, bool IsCS) {
  1673. // For the context-sensitve instrumentation, we should have a separated pass
  1674. // (before LTO/ThinLTO linking) to create these variables.
  1675. if (!IsCS)
  1676. createIRLevelProfileFlagVar(M, /*IsCS=*/false);
  1677. std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
  1678. collectComdatMembers(M, ComdatMembers);
  1679. for (auto &F : M) {
  1680. if (skipPGO(F))
  1681. continue;
  1682. auto &TLI = LookupTLI(F);
  1683. auto *BPI = LookupBPI(F);
  1684. auto *BFI = LookupBFI(F);
  1685. instrumentOneFunc(F, &M, TLI, BPI, BFI, ComdatMembers, IsCS);
  1686. }
  1687. return true;
  1688. }
  1689. PreservedAnalyses
  1690. PGOInstrumentationGenCreateVar::run(Module &M, ModuleAnalysisManager &AM) {
  1691. createProfileFileNameVar(M, CSInstrName);
  1692. // The variable in a comdat may be discarded by LTO. Ensure the declaration
  1693. // will be retained.
  1694. appendToCompilerUsed(M, createIRLevelProfileFlagVar(M, /*IsCS=*/true));
  1695. return PreservedAnalyses::all();
  1696. }
  1697. PreservedAnalyses PGOInstrumentationGen::run(Module &M,
  1698. ModuleAnalysisManager &AM) {
  1699. auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
  1700. auto LookupTLI = [&FAM](Function &F) -> TargetLibraryInfo & {
  1701. return FAM.getResult<TargetLibraryAnalysis>(F);
  1702. };
  1703. auto LookupBPI = [&FAM](Function &F) {
  1704. return &FAM.getResult<BranchProbabilityAnalysis>(F);
  1705. };
  1706. auto LookupBFI = [&FAM](Function &F) {
  1707. return &FAM.getResult<BlockFrequencyAnalysis>(F);
  1708. };
  1709. if (!InstrumentAllFunctions(M, LookupTLI, LookupBPI, LookupBFI, IsCS))
  1710. return PreservedAnalyses::all();
  1711. return PreservedAnalyses::none();
  1712. }
  1713. // Using the ratio b/w sums of profile count values and BFI count values to
  1714. // adjust the func entry count.
  1715. static void fixFuncEntryCount(PGOUseFunc &Func, LoopInfo &LI,
  1716. BranchProbabilityInfo &NBPI) {
  1717. Function &F = Func.getFunc();
  1718. BlockFrequencyInfo NBFI(F, NBPI, LI);
  1719. #ifndef NDEBUG
  1720. auto BFIEntryCount = F.getEntryCount();
  1721. assert(BFIEntryCount && (BFIEntryCount->getCount() > 0) &&
  1722. "Invalid BFI Entrycount");
  1723. #endif
  1724. auto SumCount = APFloat::getZero(APFloat::IEEEdouble());
  1725. auto SumBFICount = APFloat::getZero(APFloat::IEEEdouble());
  1726. for (auto &BBI : F) {
  1727. uint64_t CountValue = 0;
  1728. uint64_t BFICountValue = 0;
  1729. if (!Func.findBBInfo(&BBI))
  1730. continue;
  1731. auto BFICount = NBFI.getBlockProfileCount(&BBI);
  1732. CountValue = Func.getBBInfo(&BBI).CountValue;
  1733. BFICountValue = *BFICount;
  1734. SumCount.add(APFloat(CountValue * 1.0), APFloat::rmNearestTiesToEven);
  1735. SumBFICount.add(APFloat(BFICountValue * 1.0), APFloat::rmNearestTiesToEven);
  1736. }
  1737. if (SumCount.isZero())
  1738. return;
  1739. assert(SumBFICount.compare(APFloat(0.0)) == APFloat::cmpGreaterThan &&
  1740. "Incorrect sum of BFI counts");
  1741. if (SumBFICount.compare(SumCount) == APFloat::cmpEqual)
  1742. return;
  1743. double Scale = (SumCount / SumBFICount).convertToDouble();
  1744. if (Scale < 1.001 && Scale > 0.999)
  1745. return;
  1746. uint64_t FuncEntryCount = Func.getBBInfo(&*F.begin()).CountValue;
  1747. uint64_t NewEntryCount = 0.5 + FuncEntryCount * Scale;
  1748. if (NewEntryCount == 0)
  1749. NewEntryCount = 1;
  1750. if (NewEntryCount != FuncEntryCount) {
  1751. F.setEntryCount(ProfileCount(NewEntryCount, Function::PCT_Real));
  1752. LLVM_DEBUG(dbgs() << "FixFuncEntryCount: in " << F.getName()
  1753. << ", entry_count " << FuncEntryCount << " --> "
  1754. << NewEntryCount << "\n");
  1755. }
  1756. }
  1757. // Compare the profile count values with BFI count values, and print out
  1758. // the non-matching ones.
  1759. static void verifyFuncBFI(PGOUseFunc &Func, LoopInfo &LI,
  1760. BranchProbabilityInfo &NBPI,
  1761. uint64_t HotCountThreshold,
  1762. uint64_t ColdCountThreshold) {
  1763. Function &F = Func.getFunc();
  1764. BlockFrequencyInfo NBFI(F, NBPI, LI);
  1765. // bool PrintFunc = false;
  1766. bool HotBBOnly = PGOVerifyHotBFI;
  1767. std::string Msg;
  1768. OptimizationRemarkEmitter ORE(&F);
  1769. unsigned BBNum = 0, BBMisMatchNum = 0, NonZeroBBNum = 0;
  1770. for (auto &BBI : F) {
  1771. uint64_t CountValue = 0;
  1772. uint64_t BFICountValue = 0;
  1773. if (Func.getBBInfo(&BBI).CountValid)
  1774. CountValue = Func.getBBInfo(&BBI).CountValue;
  1775. BBNum++;
  1776. if (CountValue)
  1777. NonZeroBBNum++;
  1778. auto BFICount = NBFI.getBlockProfileCount(&BBI);
  1779. if (BFICount)
  1780. BFICountValue = *BFICount;
  1781. if (HotBBOnly) {
  1782. bool rawIsHot = CountValue >= HotCountThreshold;
  1783. bool BFIIsHot = BFICountValue >= HotCountThreshold;
  1784. bool rawIsCold = CountValue <= ColdCountThreshold;
  1785. bool ShowCount = false;
  1786. if (rawIsHot && !BFIIsHot) {
  1787. Msg = "raw-Hot to BFI-nonHot";
  1788. ShowCount = true;
  1789. } else if (rawIsCold && BFIIsHot) {
  1790. Msg = "raw-Cold to BFI-Hot";
  1791. ShowCount = true;
  1792. }
  1793. if (!ShowCount)
  1794. continue;
  1795. } else {
  1796. if ((CountValue < PGOVerifyBFICutoff) &&
  1797. (BFICountValue < PGOVerifyBFICutoff))
  1798. continue;
  1799. uint64_t Diff = (BFICountValue >= CountValue)
  1800. ? BFICountValue - CountValue
  1801. : CountValue - BFICountValue;
  1802. if (Diff <= CountValue / 100 * PGOVerifyBFIRatio)
  1803. continue;
  1804. }
  1805. BBMisMatchNum++;
  1806. ORE.emit([&]() {
  1807. OptimizationRemarkAnalysis Remark(DEBUG_TYPE, "bfi-verify",
  1808. F.getSubprogram(), &BBI);
  1809. Remark << "BB " << ore::NV("Block", BBI.getName())
  1810. << " Count=" << ore::NV("Count", CountValue)
  1811. << " BFI_Count=" << ore::NV("Count", BFICountValue);
  1812. if (!Msg.empty())
  1813. Remark << " (" << Msg << ")";
  1814. return Remark;
  1815. });
  1816. }
  1817. if (BBMisMatchNum)
  1818. ORE.emit([&]() {
  1819. return OptimizationRemarkAnalysis(DEBUG_TYPE, "bfi-verify",
  1820. F.getSubprogram(), &F.getEntryBlock())
  1821. << "In Func " << ore::NV("Function", F.getName())
  1822. << ": Num_of_BB=" << ore::NV("Count", BBNum)
  1823. << ", Num_of_non_zerovalue_BB=" << ore::NV("Count", NonZeroBBNum)
  1824. << ", Num_of_mis_matching_BB=" << ore::NV("Count", BBMisMatchNum);
  1825. });
  1826. }
  1827. static bool annotateAllFunctions(
  1828. Module &M, StringRef ProfileFileName, StringRef ProfileRemappingFileName,
  1829. function_ref<TargetLibraryInfo &(Function &)> LookupTLI,
  1830. function_ref<BranchProbabilityInfo *(Function &)> LookupBPI,
  1831. function_ref<BlockFrequencyInfo *(Function &)> LookupBFI,
  1832. ProfileSummaryInfo *PSI, bool IsCS) {
  1833. LLVM_DEBUG(dbgs() << "Read in profile counters: ");
  1834. auto &Ctx = M.getContext();
  1835. // Read the counter array from file.
  1836. auto ReaderOrErr =
  1837. IndexedInstrProfReader::create(ProfileFileName, ProfileRemappingFileName);
  1838. if (Error E = ReaderOrErr.takeError()) {
  1839. handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
  1840. Ctx.diagnose(
  1841. DiagnosticInfoPGOProfile(ProfileFileName.data(), EI.message()));
  1842. });
  1843. return false;
  1844. }
  1845. std::unique_ptr<IndexedInstrProfReader> PGOReader =
  1846. std::move(ReaderOrErr.get());
  1847. if (!PGOReader) {
  1848. Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),
  1849. StringRef("Cannot get PGOReader")));
  1850. return false;
  1851. }
  1852. if (!PGOReader->hasCSIRLevelProfile() && IsCS)
  1853. return false;
  1854. // TODO: might need to change the warning once the clang option is finalized.
  1855. if (!PGOReader->isIRLevelProfile() && !PGOReader->hasMemoryProfile()) {
  1856. Ctx.diagnose(DiagnosticInfoPGOProfile(
  1857. ProfileFileName.data(), "Not an IR level instrumentation profile"));
  1858. return false;
  1859. }
  1860. if (PGOReader->hasSingleByteCoverage()) {
  1861. Ctx.diagnose(DiagnosticInfoPGOProfile(
  1862. ProfileFileName.data(),
  1863. "Cannot use coverage profiles for optimization"));
  1864. return false;
  1865. }
  1866. if (PGOReader->functionEntryOnly()) {
  1867. Ctx.diagnose(DiagnosticInfoPGOProfile(
  1868. ProfileFileName.data(),
  1869. "Function entry profiles are not yet supported for optimization"));
  1870. return false;
  1871. }
  1872. // Add the profile summary (read from the header of the indexed summary) here
  1873. // so that we can use it below when reading counters (which checks if the
  1874. // function should be marked with a cold or inlinehint attribute).
  1875. M.setProfileSummary(PGOReader->getSummary(IsCS).getMD(M.getContext()),
  1876. IsCS ? ProfileSummary::PSK_CSInstr
  1877. : ProfileSummary::PSK_Instr);
  1878. PSI->refresh();
  1879. std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
  1880. collectComdatMembers(M, ComdatMembers);
  1881. std::vector<Function *> HotFunctions;
  1882. std::vector<Function *> ColdFunctions;
  1883. // If the profile marked as always instrument the entry BB, do the
  1884. // same. Note this can be overwritten by the internal option in CFGMST.h
  1885. bool InstrumentFuncEntry = PGOReader->instrEntryBBEnabled();
  1886. if (PGOInstrumentEntry.getNumOccurrences() > 0)
  1887. InstrumentFuncEntry = PGOInstrumentEntry;
  1888. for (auto &F : M) {
  1889. if (skipPGO(F))
  1890. continue;
  1891. auto &TLI = LookupTLI(F);
  1892. auto *BPI = LookupBPI(F);
  1893. auto *BFI = LookupBFI(F);
  1894. // Split indirectbr critical edges here before computing the MST rather than
  1895. // later in getInstrBB() to avoid invalidating it.
  1896. SplitIndirectBrCriticalEdges(F, /*IgnoreBlocksWithoutPHI=*/false, BPI, BFI);
  1897. PGOUseFunc Func(F, &M, TLI, ComdatMembers, BPI, BFI, PSI, IsCS,
  1898. InstrumentFuncEntry);
  1899. // Read and match memprof first since we do this via debug info and can
  1900. // match even if there is an IR mismatch detected for regular PGO below.
  1901. if (PGOReader->hasMemoryProfile())
  1902. Func.readMemprof(PGOReader.get());
  1903. if (!PGOReader->isIRLevelProfile())
  1904. continue;
  1905. // When PseudoKind is set to a vaule other than InstrProfRecord::NotPseudo,
  1906. // it means the profile for the function is unrepresentative and this
  1907. // function is actually hot / warm. We will reset the function hot / cold
  1908. // attribute and drop all the profile counters.
  1909. InstrProfRecord::CountPseudoKind PseudoKind = InstrProfRecord::NotPseudo;
  1910. bool AllZeros = false;
  1911. if (!Func.readCounters(PGOReader.get(), AllZeros, PseudoKind))
  1912. continue;
  1913. if (AllZeros) {
  1914. F.setEntryCount(ProfileCount(0, Function::PCT_Real));
  1915. if (Func.getProgramMaxCount() != 0)
  1916. ColdFunctions.push_back(&F);
  1917. continue;
  1918. }
  1919. if (PseudoKind != InstrProfRecord::NotPseudo) {
  1920. // Clear function attribute cold.
  1921. if (F.hasFnAttribute(Attribute::Cold))
  1922. F.removeFnAttr(Attribute::Cold);
  1923. // Set function attribute as hot.
  1924. if (PseudoKind == InstrProfRecord::PseudoHot)
  1925. F.addFnAttr(Attribute::Hot);
  1926. continue;
  1927. }
  1928. Func.populateCounters();
  1929. Func.setBranchWeights();
  1930. Func.annotateValueSites();
  1931. Func.annotateIrrLoopHeaderWeights();
  1932. PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr();
  1933. if (FreqAttr == PGOUseFunc::FFA_Cold)
  1934. ColdFunctions.push_back(&F);
  1935. else if (FreqAttr == PGOUseFunc::FFA_Hot)
  1936. HotFunctions.push_back(&F);
  1937. if (PGOViewCounts != PGOVCT_None &&
  1938. (ViewBlockFreqFuncName.empty() ||
  1939. F.getName().equals(ViewBlockFreqFuncName))) {
  1940. LoopInfo LI{DominatorTree(F)};
  1941. std::unique_ptr<BranchProbabilityInfo> NewBPI =
  1942. std::make_unique<BranchProbabilityInfo>(F, LI);
  1943. std::unique_ptr<BlockFrequencyInfo> NewBFI =
  1944. std::make_unique<BlockFrequencyInfo>(F, *NewBPI, LI);
  1945. if (PGOViewCounts == PGOVCT_Graph)
  1946. NewBFI->view();
  1947. else if (PGOViewCounts == PGOVCT_Text) {
  1948. dbgs() << "pgo-view-counts: " << Func.getFunc().getName() << "\n";
  1949. NewBFI->print(dbgs());
  1950. }
  1951. }
  1952. if (PGOViewRawCounts != PGOVCT_None &&
  1953. (ViewBlockFreqFuncName.empty() ||
  1954. F.getName().equals(ViewBlockFreqFuncName))) {
  1955. if (PGOViewRawCounts == PGOVCT_Graph)
  1956. if (ViewBlockFreqFuncName.empty())
  1957. WriteGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
  1958. else
  1959. ViewGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
  1960. else if (PGOViewRawCounts == PGOVCT_Text) {
  1961. dbgs() << "pgo-view-raw-counts: " << Func.getFunc().getName() << "\n";
  1962. Func.dumpInfo();
  1963. }
  1964. }
  1965. if (PGOVerifyBFI || PGOVerifyHotBFI || PGOFixEntryCount) {
  1966. LoopInfo LI{DominatorTree(F)};
  1967. BranchProbabilityInfo NBPI(F, LI);
  1968. // Fix func entry count.
  1969. if (PGOFixEntryCount)
  1970. fixFuncEntryCount(Func, LI, NBPI);
  1971. // Verify BlockFrequency information.
  1972. uint64_t HotCountThreshold = 0, ColdCountThreshold = 0;
  1973. if (PGOVerifyHotBFI) {
  1974. HotCountThreshold = PSI->getOrCompHotCountThreshold();
  1975. ColdCountThreshold = PSI->getOrCompColdCountThreshold();
  1976. }
  1977. verifyFuncBFI(Func, LI, NBPI, HotCountThreshold, ColdCountThreshold);
  1978. }
  1979. }
  1980. // Set function hotness attribute from the profile.
  1981. // We have to apply these attributes at the end because their presence
  1982. // can affect the BranchProbabilityInfo of any callers, resulting in an
  1983. // inconsistent MST between prof-gen and prof-use.
  1984. for (auto &F : HotFunctions) {
  1985. F->addFnAttr(Attribute::InlineHint);
  1986. LLVM_DEBUG(dbgs() << "Set inline attribute to function: " << F->getName()
  1987. << "\n");
  1988. }
  1989. for (auto &F : ColdFunctions) {
  1990. // Only set when there is no Attribute::Hot set by the user. For Hot
  1991. // attribute, user's annotation has the precedence over the profile.
  1992. if (F->hasFnAttribute(Attribute::Hot)) {
  1993. auto &Ctx = M.getContext();
  1994. std::string Msg = std::string("Function ") + F->getName().str() +
  1995. std::string(" is annotated as a hot function but"
  1996. " the profile is cold");
  1997. Ctx.diagnose(
  1998. DiagnosticInfoPGOProfile(M.getName().data(), Msg, DS_Warning));
  1999. continue;
  2000. }
  2001. F->addFnAttr(Attribute::Cold);
  2002. LLVM_DEBUG(dbgs() << "Set cold attribute to function: " << F->getName()
  2003. << "\n");
  2004. }
  2005. return true;
  2006. }
  2007. PGOInstrumentationUse::PGOInstrumentationUse(std::string Filename,
  2008. std::string RemappingFilename,
  2009. bool IsCS)
  2010. : ProfileFileName(std::move(Filename)),
  2011. ProfileRemappingFileName(std::move(RemappingFilename)), IsCS(IsCS) {
  2012. if (!PGOTestProfileFile.empty())
  2013. ProfileFileName = PGOTestProfileFile;
  2014. if (!PGOTestProfileRemappingFile.empty())
  2015. ProfileRemappingFileName = PGOTestProfileRemappingFile;
  2016. }
  2017. PreservedAnalyses PGOInstrumentationUse::run(Module &M,
  2018. ModuleAnalysisManager &AM) {
  2019. auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
  2020. auto LookupTLI = [&FAM](Function &F) -> TargetLibraryInfo & {
  2021. return FAM.getResult<TargetLibraryAnalysis>(F);
  2022. };
  2023. auto LookupBPI = [&FAM](Function &F) {
  2024. return &FAM.getResult<BranchProbabilityAnalysis>(F);
  2025. };
  2026. auto LookupBFI = [&FAM](Function &F) {
  2027. return &FAM.getResult<BlockFrequencyAnalysis>(F);
  2028. };
  2029. auto *PSI = &AM.getResult<ProfileSummaryAnalysis>(M);
  2030. if (!annotateAllFunctions(M, ProfileFileName, ProfileRemappingFileName,
  2031. LookupTLI, LookupBPI, LookupBFI, PSI, IsCS))
  2032. return PreservedAnalyses::all();
  2033. return PreservedAnalyses::none();
  2034. }
  2035. static std::string getSimpleNodeName(const BasicBlock *Node) {
  2036. if (!Node->getName().empty())
  2037. return std::string(Node->getName());
  2038. std::string SimpleNodeName;
  2039. raw_string_ostream OS(SimpleNodeName);
  2040. Node->printAsOperand(OS, false);
  2041. return OS.str();
  2042. }
  2043. void llvm::setProfMetadata(Module *M, Instruction *TI,
  2044. ArrayRef<uint64_t> EdgeCounts,
  2045. uint64_t MaxCount) {
  2046. MDBuilder MDB(M->getContext());
  2047. assert(MaxCount > 0 && "Bad max count");
  2048. uint64_t Scale = calculateCountScale(MaxCount);
  2049. SmallVector<unsigned, 4> Weights;
  2050. for (const auto &ECI : EdgeCounts)
  2051. Weights.push_back(scaleBranchCount(ECI, Scale));
  2052. LLVM_DEBUG(dbgs() << "Weight is: "; for (const auto &W
  2053. : Weights) {
  2054. dbgs() << W << " ";
  2055. } dbgs() << "\n";);
  2056. misexpect::checkExpectAnnotations(*TI, Weights, /*IsFrontend=*/false);
  2057. TI->setMetadata(LLVMContext::MD_prof, MDB.createBranchWeights(Weights));
  2058. if (EmitBranchProbability) {
  2059. std::string BrCondStr = getBranchCondString(TI);
  2060. if (BrCondStr.empty())
  2061. return;
  2062. uint64_t WSum =
  2063. std::accumulate(Weights.begin(), Weights.end(), (uint64_t)0,
  2064. [](uint64_t w1, uint64_t w2) { return w1 + w2; });
  2065. uint64_t TotalCount =
  2066. std::accumulate(EdgeCounts.begin(), EdgeCounts.end(), (uint64_t)0,
  2067. [](uint64_t c1, uint64_t c2) { return c1 + c2; });
  2068. Scale = calculateCountScale(WSum);
  2069. BranchProbability BP(scaleBranchCount(Weights[0], Scale),
  2070. scaleBranchCount(WSum, Scale));
  2071. std::string BranchProbStr;
  2072. raw_string_ostream OS(BranchProbStr);
  2073. OS << BP;
  2074. OS << " (total count : " << TotalCount << ")";
  2075. OS.flush();
  2076. Function *F = TI->getParent()->getParent();
  2077. OptimizationRemarkEmitter ORE(F);
  2078. ORE.emit([&]() {
  2079. return OptimizationRemark(DEBUG_TYPE, "pgo-instrumentation", TI)
  2080. << BrCondStr << " is true with probability : " << BranchProbStr;
  2081. });
  2082. }
  2083. }
  2084. namespace llvm {
  2085. void setIrrLoopHeaderMetadata(Module *M, Instruction *TI, uint64_t Count) {
  2086. MDBuilder MDB(M->getContext());
  2087. TI->setMetadata(llvm::LLVMContext::MD_irr_loop,
  2088. MDB.createIrrLoopHeaderWeight(Count));
  2089. }
  2090. template <> struct GraphTraits<PGOUseFunc *> {
  2091. using NodeRef = const BasicBlock *;
  2092. using ChildIteratorType = const_succ_iterator;
  2093. using nodes_iterator = pointer_iterator<Function::const_iterator>;
  2094. static NodeRef getEntryNode(const PGOUseFunc *G) {
  2095. return &G->getFunc().front();
  2096. }
  2097. static ChildIteratorType child_begin(const NodeRef N) {
  2098. return succ_begin(N);
  2099. }
  2100. static ChildIteratorType child_end(const NodeRef N) { return succ_end(N); }
  2101. static nodes_iterator nodes_begin(const PGOUseFunc *G) {
  2102. return nodes_iterator(G->getFunc().begin());
  2103. }
  2104. static nodes_iterator nodes_end(const PGOUseFunc *G) {
  2105. return nodes_iterator(G->getFunc().end());
  2106. }
  2107. };
  2108. template <> struct DOTGraphTraits<PGOUseFunc *> : DefaultDOTGraphTraits {
  2109. explicit DOTGraphTraits(bool isSimple = false)
  2110. : DefaultDOTGraphTraits(isSimple) {}
  2111. static std::string getGraphName(const PGOUseFunc *G) {
  2112. return std::string(G->getFunc().getName());
  2113. }
  2114. std::string getNodeLabel(const BasicBlock *Node, const PGOUseFunc *Graph) {
  2115. std::string Result;
  2116. raw_string_ostream OS(Result);
  2117. OS << getSimpleNodeName(Node) << ":\\l";
  2118. UseBBInfo *BI = Graph->findBBInfo(Node);
  2119. OS << "Count : ";
  2120. if (BI && BI->CountValid)
  2121. OS << BI->CountValue << "\\l";
  2122. else
  2123. OS << "Unknown\\l";
  2124. if (!PGOInstrSelect)
  2125. return Result;
  2126. for (const Instruction &I : *Node) {
  2127. if (!isa<SelectInst>(&I))
  2128. continue;
  2129. // Display scaled counts for SELECT instruction:
  2130. OS << "SELECT : { T = ";
  2131. uint64_t TC, FC;
  2132. bool HasProf = extractBranchWeights(I, TC, FC);
  2133. if (!HasProf)
  2134. OS << "Unknown, F = Unknown }\\l";
  2135. else
  2136. OS << TC << ", F = " << FC << " }\\l";
  2137. }
  2138. return Result;
  2139. }
  2140. };
  2141. } // end namespace llvm