blob: 80c7e87de36da917352714a640777496141860f6 [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 {
Bob Wilsond8931422014-04-11 17:16:13 +0000324 /// A RecursiveASTVisitor that fills a map of statements to PGO counters.
325 struct MapRegionCounters : public RecursiveASTVisitor<MapRegionCounters> {
Justin Bogneref512b92014-01-06 22:27:43 +0000326 /// 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
Justin Bogner191ec632014-04-11 23:06:35 +0000334 // Blocks and lambdas are handled as separate functions, so we need not
335 // traverse them in the parent context.
336 bool TraverseBlockExpr(BlockExpr *BE) { return true; }
337 bool TraverseLambdaBody(LambdaExpr *LE) { return true; }
Justin Bogner81ab90f2014-04-15 00:50:54 +0000338 bool TraverseCapturedStmt(CapturedStmt *CS) { return true; }
Justin Bogneref512b92014-01-06 22:27:43 +0000339
Bob Wilsond8931422014-04-11 17:16:13 +0000340 bool VisitDecl(const Decl *D) {
341 switch (D->getKind()) {
342 default:
343 break;
344 case Decl::Function:
345 case Decl::CXXMethod:
346 case Decl::CXXConstructor:
347 case Decl::CXXDestructor:
348 case Decl::CXXConversion:
349 case Decl::ObjCMethod:
350 case Decl::Block:
Justin Bogner81ab90f2014-04-15 00:50:54 +0000351 case Decl::Captured:
Bob Wilsond8931422014-04-11 17:16:13 +0000352 CounterMap[D->getBody()] = NextCounter++;
353 break;
354 }
355 return true;
Justin Bogneref512b92014-01-06 22:27:43 +0000356 }
Bob Wilsond8931422014-04-11 17:16:13 +0000357
358 bool VisitStmt(const Stmt *S) {
359 switch (S->getStmtClass()) {
360 default:
361 break;
362 case Stmt::LabelStmtClass:
363 case Stmt::WhileStmtClass:
364 case Stmt::DoStmtClass:
365 case Stmt::ForStmtClass:
366 case Stmt::CXXForRangeStmtClass:
367 case Stmt::ObjCForCollectionStmtClass:
368 case Stmt::SwitchStmtClass:
369 case Stmt::CaseStmtClass:
370 case Stmt::DefaultStmtClass:
371 case Stmt::IfStmtClass:
372 case Stmt::CXXTryStmtClass:
373 case Stmt::CXXCatchStmtClass:
374 case Stmt::ConditionalOperatorClass:
375 case Stmt::BinaryConditionalOperatorClass:
376 CounterMap[S] = NextCounter++;
377 break;
378 case Stmt::BinaryOperatorClass: {
379 const BinaryOperator *BO = cast<BinaryOperator>(S);
380 if (BO->getOpcode() == BO_LAnd || BO->getOpcode() == BO_LOr)
381 CounterMap[S] = NextCounter++;
382 break;
383 }
384 }
385 return true;
Justin Bogneref512b92014-01-06 22:27:43 +0000386 }
387 };
Bob Wilsonbf854f02014-02-17 19:21:09 +0000388
389 /// A StmtVisitor that propagates the raw counts through the AST and
390 /// records the count at statements where the value may change.
391 struct ComputeRegionCounts : public ConstStmtVisitor<ComputeRegionCounts> {
392 /// PGO state.
393 CodeGenPGO &PGO;
394
395 /// A flag that is set when the current count should be recorded on the
396 /// next statement, such as at the exit of a loop.
397 bool RecordNextStmtCount;
398
399 /// The map of statements to count values.
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000400 llvm::DenseMap<const Stmt *, uint64_t> &CountMap;
Bob Wilsonbf854f02014-02-17 19:21:09 +0000401
402 /// BreakContinueStack - Keep counts of breaks and continues inside loops.
403 struct BreakContinue {
404 uint64_t BreakCount;
405 uint64_t ContinueCount;
406 BreakContinue() : BreakCount(0), ContinueCount(0) {}
407 };
408 SmallVector<BreakContinue, 8> BreakContinueStack;
409
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000410 ComputeRegionCounts(llvm::DenseMap<const Stmt *, uint64_t> &CountMap,
411 CodeGenPGO &PGO)
412 : PGO(PGO), RecordNextStmtCount(false), CountMap(CountMap) {}
Bob Wilsonbf854f02014-02-17 19:21:09 +0000413
414 void RecordStmtCount(const Stmt *S) {
415 if (RecordNextStmtCount) {
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000416 CountMap[S] = PGO.getCurrentRegionCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000417 RecordNextStmtCount = false;
418 }
419 }
420
421 void VisitStmt(const Stmt *S) {
422 RecordStmtCount(S);
423 for (Stmt::const_child_range I = S->children(); I; ++I) {
424 if (*I)
425 this->Visit(*I);
426 }
427 }
428
Duncan P. N. Exon Smith4a2f5ae2014-04-10 23:37:36 +0000429 void VisitFunctionDecl(const FunctionDecl *D) {
Bob Wilsond8931422014-04-11 17:16:13 +0000430 // Counter tracks entry to the function body.
Duncan P. N. Exon Smith4a2f5ae2014-04-10 23:37:36 +0000431 RegionCounter Cnt(PGO, D->getBody());
Bob Wilsonbf854f02014-02-17 19:21:09 +0000432 Cnt.beginRegion();
Duncan P. N. Exon Smith4a2f5ae2014-04-10 23:37:36 +0000433 CountMap[D->getBody()] = PGO.getCurrentRegionCount();
434 Visit(D->getBody());
Bob Wilsonbf854f02014-02-17 19:21:09 +0000435 }
436
Justin Bogner191ec632014-04-11 23:06:35 +0000437 // Skip lambda expressions. We visit these as FunctionDecls when we're
438 // generating them and aren't interested in the body when generating a
439 // parent context.
440 void VisitLambdaExpr(const LambdaExpr *LE) {}
441
Justin Bogner81ab90f2014-04-15 00:50:54 +0000442 void VisitCapturedDecl(const CapturedDecl *D) {
443 // Counter tracks entry to the capture body.
444 RegionCounter Cnt(PGO, D->getBody());
445 Cnt.beginRegion();
446 CountMap[D->getBody()] = PGO.getCurrentRegionCount();
447 Visit(D->getBody());
448 }
449
Duncan P. N. Exon Smith4a2f5ae2014-04-10 23:37:36 +0000450 void VisitObjCMethodDecl(const ObjCMethodDecl *D) {
Bob Wilsond8931422014-04-11 17:16:13 +0000451 // Counter tracks entry to the method body.
Duncan P. N. Exon Smith4a2f5ae2014-04-10 23:37:36 +0000452 RegionCounter Cnt(PGO, D->getBody());
Bob Wilson5ec8fe12014-03-06 06:10:02 +0000453 Cnt.beginRegion();
Duncan P. N. Exon Smith4a2f5ae2014-04-10 23:37:36 +0000454 CountMap[D->getBody()] = PGO.getCurrentRegionCount();
455 Visit(D->getBody());
Bob Wilson5ec8fe12014-03-06 06:10:02 +0000456 }
457
Duncan P. N. Exon Smith4a2f5ae2014-04-10 23:37:36 +0000458 void VisitBlockDecl(const BlockDecl *D) {
Bob Wilsond8931422014-04-11 17:16:13 +0000459 // Counter tracks entry to the block body.
Duncan P. N. Exon Smith4a2f5ae2014-04-10 23:37:36 +0000460 RegionCounter Cnt(PGO, D->getBody());
Bob Wilsonc845c002014-03-06 20:24:27 +0000461 Cnt.beginRegion();
Duncan P. N. Exon Smith4a2f5ae2014-04-10 23:37:36 +0000462 CountMap[D->getBody()] = PGO.getCurrentRegionCount();
463 Visit(D->getBody());
Bob Wilsonc845c002014-03-06 20:24:27 +0000464 }
465
Bob Wilsonbf854f02014-02-17 19:21:09 +0000466 void VisitReturnStmt(const ReturnStmt *S) {
467 RecordStmtCount(S);
468 if (S->getRetValue())
469 Visit(S->getRetValue());
470 PGO.setCurrentRegionUnreachable();
471 RecordNextStmtCount = true;
472 }
473
474 void VisitGotoStmt(const GotoStmt *S) {
475 RecordStmtCount(S);
476 PGO.setCurrentRegionUnreachable();
477 RecordNextStmtCount = true;
478 }
479
480 void VisitLabelStmt(const LabelStmt *S) {
481 RecordNextStmtCount = false;
Bob Wilsond8931422014-04-11 17:16:13 +0000482 // Counter tracks the block following the label.
Bob Wilsonbf854f02014-02-17 19:21:09 +0000483 RegionCounter Cnt(PGO, S);
484 Cnt.beginRegion();
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000485 CountMap[S] = PGO.getCurrentRegionCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000486 Visit(S->getSubStmt());
487 }
488
489 void VisitBreakStmt(const BreakStmt *S) {
490 RecordStmtCount(S);
491 assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
492 BreakContinueStack.back().BreakCount += PGO.getCurrentRegionCount();
493 PGO.setCurrentRegionUnreachable();
494 RecordNextStmtCount = true;
495 }
496
497 void VisitContinueStmt(const ContinueStmt *S) {
498 RecordStmtCount(S);
499 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
500 BreakContinueStack.back().ContinueCount += PGO.getCurrentRegionCount();
501 PGO.setCurrentRegionUnreachable();
502 RecordNextStmtCount = true;
503 }
504
505 void VisitWhileStmt(const WhileStmt *S) {
506 RecordStmtCount(S);
Bob Wilsond8931422014-04-11 17:16:13 +0000507 // Counter tracks the body of the loop.
Bob Wilsonbf854f02014-02-17 19:21:09 +0000508 RegionCounter Cnt(PGO, S);
509 BreakContinueStack.push_back(BreakContinue());
510 // Visit the body region first so the break/continue adjustments can be
511 // included when visiting the condition.
512 Cnt.beginRegion();
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000513 CountMap[S->getBody()] = PGO.getCurrentRegionCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000514 Visit(S->getBody());
515 Cnt.adjustForControlFlow();
516
517 // ...then go back and propagate counts through the condition. The count
518 // at the start of the condition is the sum of the incoming edges,
519 // the backedge from the end of the loop body, and the edges from
520 // continue statements.
521 BreakContinue BC = BreakContinueStack.pop_back_val();
522 Cnt.setCurrentRegionCount(Cnt.getParentCount() +
523 Cnt.getAdjustedCount() + BC.ContinueCount);
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000524 CountMap[S->getCond()] = PGO.getCurrentRegionCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000525 Visit(S->getCond());
526 Cnt.adjustForControlFlow();
527 Cnt.applyAdjustmentsToRegion(BC.BreakCount + BC.ContinueCount);
528 RecordNextStmtCount = true;
529 }
530
531 void VisitDoStmt(const DoStmt *S) {
532 RecordStmtCount(S);
Bob Wilsond8931422014-04-11 17:16:13 +0000533 // Counter tracks the body of the loop.
Bob Wilsonbf854f02014-02-17 19:21:09 +0000534 RegionCounter Cnt(PGO, S);
535 BreakContinueStack.push_back(BreakContinue());
536 Cnt.beginRegion(/*AddIncomingFallThrough=*/true);
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000537 CountMap[S->getBody()] = PGO.getCurrentRegionCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000538 Visit(S->getBody());
539 Cnt.adjustForControlFlow();
540
541 BreakContinue BC = BreakContinueStack.pop_back_val();
542 // The count at the start of the condition is equal to the count at the
543 // end of the body. The adjusted count does not include either the
544 // fall-through count coming into the loop or the continue count, so add
545 // both of those separately. This is coincidentally the same equation as
546 // with while loops but for different reasons.
547 Cnt.setCurrentRegionCount(Cnt.getParentCount() +
548 Cnt.getAdjustedCount() + BC.ContinueCount);
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000549 CountMap[S->getCond()] = PGO.getCurrentRegionCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000550 Visit(S->getCond());
551 Cnt.adjustForControlFlow();
552 Cnt.applyAdjustmentsToRegion(BC.BreakCount + BC.ContinueCount);
553 RecordNextStmtCount = true;
554 }
555
556 void VisitForStmt(const ForStmt *S) {
557 RecordStmtCount(S);
558 if (S->getInit())
559 Visit(S->getInit());
Bob Wilsond8931422014-04-11 17:16:13 +0000560 // Counter tracks the body of the loop.
Bob Wilsonbf854f02014-02-17 19:21:09 +0000561 RegionCounter Cnt(PGO, S);
562 BreakContinueStack.push_back(BreakContinue());
563 // Visit the body region first. (This is basically the same as a while
564 // loop; see further comments in VisitWhileStmt.)
565 Cnt.beginRegion();
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000566 CountMap[S->getBody()] = PGO.getCurrentRegionCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000567 Visit(S->getBody());
568 Cnt.adjustForControlFlow();
569
570 // The increment is essentially part of the body but it needs to include
571 // the count for all the continue statements.
572 if (S->getInc()) {
573 Cnt.setCurrentRegionCount(PGO.getCurrentRegionCount() +
574 BreakContinueStack.back().ContinueCount);
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000575 CountMap[S->getInc()] = PGO.getCurrentRegionCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000576 Visit(S->getInc());
577 Cnt.adjustForControlFlow();
578 }
579
580 BreakContinue BC = BreakContinueStack.pop_back_val();
581
582 // ...then go back and propagate counts through the condition.
583 if (S->getCond()) {
584 Cnt.setCurrentRegionCount(Cnt.getParentCount() +
585 Cnt.getAdjustedCount() +
586 BC.ContinueCount);
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000587 CountMap[S->getCond()] = PGO.getCurrentRegionCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000588 Visit(S->getCond());
589 Cnt.adjustForControlFlow();
590 }
591 Cnt.applyAdjustmentsToRegion(BC.BreakCount + BC.ContinueCount);
592 RecordNextStmtCount = true;
593 }
594
595 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
596 RecordStmtCount(S);
597 Visit(S->getRangeStmt());
598 Visit(S->getBeginEndStmt());
Bob Wilsond8931422014-04-11 17:16:13 +0000599 // Counter tracks the body of the loop.
Bob Wilsonbf854f02014-02-17 19:21:09 +0000600 RegionCounter Cnt(PGO, S);
601 BreakContinueStack.push_back(BreakContinue());
602 // Visit the body region first. (This is basically the same as a while
603 // loop; see further comments in VisitWhileStmt.)
604 Cnt.beginRegion();
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000605 CountMap[S->getLoopVarStmt()] = PGO.getCurrentRegionCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000606 Visit(S->getLoopVarStmt());
607 Visit(S->getBody());
608 Cnt.adjustForControlFlow();
609
610 // The increment is essentially part of the body but it needs to include
611 // the count for all the continue statements.
612 Cnt.setCurrentRegionCount(PGO.getCurrentRegionCount() +
613 BreakContinueStack.back().ContinueCount);
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000614 CountMap[S->getInc()] = PGO.getCurrentRegionCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000615 Visit(S->getInc());
616 Cnt.adjustForControlFlow();
617
618 BreakContinue BC = BreakContinueStack.pop_back_val();
619
620 // ...then go back and propagate counts through the condition.
621 Cnt.setCurrentRegionCount(Cnt.getParentCount() +
622 Cnt.getAdjustedCount() +
623 BC.ContinueCount);
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000624 CountMap[S->getCond()] = PGO.getCurrentRegionCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000625 Visit(S->getCond());
626 Cnt.adjustForControlFlow();
627 Cnt.applyAdjustmentsToRegion(BC.BreakCount + BC.ContinueCount);
628 RecordNextStmtCount = true;
629 }
630
631 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
632 RecordStmtCount(S);
633 Visit(S->getElement());
Bob Wilsond8931422014-04-11 17:16:13 +0000634 // Counter tracks the body of the loop.
Bob Wilsonbf854f02014-02-17 19:21:09 +0000635 RegionCounter Cnt(PGO, S);
636 BreakContinueStack.push_back(BreakContinue());
637 Cnt.beginRegion();
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000638 CountMap[S->getBody()] = PGO.getCurrentRegionCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000639 Visit(S->getBody());
640 BreakContinue BC = BreakContinueStack.pop_back_val();
641 Cnt.adjustForControlFlow();
642 Cnt.applyAdjustmentsToRegion(BC.BreakCount + BC.ContinueCount);
643 RecordNextStmtCount = true;
644 }
645
646 void VisitSwitchStmt(const SwitchStmt *S) {
647 RecordStmtCount(S);
648 Visit(S->getCond());
649 PGO.setCurrentRegionUnreachable();
650 BreakContinueStack.push_back(BreakContinue());
651 Visit(S->getBody());
652 // If the switch is inside a loop, add the continue counts.
653 BreakContinue BC = BreakContinueStack.pop_back_val();
654 if (!BreakContinueStack.empty())
655 BreakContinueStack.back().ContinueCount += BC.ContinueCount;
Bob Wilsond8931422014-04-11 17:16:13 +0000656 // Counter tracks the exit block of the switch.
Bob Wilsonbf854f02014-02-17 19:21:09 +0000657 RegionCounter ExitCnt(PGO, S);
658 ExitCnt.beginRegion();
659 RecordNextStmtCount = true;
660 }
661
662 void VisitCaseStmt(const CaseStmt *S) {
663 RecordNextStmtCount = false;
Bob Wilsond8931422014-04-11 17:16:13 +0000664 // Counter for this particular case. This counts only jumps from the
665 // switch header and does not include fallthrough from the case before
666 // this one.
Bob Wilsonbf854f02014-02-17 19:21:09 +0000667 RegionCounter Cnt(PGO, S);
668 Cnt.beginRegion(/*AddIncomingFallThrough=*/true);
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000669 CountMap[S] = Cnt.getCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000670 RecordNextStmtCount = true;
671 Visit(S->getSubStmt());
672 }
673
674 void VisitDefaultStmt(const DefaultStmt *S) {
675 RecordNextStmtCount = false;
Bob Wilsond8931422014-04-11 17:16:13 +0000676 // Counter for this default case. This does not include fallthrough from
677 // the previous case.
Bob Wilsonbf854f02014-02-17 19:21:09 +0000678 RegionCounter Cnt(PGO, S);
679 Cnt.beginRegion(/*AddIncomingFallThrough=*/true);
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000680 CountMap[S] = Cnt.getCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000681 RecordNextStmtCount = true;
682 Visit(S->getSubStmt());
683 }
684
685 void VisitIfStmt(const IfStmt *S) {
686 RecordStmtCount(S);
Bob Wilsond8931422014-04-11 17:16:13 +0000687 // Counter tracks the "then" part of an if statement. The count for
688 // the "else" part, if it exists, will be calculated from this counter.
Bob Wilsonbf854f02014-02-17 19:21:09 +0000689 RegionCounter Cnt(PGO, S);
690 Visit(S->getCond());
691
692 Cnt.beginRegion();
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000693 CountMap[S->getThen()] = PGO.getCurrentRegionCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000694 Visit(S->getThen());
695 Cnt.adjustForControlFlow();
696
697 if (S->getElse()) {
698 Cnt.beginElseRegion();
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000699 CountMap[S->getElse()] = PGO.getCurrentRegionCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000700 Visit(S->getElse());
701 Cnt.adjustForControlFlow();
702 }
703 Cnt.applyAdjustmentsToRegion(0);
704 RecordNextStmtCount = true;
705 }
706
707 void VisitCXXTryStmt(const CXXTryStmt *S) {
708 RecordStmtCount(S);
709 Visit(S->getTryBlock());
710 for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
711 Visit(S->getHandler(I));
Bob Wilsond8931422014-04-11 17:16:13 +0000712 // Counter tracks the continuation block of the try statement.
Bob Wilsonbf854f02014-02-17 19:21:09 +0000713 RegionCounter Cnt(PGO, S);
714 Cnt.beginRegion();
715 RecordNextStmtCount = true;
716 }
717
718 void VisitCXXCatchStmt(const CXXCatchStmt *S) {
719 RecordNextStmtCount = false;
Bob Wilsond8931422014-04-11 17:16:13 +0000720 // Counter tracks the catch statement's handler block.
Bob Wilsonbf854f02014-02-17 19:21:09 +0000721 RegionCounter Cnt(PGO, S);
722 Cnt.beginRegion();
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000723 CountMap[S] = PGO.getCurrentRegionCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000724 Visit(S->getHandlerBlock());
725 }
726
Justin Bogner53c55d92014-04-11 06:10:10 +0000727 void VisitAbstractConditionalOperator(
728 const AbstractConditionalOperator *E) {
Bob Wilsonbf854f02014-02-17 19:21:09 +0000729 RecordStmtCount(E);
Bob Wilsond8931422014-04-11 17:16:13 +0000730 // Counter tracks the "true" part of a conditional operator. The
731 // count in the "false" part will be calculated from this counter.
Bob Wilsonbf854f02014-02-17 19:21:09 +0000732 RegionCounter Cnt(PGO, E);
733 Visit(E->getCond());
734
735 Cnt.beginRegion();
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000736 CountMap[E->getTrueExpr()] = PGO.getCurrentRegionCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000737 Visit(E->getTrueExpr());
738 Cnt.adjustForControlFlow();
739
740 Cnt.beginElseRegion();
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000741 CountMap[E->getFalseExpr()] = PGO.getCurrentRegionCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000742 Visit(E->getFalseExpr());
743 Cnt.adjustForControlFlow();
744
745 Cnt.applyAdjustmentsToRegion(0);
746 RecordNextStmtCount = true;
747 }
748
749 void VisitBinLAnd(const BinaryOperator *E) {
750 RecordStmtCount(E);
Bob Wilsond8931422014-04-11 17:16:13 +0000751 // Counter tracks the right hand side of a logical and operator.
Bob Wilsonbf854f02014-02-17 19:21:09 +0000752 RegionCounter Cnt(PGO, E);
753 Visit(E->getLHS());
754 Cnt.beginRegion();
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000755 CountMap[E->getRHS()] = PGO.getCurrentRegionCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000756 Visit(E->getRHS());
757 Cnt.adjustForControlFlow();
758 Cnt.applyAdjustmentsToRegion(0);
759 RecordNextStmtCount = true;
760 }
761
762 void VisitBinLOr(const BinaryOperator *E) {
763 RecordStmtCount(E);
Bob Wilsond8931422014-04-11 17:16:13 +0000764 // Counter tracks the right hand side of a logical or operator.
Bob Wilsonbf854f02014-02-17 19:21:09 +0000765 RegionCounter Cnt(PGO, E);
766 Visit(E->getLHS());
767 Cnt.beginRegion();
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000768 CountMap[E->getRHS()] = PGO.getCurrentRegionCount();
Bob Wilsonbf854f02014-02-17 19:21:09 +0000769 Visit(E->getRHS());
770 Cnt.adjustForControlFlow();
771 Cnt.applyAdjustmentsToRegion(0);
772 RecordNextStmtCount = true;
773 }
774 };
Justin Bogneref512b92014-01-06 22:27:43 +0000775}
776
Duncan P. N. Exon Smithd971cd12014-03-28 17:53:22 +0000777static void emitRuntimeHook(CodeGenModule &CGM) {
Duncan P. N. Exon Smith3fefedb2014-04-11 00:43:16 +0000778 const char *const RuntimeVarName = "__llvm_profile_runtime";
779 const char *const RuntimeUserName = "__llvm_profile_runtime_user";
Duncan P. N. Exon Smithd971cd12014-03-28 17:53:22 +0000780 if (CGM.getModule().getGlobalVariable(RuntimeVarName))
781 return;
782
783 // Declare the runtime hook.
784 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
785 auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
786 auto *Var = new llvm::GlobalVariable(CGM.getModule(), Int32Ty, false,
787 llvm::GlobalValue::ExternalLinkage,
788 nullptr, RuntimeVarName);
789
790 // Make a function that uses it.
791 auto *User = llvm::Function::Create(llvm::FunctionType::get(Int32Ty, false),
792 llvm::GlobalValue::LinkOnceODRLinkage,
793 RuntimeUserName, &CGM.getModule());
794 User->addFnAttr(llvm::Attribute::NoInline);
795 if (CGM.getCodeGenOpts().DisableRedZone)
796 User->addFnAttr(llvm::Attribute::NoRedZone);
797 CGBuilderTy Builder(llvm::BasicBlock::Create(CGM.getLLVMContext(), "", User));
798 auto *Load = Builder.CreateLoad(Var);
799 Builder.CreateRet(Load);
800
801 // Create a use of the function. Now the definition of the runtime variable
802 // should get pulled in, along with any static initializears.
803 CGM.addUsedGlobal(User);
804}
805
Bob Wilsonda1ebed2014-03-06 04:55:41 +0000806void CodeGenPGO::assignRegionCounters(const Decl *D, llvm::Function *Fn) {
Justin Bogneref512b92014-01-06 22:27:43 +0000807 bool InstrumentRegions = CGM.getCodeGenOpts().ProfileInstrGenerate;
Justin Bognerd66a17d2014-03-12 21:06:31 +0000808 PGOProfileData *PGOData = CGM.getPGOData();
809 if (!InstrumentRegions && !PGOData)
Justin Bogneref512b92014-01-06 22:27:43 +0000810 return;
Justin Bogneref512b92014-01-06 22:27:43 +0000811 if (!D)
812 return;
Bob Wilsonda1ebed2014-03-06 04:55:41 +0000813 setFuncName(Fn);
Duncan P. N. Exon Smith7c414512014-03-20 22:50:08 +0000814
815 // Set the linkage for variables based on the function linkage. Usually, we
816 // want to match it, but available_externally and extern_weak both have the
817 // wrong semantics.
Duncan P. N. Exon Smith73f78622014-03-20 22:49:50 +0000818 VarLinkage = Fn->getLinkage();
Duncan P. N. Exon Smith7c414512014-03-20 22:50:08 +0000819 switch (VarLinkage) {
820 case llvm::GlobalValue::ExternalWeakLinkage:
821 VarLinkage = llvm::GlobalValue::LinkOnceAnyLinkage;
822 break;
823 case llvm::GlobalValue::AvailableExternallyLinkage:
824 VarLinkage = llvm::GlobalValue::LinkOnceODRLinkage;
825 break;
826 default:
827 break;
828 }
829
Justin Bogneref512b92014-01-06 22:27:43 +0000830 mapRegionCounters(D);
Duncan P. N. Exon Smithd971cd12014-03-28 17:53:22 +0000831 if (InstrumentRegions) {
832 emitRuntimeHook(CGM);
Justin Bogneref512b92014-01-06 22:27:43 +0000833 emitCounterVariables();
Duncan P. N. Exon Smithd971cd12014-03-28 17:53:22 +0000834 }
Justin Bognerd66a17d2014-03-12 21:06:31 +0000835 if (PGOData) {
836 loadRegionCounts(PGOData);
Bob Wilsonbf854f02014-02-17 19:21:09 +0000837 computeRegionCounts(D);
Justin Bognerd66a17d2014-03-12 21:06:31 +0000838 applyFunctionAttributes(PGOData, Fn);
Bob Wilsonbf854f02014-02-17 19:21:09 +0000839 }
Justin Bogneref512b92014-01-06 22:27:43 +0000840}
841
842void CodeGenPGO::mapRegionCounters(const Decl *D) {
Duncan P. N. Exon Smith1b67cfd2014-03-26 19:26:05 +0000843 RegionCounterMap.reset(new llvm::DenseMap<const Stmt *, unsigned>);
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000844 MapRegionCounters Walker(*RegionCounterMap);
Justin Bogneref512b92014-01-06 22:27:43 +0000845 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
Bob Wilsond8931422014-04-11 17:16:13 +0000846 Walker.TraverseDecl(const_cast<FunctionDecl *>(FD));
Bob Wilson5ec8fe12014-03-06 06:10:02 +0000847 else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
Bob Wilsond8931422014-04-11 17:16:13 +0000848 Walker.TraverseDecl(const_cast<ObjCMethodDecl *>(MD));
Bob Wilsonc845c002014-03-06 20:24:27 +0000849 else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D))
Bob Wilsond8931422014-04-11 17:16:13 +0000850 Walker.TraverseDecl(const_cast<BlockDecl *>(BD));
Justin Bogner81ab90f2014-04-15 00:50:54 +0000851 else if (const CapturedDecl *CD = dyn_cast_or_null<CapturedDecl>(D))
852 Walker.TraverseDecl(const_cast<CapturedDecl *>(CD));
Justin Bogneref512b92014-01-06 22:27:43 +0000853 NumRegionCounters = Walker.NextCounter;
Justin Bognerb4416f52014-03-18 21:58:06 +0000854 // FIXME: The number of counters isn't sufficient for the hash
855 FunctionHash = NumRegionCounters;
Justin Bogneref512b92014-01-06 22:27:43 +0000856}
857
Bob Wilsonbf854f02014-02-17 19:21:09 +0000858void CodeGenPGO::computeRegionCounts(const Decl *D) {
Duncan P. N. Exon Smith1b67cfd2014-03-26 19:26:05 +0000859 StmtCountMap.reset(new llvm::DenseMap<const Stmt *, uint64_t>);
Duncan P. N. Exon Smith3586be72014-03-26 19:26:02 +0000860 ComputeRegionCounts Walker(*StmtCountMap, *this);
Bob Wilsonbf854f02014-02-17 19:21:09 +0000861 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
862 Walker.VisitFunctionDecl(FD);
Bob Wilson5ec8fe12014-03-06 06:10:02 +0000863 else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
864 Walker.VisitObjCMethodDecl(MD);
Bob Wilsonc845c002014-03-06 20:24:27 +0000865 else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D))
866 Walker.VisitBlockDecl(BD);
Justin Bogner81ab90f2014-04-15 00:50:54 +0000867 else if (const CapturedDecl *CD = dyn_cast_or_null<CapturedDecl>(D))
868 Walker.VisitCapturedDecl(const_cast<CapturedDecl *>(CD));
Bob Wilsonbf854f02014-02-17 19:21:09 +0000869}
870
Justin Bognerd66a17d2014-03-12 21:06:31 +0000871void CodeGenPGO::applyFunctionAttributes(PGOProfileData *PGOData,
Justin Bogner4c9c45c2014-03-12 18:14:32 +0000872 llvm::Function *Fn) {
873 if (!haveRegionCounts())
874 return;
875
Justin Bognerd66a17d2014-03-12 21:06:31 +0000876 uint64_t MaxFunctionCount = PGOData->getMaximumFunctionCount();
Justin Bogner4c9c45c2014-03-12 18:14:32 +0000877 uint64_t FunctionCount = getRegionCount(0);
878 if (FunctionCount >= (uint64_t)(0.3 * (double)MaxFunctionCount))
879 // Turn on InlineHint attribute for hot functions.
880 // FIXME: 30% is from preliminary tuning on SPEC, it may not be optimal.
881 Fn->addFnAttr(llvm::Attribute::InlineHint);
882 else if (FunctionCount <= (uint64_t)(0.01 * (double)MaxFunctionCount))
883 // Turn on Cold attribute for cold functions.
884 // FIXME: 1% is from preliminary tuning on SPEC, it may not be optimal.
885 Fn->addFnAttr(llvm::Attribute::Cold);
886}
887
Justin Bogneref512b92014-01-06 22:27:43 +0000888void CodeGenPGO::emitCounterVariables() {
889 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
890 llvm::ArrayType *CounterTy = llvm::ArrayType::get(llvm::Type::getInt64Ty(Ctx),
891 NumRegionCounters);
892 RegionCounters =
Duncan P. N. Exon Smith73f78622014-03-20 22:49:50 +0000893 new llvm::GlobalVariable(CGM.getModule(), CounterTy, false, VarLinkage,
Justin Bogneref512b92014-01-06 22:27:43 +0000894 llvm::Constant::getNullValue(CounterTy),
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000895 getFuncVarName("counters"));
896 RegionCounters->setAlignment(8);
897 RegionCounters->setSection(getCountersSection(CGM));
Justin Bogneref512b92014-01-06 22:27:43 +0000898}
899
900void CodeGenPGO::emitCounterIncrement(CGBuilderTy &Builder, unsigned Counter) {
Bob Wilson749ebc72014-03-06 04:55:28 +0000901 if (!RegionCounters)
Justin Bogneref512b92014-01-06 22:27:43 +0000902 return;
903 llvm::Value *Addr =
904 Builder.CreateConstInBoundsGEP2_64(RegionCounters, 0, Counter);
905 llvm::Value *Count = Builder.CreateLoad(Addr, "pgocount");
906 Count = Builder.CreateAdd(Count, Builder.getInt64(1));
907 Builder.CreateStore(Count, Addr);
908}
909
Justin Bognerd66a17d2014-03-12 21:06:31 +0000910void CodeGenPGO::loadRegionCounts(PGOProfileData *PGOData) {
Justin Bogneref512b92014-01-06 22:27:43 +0000911 // For now, ignore the counts from the PGO data file only if the number of
912 // counters does not match. This could be tightened down in the future to
913 // ignore counts when the input changes in various ways, e.g., by comparing a
914 // hash value based on some characteristics of the input.
Duncan P. N. Exon Smith1b67cfd2014-03-26 19:26:05 +0000915 RegionCounts.reset(new std::vector<uint64_t>);
Justin Bognerb4416f52014-03-18 21:58:06 +0000916 uint64_t Hash;
917 if (PGOData->getFunctionCounts(getFuncName(), Hash, *RegionCounts) ||
Duncan P. N. Exon Smith1b67cfd2014-03-26 19:26:05 +0000918 Hash != FunctionHash || RegionCounts->size() != NumRegionCounters)
919 RegionCounts.reset();
Justin Bogneref512b92014-01-06 22:27:43 +0000920}
921
922void CodeGenPGO::destroyRegionCounters() {
Duncan P. N. Exon Smith1b67cfd2014-03-26 19:26:05 +0000923 RegionCounterMap.reset();
924 StmtCountMap.reset();
925 RegionCounts.reset();
Justin Bogneref512b92014-01-06 22:27:43 +0000926}
927
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000928/// \brief Calculate what to divide by to scale weights.
929///
930/// Given the maximum weight, calculate a divisor that will scale all the
931/// weights to strictly less than UINT32_MAX.
932static uint64_t calculateWeightScale(uint64_t MaxWeight) {
933 return MaxWeight < UINT32_MAX ? 1 : MaxWeight / UINT32_MAX + 1;
934}
935
936/// \brief Scale an individual branch weight (and add 1).
937///
938/// Scale a 64-bit weight down to 32-bits using \c Scale.
939///
940/// According to Laplace's Rule of Succession, it is better to compute the
941/// weight based on the count plus 1, so universally add 1 to the value.
942///
943/// \pre \c Scale was calculated by \a calculateWeightScale() with a weight no
944/// greater than \c Weight.
945static uint32_t scaleBranchWeight(uint64_t Weight, uint64_t Scale) {
946 assert(Scale && "scale by 0?");
947 uint64_t Scaled = Weight / Scale + 1;
948 assert(Scaled <= UINT32_MAX && "overflow 32-bits");
949 return Scaled;
950}
951
Justin Bogneref512b92014-01-06 22:27:43 +0000952llvm::MDNode *CodeGenPGO::createBranchWeights(uint64_t TrueCount,
953 uint64_t FalseCount) {
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000954 // Check for empty weights.
Justin Bogneref512b92014-01-06 22:27:43 +0000955 if (!TrueCount && !FalseCount)
Duncan P. N. Exon Smitha5f804a2014-03-20 18:40:55 +0000956 return nullptr;
Justin Bogneref512b92014-01-06 22:27:43 +0000957
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000958 // Calculate how to scale down to 32-bits.
959 uint64_t Scale = calculateWeightScale(std::max(TrueCount, FalseCount));
960
Justin Bogneref512b92014-01-06 22:27:43 +0000961 llvm::MDBuilder MDHelper(CGM.getLLVMContext());
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000962 return MDHelper.createBranchWeights(scaleBranchWeight(TrueCount, Scale),
963 scaleBranchWeight(FalseCount, Scale));
Justin Bogneref512b92014-01-06 22:27:43 +0000964}
965
Bob Wilson95a27b02014-02-17 19:20:59 +0000966llvm::MDNode *CodeGenPGO::createBranchWeights(ArrayRef<uint64_t> Weights) {
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000967 // We need at least two elements to create meaningful weights.
968 if (Weights.size() < 2)
Duncan P. N. Exon Smitha5f804a2014-03-20 18:40:55 +0000969 return nullptr;
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000970
Justin Bognerf3aefca2014-04-04 02:48:51 +0000971 // Check for empty weights.
972 uint64_t MaxWeight = *std::max_element(Weights.begin(), Weights.end());
973 if (MaxWeight == 0)
974 return nullptr;
975
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000976 // Calculate how to scale down to 32-bits.
Justin Bognerf3aefca2014-04-04 02:48:51 +0000977 uint64_t Scale = calculateWeightScale(MaxWeight);
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000978
Justin Bogneref512b92014-01-06 22:27:43 +0000979 SmallVector<uint32_t, 16> ScaledWeights;
980 ScaledWeights.reserve(Weights.size());
Duncan P. N. Exon Smith38402dc2014-03-11 18:18:10 +0000981 for (uint64_t W : Weights)
982 ScaledWeights.push_back(scaleBranchWeight(W, Scale));
983
984 llvm::MDBuilder MDHelper(CGM.getLLVMContext());
Justin Bogneref512b92014-01-06 22:27:43 +0000985 return MDHelper.createBranchWeights(ScaledWeights);
986}
Bob Wilsonbf854f02014-02-17 19:21:09 +0000987
988llvm::MDNode *CodeGenPGO::createLoopWeights(const Stmt *Cond,
989 RegionCounter &Cnt) {
990 if (!haveRegionCounts())
Duncan P. N. Exon Smitha5f804a2014-03-20 18:40:55 +0000991 return nullptr;
Bob Wilsonbf854f02014-02-17 19:21:09 +0000992 uint64_t LoopCount = Cnt.getCount();
993 uint64_t CondCount = 0;
994 bool Found = getStmtCount(Cond, CondCount);
995 assert(Found && "missing expected loop condition count");
996 (void)Found;
997 if (CondCount == 0)
Duncan P. N. Exon Smitha5f804a2014-03-20 18:40:55 +0000998 return nullptr;
Bob Wilsonbf854f02014-02-17 19:21:09 +0000999 return createBranchWeights(LoopCount,
1000 std::max(CondCount, LoopCount) - LoopCount);
1001}