Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 1 | //===-- PGOInstrumentation.cpp - MST-based PGO Instrumentation ------------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This file implements PGO instrumentation using a minimum spanning tree based |
| 11 | // on the following paper: |
| 12 | // [1] Donald E. Knuth, Francis R. Stevenson. Optimal measurement of points |
| 13 | // for program frequency counts. BIT Numerical Mathematics 1973, Volume 13, |
| 14 | // Issue 3, pp 313-322 |
| 15 | // The idea of the algorithm based on the fact that for each node (except for |
| 16 | // the entry and exit), the sum of incoming edge counts equals the sum of |
| 17 | // outgoing edge counts. The count of edge on spanning tree can be derived from |
| 18 | // those edges not on the spanning tree. Knuth proves this method instruments |
| 19 | // the minimum number of edges. |
| 20 | // |
| 21 | // The minimal spanning tree here is actually a maximum weight tree -- on-tree |
| 22 | // edges have higher frequencies (more likely to execute). The idea is to |
| 23 | // instrument those less frequently executed edges to reduce the runtime |
| 24 | // overhead of instrumented binaries. |
| 25 | // |
| 26 | // This file contains two passes: |
| 27 | // (1) Pass PGOInstrumentationGen which instruments the IR to generate edge |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 28 | // count profile, and generates the instrumentation for indirect call |
| 29 | // profiling. |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 30 | // (2) Pass PGOInstrumentationUse which reads the edge count profile and |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 31 | // annotates the branch weights. It also reads the indirect call value |
| 32 | // profiling records and annotate the indirect call instructions. |
| 33 | // |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 34 | // To get the precise counter information, These two passes need to invoke at |
| 35 | // the same compilation point (so they see the same IR). For pass |
| 36 | // PGOInstrumentationGen, the real work is done in instrumentOneFunc(). For |
| 37 | // pass PGOInstrumentationUse, the real work in done in class PGOUseFunc and |
| 38 | // the profile is opened in module level and passed to each PGOUseFunc instance. |
| 39 | // The shared code for PGOInstrumentationGen and PGOInstrumentationUse is put |
| 40 | // in class FuncPGOInstrumentation. |
| 41 | // |
| 42 | // Class PGOEdge represents a CFG edge and some auxiliary information. Class |
| 43 | // BBInfo contains auxiliary information for each BB. These two classes are used |
| 44 | // in pass PGOInstrumentationGen. Class PGOUseEdge and UseBBInfo are the derived |
| 45 | // class of PGOEdge and BBInfo, respectively. They contains extra data structure |
| 46 | // used in populating profile counters. |
| 47 | // The MST implementation is in Class CFGMST (CFGMST.h). |
| 48 | // |
| 49 | //===----------------------------------------------------------------------===// |
| 50 | |
Xinliang David Li | 8aebf44 | 2016-05-06 05:49:19 +0000 | [diff] [blame] | 51 | #include "llvm/Transforms/PGOInstrumentation.h" |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 52 | #include "CFGMST.h" |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 53 | #include "llvm/ADT/STLExtras.h" |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 54 | #include "llvm/ADT/SmallVector.h" |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 55 | #include "llvm/ADT/Statistic.h" |
Rong Xu | 33c76c0 | 2016-02-10 17:18:30 +0000 | [diff] [blame] | 56 | #include "llvm/ADT/Triple.h" |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 57 | #include "llvm/Analysis/BlockFrequencyInfo.h" |
| 58 | #include "llvm/Analysis/BranchProbabilityInfo.h" |
| 59 | #include "llvm/Analysis/CFG.h" |
Teresa Johnson | 1e44b5d | 2016-07-12 21:13:44 +0000 | [diff] [blame] | 60 | #include "llvm/Analysis/IndirectCallSiteVisitor.h" |
Xinliang David Li | cb253ce | 2017-01-23 18:58:24 +0000 | [diff] [blame] | 61 | #include "llvm/Analysis/LoopInfo.h" |
Rong Xu | ed9fec7 | 2016-01-21 18:11:44 +0000 | [diff] [blame] | 62 | #include "llvm/IR/CallSite.h" |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 63 | #include "llvm/IR/DiagnosticInfo.h" |
Xinliang David Li | d289e45 | 2017-01-27 19:06:25 +0000 | [diff] [blame] | 64 | #include "llvm/IR/Dominators.h" |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 65 | #include "llvm/IR/GlobalValue.h" |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 66 | #include "llvm/IR/IRBuilder.h" |
| 67 | #include "llvm/IR/InstIterator.h" |
| 68 | #include "llvm/IR/Instructions.h" |
| 69 | #include "llvm/IR/IntrinsicInst.h" |
| 70 | #include "llvm/IR/MDBuilder.h" |
| 71 | #include "llvm/IR/Module.h" |
| 72 | #include "llvm/Pass.h" |
| 73 | #include "llvm/ProfileData/InstrProfReader.h" |
Easwaran Raman | 5fe04a1 | 2016-05-26 22:57:11 +0000 | [diff] [blame] | 74 | #include "llvm/ProfileData/ProfileCommon.h" |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 75 | #include "llvm/Support/BranchProbability.h" |
Xinliang David Li | d289e45 | 2017-01-27 19:06:25 +0000 | [diff] [blame] | 76 | #include "llvm/Support/DOTGraphTraits.h" |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 77 | #include "llvm/Support/Debug.h" |
Xinliang David Li | d289e45 | 2017-01-27 19:06:25 +0000 | [diff] [blame] | 78 | #include "llvm/Support/GraphWriter.h" |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 79 | #include "llvm/Support/JamCRC.h" |
Rong Xu | ed9fec7 | 2016-01-21 18:11:44 +0000 | [diff] [blame] | 80 | #include "llvm/Transforms/Instrumentation.h" |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 81 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
Xinliang David Li | 8aebf44 | 2016-05-06 05:49:19 +0000 | [diff] [blame] | 82 | #include <algorithm> |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 83 | #include <string> |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 84 | #include <unordered_map> |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 85 | #include <utility> |
| 86 | #include <vector> |
| 87 | |
| 88 | using namespace llvm; |
| 89 | |
| 90 | #define DEBUG_TYPE "pgo-instrumentation" |
| 91 | |
| 92 | STATISTIC(NumOfPGOInstrument, "Number of edges instrumented."); |
Xinliang David Li | 4ca1733 | 2016-09-18 18:34:07 +0000 | [diff] [blame] | 93 | STATISTIC(NumOfPGOSelectInsts, "Number of select instruction instrumented."); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 94 | STATISTIC(NumOfPGOEdge, "Number of edges."); |
| 95 | STATISTIC(NumOfPGOBB, "Number of basic-blocks."); |
| 96 | STATISTIC(NumOfPGOSplit, "Number of critical edge splits."); |
| 97 | STATISTIC(NumOfPGOFunc, "Number of functions having valid profile counts."); |
| 98 | STATISTIC(NumOfPGOMismatch, "Number of functions having mismatch profile."); |
| 99 | STATISTIC(NumOfPGOMissing, "Number of functions without profile."); |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 100 | STATISTIC(NumOfPGOICall, "Number of indirect call value instrumentations."); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 101 | |
| 102 | // Command line option to specify the file to read profile from. This is |
| 103 | // mainly used for testing. |
| 104 | static cl::opt<std::string> |
| 105 | PGOTestProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden, |
| 106 | cl::value_desc("filename"), |
| 107 | cl::desc("Specify the path of profile data file. This is" |
| 108 | "mainly for test purpose.")); |
| 109 | |
Rong Xu | ecdc98f | 2016-03-04 22:08:44 +0000 | [diff] [blame] | 110 | // Command line option to disable value profiling. The default is false: |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 111 | // i.e. value profiling is enabled by default. This is for debug purpose. |
Rong Xu | 9e926e8 | 2016-02-29 19:16:04 +0000 | [diff] [blame] | 112 | static cl::opt<bool> DisableValueProfiling("disable-vp", cl::init(false), |
| 113 | cl::Hidden, |
| 114 | cl::desc("Disable Value Profiling")); |
Rong Xu | ed9fec7 | 2016-01-21 18:11:44 +0000 | [diff] [blame] | 115 | |
Rong Xu | ecdc98f | 2016-03-04 22:08:44 +0000 | [diff] [blame] | 116 | // Command line option to set the maximum number of VP annotations to write to |
Rong Xu | 08afb05 | 2016-04-28 17:31:22 +0000 | [diff] [blame] | 117 | // the metadata for a single indirect call callsite. |
| 118 | static cl::opt<unsigned> MaxNumAnnotations( |
| 119 | "icp-max-annotations", cl::init(3), cl::Hidden, cl::ZeroOrMore, |
| 120 | cl::desc("Max number of annotations for a single indirect " |
| 121 | "call callsite")); |
Rong Xu | ecdc98f | 2016-03-04 22:08:44 +0000 | [diff] [blame] | 122 | |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 123 | // Command line option to control appending FunctionHash to the name of a COMDAT |
| 124 | // function. This is to avoid the hash mismatch caused by the preinliner. |
| 125 | static cl::opt<bool> DoComdatRenaming( |
Rong Xu | 20f5df1 | 2017-01-11 20:19:41 +0000 | [diff] [blame] | 126 | "do-comdat-renaming", cl::init(false), cl::Hidden, |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 127 | cl::desc("Append function hash to the name of COMDAT function to avoid " |
| 128 | "function hash mismatch due to the preinliner")); |
| 129 | |
Rong Xu | 0698de9 | 2016-05-13 17:26:06 +0000 | [diff] [blame] | 130 | // Command line option to enable/disable the warning about missing profile |
| 131 | // information. |
Xinliang David Li | 58fcc9b | 2017-02-02 21:29:17 +0000 | [diff] [blame] | 132 | static cl::opt<bool> |
| 133 | PGOWarnMissing("pgo-warn-missing-function", cl::init(false), cl::Hidden, |
| 134 | cl::desc("Use this option to turn on/off " |
| 135 | "warnings about missing profile data for " |
| 136 | "functions.")); |
Rong Xu | 0698de9 | 2016-05-13 17:26:06 +0000 | [diff] [blame] | 137 | |
| 138 | // Command line option to enable/disable the warning about a hash mismatch in |
| 139 | // the profile data. |
Xinliang David Li | 58fcc9b | 2017-02-02 21:29:17 +0000 | [diff] [blame] | 140 | static cl::opt<bool> |
| 141 | NoPGOWarnMismatch("no-pgo-warn-mismatch", cl::init(false), cl::Hidden, |
| 142 | cl::desc("Use this option to turn off/on " |
| 143 | "warnings about profile cfg mismatch.")); |
Rong Xu | 0698de9 | 2016-05-13 17:26:06 +0000 | [diff] [blame] | 144 | |
Rong Xu | 20f5df1 | 2017-01-11 20:19:41 +0000 | [diff] [blame] | 145 | // Command line option to enable/disable the warning about a hash mismatch in |
| 146 | // the profile data for Comdat functions, which often turns out to be false |
| 147 | // positive due to the pre-instrumentation inline. |
Xinliang David Li | 58fcc9b | 2017-02-02 21:29:17 +0000 | [diff] [blame] | 148 | static cl::opt<bool> |
| 149 | NoPGOWarnMismatchComdat("no-pgo-warn-mismatch-comdat", cl::init(true), |
| 150 | cl::Hidden, |
| 151 | cl::desc("The option is used to turn on/off " |
| 152 | "warnings about hash mismatch for comdat " |
| 153 | "functions.")); |
Rong Xu | 20f5df1 | 2017-01-11 20:19:41 +0000 | [diff] [blame] | 154 | |
Xinliang David Li | 4ca1733 | 2016-09-18 18:34:07 +0000 | [diff] [blame] | 155 | // Command line option to enable/disable select instruction instrumentation. |
Xinliang David Li | 58fcc9b | 2017-02-02 21:29:17 +0000 | [diff] [blame] | 156 | static cl::opt<bool> |
| 157 | PGOInstrSelect("pgo-instr-select", cl::init(true), cl::Hidden, |
| 158 | cl::desc("Use this option to turn on/off SELECT " |
| 159 | "instruction instrumentation. ")); |
Xinliang David Li | cb253ce | 2017-01-23 18:58:24 +0000 | [diff] [blame] | 160 | |
Xinliang David Li | d289e45 | 2017-01-27 19:06:25 +0000 | [diff] [blame] | 161 | // Command line option to turn on CFG dot dump of raw profile counts |
Xinliang David Li | 58fcc9b | 2017-02-02 21:29:17 +0000 | [diff] [blame] | 162 | static cl::opt<bool> |
| 163 | PGOViewRawCounts("pgo-view-raw-counts", cl::init(false), cl::Hidden, |
| 164 | cl::desc("A boolean option to show CFG dag " |
| 165 | "with raw profile counts from " |
| 166 | "profile data. See also option " |
| 167 | "-pgo-view-counts. To limit graph " |
| 168 | "display to only one function, use " |
| 169 | "filtering option -view-bfi-func-name.")); |
Xinliang David Li | d289e45 | 2017-01-27 19:06:25 +0000 | [diff] [blame] | 170 | |
Xinliang David Li | cb253ce | 2017-01-23 18:58:24 +0000 | [diff] [blame] | 171 | // Command line option to turn on CFG dot dump after profile annotation. |
Xinliang David Li | 58fcc9b | 2017-02-02 21:29:17 +0000 | [diff] [blame] | 172 | // Defined in Analysis/BlockFrequencyInfo.cpp: -pgo-view-counts |
Xinliang David Li | cb253ce | 2017-01-23 18:58:24 +0000 | [diff] [blame] | 173 | extern cl::opt<bool> PGOViewCounts; |
| 174 | |
Xinliang David Li | 58fcc9b | 2017-02-02 21:29:17 +0000 | [diff] [blame] | 175 | // Command line option to specify the name of the function for CFG dump |
| 176 | // Defined in Analysis/BlockFrequencyInfo.cpp: -view-bfi-func-name= |
| 177 | extern cl::opt<std::string> ViewBlockFreqFuncName; |
| 178 | |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 179 | namespace { |
Xinliang David Li | 4ca1733 | 2016-09-18 18:34:07 +0000 | [diff] [blame] | 180 | |
| 181 | /// The select instruction visitor plays three roles specified |
| 182 | /// by the mode. In \c VM_counting mode, it simply counts the number of |
| 183 | /// select instructions. In \c VM_instrument mode, it inserts code to count |
| 184 | /// the number times TrueValue of select is taken. In \c VM_annotate mode, |
| 185 | /// it reads the profile data and annotate the select instruction with metadata. |
| 186 | enum VisitMode { VM_counting, VM_instrument, VM_annotate }; |
| 187 | class PGOUseFunc; |
| 188 | |
| 189 | /// Instruction Visitor class to visit select instructions. |
| 190 | struct SelectInstVisitor : public InstVisitor<SelectInstVisitor> { |
| 191 | Function &F; |
| 192 | unsigned NSIs = 0; // Number of select instructions instrumented. |
| 193 | VisitMode Mode = VM_counting; // Visiting mode. |
| 194 | unsigned *CurCtrIdx = nullptr; // Pointer to current counter index. |
| 195 | unsigned TotalNumCtrs = 0; // Total number of counters |
| 196 | GlobalVariable *FuncNameVar = nullptr; |
| 197 | uint64_t FuncHash = 0; |
| 198 | PGOUseFunc *UseFunc = nullptr; |
| 199 | |
| 200 | SelectInstVisitor(Function &Func) : F(Func) {} |
| 201 | |
| 202 | void countSelects(Function &Func) { |
| 203 | Mode = VM_counting; |
| 204 | visit(Func); |
| 205 | } |
| 206 | // Visit the IR stream and instrument all select instructions. \p |
| 207 | // Ind is a pointer to the counter index variable; \p TotalNC |
| 208 | // is the total number of counters; \p FNV is the pointer to the |
| 209 | // PGO function name var; \p FHash is the function hash. |
| 210 | void instrumentSelects(Function &Func, unsigned *Ind, unsigned TotalNC, |
| 211 | GlobalVariable *FNV, uint64_t FHash) { |
| 212 | Mode = VM_instrument; |
| 213 | CurCtrIdx = Ind; |
| 214 | TotalNumCtrs = TotalNC; |
| 215 | FuncHash = FHash; |
| 216 | FuncNameVar = FNV; |
| 217 | visit(Func); |
| 218 | } |
| 219 | |
| 220 | // Visit the IR stream and annotate all select instructions. |
| 221 | void annotateSelects(Function &Func, PGOUseFunc *UF, unsigned *Ind) { |
| 222 | Mode = VM_annotate; |
| 223 | UseFunc = UF; |
| 224 | CurCtrIdx = Ind; |
| 225 | visit(Func); |
| 226 | } |
| 227 | |
| 228 | void instrumentOneSelectInst(SelectInst &SI); |
| 229 | void annotateOneSelectInst(SelectInst &SI); |
| 230 | // Visit \p SI instruction and perform tasks according to visit mode. |
| 231 | void visitSelectInst(SelectInst &SI); |
| 232 | unsigned getNumOfSelectInsts() const { return NSIs; } |
| 233 | }; |
| 234 | |
Xinliang David Li | 8aebf44 | 2016-05-06 05:49:19 +0000 | [diff] [blame] | 235 | class PGOInstrumentationGenLegacyPass : public ModulePass { |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 236 | public: |
| 237 | static char ID; |
| 238 | |
Xinliang David Li | dfa21c3 | 2016-05-09 21:37:12 +0000 | [diff] [blame] | 239 | PGOInstrumentationGenLegacyPass() : ModulePass(ID) { |
Xinliang David Li | 8aebf44 | 2016-05-06 05:49:19 +0000 | [diff] [blame] | 240 | initializePGOInstrumentationGenLegacyPassPass( |
| 241 | *PassRegistry::getPassRegistry()); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 242 | } |
| 243 | |
Mehdi Amini | 117296c | 2016-10-01 02:56:57 +0000 | [diff] [blame] | 244 | StringRef getPassName() const override { return "PGOInstrumentationGenPass"; } |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 245 | |
| 246 | private: |
| 247 | bool runOnModule(Module &M) override; |
| 248 | |
| 249 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
| 250 | AU.addRequired<BlockFrequencyInfoWrapperPass>(); |
| 251 | } |
| 252 | }; |
| 253 | |
Xinliang David Li | d55827f | 2016-05-07 05:39:12 +0000 | [diff] [blame] | 254 | class PGOInstrumentationUseLegacyPass : public ModulePass { |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 255 | public: |
| 256 | static char ID; |
| 257 | |
| 258 | // Provide the profile filename as the parameter. |
Xinliang David Li | d55827f | 2016-05-07 05:39:12 +0000 | [diff] [blame] | 259 | PGOInstrumentationUseLegacyPass(std::string Filename = "") |
Benjamin Kramer | 82de7d3 | 2016-05-27 14:27:24 +0000 | [diff] [blame] | 260 | : ModulePass(ID), ProfileFileName(std::move(Filename)) { |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 261 | if (!PGOTestProfileFile.empty()) |
| 262 | ProfileFileName = PGOTestProfileFile; |
Xinliang David Li | d55827f | 2016-05-07 05:39:12 +0000 | [diff] [blame] | 263 | initializePGOInstrumentationUseLegacyPassPass( |
| 264 | *PassRegistry::getPassRegistry()); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 265 | } |
| 266 | |
Mehdi Amini | 117296c | 2016-10-01 02:56:57 +0000 | [diff] [blame] | 267 | StringRef getPassName() const override { return "PGOInstrumentationUsePass"; } |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 268 | |
| 269 | private: |
| 270 | std::string ProfileFileName; |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 271 | |
Xinliang David Li | da19558 | 2016-05-10 21:59:52 +0000 | [diff] [blame] | 272 | bool runOnModule(Module &M) override; |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 273 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
| 274 | AU.addRequired<BlockFrequencyInfoWrapperPass>(); |
| 275 | } |
| 276 | }; |
Xinliang David Li | 4ca1733 | 2016-09-18 18:34:07 +0000 | [diff] [blame] | 277 | |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 278 | } // end anonymous namespace |
| 279 | |
Xinliang David Li | 8aebf44 | 2016-05-06 05:49:19 +0000 | [diff] [blame] | 280 | char PGOInstrumentationGenLegacyPass::ID = 0; |
| 281 | INITIALIZE_PASS_BEGIN(PGOInstrumentationGenLegacyPass, "pgo-instr-gen", |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 282 | "PGO instrumentation.", false, false) |
| 283 | INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass) |
| 284 | INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass) |
Xinliang David Li | 8aebf44 | 2016-05-06 05:49:19 +0000 | [diff] [blame] | 285 | INITIALIZE_PASS_END(PGOInstrumentationGenLegacyPass, "pgo-instr-gen", |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 286 | "PGO instrumentation.", false, false) |
| 287 | |
Xinliang David Li | 8aebf44 | 2016-05-06 05:49:19 +0000 | [diff] [blame] | 288 | ModulePass *llvm::createPGOInstrumentationGenLegacyPass() { |
| 289 | return new PGOInstrumentationGenLegacyPass(); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 290 | } |
| 291 | |
Xinliang David Li | d55827f | 2016-05-07 05:39:12 +0000 | [diff] [blame] | 292 | char PGOInstrumentationUseLegacyPass::ID = 0; |
| 293 | INITIALIZE_PASS_BEGIN(PGOInstrumentationUseLegacyPass, "pgo-instr-use", |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 294 | "Read PGO instrumentation profile.", false, false) |
| 295 | INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass) |
| 296 | INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass) |
Xinliang David Li | d55827f | 2016-05-07 05:39:12 +0000 | [diff] [blame] | 297 | INITIALIZE_PASS_END(PGOInstrumentationUseLegacyPass, "pgo-instr-use", |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 298 | "Read PGO instrumentation profile.", false, false) |
| 299 | |
Xinliang David Li | d55827f | 2016-05-07 05:39:12 +0000 | [diff] [blame] | 300 | ModulePass *llvm::createPGOInstrumentationUseLegacyPass(StringRef Filename) { |
| 301 | return new PGOInstrumentationUseLegacyPass(Filename.str()); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 302 | } |
| 303 | |
| 304 | namespace { |
| 305 | /// \brief An MST based instrumentation for PGO |
| 306 | /// |
| 307 | /// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO |
| 308 | /// in the function level. |
| 309 | struct PGOEdge { |
| 310 | // This class implements the CFG edges. Note the CFG can be a multi-graph. |
| 311 | // So there might be multiple edges with same SrcBB and DestBB. |
| 312 | const BasicBlock *SrcBB; |
| 313 | const BasicBlock *DestBB; |
| 314 | uint64_t Weight; |
| 315 | bool InMST; |
| 316 | bool Removed; |
| 317 | bool IsCritical; |
| 318 | PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1) |
| 319 | : SrcBB(Src), DestBB(Dest), Weight(W), InMST(false), Removed(false), |
| 320 | IsCritical(false) {} |
| 321 | // Return the information string of an edge. |
| 322 | const std::string infoString() const { |
| 323 | return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") + |
| 324 | (IsCritical ? "c" : " ") + " W=" + Twine(Weight)).str(); |
| 325 | } |
| 326 | }; |
| 327 | |
| 328 | // This class stores the auxiliary information for each BB. |
| 329 | struct BBInfo { |
| 330 | BBInfo *Group; |
| 331 | uint32_t Index; |
| 332 | uint32_t Rank; |
| 333 | |
| 334 | BBInfo(unsigned IX) : Group(this), Index(IX), Rank(0) {} |
| 335 | |
| 336 | // Return the information string of this object. |
| 337 | const std::string infoString() const { |
| 338 | return (Twine("Index=") + Twine(Index)).str(); |
| 339 | } |
| 340 | }; |
| 341 | |
| 342 | // This class implements the CFG edges. Note the CFG can be a multi-graph. |
| 343 | template <class Edge, class BBInfo> class FuncPGOInstrumentation { |
| 344 | private: |
| 345 | Function &F; |
| 346 | void computeCFGHash(); |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 347 | void renameComdatFunction(); |
| 348 | // A map that stores the Comdat group in function F. |
| 349 | std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers; |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 350 | |
| 351 | public: |
Rong Xu | a3bbf96 | 2017-03-15 18:23:39 +0000 | [diff] [blame^] | 352 | std::vector<std::vector<Instruction *>> ValueSites; |
Xinliang David Li | 4ca1733 | 2016-09-18 18:34:07 +0000 | [diff] [blame] | 353 | SelectInstVisitor SIVisitor; |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 354 | std::string FuncName; |
| 355 | GlobalVariable *FuncNameVar; |
| 356 | // CFG hash value for this function. |
| 357 | uint64_t FunctionHash; |
| 358 | |
| 359 | // The Minimum Spanning Tree of function CFG. |
| 360 | CFGMST<Edge, BBInfo> MST; |
| 361 | |
| 362 | // Give an edge, find the BB that will be instrumented. |
| 363 | // Return nullptr if there is no BB to be instrumented. |
| 364 | BasicBlock *getInstrBB(Edge *E); |
| 365 | |
| 366 | // Return the auxiliary BB information. |
| 367 | BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); } |
| 368 | |
Rong Xu | a5b5745 | 2016-12-02 19:10:29 +0000 | [diff] [blame] | 369 | // Return the auxiliary BB information if available. |
| 370 | BBInfo *findBBInfo(const BasicBlock *BB) const { return MST.findBBInfo(BB); } |
| 371 | |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 372 | // Dump edges and BB information. |
| 373 | void dumpInfo(std::string Str = "") const { |
| 374 | MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName + " Hash: " + |
Rong Xu | ed9fec7 | 2016-01-21 18:11:44 +0000 | [diff] [blame] | 375 | Twine(FunctionHash) + "\t" + Str); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 376 | } |
| 377 | |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 378 | FuncPGOInstrumentation( |
| 379 | Function &Func, |
| 380 | std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers, |
| 381 | bool CreateGlobalVar = false, BranchProbabilityInfo *BPI = nullptr, |
| 382 | BlockFrequencyInfo *BFI = nullptr) |
Rong Xu | a3bbf96 | 2017-03-15 18:23:39 +0000 | [diff] [blame^] | 383 | : F(Func), ComdatMembers(ComdatMembers), ValueSites(IPVK_Last + 1), |
| 384 | SIVisitor(Func), FunctionHash(0), MST(F, BPI, BFI) { |
Xinliang David Li | 4ca1733 | 2016-09-18 18:34:07 +0000 | [diff] [blame] | 385 | |
| 386 | // This should be done before CFG hash computation. |
| 387 | SIVisitor.countSelects(Func); |
| 388 | NumOfPGOSelectInsts += SIVisitor.getNumOfSelectInsts(); |
Rong Xu | a3bbf96 | 2017-03-15 18:23:39 +0000 | [diff] [blame^] | 389 | ValueSites[IPVK_IndirectCallTarget] = findIndirectCallSites(Func); |
Xinliang David Li | 4ca1733 | 2016-09-18 18:34:07 +0000 | [diff] [blame] | 390 | |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 391 | FuncName = getPGOFuncName(F); |
| 392 | computeCFGHash(); |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 393 | if (ComdatMembers.size()) |
| 394 | renameComdatFunction(); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 395 | DEBUG(dumpInfo("after CFGMST")); |
| 396 | |
| 397 | NumOfPGOBB += MST.BBInfos.size(); |
| 398 | for (auto &E : MST.AllEdges) { |
| 399 | if (E->Removed) |
| 400 | continue; |
| 401 | NumOfPGOEdge++; |
| 402 | if (!E->InMST) |
| 403 | NumOfPGOInstrument++; |
| 404 | } |
| 405 | |
| 406 | if (CreateGlobalVar) |
| 407 | FuncNameVar = createPGOFuncNameVar(F, FuncName); |
Eugene Zelenko | 6ac3f73 | 2016-01-26 18:48:36 +0000 | [diff] [blame] | 408 | } |
Xinliang David Li | d119761 | 2016-08-01 20:25:06 +0000 | [diff] [blame] | 409 | |
| 410 | // Return the number of profile counters needed for the function. |
| 411 | unsigned getNumCounters() { |
| 412 | unsigned NumCounters = 0; |
| 413 | for (auto &E : this->MST.AllEdges) { |
| 414 | if (!E->InMST && !E->Removed) |
| 415 | NumCounters++; |
| 416 | } |
Xinliang David Li | 4ca1733 | 2016-09-18 18:34:07 +0000 | [diff] [blame] | 417 | return NumCounters + SIVisitor.getNumOfSelectInsts(); |
Xinliang David Li | d119761 | 2016-08-01 20:25:06 +0000 | [diff] [blame] | 418 | } |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 419 | }; |
| 420 | |
| 421 | // Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index |
| 422 | // value of each BB in the CFG. The higher 32 bits record the number of edges. |
| 423 | template <class Edge, class BBInfo> |
| 424 | void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() { |
| 425 | std::vector<char> Indexes; |
| 426 | JamCRC JC; |
| 427 | for (auto &BB : F) { |
| 428 | const TerminatorInst *TI = BB.getTerminator(); |
| 429 | for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) { |
| 430 | BasicBlock *Succ = TI->getSuccessor(I); |
Rong Xu | a5b5745 | 2016-12-02 19:10:29 +0000 | [diff] [blame] | 431 | auto BI = findBBInfo(Succ); |
| 432 | if (BI == nullptr) |
| 433 | continue; |
| 434 | uint32_t Index = BI->Index; |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 435 | for (int J = 0; J < 4; J++) |
| 436 | Indexes.push_back((char)(Index >> (J * 8))); |
| 437 | } |
| 438 | } |
| 439 | JC.update(Indexes); |
Xinliang David Li | 4ca1733 | 2016-09-18 18:34:07 +0000 | [diff] [blame] | 440 | FunctionHash = (uint64_t)SIVisitor.getNumOfSelectInsts() << 56 | |
Rong Xu | a3bbf96 | 2017-03-15 18:23:39 +0000 | [diff] [blame^] | 441 | (uint64_t)ValueSites[IPVK_IndirectCallTarget].size() << 48 | |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 442 | (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC(); |
| 443 | } |
| 444 | |
| 445 | // Check if we can safely rename this Comdat function. |
| 446 | static bool canRenameComdat( |
| 447 | Function &F, |
| 448 | std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) { |
Rong Xu | 20f5df1 | 2017-01-11 20:19:41 +0000 | [diff] [blame] | 449 | if (!DoComdatRenaming || !canRenameComdatFunc(F, true)) |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 450 | return false; |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 451 | |
| 452 | // FIXME: Current only handle those Comdat groups that only containing one |
| 453 | // function and function aliases. |
| 454 | // (1) For a Comdat group containing multiple functions, we need to have a |
| 455 | // unique postfix based on the hashes for each function. There is a |
| 456 | // non-trivial code refactoring to do this efficiently. |
| 457 | // (2) Variables can not be renamed, so we can not rename Comdat function in a |
| 458 | // group including global vars. |
| 459 | Comdat *C = F.getComdat(); |
| 460 | for (auto &&CM : make_range(ComdatMembers.equal_range(C))) { |
| 461 | if (dyn_cast<GlobalAlias>(CM.second)) |
| 462 | continue; |
| 463 | Function *FM = dyn_cast<Function>(CM.second); |
| 464 | if (FM != &F) |
| 465 | return false; |
| 466 | } |
| 467 | return true; |
| 468 | } |
| 469 | |
| 470 | // Append the CFGHash to the Comdat function name. |
| 471 | template <class Edge, class BBInfo> |
| 472 | void FuncPGOInstrumentation<Edge, BBInfo>::renameComdatFunction() { |
| 473 | if (!canRenameComdat(F, ComdatMembers)) |
| 474 | return; |
Rong Xu | 0e79f7d | 2016-10-06 20:38:13 +0000 | [diff] [blame] | 475 | std::string OrigName = F.getName().str(); |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 476 | std::string NewFuncName = |
| 477 | Twine(F.getName() + "." + Twine(FunctionHash)).str(); |
| 478 | F.setName(Twine(NewFuncName)); |
Rong Xu | 0e79f7d | 2016-10-06 20:38:13 +0000 | [diff] [blame] | 479 | GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigName, &F); |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 480 | FuncName = Twine(FuncName + "." + Twine(FunctionHash)).str(); |
| 481 | Comdat *NewComdat; |
| 482 | Module *M = F.getParent(); |
| 483 | // For AvailableExternallyLinkage functions, change the linkage to |
| 484 | // LinkOnceODR and put them into comdat. This is because after renaming, there |
| 485 | // is no backup external copy available for the function. |
| 486 | if (!F.hasComdat()) { |
| 487 | assert(F.getLinkage() == GlobalValue::AvailableExternallyLinkage); |
| 488 | NewComdat = M->getOrInsertComdat(StringRef(NewFuncName)); |
| 489 | F.setLinkage(GlobalValue::LinkOnceODRLinkage); |
| 490 | F.setComdat(NewComdat); |
| 491 | return; |
| 492 | } |
| 493 | |
| 494 | // This function belongs to a single function Comdat group. |
| 495 | Comdat *OrigComdat = F.getComdat(); |
| 496 | std::string NewComdatName = |
| 497 | Twine(OrigComdat->getName() + "." + Twine(FunctionHash)).str(); |
| 498 | NewComdat = M->getOrInsertComdat(StringRef(NewComdatName)); |
| 499 | NewComdat->setSelectionKind(OrigComdat->getSelectionKind()); |
| 500 | |
| 501 | for (auto &&CM : make_range(ComdatMembers.equal_range(OrigComdat))) { |
| 502 | if (GlobalAlias *GA = dyn_cast<GlobalAlias>(CM.second)) { |
| 503 | // For aliases, change the name directly. |
| 504 | assert(dyn_cast<Function>(GA->getAliasee()->stripPointerCasts()) == &F); |
Rong Xu | 0e79f7d | 2016-10-06 20:38:13 +0000 | [diff] [blame] | 505 | std::string OrigGAName = GA->getName().str(); |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 506 | GA->setName(Twine(GA->getName() + "." + Twine(FunctionHash))); |
Rong Xu | 0e79f7d | 2016-10-06 20:38:13 +0000 | [diff] [blame] | 507 | GlobalAlias::create(GlobalValue::WeakAnyLinkage, OrigGAName, GA); |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 508 | continue; |
| 509 | } |
| 510 | // Must be a function. |
| 511 | Function *CF = dyn_cast<Function>(CM.second); |
| 512 | assert(CF); |
| 513 | CF->setComdat(NewComdat); |
| 514 | } |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 515 | } |
| 516 | |
| 517 | // Given a CFG E to be instrumented, find which BB to place the instrumented |
| 518 | // code. The function will split the critical edge if necessary. |
| 519 | template <class Edge, class BBInfo> |
| 520 | BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) { |
| 521 | if (E->InMST || E->Removed) |
| 522 | return nullptr; |
| 523 | |
| 524 | BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB); |
| 525 | BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB); |
| 526 | // For a fake edge, instrument the real BB. |
| 527 | if (SrcBB == nullptr) |
| 528 | return DestBB; |
| 529 | if (DestBB == nullptr) |
| 530 | return SrcBB; |
| 531 | |
| 532 | // Instrument the SrcBB if it has a single successor, |
| 533 | // otherwise, the DestBB if this is not a critical edge. |
| 534 | TerminatorInst *TI = SrcBB->getTerminator(); |
| 535 | if (TI->getNumSuccessors() <= 1) |
| 536 | return SrcBB; |
| 537 | if (!E->IsCritical) |
| 538 | return DestBB; |
| 539 | |
| 540 | // For a critical edge, we have to split. Instrument the newly |
| 541 | // created BB. |
| 542 | NumOfPGOSplit++; |
| 543 | DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index << " --> " |
| 544 | << getBBInfo(DestBB).Index << "\n"); |
| 545 | unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB); |
| 546 | BasicBlock *InstrBB = SplitCriticalEdge(TI, SuccNum); |
| 547 | assert(InstrBB && "Critical edge is not split"); |
| 548 | |
| 549 | E->Removed = true; |
| 550 | return InstrBB; |
| 551 | } |
| 552 | |
Rong Xu | ed9fec7 | 2016-01-21 18:11:44 +0000 | [diff] [blame] | 553 | // Visit all edge and instrument the edges not in MST, and do value profiling. |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 554 | // Critical edges will be split. |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 555 | static void instrumentOneFunc( |
| 556 | Function &F, Module *M, BranchProbabilityInfo *BPI, BlockFrequencyInfo *BFI, |
| 557 | std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) { |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 558 | FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, ComdatMembers, true, BPI, |
| 559 | BFI); |
Xinliang David Li | d119761 | 2016-08-01 20:25:06 +0000 | [diff] [blame] | 560 | unsigned NumCounters = FuncInfo.getNumCounters(); |
| 561 | |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 562 | uint32_t I = 0; |
Rong Xu | ed9fec7 | 2016-01-21 18:11:44 +0000 | [diff] [blame] | 563 | Type *I8PtrTy = Type::getInt8PtrTy(M->getContext()); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 564 | for (auto &E : FuncInfo.MST.AllEdges) { |
| 565 | BasicBlock *InstrBB = FuncInfo.getInstrBB(E.get()); |
| 566 | if (!InstrBB) |
| 567 | continue; |
| 568 | |
| 569 | IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt()); |
| 570 | assert(Builder.GetInsertPoint() != InstrBB->end() && |
| 571 | "Cannot get the Instrumentation point"); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 572 | Builder.CreateCall( |
| 573 | Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment), |
| 574 | {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy), |
| 575 | Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters), |
| 576 | Builder.getInt32(I++)}); |
| 577 | } |
Xinliang David Li | 4ca1733 | 2016-09-18 18:34:07 +0000 | [diff] [blame] | 578 | |
| 579 | // Now instrument select instructions: |
| 580 | FuncInfo.SIVisitor.instrumentSelects(F, &I, NumCounters, FuncInfo.FuncNameVar, |
| 581 | FuncInfo.FunctionHash); |
Xinliang David Li | d119761 | 2016-08-01 20:25:06 +0000 | [diff] [blame] | 582 | assert(I == NumCounters); |
Rong Xu | ed9fec7 | 2016-01-21 18:11:44 +0000 | [diff] [blame] | 583 | |
| 584 | if (DisableValueProfiling) |
| 585 | return; |
| 586 | |
| 587 | unsigned NumIndirectCallSites = 0; |
Rong Xu | a3bbf96 | 2017-03-15 18:23:39 +0000 | [diff] [blame^] | 588 | for (auto &I : FuncInfo.ValueSites[IPVK_IndirectCallTarget]) { |
Rong Xu | ed9fec7 | 2016-01-21 18:11:44 +0000 | [diff] [blame] | 589 | CallSite CS(I); |
| 590 | Value *Callee = CS.getCalledValue(); |
| 591 | DEBUG(dbgs() << "Instrument one indirect call: CallSite Index = " |
| 592 | << NumIndirectCallSites << "\n"); |
| 593 | IRBuilder<> Builder(I); |
| 594 | assert(Builder.GetInsertPoint() != I->getParent()->end() && |
| 595 | "Cannot get the Instrumentation point"); |
| 596 | Builder.CreateCall( |
| 597 | Intrinsic::getDeclaration(M, Intrinsic::instrprof_value_profile), |
| 598 | {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy), |
| 599 | Builder.getInt64(FuncInfo.FunctionHash), |
| 600 | Builder.CreatePtrToInt(Callee, Builder.getInt64Ty()), |
Rong Xu | a3bbf96 | 2017-03-15 18:23:39 +0000 | [diff] [blame^] | 601 | Builder.getInt32(IPVK_IndirectCallTarget), |
Rong Xu | ed9fec7 | 2016-01-21 18:11:44 +0000 | [diff] [blame] | 602 | Builder.getInt32(NumIndirectCallSites++)}); |
| 603 | } |
| 604 | NumOfPGOICall += NumIndirectCallSites; |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 605 | } |
| 606 | |
| 607 | // This class represents a CFG edge in profile use compilation. |
| 608 | struct PGOUseEdge : public PGOEdge { |
| 609 | bool CountValid; |
| 610 | uint64_t CountValue; |
| 611 | PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1) |
| 612 | : PGOEdge(Src, Dest, W), CountValid(false), CountValue(0) {} |
| 613 | |
| 614 | // Set edge count value |
| 615 | void setEdgeCount(uint64_t Value) { |
| 616 | CountValue = Value; |
| 617 | CountValid = true; |
| 618 | } |
| 619 | |
| 620 | // Return the information string for this object. |
| 621 | const std::string infoString() const { |
| 622 | if (!CountValid) |
| 623 | return PGOEdge::infoString(); |
Rong Xu | 9e926e8 | 2016-02-29 19:16:04 +0000 | [diff] [blame] | 624 | return (Twine(PGOEdge::infoString()) + " Count=" + Twine(CountValue)) |
| 625 | .str(); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 626 | } |
| 627 | }; |
| 628 | |
| 629 | typedef SmallVector<PGOUseEdge *, 2> DirectEdges; |
| 630 | |
| 631 | // This class stores the auxiliary information for each BB. |
| 632 | struct UseBBInfo : public BBInfo { |
| 633 | uint64_t CountValue; |
| 634 | bool CountValid; |
| 635 | int32_t UnknownCountInEdge; |
| 636 | int32_t UnknownCountOutEdge; |
| 637 | DirectEdges InEdges; |
| 638 | DirectEdges OutEdges; |
| 639 | UseBBInfo(unsigned IX) |
| 640 | : BBInfo(IX), CountValue(0), CountValid(false), UnknownCountInEdge(0), |
| 641 | UnknownCountOutEdge(0) {} |
| 642 | UseBBInfo(unsigned IX, uint64_t C) |
| 643 | : BBInfo(IX), CountValue(C), CountValid(true), UnknownCountInEdge(0), |
| 644 | UnknownCountOutEdge(0) {} |
| 645 | |
| 646 | // Set the profile count value for this BB. |
| 647 | void setBBInfoCount(uint64_t Value) { |
| 648 | CountValue = Value; |
| 649 | CountValid = true; |
| 650 | } |
| 651 | |
| 652 | // Return the information string of this object. |
| 653 | const std::string infoString() const { |
| 654 | if (!CountValid) |
| 655 | return BBInfo::infoString(); |
| 656 | return (Twine(BBInfo::infoString()) + " Count=" + Twine(CountValue)).str(); |
| 657 | } |
| 658 | }; |
| 659 | |
| 660 | // Sum up the count values for all the edges. |
| 661 | static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) { |
| 662 | uint64_t Total = 0; |
| 663 | for (auto &E : Edges) { |
| 664 | if (E->Removed) |
| 665 | continue; |
| 666 | Total += E->CountValue; |
| 667 | } |
| 668 | return Total; |
| 669 | } |
| 670 | |
| 671 | class PGOUseFunc { |
Rong Xu | 6090afd | 2016-03-28 17:08:56 +0000 | [diff] [blame] | 672 | public: |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 673 | PGOUseFunc(Function &Func, Module *Modu, |
| 674 | std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers, |
| 675 | BranchProbabilityInfo *BPI = nullptr, |
Rong Xu | 6090afd | 2016-03-28 17:08:56 +0000 | [diff] [blame] | 676 | BlockFrequencyInfo *BFI = nullptr) |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 677 | : F(Func), M(Modu), FuncInfo(Func, ComdatMembers, false, BPI, BFI), |
Rong Xu | 33308f9 | 2016-10-25 21:47:24 +0000 | [diff] [blame] | 678 | CountPosition(0), ProfileCountSize(0), FreqAttr(FFA_Normal) {} |
Rong Xu | 6090afd | 2016-03-28 17:08:56 +0000 | [diff] [blame] | 679 | |
| 680 | // Read counts for the instrumented BB from profile. |
| 681 | bool readCounters(IndexedInstrProfReader *PGOReader); |
| 682 | |
| 683 | // Populate the counts for all BBs. |
| 684 | void populateCounters(); |
| 685 | |
| 686 | // Set the branch weights based on the count values. |
| 687 | void setBranchWeights(); |
| 688 | |
Rong Xu | a3bbf96 | 2017-03-15 18:23:39 +0000 | [diff] [blame^] | 689 | // Annotate the value profile call sites all all value kind. |
| 690 | void annotateValueSites(); |
| 691 | |
| 692 | // Annotate the value profile call sites for one value kind. |
| 693 | void annotateValueSites(uint32_t Kind); |
Rong Xu | 6090afd | 2016-03-28 17:08:56 +0000 | [diff] [blame] | 694 | |
Sean Silva | 9dd4b5c | 2016-05-28 03:56:25 +0000 | [diff] [blame] | 695 | // The hotness of the function from the profile count. |
| 696 | enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot }; |
| 697 | |
| 698 | // Return the function hotness from the profile. |
| 699 | FuncFreqAttr getFuncFreqAttr() const { return FreqAttr; } |
| 700 | |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 701 | // Return the function hash. |
| 702 | uint64_t getFuncHash() const { return FuncInfo.FunctionHash; } |
Easwaran Raman | 5fe04a1 | 2016-05-26 22:57:11 +0000 | [diff] [blame] | 703 | // Return the profile record for this function; |
| 704 | InstrProfRecord &getProfileRecord() { return ProfileRecord; } |
| 705 | |
Xinliang David Li | 4ca1733 | 2016-09-18 18:34:07 +0000 | [diff] [blame] | 706 | // Return the auxiliary BB information. |
| 707 | UseBBInfo &getBBInfo(const BasicBlock *BB) const { |
| 708 | return FuncInfo.getBBInfo(BB); |
| 709 | } |
| 710 | |
Rong Xu | a5b5745 | 2016-12-02 19:10:29 +0000 | [diff] [blame] | 711 | // Return the auxiliary BB information if available. |
| 712 | UseBBInfo *findBBInfo(const BasicBlock *BB) const { |
| 713 | return FuncInfo.findBBInfo(BB); |
| 714 | } |
| 715 | |
Xinliang David Li | d289e45 | 2017-01-27 19:06:25 +0000 | [diff] [blame] | 716 | Function &getFunc() const { return F; } |
| 717 | |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 718 | private: |
| 719 | Function &F; |
| 720 | Module *M; |
| 721 | // This member stores the shared information with class PGOGenFunc. |
| 722 | FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo; |
| 723 | |
Sean Silva | 9dd4b5c | 2016-05-28 03:56:25 +0000 | [diff] [blame] | 724 | // The maximum count value in the profile. This is only used in PGO use |
| 725 | // compilation. |
| 726 | uint64_t ProgramMaxCount; |
| 727 | |
Rong Xu | 33308f9 | 2016-10-25 21:47:24 +0000 | [diff] [blame] | 728 | // Position of counter that remains to be read. |
| 729 | uint32_t CountPosition; |
| 730 | |
| 731 | // Total size of the profile count for this function. |
| 732 | uint32_t ProfileCountSize; |
| 733 | |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 734 | // ProfileRecord for this function. |
| 735 | InstrProfRecord ProfileRecord; |
| 736 | |
Sean Silva | 9dd4b5c | 2016-05-28 03:56:25 +0000 | [diff] [blame] | 737 | // Function hotness info derived from profile. |
| 738 | FuncFreqAttr FreqAttr; |
| 739 | |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 740 | // Find the Instrumented BB and set the value. |
| 741 | void setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile); |
| 742 | |
| 743 | // Set the edge counter value for the unknown edge -- there should be only |
| 744 | // one unknown edge. |
| 745 | void setEdgeCount(DirectEdges &Edges, uint64_t Value); |
| 746 | |
| 747 | // Return FuncName string; |
| 748 | const std::string getFuncName() const { return FuncInfo.FuncName; } |
Sean Silva | 9dd4b5c | 2016-05-28 03:56:25 +0000 | [diff] [blame] | 749 | |
| 750 | // Set the hot/cold inline hints based on the count values. |
| 751 | // FIXME: This function should be removed once the functionality in |
| 752 | // the inliner is implemented. |
| 753 | void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) { |
| 754 | if (ProgramMaxCount == 0) |
| 755 | return; |
| 756 | // Threshold of the hot functions. |
| 757 | const BranchProbability HotFunctionThreshold(1, 100); |
| 758 | // Threshold of the cold functions. |
| 759 | const BranchProbability ColdFunctionThreshold(2, 10000); |
| 760 | if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount)) |
| 761 | FreqAttr = FFA_Hot; |
| 762 | else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount)) |
| 763 | FreqAttr = FFA_Cold; |
| 764 | } |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 765 | }; |
| 766 | |
| 767 | // Visit all the edges and assign the count value for the instrumented |
| 768 | // edges and the BB. |
| 769 | void PGOUseFunc::setInstrumentedCounts( |
| 770 | const std::vector<uint64_t> &CountFromProfile) { |
| 771 | |
Xinliang David Li | d119761 | 2016-08-01 20:25:06 +0000 | [diff] [blame] | 772 | assert(FuncInfo.getNumCounters() == CountFromProfile.size()); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 773 | // Use a worklist as we will update the vector during the iteration. |
| 774 | std::vector<PGOUseEdge *> WorkList; |
| 775 | for (auto &E : FuncInfo.MST.AllEdges) |
| 776 | WorkList.push_back(E.get()); |
| 777 | |
| 778 | uint32_t I = 0; |
| 779 | for (auto &E : WorkList) { |
| 780 | BasicBlock *InstrBB = FuncInfo.getInstrBB(E); |
| 781 | if (!InstrBB) |
| 782 | continue; |
| 783 | uint64_t CountValue = CountFromProfile[I++]; |
| 784 | if (!E->Removed) { |
| 785 | getBBInfo(InstrBB).setBBInfoCount(CountValue); |
| 786 | E->setEdgeCount(CountValue); |
| 787 | continue; |
| 788 | } |
| 789 | |
| 790 | // Need to add two new edges. |
| 791 | BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB); |
| 792 | BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB); |
| 793 | // Add new edge of SrcBB->InstrBB. |
| 794 | PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0); |
| 795 | NewEdge.setEdgeCount(CountValue); |
| 796 | // Add new edge of InstrBB->DestBB. |
| 797 | PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0); |
| 798 | NewEdge1.setEdgeCount(CountValue); |
| 799 | NewEdge1.InMST = true; |
| 800 | getBBInfo(InstrBB).setBBInfoCount(CountValue); |
| 801 | } |
Rong Xu | 0a2a131 | 2017-03-09 19:08:55 +0000 | [diff] [blame] | 802 | ProfileCountSize = CountFromProfile.size(); |
Rong Xu | 33308f9 | 2016-10-25 21:47:24 +0000 | [diff] [blame] | 803 | CountPosition = I; |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 804 | } |
| 805 | |
| 806 | // Set the count value for the unknown edge. There should be one and only one |
| 807 | // unknown edge in Edges vector. |
| 808 | void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) { |
| 809 | for (auto &E : Edges) { |
| 810 | if (E->CountValid) |
| 811 | continue; |
| 812 | E->setEdgeCount(Value); |
| 813 | |
| 814 | getBBInfo(E->SrcBB).UnknownCountOutEdge--; |
| 815 | getBBInfo(E->DestBB).UnknownCountInEdge--; |
| 816 | return; |
| 817 | } |
| 818 | llvm_unreachable("Cannot find the unknown count edge"); |
| 819 | } |
| 820 | |
| 821 | // Read the profile from ProfileFileName and assign the value to the |
| 822 | // instrumented BB and the edges. This function also updates ProgramMaxCount. |
| 823 | // Return true if the profile are successfully read, and false on errors. |
| 824 | bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader) { |
| 825 | auto &Ctx = M->getContext(); |
Vedant Kumar | 9152fd1 | 2016-05-19 03:54:45 +0000 | [diff] [blame] | 826 | Expected<InstrProfRecord> Result = |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 827 | PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash); |
Vedant Kumar | 9152fd1 | 2016-05-19 03:54:45 +0000 | [diff] [blame] | 828 | if (Error E = Result.takeError()) { |
| 829 | handleAllErrors(std::move(E), [&](const InstrProfError &IPE) { |
| 830 | auto Err = IPE.get(); |
| 831 | bool SkipWarning = false; |
| 832 | if (Err == instrprof_error::unknown_function) { |
| 833 | NumOfPGOMissing++; |
Xinliang David Li | 76a0108 | 2016-08-11 05:09:30 +0000 | [diff] [blame] | 834 | SkipWarning = !PGOWarnMissing; |
Vedant Kumar | 9152fd1 | 2016-05-19 03:54:45 +0000 | [diff] [blame] | 835 | } else if (Err == instrprof_error::hash_mismatch || |
| 836 | Err == instrprof_error::malformed) { |
| 837 | NumOfPGOMismatch++; |
Rong Xu | 20f5df1 | 2017-01-11 20:19:41 +0000 | [diff] [blame] | 838 | SkipWarning = |
| 839 | NoPGOWarnMismatch || |
| 840 | (NoPGOWarnMismatchComdat && |
| 841 | (F.hasComdat() || |
| 842 | F.getLinkage() == GlobalValue::AvailableExternallyLinkage)); |
Vedant Kumar | 9152fd1 | 2016-05-19 03:54:45 +0000 | [diff] [blame] | 843 | } |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 844 | |
Vedant Kumar | 9152fd1 | 2016-05-19 03:54:45 +0000 | [diff] [blame] | 845 | if (SkipWarning) |
| 846 | return; |
| 847 | |
| 848 | std::string Msg = IPE.message() + std::string(" ") + F.getName().str(); |
| 849 | Ctx.diagnose( |
| 850 | DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning)); |
| 851 | }); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 852 | return false; |
| 853 | } |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 854 | ProfileRecord = std::move(Result.get()); |
| 855 | std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts; |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 856 | |
| 857 | NumOfPGOFunc++; |
| 858 | DEBUG(dbgs() << CountFromProfile.size() << " counts\n"); |
| 859 | uint64_t ValueSum = 0; |
| 860 | for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) { |
| 861 | DEBUG(dbgs() << " " << I << ": " << CountFromProfile[I] << "\n"); |
| 862 | ValueSum += CountFromProfile[I]; |
| 863 | } |
| 864 | |
| 865 | DEBUG(dbgs() << "SUM = " << ValueSum << "\n"); |
| 866 | |
| 867 | getBBInfo(nullptr).UnknownCountOutEdge = 2; |
| 868 | getBBInfo(nullptr).UnknownCountInEdge = 2; |
| 869 | |
| 870 | setInstrumentedCounts(CountFromProfile); |
Sean Silva | 9dd4b5c | 2016-05-28 03:56:25 +0000 | [diff] [blame] | 871 | ProgramMaxCount = PGOReader->getMaximumFunctionCount(); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 872 | return true; |
| 873 | } |
| 874 | |
| 875 | // Populate the counters from instrumented BBs to all BBs. |
| 876 | // In the end of this operation, all BBs should have a valid count value. |
| 877 | void PGOUseFunc::populateCounters() { |
| 878 | // First set up Count variable for all BBs. |
| 879 | for (auto &E : FuncInfo.MST.AllEdges) { |
| 880 | if (E->Removed) |
| 881 | continue; |
| 882 | |
| 883 | const BasicBlock *SrcBB = E->SrcBB; |
| 884 | const BasicBlock *DestBB = E->DestBB; |
| 885 | UseBBInfo &SrcInfo = getBBInfo(SrcBB); |
| 886 | UseBBInfo &DestInfo = getBBInfo(DestBB); |
| 887 | SrcInfo.OutEdges.push_back(E.get()); |
| 888 | DestInfo.InEdges.push_back(E.get()); |
| 889 | SrcInfo.UnknownCountOutEdge++; |
| 890 | DestInfo.UnknownCountInEdge++; |
| 891 | |
| 892 | if (!E->CountValid) |
| 893 | continue; |
| 894 | DestInfo.UnknownCountInEdge--; |
| 895 | SrcInfo.UnknownCountOutEdge--; |
| 896 | } |
| 897 | |
| 898 | bool Changes = true; |
| 899 | unsigned NumPasses = 0; |
| 900 | while (Changes) { |
| 901 | NumPasses++; |
| 902 | Changes = false; |
| 903 | |
| 904 | // For efficient traversal, it's better to start from the end as most |
| 905 | // of the instrumented edges are at the end. |
| 906 | for (auto &BB : reverse(F)) { |
Rong Xu | a5b5745 | 2016-12-02 19:10:29 +0000 | [diff] [blame] | 907 | UseBBInfo *Count = findBBInfo(&BB); |
| 908 | if (Count == nullptr) |
| 909 | continue; |
| 910 | if (!Count->CountValid) { |
| 911 | if (Count->UnknownCountOutEdge == 0) { |
| 912 | Count->CountValue = sumEdgeCount(Count->OutEdges); |
| 913 | Count->CountValid = true; |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 914 | Changes = true; |
Rong Xu | a5b5745 | 2016-12-02 19:10:29 +0000 | [diff] [blame] | 915 | } else if (Count->UnknownCountInEdge == 0) { |
| 916 | Count->CountValue = sumEdgeCount(Count->InEdges); |
| 917 | Count->CountValid = true; |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 918 | Changes = true; |
| 919 | } |
| 920 | } |
Rong Xu | a5b5745 | 2016-12-02 19:10:29 +0000 | [diff] [blame] | 921 | if (Count->CountValid) { |
| 922 | if (Count->UnknownCountOutEdge == 1) { |
Rong Xu | 51a1e3c | 2016-12-13 06:41:14 +0000 | [diff] [blame] | 923 | uint64_t Total = 0; |
| 924 | uint64_t OutSum = sumEdgeCount(Count->OutEdges); |
| 925 | // If the one of the successor block can early terminate (no-return), |
| 926 | // we can end up with situation where out edge sum count is larger as |
| 927 | // the source BB's count is collected by a post-dominated block. |
| 928 | if (Count->CountValue > OutSum) |
| 929 | Total = Count->CountValue - OutSum; |
Rong Xu | a5b5745 | 2016-12-02 19:10:29 +0000 | [diff] [blame] | 930 | setEdgeCount(Count->OutEdges, Total); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 931 | Changes = true; |
| 932 | } |
Rong Xu | a5b5745 | 2016-12-02 19:10:29 +0000 | [diff] [blame] | 933 | if (Count->UnknownCountInEdge == 1) { |
Rong Xu | 51a1e3c | 2016-12-13 06:41:14 +0000 | [diff] [blame] | 934 | uint64_t Total = 0; |
| 935 | uint64_t InSum = sumEdgeCount(Count->InEdges); |
| 936 | if (Count->CountValue > InSum) |
| 937 | Total = Count->CountValue - InSum; |
Rong Xu | a5b5745 | 2016-12-02 19:10:29 +0000 | [diff] [blame] | 938 | setEdgeCount(Count->InEdges, Total); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 939 | Changes = true; |
| 940 | } |
| 941 | } |
| 942 | } |
| 943 | } |
| 944 | |
| 945 | DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n"); |
Sean Silva | 8c7e121 | 2016-05-28 04:19:45 +0000 | [diff] [blame] | 946 | #ifndef NDEBUG |
Sean Silva | 9dd4b5c | 2016-05-28 03:56:25 +0000 | [diff] [blame] | 947 | // Assert every BB has a valid counter. |
Rong Xu | a5b5745 | 2016-12-02 19:10:29 +0000 | [diff] [blame] | 948 | for (auto &BB : F) { |
| 949 | auto BI = findBBInfo(&BB); |
| 950 | if (BI == nullptr) |
| 951 | continue; |
| 952 | assert(BI->CountValid && "BB count is not valid"); |
| 953 | } |
Sean Silva | 8c7e121 | 2016-05-28 04:19:45 +0000 | [diff] [blame] | 954 | #endif |
Sean Silva | 9dd4b5c | 2016-05-28 03:56:25 +0000 | [diff] [blame] | 955 | uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue; |
Sean Silva | 02b9d89 | 2016-05-28 04:05:36 +0000 | [diff] [blame] | 956 | F.setEntryCount(FuncEntryCount); |
Sean Silva | 9dd4b5c | 2016-05-28 03:56:25 +0000 | [diff] [blame] | 957 | uint64_t FuncMaxCount = FuncEntryCount; |
Rong Xu | a5b5745 | 2016-12-02 19:10:29 +0000 | [diff] [blame] | 958 | for (auto &BB : F) { |
| 959 | auto BI = findBBInfo(&BB); |
| 960 | if (BI == nullptr) |
| 961 | continue; |
| 962 | FuncMaxCount = std::max(FuncMaxCount, BI->CountValue); |
| 963 | } |
Sean Silva | 9dd4b5c | 2016-05-28 03:56:25 +0000 | [diff] [blame] | 964 | markFunctionAttributes(FuncEntryCount, FuncMaxCount); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 965 | |
Rong Xu | 33308f9 | 2016-10-25 21:47:24 +0000 | [diff] [blame] | 966 | // Now annotate select instructions |
| 967 | FuncInfo.SIVisitor.annotateSelects(F, this, &CountPosition); |
| 968 | assert(CountPosition == ProfileCountSize); |
| 969 | |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 970 | DEBUG(FuncInfo.dumpInfo("after reading profile.")); |
| 971 | } |
| 972 | |
Xinliang David Li | 4ca1733 | 2016-09-18 18:34:07 +0000 | [diff] [blame] | 973 | static void setProfMetadata(Module *M, Instruction *TI, |
Xinliang David Li | 63248ab | 2016-08-19 06:31:45 +0000 | [diff] [blame] | 974 | ArrayRef<uint64_t> EdgeCounts, uint64_t MaxCount) { |
Xinliang David Li | 2c93368 | 2016-08-19 05:31:33 +0000 | [diff] [blame] | 975 | MDBuilder MDB(M->getContext()); |
| 976 | assert(MaxCount > 0 && "Bad max count"); |
| 977 | uint64_t Scale = calculateCountScale(MaxCount); |
| 978 | SmallVector<unsigned, 4> Weights; |
| 979 | for (const auto &ECI : EdgeCounts) |
| 980 | Weights.push_back(scaleBranchCount(ECI, Scale)); |
| 981 | |
| 982 | DEBUG(dbgs() << "Weight is: "; |
Rong Xu | 0a2a131 | 2017-03-09 19:08:55 +0000 | [diff] [blame] | 983 | for (const auto &W : Weights) { dbgs() << W << " "; } |
Xinliang David Li | 2c93368 | 2016-08-19 05:31:33 +0000 | [diff] [blame] | 984 | dbgs() << "\n";); |
| 985 | TI->setMetadata(llvm::LLVMContext::MD_prof, MDB.createBranchWeights(Weights)); |
| 986 | } |
| 987 | |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 988 | // Assign the scaled count values to the BB with multiple out edges. |
| 989 | void PGOUseFunc::setBranchWeights() { |
| 990 | // Generate MD_prof metadata for every branch instruction. |
| 991 | DEBUG(dbgs() << "\nSetting branch weights.\n"); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 992 | for (auto &BB : F) { |
| 993 | TerminatorInst *TI = BB.getTerminator(); |
| 994 | if (TI->getNumSuccessors() < 2) |
| 995 | continue; |
| 996 | if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI)) |
| 997 | continue; |
| 998 | if (getBBInfo(&BB).CountValue == 0) |
| 999 | continue; |
| 1000 | |
| 1001 | // We have a non-zero Branch BB. |
| 1002 | const UseBBInfo &BBCountInfo = getBBInfo(&BB); |
| 1003 | unsigned Size = BBCountInfo.OutEdges.size(); |
Xinliang David Li | 63248ab | 2016-08-19 06:31:45 +0000 | [diff] [blame] | 1004 | SmallVector<uint64_t, 2> EdgeCounts(Size, 0); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 1005 | uint64_t MaxCount = 0; |
| 1006 | for (unsigned s = 0; s < Size; s++) { |
| 1007 | const PGOUseEdge *E = BBCountInfo.OutEdges[s]; |
| 1008 | const BasicBlock *SrcBB = E->SrcBB; |
| 1009 | const BasicBlock *DestBB = E->DestBB; |
Eugene Zelenko | 6ac3f73 | 2016-01-26 18:48:36 +0000 | [diff] [blame] | 1010 | if (DestBB == nullptr) |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 1011 | continue; |
| 1012 | unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB); |
| 1013 | uint64_t EdgeCount = E->CountValue; |
| 1014 | if (EdgeCount > MaxCount) |
| 1015 | MaxCount = EdgeCount; |
| 1016 | EdgeCounts[SuccNum] = EdgeCount; |
| 1017 | } |
Xinliang David Li | 2c93368 | 2016-08-19 05:31:33 +0000 | [diff] [blame] | 1018 | setProfMetadata(M, TI, EdgeCounts, MaxCount); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 1019 | } |
| 1020 | } |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 1021 | |
Xinliang David Li | 4ca1733 | 2016-09-18 18:34:07 +0000 | [diff] [blame] | 1022 | void SelectInstVisitor::instrumentOneSelectInst(SelectInst &SI) { |
| 1023 | Module *M = F.getParent(); |
| 1024 | IRBuilder<> Builder(&SI); |
| 1025 | Type *Int64Ty = Builder.getInt64Ty(); |
| 1026 | Type *I8PtrTy = Builder.getInt8PtrTy(); |
| 1027 | auto *Step = Builder.CreateZExt(SI.getCondition(), Int64Ty); |
| 1028 | Builder.CreateCall( |
| 1029 | Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment_step), |
| 1030 | {llvm::ConstantExpr::getBitCast(FuncNameVar, I8PtrTy), |
Rong Xu | 0a2a131 | 2017-03-09 19:08:55 +0000 | [diff] [blame] | 1031 | Builder.getInt64(FuncHash), Builder.getInt32(TotalNumCtrs), |
| 1032 | Builder.getInt32(*CurCtrIdx), Step}); |
Xinliang David Li | 4ca1733 | 2016-09-18 18:34:07 +0000 | [diff] [blame] | 1033 | ++(*CurCtrIdx); |
| 1034 | } |
| 1035 | |
| 1036 | void SelectInstVisitor::annotateOneSelectInst(SelectInst &SI) { |
| 1037 | std::vector<uint64_t> &CountFromProfile = UseFunc->getProfileRecord().Counts; |
| 1038 | assert(*CurCtrIdx < CountFromProfile.size() && |
| 1039 | "Out of bound access of counters"); |
| 1040 | uint64_t SCounts[2]; |
| 1041 | SCounts[0] = CountFromProfile[*CurCtrIdx]; // True count |
| 1042 | ++(*CurCtrIdx); |
Rong Xu | a5b5745 | 2016-12-02 19:10:29 +0000 | [diff] [blame] | 1043 | uint64_t TotalCount = 0; |
| 1044 | auto BI = UseFunc->findBBInfo(SI.getParent()); |
| 1045 | if (BI != nullptr) |
| 1046 | TotalCount = BI->CountValue; |
Xinliang David Li | 4ca1733 | 2016-09-18 18:34:07 +0000 | [diff] [blame] | 1047 | // False Count |
| 1048 | SCounts[1] = (TotalCount > SCounts[0] ? TotalCount - SCounts[0] : 0); |
| 1049 | uint64_t MaxCount = std::max(SCounts[0], SCounts[1]); |
Xinliang David Li | c736828 | 2016-09-20 20:20:01 +0000 | [diff] [blame] | 1050 | if (MaxCount) |
| 1051 | setProfMetadata(F.getParent(), &SI, SCounts, MaxCount); |
Xinliang David Li | 4ca1733 | 2016-09-18 18:34:07 +0000 | [diff] [blame] | 1052 | } |
| 1053 | |
| 1054 | void SelectInstVisitor::visitSelectInst(SelectInst &SI) { |
| 1055 | if (!PGOInstrSelect) |
| 1056 | return; |
| 1057 | // FIXME: do not handle this yet. |
| 1058 | if (SI.getCondition()->getType()->isVectorTy()) |
| 1059 | return; |
| 1060 | |
| 1061 | NSIs++; |
| 1062 | switch (Mode) { |
| 1063 | case VM_counting: |
| 1064 | return; |
| 1065 | case VM_instrument: |
| 1066 | instrumentOneSelectInst(SI); |
Simon Pilgrim | f33a6b7 | 2016-09-18 21:08:35 +0000 | [diff] [blame] | 1067 | return; |
Xinliang David Li | 4ca1733 | 2016-09-18 18:34:07 +0000 | [diff] [blame] | 1068 | case VM_annotate: |
| 1069 | annotateOneSelectInst(SI); |
Simon Pilgrim | f33a6b7 | 2016-09-18 21:08:35 +0000 | [diff] [blame] | 1070 | return; |
Xinliang David Li | 4ca1733 | 2016-09-18 18:34:07 +0000 | [diff] [blame] | 1071 | } |
Simon Pilgrim | f33a6b7 | 2016-09-18 21:08:35 +0000 | [diff] [blame] | 1072 | |
| 1073 | llvm_unreachable("Unknown visiting mode"); |
Xinliang David Li | 4ca1733 | 2016-09-18 18:34:07 +0000 | [diff] [blame] | 1074 | } |
| 1075 | |
Rong Xu | a3bbf96 | 2017-03-15 18:23:39 +0000 | [diff] [blame^] | 1076 | // Traverse all valuesites and annotate the instructions for all value kind. |
| 1077 | void PGOUseFunc::annotateValueSites() { |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 1078 | if (DisableValueProfiling) |
| 1079 | return; |
| 1080 | |
Rong Xu | 8e8fe85 | 2016-04-01 16:43:30 +0000 | [diff] [blame] | 1081 | // Create the PGOFuncName meta data. |
Rong Xu | f8f051c | 2016-04-22 21:00:17 +0000 | [diff] [blame] | 1082 | createPGOFuncNameMetadata(F, FuncInfo.FuncName); |
Rong Xu | b534166 | 2016-03-30 18:37:52 +0000 | [diff] [blame] | 1083 | |
Rong Xu | a3bbf96 | 2017-03-15 18:23:39 +0000 | [diff] [blame^] | 1084 | for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) |
| 1085 | annotateValueSites(Kind); |
| 1086 | } |
| 1087 | |
| 1088 | // Annotate the instructions for a specific value kind. |
| 1089 | void PGOUseFunc::annotateValueSites(uint32_t Kind) { |
| 1090 | unsigned ValueSiteIndex = 0; |
| 1091 | auto &ValueSites = FuncInfo.ValueSites[Kind]; |
| 1092 | unsigned NumValueSites = ProfileRecord.getNumValueSites(Kind); |
| 1093 | if (NumValueSites != ValueSites.size()) { |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 1094 | auto &Ctx = M->getContext(); |
Rong Xu | a3bbf96 | 2017-03-15 18:23:39 +0000 | [diff] [blame^] | 1095 | Ctx.diagnose(DiagnosticInfoPGOProfile( |
| 1096 | M->getName().data(), |
| 1097 | Twine("Inconsistent number of value sites for kind = ") + Twine(Kind) + |
| 1098 | " in " + F.getName().str(), |
| 1099 | DS_Warning)); |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 1100 | return; |
| 1101 | } |
| 1102 | |
Rong Xu | a3bbf96 | 2017-03-15 18:23:39 +0000 | [diff] [blame^] | 1103 | for (auto &I : ValueSites) { |
| 1104 | DEBUG(dbgs() << "Read one value site profile (kind = " << Kind |
| 1105 | << "): Index = " << ValueSiteIndex << " out of " |
| 1106 | << NumValueSites << "\n"); |
| 1107 | annotateValueSite(*M, *I, ProfileRecord, |
| 1108 | static_cast<InstrProfValueKind>(Kind), ValueSiteIndex, |
| 1109 | MaxNumAnnotations); |
| 1110 | ValueSiteIndex++; |
Rong Xu | 13b01dc | 2016-02-10 18:24:45 +0000 | [diff] [blame] | 1111 | } |
| 1112 | } |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 1113 | } // end anonymous namespace |
| 1114 | |
Xinliang David Li | d382e9d | 2016-07-22 04:46:56 +0000 | [diff] [blame] | 1115 | // Create a COMDAT variable INSTR_PROF_RAW_VERSION_VAR to make the runtime |
Rong Xu | 33c76c0 | 2016-02-10 17:18:30 +0000 | [diff] [blame] | 1116 | // aware this is an ir_level profile so it can set the version flag. |
| 1117 | static void createIRLevelProfileFlagVariable(Module &M) { |
| 1118 | Type *IntTy64 = Type::getInt64Ty(M.getContext()); |
| 1119 | uint64_t ProfileVersion = (INSTR_PROF_RAW_VERSION | VARIANT_MASK_IR_PROF); |
Rong Xu | 9e926e8 | 2016-02-29 19:16:04 +0000 | [diff] [blame] | 1120 | auto IRLevelVersionVariable = new GlobalVariable( |
| 1121 | M, IntTy64, true, GlobalVariable::ExternalLinkage, |
| 1122 | Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)), |
Xinliang David Li | d382e9d | 2016-07-22 04:46:56 +0000 | [diff] [blame] | 1123 | INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR)); |
Rong Xu | 33c76c0 | 2016-02-10 17:18:30 +0000 | [diff] [blame] | 1124 | IRLevelVersionVariable->setVisibility(GlobalValue::DefaultVisibility); |
| 1125 | Triple TT(M.getTargetTriple()); |
Xinliang David Li | 11c849c | 2016-05-27 16:22:03 +0000 | [diff] [blame] | 1126 | if (!TT.supportsCOMDAT()) |
Rong Xu | ca28a0a | 2016-05-11 00:31:59 +0000 | [diff] [blame] | 1127 | IRLevelVersionVariable->setLinkage(GlobalValue::WeakAnyLinkage); |
Rong Xu | 33c76c0 | 2016-02-10 17:18:30 +0000 | [diff] [blame] | 1128 | else |
Rong Xu | 9e926e8 | 2016-02-29 19:16:04 +0000 | [diff] [blame] | 1129 | IRLevelVersionVariable->setComdat(M.getOrInsertComdat( |
Xinliang David Li | d382e9d | 2016-07-22 04:46:56 +0000 | [diff] [blame] | 1130 | StringRef(INSTR_PROF_QUOTE(INSTR_PROF_RAW_VERSION_VAR)))); |
Rong Xu | 33c76c0 | 2016-02-10 17:18:30 +0000 | [diff] [blame] | 1131 | } |
| 1132 | |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 1133 | // Collect the set of members for each Comdat in module M and store |
| 1134 | // in ComdatMembers. |
| 1135 | static void collectComdatMembers( |
| 1136 | Module &M, |
| 1137 | std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) { |
| 1138 | if (!DoComdatRenaming) |
| 1139 | return; |
| 1140 | for (Function &F : M) |
| 1141 | if (Comdat *C = F.getComdat()) |
| 1142 | ComdatMembers.insert(std::make_pair(C, &F)); |
| 1143 | for (GlobalVariable &GV : M.globals()) |
| 1144 | if (Comdat *C = GV.getComdat()) |
| 1145 | ComdatMembers.insert(std::make_pair(C, &GV)); |
| 1146 | for (GlobalAlias &GA : M.aliases()) |
| 1147 | if (Comdat *C = GA.getComdat()) |
| 1148 | ComdatMembers.insert(std::make_pair(C, &GA)); |
| 1149 | } |
| 1150 | |
Xinliang David Li | 5ad7c82 | 2016-05-02 20:33:59 +0000 | [diff] [blame] | 1151 | static bool InstrumentAllFunctions( |
Xinliang David Li | dfa21c3 | 2016-05-09 21:37:12 +0000 | [diff] [blame] | 1152 | Module &M, function_ref<BranchProbabilityInfo *(Function &)> LookupBPI, |
| 1153 | function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) { |
Rong Xu | 33c76c0 | 2016-02-10 17:18:30 +0000 | [diff] [blame] | 1154 | createIRLevelProfileFlagVariable(M); |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 1155 | std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers; |
| 1156 | collectComdatMembers(M, ComdatMembers); |
| 1157 | |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 1158 | for (auto &F : M) { |
| 1159 | if (F.isDeclaration()) |
| 1160 | continue; |
Xinliang David Li | dfa21c3 | 2016-05-09 21:37:12 +0000 | [diff] [blame] | 1161 | auto *BPI = LookupBPI(F); |
| 1162 | auto *BFI = LookupBFI(F); |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 1163 | instrumentOneFunc(F, &M, BPI, BFI, ComdatMembers); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 1164 | } |
| 1165 | return true; |
| 1166 | } |
| 1167 | |
Xinliang David Li | 8aebf44 | 2016-05-06 05:49:19 +0000 | [diff] [blame] | 1168 | bool PGOInstrumentationGenLegacyPass::runOnModule(Module &M) { |
Xinliang David Li | 5ad7c82 | 2016-05-02 20:33:59 +0000 | [diff] [blame] | 1169 | if (skipModule(M)) |
| 1170 | return false; |
| 1171 | |
Xinliang David Li | dfa21c3 | 2016-05-09 21:37:12 +0000 | [diff] [blame] | 1172 | auto LookupBPI = [this](Function &F) { |
| 1173 | return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI(); |
Xinliang David Li | 5ad7c82 | 2016-05-02 20:33:59 +0000 | [diff] [blame] | 1174 | }; |
Xinliang David Li | dfa21c3 | 2016-05-09 21:37:12 +0000 | [diff] [blame] | 1175 | auto LookupBFI = [this](Function &F) { |
| 1176 | return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI(); |
Xinliang David Li | 5ad7c82 | 2016-05-02 20:33:59 +0000 | [diff] [blame] | 1177 | }; |
| 1178 | return InstrumentAllFunctions(M, LookupBPI, LookupBFI); |
| 1179 | } |
| 1180 | |
Xinliang David Li | 8aebf44 | 2016-05-06 05:49:19 +0000 | [diff] [blame] | 1181 | PreservedAnalyses PGOInstrumentationGen::run(Module &M, |
Sean Silva | fd03ac6 | 2016-08-09 00:28:38 +0000 | [diff] [blame] | 1182 | ModuleAnalysisManager &AM) { |
Xinliang David Li | 8aebf44 | 2016-05-06 05:49:19 +0000 | [diff] [blame] | 1183 | |
| 1184 | auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); |
Xinliang David Li | dfa21c3 | 2016-05-09 21:37:12 +0000 | [diff] [blame] | 1185 | auto LookupBPI = [&FAM](Function &F) { |
| 1186 | return &FAM.getResult<BranchProbabilityAnalysis>(F); |
Xinliang David Li | 8aebf44 | 2016-05-06 05:49:19 +0000 | [diff] [blame] | 1187 | }; |
| 1188 | |
Xinliang David Li | dfa21c3 | 2016-05-09 21:37:12 +0000 | [diff] [blame] | 1189 | auto LookupBFI = [&FAM](Function &F) { |
| 1190 | return &FAM.getResult<BlockFrequencyAnalysis>(F); |
Xinliang David Li | 8aebf44 | 2016-05-06 05:49:19 +0000 | [diff] [blame] | 1191 | }; |
| 1192 | |
| 1193 | if (!InstrumentAllFunctions(M, LookupBPI, LookupBFI)) |
| 1194 | return PreservedAnalyses::all(); |
| 1195 | |
| 1196 | return PreservedAnalyses::none(); |
| 1197 | } |
| 1198 | |
Xinliang David Li | da19558 | 2016-05-10 21:59:52 +0000 | [diff] [blame] | 1199 | static bool annotateAllFunctions( |
| 1200 | Module &M, StringRef ProfileFileName, |
| 1201 | function_ref<BranchProbabilityInfo *(Function &)> LookupBPI, |
Xinliang David Li | dfa21c3 | 2016-05-09 21:37:12 +0000 | [diff] [blame] | 1202 | function_ref<BlockFrequencyInfo *(Function &)> LookupBFI) { |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 1203 | DEBUG(dbgs() << "Read in profile counters: "); |
| 1204 | auto &Ctx = M.getContext(); |
| 1205 | // Read the counter array from file. |
| 1206 | auto ReaderOrErr = IndexedInstrProfReader::create(ProfileFileName); |
Vedant Kumar | 9152fd1 | 2016-05-19 03:54:45 +0000 | [diff] [blame] | 1207 | if (Error E = ReaderOrErr.takeError()) { |
| 1208 | handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) { |
| 1209 | Ctx.diagnose( |
| 1210 | DiagnosticInfoPGOProfile(ProfileFileName.data(), EI.message())); |
| 1211 | }); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 1212 | return false; |
| 1213 | } |
| 1214 | |
Xinliang David Li | da19558 | 2016-05-10 21:59:52 +0000 | [diff] [blame] | 1215 | std::unique_ptr<IndexedInstrProfReader> PGOReader = |
| 1216 | std::move(ReaderOrErr.get()); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 1217 | if (!PGOReader) { |
| 1218 | Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(), |
Xinliang David Li | da19558 | 2016-05-10 21:59:52 +0000 | [diff] [blame] | 1219 | StringRef("Cannot get PGOReader"))); |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 1220 | return false; |
| 1221 | } |
Rong Xu | 33c76c0 | 2016-02-10 17:18:30 +0000 | [diff] [blame] | 1222 | // TODO: might need to change the warning once the clang option is finalized. |
| 1223 | if (!PGOReader->isIRLevelProfile()) { |
| 1224 | Ctx.diagnose(DiagnosticInfoPGOProfile( |
| 1225 | ProfileFileName.data(), "Not an IR level instrumentation profile")); |
| 1226 | return false; |
| 1227 | } |
| 1228 | |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 1229 | std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers; |
| 1230 | collectComdatMembers(M, ComdatMembers); |
Rong Xu | 6090afd | 2016-03-28 17:08:56 +0000 | [diff] [blame] | 1231 | std::vector<Function *> HotFunctions; |
| 1232 | std::vector<Function *> ColdFunctions; |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 1233 | for (auto &F : M) { |
| 1234 | if (F.isDeclaration()) |
| 1235 | continue; |
Xinliang David Li | dfa21c3 | 2016-05-09 21:37:12 +0000 | [diff] [blame] | 1236 | auto *BPI = LookupBPI(F); |
| 1237 | auto *BFI = LookupBFI(F); |
Rong Xu | 705f777 | 2016-07-25 18:45:37 +0000 | [diff] [blame] | 1238 | PGOUseFunc Func(F, &M, ComdatMembers, BPI, BFI); |
Sean Silva | 2e8f095 | 2016-05-28 04:19:40 +0000 | [diff] [blame] | 1239 | if (!Func.readCounters(PGOReader.get())) |
| 1240 | continue; |
| 1241 | Func.populateCounters(); |
| 1242 | Func.setBranchWeights(); |
Rong Xu | a3bbf96 | 2017-03-15 18:23:39 +0000 | [diff] [blame^] | 1243 | Func.annotateValueSites(); |
Sean Silva | 9dd4b5c | 2016-05-28 03:56:25 +0000 | [diff] [blame] | 1244 | PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr(); |
| 1245 | if (FreqAttr == PGOUseFunc::FFA_Cold) |
Sean Silva | 2a73019 | 2016-05-28 03:02:50 +0000 | [diff] [blame] | 1246 | ColdFunctions.push_back(&F); |
Sean Silva | 9dd4b5c | 2016-05-28 03:56:25 +0000 | [diff] [blame] | 1247 | else if (FreqAttr == PGOUseFunc::FFA_Hot) |
| 1248 | HotFunctions.push_back(&F); |
Xinliang David Li | 58fcc9b | 2017-02-02 21:29:17 +0000 | [diff] [blame] | 1249 | if (PGOViewCounts && (ViewBlockFreqFuncName.empty() || |
| 1250 | F.getName().equals(ViewBlockFreqFuncName))) { |
Xinliang David Li | cb253ce | 2017-01-23 18:58:24 +0000 | [diff] [blame] | 1251 | LoopInfo LI{DominatorTree(F)}; |
| 1252 | std::unique_ptr<BranchProbabilityInfo> NewBPI = |
| 1253 | llvm::make_unique<BranchProbabilityInfo>(F, LI); |
| 1254 | std::unique_ptr<BlockFrequencyInfo> NewBFI = |
| 1255 | llvm::make_unique<BlockFrequencyInfo>(F, *NewBPI, LI); |
| 1256 | |
| 1257 | NewBFI->view(); |
| 1258 | } |
Xinliang David Li | 58fcc9b | 2017-02-02 21:29:17 +0000 | [diff] [blame] | 1259 | if (PGOViewRawCounts && (ViewBlockFreqFuncName.empty() || |
| 1260 | F.getName().equals(ViewBlockFreqFuncName))) { |
| 1261 | if (ViewBlockFreqFuncName.empty()) |
Xinliang David Li | d289e45 | 2017-01-27 19:06:25 +0000 | [diff] [blame] | 1262 | WriteGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName()); |
| 1263 | else |
| 1264 | ViewGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName()); |
| 1265 | } |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 1266 | } |
Easwaran Raman | 8bceb9d | 2016-06-21 19:29:49 +0000 | [diff] [blame] | 1267 | M.setProfileSummary(PGOReader->getSummary().getMD(M.getContext())); |
Rong Xu | 6090afd | 2016-03-28 17:08:56 +0000 | [diff] [blame] | 1268 | // Set function hotness attribute from the profile. |
Sean Silva | 42cc342 | 2016-05-28 04:24:39 +0000 | [diff] [blame] | 1269 | // We have to apply these attributes at the end because their presence |
| 1270 | // can affect the BranchProbabilityInfo of any callers, resulting in an |
| 1271 | // inconsistent MST between prof-gen and prof-use. |
Rong Xu | 6090afd | 2016-03-28 17:08:56 +0000 | [diff] [blame] | 1272 | for (auto &F : HotFunctions) { |
| 1273 | F->addFnAttr(llvm::Attribute::InlineHint); |
| 1274 | DEBUG(dbgs() << "Set inline attribute to function: " << F->getName() |
| 1275 | << "\n"); |
| 1276 | } |
| 1277 | for (auto &F : ColdFunctions) { |
| 1278 | F->addFnAttr(llvm::Attribute::Cold); |
| 1279 | DEBUG(dbgs() << "Set cold attribute to function: " << F->getName() << "\n"); |
| 1280 | } |
Rong Xu | f430ae4 | 2015-12-09 18:08:16 +0000 | [diff] [blame] | 1281 | return true; |
| 1282 | } |
Xinliang David Li | d55827f | 2016-05-07 05:39:12 +0000 | [diff] [blame] | 1283 | |
Xinliang David Li | da19558 | 2016-05-10 21:59:52 +0000 | [diff] [blame] | 1284 | PGOInstrumentationUse::PGOInstrumentationUse(std::string Filename) |
Benjamin Kramer | 82de7d3 | 2016-05-27 14:27:24 +0000 | [diff] [blame] | 1285 | : ProfileFileName(std::move(Filename)) { |
Xinliang David Li | da19558 | 2016-05-10 21:59:52 +0000 | [diff] [blame] | 1286 | if (!PGOTestProfileFile.empty()) |
| 1287 | ProfileFileName = PGOTestProfileFile; |
| 1288 | } |
| 1289 | |
| 1290 | PreservedAnalyses PGOInstrumentationUse::run(Module &M, |
Sean Silva | fd03ac6 | 2016-08-09 00:28:38 +0000 | [diff] [blame] | 1291 | ModuleAnalysisManager &AM) { |
Xinliang David Li | da19558 | 2016-05-10 21:59:52 +0000 | [diff] [blame] | 1292 | |
| 1293 | auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); |
| 1294 | auto LookupBPI = [&FAM](Function &F) { |
| 1295 | return &FAM.getResult<BranchProbabilityAnalysis>(F); |
| 1296 | }; |
| 1297 | |
| 1298 | auto LookupBFI = [&FAM](Function &F) { |
| 1299 | return &FAM.getResult<BlockFrequencyAnalysis>(F); |
| 1300 | }; |
| 1301 | |
| 1302 | if (!annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI)) |
| 1303 | return PreservedAnalyses::all(); |
| 1304 | |
| 1305 | return PreservedAnalyses::none(); |
| 1306 | } |
| 1307 | |
Xinliang David Li | d55827f | 2016-05-07 05:39:12 +0000 | [diff] [blame] | 1308 | bool PGOInstrumentationUseLegacyPass::runOnModule(Module &M) { |
| 1309 | if (skipModule(M)) |
| 1310 | return false; |
| 1311 | |
Xinliang David Li | dfa21c3 | 2016-05-09 21:37:12 +0000 | [diff] [blame] | 1312 | auto LookupBPI = [this](Function &F) { |
| 1313 | return &this->getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI(); |
Xinliang David Li | d55827f | 2016-05-07 05:39:12 +0000 | [diff] [blame] | 1314 | }; |
Xinliang David Li | dfa21c3 | 2016-05-09 21:37:12 +0000 | [diff] [blame] | 1315 | auto LookupBFI = [this](Function &F) { |
| 1316 | return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI(); |
Xinliang David Li | d55827f | 2016-05-07 05:39:12 +0000 | [diff] [blame] | 1317 | }; |
| 1318 | |
Xinliang David Li | da19558 | 2016-05-10 21:59:52 +0000 | [diff] [blame] | 1319 | return annotateAllFunctions(M, ProfileFileName, LookupBPI, LookupBFI); |
Xinliang David Li | d55827f | 2016-05-07 05:39:12 +0000 | [diff] [blame] | 1320 | } |
Xinliang David Li | d289e45 | 2017-01-27 19:06:25 +0000 | [diff] [blame] | 1321 | |
| 1322 | namespace llvm { |
| 1323 | template <> struct GraphTraits<PGOUseFunc *> { |
| 1324 | typedef const BasicBlock *NodeRef; |
| 1325 | typedef succ_const_iterator ChildIteratorType; |
| 1326 | typedef pointer_iterator<Function::const_iterator> nodes_iterator; |
| 1327 | |
| 1328 | static NodeRef getEntryNode(const PGOUseFunc *G) { |
| 1329 | return &G->getFunc().front(); |
| 1330 | } |
| 1331 | static ChildIteratorType child_begin(const NodeRef N) { |
| 1332 | return succ_begin(N); |
| 1333 | } |
| 1334 | static ChildIteratorType child_end(const NodeRef N) { return succ_end(N); } |
| 1335 | static nodes_iterator nodes_begin(const PGOUseFunc *G) { |
| 1336 | return nodes_iterator(G->getFunc().begin()); |
| 1337 | } |
| 1338 | static nodes_iterator nodes_end(const PGOUseFunc *G) { |
| 1339 | return nodes_iterator(G->getFunc().end()); |
| 1340 | } |
| 1341 | }; |
| 1342 | |
Xinliang David Li | 6144a59 | 2017-02-03 21:57:51 +0000 | [diff] [blame] | 1343 | static std::string getSimpleNodeName(const BasicBlock *Node) { |
| 1344 | if (!Node->getName().empty()) |
| 1345 | return Node->getName(); |
| 1346 | |
| 1347 | std::string SimpleNodeName; |
| 1348 | raw_string_ostream OS(SimpleNodeName); |
| 1349 | Node->printAsOperand(OS, false); |
| 1350 | return OS.str(); |
| 1351 | } |
| 1352 | |
Xinliang David Li | d289e45 | 2017-01-27 19:06:25 +0000 | [diff] [blame] | 1353 | template <> struct DOTGraphTraits<PGOUseFunc *> : DefaultDOTGraphTraits { |
| 1354 | explicit DOTGraphTraits(bool isSimple = false) |
| 1355 | : DefaultDOTGraphTraits(isSimple) {} |
| 1356 | |
| 1357 | static std::string getGraphName(const PGOUseFunc *G) { |
| 1358 | return G->getFunc().getName(); |
| 1359 | } |
| 1360 | |
| 1361 | std::string getNodeLabel(const BasicBlock *Node, const PGOUseFunc *Graph) { |
| 1362 | std::string Result; |
| 1363 | raw_string_ostream OS(Result); |
Xinliang David Li | 6144a59 | 2017-02-03 21:57:51 +0000 | [diff] [blame] | 1364 | |
| 1365 | OS << getSimpleNodeName(Node) << ":\\l"; |
Xinliang David Li | d289e45 | 2017-01-27 19:06:25 +0000 | [diff] [blame] | 1366 | UseBBInfo *BI = Graph->findBBInfo(Node); |
Xinliang David Li | 6144a59 | 2017-02-03 21:57:51 +0000 | [diff] [blame] | 1367 | OS << "Count : "; |
Xinliang David Li | d289e45 | 2017-01-27 19:06:25 +0000 | [diff] [blame] | 1368 | if (BI && BI->CountValid) |
Xinliang David Li | 6144a59 | 2017-02-03 21:57:51 +0000 | [diff] [blame] | 1369 | OS << BI->CountValue << "\\l"; |
Xinliang David Li | d289e45 | 2017-01-27 19:06:25 +0000 | [diff] [blame] | 1370 | else |
Xinliang David Li | 6144a59 | 2017-02-03 21:57:51 +0000 | [diff] [blame] | 1371 | OS << "Unknown\\l"; |
| 1372 | |
| 1373 | if (!PGOInstrSelect) |
| 1374 | return Result; |
| 1375 | |
| 1376 | for (auto BI = Node->begin(); BI != Node->end(); ++BI) { |
| 1377 | auto *I = &*BI; |
| 1378 | if (!isa<SelectInst>(I)) |
| 1379 | continue; |
| 1380 | // Display scaled counts for SELECT instruction: |
| 1381 | OS << "SELECT : { T = "; |
| 1382 | uint64_t TC, FC; |
Xinliang David Li | c7db0d0 | 2017-02-04 07:40:43 +0000 | [diff] [blame] | 1383 | bool HasProf = I->extractProfMetadata(TC, FC); |
| 1384 | if (!HasProf) |
Xinliang David Li | 6144a59 | 2017-02-03 21:57:51 +0000 | [diff] [blame] | 1385 | OS << "Unknown, F = Unknown }\\l"; |
| 1386 | else |
| 1387 | OS << TC << ", F = " << FC << " }\\l"; |
| 1388 | } |
Xinliang David Li | d289e45 | 2017-01-27 19:06:25 +0000 | [diff] [blame] | 1389 | return Result; |
| 1390 | } |
| 1391 | }; |
Rong Xu | 0a2a131 | 2017-03-09 19:08:55 +0000 | [diff] [blame] | 1392 | } // namespace llvm |