1 //===--- 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"
18 #include "llvm/Config/config.h" // for strtoull()/strtoul() define
19 #include "llvm/IR/MDBuilder.h"
20 #include "llvm/Support/FileSystem.h"
21 
22 using namespace clang;
23 using namespace CodeGen;
24 
25 static 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 
31 PGOProfileData::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     }
61     StringRef FuncName(FuncStart, CurPtr - FuncStart);
62 
63     // 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 
70     // Read the number of counters.
71     char *EndPtr;
72     unsigned NumCounters = strtoul(++CurPtr, &EndPtr, 10);
73     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.
80     uint64_t Count = strtoull(CurPtr, &EndPtr, 10);
81     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 
107 bool PGOProfileData::getFunctionCounts(StringRef FuncName, uint64_t &FuncHash,
108                                        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");
119 
120   char *EndPtr;
121   // Read the function hash.
122   FuncHash = strtoull(++CurPtr, &EndPtr, 10);
123   assert(EndPtr != CurPtr && *EndPtr == '\n' &&
124          "pgo-data file has corrupted function hash");
125   CurPtr = EndPtr;
126 
127   // Read the number of counters.
128   unsigned NumCounters = strtoul(++CurPtr, &EndPtr, 10);
129   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.
137     uint64_t Count = strtoull(CurPtr, &EndPtr, 10);
138     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 
155 void CodeGenPGO::setFuncName(llvm::Function *Fn) {
156   RawFuncName = Fn->getName();
157 
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.
161   if (RawFuncName[0] == '\1')
162     RawFuncName = RawFuncName.substr(1);
163 
164   if (!Fn->hasLocalLinkage()) {
165     PrefixedFuncName.reset(new std::string(RawFuncName));
166     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.
173   PrefixedFuncName.reset(new std::string(CGM.getCodeGenOpts().MainFileName));
174   if (PrefixedFuncName->empty())
175     PrefixedFuncName->assign("<unknown>");
176   PrefixedFuncName->append(":");
177   PrefixedFuncName->append(RawFuncName);
178 }
179 
180 static llvm::Function *getRegisterFunc(CodeGenModule &CGM) {
181   return CGM.getModule().getFunction("__llvm_profile_register_functions");
182 }
183 
184 static llvm::BasicBlock *getOrInsertRegisterBB(CodeGenModule &CGM) {
185   // Don't do this for Darwin.  compiler-rt uses linker magic.
186   if (CGM.getTarget().getTriple().isOSDarwin())
187     return nullptr;
188 
189   // 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,
198                                            "__llvm_profile_register_functions",
199                                            &CGM.getModule());
200   RegisterF->setUnnamedAddr(true);
201   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 
211 static 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);
215   return CGM.getModule().getOrInsertFunction("__llvm_profile_register_function",
216                                              RuntimeRegisterTy);
217 }
218 
219 static bool isMachO(const CodeGenModule &CGM) {
220   return CGM.getTarget().getTriple().isOSBinFormatMachO();
221 }
222 
223 static StringRef getCountersSection(const CodeGenModule &CGM) {
224   return isMachO(CGM) ? "__DATA,__llvm_prf_cnts" : "__llvm_prf_cnts";
225 }
226 
227 static StringRef getNameSection(const CodeGenModule &CGM) {
228   return isMachO(CGM) ? "__DATA,__llvm_prf_names" : "__llvm_prf_names";
229 }
230 
231 static StringRef getDataSection(const CodeGenModule &CGM) {
232   return isMachO(CGM) ? "__DATA,__llvm_prf_data" : "__llvm_prf_data";
233 }
234 
235 llvm::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(),
241                                         true, VarLinkage, VarName,
242                                         getFuncVarName("name"));
243   Name->setSection(getNameSection(CGM));
244   Name->setAlignment(1);
245 
246   // Create data variable.
247   auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
248   auto *Int64Ty = llvm::Type::getInt64Ty(Ctx);
249   auto *Int8PtrTy = llvm::Type::getInt8PtrTy(Ctx);
250   auto *Int64PtrTy = llvm::Type::getInt64PtrTy(Ctx);
251   llvm::Type *DataTypes[] = {
252     Int32Ty, Int32Ty, Int64Ty, Int8PtrTy, Int64PtrTy
253   };
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),
258     llvm::ConstantInt::get(Int64Ty, FunctionHash),
259     llvm::ConstantExpr::getBitCast(Name, Int8PtrTy),
260     llvm::ConstantExpr::getBitCast(RegionCounters, Int64PtrTy)
261   };
262   auto *Data =
263     new llvm::GlobalVariable(CGM.getModule(), DataTy, true, VarLinkage,
264                              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 
276 void CodeGenPGO::emitInstrumentationData() {
277   if (!CGM.getCodeGenOpts().ProfileInstrGenerate)
278     return;
279 
280   // Build the data.
281   auto *Data = buildDataVar();
282 
283   // Register the data.
284   auto *RegisterBB = getOrInsertRegisterBB(CGM);
285   if (!RegisterBB)
286     return;
287   CGBuilderTy Builder(RegisterBB->getTerminator());
288   auto *VoidPtrTy = llvm::Type::getInt8PtrTy(CGM.getLLVMContext());
289   Builder.CreateCall(getOrInsertRuntimeRegister(CGM),
290                      Builder.CreateBitCast(Data, VoidPtrTy));
291 }
292 
293 llvm::Function *CodeGenPGO::emitInitialization(CodeGenModule &CGM) {
294   if (!CGM.getCodeGenOpts().ProfileInstrGenerate)
295     return nullptr;
296 
297   assert(CGM.getModule().getFunction("__llvm_profile_init") == nullptr &&
298          "profile initialization already emitted");
299 
300   // Get the function to call at initialization.
301   llvm::Constant *RegisterF = getRegisterFunc(CGM);
302   if (!RegisterF)
303     return nullptr;
304 
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,
309                                    "__llvm_profile_init", &CGM.getModule());
310   F->setUnnamedAddr(true);
311   F->addFnAttr(llvm::Attribute::NoInline);
312   if (CGM.getCodeGenOpts().DisableRedZone)
313     F->addFnAttr(llvm::Attribute::NoRedZone);
314 
315   // Add the basic block and the necessary calls.
316   CGBuilderTy Builder(llvm::BasicBlock::Create(CGM.getLLVMContext(), "", F));
317   Builder.CreateCall(RegisterF);
318   Builder.CreateRetVoid();
319 
320   return F;
321 }
322 
323 namespace {
324   /// A RecursiveASTVisitor that fills a map of statements to PGO counters.
325   struct MapRegionCounters : public RecursiveASTVisitor<MapRegionCounters> {
326     /// The next counter value to assign.
327     unsigned NextCounter;
328     /// The map of statements to counters.
329     llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
330 
331     MapRegionCounters(llvm::DenseMap<const Stmt *, unsigned> &CounterMap)
332         : NextCounter(0), CounterMap(CounterMap) {}
333 
334     // 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; }
338     bool TraverseCapturedStmt(CapturedStmt *CS) { return true; }
339 
340     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:
351       case Decl::Captured:
352         CounterMap[D->getBody()] = NextCounter++;
353         break;
354       }
355       return true;
356     }
357 
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;
386     }
387   };
388 
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.
400     llvm::DenseMap<const Stmt *, uint64_t> &CountMap;
401 
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 
410     ComputeRegionCounts(llvm::DenseMap<const Stmt *, uint64_t> &CountMap,
411                         CodeGenPGO &PGO)
412         : PGO(PGO), RecordNextStmtCount(false), CountMap(CountMap) {}
413 
414     void RecordStmtCount(const Stmt *S) {
415       if (RecordNextStmtCount) {
416         CountMap[S] = PGO.getCurrentRegionCount();
417         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 
429     void VisitFunctionDecl(const FunctionDecl *D) {
430       // Counter tracks entry to the function body.
431       RegionCounter Cnt(PGO, D->getBody());
432       Cnt.beginRegion();
433       CountMap[D->getBody()] = PGO.getCurrentRegionCount();
434       Visit(D->getBody());
435     }
436 
437     // 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 
442     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 
450     void VisitObjCMethodDecl(const ObjCMethodDecl *D) {
451       // Counter tracks entry to the method body.
452       RegionCounter Cnt(PGO, D->getBody());
453       Cnt.beginRegion();
454       CountMap[D->getBody()] = PGO.getCurrentRegionCount();
455       Visit(D->getBody());
456     }
457 
458     void VisitBlockDecl(const BlockDecl *D) {
459       // Counter tracks entry to the block body.
460       RegionCounter Cnt(PGO, D->getBody());
461       Cnt.beginRegion();
462       CountMap[D->getBody()] = PGO.getCurrentRegionCount();
463       Visit(D->getBody());
464     }
465 
466     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;
482       // Counter tracks the block following the label.
483       RegionCounter Cnt(PGO, S);
484       Cnt.beginRegion();
485       CountMap[S] = PGO.getCurrentRegionCount();
486       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);
507       // Counter tracks the body of the loop.
508       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();
513       CountMap[S->getBody()] = PGO.getCurrentRegionCount();
514       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);
524       CountMap[S->getCond()] = PGO.getCurrentRegionCount();
525       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);
533       // Counter tracks the body of the loop.
534       RegionCounter Cnt(PGO, S);
535       BreakContinueStack.push_back(BreakContinue());
536       Cnt.beginRegion(/*AddIncomingFallThrough=*/true);
537       CountMap[S->getBody()] = PGO.getCurrentRegionCount();
538       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);
549       CountMap[S->getCond()] = PGO.getCurrentRegionCount();
550       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());
560       // Counter tracks the body of the loop.
561       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();
566       CountMap[S->getBody()] = PGO.getCurrentRegionCount();
567       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);
575         CountMap[S->getInc()] = PGO.getCurrentRegionCount();
576         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);
587         CountMap[S->getCond()] = PGO.getCurrentRegionCount();
588         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());
599       // Counter tracks the body of the loop.
600       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();
605       CountMap[S->getLoopVarStmt()] = PGO.getCurrentRegionCount();
606       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);
614       CountMap[S->getInc()] = PGO.getCurrentRegionCount();
615       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);
624       CountMap[S->getCond()] = PGO.getCurrentRegionCount();
625       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());
634       // Counter tracks the body of the loop.
635       RegionCounter Cnt(PGO, S);
636       BreakContinueStack.push_back(BreakContinue());
637       Cnt.beginRegion();
638       CountMap[S->getBody()] = PGO.getCurrentRegionCount();
639       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;
656       // Counter tracks the exit block of the switch.
657       RegionCounter ExitCnt(PGO, S);
658       ExitCnt.beginRegion();
659       RecordNextStmtCount = true;
660     }
661 
662     void VisitCaseStmt(const CaseStmt *S) {
663       RecordNextStmtCount = false;
664       // 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.
667       RegionCounter Cnt(PGO, S);
668       Cnt.beginRegion(/*AddIncomingFallThrough=*/true);
669       CountMap[S] = Cnt.getCount();
670       RecordNextStmtCount = true;
671       Visit(S->getSubStmt());
672     }
673 
674     void VisitDefaultStmt(const DefaultStmt *S) {
675       RecordNextStmtCount = false;
676       // Counter for this default case. This does not include fallthrough from
677       // the previous case.
678       RegionCounter Cnt(PGO, S);
679       Cnt.beginRegion(/*AddIncomingFallThrough=*/true);
680       CountMap[S] = Cnt.getCount();
681       RecordNextStmtCount = true;
682       Visit(S->getSubStmt());
683     }
684 
685     void VisitIfStmt(const IfStmt *S) {
686       RecordStmtCount(S);
687       // 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.
689       RegionCounter Cnt(PGO, S);
690       Visit(S->getCond());
691 
692       Cnt.beginRegion();
693       CountMap[S->getThen()] = PGO.getCurrentRegionCount();
694       Visit(S->getThen());
695       Cnt.adjustForControlFlow();
696 
697       if (S->getElse()) {
698         Cnt.beginElseRegion();
699         CountMap[S->getElse()] = PGO.getCurrentRegionCount();
700         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));
712       // Counter tracks the continuation block of the try statement.
713       RegionCounter Cnt(PGO, S);
714       Cnt.beginRegion();
715       RecordNextStmtCount = true;
716     }
717 
718     void VisitCXXCatchStmt(const CXXCatchStmt *S) {
719       RecordNextStmtCount = false;
720       // Counter tracks the catch statement's handler block.
721       RegionCounter Cnt(PGO, S);
722       Cnt.beginRegion();
723       CountMap[S] = PGO.getCurrentRegionCount();
724       Visit(S->getHandlerBlock());
725     }
726 
727     void VisitAbstractConditionalOperator(
728         const AbstractConditionalOperator *E) {
729       RecordStmtCount(E);
730       // Counter tracks the "true" part of a conditional operator. The
731       // count in the "false" part will be calculated from this counter.
732       RegionCounter Cnt(PGO, E);
733       Visit(E->getCond());
734 
735       Cnt.beginRegion();
736       CountMap[E->getTrueExpr()] = PGO.getCurrentRegionCount();
737       Visit(E->getTrueExpr());
738       Cnt.adjustForControlFlow();
739 
740       Cnt.beginElseRegion();
741       CountMap[E->getFalseExpr()] = PGO.getCurrentRegionCount();
742       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);
751       // Counter tracks the right hand side of a logical and operator.
752       RegionCounter Cnt(PGO, E);
753       Visit(E->getLHS());
754       Cnt.beginRegion();
755       CountMap[E->getRHS()] = PGO.getCurrentRegionCount();
756       Visit(E->getRHS());
757       Cnt.adjustForControlFlow();
758       Cnt.applyAdjustmentsToRegion(0);
759       RecordNextStmtCount = true;
760     }
761 
762     void VisitBinLOr(const BinaryOperator *E) {
763       RecordStmtCount(E);
764       // Counter tracks the right hand side of a logical or operator.
765       RegionCounter Cnt(PGO, E);
766       Visit(E->getLHS());
767       Cnt.beginRegion();
768       CountMap[E->getRHS()] = PGO.getCurrentRegionCount();
769       Visit(E->getRHS());
770       Cnt.adjustForControlFlow();
771       Cnt.applyAdjustmentsToRegion(0);
772       RecordNextStmtCount = true;
773     }
774   };
775 }
776 
777 static void emitRuntimeHook(CodeGenModule &CGM) {
778   const char *const RuntimeVarName = "__llvm_profile_runtime";
779   const char *const RuntimeUserName = "__llvm_profile_runtime_user";
780   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 
806 void CodeGenPGO::assignRegionCounters(const Decl *D, llvm::Function *Fn) {
807   bool InstrumentRegions = CGM.getCodeGenOpts().ProfileInstrGenerate;
808   PGOProfileData *PGOData = CGM.getPGOData();
809   if (!InstrumentRegions && !PGOData)
810     return;
811   if (!D)
812     return;
813   setFuncName(Fn);
814 
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.
818   VarLinkage = Fn->getLinkage();
819   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 
830   mapRegionCounters(D);
831   if (InstrumentRegions) {
832     emitRuntimeHook(CGM);
833     emitCounterVariables();
834   }
835   if (PGOData) {
836     loadRegionCounts(PGOData);
837     computeRegionCounts(D);
838     applyFunctionAttributes(PGOData, Fn);
839   }
840 }
841 
842 void CodeGenPGO::mapRegionCounters(const Decl *D) {
843   RegionCounterMap.reset(new llvm::DenseMap<const Stmt *, unsigned>);
844   MapRegionCounters Walker(*RegionCounterMap);
845   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
846     Walker.TraverseDecl(const_cast<FunctionDecl *>(FD));
847   else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
848     Walker.TraverseDecl(const_cast<ObjCMethodDecl *>(MD));
849   else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D))
850     Walker.TraverseDecl(const_cast<BlockDecl *>(BD));
851   else if (const CapturedDecl *CD = dyn_cast_or_null<CapturedDecl>(D))
852     Walker.TraverseDecl(const_cast<CapturedDecl *>(CD));
853   NumRegionCounters = Walker.NextCounter;
854   // FIXME: The number of counters isn't sufficient for the hash
855   FunctionHash = NumRegionCounters;
856 }
857 
858 void CodeGenPGO::computeRegionCounts(const Decl *D) {
859   StmtCountMap.reset(new llvm::DenseMap<const Stmt *, uint64_t>);
860   ComputeRegionCounts Walker(*StmtCountMap, *this);
861   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
862     Walker.VisitFunctionDecl(FD);
863   else if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
864     Walker.VisitObjCMethodDecl(MD);
865   else if (const BlockDecl *BD = dyn_cast_or_null<BlockDecl>(D))
866     Walker.VisitBlockDecl(BD);
867   else if (const CapturedDecl *CD = dyn_cast_or_null<CapturedDecl>(D))
868     Walker.VisitCapturedDecl(const_cast<CapturedDecl *>(CD));
869 }
870 
871 void CodeGenPGO::applyFunctionAttributes(PGOProfileData *PGOData,
872                                          llvm::Function *Fn) {
873   if (!haveRegionCounts())
874     return;
875 
876   uint64_t MaxFunctionCount = PGOData->getMaximumFunctionCount();
877   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 
888 void CodeGenPGO::emitCounterVariables() {
889   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
890   llvm::ArrayType *CounterTy = llvm::ArrayType::get(llvm::Type::getInt64Ty(Ctx),
891                                                     NumRegionCounters);
892   RegionCounters =
893     new llvm::GlobalVariable(CGM.getModule(), CounterTy, false, VarLinkage,
894                              llvm::Constant::getNullValue(CounterTy),
895                              getFuncVarName("counters"));
896   RegionCounters->setAlignment(8);
897   RegionCounters->setSection(getCountersSection(CGM));
898 }
899 
900 void CodeGenPGO::emitCounterIncrement(CGBuilderTy &Builder, unsigned Counter) {
901   if (!RegionCounters)
902     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 
910 void CodeGenPGO::loadRegionCounts(PGOProfileData *PGOData) {
911   CGM.getPGOStats().Visited++;
912   RegionCounts.reset(new std::vector<uint64_t>);
913   uint64_t Hash;
914   if (PGOData->getFunctionCounts(getFuncName(), Hash, *RegionCounts)) {
915     CGM.getPGOStats().Missing++;
916     RegionCounts.reset();
917   } else if (Hash != FunctionHash ||
918              RegionCounts->size() != NumRegionCounters) {
919     CGM.getPGOStats().Mismatched++;
920     RegionCounts.reset();
921   }
922 }
923 
924 void CodeGenPGO::destroyRegionCounters() {
925   RegionCounterMap.reset();
926   StmtCountMap.reset();
927   RegionCounts.reset();
928 }
929 
930 /// \brief Calculate what to divide by to scale weights.
931 ///
932 /// Given the maximum weight, calculate a divisor that will scale all the
933 /// weights to strictly less than UINT32_MAX.
934 static uint64_t calculateWeightScale(uint64_t MaxWeight) {
935   return MaxWeight < UINT32_MAX ? 1 : MaxWeight / UINT32_MAX + 1;
936 }
937 
938 /// \brief Scale an individual branch weight (and add 1).
939 ///
940 /// Scale a 64-bit weight down to 32-bits using \c Scale.
941 ///
942 /// According to Laplace's Rule of Succession, it is better to compute the
943 /// weight based on the count plus 1, so universally add 1 to the value.
944 ///
945 /// \pre \c Scale was calculated by \a calculateWeightScale() with a weight no
946 /// greater than \c Weight.
947 static uint32_t scaleBranchWeight(uint64_t Weight, uint64_t Scale) {
948   assert(Scale && "scale by 0?");
949   uint64_t Scaled = Weight / Scale + 1;
950   assert(Scaled <= UINT32_MAX && "overflow 32-bits");
951   return Scaled;
952 }
953 
954 llvm::MDNode *CodeGenPGO::createBranchWeights(uint64_t TrueCount,
955                                               uint64_t FalseCount) {
956   // Check for empty weights.
957   if (!TrueCount && !FalseCount)
958     return nullptr;
959 
960   // Calculate how to scale down to 32-bits.
961   uint64_t Scale = calculateWeightScale(std::max(TrueCount, FalseCount));
962 
963   llvm::MDBuilder MDHelper(CGM.getLLVMContext());
964   return MDHelper.createBranchWeights(scaleBranchWeight(TrueCount, Scale),
965                                       scaleBranchWeight(FalseCount, Scale));
966 }
967 
968 llvm::MDNode *CodeGenPGO::createBranchWeights(ArrayRef<uint64_t> Weights) {
969   // We need at least two elements to create meaningful weights.
970   if (Weights.size() < 2)
971     return nullptr;
972 
973   // Check for empty weights.
974   uint64_t MaxWeight = *std::max_element(Weights.begin(), Weights.end());
975   if (MaxWeight == 0)
976     return nullptr;
977 
978   // Calculate how to scale down to 32-bits.
979   uint64_t Scale = calculateWeightScale(MaxWeight);
980 
981   SmallVector<uint32_t, 16> ScaledWeights;
982   ScaledWeights.reserve(Weights.size());
983   for (uint64_t W : Weights)
984     ScaledWeights.push_back(scaleBranchWeight(W, Scale));
985 
986   llvm::MDBuilder MDHelper(CGM.getLLVMContext());
987   return MDHelper.createBranchWeights(ScaledWeights);
988 }
989 
990 llvm::MDNode *CodeGenPGO::createLoopWeights(const Stmt *Cond,
991                                             RegionCounter &Cnt) {
992   if (!haveRegionCounts())
993     return nullptr;
994   uint64_t LoopCount = Cnt.getCount();
995   uint64_t CondCount = 0;
996   bool Found = getStmtCount(Cond, CondCount);
997   assert(Found && "missing expected loop condition count");
998   (void)Found;
999   if (CondCount == 0)
1000     return nullptr;
1001   return createBranchWeights(LoopCount,
1002                              std::max(CondCount, LoopCount) - LoopCount);
1003 }
1004