blob: 8c3340a9d3bd8ae626dc7a633fce4caaecb173e2 [file] [log] [blame]
Justin Bogneref512b92014-01-06 22:27:43 +00001//===--- CodeGenPGO.cpp - 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#include "CodeGenPGO.h"
15#include "CodeGenFunction.h"
16#include "clang/AST/RecursiveASTVisitor.h"
17#include "clang/AST/StmtVisitor.h"
Duncan P. N. Exon Smithe9624292014-04-10 23:37:34 +000018#include "llvm/Config/config.h" // for strtoull()/strtoul() define
Justin Bogneref512b92014-01-06 22:27:43 +000019#include "llvm/IR/MDBuilder.h"
20#include "llvm/Support/FileSystem.h"
21
22using namespace clang;
23using namespace CodeGen;
24
Justin Bognerd66a17d2014-03-12 21:06:31 +000025static void ReportBadPGOData(CodeGenModule &CGM, const char *Message) {
26 DiagnosticsEngine &Diags = CGM.getDiags();
27 unsigned diagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, "%0");
28 Diags.Report(diagID) << Message;
29}
30
31PGOProfileData::PGOProfileData(CodeGenModule &CGM, std::string Path)
32 : CGM(CGM) {
33 if (llvm::MemoryBuffer::getFile(Path, DataBuffer)) {
34 ReportBadPGOData(CGM, "failed to open pgo data file");
35 return;
36 }
37
38 if (DataBuffer->getBufferSize() > std::numeric_limits<unsigned>::max()) {
39 ReportBadPGOData(CGM, "pgo data file too big");
40 return;
41 }
42
43 // Scan through the data file and map each function to the corresponding
44 // file offset where its counts are stored.
45 const char *BufferStart = DataBuffer->getBufferStart();
46 const char *BufferEnd = DataBuffer->getBufferEnd();
47 const char *CurPtr = BufferStart;
48 uint64_t MaxCount = 0;
49 while (CurPtr < BufferEnd) {
50 // Read the function name.
51 const char *FuncStart = CurPtr;
52 // For Objective-C methods, the name may include whitespace, so search
53 // backward from the end of the line to find the space that separates the
54 // name from the number of counters. (This is a temporary hack since we are
55 // going to completely replace this file format in the near future.)
56 CurPtr = strchr(CurPtr, '\n');
57 if (!CurPtr) {
58 ReportBadPGOData(CGM, "pgo data file has malformed function entry");
59 return;
60 }
Justin Bognerd66a17d2014-03-12 21:06:31 +000061 StringRef FuncName(FuncStart, CurPtr - FuncStart);
62
Justin Bognerb4416f52014-03-18 21:58:06 +000063 // Skip over the function hash.
64 CurPtr = strchr(++CurPtr, '\n');
65 if (!CurPtr) {
66 ReportBadPGOData(CGM, "pgo data file is missing the function hash");
67 return;
68 }
69
Justin Bognerd66a17d2014-03-12 21:06:31 +000070 // Read the number of counters.
71 char *EndPtr;
Duncan P. N. Exon Smithe9624292014-04-10 23:37:34 +000072 unsigned NumCounters = strtoul(++CurPtr, &EndPtr, 10);
Justin Bognerd66a17d2014-03-12 21:06:31 +000073 if (EndPtr == CurPtr || *EndPtr != '\n' || NumCounters <= 0) {
74 ReportBadPGOData(CGM, "pgo data file has unexpected number of counters");
75 return;
76 }
77 CurPtr = EndPtr;
78
79 // Read function count.
Duncan P. N. Exon Smithe9624292014-04-10 23:37:34 +000080 uint64_t Count = strtoull(CurPtr, &EndPtr, 10);
Justin Bognerd66a17d2014-03-12 21:06:31 +000081 if (EndPtr == CurPtr || *EndPtr != '\n') {
82 ReportBadPGOData(CGM, "pgo-data file has bad count value");
83 return;
84 }
85 CurPtr = EndPtr; // Point to '\n'.
86 FunctionCounts[FuncName] = Count;
87 MaxCount = Count > MaxCount ? Count : MaxCount;
88
89 // There is one line for each counter; skip over those lines.
90 // Since function count is already read, we start the loop from 1.
91 for (unsigned N = 1; N < NumCounters; ++N) {
92 CurPtr = strchr(++CurPtr, '\n');
93 if (!CurPtr) {
94 ReportBadPGOData(CGM, "pgo data file is missing some counter info");
95 return;
96 }
97 }
98
99 // Skip over the blank line separating functions.
100 CurPtr += 2;
101
102 DataOffsets[FuncName] = FuncStart - BufferStart;
103 }
104 MaxFunctionCount = MaxCount;
105}
106
Justin Bognerb4416f52014-03-18 21:58:06 +0000107bool PGOProfileData::getFunctionCounts(StringRef FuncName, uint64_t &FuncHash,
Justin Bognerd66a17d2014-03-12 21:06:31 +0000108 std::vector<uint64_t> &Counts) {
109 // Find the relevant section of the pgo-data file.
110 llvm::StringMap<unsigned>::const_iterator OffsetIter =
111 DataOffsets.find(FuncName);
112 if (OffsetIter == DataOffsets.end())
113 return true;
114 const char *CurPtr = DataBuffer->getBufferStart() + OffsetIter->getValue();
115
116 // Skip over the function name.
117 CurPtr = strchr(CurPtr, '\n');
118 assert(CurPtr && "pgo-data has corrupted function entry");
Justin Bognerb4416f52014-03-18 21:58:06 +0000119
120 char *EndPtr;
121 // Read the function hash.
Duncan P. N. Exon Smithe9624292014-04-10 23:37:34 +0000122 FuncHash = strtoull(++CurPtr, &EndPtr, 10);
Justin Bognerb4416f52014-03-18 21:58:06 +0000123 assert(EndPtr != CurPtr && *EndPtr == '\n' &&
124 "pgo-data file has corrupted function hash");
125 CurPtr = EndPtr;
Justin Bognerd66a17d2014-03-12 21:06:31 +0000126
127 // Read the number of counters.
Duncan P. N. Exon Smithe9624292014-04-10 23:37:34 +0000128 unsigned NumCounters = strtoul(++CurPtr, &EndPtr, 10);
Justin Bognerd66a17d2014-03-12 21:06:31 +0000129 assert(EndPtr != CurPtr && *EndPtr == '\n' && NumCounters > 0 &&
130 "pgo-data file has corrupted number of counters");
131 CurPtr = EndPtr;
132
133 Counts.reserve(NumCounters);
134
135 for (unsigned N = 0; N < NumCounters; ++N) {
136 // Read the count value.
Duncan P. N. Exon Smithe9624292014-04-10 23:37:34 +0000137 uint64_t Count = strtoull(CurPtr, &EndPtr, 10);
Justin Bognerd66a17d2014-03-12 21:06:31 +0000138 if (EndPtr == CurPtr || *EndPtr != '\n') {
139 ReportBadPGOData(CGM, "pgo-data file has bad count value");
140 return true;
141 }
142 Counts.push_back(Count);
143 CurPtr = EndPtr + 1;
144 }
145
146 // Make sure the number of counters matches up.
147 if (Counts.size() != NumCounters) {
148 ReportBadPGOData(CGM, "pgo-data file has inconsistent counters");
149 return true;
150 }
151
152 return false;
153}
154
Bob Wilsonda1ebed2014-03-06 04:55:41 +0000155void CodeGenPGO::setFuncName(llvm::Function *Fn) {
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000156 RawFuncName = Fn->getName();
Bob Wilsonda1ebed2014-03-06 04:55:41 +0000157
158 // Function names may be prefixed with a binary '1' to indicate
159 // that the backend should not modify the symbols due to any platform
160 // naming convention. Do not include that '1' in the PGO profile name.
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000161 if (RawFuncName[0] == '\1')
162 RawFuncName = RawFuncName.substr(1);
Bob Wilsonda1ebed2014-03-06 04:55:41 +0000163
164 if (!Fn->hasLocalLinkage()) {
Duncan P. N. Exon Smith1b67cfd2014-03-26 19:26:05 +0000165 PrefixedFuncName.reset(new std::string(RawFuncName));
Bob Wilsonda1ebed2014-03-06 04:55:41 +0000166 return;
167 }
168
169 // For local symbols, prepend the main file name to distinguish them.
170 // Do not include the full path in the file name since there's no guarantee
171 // that it will stay the same, e.g., if the files are checked out from
172 // version control in different locations.
Duncan P. N. Exon Smith1b67cfd2014-03-26 19:26:05 +0000173 PrefixedFuncName.reset(new std::string(CGM.getCodeGenOpts().MainFileName));
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000174 if (PrefixedFuncName->empty())
175 PrefixedFuncName->assign("<unknown>");
176 PrefixedFuncName->append(":");
177 PrefixedFuncName->append(RawFuncName);
Bob Wilsonda1ebed2014-03-06 04:55:41 +0000178}
179
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000180static llvm::Function *getRegisterFunc(CodeGenModule &CGM) {
Duncan P. N. Exon Smitha7807632014-03-20 20:00:41 +0000181 return CGM.getModule().getFunction("__llvm_profile_register_functions");
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000182}
183
184static llvm::BasicBlock *getOrInsertRegisterBB(CodeGenModule &CGM) {
Duncan P. N. Exon Smith780443e2014-03-20 03:57:11 +0000185 // Don't do this for Darwin. compiler-rt uses linker magic.
186 if (CGM.getTarget().getTriple().isOSDarwin())
187 return nullptr;
188
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000189 // Only need to insert this once per module.
190 if (llvm::Function *RegisterF = getRegisterFunc(CGM))
191 return &RegisterF->getEntryBlock();
192
193 // Construct the function.
194 auto *VoidTy = llvm::Type::getVoidTy(CGM.getLLVMContext());
195 auto *RegisterFTy = llvm::FunctionType::get(VoidTy, false);
196 auto *RegisterF = llvm::Function::Create(RegisterFTy,
197 llvm::GlobalValue::InternalLinkage,
Duncan P. N. Exon Smitha7807632014-03-20 20:00:41 +0000198 "__llvm_profile_register_functions",
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000199 &CGM.getModule());
200 RegisterF->setUnnamedAddr(true);
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000201 if (CGM.getCodeGenOpts().DisableRedZone)
202 RegisterF->addFnAttr(llvm::Attribute::NoRedZone);
203
204 // Construct and return the entry block.
205 auto *BB = llvm::BasicBlock::Create(CGM.getLLVMContext(), "", RegisterF);
206 CGBuilderTy Builder(BB);
207 Builder.CreateRetVoid();
208 return BB;
209}
210
211static llvm::Constant *getOrInsertRuntimeRegister(CodeGenModule &CGM) {
212 auto *VoidTy = llvm::Type::getVoidTy(CGM.getLLVMContext());
213 auto *VoidPtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
214 auto *RuntimeRegisterTy = llvm::FunctionType::get(VoidTy, VoidPtrTy, false);
Duncan P. N. Exon Smitha7807632014-03-20 20:00:41 +0000215 return CGM.getModule().getOrInsertFunction("__llvm_profile_register_function",
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000216 RuntimeRegisterTy);
217}
218
Duncan P. N. Exon Smith7134d472014-03-20 03:17:15 +0000219static bool isMachO(const CodeGenModule &CGM) {
220 return CGM.getTarget().getTriple().isOSBinFormatMachO();
221}
222
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000223static StringRef getCountersSection(const CodeGenModule &CGM) {
Duncan P. N. Exon Smitha7807632014-03-20 20:00:41 +0000224 return isMachO(CGM) ? "__DATA,__llvm_prf_cnts" : "__llvm_prf_cnts";
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000225}
226
227static StringRef getNameSection(const CodeGenModule &CGM) {
Duncan P. N. Exon Smitha7807632014-03-20 20:00:41 +0000228 return isMachO(CGM) ? "__DATA,__llvm_prf_names" : "__llvm_prf_names";
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000229}
230
231static StringRef getDataSection(const CodeGenModule &CGM) {
Duncan P. N. Exon Smitha7807632014-03-20 20:00:41 +0000232 return isMachO(CGM) ? "__DATA,__llvm_prf_data" : "__llvm_prf_data";
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000233}
234
235llvm::GlobalVariable *CodeGenPGO::buildDataVar() {
236 // Create name variable.
237 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
238 auto *VarName = llvm::ConstantDataArray::getString(Ctx, getFuncName(),
239 false);
240 auto *Name = new llvm::GlobalVariable(CGM.getModule(), VarName->getType(),
Duncan P. N. Exon Smith73f78622014-03-20 22:49:50 +0000241 true, VarLinkage, VarName,
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000242 getFuncVarName("name"));
243 Name->setSection(getNameSection(CGM));
244 Name->setAlignment(1);
245
246 // Create data variable.
247 auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
Justin Bognerb4416f52014-03-18 21:58:06 +0000248 auto *Int64Ty = llvm::Type::getInt64Ty(Ctx);
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000249 auto *Int8PtrTy = llvm::Type::getInt8PtrTy(Ctx);
250 auto *Int64PtrTy = llvm::Type::getInt64PtrTy(Ctx);
251 llvm::Type *DataTypes[] = {
Justin Bognerb4416f52014-03-18 21:58:06 +0000252 Int32Ty, Int32Ty, Int64Ty, Int8PtrTy, Int64PtrTy
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000253 };
254 auto *DataTy = llvm::StructType::get(Ctx, makeArrayRef(DataTypes));
255 llvm::Constant *DataVals[] = {
256 llvm::ConstantInt::get(Int32Ty, getFuncName().size()),
257 llvm::ConstantInt::get(Int32Ty, NumRegionCounters),
Justin Bognerb4416f52014-03-18 21:58:06 +0000258 llvm::ConstantInt::get(Int64Ty, FunctionHash),
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000259 llvm::ConstantExpr::getBitCast(Name, Int8PtrTy),
260 llvm::ConstantExpr::getBitCast(RegionCounters, Int64PtrTy)
261 };
262 auto *Data =
Duncan P. N. Exon Smith73f78622014-03-20 22:49:50 +0000263 new llvm::GlobalVariable(CGM.getModule(), DataTy, true, VarLinkage,
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000264 llvm::ConstantStruct::get(DataTy, DataVals),
265 getFuncVarName("data"));
266
267 // All the data should be packed into an array in its own section.
268 Data->setSection(getDataSection(CGM));
269 Data->setAlignment(8);
270
271 // Make sure the data doesn't get deleted.
272 CGM.addUsedGlobal(Data);
273 return Data;
274}
275
276void CodeGenPGO::emitInstrumentationData() {
Justin Bogneref512b92014-01-06 22:27:43 +0000277 if (!CGM.getCodeGenOpts().ProfileInstrGenerate)
278 return;
279
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000280 // Build the data.
281 auto *Data = buildDataVar();
Justin Bogneref512b92014-01-06 22:27:43 +0000282
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000283 // Register the data.
Duncan P. N. Exon Smith780443e2014-03-20 03:57:11 +0000284 auto *RegisterBB = getOrInsertRegisterBB(CGM);
285 if (!RegisterBB)
286 return;
287 CGBuilderTy Builder(RegisterBB->getTerminator());
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000288 auto *VoidPtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
289 Builder.CreateCall(getOrInsertRuntimeRegister(CGM),
290 Builder.CreateBitCast(Data, VoidPtrTy));
Justin Bogneref512b92014-01-06 22:27:43 +0000291}
292
293llvm::Function *CodeGenPGO::emitInitialization(CodeGenModule &CGM) {
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000294 if (!CGM.getCodeGenOpts().ProfileInstrGenerate)
Duncan P. N. Exon Smitha5f804a2014-03-20 18:40:55 +0000295 return nullptr;
Justin Bogneref512b92014-01-06 22:27:43 +0000296
Justin Bognerf2ea7752014-04-10 18:13:13 +0000297 assert(CGM.getModule().getFunction("__llvm_profile_init") == nullptr &&
298 "profile initialization already emitted");
Justin Bogneref512b92014-01-06 22:27:43 +0000299
Duncan P. N. Exon Smith5188e912014-03-20 19:23:46 +0000300 // Get the function to call at initialization.
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000301 llvm::Constant *RegisterF = getRegisterFunc(CGM);
Duncan P. N. Exon Smith5188e912014-03-20 19:23:46 +0000302 if (!RegisterF)
Duncan P. N. Exon Smitha5f804a2014-03-20 18:40:55 +0000303 return nullptr;
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000304
305 // Create the initialization function.
306 auto *VoidTy = llvm::Type::getVoidTy(CGM.getLLVMContext());
307 auto *F = llvm::Function::Create(llvm::FunctionType::get(VoidTy, false),
308 llvm::GlobalValue::InternalLinkage,
Duncan P. N. Exon Smitha7807632014-03-20 20:00:41 +0000309 "__llvm_profile_init", &CGM.getModule());
Justin Bogneref512b92014-01-06 22:27:43 +0000310 F->setUnnamedAddr(true);
Justin Bogneref512b92014-01-06 22:27:43 +0000311 F->addFnAttr(llvm::Attribute::NoInline);
312 if (CGM.getCodeGenOpts().DisableRedZone)
313 F->addFnAttr(llvm::Attribute::NoRedZone);
314
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000315 // Add the basic block and the necessary calls.
316 CGBuilderTy Builder(llvm::BasicBlock::Create(CGM.getLLVMContext(), "", F));
Duncan P. N. Exon Smith5188e912014-03-20 19:23:46 +0000317 Builder.CreateCall(RegisterF);
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000318 Builder.CreateRetVoid();
Justin Bogneref512b92014-01-06 22:27:43 +0000319
320 return F;
321}
322
323namespace {
324 /// A StmtVisitor that fills a map of statements to PGO counters.
325 struct MapRegionCounters : public ConstStmtVisitor<MapRegionCounters> {
326 /// The next counter value to assign.
327 unsigned NextCounter;
328 /// The map of statements to counters.
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000329 llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
Justin Bogneref512b92014-01-06 22:27:43 +0000330
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000331 MapRegionCounters(llvm::DenseMap<const Stmt *, unsigned> &CounterMap)
332 : NextCounter(0), CounterMap(CounterMap) {}
Justin Bogneref512b92014-01-06 22:27:43 +0000333
334 void VisitChildren(const Stmt *S) {
335 for (Stmt::const_child_range I = S->children(); I; ++I)
336 if (*I)
337 this->Visit(*I);
338 }
339 void VisitStmt(const Stmt *S) { VisitChildren(S); }
340
Justin Bognerea278c32014-01-07 00:20:28 +0000341 /// Assign a counter to track entry to the function body.
Duncan P. N. Exon Smith4a2f5ae2014-04-10 23:37:36 +0000342 void VisitFunctionDecl(const FunctionDecl *D) {
343 CounterMap[D->getBody()] = NextCounter++;
344 Visit(D->getBody());
Justin Bogneref512b92014-01-06 22:27:43 +0000345 }
Duncan P. N. Exon Smith4a2f5ae2014-04-10 23:37:36 +0000346 void VisitObjCMethodDecl(const ObjCMethodDecl *D) {
347 CounterMap[D->getBody()] = NextCounter++;
348 Visit(D->getBody());
Bob Wilson5ec8fe12014-03-06 06:10:02 +0000349 }
Duncan P. N. Exon Smith4a2f5ae2014-04-10 23:37:36 +0000350 void VisitBlockDecl(const BlockDecl *D) {
351 CounterMap[D->getBody()] = NextCounter++;
352 Visit(D->getBody());
Bob Wilsonc845c002014-03-06 20:24:27 +0000353 }
Justin Bognerea278c32014-01-07 00:20:28 +0000354 /// Assign a counter to track the block following a label.
Justin Bogneref512b92014-01-06 22:27:43 +0000355 void VisitLabelStmt(const LabelStmt *S) {
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000356 CounterMap[S] = NextCounter++;
Justin Bogneref512b92014-01-06 22:27:43 +0000357 Visit(S->getSubStmt());
358 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000359 /// Assign a counter for the body of a while loop.
Justin Bogneref512b92014-01-06 22:27:43 +0000360 void VisitWhileStmt(const WhileStmt *S) {
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000361 CounterMap[S] = NextCounter++;
Justin Bogneref512b92014-01-06 22:27:43 +0000362 Visit(S->getCond());
363 Visit(S->getBody());
364 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000365 /// Assign a counter for the body of a do-while loop.
Justin Bogneref512b92014-01-06 22:27:43 +0000366 void VisitDoStmt(const DoStmt *S) {
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000367 CounterMap[S] = NextCounter++;
Justin Bogneref512b92014-01-06 22:27:43 +0000368 Visit(S->getBody());
369 Visit(S->getCond());
370 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000371 /// Assign a counter for the body of a for loop.
Justin Bogneref512b92014-01-06 22:27:43 +0000372 void VisitForStmt(const ForStmt *S) {
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000373 CounterMap[S] = NextCounter++;
Bob Wilsonbf854f02014-02-17 19:21:09 +0000374 if (S->getInit())
375 Visit(S->getInit());
Justin Bogneref512b92014-01-06 22:27:43 +0000376 const Expr *E;
377 if ((E = S->getCond()))
378 Visit(E);
Justin Bogneref512b92014-01-06 22:27:43 +0000379 if ((E = S->getInc()))
380 Visit(E);
Bob Wilsonbf854f02014-02-17 19:21:09 +0000381 Visit(S->getBody());
Justin Bogneref512b92014-01-06 22:27:43 +0000382 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000383 /// Assign a counter for the body of a for-range loop.
Justin Bogneref512b92014-01-06 22:27:43 +0000384 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000385 CounterMap[S] = NextCounter++;
Bob Wilsonbf854f02014-02-17 19:21:09 +0000386 Visit(S->getRangeStmt());
387 Visit(S->getBeginEndStmt());
388 Visit(S->getCond());
389 Visit(S->getLoopVarStmt());
Justin Bogneref512b92014-01-06 22:27:43 +0000390 Visit(S->getBody());
Bob Wilsonbf854f02014-02-17 19:21:09 +0000391 Visit(S->getInc());
Justin Bogneref512b92014-01-06 22:27:43 +0000392 }
Bob Wilsonbf854f02014-02-17 19:21:09 +0000393 /// Assign a counter for the body of a for-collection loop.
Justin Bogneref512b92014-01-06 22:27:43 +0000394 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000395 CounterMap[S] = NextCounter++;
Justin Bogneref512b92014-01-06 22:27:43 +0000396 Visit(S->getElement());
397 Visit(S->getBody());
398 }
399 /// Assign a counter for the exit block of the switch statement.
400 void VisitSwitchStmt(const SwitchStmt *S) {
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000401 CounterMap[S] = NextCounter++;
Justin Bogneref512b92014-01-06 22:27:43 +0000402 Visit(S->getCond());
403 Visit(S->getBody());
404 }
405 /// Assign a counter for a particular case in a switch. This counts jumps
406 /// from the switch header as well as fallthrough from the case before this
407 /// one.
408 void VisitCaseStmt(const CaseStmt *S) {
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000409 CounterMap[S] = NextCounter++;
Justin Bogneref512b92014-01-06 22:27:43 +0000410 Visit(S->getSubStmt());
411 }
412 /// Assign a counter for the default case of a switch statement. The count
413 /// is the number of branches from the loop header to the default, and does
414 /// not include fallthrough from previous cases. If we have multiple
415 /// conditional branch blocks from the switch instruction to the default
416 /// block, as with large GNU case ranges, this is the counter for the last
417 /// edge in that series, rather than the first.
418 void VisitDefaultStmt(const DefaultStmt *S) {
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000419 CounterMap[S] = NextCounter++;
Justin Bogneref512b92014-01-06 22:27:43 +0000420 Visit(S->getSubStmt());
421 }
422 /// Assign a counter for the "then" part of an if statement. The count for
423 /// the "else" part, if it exists, will be calculated from this counter.
424 void VisitIfStmt(const IfStmt *S) {
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000425 CounterMap[S] = NextCounter++;
Justin Bogneref512b92014-01-06 22:27:43 +0000426 Visit(S->getCond());
427 Visit(S->getThen());
428 if (S->getElse())
429 Visit(S->getElse());
430 }
431 /// Assign a counter for the continuation block of a C++ try statement.
432 void VisitCXXTryStmt(const CXXTryStmt *S) {
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000433 CounterMap[S] = NextCounter++;
Justin Bogneref512b92014-01-06 22:27:43 +0000434 Visit(S->getTryBlock());
435 for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
436 Visit(S->getHandler(I));
437 }
438 /// Assign a counter for a catch statement's handler block.
439 void VisitCXXCatchStmt(const CXXCatchStmt *S) {
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000440 CounterMap[S] = NextCounter++;
Justin Bogneref512b92014-01-06 22:27:43 +0000441 Visit(S->getHandlerBlock());
442 }
443 /// Assign a counter for the "true" part of a conditional operator. The
444 /// count in the "false" part will be calculated from this counter.
445 void VisitConditionalOperator(const ConditionalOperator *E) {
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000446 CounterMap[E] = NextCounter++;
Justin Bogneref512b92014-01-06 22:27:43 +0000447 Visit(E->getCond());
448 Visit(E->getTrueExpr());
449 Visit(E->getFalseExpr());
450 }
451 /// Assign a counter for the right hand side of a logical and operator.
452 void VisitBinLAnd(const BinaryOperator *E) {
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000453 CounterMap[E] = NextCounter++;
Justin Bogneref512b92014-01-06 22:27:43 +0000454 Visit(E->getLHS());
455 Visit(E->getRHS());
456 }
457 /// Assign a counter for the right hand side of a logical or operator.
458 void VisitBinLOr(const BinaryOperator *E) {
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000459 CounterMap[E] = NextCounter++;
Justin Bogneref512b92014-01-06 22:27:43 +0000460 Visit(E->getLHS());
461 Visit(E->getRHS());
462 }
463 };
Bob Wilsonbf854f02014-02-17 19:21:09 +0000464
465 /// A StmtVisitor that propagates the raw counts through the AST and
466 /// records the count at statements where the value may change.
467 struct ComputeRegionCounts : public ConstStmtVisitor<ComputeRegionCounts> {
468 /// PGO state.
469 CodeGenPGO &PGO;
470
471 /// A flag that is set when the current count should be recorded on the
472 /// next statement, such as at the exit of a loop.
473 bool RecordNextStmtCount;
474
475 /// The map of statements to count values.
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000476 llvm::DenseMap<const Stmt *, uint64_t> &CountMap;
Bob Wilsonbf854f02014-02-17 19:21:09 +0000477
478 /// BreakContinueStack - Keep counts of breaks and continues inside loops.
479 struct BreakContinue {
480 uint64_t BreakCount;
481 uint64_t ContinueCount;
482 BreakContinue() : BreakCount(0), ContinueCount(0) {}
483 };
484 SmallVector<BreakContinue, 8> BreakContinueStack;
485
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000486 ComputeRegionCounts(llvm::DenseMap<const Stmt *, uint64_t> &CountMap,
487 CodeGenPGO &PGO)
488 : PGO(PGO), RecordNextStmtCount(false), CountMap(CountMap) {}
Bob Wilsonbf854f02014-02-17 19:21:09 +0000489
490 void RecordStmtCount(const Stmt *S) {
491 if (RecordNextStmtCount) {
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000492 CountMap[S] = PGO.getCurrentRegionCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000493 RecordNextStmtCount = false;
494 }
495 }
496
497 void VisitStmt(const Stmt *S) {
498 RecordStmtCount(S);
499 for (Stmt::const_child_range I = S->children(); I; ++I) {
500 if (*I)
501 this->Visit(*I);
502 }
503 }
504
Duncan P. N. Exon Smith4a2f5ae2014-04-10 23:37:36 +0000505 void VisitFunctionDecl(const FunctionDecl *D) {
506 RegionCounter Cnt(PGO, D->getBody());
Bob Wilsonbf854f02014-02-17 19:21:09 +0000507 Cnt.beginRegion();
Duncan P. N. Exon Smith4a2f5ae2014-04-10 23:37:36 +0000508 CountMap[D->getBody()] = PGO.getCurrentRegionCount();
509 Visit(D->getBody());
Bob Wilsonbf854f02014-02-17 19:21:09 +0000510 }
511
Duncan P. N. Exon Smith4a2f5ae2014-04-10 23:37:36 +0000512 void VisitObjCMethodDecl(const ObjCMethodDecl *D) {
513 RegionCounter Cnt(PGO, D->getBody());
Bob Wilson5ec8fe12014-03-06 06:10:02 +0000514 Cnt.beginRegion();
Duncan P. N. Exon Smith4a2f5ae2014-04-10 23:37:36 +0000515 CountMap[D->getBody()] = PGO.getCurrentRegionCount();
516 Visit(D->getBody());
Bob Wilson5ec8fe12014-03-06 06:10:02 +0000517 }
518
Duncan P. N. Exon Smith4a2f5ae2014-04-10 23:37:36 +0000519 void VisitBlockDecl(const BlockDecl *D) {
520 RegionCounter Cnt(PGO, D->getBody());
Bob Wilsonc845c002014-03-06 20:24:27 +0000521 Cnt.beginRegion();
Duncan P. N. Exon Smith4a2f5ae2014-04-10 23:37:36 +0000522 CountMap[D->getBody()] = PGO.getCurrentRegionCount();
523 Visit(D->getBody());
Bob Wilsonc845c002014-03-06 20:24:27 +0000524 }
525
Bob Wilsonbf854f02014-02-17 19:21:09 +0000526 void VisitReturnStmt(const ReturnStmt *S) {
527 RecordStmtCount(S);
528 if (S->getRetValue())
529 Visit(S->getRetValue());
530 PGO.setCurrentRegionUnreachable();
531 RecordNextStmtCount = true;
532 }
533
534 void VisitGotoStmt(const GotoStmt *S) {
535 RecordStmtCount(S);
536 PGO.setCurrentRegionUnreachable();
537 RecordNextStmtCount = true;
538 }
539
540 void VisitLabelStmt(const LabelStmt *S) {
541 RecordNextStmtCount = false;
542 RegionCounter Cnt(PGO, S);
543 Cnt.beginRegion();
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000544 CountMap[S] = PGO.getCurrentRegionCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000545 Visit(S->getSubStmt());
546 }
547
548 void VisitBreakStmt(const BreakStmt *S) {
549 RecordStmtCount(S);
550 assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
551 BreakContinueStack.back().BreakCount += PGO.getCurrentRegionCount();
552 PGO.setCurrentRegionUnreachable();
553 RecordNextStmtCount = true;
554 }
555
556 void VisitContinueStmt(const ContinueStmt *S) {
557 RecordStmtCount(S);
558 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
559 BreakContinueStack.back().ContinueCount += PGO.getCurrentRegionCount();
560 PGO.setCurrentRegionUnreachable();
561 RecordNextStmtCount = true;
562 }
563
564 void VisitWhileStmt(const WhileStmt *S) {
565 RecordStmtCount(S);
566 RegionCounter Cnt(PGO, S);
567 BreakContinueStack.push_back(BreakContinue());
568 // Visit the body region first so the break/continue adjustments can be
569 // included when visiting the condition.
570 Cnt.beginRegion();
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000571 CountMap[S->getBody()] = PGO.getCurrentRegionCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000572 Visit(S->getBody());
573 Cnt.adjustForControlFlow();
574
575 // ...then go back and propagate counts through the condition. The count
576 // at the start of the condition is the sum of the incoming edges,
577 // the backedge from the end of the loop body, and the edges from
578 // continue statements.
579 BreakContinue BC = BreakContinueStack.pop_back_val();
580 Cnt.setCurrentRegionCount(Cnt.getParentCount() +
581 Cnt.getAdjustedCount() + BC.ContinueCount);
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000582 CountMap[S->getCond()] = PGO.getCurrentRegionCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000583 Visit(S->getCond());
584 Cnt.adjustForControlFlow();
585 Cnt.applyAdjustmentsToRegion(BC.BreakCount + BC.ContinueCount);
586 RecordNextStmtCount = true;
587 }
588
589 void VisitDoStmt(const DoStmt *S) {
590 RecordStmtCount(S);
591 RegionCounter Cnt(PGO, S);
592 BreakContinueStack.push_back(BreakContinue());
593 Cnt.beginRegion(/*AddIncomingFallThrough=*/true);
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000594 CountMap[S->getBody()] = PGO.getCurrentRegionCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000595 Visit(S->getBody());
596 Cnt.adjustForControlFlow();
597
598 BreakContinue BC = BreakContinueStack.pop_back_val();
599 // The count at the start of the condition is equal to the count at the
600 // end of the body. The adjusted count does not include either the
601 // fall-through count coming into the loop or the continue count, so add
602 // both of those separately. This is coincidentally the same equation as
603 // with while loops but for different reasons.
604 Cnt.setCurrentRegionCount(Cnt.getParentCount() +
605 Cnt.getAdjustedCount() + BC.ContinueCount);
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000606 CountMap[S->getCond()] = PGO.getCurrentRegionCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000607 Visit(S->getCond());
608 Cnt.adjustForControlFlow();
609 Cnt.applyAdjustmentsToRegion(BC.BreakCount + BC.ContinueCount);
610 RecordNextStmtCount = true;
611 }
612
613 void VisitForStmt(const ForStmt *S) {
614 RecordStmtCount(S);
615 if (S->getInit())
616 Visit(S->getInit());
617 RegionCounter Cnt(PGO, S);
618 BreakContinueStack.push_back(BreakContinue());
619 // Visit the body region first. (This is basically the same as a while
620 // loop; see further comments in VisitWhileStmt.)
621 Cnt.beginRegion();
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000622 CountMap[S->getBody()] = PGO.getCurrentRegionCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000623 Visit(S->getBody());
624 Cnt.adjustForControlFlow();
625
626 // The increment is essentially part of the body but it needs to include
627 // the count for all the continue statements.
628 if (S->getInc()) {
629 Cnt.setCurrentRegionCount(PGO.getCurrentRegionCount() +
630 BreakContinueStack.back().ContinueCount);
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000631 CountMap[S->getInc()] = PGO.getCurrentRegionCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000632 Visit(S->getInc());
633 Cnt.adjustForControlFlow();
634 }
635
636 BreakContinue BC = BreakContinueStack.pop_back_val();
637
638 // ...then go back and propagate counts through the condition.
639 if (S->getCond()) {
640 Cnt.setCurrentRegionCount(Cnt.getParentCount() +
641 Cnt.getAdjustedCount() +
642 BC.ContinueCount);
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000643 CountMap[S->getCond()] = PGO.getCurrentRegionCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000644 Visit(S->getCond());
645 Cnt.adjustForControlFlow();
646 }
647 Cnt.applyAdjustmentsToRegion(BC.BreakCount + BC.ContinueCount);
648 RecordNextStmtCount = true;
649 }
650
651 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
652 RecordStmtCount(S);
653 Visit(S->getRangeStmt());
654 Visit(S->getBeginEndStmt());
655 RegionCounter Cnt(PGO, S);
656 BreakContinueStack.push_back(BreakContinue());
657 // Visit the body region first. (This is basically the same as a while
658 // loop; see further comments in VisitWhileStmt.)
659 Cnt.beginRegion();
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000660 CountMap[S->getLoopVarStmt()] = PGO.getCurrentRegionCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000661 Visit(S->getLoopVarStmt());
662 Visit(S->getBody());
663 Cnt.adjustForControlFlow();
664
665 // The increment is essentially part of the body but it needs to include
666 // the count for all the continue statements.
667 Cnt.setCurrentRegionCount(PGO.getCurrentRegionCount() +
668 BreakContinueStack.back().ContinueCount);
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000669 CountMap[S->getInc()] = PGO.getCurrentRegionCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000670 Visit(S->getInc());
671 Cnt.adjustForControlFlow();
672
673 BreakContinue BC = BreakContinueStack.pop_back_val();
674
675 // ...then go back and propagate counts through the condition.
676 Cnt.setCurrentRegionCount(Cnt.getParentCount() +
677 Cnt.getAdjustedCount() +
678 BC.ContinueCount);
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000679 CountMap[S->getCond()] = PGO.getCurrentRegionCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000680 Visit(S->getCond());
681 Cnt.adjustForControlFlow();
682 Cnt.applyAdjustmentsToRegion(BC.BreakCount + BC.ContinueCount);
683 RecordNextStmtCount = true;
684 }
685
686 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
687 RecordStmtCount(S);
688 Visit(S->getElement());
689 RegionCounter Cnt(PGO, S);
690 BreakContinueStack.push_back(BreakContinue());
691 Cnt.beginRegion();
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000692 CountMap[S->getBody()] = PGO.getCurrentRegionCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000693 Visit(S->getBody());
694 BreakContinue BC = BreakContinueStack.pop_back_val();
695 Cnt.adjustForControlFlow();
696 Cnt.applyAdjustmentsToRegion(BC.BreakCount + BC.ContinueCount);
697 RecordNextStmtCount = true;
698 }
699
700 void VisitSwitchStmt(const SwitchStmt *S) {
701 RecordStmtCount(S);
702 Visit(S->getCond());
703 PGO.setCurrentRegionUnreachable();
704 BreakContinueStack.push_back(BreakContinue());
705 Visit(S->getBody());
706 // If the switch is inside a loop, add the continue counts.
707 BreakContinue BC = BreakContinueStack.pop_back_val();
708 if (!BreakContinueStack.empty())
709 BreakContinueStack.back().ContinueCount += BC.ContinueCount;
710 RegionCounter ExitCnt(PGO, S);
711 ExitCnt.beginRegion();
712 RecordNextStmtCount = true;
713 }
714
715 void VisitCaseStmt(const CaseStmt *S) {
716 RecordNextStmtCount = false;
717 RegionCounter Cnt(PGO, S);
718 Cnt.beginRegion(/*AddIncomingFallThrough=*/true);
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000719 CountMap[S] = Cnt.getCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000720 RecordNextStmtCount = true;
721 Visit(S->getSubStmt());
722 }
723
724 void VisitDefaultStmt(const DefaultStmt *S) {
725 RecordNextStmtCount = false;
726 RegionCounter Cnt(PGO, S);
727 Cnt.beginRegion(/*AddIncomingFallThrough=*/true);
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000728 CountMap[S] = Cnt.getCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000729 RecordNextStmtCount = true;
730 Visit(S->getSubStmt());
731 }
732
733 void VisitIfStmt(const IfStmt *S) {
734 RecordStmtCount(S);
735 RegionCounter Cnt(PGO, S);
736 Visit(S->getCond());
737
738 Cnt.beginRegion();
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000739 CountMap[S->getThen()] = PGO.getCurrentRegionCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000740 Visit(S->getThen());
741 Cnt.adjustForControlFlow();
742
743 if (S->getElse()) {
744 Cnt.beginElseRegion();
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000745 CountMap[S->getElse()] = PGO.getCurrentRegionCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000746 Visit(S->getElse());
747 Cnt.adjustForControlFlow();
748 }
749 Cnt.applyAdjustmentsToRegion(0);
750 RecordNextStmtCount = true;
751 }
752
753 void VisitCXXTryStmt(const CXXTryStmt *S) {
754 RecordStmtCount(S);
755 Visit(S->getTryBlock());
756 for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
757 Visit(S->getHandler(I));
758 RegionCounter Cnt(PGO, S);
759 Cnt.beginRegion();
760 RecordNextStmtCount = true;
761 }
762
763 void VisitCXXCatchStmt(const CXXCatchStmt *S) {
764 RecordNextStmtCount = false;
765 RegionCounter Cnt(PGO, S);
766 Cnt.beginRegion();
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000767 CountMap[S] = PGO.getCurrentRegionCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000768 Visit(S->getHandlerBlock());
769 }
770
771 void VisitConditionalOperator(const ConditionalOperator *E) {
772 RecordStmtCount(E);
773 RegionCounter Cnt(PGO, E);
774 Visit(E->getCond());
775
776 Cnt.beginRegion();
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000777 CountMap[E->getTrueExpr()] = PGO.getCurrentRegionCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000778 Visit(E->getTrueExpr());
779 Cnt.adjustForControlFlow();
780
781 Cnt.beginElseRegion();
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000782 CountMap[E->getFalseExpr()] = PGO.getCurrentRegionCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000783 Visit(E->getFalseExpr());
784 Cnt.adjustForControlFlow();
785
786 Cnt.applyAdjustmentsToRegion(0);
787 RecordNextStmtCount = true;
788 }
789
790 void VisitBinLAnd(const BinaryOperator *E) {
791 RecordStmtCount(E);
792 RegionCounter Cnt(PGO, E);
793 Visit(E->getLHS());
794 Cnt.beginRegion();
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000795 CountMap[E->getRHS()] = PGO.getCurrentRegionCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000796 Visit(E->getRHS());
797 Cnt.adjustForControlFlow();
798 Cnt.applyAdjustmentsToRegion(0);
799 RecordNextStmtCount = true;
800 }
801
802 void VisitBinLOr(const BinaryOperator *E) {
803 RecordStmtCount(E);
804 RegionCounter Cnt(PGO, E);
805 Visit(E->getLHS());
806 Cnt.beginRegion();
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000807 CountMap[E->getRHS()] = PGO.getCurrentRegionCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000808 Visit(E->getRHS());
809 Cnt.adjustForControlFlow();
810 Cnt.applyAdjustmentsToRegion(0);
811 RecordNextStmtCount = true;
812 }
813 };
Justin Bogneref512b92014-01-06 22:27:43 +0000814}
815
Duncan P. N. Exon Smithd971cd12014-03-28 17:53:22 +0000816static void emitRuntimeHook(CodeGenModule &CGM) {
Duncan P. N. Exon Smith3fefedb2014-04-11 00:43:16 +0000817 const char *const RuntimeVarName = "__llvm_profile_runtime";
818 const char *const RuntimeUserName = "__llvm_profile_runtime_user";
Duncan P. N. Exon Smithd971cd12014-03-28 17:53:22 +0000819 if (CGM.getModule().getGlobalVariable(RuntimeVarName))
820 return;
821
822 // Declare the runtime hook.
823 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
824 auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
825 auto *Var = new llvm::GlobalVariable(CGM.getModule(), Int32Ty, false,
826 llvm::GlobalValue::ExternalLinkage,
827 nullptr, RuntimeVarName);
828
829 // Make a function that uses it.
830 auto *User = llvm::Function::Create(llvm::FunctionType::get(Int32Ty, false),
831 llvm::GlobalValue::LinkOnceODRLinkage,
832 RuntimeUserName, &CGM.getModule());
833 User->addFnAttr(llvm::Attribute::NoInline);
834 if (CGM.getCodeGenOpts().DisableRedZone)
835 User->addFnAttr(llvm::Attribute::NoRedZone);
836 CGBuilderTy Builder(llvm::BasicBlock::Create(CGM.getLLVMContext(), "", User));
837 auto *Load = Builder.CreateLoad(Var);
838 Builder.CreateRet(Load);
839
840 // Create a use of the function. Now the definition of the runtime variable
841 // should get pulled in, along with any static initializears.
842 CGM.addUsedGlobal(User);
843}
844
Bob Wilsonda1ebed2014-03-06 04:55:41 +0000845void CodeGenPGO::assignRegionCounters(const Decl *D, llvm::Function *Fn) {
Justin Bogneref512b92014-01-06 22:27:43 +0000846 bool InstrumentRegions = CGM.getCodeGenOpts().ProfileInstrGenerate;
Justin Bognerd66a17d2014-03-12 21:06:31 +0000847 PGOProfileData *PGOData = CGM.getPGOData();
848 if (!InstrumentRegions && !PGOData)
Justin Bogneref512b92014-01-06 22:27:43 +0000849 return;
Justin Bogneref512b92014-01-06 22:27:43 +0000850 if (!D)
851 return;
Bob Wilsonda1ebed2014-03-06 04:55:41 +0000852 setFuncName(Fn);
Duncan P. N. Exon Smith7c414512014-03-20 22:50:08 +0000853
854 // Set the linkage for variables based on the function linkage. Usually, we
855 // want to match it, but available_externally and extern_weak both have the
856 // wrong semantics.
Duncan P. N. Exon Smith73f78622014-03-20 22:49:50 +0000857 VarLinkage = Fn->getLinkage();
Duncan P. N. Exon Smith7c414512014-03-20 22:50:08 +0000858 switch (VarLinkage) {
859 case llvm::GlobalValue::ExternalWeakLinkage:
860 VarLinkage = llvm::GlobalValue::LinkOnceAnyLinkage;
861 break;
862 case llvm::GlobalValue::AvailableExternallyLinkage:
863 VarLinkage = llvm::GlobalValue::LinkOnceODRLinkage;
864 break;
865 default:
866 break;
867 }
868
Justin Bogneref512b92014-01-06 22:27:43 +0000869 mapRegionCounters(D);
Duncan P. N. Exon Smithd971cd12014-03-28 17:53:22 +0000870 if (InstrumentRegions) {
871 emitRuntimeHook(CGM);
Justin Bogneref512b92014-01-06 22:27:43 +0000872 emitCounterVariables();
Duncan P. N. Exon Smithd971cd12014-03-28 17:53:22 +0000873 }
Justin Bognerd66a17d2014-03-12 21:06:31 +0000874 if (PGOData) {
875 loadRegionCounts(PGOData);
Bob Wilsonbf854f02014-02-17 19:21:09 +0000876 computeRegionCounts(D);
Justin Bognerd66a17d2014-03-12 21:06:31 +0000877 applyFunctionAttributes(PGOData, Fn);
Bob Wilsonbf854f02014-02-17 19:21:09 +0000878 }
Justin Bogneref512b92014-01-06 22:27:43 +0000879}
880
881void CodeGenPGO::mapRegionCounters(const Decl *D) {
Duncan P. N. Exon Smith1b67cfd2014-03-26 19:26:05 +0000882 RegionCounterMap.reset(new llvm::DenseMap<const Stmt *, unsigned>);
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000883 MapRegionCounters Walker(*RegionCounterMap);
Justin Bogneref512b92014-01-06 22:27:43 +0000884 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
885 Walker.VisitFunctionDecl(FD);
Bob Wilson5ec8fe12014-03-06 06:10:02 +0000886 else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
887 Walker.VisitObjCMethodDecl(MD);
Bob Wilsonc845c002014-03-06 20:24:27 +0000888 else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D))
889 Walker.VisitBlockDecl(BD);
Justin Bogneref512b92014-01-06 22:27:43 +0000890 NumRegionCounters = Walker.NextCounter;
Justin Bognerb4416f52014-03-18 21:58:06 +0000891 // FIXME: The number of counters isn't sufficient for the hash
892 FunctionHash = NumRegionCounters;
Justin Bogneref512b92014-01-06 22:27:43 +0000893}
894
Bob Wilsonbf854f02014-02-17 19:21:09 +0000895void CodeGenPGO::computeRegionCounts(const Decl *D) {
Duncan P. N. Exon Smith1b67cfd2014-03-26 19:26:05 +0000896 StmtCountMap.reset(new llvm::DenseMap<const Stmt *, uint64_t>);
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000897 ComputeRegionCounts Walker(*StmtCountMap, *this);
Bob Wilsonbf854f02014-02-17 19:21:09 +0000898 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
899 Walker.VisitFunctionDecl(FD);
Bob Wilson5ec8fe12014-03-06 06:10:02 +0000900 else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
901 Walker.VisitObjCMethodDecl(MD);
Bob Wilsonc845c002014-03-06 20:24:27 +0000902 else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D))
903 Walker.VisitBlockDecl(BD);
Bob Wilsonbf854f02014-02-17 19:21:09 +0000904}
905
Justin Bognerd66a17d2014-03-12 21:06:31 +0000906void CodeGenPGO::applyFunctionAttributes(PGOProfileData *PGOData,
Justin Bogner4c9c45c2014-03-12 18:14:32 +0000907 llvm::Function *Fn) {
908 if (!haveRegionCounts())
909 return;
910
Justin Bognerd66a17d2014-03-12 21:06:31 +0000911 uint64_t MaxFunctionCount = PGOData->getMaximumFunctionCount();
Justin Bogner4c9c45c2014-03-12 18:14:32 +0000912 uint64_t FunctionCount = getRegionCount(0);
913 if (FunctionCount >= (uint64_t)(0.3 * (double)MaxFunctionCount))
914 // Turn on InlineHint attribute for hot functions.
915 // FIXME: 30% is from preliminary tuning on SPEC, it may not be optimal.
916 Fn->addFnAttr(llvm::Attribute::InlineHint);
917 else if (FunctionCount <= (uint64_t)(0.01 * (double)MaxFunctionCount))
918 // Turn on Cold attribute for cold functions.
919 // FIXME: 1% is from preliminary tuning on SPEC, it may not be optimal.
920 Fn->addFnAttr(llvm::Attribute::Cold);
921}
922
Justin Bogneref512b92014-01-06 22:27:43 +0000923void CodeGenPGO::emitCounterVariables() {
924 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
925 llvm::ArrayType *CounterTy = llvm::ArrayType::get(llvm::Type::getInt64Ty(Ctx),
926 NumRegionCounters);
927 RegionCounters =
Duncan P. N. Exon Smith73f78622014-03-20 22:49:50 +0000928 new llvm::GlobalVariable(CGM.getModule(), CounterTy, false, VarLinkage,
Justin Bogneref512b92014-01-06 22:27:43 +0000929 llvm::Constant::getNullValue(CounterTy),
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000930 getFuncVarName("counters"));
931 RegionCounters->setAlignment(8);
932 RegionCounters->setSection(getCountersSection(CGM));
Justin Bogneref512b92014-01-06 22:27:43 +0000933}
934
935void CodeGenPGO::emitCounterIncrement(CGBuilderTy &Builder, unsigned Counter) {
Bob Wilson749ebc72014-03-06 04:55:28 +0000936 if (!RegionCounters)
Justin Bogneref512b92014-01-06 22:27:43 +0000937 return;
938 llvm::Value *Addr =
939 Builder.CreateConstInBoundsGEP2_64(RegionCounters, 0, Counter);
940 llvm::Value *Count = Builder.CreateLoad(Addr, "pgocount");
941 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
942 Builder.CreateStore(Count, Addr);
943}
944
Justin Bognerd66a17d2014-03-12 21:06:31 +0000945void CodeGenPGO::loadRegionCounts(PGOProfileData *PGOData) {
Justin Bogneref512b92014-01-06 22:27:43 +0000946 // For now, ignore the counts from the PGO data file only if the number of
947 // counters does not match. This could be tightened down in the future to
948 // ignore counts when the input changes in various ways, e.g., by comparing a
949 // hash value based on some characteristics of the input.
Duncan P. N. Exon Smith1b67cfd2014-03-26 19:26:05 +0000950 RegionCounts.reset(new std::vector<uint64_t>);
Justin Bognerb4416f52014-03-18 21:58:06 +0000951 uint64_t Hash;
952 if (PGOData->getFunctionCounts(getFuncName(), Hash, *RegionCounts) ||
Duncan P. N. Exon Smith1b67cfd2014-03-26 19:26:05 +0000953 Hash != FunctionHash || RegionCounts->size() != NumRegionCounters)
954 RegionCounts.reset();
Justin Bogneref512b92014-01-06 22:27:43 +0000955}
956
957void CodeGenPGO::destroyRegionCounters() {
Duncan P. N. Exon Smith1b67cfd2014-03-26 19:26:05 +0000958 RegionCounterMap.reset();
959 StmtCountMap.reset();
960 RegionCounts.reset();
Justin Bogneref512b92014-01-06 22:27:43 +0000961}
962
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000963/// \brief Calculate what to divide by to scale weights.
964///
965/// Given the maximum weight, calculate a divisor that will scale all the
966/// weights to strictly less than UINT32_MAX.
967static uint64_t calculateWeightScale(uint64_t MaxWeight) {
968 return MaxWeight < UINT32_MAX ? 1 : MaxWeight / UINT32_MAX + 1;
969}
970
971/// \brief Scale an individual branch weight (and add 1).
972///
973/// Scale a 64-bit weight down to 32-bits using \c Scale.
974///
975/// According to Laplace's Rule of Succession, it is better to compute the
976/// weight based on the count plus 1, so universally add 1 to the value.
977///
978/// \pre \c Scale was calculated by \a calculateWeightScale() with a weight no
979/// greater than \c Weight.
980static uint32_t scaleBranchWeight(uint64_t Weight, uint64_t Scale) {
981 assert(Scale && "scale by 0?");
982 uint64_t Scaled = Weight / Scale + 1;
983 assert(Scaled <= UINT32_MAX && "overflow 32-bits");
984 return Scaled;
985}
986
Justin Bogneref512b92014-01-06 22:27:43 +0000987llvm::MDNode *CodeGenPGO::createBranchWeights(uint64_t TrueCount,
988 uint64_t FalseCount) {
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000989 // Check for empty weights.
Justin Bogneref512b92014-01-06 22:27:43 +0000990 if (!TrueCount && !FalseCount)
Duncan P. N. Exon Smitha5f804a2014-03-20 18:40:55 +0000991 return nullptr;
Justin Bogneref512b92014-01-06 22:27:43 +0000992
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000993 // Calculate how to scale down to 32-bits.
994 uint64_t Scale = calculateWeightScale(std::max(TrueCount, FalseCount));
995
Justin Bogneref512b92014-01-06 22:27:43 +0000996 llvm::MDBuilder MDHelper(CGM.getLLVMContext());
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000997 return MDHelper.createBranchWeights(scaleBranchWeight(TrueCount, Scale),
998 scaleBranchWeight(FalseCount, Scale));
Justin Bogneref512b92014-01-06 22:27:43 +0000999}
1000
Bob Wilson95a27b02014-02-17 19:20:59 +00001001llvm::MDNode *CodeGenPGO::createBranchWeights(ArrayRef<uint64_t> Weights) {
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +00001002 // We need at least two elements to create meaningful weights.
1003 if (Weights.size() < 2)
Duncan P. N. Exon Smitha5f804a2014-03-20 18:40:55 +00001004 return nullptr;
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +00001005
Justin Bognerf3aefca2014-04-04 02:48:51 +00001006 // Check for empty weights.
1007 uint64_t MaxWeight = *std::max_element(Weights.begin(), Weights.end());
1008 if (MaxWeight == 0)
1009 return nullptr;
1010
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +00001011 // Calculate how to scale down to 32-bits.
Justin Bognerf3aefca2014-04-04 02:48:51 +00001012 uint64_t Scale = calculateWeightScale(MaxWeight);
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +00001013
Justin Bogneref512b92014-01-06 22:27:43 +00001014 SmallVector<uint32_t, 16> ScaledWeights;
1015 ScaledWeights.reserve(Weights.size());
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +00001016 for (uint64_t W : Weights)
1017 ScaledWeights.push_back(scaleBranchWeight(W, Scale));
1018
1019 llvm::MDBuilder MDHelper(CGM.getLLVMContext());
Justin Bogneref512b92014-01-06 22:27:43 +00001020 return MDHelper.createBranchWeights(ScaledWeights);
1021}
Bob Wilsonbf854f02014-02-17 19:21:09 +00001022
1023llvm::MDNode *CodeGenPGO::createLoopWeights(const Stmt *Cond,
1024 RegionCounter &Cnt) {
1025 if (!haveRegionCounts())
Duncan P. N. Exon Smitha5f804a2014-03-20 18:40:55 +00001026 return nullptr;
Bob Wilsonbf854f02014-02-17 19:21:09 +00001027 uint64_t LoopCount = Cnt.getCount();
1028 uint64_t CondCount = 0;
1029 bool Found = getStmtCount(Cond, CondCount);
1030 assert(Found && "missing expected loop condition count");
1031 (void)Found;
1032 if (CondCount == 0)
Duncan P. N. Exon Smitha5f804a2014-03-20 18:40:55 +00001033 return nullptr;
Bob Wilsonbf854f02014-02-17 19:21:09 +00001034 return createBranchWeights(LoopCount,
1035 std::max(CondCount, LoopCount) - LoopCount);
1036}