LLVM 24.0.0git
PGOInstrumentation.cpp
Go to the documentation of this file.
1//===- PGOInstrumentation.cpp - MST-based PGO Instrumentation -------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements PGO instrumentation using a minimum spanning tree based
10// on the following paper:
11// [1] Donald E. Knuth, Francis R. Stevenson. Optimal measurement of points
12// for program frequency counts. BIT Numerical Mathematics 1973, Volume 13,
13// Issue 3, pp 313-322
14// The idea of the algorithm based on the fact that for each node (except for
15// the entry and exit), the sum of incoming edge counts equals the sum of
16// outgoing edge counts. The count of edge on spanning tree can be derived from
17// those edges not on the spanning tree. Knuth proves this method instruments
18// the minimum number of edges.
19//
20// The minimal spanning tree here is actually a maximum weight tree -- on-tree
21// edges have higher frequencies (more likely to execute). The idea is to
22// instrument those less frequently executed edges to reduce the runtime
23// overhead of instrumented binaries.
24//
25// This file contains two passes:
26// (1) Pass PGOInstrumentationGen which instruments the IR to generate edge
27// count profile, and generates the instrumentation for indirect call
28// profiling.
29// (2) Pass PGOInstrumentationUse which reads the edge count profile and
30// annotates the branch weights. It also reads the indirect call value
31// profiling records and annotate the indirect call instructions.
32//
33// To get the precise counter information, These two passes need to invoke at
34// the same compilation point (so they see the same IR). For pass
35// PGOInstrumentationGen, the real work is done in instrumentOneFunc(). For
36// pass PGOInstrumentationUse, the real work in done in class PGOUseFunc and
37// the profile is opened in module level and passed to each PGOUseFunc instance.
38// The shared code for PGOInstrumentationGen and PGOInstrumentationUse is put
39// in class FuncPGOInstrumentation.
40//
41// Class PGOEdge represents a CFG edge and some auxiliary information. Class
42// BBInfo contains auxiliary information for each BB. These two classes are used
43// in pass PGOInstrumentationGen. Class PGOUseEdge and UseBBInfo are the derived
44// class of PGOEdge and BBInfo, respectively. They contains extra data structure
45// used in populating profile counters.
46// The MST implementation is in Class CFGMST (CFGMST.h).
47//
48//===----------------------------------------------------------------------===//
49
53#include "llvm/ADT/APInt.h"
54#include "llvm/ADT/ArrayRef.h"
55#include "llvm/ADT/STLExtras.h"
57#include "llvm/ADT/Statistic.h"
58#include "llvm/ADT/StringRef.h"
59#include "llvm/ADT/StringSet.h"
60#include "llvm/ADT/Twine.h"
61#include "llvm/ADT/iterator.h"
65#include "llvm/Analysis/CFG.h"
72#include "llvm/IR/Attributes.h"
73#include "llvm/IR/BasicBlock.h"
74#include "llvm/IR/CFG.h"
75#include "llvm/IR/Comdat.h"
76#include "llvm/IR/Constant.h"
77#include "llvm/IR/Constants.h"
78#include "llvm/IR/CycleInfo.h"
81#include "llvm/IR/Function.h"
82#include "llvm/IR/GlobalAlias.h"
83#include "llvm/IR/GlobalValue.h"
85#include "llvm/IR/IRBuilder.h"
86#include "llvm/IR/InstVisitor.h"
87#include "llvm/IR/InstrTypes.h"
88#include "llvm/IR/Instruction.h"
91#include "llvm/IR/Intrinsics.h"
92#include "llvm/IR/LLVMContext.h"
93#include "llvm/IR/MDBuilder.h"
94#include "llvm/IR/Module.h"
95#include "llvm/IR/PassManager.h"
98#include "llvm/IR/Type.h"
99#include "llvm/IR/Value.h"
103#include "llvm/Support/CRC.h"
104#include "llvm/Support/Casting.h"
108#include "llvm/Support/Debug.h"
109#include "llvm/Support/Error.h"
121#include <algorithm>
122#include <cassert>
123#include <cstdint>
124#include <memory>
125#include <numeric>
126#include <optional>
127#include <stack>
128#include <string>
129#include <unordered_map>
130#include <utility>
131#include <vector>
132
133using namespace llvm;
135
136#define DEBUG_TYPE "pgo-instrumentation"
137
138STATISTIC(NumOfPGOInstrument, "Number of edges instrumented.");
139STATISTIC(NumOfPGOSelectInsts, "Number of select instruction instrumented.");
140STATISTIC(NumOfPGOMemIntrinsics, "Number of mem intrinsics instrumented.");
141STATISTIC(NumOfPGOEdge, "Number of edges.");
142STATISTIC(NumOfPGOBB, "Number of basic-blocks.");
143STATISTIC(NumOfPGOSplit, "Number of critical edge splits.");
144STATISTIC(NumOfPGOFunc, "Number of functions having valid profile counts.");
145STATISTIC(NumOfPGOMismatch, "Number of functions having mismatch profile.");
146STATISTIC(NumOfPGOMissing, "Number of functions without profile.");
147STATISTIC(NumOfPGOICall, "Number of indirect call value instrumentations.");
148STATISTIC(NumOfCSPGOInstrument, "Number of edges instrumented in CSPGO.");
149STATISTIC(NumOfCSPGOSelectInsts,
150 "Number of select instruction instrumented in CSPGO.");
151STATISTIC(NumOfCSPGOMemIntrinsics,
152 "Number of mem intrinsics instrumented in CSPGO.");
153STATISTIC(NumOfCSPGOEdge, "Number of edges in CSPGO.");
154STATISTIC(NumOfCSPGOBB, "Number of basic-blocks in CSPGO.");
155STATISTIC(NumOfCSPGOSplit, "Number of critical edge splits in CSPGO.");
156STATISTIC(NumOfCSPGOFunc,
157 "Number of functions having valid profile counts in CSPGO.");
158STATISTIC(NumOfCSPGOMismatch,
159 "Number of functions having mismatch profile in CSPGO.");
160STATISTIC(NumOfCSPGOMissing, "Number of functions without profile in CSPGO.");
161STATISTIC(NumCoveredBlocks, "Number of basic blocks that were executed");
162
163namespace llvm {
164
165// Command line option to enable/disable the warning about a hash mismatch in
166// the profile data.
168 NoPGOWarnMismatch("no-pgo-warn-mismatch", cl::init(false), cl::Hidden,
169 cl::desc("Use this option to turn off/on "
170 "warnings about profile cfg mismatch."));
171
172// Command line option to enable vtable value profiling. Defined in
173// ProfileData/InstrProf.cpp: -enable-vtable-value-profiling=
176} // namespace llvm
177
179 const cl::LibraryOptionsContext &LibraryOptions) {
180 return LibraryOptions.get<InstrumentationOptions>()
181 .pgo_instrument_cold_function_only;
182}
183
184namespace {
185class FunctionInstrumenter final {
186 const InstrumentationOptions &Opts;
187 Module &M;
188 Function &F;
190 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers;
191 BranchProbabilityInfo *const BPI;
192 BlockFrequencyInfo *const BFI;
193 LoopInfo *const LI;
194
195 const PGOInstrumentationType InstrumentationType;
196
197 // FIXME(mtrofin): re-enable this for ctx profiling, for non-indirect calls.
198 // Ctx profiling implicitly captures indirect call cases, but not other
199 // values. Supporting other values is relatively straight-forward - just
200 // another counter range within the context.
201 bool isValueProfilingDisabled() const {
202 // Value profiling is disabled for GPU targets because the device-side
203 // profiling runtime does not yet implement
204 // __llvm_profile_instrument_target. The existing compiler-rt implementation
205 // uses a linked-list with locks and eviction policy that is not efficient
206 // for massively parallel GPU execution. A GPU-optimized implementation is
207 // left as future work.
208 return Opts.disable_vp ||
209 InstrumentationType == PGOInstrumentationType::CTXPROF ||
211 }
212
213 bool shouldInstrumentEntryBB() const {
214 return valueOr(Opts.pgo_instrument_entry, false) ||
215 InstrumentationType == PGOInstrumentationType::CTXPROF;
216 }
217
218 bool shouldInstrumentLoopEntries() const {
219 return valueOr(Opts.pgo_instrument_loop_entries, false);
220 }
221
222public:
223 FunctionInstrumenter(
224 const InstrumentationOptions &Opts, Module &M, Function &F,
225 TargetLibraryInfo &TLI,
226 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
227 BranchProbabilityInfo *BPI = nullptr, BlockFrequencyInfo *BFI = nullptr,
228 LoopInfo *LI = nullptr,
229 PGOInstrumentationType InstrumentationType = PGOInstrumentationType::FDO)
230 : Opts(Opts), M(M), F(F), TLI(TLI), ComdatMembers(ComdatMembers),
231 BPI(BPI), BFI(BFI), LI(LI), InstrumentationType(InstrumentationType) {}
232
233 void instrument();
234};
235} // namespace
236
237// Return a string describing the branch condition that can be
238// used in static branch probability heuristics:
239static std::string getBranchCondString(Instruction *TI) {
241 if (!BI)
242 return std::string();
243
244 Value *Cond = BI->getCondition();
246 if (!CI)
247 return std::string();
248
249 std::string result;
250 raw_string_ostream OS(result);
251 OS << CI->getPredicate() << "_";
252 CI->getOperand(0)->getType()->print(OS, true);
253
254 Value *RHS = CI->getOperand(1);
256 if (CV) {
257 if (CV->isZero())
258 OS << "_Zero";
259 else if (CV->isOne())
260 OS << "_One";
261 else if (CV->isMinusOne())
262 OS << "_MinusOne";
263 else
264 OS << "_Const";
265 }
266 return result;
267}
268
269static const char *ValueProfKindDescr[] = {
270#define VALUE_PROF_KIND(Enumerator, Value, Descr) Descr,
272};
273
274// Create a COMDAT variable INSTR_PROF_RAW_VERSION_VAR to make the runtime
275// aware this is an ir_level profile so it can set the version flag.
276static GlobalVariable *
277createIRLevelProfileFlagVar(const InstrumentationOptions &Opts, Module &M,
278 PGOInstrumentationType InstrumentationType) {
280 Type *IntTy64 = Type::getInt64Ty(M.getContext());
282 if (InstrumentationType == PGOInstrumentationType::CSFDO)
283 ProfileVersion |= VARIANT_MASK_CSIR_PROF;
284 if (valueOr(Opts.pgo_instrument_entry, false) ||
285 InstrumentationType == PGOInstrumentationType::CTXPROF)
286 ProfileVersion |= VARIANT_MASK_INSTR_ENTRY;
287 if (valueOr(Opts.pgo_instrument_loop_entries, false))
288 ProfileVersion |= VARIANT_MASK_INSTR_LOOP_ENTRIES;
289 if (Opts.profile_correlate == ProfCorrelatorKind::DebugInfo)
290 ProfileVersion |= VARIANT_MASK_DBG_CORRELATE;
291 if (Opts.pgo_function_entry_coverage)
292 ProfileVersion |=
294 if (Opts.pgo_block_coverage)
295 ProfileVersion |= VARIANT_MASK_BYTE_COVERAGE;
296 if (Opts.pgo_temporal_instrumentation)
297 ProfileVersion |= VARIANT_MASK_TEMPORAL_PROF;
298 auto IRLevelVersionVariable = new GlobalVariable(
299 M, IntTy64, true, GlobalValue::WeakAnyLinkage,
300 Constant::getIntegerValue(IntTy64, APInt(64, ProfileVersion)), VarName);
301 Triple TT(M.getTargetTriple());
302 IRLevelVersionVariable->setVisibility(TT.isGPU()
305 if (TT.supportsCOMDAT()) {
306 IRLevelVersionVariable->setLinkage(GlobalValue::ExternalLinkage);
307 IRLevelVersionVariable->setComdat(M.getOrInsertComdat(VarName));
308 }
309 return IRLevelVersionVariable;
310}
311
312namespace {
313
314/// The select instruction visitor plays three roles specified
315/// by the mode. In \c VM_counting mode, it simply counts the number of
316/// select instructions. In \c VM_instrument mode, it inserts code to count
317/// the number times TrueValue of select is taken. In \c VM_annotate mode,
318/// it reads the profile data and annotate the select instruction with metadata.
319enum VisitMode { VM_counting, VM_instrument, VM_annotate };
320class PGOUseFunc;
321
322/// Instruction Visitor class to visit select instructions.
323struct SelectInstVisitor : public InstVisitor<SelectInstVisitor> {
324 const InstrumentationOptions &Opts;
325 Function &F;
326 unsigned NSIs = 0; // Number of select instructions instrumented.
327 VisitMode Mode = VM_counting; // Visiting mode.
328 unsigned *CurCtrIdx = nullptr; // Pointer to current counter index.
329 unsigned TotalNumCtrs = 0; // Total number of counters
330 GlobalValue *FuncNameVar = nullptr;
331 uint64_t FuncHash = 0;
332 PGOUseFunc *UseFunc = nullptr;
333 bool HasSingleByteCoverage;
334
335 SelectInstVisitor(const InstrumentationOptions &Opts, Function &Func,
336 bool HasSingleByteCoverage)
337 : Opts(Opts), F(Func), HasSingleByteCoverage(HasSingleByteCoverage) {}
338
339 void countSelects() {
340 NSIs = 0;
341 Mode = VM_counting;
342 visit(F);
343 }
344
345 // Visit the IR stream and instrument all select instructions. \p
346 // Ind is a pointer to the counter index variable; \p TotalNC
347 // is the total number of counters; \p FNV is the pointer to the
348 // PGO function name var; \p FHash is the function hash.
349 void instrumentSelects(unsigned *Ind, unsigned TotalNC, GlobalValue *FNV,
350 uint64_t FHash) {
351 Mode = VM_instrument;
352 CurCtrIdx = Ind;
353 TotalNumCtrs = TotalNC;
354 FuncHash = FHash;
355 FuncNameVar = FNV;
356 visit(F);
357 }
358
359 // Visit the IR stream and annotate all select instructions.
360 void annotateSelects(PGOUseFunc *UF, unsigned *Ind) {
361 Mode = VM_annotate;
362 UseFunc = UF;
363 CurCtrIdx = Ind;
364 visit(F);
365 }
366
367 void instrumentOneSelectInst(SelectInst &SI);
368 void annotateOneSelectInst(SelectInst &SI);
369
370 // Visit \p SI instruction and perform tasks according to visit mode.
371 void visitSelectInst(SelectInst &SI);
372
373 // Return the number of select instructions. This needs be called after
374 // countSelects().
375 unsigned getNumOfSelectInsts() const { return NSIs; }
376};
377
378/// This class implements the CFG edges for the Minimum Spanning Tree (MST)
379/// based instrumentation.
380/// Note that the CFG can be a multi-graph. So there might be multiple edges
381/// with the same SrcBB and DestBB.
382struct PGOEdge {
383 BasicBlock *SrcBB;
384 BasicBlock *DestBB;
385 uint64_t Weight;
386 bool InMST = false;
387 bool Removed = false;
388 bool IsCritical = false;
389
390 PGOEdge(BasicBlock *Src, BasicBlock *Dest, uint64_t W = 1)
391 : SrcBB(Src), DestBB(Dest), Weight(W) {}
392
393 /// Return the information string of an edge.
394 std::string infoString() const {
395 return (Twine(Removed ? "-" : " ") + (InMST ? " " : "*") +
396 (IsCritical ? "c" : " ") + " W=" + Twine(Weight))
397 .str();
398 }
399};
400
401/// This class stores the auxiliary information for each BB in the MST.
402struct PGOBBInfo {
403 PGOBBInfo *Group;
404 uint32_t Index;
405 uint32_t Rank = 0;
406
407 PGOBBInfo(unsigned IX) : Group(this), Index(IX) {}
408
409 /// Return the information string of this object.
410 std::string infoString() const {
411 return (Twine("Index=") + Twine(Index)).str();
412 }
413};
414
415// This class implements the CFG edges. Note the CFG can be a multi-graph.
416template <class Edge, class BBInfo> class FuncPGOInstrumentation {
417private:
418 const InstrumentationOptions &Opts;
419 Function &F;
420
421 // Is this is context-sensitive instrumentation.
422 bool IsCS;
423
424 // A map that stores the Comdat group in function F.
425 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers;
426
427 ValueProfileCollector VPC;
428
429 void computeCFGHash();
430 void renameComdatFunction();
431
432public:
433 std::vector<std::vector<VPCandidateInfo>> ValueSites;
434 SelectInstVisitor SIVisitor;
435 std::string FuncName;
436 std::string DeprecatedFuncName;
437 GlobalVariable *FuncNameVar;
438
439 // CFG hash value for this function.
440 uint64_t FunctionHash = 0;
441
442 // The Minimum Spanning Tree of function CFG.
443 CFGMST<Edge, BBInfo> MST;
444
445 const std::optional<BlockCoverageInference> BCI;
446
447 static std::optional<BlockCoverageInference>
448 constructBCI(Function &Func, bool HasSingleByteCoverage,
449 bool InstrumentFuncEntry) {
450 if (HasSingleByteCoverage)
451 return BlockCoverageInference(Func, InstrumentFuncEntry);
452 return {};
453 }
454
455 // Collect all the BBs that will be instrumented, and store them in
456 // InstrumentBBs.
457 void getInstrumentBBs(std::vector<BasicBlock *> &InstrumentBBs);
458
459 // Give an edge, find the BB that will be instrumented.
460 // Return nullptr if there is no BB to be instrumented.
462
463 // Return the auxiliary BB information.
464 BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); }
465
466 // Return the auxiliary BB information if available.
467 BBInfo *findBBInfo(const BasicBlock *BB) const { return MST.findBBInfo(BB); }
468
469 // Dump edges and BB information.
470 void dumpInfo(StringRef Str = "") const {
471 MST.dumpEdges(dbgs(), Twine("Dump Function ") + FuncName +
472 " Hash: " + Twine(FunctionHash) + "\t" + Str);
473 }
474
475 FuncPGOInstrumentation(
476 const InstrumentationOptions &Opts, Function &Func,
477 TargetLibraryInfo &TLI,
478 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
479 bool CreateGlobalVar = false, BranchProbabilityInfo *BPI = nullptr,
480 BlockFrequencyInfo *BFI = nullptr, LoopInfo *LI = nullptr,
481 bool IsCS = false, bool InstrumentFuncEntry = true,
482 bool InstrumentLoopEntries = false, bool HasSingleByteCoverage = false)
483 : Opts(Opts), F(Func), IsCS(IsCS), ComdatMembers(ComdatMembers),
484 VPC(Func, TLI), ValueSites(IPVK_Last + 1),
485 SIVisitor(Opts, Func, HasSingleByteCoverage),
486 MST(F, InstrumentFuncEntry, InstrumentLoopEntries, BPI, BFI, LI),
487 BCI(constructBCI(Func, HasSingleByteCoverage, InstrumentFuncEntry)) {
488 if (BCI && Opts.pgo_view_block_coverage_graph)
489 BCI->viewBlockCoverageGraph();
490 // This should be done before CFG hash computation.
491 SIVisitor.countSelects();
492 ValueSites[IPVK_MemOPSize] = VPC.get(IPVK_MemOPSize);
493 if (!IsCS) {
494 NumOfPGOSelectInsts += SIVisitor.getNumOfSelectInsts();
495 NumOfPGOMemIntrinsics += ValueSites[IPVK_MemOPSize].size();
496 NumOfPGOBB += MST.bbInfoSize();
497 ValueSites[IPVK_IndirectCallTarget] = VPC.get(IPVK_IndirectCallTarget);
499 ValueSites[IPVK_VTableTarget] = VPC.get(IPVK_VTableTarget);
500 } else {
501 NumOfCSPGOSelectInsts += SIVisitor.getNumOfSelectInsts();
502 NumOfCSPGOMemIntrinsics += ValueSites[IPVK_MemOPSize].size();
503 NumOfCSPGOBB += MST.bbInfoSize();
504 }
505
506 FuncName = getIRPGOObjectName(F);
507 DeprecatedFuncName = getPGOFuncName(F);
508 computeCFGHash();
509 if (!ComdatMembers.empty())
510 renameComdatFunction();
511 LLVM_DEBUG(dumpInfo("after CFGMST"));
512
513 for (const auto &E : MST.allEdges()) {
514 if (E->Removed)
515 continue;
516 IsCS ? NumOfCSPGOEdge++ : NumOfPGOEdge++;
517 if (!E->InMST)
518 IsCS ? NumOfCSPGOInstrument++ : NumOfPGOInstrument++;
519 }
520
521 if (CreateGlobalVar)
522 FuncNameVar = createPGOFuncNameVar(F, FuncName);
523 }
524};
525
526} // end anonymous namespace
527
528// Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index
529// value of each BB in the CFG. The higher 32 bits are the CRC32 of the numbers
530// of selects, indirect calls, mem ops and edges.
531template <class Edge, class BBInfo>
532void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() {
533 std::vector<uint8_t> Indexes;
534 JamCRC JC;
535 for (auto &BB : F) {
536 for (BasicBlock *Succ : successors(&BB)) {
537 auto BI = findBBInfo(Succ);
538 if (BI == nullptr)
539 continue;
540 uint32_t Index = BI->Index;
541 for (int J = 0; J < 4; J++)
542 Indexes.push_back((uint8_t)(Index >> (J * 8)));
543 }
544 }
545 JC.update(Indexes);
546
547 JamCRC JCH;
548 // The higher 32 bits.
549 auto updateJCH = [&JCH](uint64_t Num) {
550 uint8_t Data[8];
552 JCH.update(Data);
553 };
554 updateJCH((uint64_t)SIVisitor.getNumOfSelectInsts());
555 updateJCH((uint64_t)ValueSites[IPVK_IndirectCallTarget].size());
556 updateJCH((uint64_t)ValueSites[IPVK_MemOPSize].size());
557 if (BCI) {
558 updateJCH(BCI->getInstrumentedBlocksHash());
559 } else {
560 updateJCH((uint64_t)MST.numEdges());
561 }
562
563 // Hash format for context sensitive profile. Reserve 4 bits for other
564 // information.
565 FunctionHash = (((uint64_t)JCH.getCRC()) << 28) + JC.getCRC();
566
567 // Reserve bit 60-63 for other information purpose.
569 if (IsCS)
571 LLVM_DEBUG(dbgs() << "Function Hash Computation for " << F.getName() << ":\n"
572 << " CRC = " << JC.getCRC()
573 << ", Selects = " << SIVisitor.getNumOfSelectInsts()
574 << ", Edges = " << MST.numEdges() << ", ICSites = "
575 << ValueSites[IPVK_IndirectCallTarget].size()
576 << ", Memops = " << ValueSites[IPVK_MemOPSize].size()
577 << ", High32 CRC = " << JCH.getCRC()
578 << ", Hash = " << FunctionHash << "\n";);
579
580 if (Opts.pgo_trace_func_hash != "-" &&
581 F.getName().contains(Opts.pgo_trace_func_hash))
582 dbgs() << "Funcname=" << F.getName() << ", Hash=" << FunctionHash
583 << " in building " << F.getParent()->getSourceFileName() << "\n";
584}
585
586// Check if we can safely rename this Comdat function.
587static bool canRenameComdat(
588 const InstrumentationOptions &Opts, Function &F,
589 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
590 if (!Opts.do_comdat_renaming || !canRenameComdatFunc(F, true))
591 return false;
592
593 // FIXME: Current only handle those Comdat groups that only containing one
594 // function.
595 // (1) For a Comdat group containing multiple functions, we need to have a
596 // unique postfix based on the hashes for each function. There is a
597 // non-trivial code refactoring to do this efficiently.
598 // (2) Variables can not be renamed, so we can not rename Comdat function in a
599 // group including global vars.
600 Comdat *C = F.getComdat();
601 for (auto &&CM : make_range(ComdatMembers.equal_range(C))) {
602 assert(!isa<GlobalAlias>(CM.second));
603 Function *FM = dyn_cast<Function>(CM.second);
604 if (FM != &F)
605 return false;
606 }
607 return true;
608}
609
610// Append the CFGHash to the Comdat function name.
611template <class Edge, class BBInfo>
612void FuncPGOInstrumentation<Edge, BBInfo>::renameComdatFunction() {
613 if (!canRenameComdat(Opts, F, ComdatMembers))
614 return;
615 std::string OrigName = F.getName().str();
616 std::string NewFuncName =
617 Twine(F.getName() + "." + Twine(FunctionHash)).str();
618 F.setName(Twine(NewFuncName));
620 FuncName = Twine(FuncName + "." + Twine(FunctionHash)).str();
621 Comdat *NewComdat;
622 Module *M = F.getParent();
623 // For AvailableExternallyLinkage functions, change the linkage to
624 // LinkOnceODR and put them into comdat. This is because after renaming, there
625 // is no backup external copy available for the function.
626 if (!F.hasComdat()) {
628 NewComdat = M->getOrInsertComdat(StringRef(NewFuncName));
630 F.setComdat(NewComdat);
631 return;
632 }
633
634 // This function belongs to a single function Comdat group.
635 Comdat *OrigComdat = F.getComdat();
636 std::string NewComdatName =
637 Twine(OrigComdat->getName() + "." + Twine(FunctionHash)).str();
638 NewComdat = M->getOrInsertComdat(StringRef(NewComdatName));
639 NewComdat->setSelectionKind(OrigComdat->getSelectionKind());
640
641 for (auto &&CM : make_range(ComdatMembers.equal_range(OrigComdat))) {
642 // Must be a function.
643 cast<Function>(CM.second)->setComdat(NewComdat);
644 }
645}
646
647/// Collect all the BBs that will be instruments and add them to
648/// `InstrumentBBs`.
649template <class Edge, class BBInfo>
650void FuncPGOInstrumentation<Edge, BBInfo>::getInstrumentBBs(
651 std::vector<BasicBlock *> &InstrumentBBs) {
652 if (BCI) {
653 for (auto &BB : F)
654 if (BCI->shouldInstrumentBlock(BB))
655 InstrumentBBs.push_back(&BB);
656 return;
657 }
658
659 // Use a worklist as we will update the vector during the iteration.
660 std::vector<Edge *> EdgeList;
661 EdgeList.reserve(MST.numEdges());
662 for (const auto &E : MST.allEdges())
663 EdgeList.push_back(E.get());
664
665 for (auto &E : EdgeList) {
666 BasicBlock *InstrBB = getInstrBB(E);
667 if (InstrBB)
668 InstrumentBBs.push_back(InstrBB);
669 }
670}
671
672// Given a CFG E to be instrumented, find which BB to place the instrumented
673// code. The function will split the critical edge if necessary.
674template <class Edge, class BBInfo>
675BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) {
676 if (E->InMST || E->Removed)
677 return nullptr;
678
679 BasicBlock *SrcBB = E->SrcBB;
680 BasicBlock *DestBB = E->DestBB;
681 // For a fake edge, instrument the real BB.
682 if (SrcBB == nullptr)
683 return DestBB;
684 if (DestBB == nullptr)
685 return SrcBB;
686
687 auto canInstrument = [](BasicBlock *BB) -> BasicBlock * {
688 // There are basic blocks (such as catchswitch) cannot be instrumented.
689 // If the returned first insertion point is the end of BB, skip this BB.
690 if (BB->getFirstNonPHIOrAlloca() == BB->end())
691 return nullptr;
692 return BB;
693 };
694
695 // Instrument the SrcBB if it has a single successor,
696 // otherwise, the DestBB if this is not a critical edge.
697 Instruction *TI = SrcBB->getTerminator();
698 if (TI->getNumSuccessors() <= 1)
699 return canInstrument(SrcBB);
700 if (!E->IsCritical)
701 return canInstrument(DestBB);
702
703 // Some IndirectBr critical edges cannot be split by the previous
704 // SplitIndirectBrCriticalEdges call. Bail out.
705 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
706 BasicBlock *InstrBB =
707 isa<IndirectBrInst>(TI) ? nullptr : SplitCriticalEdge(TI, SuccNum);
708 if (!InstrBB) {
710 dbgs() << "Fail to split critical edge: not instrument this edge.\n");
711 return nullptr;
712 }
713 // For a critical edge, we have to split. Instrument the newly
714 // created BB.
715 IsCS ? NumOfCSPGOSplit++ : NumOfPGOSplit++;
716 LLVM_DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index
717 << " --> " << getBBInfo(DestBB).Index << "\n");
718 // Need to add two new edges. First one: Add new edge of SrcBB->InstrBB.
719 MST.addEdge(SrcBB, InstrBB, 0);
720 // Second one: Add new edge of InstrBB->DestBB.
721 Edge &NewEdge1 = MST.addEdge(InstrBB, DestBB, 0);
722 NewEdge1.InMST = true;
723 E->Removed = true;
724
725 return canInstrument(InstrBB);
726}
727
728// When generating value profiling calls on Windows routines that make use of
729// handler funclets for exception processing an operand bundle needs to attached
730// to the called function. This routine will set \p OpBundles to contain the
731// funclet information, if any is needed, that should be placed on the generated
732// value profiling call for the value profile candidate call.
733static void
737 auto *OrigCall = dyn_cast<CallBase>(Cand.AnnotatedInst);
738 if (!OrigCall)
739 return;
740
741 if (!isa<IntrinsicInst>(OrigCall)) {
742 // The instrumentation call should belong to the same funclet as a
743 // non-intrinsic call, so just copy the operand bundle, if any exists.
744 std::optional<OperandBundleUse> ParentFunclet =
745 OrigCall->getOperandBundle(LLVMContext::OB_funclet);
746 if (ParentFunclet)
747 OpBundles.emplace_back(OperandBundleDef(*ParentFunclet));
748 } else {
749 // Intrinsics or other instructions do not get funclet information from the
750 // front-end. Need to use the BlockColors that was computed by the routine
751 // colorEHFunclets to determine whether a funclet is needed.
752 if (!BlockColors.empty()) {
753 const ColorVector &CV = BlockColors.find(OrigCall->getParent())->second;
754 assert(CV.size() == 1 && "non-unique color for block!");
756 if (EHPadIt->isEHPad())
757 OpBundles.emplace_back("funclet", &*EHPadIt);
758 }
759 }
760}
761
762// Visit all edge and instrument the edges not in MST, and do value profiling.
763// Critical edges will be split.
764void FunctionInstrumenter::instrument() {
765 if (!Opts.pgo_block_coverage) {
766 // Split indirectbr critical edges here before computing the MST rather than
767 // later in getInstrBB() to avoid invalidating it.
768 SplitIndirectBrCriticalEdges(F, /*IgnoreBlocksWithoutPHI=*/false, BPI, BFI);
769 }
770
771 const bool IsCtxProf = InstrumentationType == PGOInstrumentationType::CTXPROF;
772 FuncPGOInstrumentation<PGOEdge, PGOBBInfo> FuncInfo(
773 Opts, F, TLI, ComdatMembers, /*CreateGlobalVar=*/!IsCtxProf, BPI, BFI, LI,
774 InstrumentationType == PGOInstrumentationType::CSFDO,
775 shouldInstrumentEntryBB(), shouldInstrumentLoopEntries(),
776 Opts.pgo_block_coverage);
777
778 auto *const Name = IsCtxProf ? cast<GlobalValue>(&F) : FuncInfo.FuncNameVar;
779 auto *const CFGHash =
780 ConstantInt::get(Type::getInt64Ty(M.getContext()), FuncInfo.FunctionHash);
781 // Make sure that pointer to global is passed in with zero addrspace
782 // This is relevant during GPU profiling
783 auto *NormalizedNamePtr = ConstantExpr::getPointerBitCastOrAddrSpaceCast(
784 Name, PointerType::get(M.getContext(), 0));
785 if (Opts.pgo_function_entry_coverage) {
786 auto &EntryBB = F.getEntryBlock();
787 IRBuilder<> Builder(EntryBB.getFirstNonPHIOrAlloca());
788 // llvm.instrprof.cover(i8* <name>, i64 <hash>, i32 <num-counters>,
789 // i32 <index>)
790 Builder.CreateIntrinsic(
791 Intrinsic::instrprof_cover,
792 {NormalizedNamePtr, CFGHash, Builder.getInt32(1), Builder.getInt32(0)});
793 return;
794 }
795
796 std::vector<BasicBlock *> InstrumentBBs;
797 FuncInfo.getInstrumentBBs(InstrumentBBs);
798 unsigned NumCounters =
799 InstrumentBBs.size() + FuncInfo.SIVisitor.getNumOfSelectInsts();
800
801 if (IsCtxProf) {
802 StringSet<> SkipCSInstr(llvm::from_range,
803 Opts.ctx_prof_skip_callsite_instr);
804
805 auto *CSIntrinsic =
806 Intrinsic::getOrInsertDeclaration(&M, Intrinsic::instrprof_callsite);
807 // We want to count the instrumentable callsites, then instrument them. This
808 // is because the llvm.instrprof.callsite intrinsic has an argument (like
809 // the other instrprof intrinsics) capturing the total number of
810 // instrumented objects (counters, or callsites, in this case). In this
811 // case, we want that value so we can readily pass it to the compiler-rt
812 // APIs that may have to allocate memory based on the nr of callsites.
813 // The traversal logic is the same for both counting and instrumentation,
814 // just needs to be done in succession.
815 auto Visit = [&](llvm::function_ref<void(CallBase * CB)> Visitor) {
816 for (auto &BB : F)
817 for (auto &Instr : BB)
818 if (auto *CS = dyn_cast<CallBase>(&Instr)) {
820 continue;
821 if (CS->getCalledFunction() &&
822 SkipCSInstr.contains(CS->getCalledFunction()->getName()))
823 continue;
824 Visitor(CS);
825 }
826 };
827 // First, count callsites.
828 uint32_t TotalNumCallsites = 0;
829 Visit([&TotalNumCallsites](auto *) { ++TotalNumCallsites; });
830
831 // Now instrument.
832 uint32_t CallsiteIndex = 0;
833 Visit([&](auto *CB) {
834 IRBuilder<> Builder(CB);
835 Builder.CreateCall(CSIntrinsic,
836 {Name, CFGHash, Builder.getInt32(TotalNumCallsites),
837 Builder.getInt32(CallsiteIndex++),
838 CB->getCalledOperand()});
839 });
840 }
841
842 uint32_t I = 0;
843 if (Opts.pgo_temporal_instrumentation) {
844 NumCounters += Opts.pgo_block_coverage ? 8 : 1;
845 auto &EntryBB = F.getEntryBlock();
846 IRBuilder<> Builder(EntryBB.getFirstNonPHIOrAlloca());
847 // llvm.instrprof.timestamp(i8* <name>, i64 <hash>, i32 <num-counters>,
848 // i32 <index>)
849 Builder.CreateIntrinsic(Intrinsic::instrprof_timestamp,
850 {NormalizedNamePtr, CFGHash,
851 Builder.getInt32(NumCounters),
852 Builder.getInt32(I)});
853 I += Opts.pgo_block_coverage ? 8 : 1;
854 }
855
856 for (auto *InstrBB : InstrumentBBs) {
857 IRBuilder<> Builder(InstrBB->getFirstNonPHIOrAlloca());
858 assert(Builder.GetInsertPoint() != InstrBB->end() &&
859 "Cannot get the Instrumentation point");
860 // llvm.instrprof.increment(i8* <name>, i64 <hash>, i32 <num-counters>,
861 // i32 <index>)
862 Builder.CreateIntrinsic(
863 Opts.pgo_block_coverage ? Intrinsic::instrprof_cover
864 : Intrinsic::instrprof_increment,
865 {NormalizedNamePtr, CFGHash, Builder.getInt32(NumCounters),
866 Builder.getInt32(I++)});
867 }
868
869 // Now instrument select instructions:
870 FuncInfo.SIVisitor.instrumentSelects(&I, NumCounters, Name,
871 FuncInfo.FunctionHash);
872 assert(I == NumCounters);
873
874 if (isValueProfilingDisabled())
875 return;
876
877 NumOfPGOICall += FuncInfo.ValueSites[IPVK_IndirectCallTarget].size();
878
879 // Intrinsic function calls do not have funclet operand bundles needed for
880 // Windows exception handling attached to them. However, if value profiling is
881 // inserted for one of these calls, then a funclet value will need to be set
882 // on the instrumentation call based on the funclet coloring.
883 DenseMap<BasicBlock *, ColorVector> BlockColors;
884 if (F.hasPersonalityFn() &&
885 isScopedEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
886 BlockColors = colorEHFunclets(F);
887
888 // For each VP Kind, walk the VP candidates and instrument each one.
889 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind) {
890 unsigned SiteIndex = 0;
891 if (Kind == IPVK_MemOPSize && !Opts.pgo_instr_memop)
892 continue;
893
894 for (VPCandidateInfo Cand : FuncInfo.ValueSites[Kind]) {
895 LLVM_DEBUG(dbgs() << "Instrument one VP " << ValueProfKindDescr[Kind]
896 << " site: CallSite Index = " << SiteIndex << "\n");
897
898 IRBuilder<> Builder(Cand.InsertPt);
899 assert(Builder.GetInsertPoint() != Cand.InsertPt->getParent()->end() &&
900 "Cannot get the Instrumentation point");
901
902 Value *ToProfile = nullptr;
903 if (Cand.V->getType()->isIntegerTy())
904 ToProfile = Builder.CreateZExtOrTrunc(Cand.V, Builder.getInt64Ty());
905 else if (Cand.V->getType()->isPointerTy())
906 ToProfile = Builder.CreatePtrToInt(Cand.V, Builder.getInt64Ty());
907 assert(ToProfile && "value profiling Value is of unexpected type");
908
909 auto *NormalizedNamePtr = ConstantExpr::getPointerBitCastOrAddrSpaceCast(
910 Name, PointerType::get(M.getContext(), 0));
911
913 populateEHOperandBundle(Cand, BlockColors, OpBundles);
914 Builder.CreateCall(
916 Intrinsic::instrprof_value_profile),
917 {NormalizedNamePtr, Builder.getInt64(FuncInfo.FunctionHash),
918 ToProfile, Builder.getInt32(Kind), Builder.getInt32(SiteIndex++)},
919 OpBundles);
920 }
921 } // IPVK_First <= Kind <= IPVK_Last
922}
923
924namespace {
925
926// This class represents a CFG edge in profile use compilation.
927struct PGOUseEdge : public PGOEdge {
928 using PGOEdge::PGOEdge;
929
930 std::optional<uint64_t> Count;
931
932 // Set edge count value
933 void setEdgeCount(uint64_t Value) { Count = Value; }
934
935 // Return the information string for this object.
936 std::string infoString() const {
937 if (!Count)
938 return PGOEdge::infoString();
939 return (Twine(PGOEdge::infoString()) + " Count=" + Twine(*Count)).str();
940 }
941};
942
943using DirectEdges = SmallVector<PGOUseEdge *, 2>;
944
945// This class stores the auxiliary information for each BB.
946struct PGOUseBBInfo : public PGOBBInfo {
947 std::optional<uint64_t> Count;
948 int32_t UnknownCountInEdge = 0;
949 int32_t UnknownCountOutEdge = 0;
950 DirectEdges InEdges;
951 DirectEdges OutEdges;
952
953 PGOUseBBInfo(unsigned IX) : PGOBBInfo(IX) {}
954
955 // Set the profile count value for this BB.
956 void setBBInfoCount(uint64_t Value) { Count = Value; }
957
958 // Return the information string of this object.
959 std::string infoString() const {
960 if (!Count)
961 return PGOBBInfo::infoString();
962 return (Twine(PGOBBInfo::infoString()) + " Count=" + Twine(*Count)).str();
963 }
964
965 // Add an OutEdge and update the edge count.
966 void addOutEdge(PGOUseEdge *E) {
967 OutEdges.push_back(E);
968 UnknownCountOutEdge++;
969 }
970
971 // Add an InEdge and update the edge count.
972 void addInEdge(PGOUseEdge *E) {
973 InEdges.push_back(E);
974 UnknownCountInEdge++;
975 }
976};
977
978} // end anonymous namespace
979
980// Sum up the count values for all the edges.
982 uint64_t Total = 0;
983 for (const auto &E : Edges) {
984 if (E->Removed)
985 continue;
986 if (E->Count)
987 Total += *E->Count;
988 }
989 return Total;
990}
991
992namespace {
993
994class PGOUseFunc {
995public:
996 PGOUseFunc(const InstrumentationOptions &Opts, Function &Func, Module *Modu,
997 TargetLibraryInfo &TLI,
998 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers,
999 BranchProbabilityInfo *BPI, BlockFrequencyInfo *BFIin,
1000 LoopInfo *LI, ProfileSummaryInfo *PSI, bool IsCS,
1001 bool InstrumentFuncEntry, bool InstrumentLoopEntries,
1002 bool HasSingleByteCoverage)
1003 : Opts(Opts), F(Func), M(Modu), BFI(BFIin), PSI(PSI),
1004 FuncInfo(Opts, Func, TLI, ComdatMembers, false, BPI, BFIin, LI, IsCS,
1005 InstrumentFuncEntry, InstrumentLoopEntries,
1006 HasSingleByteCoverage),
1007 FreqAttr(FFA_Normal), IsCS(IsCS), VPC(Func, TLI) {}
1008
1009 void handleInstrProfError(Error Err, uint64_t MismatchedFuncSum);
1010
1011 /// Get the profile record, assign it to \p ProfileRecord, handle errors if
1012 /// necessary, and assign \p ProgramMaxCount. \returns true if there are no
1013 /// errors.
1014 bool getRecord(IndexedInstrProfReader *PGOReader);
1015
1016 // Read counts for the instrumented BB from profile.
1017 bool readCounters(bool &AllZeros,
1019
1020 // Populate the counts for all BBs.
1021 void populateCounters();
1022
1023 // Set block coverage based on profile coverage values.
1024 void populateCoverage();
1025
1026 // Set the branch weights based on the count values.
1027 void setBranchWeights();
1028
1029 // Annotate the value profile call sites for all value kind.
1030 void annotateValueSites();
1031
1032 // Annotate the value profile call sites for one value kind.
1033 void annotateValueSites(uint32_t Kind);
1034
1035 // Annotate the irreducible loop header weights.
1036 void annotateIrrLoopHeaderWeights();
1037
1038 // Annotate per-block uniformity info for offload profiling.
1039 void setBlockUniformityAttribute();
1040
1041 // The hotness of the function from the profile count.
1042 enum FuncFreqAttr { FFA_Normal, FFA_Cold, FFA_Hot };
1043
1044 // Return the function hotness from the profile.
1045 FuncFreqAttr getFuncFreqAttr() const { return FreqAttr; }
1046
1047 // Return the function hash.
1048 uint64_t getFuncHash() const { return FuncInfo.FunctionHash; }
1049
1050 // Return the profile record for this function;
1051 NamedInstrProfRecord &getProfileRecord() { return ProfileRecord; }
1052
1053 // Return the auxiliary BB information.
1054 PGOUseBBInfo &getBBInfo(const BasicBlock *BB) const {
1055 return FuncInfo.getBBInfo(BB);
1056 }
1057
1058 // Return the auxiliary BB information if available.
1059 PGOUseBBInfo *findBBInfo(const BasicBlock *BB) const {
1060 return FuncInfo.findBBInfo(BB);
1061 }
1062
1063 Function &getFunc() const { return F; }
1064
1065 void dumpInfo(StringRef Str = "") const { FuncInfo.dumpInfo(Str); }
1066
1067 uint64_t getProgramMaxCount() const { return ProgramMaxCount; }
1068
1069private:
1070 const InstrumentationOptions &Opts;
1071 Function &F;
1072 Module *M;
1073 BlockFrequencyInfo *BFI;
1074 ProfileSummaryInfo *PSI;
1075
1076 // This member stores the shared information with class PGOGenFunc.
1077 FuncPGOInstrumentation<PGOUseEdge, PGOUseBBInfo> FuncInfo;
1078
1079 // The maximum count value in the profile. This is only used in PGO use
1080 // compilation.
1081 uint64_t ProgramMaxCount;
1082
1083 // Position of counter that remains to be read.
1084 uint32_t CountPosition = 0;
1085
1086 // Total size of the profile count for this function.
1087 uint32_t ProfileCountSize = 0;
1088
1089 // ProfileRecord for this function.
1090 NamedInstrProfRecord ProfileRecord;
1091
1092 // Function hotness info derived from profile.
1093 FuncFreqAttr FreqAttr;
1094
1095 // Is to use the context sensitive profile.
1096 bool IsCS;
1097
1098 ValueProfileCollector VPC;
1099
1100 // Find the Instrumented BB and set the value. Return false on error.
1101 bool setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile);
1102
1103 // Set the edge counter value for the unknown edge -- there should be only
1104 // one unknown edge.
1105 void setEdgeCount(DirectEdges &Edges, uint64_t Value);
1106
1107 // Set the hot/cold inline hints based on the count values.
1108 // FIXME: This function should be removed once the functionality in
1109 // the inliner is implemented.
1110 void markFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {
1111 if (PSI->isHotCount(EntryCount))
1112 FreqAttr = FFA_Hot;
1113 else if (PSI->isColdCount(MaxCount))
1114 FreqAttr = FFA_Cold;
1115 }
1116};
1117
1118} // end anonymous namespace
1119
1120/// Set up InEdges/OutEdges for all BBs in the MST.
1122 const FuncPGOInstrumentation<PGOUseEdge, PGOUseBBInfo> &FuncInfo) {
1123 // This is not required when there is block coverage inference.
1124 if (FuncInfo.BCI)
1125 return;
1126 for (const auto &E : FuncInfo.MST.allEdges()) {
1127 if (E->Removed)
1128 continue;
1129 const BasicBlock *SrcBB = E->SrcBB;
1130 const BasicBlock *DestBB = E->DestBB;
1131 PGOUseBBInfo &SrcInfo = FuncInfo.getBBInfo(SrcBB);
1132 PGOUseBBInfo &DestInfo = FuncInfo.getBBInfo(DestBB);
1133 SrcInfo.addOutEdge(E.get());
1134 DestInfo.addInEdge(E.get());
1135 }
1136}
1137
1138// Visit all the edges and assign the count value for the instrumented
1139// edges and the BB. Return false on error.
1140bool PGOUseFunc::setInstrumentedCounts(
1141 const std::vector<uint64_t> &CountFromProfile) {
1142
1143 std::vector<BasicBlock *> InstrumentBBs;
1144 FuncInfo.getInstrumentBBs(InstrumentBBs);
1145
1146 setupBBInfoEdges(FuncInfo);
1147
1148 unsigned NumInstrumentedBBs = InstrumentBBs.size();
1149 unsigned NumSelects = FuncInfo.SIVisitor.getNumOfSelectInsts();
1150 unsigned NumCounters = NumInstrumentedBBs + NumSelects;
1151 // The number of counters here should match the number of counters
1152 // in profile. Return if they mismatch.
1153 if (NumCounters != CountFromProfile.size()) {
1154 LLVM_DEBUG({
1155 dbgs() << "PGO COUNTER MISMATCH for function " << F.getName() << ":\n";
1156 dbgs() << " Expected counters: " << NumCounters << "\n";
1157 dbgs() << " - From instrumented edges: " << NumInstrumentedBBs << "\n";
1158 for (size_t i = 0; i < InstrumentBBs.size(); ++i) {
1159 dbgs() << " " << i << ": ";
1160 InstrumentBBs[i]->printAsOperand(dbgs(), false);
1161 dbgs() << "\n";
1162 }
1163 dbgs() << " - From select instructions: " << NumSelects << "\n";
1164 dbgs() << " Actual counters from profile: " << CountFromProfile.size()
1165 << "\n";
1166 });
1167 return false;
1168 }
1169 auto *FuncEntry = &*F.begin();
1170
1171 // Set the profile count to the Instrumented BBs.
1172 uint32_t I = 0;
1173 for (BasicBlock *InstrBB : InstrumentBBs) {
1174 uint64_t CountValue = CountFromProfile[I++];
1175 PGOUseBBInfo &Info = getBBInfo(InstrBB);
1176 // If we reach here, we know that we have some nonzero count
1177 // values in this function. The entry count should not be 0.
1178 // Fix it if necessary.
1179 if (InstrBB == FuncEntry && CountValue == 0)
1180 CountValue = 1;
1181 Info.setBBInfoCount(CountValue);
1182 }
1183 ProfileCountSize = CountFromProfile.size();
1184 CountPosition = I;
1185
1186 // Set the edge count and update the count of unknown edges for BBs.
1187 auto setEdgeCount = [this](PGOUseEdge *E, uint64_t Value) -> void {
1188 E->setEdgeCount(Value);
1189 this->getBBInfo(E->SrcBB).UnknownCountOutEdge--;
1190 this->getBBInfo(E->DestBB).UnknownCountInEdge--;
1191 };
1192
1193 // Set the profile count the Instrumented edges. There are BBs that not in
1194 // MST but not instrumented. Need to set the edge count value so that we can
1195 // populate the profile counts later.
1196 for (const auto &E : FuncInfo.MST.allEdges()) {
1197 if (E->Removed || E->InMST)
1198 continue;
1199 const BasicBlock *SrcBB = E->SrcBB;
1200 PGOUseBBInfo &SrcInfo = getBBInfo(SrcBB);
1201
1202 // If only one out-edge, the edge profile count should be the same as BB
1203 // profile count.
1204 if (SrcInfo.Count && SrcInfo.OutEdges.size() == 1)
1205 setEdgeCount(E.get(), *SrcInfo.Count);
1206 else {
1207 const BasicBlock *DestBB = E->DestBB;
1208 PGOUseBBInfo &DestInfo = getBBInfo(DestBB);
1209 // If only one in-edge, the edge profile count should be the same as BB
1210 // profile count.
1211 if (DestInfo.Count && DestInfo.InEdges.size() == 1)
1212 setEdgeCount(E.get(), *DestInfo.Count);
1213 }
1214 if (E->Count)
1215 continue;
1216 // E's count should have been set from profile. If not, this meenas E skips
1217 // the instrumentation. We set the count to 0.
1218 setEdgeCount(E.get(), 0);
1219 }
1220 return true;
1221}
1222
1223// Set the count value for the unknown edge. There should be one and only one
1224// unknown edge in Edges vector.
1225void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) {
1226 for (auto &E : Edges) {
1227 if (E->Count)
1228 continue;
1229 E->setEdgeCount(Value);
1230
1231 getBBInfo(E->SrcBB).UnknownCountOutEdge--;
1232 getBBInfo(E->DestBB).UnknownCountInEdge--;
1233 return;
1234 }
1235 llvm_unreachable("Cannot find the unknown count edge");
1236}
1237
1238// Emit function metadata indicating PGO profile mismatch.
1240 const char MetadataName[] = "instr_prof_hash_mismatch";
1242 // If this metadata already exists, ignore.
1243 auto *Existing = F.getMetadata(LLVMContext::MD_annotation);
1244 if (Existing) {
1245 MDTuple *Tuple = cast<MDTuple>(Existing);
1246 for (const auto &N : Tuple->operands()) {
1247 if (N.equalsStr(MetadataName))
1248 return;
1249 Names.push_back(N.get());
1250 }
1251 }
1252
1253 MDBuilder MDB(ctx);
1254 Names.push_back(MDB.createString(MetadataName));
1255 MDNode *MD = MDTuple::get(ctx, Names);
1256 F.setMetadata(LLVMContext::MD_annotation, MD);
1257}
1258
1259void PGOUseFunc::handleInstrProfError(Error Err, uint64_t MismatchedFuncSum) {
1260 handleAllErrors(std::move(Err), [&](const InstrProfError &IPE) {
1261 auto &Ctx = M->getContext();
1262 auto Err = IPE.get();
1263 bool SkipWarning = false;
1264 LLVM_DEBUG(dbgs() << "Error in reading profile for Func "
1265 << FuncInfo.FuncName << ": ");
1266 if (Err == instrprof_error::unknown_function) {
1267 IsCS ? NumOfCSPGOMissing++ : NumOfPGOMissing++;
1268 SkipWarning = !Opts.pgo_warn_missing_function;
1269 LLVM_DEBUG(dbgs() << "unknown function");
1270 } else if (Err == instrprof_error::hash_mismatch ||
1271 Err == instrprof_error::malformed) {
1272 IsCS ? NumOfCSPGOMismatch++ : NumOfPGOMismatch++;
1273 SkipWarning =
1275 (Opts.no_pgo_warn_mismatch_comdat_weak &&
1276 (F.hasComdat() || F.getLinkage() == GlobalValue::WeakAnyLinkage ||
1278 LLVM_DEBUG(dbgs() << "hash mismatch (hash= " << FuncInfo.FunctionHash
1279 << " skip=" << SkipWarning << ")");
1280 // Emit function metadata indicating PGO profile mismatch.
1281 annotateFunctionWithHashMismatch(F, M->getContext());
1282 }
1283
1284 LLVM_DEBUG(dbgs() << " IsCS=" << IsCS << "\n");
1285 if (SkipWarning)
1286 return;
1287
1288 std::string Msg =
1289 IPE.message() + std::string(" ") + F.getName().str() +
1290 std::string(" Hash = ") + std::to_string(FuncInfo.FunctionHash) +
1291 std::string(" up to ") + std::to_string(MismatchedFuncSum) +
1292 std::string(" count discarded");
1293
1294 Ctx.diagnose(
1295 DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));
1296 });
1297}
1298
1299bool PGOUseFunc::getRecord(IndexedInstrProfReader *PGOReader) {
1300 uint64_t MismatchedFuncSum = 0;
1301 auto Result = PGOReader->getInstrProfRecord(
1302 FuncInfo.FuncName, FuncInfo.FunctionHash, FuncInfo.DeprecatedFuncName,
1303 &MismatchedFuncSum);
1304 if (Error E = Result.takeError()) {
1305 handleInstrProfError(std::move(E), MismatchedFuncSum);
1306 return false;
1307 }
1308 ProfileRecord = std::move(Result.get());
1309 ProgramMaxCount = PGOReader->getMaximumFunctionCount(IsCS);
1310 return true;
1311}
1312
1313// Read the profile from ProfileFileName and assign the value to the
1314// instrumented BB and the edges. Return true if the profile are successfully
1315// read, and false on errors.
1316bool PGOUseFunc::readCounters(bool &AllZeros,
1318 auto &Ctx = M->getContext();
1319 PseudoKind = ProfileRecord.getCountPseudoKind();
1320 if (PseudoKind != InstrProfRecord::NotPseudo) {
1321 return true;
1322 }
1323 std::vector<uint64_t> &CountFromProfile = ProfileRecord.Counts;
1324
1325 IsCS ? NumOfCSPGOFunc++ : NumOfPGOFunc++;
1326 LLVM_DEBUG(dbgs() << CountFromProfile.size() << " counts\n");
1327
1328 uint64_t ValueSum = 0;
1329 for (unsigned I = 0, S = CountFromProfile.size(); I < S; I++) {
1330 LLVM_DEBUG(dbgs() << " " << I << ": " << CountFromProfile[I] << "\n");
1331 ValueSum += CountFromProfile[I];
1332 }
1333 AllZeros = (ValueSum == 0);
1334
1335 LLVM_DEBUG(dbgs() << "SUM = " << ValueSum << "\n");
1336
1337 getBBInfo(nullptr).UnknownCountOutEdge = 2;
1338 getBBInfo(nullptr).UnknownCountInEdge = 2;
1339
1340 if (!setInstrumentedCounts(CountFromProfile)) {
1341 LLVM_DEBUG(
1342 dbgs() << "Inconsistent number of counts, skipping this function");
1343 Ctx.diagnose(DiagnosticInfoPGOProfile(
1344 M->getName().data(),
1345 Twine("Inconsistent number of counts in ") + F.getName().str() +
1346 Twine(": the profile may be stale or there is a function name "
1347 "collision."),
1348 DS_Warning));
1349 return false;
1350 }
1351 return true;
1352}
1353
1354void PGOUseFunc::populateCoverage() {
1355 IsCS ? NumOfCSPGOFunc++ : NumOfPGOFunc++;
1356
1357 ArrayRef<uint64_t> CountsFromProfile = ProfileRecord.Counts;
1358 DenseMap<const BasicBlock *, bool> Coverage;
1359 unsigned Index = 0;
1360 for (auto &BB : F)
1361 if (FuncInfo.BCI->shouldInstrumentBlock(BB))
1362 Coverage[&BB] = (CountsFromProfile[Index++] != 0);
1363 assert(Index == CountsFromProfile.size());
1364
1365 // For each B in InverseDependencies[A], if A is covered then B is covered.
1366 DenseMap<const BasicBlock *, DenseSet<const BasicBlock *>>
1367 InverseDependencies;
1368 for (auto &BB : F) {
1369 for (auto *Dep : FuncInfo.BCI->getDependencies(BB)) {
1370 // If Dep is covered then BB is covered.
1371 InverseDependencies[Dep].insert(&BB);
1372 }
1373 }
1374
1375 // Infer coverage of the non-instrumented blocks using a flood-fill algorithm.
1376 std::stack<const BasicBlock *> CoveredBlocksToProcess;
1377 for (auto &[BB, IsCovered] : Coverage)
1378 if (IsCovered)
1379 CoveredBlocksToProcess.push(BB);
1380
1381 while (!CoveredBlocksToProcess.empty()) {
1382 auto *CoveredBlock = CoveredBlocksToProcess.top();
1383 assert(Coverage[CoveredBlock]);
1384 CoveredBlocksToProcess.pop();
1385 for (auto *BB : InverseDependencies[CoveredBlock]) {
1386 // If CoveredBlock is covered then BB is covered.
1387 bool &Cov = Coverage[BB];
1388 if (Cov)
1389 continue;
1390 Cov = true;
1391 CoveredBlocksToProcess.push(BB);
1392 }
1393 }
1394
1395 // Annotate block coverage.
1396 MDBuilder MDB(F.getContext());
1397 // We set the entry count to 10000 if the entry block is covered so that BFI
1398 // can propagate a fraction of this count to the other covered blocks.
1399 F.setEntryCount(Coverage[&F.getEntryBlock()] ? 10000 : 0);
1400 for (auto &BB : F) {
1401 // For a block A and its successor B, we set the edge weight as follows:
1402 // If A is covered and B is covered, set weight=1.
1403 // If A is covered and B is uncovered, set weight=0.
1404 // If A is uncovered, set weight=1.
1405 // This setup will allow BFI to give nonzero profile counts to only covered
1406 // blocks.
1407 SmallVector<uint32_t, 4> Weights;
1408 for (auto *Succ : successors(&BB))
1409 Weights.push_back((Coverage[Succ] || !Coverage[&BB]) ? 1 : 0);
1410 if (Weights.size() >= 2)
1411 llvm::setBranchWeights(*BB.getTerminator(), Weights,
1412 /*IsExpected=*/false);
1413 }
1414
1415 unsigned NumCorruptCoverage = 0;
1416 CycleInfo CI;
1417 CI.compute(F);
1418 BranchProbabilityInfo BPI(F, CI);
1419 BlockFrequencyInfo BFI(F, BPI, CI);
1420 auto IsBlockDead = [&](const BasicBlock &BB) -> std::optional<bool> {
1421 if (auto C = BFI.getBlockProfileCount(&BB))
1422 return C == 0;
1423 return {};
1424 };
1425 LLVM_DEBUG(dbgs() << "Block Coverage: (Instrumented=*, Covered=X)\n");
1426 for (auto &BB : F) {
1427 LLVM_DEBUG(dbgs() << (FuncInfo.BCI->shouldInstrumentBlock(BB) ? "* " : " ")
1428 << (Coverage[&BB] ? "X " : " ") << " " << BB.getName()
1429 << "\n");
1430 // In some cases it is possible to find a covered block that has no covered
1431 // successors, e.g., when a block calls a function that may call exit(). In
1432 // those cases, BFI could find its successor to be covered while BCI could
1433 // find its successor to be dead.
1434 const bool &Cov = Coverage[&BB];
1435 if (Cov == IsBlockDead(BB).value_or(false)) {
1436 LLVM_DEBUG(
1437 dbgs() << "Found inconsistent block covearge for " << BB.getName()
1438 << ": BCI=" << (Cov ? "Covered" : "Dead") << " BFI="
1439 << (IsBlockDead(BB).value() ? "Dead" : "Covered") << "\n");
1440 ++NumCorruptCoverage;
1441 }
1442 if (Cov)
1443 ++NumCoveredBlocks;
1444 }
1445 if (Opts.pgo_verify_bfi && NumCorruptCoverage) {
1446 auto &Ctx = M->getContext();
1447 Ctx.diagnose(DiagnosticInfoPGOProfile(
1448 M->getName().data(),
1449 Twine("Found inconsistent block coverage for function ") + F.getName() +
1450 " in " + Twine(NumCorruptCoverage) + " blocks.",
1451 DS_Warning));
1452 }
1453 if (Opts.pgo_view_block_coverage_graph)
1454 FuncInfo.BCI->viewBlockCoverageGraph(&Coverage);
1455}
1456
1457// Populate the counters from instrumented BBs to all BBs.
1458// In the end of this operation, all BBs should have a valid count value.
1459void PGOUseFunc::populateCounters() {
1460 bool Changes = true;
1461 unsigned NumPasses = 0;
1462 while (Changes) {
1463 NumPasses++;
1464 Changes = false;
1465
1466 // For efficient traversal, it's better to start from the end as most
1467 // of the instrumented edges are at the end.
1468 for (auto &BB : reverse(F)) {
1469 PGOUseBBInfo *UseBBInfo = findBBInfo(&BB);
1470 if (UseBBInfo == nullptr)
1471 continue;
1472 if (!UseBBInfo->Count) {
1473 if (UseBBInfo->UnknownCountOutEdge == 0) {
1474 UseBBInfo->Count = sumEdgeCount(UseBBInfo->OutEdges);
1475 Changes = true;
1476 } else if (UseBBInfo->UnknownCountInEdge == 0) {
1477 UseBBInfo->Count = sumEdgeCount(UseBBInfo->InEdges);
1478 Changes = true;
1479 }
1480 }
1481 if (UseBBInfo->Count) {
1482 if (UseBBInfo->UnknownCountOutEdge == 1) {
1483 uint64_t Total = 0;
1484 uint64_t OutSum = sumEdgeCount(UseBBInfo->OutEdges);
1485 // If the one of the successor block can early terminate (no-return),
1486 // we can end up with situation where out edge sum count is larger as
1487 // the source BB's count is collected by a post-dominated block.
1488 if (*UseBBInfo->Count > OutSum)
1489 Total = *UseBBInfo->Count - OutSum;
1490 setEdgeCount(UseBBInfo->OutEdges, Total);
1491 Changes = true;
1492 }
1493 if (UseBBInfo->UnknownCountInEdge == 1) {
1494 uint64_t Total = 0;
1495 uint64_t InSum = sumEdgeCount(UseBBInfo->InEdges);
1496 if (*UseBBInfo->Count > InSum)
1497 Total = *UseBBInfo->Count - InSum;
1498 setEdgeCount(UseBBInfo->InEdges, Total);
1499 Changes = true;
1500 }
1501 }
1502 }
1503 }
1504
1505 LLVM_DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n");
1506 (void)NumPasses;
1507#ifndef NDEBUG
1508 // Assert every BB has a valid counter.
1509 for (auto &BB : F) {
1510 auto BI = findBBInfo(&BB);
1511 if (BI == nullptr)
1512 continue;
1513 assert(BI->Count && "BB count is not valid");
1514 }
1515#endif
1516 // Now annotate select instructions. This may fixup impossible block counts.
1517 FuncInfo.SIVisitor.annotateSelects(this, &CountPosition);
1518 assert(CountPosition == ProfileCountSize);
1519
1520 uint64_t FuncEntryCount = *getBBInfo(&*F.begin()).Count;
1521 uint64_t FuncMaxCount = FuncEntryCount;
1522 for (auto &BB : F) {
1523 auto BI = findBBInfo(&BB);
1524 if (BI == nullptr)
1525 continue;
1526 FuncMaxCount = std::max(FuncMaxCount, *BI->Count);
1527 }
1528
1529 // Fix the obviously inconsistent entry count.
1530 if (FuncMaxCount > 0 && FuncEntryCount == 0)
1531 FuncEntryCount = 1;
1532 F.setEntryCount(FuncEntryCount);
1533 markFunctionAttributes(FuncEntryCount, FuncMaxCount);
1534
1535 LLVM_DEBUG(FuncInfo.dumpInfo("after reading profile."));
1536}
1537
1538// Assign the scaled count values to the BB with multiple out edges.
1539void PGOUseFunc::setBranchWeights() {
1540 // Generate MD_prof metadata for every branch instruction.
1541 LLVM_DEBUG(dbgs() << "\nSetting branch weights for func " << F.getName()
1542 << " IsCS=" << IsCS << "\n");
1543 for (auto &BB : F) {
1544 Instruction *TI = BB.getTerminator();
1545 if (TI->getNumSuccessors() < 2)
1546 continue;
1547 if (!(isa<CondBrInst>(TI) || isa<SwitchInst>(TI) ||
1549 isa<CallBrInst>(TI)))
1550 continue;
1551
1552 const PGOUseBBInfo &BBCountInfo = getBBInfo(&BB);
1553 if (!*BBCountInfo.Count)
1554 continue;
1555
1556 // We have a non-zero Branch BB.
1557
1558 // SuccessorCount can be greater than OutEdgesCount, because
1559 // removed edges don't appear in OutEdges.
1560 unsigned OutEdgesCount = BBCountInfo.OutEdges.size();
1561 unsigned SuccessorCount = BB.getTerminator()->getNumSuccessors();
1562 assert(OutEdgesCount <= SuccessorCount);
1563
1564 SmallVector<uint64_t, 2> EdgeCounts(SuccessorCount, 0);
1565 uint64_t MaxCount = 0;
1566 for (unsigned It = 0; It < OutEdgesCount; It++) {
1567 const PGOUseEdge *E = BBCountInfo.OutEdges[It];
1568 const BasicBlock *SrcBB = E->SrcBB;
1569 const BasicBlock *DestBB = E->DestBB;
1570 if (DestBB == nullptr)
1571 continue;
1572 unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);
1573 uint64_t EdgeCount = *E->Count;
1574 if (EdgeCount > MaxCount)
1575 MaxCount = EdgeCount;
1576 EdgeCounts[SuccNum] = EdgeCount;
1577 }
1578
1579 if (MaxCount)
1580 setProfMetadata(TI, EdgeCounts, MaxCount);
1581 else {
1582 // A zero MaxCount can come about when we have a BB with a positive
1583 // count, and whose successor blocks all have 0 count. This can happen
1584 // when there is no exit block and the code exits via a noreturn function.
1585 auto &Ctx = M->getContext();
1586 Ctx.diagnose(DiagnosticInfoPGOProfile(
1587 M->getName().data(),
1588 Twine("Profile in ") + F.getName().str() +
1589 Twine(" partially ignored") +
1590 Twine(", possibly due to the lack of a return path."),
1591 DS_Warning));
1592 }
1593 }
1594}
1595
1597 for (BasicBlock *Pred : predecessors(BB)) {
1598 if (isa<IndirectBrInst>(Pred->getTerminator()))
1599 return true;
1600 }
1601 return false;
1602}
1603
1604void PGOUseFunc::annotateIrrLoopHeaderWeights() {
1605 LLVM_DEBUG(dbgs() << "\nAnnotating irreducible loop header weights.\n");
1606 // Find irr loop headers
1607 for (auto &BB : F) {
1608 // As a heuristic also annotate indrectbr targets as they have a high chance
1609 // to become an irreducible loop header after the indirectbr tail
1610 // duplication.
1611 if (BFI->isIrrLoopHeader(&BB) || isIndirectBrTarget(&BB)) {
1612 Instruction *TI = BB.getTerminator();
1613 const PGOUseBBInfo &BBCountInfo = getBBInfo(&BB);
1614 setIrrLoopHeaderMetadata(M, TI, *BBCountInfo.Count);
1615 }
1616 }
1617}
1618
1619void PGOUseFunc::setBlockUniformityAttribute() {
1620 if (ProfileRecord.UniformityBits.empty())
1621 return;
1622
1623 // Annotate uniformity on each instrumented IR basic block so later codegen
1624 // passes (MachineFunction) can consume it without relying on fragile block
1625 // numbering heuristics.
1626 //
1627 // Metadata kind: LLVMContext::MD_block_uniformity_profile
1628 // Payload: i1 (true = uniform, false = divergent)
1629
1630 std::vector<BasicBlock *> InstrumentBBs;
1631 FuncInfo.getInstrumentBBs(InstrumentBBs);
1632
1633 LLVMContext &Ctx = F.getContext();
1634 Type *Int1Ty = Type::getInt1Ty(Ctx);
1635
1636 for (size_t I = 0, E = InstrumentBBs.size(); I < E; ++I) {
1637 BasicBlock *BB = InstrumentBBs[I];
1638 if (!BB)
1639 continue;
1640 bool IsUniform = ProfileRecord.isBlockUniform(I);
1641 auto *MD = MDNode::get(
1642 Ctx, ConstantAsMetadata::get(ConstantInt::get(Int1Ty, IsUniform)));
1643 BB->getTerminator()->setMetadata(LLVMContext::MD_block_uniformity_profile,
1644 MD);
1645 }
1646
1647 LLVM_DEBUG({
1648 dbgs() << "PGO: Set block uniformity profile for " << F.getName() << ": ";
1649 for (size_t I = 0, E = InstrumentBBs.size(); I < E; ++I)
1650 dbgs() << (ProfileRecord.isBlockUniform(I) ? 'U' : 'D');
1651 dbgs() << "\n";
1652 });
1653}
1654
1655void SelectInstVisitor::instrumentOneSelectInst(SelectInst &SI) {
1656 Module *M = F.getParent();
1657 IRBuilder<> Builder(&SI);
1658 Type *Int64Ty = Builder.getInt64Ty();
1659 Value *Cond = SI.getCondition();
1660 // Freeze the condition so that a poison condition can only increment by
1661 // 0 or 1, but not some other value.
1663 Cond = Builder.CreateFreeze(Cond);
1664 auto *Step = Builder.CreateZExt(Cond, Int64Ty);
1665 auto *NormalizedFuncNameVarPtr =
1667 FuncNameVar, PointerType::get(M->getContext(), 0));
1668 Builder.CreateIntrinsic(Intrinsic::instrprof_increment_step,
1669 {NormalizedFuncNameVarPtr, Builder.getInt64(FuncHash),
1670 Builder.getInt32(TotalNumCtrs),
1671 Builder.getInt32(*CurCtrIdx), Step});
1672 ++(*CurCtrIdx);
1673}
1674
1675void SelectInstVisitor::annotateOneSelectInst(SelectInst &SI) {
1676 std::vector<uint64_t> &CountFromProfile = UseFunc->getProfileRecord().Counts;
1677 assert(*CurCtrIdx < CountFromProfile.size() &&
1678 "Out of bound access of counters");
1679 uint64_t SCounts[2];
1680 SCounts[0] = CountFromProfile[*CurCtrIdx]; // True count
1681 ++(*CurCtrIdx);
1682 uint64_t TotalCount = 0;
1683 auto BI = UseFunc->findBBInfo(SI.getParent());
1684 if (BI != nullptr) {
1685 TotalCount = *BI->Count;
1686
1687 // Fix the block count if it is impossible.
1688 if (TotalCount < SCounts[0])
1689 BI->Count = SCounts[0];
1690 }
1691 // False Count
1692 SCounts[1] = (TotalCount > SCounts[0] ? TotalCount - SCounts[0] : 0);
1693 uint64_t MaxCount = std::max(SCounts[0], SCounts[1]);
1694 if (MaxCount)
1695 setProfMetadata(&SI, SCounts, MaxCount);
1696}
1697
1698void SelectInstVisitor::visitSelectInst(SelectInst &SI) {
1699 if (!Opts.pgo_instr_select || Opts.pgo_function_entry_coverage ||
1700 HasSingleByteCoverage)
1701 return;
1702 // FIXME: do not handle this yet.
1703 if (SI.getCondition()->getType()->isVectorTy())
1704 return;
1705
1706 switch (Mode) {
1707 case VM_counting:
1708 NSIs++;
1709 return;
1710 case VM_instrument:
1711 instrumentOneSelectInst(SI);
1712 return;
1713 case VM_annotate:
1714 annotateOneSelectInst(SI);
1715 return;
1716 }
1717
1718 llvm_unreachable("Unknown visiting mode");
1719}
1720
1721static uint32_t getMaxNumAnnotations(const InstrumentationOptions &Opts,
1722 const LLVMContext &C,
1723 InstrProfValueKind ValueProfKind) {
1724 if (ValueProfKind == IPVK_MemOPSize)
1725 return Opts.memop_max_annotations;
1726 if (ValueProfKind == llvm::IPVK_VTableTarget)
1728 return Opts.icp_max_annotations;
1729}
1730
1731// Traverse all valuesites and annotate the instructions for all value kind.
1732void PGOUseFunc::annotateValueSites() {
1733 if (Opts.disable_vp)
1734 return;
1735
1736 for (uint32_t Kind = IPVK_First; Kind <= IPVK_Last; ++Kind)
1737 annotateValueSites(Kind);
1738}
1739
1740// Annotate the instructions for a specific value kind.
1741void PGOUseFunc::annotateValueSites(uint32_t Kind) {
1742 assert(Kind <= IPVK_Last);
1743 unsigned ValueSiteIndex = 0;
1744
1745 unsigned NumValueSites = ProfileRecord.getNumValueSites(Kind);
1746
1747 // Since there isn't a reliable or fast way for profile reader to tell if a
1748 // profile is generated with `-enable-vtable-value-profiling` on, we run the
1749 // value profile collector over the function IR to find the instrumented sites
1750 // iff function profile records shows the number of instrumented vtable sites
1751 // is not zero. Function cfg already takes the number of instrumented
1752 // indirect call sites into account so it doesn't hash the number of
1753 // instrumented vtables; as a side effect it makes it easier to enable
1754 // profiling and profile use in two steps if needed.
1755 // TODO: Remove this if/when -enable-vtable-value-profiling is on by default.
1756 if (NumValueSites > 0 && Kind == IPVK_VTableTarget &&
1757 NumValueSites != FuncInfo.ValueSites[IPVK_VTableTarget].size() &&
1758 getMaxNumVTableAnnotations(M->getContext()) != 0)
1759 FuncInfo.ValueSites[IPVK_VTableTarget] = VPC.get(IPVK_VTableTarget);
1760 auto &ValueSites = FuncInfo.ValueSites[Kind];
1761 if (NumValueSites != ValueSites.size()) {
1762 auto &Ctx = M->getContext();
1763 Ctx.diagnose(DiagnosticInfoPGOProfile(
1764 M->getName().data(),
1765 Twine("Inconsistent number of value sites for ") +
1766 Twine(ValueProfKindDescr[Kind]) + Twine(" profiling in \"") +
1767 F.getName().str() +
1768 Twine("\", possibly due to the use of a stale profile."),
1769 DS_Warning));
1770 return;
1771 }
1772
1773 for (VPCandidateInfo &I : ValueSites) {
1774 LLVM_DEBUG(dbgs() << "Read one value site profile (kind = " << Kind
1775 << "): Index = " << ValueSiteIndex << " out of "
1776 << NumValueSites << "\n");
1778 *M, *I.AnnotatedInst, ProfileRecord,
1779 static_cast<InstrProfValueKind>(Kind), ValueSiteIndex,
1780 getMaxNumAnnotations(Opts, M->getContext(),
1781 static_cast<InstrProfValueKind>(Kind)));
1782 ValueSiteIndex++;
1783 }
1784}
1785
1786// Collect the set of members for each Comdat in module M and store
1787// in ComdatMembers.
1789 const InstrumentationOptions &Opts, Module &M,
1790 std::unordered_multimap<Comdat *, GlobalValue *> &ComdatMembers) {
1791 if (!Opts.do_comdat_renaming)
1792 return;
1793 for (Function &F : M)
1794 if (Comdat *C = F.getComdat())
1795 ComdatMembers.insert(std::make_pair(C, &F));
1796 for (GlobalVariable &GV : M.globals())
1797 if (Comdat *C = GV.getComdat())
1798 ComdatMembers.insert(std::make_pair(C, &GV));
1799 for (GlobalAlias &GA : M.aliases())
1800 if (Comdat *C = GA.getComdat())
1801 ComdatMembers.insert(std::make_pair(C, &GA));
1802}
1803
1804// Return true if we should not find instrumentation data for this function
1805static bool skipPGOUse(const InstrumentationOptions &Opts, const Function &F) {
1806 if (F.isDeclaration())
1807 return true;
1808 // If there are too many critical edges, PGO might cause
1809 // compiler time problem. Skip PGO if the number of
1810 // critical edges execeed the threshold.
1811 unsigned NumCriticalEdges = 0;
1812 for (auto &BB : F) {
1813 const Instruction *TI = BB.getTerminator();
1814 for (unsigned I = 0, E = TI->getNumSuccessors(); I != E; ++I) {
1815 if (isCriticalEdge(TI, I))
1816 NumCriticalEdges++;
1817 }
1818 }
1819 if (NumCriticalEdges > Opts.pgo_critical_edge_threshold) {
1820 LLVM_DEBUG(dbgs() << "In func " << F.getName()
1821 << ", NumCriticalEdges=" << NumCriticalEdges
1822 << " exceed the threshold. Skip PGO.\n");
1823 return true;
1824 }
1825 return false;
1826}
1827
1828// Return true if we should not instrument this function
1829static bool skipPGOGen(const InstrumentationOptions &Opts, const Function &F) {
1830 if (skipPGOUse(Opts, F))
1831 return true;
1832 if (F.hasFnAttribute(llvm::Attribute::Naked))
1833 return true;
1834 if (F.hasFnAttribute(llvm::Attribute::NoProfile))
1835 return true;
1836 if (F.hasFnAttribute(llvm::Attribute::SkipProfile))
1837 return true;
1838 if (F.getInstructionCount() < Opts.pgo_function_size_threshold)
1839 return true;
1840 if (Opts.pgo_instrument_cold_function_only) {
1841 if (auto EntryCount = F.getEntryCount())
1842 return *EntryCount > Opts.pgo_cold_instrument_entry_threshold;
1843 return !Opts.pgo_treat_unknown_as_cold;
1844 }
1845 return false;
1846}
1847
1849 const InstrumentationOptions &Opts, Module &M,
1850 function_ref<TargetLibraryInfo &(Function &)> LookupTLI,
1853 function_ref<LoopInfo *(Function &)> LookupLI,
1854 PGOInstrumentationType InstrumentationType) {
1855 // For the context-sensitive instrumentation, we should have a separated pass
1856 // (before LTO/ThinLTO linking) to create these variables.
1857 if (InstrumentationType == PGOInstrumentationType::FDO)
1858 createIRLevelProfileFlagVar(Opts, M, InstrumentationType);
1859
1860 Triple TT(M.getTargetTriple());
1861 LLVMContext &Ctx = M.getContext();
1862 if (!TT.isOSBinFormatELF() && EnableVTableValueProfiling)
1864 M.getName().data(),
1865 Twine("VTable value profiling is presently not "
1866 "supported for non-ELF object formats"),
1867 DS_Warning));
1868 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
1869 collectComdatMembers(Opts, M, ComdatMembers);
1870
1871 for (auto &F : M) {
1872 if (skipPGOGen(Opts, F))
1873 continue;
1874 TargetLibraryInfo &TLI = LookupTLI(F);
1875 BranchProbabilityInfo *BPI = LookupBPI(F);
1876 BlockFrequencyInfo *BFI = LookupBFI(F);
1877 LoopInfo *LI = LookupLI(F);
1878 FunctionInstrumenter FI(Opts, M, F, TLI, ComdatMembers, BPI, BFI, LI,
1879 InstrumentationType);
1880 FI.instrument();
1881 }
1882 return true;
1883}
1884
1885PreservedAnalyses
1887 createProfileFileNameVar(M, CSInstrName);
1888 const InstrumentationOptions &Opts = getInstrumentationOptions(M);
1889 // The variable in a comdat may be discarded by LTO. Ensure the declaration
1890 // will be retained.
1893 if (ProfileSampling)
1898 return PA;
1899}
1900
1903 auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1904 auto LookupTLI = [&FAM](Function &F) -> TargetLibraryInfo & {
1905 return FAM.getResult<TargetLibraryAnalysis>(F);
1906 };
1907 auto LookupBPI = [&FAM](Function &F) {
1908 return &FAM.getResult<BranchProbabilityAnalysis>(F);
1909 };
1910 auto LookupBFI = [&FAM](Function &F) {
1911 return &FAM.getResult<BlockFrequencyAnalysis>(F);
1912 };
1913 auto LookupLI = [&FAM](Function &F) {
1914 return &FAM.getResult<LoopAnalysis>(F);
1915 };
1916
1917 const InstrumentationOptions &Opts = getInstrumentationOptions(M);
1918 if (!instrumentAllFunctions(Opts, M, LookupTLI, LookupBPI, LookupBFI,
1919 LookupLI, InstrumentationType))
1920 return PreservedAnalyses::all();
1921
1922 return PreservedAnalyses::none();
1923}
1924
1925// Using the ratio b/w sums of profile count values and BFI count values to
1926// adjust the func entry count.
1927static void fixFuncEntryCount(PGOUseFunc &Func, CycleInfo &CI,
1928 BranchProbabilityInfo &NBPI) {
1929 Function &F = Func.getFunc();
1930 BlockFrequencyInfo NBFI(F, NBPI, CI);
1931#ifndef NDEBUG
1932 auto BFIEntryCount = F.getEntryCount();
1933 assert(BFIEntryCount && (*BFIEntryCount > 0) && "Invalid BFI Entrycount");
1934#endif
1935 auto SumCount = APFloat::getZero(APFloat::IEEEdouble());
1936 auto SumBFICount = APFloat::getZero(APFloat::IEEEdouble());
1937 for (auto &BBI : F) {
1938 uint64_t CountValue = 0;
1939 uint64_t BFICountValue = 0;
1940 if (!Func.findBBInfo(&BBI))
1941 continue;
1942 auto BFICount = NBFI.getBlockProfileCount(&BBI);
1943 CountValue = *Func.getBBInfo(&BBI).Count;
1944 BFICountValue = *BFICount;
1945 SumCount.add(APFloat(CountValue * 1.0), APFloat::rmNearestTiesToEven);
1946 SumBFICount.add(APFloat(BFICountValue * 1.0), APFloat::rmNearestTiesToEven);
1947 }
1948 if (SumCount.isZero())
1949 return;
1950
1951 assert(SumBFICount.compare(APFloat(0.0)) == APFloat::cmpGreaterThan &&
1952 "Incorrect sum of BFI counts");
1953 if (SumBFICount.compare(SumCount) == APFloat::cmpEqual)
1954 return;
1955 double Scale = (SumCount / SumBFICount).convertToDouble();
1956 if (Scale < 1.001 && Scale > 0.999)
1957 return;
1958
1959 uint64_t FuncEntryCount = *Func.getBBInfo(&*F.begin()).Count;
1960 uint64_t NewEntryCount = 0.5 + FuncEntryCount * Scale;
1961 if (NewEntryCount == 0)
1962 NewEntryCount = 1;
1963 if (NewEntryCount != FuncEntryCount) {
1964 F.setEntryCount(NewEntryCount);
1965 LLVM_DEBUG(dbgs() << "FixFuncEntryCount: in " << F.getName()
1966 << ", entry_count " << FuncEntryCount << " --> "
1967 << NewEntryCount << "\n");
1968 }
1969}
1970
1971// Compare the profile count values with BFI count values, and print out
1972// the non-matching ones.
1973static void verifyFuncBFI(const InstrumentationOptions &Opts, PGOUseFunc &Func,
1975 uint64_t HotCountThreshold,
1977 Function &F = Func.getFunc();
1978 BlockFrequencyInfo NBFI(F, NBPI, CI);
1979 // bool PrintFunc = false;
1980 bool HotBBOnly = Opts.pgo_verify_hot_bfi;
1981 StringRef Msg;
1983
1984 unsigned BBNum = 0, BBMisMatchNum = 0, NonZeroBBNum = 0;
1985 for (auto &BBI : F) {
1986 PGOUseBBInfo *BBInfo = Func.findBBInfo(&BBI);
1987 if (!BBInfo)
1988 continue;
1989
1990 uint64_t CountValue = BBInfo->Count.value_or(CountValue);
1991 uint64_t BFICountValue = 0;
1992
1993 BBNum++;
1994 if (CountValue)
1995 NonZeroBBNum++;
1996 auto BFICount = NBFI.getBlockProfileCount(&BBI);
1997 if (BFICount)
1998 BFICountValue = *BFICount;
1999
2000 if (HotBBOnly) {
2001 bool rawIsHot = CountValue >= HotCountThreshold;
2002 bool BFIIsHot = BFICountValue >= HotCountThreshold;
2003 bool rawIsCold = CountValue <= ColdCountThreshold;
2004 bool ShowCount = false;
2005 if (rawIsHot && !BFIIsHot) {
2006 Msg = "raw-Hot to BFI-nonHot";
2007 ShowCount = true;
2008 } else if (rawIsCold && BFIIsHot) {
2009 Msg = "raw-Cold to BFI-Hot";
2010 ShowCount = true;
2011 }
2012 if (!ShowCount)
2013 continue;
2014 } else {
2015 if ((CountValue < Opts.pgo_verify_bfi_cutoff) &&
2016 (BFICountValue < Opts.pgo_verify_bfi_cutoff))
2017 continue;
2018 uint64_t Diff = (BFICountValue >= CountValue)
2019 ? BFICountValue - CountValue
2020 : CountValue - BFICountValue;
2021 if (Diff <= CountValue / 100 * Opts.pgo_verify_bfi_ratio)
2022 continue;
2023 }
2024 BBMisMatchNum++;
2025
2026 ORE.emit([&]() {
2028 F.getSubprogram(), &BBI);
2029 Remark << "BB " << ore::NV("Block", BBI.getName())
2030 << " Count=" << ore::NV("Count", CountValue)
2031 << " BFI_Count=" << ore::NV("Count", BFICountValue);
2032 if (!Msg.empty())
2033 Remark << " (" << Msg << ")";
2034 return Remark;
2035 });
2036 }
2037 if (BBMisMatchNum)
2038 ORE.emit([&]() {
2039 return OptimizationRemarkAnalysis(DEBUG_TYPE, "bfi-verify",
2040 F.getSubprogram(), &F.getEntryBlock())
2041 << "In Func " << ore::NV("Function", F.getName())
2042 << ": Num_of_BB=" << ore::NV("Count", BBNum)
2043 << ", Num_of_non_zerovalue_BB=" << ore::NV("Count", NonZeroBBNum)
2044 << ", Num_of_mis_matching_BB=" << ore::NV("Count", BBMisMatchNum);
2045 });
2046}
2047
2049 const InstrumentationOptions &Opts, Module &M, StringRef ProfileFileName,
2050 StringRef ProfileRemappingFileName, vfs::FileSystem &FS,
2051 function_ref<TargetLibraryInfo &(Function &)> LookupTLI,
2054 function_ref<LoopInfo *(Function &)> LookupLI, ProfileSummaryInfo *PSI,
2055 bool IsCS) {
2056 LLVM_DEBUG(dbgs() << "Read in profile counters: ");
2057 auto &Ctx = M.getContext();
2058 // Read the counter array from file.
2059 auto ReaderOrErr = IndexedInstrProfReader::create(ProfileFileName, FS,
2060 ProfileRemappingFileName);
2061 if (Error E = ReaderOrErr.takeError()) {
2062 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
2063 Ctx.diagnose(
2064 DiagnosticInfoPGOProfile(ProfileFileName.data(), EI.message()));
2065 });
2066 return false;
2067 }
2068
2069 std::unique_ptr<IndexedInstrProfReader> PGOReader =
2070 std::move(ReaderOrErr.get());
2071 if (!PGOReader) {
2072 Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),
2073 StringRef("Cannot get PGOReader")));
2074 return false;
2075 }
2076 if (!PGOReader->hasCSIRLevelProfile() && IsCS)
2077 return false;
2078
2079 // TODO: might need to change the warning once the clang option is finalized.
2080 if (!PGOReader->isIRLevelProfile()) {
2081 Ctx.diagnose(DiagnosticInfoPGOProfile(
2082 ProfileFileName.data(), "Not an IR level instrumentation profile"));
2083 return false;
2084 }
2085 if (PGOReader->functionEntryOnly()) {
2086 Ctx.diagnose(DiagnosticInfoPGOProfile(
2087 ProfileFileName.data(),
2088 "Function entry profiles are not yet supported for optimization"));
2089 return false;
2090 }
2091
2092 // Add the profile summary (read from the header of the indexed summary) here
2093 // so that we can use it below when reading counters (which checks if the
2094 // function should be marked with a cold or inlinehint attribute).
2095 M.setProfileSummary(PGOReader->getSummary(IsCS).getMD(M.getContext()),
2098 PSI->refresh();
2099
2100 std::unordered_multimap<Comdat *, GlobalValue *> ComdatMembers;
2101 collectComdatMembers(Opts, M, ComdatMembers);
2102 std::vector<Function *> HotFunctions;
2103 std::vector<Function *> ColdFunctions;
2104
2105 // If the profile marked as always instrument the entry BB, do the
2106 // same. Note this can be overwritten by the internal option in CFGMST.h
2107 bool InstrumentFuncEntry =
2108 valueOr(Opts.pgo_instrument_entry, PGOReader->instrEntryBBEnabled());
2109 bool InstrumentLoopEntries = valueOr(Opts.pgo_instrument_loop_entries,
2110 PGOReader->instrLoopEntriesEnabled());
2111
2112 bool HasSingleByteCoverage = PGOReader->hasSingleByteCoverage();
2113 for (auto &F : M) {
2114 if (skipPGOUse(Opts, F))
2115 continue;
2116 TargetLibraryInfo &TLI = LookupTLI(F);
2117 BranchProbabilityInfo *BPI = LookupBPI(F);
2118 BlockFrequencyInfo *BFI = LookupBFI(F);
2119 LoopInfo *LI = LookupLI(F);
2120 if (!HasSingleByteCoverage) {
2121 // Split indirectbr critical edges here before computing the MST rather
2122 // than later in getInstrBB() to avoid invalidating it.
2123 SplitIndirectBrCriticalEdges(F, /*IgnoreBlocksWithoutPHI=*/false, BPI,
2124 BFI);
2125 }
2126 PGOUseFunc Func(Opts, F, &M, TLI, ComdatMembers, BPI, BFI, LI, PSI, IsCS,
2127 InstrumentFuncEntry, InstrumentLoopEntries,
2128 HasSingleByteCoverage);
2129 if (!Func.getRecord(PGOReader.get()))
2130 continue;
2131 if (HasSingleByteCoverage) {
2132 Func.populateCoverage();
2133 continue;
2134 }
2135 // When PseudoKind is set to a value other than InstrProfRecord::NotPseudo,
2136 // it means the profile for the function is unrepresentative and this
2137 // function is actually hot / warm. We will reset the function hot / cold
2138 // attribute and drop all the profile counters.
2140 bool AllZeros = false;
2141 if (!Func.readCounters(AllZeros, PseudoKind))
2142 continue;
2143 if (AllZeros) {
2144 F.setEntryCount(0);
2145 if (Func.getProgramMaxCount() != 0)
2146 ColdFunctions.push_back(&F);
2147 continue;
2148 }
2149 if (PseudoKind != InstrProfRecord::NotPseudo) {
2150 // Clear function attribute cold.
2151 if (F.hasFnAttribute(Attribute::Cold))
2152 F.removeFnAttr(Attribute::Cold);
2153 // Set function attribute as hot.
2154 if (PseudoKind == InstrProfRecord::PseudoHot)
2155 F.addFnAttr(Attribute::Hot);
2156 continue;
2157 }
2158 Func.populateCounters();
2159 Func.setBranchWeights();
2160 Func.annotateValueSites();
2161 Func.annotateIrrLoopHeaderWeights();
2162 Func.setBlockUniformityAttribute();
2163 PGOUseFunc::FuncFreqAttr FreqAttr = Func.getFuncFreqAttr();
2164 if (FreqAttr == PGOUseFunc::FFA_Cold)
2165 ColdFunctions.push_back(&F);
2166 else if (FreqAttr == PGOUseFunc::FFA_Hot)
2167 HotFunctions.push_back(&F);
2168 PGOViewCountsType ViewCounts = getPGOViewCounts(F.getContext());
2169 StringRef ViewFuncName = getViewBlockFreqFuncName(F.getContext());
2170 if (ViewCounts != PGOViewCountsType::None &&
2171 (ViewFuncName.empty() || F.getName() == ViewFuncName)) {
2172 CycleInfo CI;
2173 CI.compute(F);
2174 std::unique_ptr<BranchProbabilityInfo> NewBPI =
2175 std::make_unique<BranchProbabilityInfo>(F, CI);
2176 std::unique_ptr<BlockFrequencyInfo> NewBFI =
2177 std::make_unique<BlockFrequencyInfo>(F, *NewBPI, CI);
2178 if (ViewCounts == PGOViewCountsType::Graph)
2179 NewBFI->view();
2180 else if (ViewCounts == PGOViewCountsType::Text) {
2181 dbgs() << "pgo-view-counts: " << Func.getFunc().getName() << "\n";
2182 NewBFI->print(dbgs());
2183 }
2184 }
2185 if (Opts.pgo_view_raw_counts != PGOViewCountsType::None &&
2186 (ViewFuncName.empty() || F.getName() == ViewFuncName)) {
2187 if (Opts.pgo_view_raw_counts == PGOViewCountsType::Graph)
2188 if (ViewFuncName.empty())
2189 WriteGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
2190 else
2191 ViewGraph(&Func, Twine("PGORawCounts_") + Func.getFunc().getName());
2192 else if (Opts.pgo_view_raw_counts == PGOViewCountsType::Text) {
2193 dbgs() << "pgo-view-raw-counts: " << Func.getFunc().getName() << "\n";
2194 Func.dumpInfo();
2195 }
2196 }
2197
2198 if (Opts.pgo_verify_bfi || Opts.pgo_verify_hot_bfi ||
2199 Opts.pgo_fix_entry_count) {
2200 CycleInfo CI;
2201 CI.compute(F);
2202 BranchProbabilityInfo NBPI(F, CI);
2203
2204 // Fix func entry count.
2205 if (Opts.pgo_fix_entry_count)
2206 fixFuncEntryCount(Func, CI, NBPI);
2207
2208 // Verify BlockFrequency information.
2209 uint64_t HotCountThreshold = 0, ColdCountThreshold = 0;
2210 if (Opts.pgo_verify_hot_bfi) {
2211 HotCountThreshold = PSI->getOrCompHotCountThreshold();
2213 }
2214 verifyFuncBFI(Opts, Func, CI, NBPI, HotCountThreshold,
2216 }
2217 }
2218
2219 // Set function hotness attribute from the profile.
2220 // We have to apply these attributes at the end because their presence
2221 // can affect the BranchProbabilityInfo of any callers, resulting in an
2222 // inconsistent MST between prof-gen and prof-use.
2223 for (auto &F : HotFunctions) {
2224 F->addFnAttr(Attribute::InlineHint);
2225 LLVM_DEBUG(dbgs() << "Set inline attribute to function: " << F->getName()
2226 << "\n");
2227 }
2228 for (auto &F : ColdFunctions) {
2229 // Only set when there is no Attribute::Hot set by the user. For Hot
2230 // attribute, user's annotation has the precedence over the profile.
2231 if (F->hasFnAttribute(Attribute::Hot)) {
2232 auto &Ctx = M.getContext();
2233 std::string Msg = std::string("Function ") + F->getName().str() +
2234 std::string(" is annotated as a hot function but"
2235 " the profile is cold");
2236 Ctx.diagnose(
2237 DiagnosticInfoPGOProfile(M.getName().data(), Msg, DS_Warning));
2238 continue;
2239 }
2240 F->addFnAttr(Attribute::Cold);
2241 LLVM_DEBUG(dbgs() << "Set cold attribute to function: " << F->getName()
2242 << "\n");
2243 }
2244 return true;
2245}
2246
2248 std::string Filename, std::string RemappingFilename, bool IsCS,
2250 : ProfileFileName(std::move(Filename)),
2251 ProfileRemappingFileName(std::move(RemappingFilename)), IsCS(IsCS),
2252 FS(std::move(VFS)) {
2253 if (!FS)
2255}
2256
2259
2260 auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
2261 auto LookupTLI = [&FAM](Function &F) -> TargetLibraryInfo & {
2262 return FAM.getResult<TargetLibraryAnalysis>(F);
2263 };
2264 auto LookupBPI = [&FAM](Function &F) {
2265 return &FAM.getResult<BranchProbabilityAnalysis>(F);
2266 };
2267 auto LookupBFI = [&FAM](Function &F) {
2268 return &FAM.getResult<BlockFrequencyAnalysis>(F);
2269 };
2270 auto LookupLI = [&FAM](Function &F) {
2271 return &FAM.getResult<LoopAnalysis>(F);
2272 };
2273
2274 auto *PSI = &MAM.getResult<ProfileSummaryAnalysis>(M);
2275 const InstrumentationOptions &Opts = getInstrumentationOptions(M);
2276 StringRef ProfileFile = ProfileFileName;
2277 if (!Opts.pgo_test_profile_file.empty())
2278 ProfileFile = Opts.pgo_test_profile_file;
2279 StringRef RemappingFile = ProfileRemappingFileName;
2280 if (!Opts.pgo_test_profile_remapping_file.empty())
2281 RemappingFile = Opts.pgo_test_profile_remapping_file;
2282 if (!annotateAllFunctions(Opts, M, ProfileFile, RemappingFile, *FS, LookupTLI,
2283 LookupBPI, LookupBFI, LookupLI, PSI, IsCS))
2284 return PreservedAnalyses::all();
2285
2286 return PreservedAnalyses::none();
2287}
2288
2289static std::string getSimpleNodeName(const BasicBlock *Node) {
2290 if (!Node->getName().empty())
2291 return Node->getName().str();
2292
2293 std::string SimpleNodeName;
2294 raw_string_ostream OS(SimpleNodeName);
2295 Node->printAsOperand(OS, false);
2296 return SimpleNodeName;
2297}
2298
2300 uint64_t MaxCount) {
2301 auto Weights = downscaleWeights(EdgeCounts, MaxCount);
2302
2303 LLVM_DEBUG(dbgs() << "Weight is: "; for (const auto &W : Weights) {
2304 dbgs() << W << " ";
2305 } dbgs() << "\n");
2306
2307 misexpect::checkExpectAnnotations(*TI, Weights, /*IsFrontend=*/false);
2308
2309 setBranchWeights(*TI, Weights, /*IsExpected=*/false);
2310
2311 const InstrumentationOptions &Opts =
2313 if (Opts.pgo_emit_branch_prob) {
2314 std::string BrCondStr = getBranchCondString(TI);
2315 if (BrCondStr.empty())
2316 return;
2317
2318 uint64_t WSum =
2319 std::accumulate(Weights.begin(), Weights.end(), (uint64_t)0,
2320 [](uint64_t w1, uint64_t w2) { return w1 + w2; });
2321 uint64_t TotalCount =
2322 std::accumulate(EdgeCounts.begin(), EdgeCounts.end(), (uint64_t)0,
2323 [](uint64_t c1, uint64_t c2) { return c1 + c2; });
2324 uint64_t Scale = calculateCountScale(WSum);
2325 BranchProbability BP(scaleBranchCount(Weights[0], Scale),
2326 scaleBranchCount(WSum, Scale));
2327 std::string BranchProbStr;
2328 raw_string_ostream OS(BranchProbStr);
2329 OS << BP;
2330 OS << " (total count : " << TotalCount << ")";
2331 Function *F = TI->getParent()->getParent();
2333 ORE.emit([&]() {
2334 return OptimizationRemark(DEBUG_TYPE, "pgo-instrumentation", TI)
2335 << BrCondStr << " is true with probability : " << BranchProbStr;
2336 });
2337 }
2338}
2339
2340namespace llvm {
2341
2343 MDBuilder MDB(M->getContext());
2344 TI->setMetadata(llvm::LLVMContext::MD_irr_loop,
2346}
2347
2348template <> struct GraphTraits<PGOUseFunc *> {
2349 using NodeRef = const BasicBlock *;
2352
2353 static NodeRef getEntryNode(const PGOUseFunc *G) {
2354 return &G->getFunc().front();
2355 }
2356
2358 return succ_begin(N);
2359 }
2360
2361 static ChildIteratorType child_end(const NodeRef N) { return succ_end(N); }
2362
2363 static nodes_iterator nodes_begin(const PGOUseFunc *G) {
2364 return nodes_iterator(G->getFunc().begin());
2365 }
2366
2367 static nodes_iterator nodes_end(const PGOUseFunc *G) {
2368 return nodes_iterator(G->getFunc().end());
2369 }
2370};
2371
2372template <> struct DOTGraphTraits<PGOUseFunc *> : DefaultDOTGraphTraits {
2373 explicit DOTGraphTraits(bool isSimple = false)
2375
2376 static std::string getGraphName(const PGOUseFunc *G) {
2377 return std::string(G->getFunc().getName());
2378 }
2379
2380 std::string getNodeLabel(const BasicBlock *Node, const PGOUseFunc *Graph) {
2381 std::string Result;
2382 raw_string_ostream OS(Result);
2383
2384 OS << getSimpleNodeName(Node) << ":\\l";
2385 PGOUseBBInfo *BI = Graph->findBBInfo(Node);
2386 OS << "Count : ";
2387 if (BI && BI->Count)
2388 OS << *BI->Count << "\\l";
2389 else
2390 OS << "Unknown\\l";
2391
2392 const InstrumentationOptions &Opts =
2393 getInstrumentationOptions(*Node->getParent());
2394 if (!Opts.pgo_instr_select)
2395 return Result;
2396
2397 for (const Instruction &I : *Node) {
2398 if (!isa<SelectInst>(&I))
2399 continue;
2400 // Display scaled counts for SELECT instruction:
2401 OS << "SELECT : { T = ";
2402 uint64_t TC, FC;
2403 bool HasProf = extractBranchWeights(I, TC, FC);
2404 if (!HasProf)
2405 OS << "Unknown, F = Unknown }\\l";
2406 else
2407 OS << TC << ", F = " << FC << " }\\l";
2408 }
2409 return Result;
2410 }
2411};
2412
2413} // end namespace llvm
const TargetLowering & TLI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
This file implements a class to represent arbitrary precision integral constant values and operations...
Function Alias Analysis false
This file contains the simple types necessary to represent the attributes associated with functions a...
static cl::opt< unsigned > ColdCountThreshold("mfs-count-threshold", cl::desc("Minimum number of times a block must be executed to be retained."), cl::init(1), cl::Hidden)
This file finds the minimum set of blocks on a CFG that must be instrumented to infer execution cover...
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file declares the LLVM IR specialization of the GenericCycle templates.
post inline ee instrument
static BasicBlock * getInstrBB(CFGMST< Edge, BBInfo > &MST, Edge &E, const DenseSet< const BasicBlock * > &ExecBlocks)
#define DEBUG_TYPE
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
Interface to identify indirect call promotion candidates.
#define INSTR_PROF_QUOTE(x)
#define VARIANT_MASK_CSIR_PROF
#define VARIANT_MASK_DBG_CORRELATE
#define INSTR_PROF_RAW_VERSION
#define INSTR_PROF_RAW_VERSION_VAR
#define VARIANT_MASK_TEMPORAL_PROF
#define VARIANT_MASK_IR_PROF
#define VARIANT_MASK_BYTE_COVERAGE
#define VARIANT_MASK_INSTR_ENTRY
#define VARIANT_MASK_FUNCTION_ENTRY_ONLY
#define VARIANT_MASK_INSTR_LOOP_ENTRIES
SmallVector< MachineOperand, 4 > Cond
if(!TBB||Cond.size()< 1) return false
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
Machine Check Debug Module
static constexpr StringLiteral Filename
static void annotateFunctionWithHashMismatch(Function &F, LLVMContext &ctx)
static bool instrumentAllFunctions(const InstrumentationOptions &Opts, Module &M, function_ref< TargetLibraryInfo &(Function &)> LookupTLI, function_ref< BranchProbabilityInfo *(Function &)> LookupBPI, function_ref< BlockFrequencyInfo *(Function &)> LookupBFI, function_ref< LoopInfo *(Function &)> LookupLI, PGOInstrumentationType InstrumentationType)
static bool skipPGOGen(const InstrumentationOptions &Opts, const Function &F)
static void fixFuncEntryCount(PGOUseFunc &Func, CycleInfo &CI, BranchProbabilityInfo &NBPI)
static void populateEHOperandBundle(VPCandidateInfo &Cand, DenseMap< BasicBlock *, ColorVector > &BlockColors, SmallVectorImpl< OperandBundleDef > &OpBundles)
static void collectComdatMembers(const InstrumentationOptions &Opts, Module &M, std::unordered_multimap< Comdat *, GlobalValue * > &ComdatMembers)
static void setupBBInfoEdges(const FuncPGOInstrumentation< PGOUseEdge, PGOUseBBInfo > &FuncInfo)
Set up InEdges/OutEdges for all BBs in the MST.
ValueProfileCollector::CandidateInfo VPCandidateInfo
static bool skipPGOUse(const InstrumentationOptions &Opts, const Function &F)
static uint64_t sumEdgeCount(const ArrayRef< PGOUseEdge * > Edges)
static std::string getSimpleNodeName(const BasicBlock *Node)
static bool isIndirectBrTarget(BasicBlock *BB)
static bool annotateAllFunctions(const InstrumentationOptions &Opts, Module &M, StringRef ProfileFileName, StringRef ProfileRemappingFileName, vfs::FileSystem &FS, function_ref< TargetLibraryInfo &(Function &)> LookupTLI, function_ref< BranchProbabilityInfo *(Function &)> LookupBPI, function_ref< BlockFrequencyInfo *(Function &)> LookupBFI, function_ref< LoopInfo *(Function &)> LookupLI, ProfileSummaryInfo *PSI, bool IsCS)
static GlobalVariable * createIRLevelProfileFlagVar(const InstrumentationOptions &Opts, Module &M, PGOInstrumentationType InstrumentationType)
static void verifyFuncBFI(const InstrumentationOptions &Opts, PGOUseFunc &Func, CycleInfo &CI, BranchProbabilityInfo &NBPI, uint64_t HotCountThreshold, uint64_t ColdCountThreshold)
static bool canRenameComdat(const InstrumentationOptions &Opts, Function &F, std::unordered_multimap< Comdat *, GlobalValue * > &ComdatMembers)
static std::string getBranchCondString(Instruction *TI)
static uint32_t getMaxNumAnnotations(const InstrumentationOptions &Opts, const LLVMContext &C, InstrProfValueKind ValueProfKind)
static const char * ValueProfKindDescr[]
This file provides the interface for IR based instrumentation passes ( (profile-gen,...
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
This file contains the declarations for profiling metadata utility functions.
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
const char * Msg
static void visit(BasicBlock &Start, std::function< bool(BasicBlock *)> op)
std::pair< BasicBlock *, BasicBlock * > Edge
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
StringSet - A set-like wrapper for the StringMap.
#define LLVM_DEBUG(...)
Definition Debug.h:119
Defines the virtual file system interface vfs::FileSystem.
Value * RHS
void printAsOperand(OutputBuffer &OB, Prec P=Prec::Default, bool StrictlyWorse=false) const
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:379
static constexpr const fltSemantics & IEEEdouble()
Definition APFloat.h:305
static APFloat getZero(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Zero.
Definition APFloat.h:1216
Class for arbitrary precision integers.
Definition APInt.h:78
This templated class represents "all analyses that operate over <aparticular IR unit>" (e....
Definition Analysis.h:50
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
LLVM Basic Block Representation.
Definition BasicBlock.h:61
iterator end()
Definition BasicBlock.h:452
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:169
LLVM_ABI const_iterator getFirstNonPHIOrAlloca() const
Returns an iterator to the first instruction in this block that is not a PHINode, a static alloca,...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:236
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
LLVM_ABI bool isIrrLoopHeader(const BasicBlock *BB)
Returns true if BB is an irreducible loop header block.
LLVM_ABI std::optional< uint64_t > getBlockProfileCount(const BasicBlock *BB) const
Returns the estimated profile count of BB.
Analysis pass which computes BranchProbabilityInfo.
Analysis providing branch probability information.
Edge & addEdge(BasicBlock *Src, BasicBlock *Dest, uint64_t W)
Definition CFGMST.h:329
const std::vector< std::unique_ptr< Edge > > & allEdges() const
Definition CFGMST.h:366
size_t numEdges() const
Definition CFGMST.h:372
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
LLVM_ABI StringRef getName() const
Definition Comdat.cpp:28
void setSelectionKind(SelectionKind Val)
Definition Comdat.h:48
SelectionKind getSelectionKind() const
Definition Comdat.h:47
Conditional Branch instruction.
Value * getCondition() const
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:549
static LLVM_ABI Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
This is the shared class of boolean and integer constants.
Definition Constants.h:87
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
Definition Constants.h:231
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
Definition Constants.h:225
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
static LLVM_ABI Constant * getIntegerValue(Type *Ty, const APInt &V)
Return the value for an integer or pointer constant, or a vector thereof, with the given scalar value...
bool empty() const
Definition DenseMap.h:716
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
Diagnostic information for the PGO profiler.
Base class for error info classes.
Definition Error.h:44
virtual std::string message() const
Return the error message as a string.
Definition Error.h:52
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
void compute(FunctionT &F)
Compute the cycle info for a function.
static LLVM_ABI GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
Definition Globals.cpp:695
@ HiddenVisibility
The GV is hidden.
Definition GlobalValue.h:69
@ ProtectedVisibility
The GV is protected.
Definition GlobalValue.h:70
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition GlobalValue.h:57
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition GlobalValue.h:54
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:56
This instruction compares its operands according to the predicate given to the constructor.
static Expected< std::unique_ptr< IndexedInstrProfReader > > create(const Twine &Path, vfs::FileSystem &FS, const Twine &RemappingPath="")
Factory method to create an indexed reader.
uint64_t getMaximumFunctionCount(bool UseCS)
Return the maximum of all known function counts.
Expected< NamedInstrProfRecord > getInstrProfRecord(StringRef FuncName, uint64_t FuncHash, StringRef DeprecatedFuncName="", uint64_t *MismatchedFuncSum=nullptr)
Return the NamedInstrProfRecord associated with FuncName and FuncHash.
Base class for instruction visitors.
Definition InstVisitor.h:78
static bool canInstrumentCallsite(const CallBase &CB)
instrprof_error get() const
Definition InstrProf.h:458
std::string message() const override
Return the error message as a string.
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
A smart pointer to a reference-counted object that inherits from RefCountedBase or ThreadSafeRefCount...
uint32_t getCRC() const
Definition CRC.h:77
LLVM_ABI void update(ArrayRef< uint8_t > Data)
Definition CRC.cpp:103
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:598
LLVM_ABI MDString * createString(StringRef Str)
Return the given string as metadata.
Definition MDBuilder.cpp:21
LLVM_ABI MDNode * createIrrLoopHeaderWeight(uint64_t Weight)
Return metadata containing an irreducible loop header weight.
Metadata node.
Definition Metadata.h:1087
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1588
Tuple of metadata.
Definition Metadata.h:1505
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1534
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
Diagnostic information for optimization analysis remarks.
The optimization diagnostic interface.
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Diagnostic information for applied optimization remarks.
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
LLVM_ABI PGOInstrumentationUse(std::string Filename="", std::string RemappingFilename="", bool IsCS=false, IntrusiveRefCntPtr< vfs::FileSystem > FS=nullptr)
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
Analysis providing profile information.
LLVM_ABI uint64_t getOrCompColdCountThreshold() const
Returns ColdCountThreshold if set.
LLVM_ABI bool isColdCount(uint64_t C) const
Returns true if count C is considered cold.
LLVM_ABI void refresh(std::unique_ptr< ProfileSummary > &&Other=nullptr)
If a summary is provided as argument, use that.
LLVM_ABI bool isHotCount(uint64_t C) const
Returns true if count C is considered hot.
LLVM_ABI uint64_t getOrCompHotCountThreshold() const
Returns HotCountThreshold if set.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
EltTy front() const
unsigned size() const
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
Definition Twine.cpp:17
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:295
LLVM_ABI void print(raw_ostream &O, bool IsForDebug=false, bool NoDetails=false) const
Print the current type.
Value * getOperand(unsigned i) const
Definition User.h:207
std::vector< CandidateInfo > get(InstrProfValueKind Kind) const
returns a list of value profiling candidates of the given kind
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
A raw_ostream that writes to an std::string.
The virtual file system interface.
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
initializer< Ty > init(const Ty &Val)
uint64_t getFuncHash(const FuncRecordTy *Record)
Return the structural hash associated with the function.
LLVM_ABI void checkExpectAnnotations(const Instruction &I, ArrayRef< uint32_t > ExistingWeights, bool IsFrontend)
checkExpectAnnotations - compares PGO counters to the thresholds used for llvm.expect and warns if th...
DiagnosticInfoOptimizationBase::Argument NV
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
void write64le(void *P, uint64_t V)
Definition Endian.h:458
LLVM_ABI IntrusiveRefCntPtr< FileSystem > getRealFileSystem()
Gets an vfs::FileSystem for the 'real' file system, as seen by the operating system.
This is an optimization pass for GlobalISel generic memory operations.
const InstrumentationOptions & getInstrumentationOptions(const LLVMContext &C)
LLVM_ABI void setIrrLoopHeaderMetadata(Module *M, Instruction *TI, uint64_t Count)
LLVM_ABI void setProfMetadata(Instruction *TI, ArrayRef< uint64_t > EdgeCounts, uint64_t MaxCount)
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
LLVM_ABI std::string getPGOFuncName(const Function &F, bool InLTO=false, uint64_t Version=INSTR_PROF_INDEX_VERSION)
Please use getIRPGOObjectName for LLVM IR instrumentation.
LLVM_ABI unsigned GetSuccessorNumber(const BasicBlock *BB, const BasicBlock *Succ)
Search for the specified successor of basic block BB and return its position in the terminator instru...
Definition CFG.cpp:90
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
RelativeUniformCounterPtr ValuesPtrExpr NumValueSites[IPVK_Last+1]
Definition InstrProf.h:95
auto successors(const MachineBasicBlock *BB)
LLVM_ABI void createProfileSamplingVar(Module &M)
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
Definition Error.h:1013
constexpr from_range_t from_range
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI bool SplitIndirectBrCriticalEdges(Function &F, bool IgnoreBlocksWithoutPHI, BranchProbabilityInfo *BPI=nullptr, BlockFrequencyInfo *BFI=nullptr, DomTreeUpdater *DTU=nullptr)
LLVM_ABI DenseMap< BasicBlock *, ColorVector > colorEHFunclets(Function &F)
If an EH funclet personality is in use (see isFuncletEHPersonality), this will recompute which blocks...
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
LLVM_ABI std::string getIRPGOObjectName(const GlobalObject &GO, bool InLTO=false)
raw_ostream & WriteGraph(raw_ostream &O, const GraphType &G, bool ShortNames=false, const Twine &Title="")
cl::opt< bool > EnableVTableProfileUse("enable-vtable-profile-use", cl::init(false), cl::desc("If ThinLTO and WPD is enabled and this option is true, vtable " "profiles will be used by ICP pass for more efficient indirect " "call sequence. If false, type profiles won't be used."))
bool isScopedEHPersonality(EHPersonality Pers)
Returns true if this personality uses scope-style EH IR instructions: catchswitch,...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI void setBranchWeights(Instruction &I, ArrayRef< uint32_t > Weights, bool IsExpected, bool ElideAllZero=false)
Create a new branch_weights metadata node and add or overwrite a prof metadata reference to instructi...
FuncHash
Definition InstrProf.h:78
LLVM_ABI GlobalVariable * createPGOFuncNameVar(Function &F, StringRef PGOFuncName)
Create and return the global variable for function name used in PGO instrumentation.
LLVM_ABI void annotateValueSite(Module &M, Instruction &Inst, const InstrProfRecord &InstrProfR, InstrProfValueKind ValueKind, uint32_t SiteIndx, uint32_t MaxMDCount=3)
Get the value profile data for value site SiteIdx from InstrProfR and annotate the instruction Inst w...
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI PGOViewCountsType getPGOViewCounts(const LLVMContext &C)
Return -pgo-view-counts.
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
cl::opt< bool > NoPGOWarnMismatch
RNSuccIterator< NodeRef, BlockT, RegionT > succ_begin(NodeRef Node)
InstrProfValueKind
Definition InstrProf.h:323
RNSuccIterator< NodeRef, BlockT, RegionT > succ_end(NodeRef Node)
OperandBundleDefT< Value * > OperandBundleDef
Definition AutoUpgrade.h:35
LLVM_ABI void appendToCompilerUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.compiler.used list.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
LLVM_ABI BasicBlock * SplitCriticalEdge(Instruction *TI, unsigned SuccNum, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions(), const Twine &BBName="")
If this edge is a critical edge, insert a new node to split the critical edge.
void ViewGraph(const GraphType &G, const Twine &Name, bool ShortNames=false, const Twine &Title="", GraphProgram::Name Program=GraphProgram::DOT)
ViewGraph - Emit a dot graph, run 'dot', run gv on the postscript file, then cleanup.
LLVM_ABI bool isCriticalEdge(const Instruction *TI, unsigned SuccNum, bool AllowIdenticalEdges=false)
Return true if the specified edge is a critical edge.
Definition CFG.cpp:106
LLVM_ABI bool canRenameComdatFunc(const Function &F, bool CheckAddressTaken=false)
Check if we can safely rename this Comdat function.
LLVM_ABI void createProfileFileNameVar(Module &M, StringRef InstrProfileOutput)
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
TinyPtrVector< BasicBlock * > ColorVector
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto predecessors(const MachineBasicBlock *BB)
Instruction::const_succ_iterator const_succ_iterator
Definition CFG.h:127
uint32_t scaleBranchCount(uint64_t Count, uint64_t Scale)
Scale an individual branch count.
constexpr bool valueOr(BoolOrDefault X, bool Default)
LLVM_ABI unsigned getMaxNumVTableAnnotations(const LLVMContext &C)
Return -icp-max-num-vtables.
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
LLVM_ABI StringRef getViewBlockFreqFuncName(const LLVMContext &C)
Return -view-bfi-func-name.
uint64_t calculateCountScale(uint64_t MaxCount)
Calculate what to divide by to scale counts.
LLVM_ABI SmallVector< uint32_t > downscaleWeights(ArrayRef< uint64_t > Weights, std::optional< uint64_t > KnownMaxCount=std::nullopt)
downscale the given weights preserving the ratio.
LLVM_ABI bool isGPUProfTarget(const Module &M)
Determines whether module targets a GPU eligable for PGO instrumentation.
cl::opt< bool > EnableVTableValueProfiling("enable-vtable-value-profiling", cl::init(false), cl::desc("If true, the virtual table address will be instrumented to know " "the types of a C++ pointer. The information is used in indirect " "call promotion to do selective vtable-based comparison."))
LLVM_ABI bool isPGOInstrumentColdFunctionOnly(const cl::LibraryOptionsContext &LibraryOptions)
Return the value of -pgo-instrument-cold-function-only in LibraryOptions.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
#define N
static std::string getGraphName(const PGOUseFunc *G)
std::string getNodeLabel(const BasicBlock *Node, const PGOUseFunc *Graph)
DefaultDOTGraphTraits(bool simple=false)
static ChildIteratorType child_end(const NodeRef N)
static NodeRef getEntryNode(const PGOUseFunc *G)
static ChildIteratorType child_begin(const NodeRef N)
static nodes_iterator nodes_end(const PGOUseFunc *G)
static nodes_iterator nodes_begin(const PGOUseFunc *G)
pointer_iterator< Function::const_iterator > nodes_iterator
bool isBlockUniform(unsigned BlockIdx) const
Check if a basic block is entered via a wave-uniform branch.
Definition InstrProf.h:952
std::vector< uint64_t > Counts
Definition InstrProf.h:907
CountPseudoKind getCountPseudoKind() const
Definition InstrProf.h:1035
uint32_t getNumValueSites(uint32_t ValueKind) const
Return the number of instrumented sites for ValueKind.
Definition InstrProf.h:1147
std::vector< uint8_t > UniformityBits
For AMDGPU offload profiling: 1 bit per basic block indicating whether the block is usually entered w...
Definition InstrProf.h:915
static void setCSFlagInHash(uint64_t &FuncHash)
Definition InstrProf.h:1128
static constexpr uint64_t FUNC_HASH_MASK
Definition InstrProf.h:1103