blob: c4348085882d1d24812dae6612da06c0289a6e2f [file] [log] [blame]
Justin Bogneref512b92014-01-06 22:27:43 +00001//===--- CodeGenPGO.h - PGO Instrumentation for LLVM CodeGen ----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Instrumentation-based profile-guided optimization
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef CLANG_CODEGEN_CODEGENPGO_H
15#define CLANG_CODEGEN_CODEGENPGO_H
16
17#include "CGBuilder.h"
18#include "CodeGenModule.h"
19#include "CodeGenTypes.h"
20#include "clang/Frontend/CodeGenOptions.h"
Justin Bogneref512b92014-01-06 22:27:43 +000021#include "llvm/ADT/StringMap.h"
22#include "llvm/Support/MemoryBuffer.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000023#include <memory>
Justin Bogneref512b92014-01-06 22:27:43 +000024
25namespace clang {
26namespace CodeGen {
27class RegionCounter;
28
Justin Bogneref512b92014-01-06 22:27:43 +000029/// Per-function PGO state. This class should generally not be used directly,
30/// but instead through the CodeGenFunction and RegionCounter types.
31class CodeGenPGO {
32private:
33 CodeGenModule &CGM;
Duncan P. N. Exon Smith1b67cfd2014-03-26 19:26:05 +000034 std::unique_ptr<std::string> PrefixedFuncName;
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +000035 StringRef RawFuncName;
Duncan P. N. Exon Smith73f78622014-03-20 22:49:50 +000036 llvm::GlobalValue::LinkageTypes VarLinkage;
Justin Bogneref512b92014-01-06 22:27:43 +000037
38 unsigned NumRegionCounters;
Justin Bognerb4416f52014-03-18 21:58:06 +000039 uint64_t FunctionHash;
Justin Bogneref512b92014-01-06 22:27:43 +000040 llvm::GlobalVariable *RegionCounters;
Duncan P. N. Exon Smith1b67cfd2014-03-26 19:26:05 +000041 std::unique_ptr<llvm::DenseMap<const Stmt *, unsigned>> RegionCounterMap;
42 std::unique_ptr<llvm::DenseMap<const Stmt *, uint64_t>> StmtCountMap;
43 std::unique_ptr<std::vector<uint64_t>> RegionCounts;
Justin Bogneref512b92014-01-06 22:27:43 +000044 uint64_t CurrentRegionCount;
45
46public:
47 CodeGenPGO(CodeGenModule &CGM)
Craig Topper8a13c412014-05-21 05:09:00 +000048 : CGM(CGM), NumRegionCounters(0), FunctionHash(0),
49 RegionCounters(nullptr), CurrentRegionCount(0) {}
Justin Bogneref512b92014-01-06 22:27:43 +000050
51 /// Whether or not we have PGO region data for the current function. This is
52 /// false both when we have no data at all and when our data has been
53 /// discarded.
Craig Topper8a13c412014-05-21 05:09:00 +000054 bool haveRegionCounts() const { return RegionCounts != nullptr; }
Justin Bogneref512b92014-01-06 22:27:43 +000055
Bob Wilsonda1ebed2014-03-06 04:55:41 +000056 /// Get the string used to identify this function in the profile data.
57 /// For functions with local linkage, this includes the main file name.
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +000058 StringRef getFuncName() const { return StringRef(*PrefixedFuncName); }
59 std::string getFuncVarName(StringRef VarName) const {
Duncan P. N. Exon Smitha7807632014-03-20 20:00:41 +000060 return ("__llvm_profile_" + VarName + "_" + RawFuncName).str();
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +000061 }
Bob Wilsonda1ebed2014-03-06 04:55:41 +000062
Justin Bogneref512b92014-01-06 22:27:43 +000063 /// Return the counter value of the current region.
64 uint64_t getCurrentRegionCount() const { return CurrentRegionCount; }
Bob Wilsonbf854f02014-02-17 19:21:09 +000065
Justin Bogneref512b92014-01-06 22:27:43 +000066 /// Set the counter value for the current region. This is used to keep track
67 /// of changes to the most recent counter from control flow and non-local
68 /// exits.
69 void setCurrentRegionCount(uint64_t Count) { CurrentRegionCount = Count; }
Bob Wilsonbf854f02014-02-17 19:21:09 +000070
Justin Bogner06bd6d02014-01-13 21:24:18 +000071 /// Indicate that the current region is never reached, and thus should have a
72 /// counter value of zero. This is important so that subsequent regions can
73 /// correctly track their parent counts.
74 void setCurrentRegionUnreachable() { setCurrentRegionCount(0); }
Justin Bogneref512b92014-01-06 22:27:43 +000075
Bob Wilsonbf854f02014-02-17 19:21:09 +000076 /// Check if an execution count is known for a given statement. If so, return
77 /// true and put the value in Count; else return false.
78 bool getStmtCount(const Stmt *S, uint64_t &Count) {
79 if (!StmtCountMap)
80 return false;
81 llvm::DenseMap<const Stmt*, uint64_t>::const_iterator
82 I = StmtCountMap->find(S);
83 if (I == StmtCountMap->end())
84 return false;
85 Count = I->second;
86 return true;
87 }
88
89 /// If the execution count for the current statement is known, record that
90 /// as the current count.
91 void setCurrentStmt(const Stmt *S) {
92 uint64_t Count;
93 if (getStmtCount(S, Count))
94 setCurrentRegionCount(Count);
95 }
96
Justin Bogneref512b92014-01-06 22:27:43 +000097 /// Calculate branch weights appropriate for PGO data
98 llvm::MDNode *createBranchWeights(uint64_t TrueCount, uint64_t FalseCount);
99 llvm::MDNode *createBranchWeights(ArrayRef<uint64_t> Weights);
Bob Wilsonbf854f02014-02-17 19:21:09 +0000100 llvm::MDNode *createLoopWeights(const Stmt *Cond, RegionCounter &Cnt);
Justin Bogneref512b92014-01-06 22:27:43 +0000101
102 /// Assign counters to regions and configure them for PGO of a given
103 /// function. Does nothing if instrumentation is not enabled and either
104 /// generates global variables or associates PGO data with each of the
105 /// counters depending on whether we are generating or using instrumentation.
Bob Wilsonda1ebed2014-03-06 04:55:41 +0000106 void assignRegionCounters(const Decl *D, llvm::Function *Fn);
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000107 /// Emit static data structures for instrumentation data.
108 void emitInstrumentationData();
Justin Bogneref512b92014-01-06 22:27:43 +0000109 /// Clean up region counter state. Must be called if assignRegionCounters is
110 /// used.
111 void destroyRegionCounters();
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000112 /// Emit static initialization code, if any.
Justin Bogneref512b92014-01-06 22:27:43 +0000113 static llvm::Function *emitInitialization(CodeGenModule &CGM);
114
115private:
Bob Wilsonda1ebed2014-03-06 04:55:41 +0000116 void setFuncName(llvm::Function *Fn);
Justin Bogneref512b92014-01-06 22:27:43 +0000117 void mapRegionCounters(const Decl *D);
Bob Wilsonbf854f02014-02-17 19:21:09 +0000118 void computeRegionCounts(const Decl *D);
Justin Bogner837a6f62014-04-18 21:52:00 +0000119 void applyFunctionAttributes(llvm::IndexedInstrProfReader *PGOReader,
120 llvm::Function *Fn);
121 void loadRegionCounts(llvm::IndexedInstrProfReader *PGOReader);
Justin Bogneref512b92014-01-06 22:27:43 +0000122 void emitCounterVariables();
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000123 llvm::GlobalVariable *buildDataVar();
Justin Bogneref512b92014-01-06 22:27:43 +0000124
125 /// Emit code to increment the counter at the given index
126 void emitCounterIncrement(CGBuilderTy &Builder, unsigned Counter);
127
128 /// Return the region counter for the given statement. This should only be
129 /// called on statements that have a dedicated counter.
130 unsigned getRegionCounter(const Stmt *S) {
Craig Topper8a13c412014-05-21 05:09:00 +0000131 if (!RegionCounterMap)
Justin Bogneref512b92014-01-06 22:27:43 +0000132 return 0;
133 return (*RegionCounterMap)[S];
134 }
135
136 /// Return the region count for the counter at the given index.
137 uint64_t getRegionCount(unsigned Counter) {
138 if (!haveRegionCounts())
139 return 0;
140 return (*RegionCounts)[Counter];
141 }
142
143 friend class RegionCounter;
144};
145
146/// A counter for a particular region. This is the primary interface through
147/// which clients manage PGO counters and their values.
148class RegionCounter {
149 CodeGenPGO *PGO;
150 unsigned Counter;
151 uint64_t Count;
152 uint64_t ParentCount;
153 uint64_t RegionCount;
154 int64_t Adjust;
155
156 RegionCounter(CodeGenPGO &PGO, unsigned CounterIndex)
157 : PGO(&PGO), Counter(CounterIndex), Count(PGO.getRegionCount(Counter)),
158 ParentCount(PGO.getCurrentRegionCount()), Adjust(0) {}
159
160public:
161 RegionCounter(CodeGenPGO &PGO, const Stmt *S)
162 : PGO(&PGO), Counter(PGO.getRegionCounter(S)),
163 Count(PGO.getRegionCount(Counter)),
164 ParentCount(PGO.getCurrentRegionCount()), Adjust(0) {}
165
166 /// Get the value of the counter. In most cases this is the number of times
167 /// the region of the counter was entered, but for switch labels it's the
168 /// number of direct jumps to that label.
169 uint64_t getCount() const { return Count; }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000170
Justin Bogneref512b92014-01-06 22:27:43 +0000171 /// Get the value of the counter with adjustments applied. Adjustments occur
Bob Wilsona7b16e02014-02-17 19:21:03 +0000172 /// when control enters or leaves the region abnormally; i.e., if there is a
Justin Bogneref512b92014-01-06 22:27:43 +0000173 /// jump to a label within the region, or if the function can return from
174 /// within the region. The adjusted count, then, is the value of the counter
175 /// at the end of the region.
176 uint64_t getAdjustedCount() const {
Justin Bogneref512b92014-01-06 22:27:43 +0000177 return Count + Adjust;
178 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000179
Bob Wilsona7b16e02014-02-17 19:21:03 +0000180 /// Get the value of the counter in this region's parent, i.e., the region
181 /// that was active when this region began. This is useful for deriving
182 /// counts in implicitly counted regions, like the false case of a condition
183 /// or the normal exits of a loop.
Justin Bogneref512b92014-01-06 22:27:43 +0000184 uint64_t getParentCount() const { return ParentCount; }
185
Justin Bogneref512b92014-01-06 22:27:43 +0000186 /// Activate the counter by emitting an increment and starting to track
187 /// adjustments. If AddIncomingFallThrough is true, the current region count
188 /// will be added to the counter for the purposes of tracking the region.
189 void beginRegion(CGBuilderTy &Builder, bool AddIncomingFallThrough=false) {
Bob Wilsonbf854f02014-02-17 19:21:09 +0000190 beginRegion(AddIncomingFallThrough);
191 PGO->emitCounterIncrement(Builder, Counter);
192 }
193 void beginRegion(bool AddIncomingFallThrough=false) {
Justin Bogneref512b92014-01-06 22:27:43 +0000194 RegionCount = Count;
195 if (AddIncomingFallThrough)
196 RegionCount += PGO->getCurrentRegionCount();
197 PGO->setCurrentRegionCount(RegionCount);
Justin Bogneref512b92014-01-06 22:27:43 +0000198 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000199
Justin Bogneref512b92014-01-06 22:27:43 +0000200 /// For counters on boolean branches, begins tracking adjustments for the
201 /// uncounted path.
202 void beginElseRegion() {
203 RegionCount = ParentCount - Count;
204 PGO->setCurrentRegionCount(RegionCount);
205 }
206
Bob Wilsonbf854f02014-02-17 19:21:09 +0000207 /// Reset the current region count.
208 void setCurrentRegionCount(uint64_t CurrentCount) {
209 RegionCount = CurrentCount;
210 PGO->setCurrentRegionCount(RegionCount);
211 }
212
Justin Bogner0718a3a2014-01-13 21:24:22 +0000213 /// Adjust for non-local control flow after emitting a subexpression or
214 /// substatement. This must be called to account for constructs such as gotos,
215 /// labels, and returns, so that we can ensure that our region's count is
216 /// correct in the code that follows.
217 void adjustForControlFlow() {
Justin Bogneref512b92014-01-06 22:27:43 +0000218 Adjust += PGO->getCurrentRegionCount() - RegionCount;
Bob Wilsonbf854f02014-02-17 19:21:09 +0000219 // Reset the region count in case this is called again later.
220 RegionCount = PGO->getCurrentRegionCount();
Justin Bogneref512b92014-01-06 22:27:43 +0000221 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000222
223 /// Commit all adjustments to the current region. If the region is a loop,
224 /// the LoopAdjust value should be the count of all the breaks and continues
225 /// from the loop, to compensate for those counts being deducted from the
226 /// adjustments for the body of the loop.
227 void applyAdjustmentsToRegion(uint64_t LoopAdjust) {
228 PGO->setCurrentRegionCount(ParentCount + Adjust + LoopAdjust);
Justin Bogneref512b92014-01-06 22:27:43 +0000229 }
230};
231
232} // end namespace CodeGen
233} // end namespace clang
234
235#endif