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