1 //===- SampleProfile.cpp - Incorporate sample profiles into the IR --------===//
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 the SampleProfileLoader transformation. This pass
10 // reads a profile file generated by a sampling profiler (e.g. Linux Perf -
11 // http://perf.wiki.kernel.org/) and generates IR metadata to reflect the
12 // profile information in the given profile.
13 //
14 // This pass generates branch weight annotations on the IR:
15 //
16 // - prof: Represents branch weights. This annotation is added to branches
17 // to indicate the weights of each edge coming out of the branch.
18 // The weight of each edge is the weight of the target block for
19 // that edge. The weight of a block B is computed as the maximum
20 // number of samples found in B.
21 //
22 //===----------------------------------------------------------------------===//
23
24 #include "llvm/Transforms/IPO/SampleProfile.h"
25 #include "llvm/ADT/ArrayRef.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/DenseSet.h"
28 #include "llvm/ADT/None.h"
29 #include "llvm/ADT/SCCIterator.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/SmallSet.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/ADT/StringMap.h"
35 #include "llvm/ADT/StringRef.h"
36 #include "llvm/ADT/Twine.h"
37 #include "llvm/Analysis/AssumptionCache.h"
38 #include "llvm/Analysis/CallGraph.h"
39 #include "llvm/Analysis/CallGraphSCCPass.h"
40 #include "llvm/Analysis/InlineAdvisor.h"
41 #include "llvm/Analysis/InlineCost.h"
42 #include "llvm/Analysis/LoopInfo.h"
43 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
44 #include "llvm/Analysis/PostDominators.h"
45 #include "llvm/Analysis/ProfileSummaryInfo.h"
46 #include "llvm/Analysis/TargetLibraryInfo.h"
47 #include "llvm/Analysis/TargetTransformInfo.h"
48 #include "llvm/IR/BasicBlock.h"
49 #include "llvm/IR/CFG.h"
50 #include "llvm/IR/DebugInfoMetadata.h"
51 #include "llvm/IR/DebugLoc.h"
52 #include "llvm/IR/DiagnosticInfo.h"
53 #include "llvm/IR/Dominators.h"
54 #include "llvm/IR/Function.h"
55 #include "llvm/IR/GlobalValue.h"
56 #include "llvm/IR/InstrTypes.h"
57 #include "llvm/IR/Instruction.h"
58 #include "llvm/IR/Instructions.h"
59 #include "llvm/IR/IntrinsicInst.h"
60 #include "llvm/IR/LLVMContext.h"
61 #include "llvm/IR/MDBuilder.h"
62 #include "llvm/IR/Module.h"
63 #include "llvm/IR/PassManager.h"
64 #include "llvm/IR/ValueSymbolTable.h"
65 #include "llvm/InitializePasses.h"
66 #include "llvm/Pass.h"
67 #include "llvm/ProfileData/InstrProf.h"
68 #include "llvm/ProfileData/SampleProf.h"
69 #include "llvm/ProfileData/SampleProfReader.h"
70 #include "llvm/Support/Casting.h"
71 #include "llvm/Support/CommandLine.h"
72 #include "llvm/Support/Debug.h"
73 #include "llvm/Support/ErrorHandling.h"
74 #include "llvm/Support/ErrorOr.h"
75 #include "llvm/Support/GenericDomTree.h"
76 #include "llvm/Support/raw_ostream.h"
77 #include "llvm/Transforms/IPO.h"
78 #include "llvm/Transforms/Instrumentation.h"
79 #include "llvm/Transforms/Utils/CallPromotionUtils.h"
80 #include "llvm/Transforms/Utils/Cloning.h"
81 #include "llvm/Transforms/Utils/MisExpect.h"
82 #include <algorithm>
83 #include <cassert>
84 #include <cstdint>
85 #include <functional>
86 #include <limits>
87 #include <map>
88 #include <memory>
89 #include <queue>
90 #include <string>
91 #include <system_error>
92 #include <utility>
93 #include <vector>
94
95 using namespace llvm;
96 using namespace sampleprof;
97 using ProfileCount = Function::ProfileCount;
98 #define DEBUG_TYPE "sample-profile"
99 #define CSINLINE_DEBUG DEBUG_TYPE "-inline"
100
101 STATISTIC(NumCSInlined,
102 "Number of functions inlined with context sensitive profile");
103 STATISTIC(NumCSNotInlined,
104 "Number of functions not inlined with context sensitive profile");
105
106 // Command line option to specify the file to read samples from. This is
107 // mainly used for debugging.
108 static cl::opt<std::string> SampleProfileFile(
109 "sample-profile-file", cl::init(""), cl::value_desc("filename"),
110 cl::desc("Profile file loaded by -sample-profile"), cl::Hidden);
111
112 // The named file contains a set of transformations that may have been applied
113 // to the symbol names between the program from which the sample data was
114 // collected and the current program's symbols.
115 static cl::opt<std::string> SampleProfileRemappingFile(
116 "sample-profile-remapping-file", cl::init(""), cl::value_desc("filename"),
117 cl::desc("Profile remapping file loaded by -sample-profile"), cl::Hidden);
118
119 static cl::opt<unsigned> SampleProfileMaxPropagateIterations(
120 "sample-profile-max-propagate-iterations", cl::init(100),
121 cl::desc("Maximum number of iterations to go through when propagating "
122 "sample block/edge weights through the CFG."));
123
124 static cl::opt<unsigned> SampleProfileRecordCoverage(
125 "sample-profile-check-record-coverage", cl::init(0), cl::value_desc("N"),
126 cl::desc("Emit a warning if less than N% of records in the input profile "
127 "are matched to the IR."));
128
129 static cl::opt<unsigned> SampleProfileSampleCoverage(
130 "sample-profile-check-sample-coverage", cl::init(0), cl::value_desc("N"),
131 cl::desc("Emit a warning if less than N% of samples in the input profile "
132 "are matched to the IR."));
133
134 static cl::opt<bool> NoWarnSampleUnused(
135 "no-warn-sample-unused", cl::init(false), cl::Hidden,
136 cl::desc("Use this option to turn off/on warnings about function with "
137 "samples but without debug information to use those samples. "));
138
139 static cl::opt<bool> ProfileSampleAccurate(
140 "profile-sample-accurate", cl::Hidden, cl::init(false),
141 cl::desc("If the sample profile is accurate, we will mark all un-sampled "
142 "callsite and function as having 0 samples. Otherwise, treat "
143 "un-sampled callsites and functions conservatively as unknown. "));
144
145 static cl::opt<bool> ProfileAccurateForSymsInList(
146 "profile-accurate-for-symsinlist", cl::Hidden, cl::ZeroOrMore,
147 cl::init(true),
148 cl::desc("For symbols in profile symbol list, regard their profiles to "
149 "be accurate. It may be overriden by profile-sample-accurate. "));
150
151 static cl::opt<bool> ProfileMergeInlinee(
152 "sample-profile-merge-inlinee", cl::Hidden, cl::init(true),
153 cl::desc("Merge past inlinee's profile to outline version if sample "
154 "profile loader decided not to inline a call site. It will "
155 "only be enabled when top-down order of profile loading is "
156 "enabled. "));
157
158 static cl::opt<bool> ProfileTopDownLoad(
159 "sample-profile-top-down-load", cl::Hidden, cl::init(true),
160 cl::desc("Do profile annotation and inlining for functions in top-down "
161 "order of call graph during sample profile loading. It only "
162 "works for new pass manager. "));
163
164 static cl::opt<bool> ProfileSizeInline(
165 "sample-profile-inline-size", cl::Hidden, cl::init(false),
166 cl::desc("Inline cold call sites in profile loader if it's beneficial "
167 "for code size."));
168
169 static cl::opt<int> SampleColdCallSiteThreshold(
170 "sample-profile-cold-inline-threshold", cl::Hidden, cl::init(45),
171 cl::desc("Threshold for inlining cold callsites"));
172
173 namespace {
174
175 using BlockWeightMap = DenseMap<const BasicBlock *, uint64_t>;
176 using EquivalenceClassMap = DenseMap<const BasicBlock *, const BasicBlock *>;
177 using Edge = std::pair<const BasicBlock *, const BasicBlock *>;
178 using EdgeWeightMap = DenseMap<Edge, uint64_t>;
179 using BlockEdgeMap =
180 DenseMap<const BasicBlock *, SmallVector<const BasicBlock *, 8>>;
181
182 class SampleProfileLoader;
183
184 class SampleCoverageTracker {
185 public:
SampleCoverageTracker(SampleProfileLoader & SPL)186 SampleCoverageTracker(SampleProfileLoader &SPL) : SPLoader(SPL){};
187
188 bool markSamplesUsed(const FunctionSamples *FS, uint32_t LineOffset,
189 uint32_t Discriminator, uint64_t Samples);
190 unsigned computeCoverage(unsigned Used, unsigned Total) const;
191 unsigned countUsedRecords(const FunctionSamples *FS,
192 ProfileSummaryInfo *PSI) const;
193 unsigned countBodyRecords(const FunctionSamples *FS,
194 ProfileSummaryInfo *PSI) const;
getTotalUsedSamples() const195 uint64_t getTotalUsedSamples() const { return TotalUsedSamples; }
196 uint64_t countBodySamples(const FunctionSamples *FS,
197 ProfileSummaryInfo *PSI) const;
198
clear()199 void clear() {
200 SampleCoverage.clear();
201 TotalUsedSamples = 0;
202 }
203
204 private:
205 using BodySampleCoverageMap = std::map<LineLocation, unsigned>;
206 using FunctionSamplesCoverageMap =
207 DenseMap<const FunctionSamples *, BodySampleCoverageMap>;
208
209 /// Coverage map for sampling records.
210 ///
211 /// This map keeps a record of sampling records that have been matched to
212 /// an IR instruction. This is used to detect some form of staleness in
213 /// profiles (see flag -sample-profile-check-coverage).
214 ///
215 /// Each entry in the map corresponds to a FunctionSamples instance. This is
216 /// another map that counts how many times the sample record at the
217 /// given location has been used.
218 FunctionSamplesCoverageMap SampleCoverage;
219
220 /// Number of samples used from the profile.
221 ///
222 /// When a sampling record is used for the first time, the samples from
223 /// that record are added to this accumulator. Coverage is later computed
224 /// based on the total number of samples available in this function and
225 /// its callsites.
226 ///
227 /// Note that this accumulator tracks samples used from a single function
228 /// and all the inlined callsites. Strictly, we should have a map of counters
229 /// keyed by FunctionSamples pointers, but these stats are cleared after
230 /// every function, so we just need to keep a single counter.
231 uint64_t TotalUsedSamples = 0;
232
233 SampleProfileLoader &SPLoader;
234 };
235
236 class GUIDToFuncNameMapper {
237 public:
GUIDToFuncNameMapper(Module & M,SampleProfileReader & Reader,DenseMap<uint64_t,StringRef> & GUIDToFuncNameMap)238 GUIDToFuncNameMapper(Module &M, SampleProfileReader &Reader,
239 DenseMap<uint64_t, StringRef> &GUIDToFuncNameMap)
240 : CurrentReader(Reader), CurrentModule(M),
241 CurrentGUIDToFuncNameMap(GUIDToFuncNameMap) {
242 if (!CurrentReader.useMD5())
243 return;
244
245 for (const auto &F : CurrentModule) {
246 StringRef OrigName = F.getName();
247 CurrentGUIDToFuncNameMap.insert(
248 {Function::getGUID(OrigName), OrigName});
249
250 // Local to global var promotion used by optimization like thinlto
251 // will rename the var and add suffix like ".llvm.xxx" to the
252 // original local name. In sample profile, the suffixes of function
253 // names are all stripped. Since it is possible that the mapper is
254 // built in post-thin-link phase and var promotion has been done,
255 // we need to add the substring of function name without the suffix
256 // into the GUIDToFuncNameMap.
257 StringRef CanonName = FunctionSamples::getCanonicalFnName(F);
258 if (CanonName != OrigName)
259 CurrentGUIDToFuncNameMap.insert(
260 {Function::getGUID(CanonName), CanonName});
261 }
262
263 // Update GUIDToFuncNameMap for each function including inlinees.
264 SetGUIDToFuncNameMapForAll(&CurrentGUIDToFuncNameMap);
265 }
266
~GUIDToFuncNameMapper()267 ~GUIDToFuncNameMapper() {
268 if (!CurrentReader.useMD5())
269 return;
270
271 CurrentGUIDToFuncNameMap.clear();
272
273 // Reset GUIDToFuncNameMap for of each function as they're no
274 // longer valid at this point.
275 SetGUIDToFuncNameMapForAll(nullptr);
276 }
277
278 private:
SetGUIDToFuncNameMapForAll(DenseMap<uint64_t,StringRef> * Map)279 void SetGUIDToFuncNameMapForAll(DenseMap<uint64_t, StringRef> *Map) {
280 std::queue<FunctionSamples *> FSToUpdate;
281 for (auto &IFS : CurrentReader.getProfiles()) {
282 FSToUpdate.push(&IFS.second);
283 }
284
285 while (!FSToUpdate.empty()) {
286 FunctionSamples *FS = FSToUpdate.front();
287 FSToUpdate.pop();
288 FS->GUIDToFuncNameMap = Map;
289 for (const auto &ICS : FS->getCallsiteSamples()) {
290 const FunctionSamplesMap &FSMap = ICS.second;
291 for (auto &IFS : FSMap) {
292 FunctionSamples &FS = const_cast<FunctionSamples &>(IFS.second);
293 FSToUpdate.push(&FS);
294 }
295 }
296 }
297 }
298
299 SampleProfileReader &CurrentReader;
300 Module &CurrentModule;
301 DenseMap<uint64_t, StringRef> &CurrentGUIDToFuncNameMap;
302 };
303
304 /// Sample profile pass.
305 ///
306 /// This pass reads profile data from the file specified by
307 /// -sample-profile-file and annotates every affected function with the
308 /// profile information found in that file.
309 class SampleProfileLoader {
310 public:
SampleProfileLoader(StringRef Name,StringRef RemapName,bool IsThinLTOPreLink,std::function<AssumptionCache & (Function &)> GetAssumptionCache,std::function<TargetTransformInfo & (Function &)> GetTargetTransformInfo,std::function<const TargetLibraryInfo & (Function &)> GetTLI)311 SampleProfileLoader(
312 StringRef Name, StringRef RemapName, bool IsThinLTOPreLink,
313 std::function<AssumptionCache &(Function &)> GetAssumptionCache,
314 std::function<TargetTransformInfo &(Function &)> GetTargetTransformInfo,
315 std::function<const TargetLibraryInfo &(Function &)> GetTLI)
316 : GetAC(std::move(GetAssumptionCache)),
317 GetTTI(std::move(GetTargetTransformInfo)), GetTLI(std::move(GetTLI)),
318 CoverageTracker(*this), Filename(std::string(Name)),
319 RemappingFilename(std::string(RemapName)),
320 IsThinLTOPreLink(IsThinLTOPreLink) {}
321
322 bool doInitialization(Module &M);
323 bool runOnModule(Module &M, ModuleAnalysisManager *AM,
324 ProfileSummaryInfo *_PSI, CallGraph *CG);
325
dump()326 void dump() { Reader->dump(); }
327
328 protected:
329 friend class SampleCoverageTracker;
330
331 bool runOnFunction(Function &F, ModuleAnalysisManager *AM);
332 unsigned getFunctionLoc(Function &F);
333 bool emitAnnotations(Function &F);
334 ErrorOr<uint64_t> getInstWeight(const Instruction &I);
335 ErrorOr<uint64_t> getBlockWeight(const BasicBlock *BB);
336 const FunctionSamples *findCalleeFunctionSamples(const CallBase &I) const;
337 std::vector<const FunctionSamples *>
338 findIndirectCallFunctionSamples(const Instruction &I, uint64_t &Sum) const;
339 mutable DenseMap<const DILocation *, const FunctionSamples *> DILocation2SampleMap;
340 const FunctionSamples *findFunctionSamples(const Instruction &I) const;
341 bool inlineCallInstruction(CallBase &CB);
342 bool inlineHotFunctions(Function &F,
343 DenseSet<GlobalValue::GUID> &InlinedGUIDs);
344 // Inline cold/small functions in addition to hot ones
345 bool shouldInlineColdCallee(CallBase &CallInst);
346 void emitOptimizationRemarksForInlineCandidates(
347 const SmallVectorImpl<CallBase *> &Candidates, const Function &F,
348 bool Hot);
349 void printEdgeWeight(raw_ostream &OS, Edge E);
350 void printBlockWeight(raw_ostream &OS, const BasicBlock *BB) const;
351 void printBlockEquivalence(raw_ostream &OS, const BasicBlock *BB);
352 bool computeBlockWeights(Function &F);
353 void findEquivalenceClasses(Function &F);
354 template <bool IsPostDom>
355 void findEquivalencesFor(BasicBlock *BB1, ArrayRef<BasicBlock *> Descendants,
356 DominatorTreeBase<BasicBlock, IsPostDom> *DomTree);
357
358 void propagateWeights(Function &F);
359 uint64_t visitEdge(Edge E, unsigned *NumUnknownEdges, Edge *UnknownEdge);
360 void buildEdges(Function &F);
361 std::vector<Function *> buildFunctionOrder(Module &M, CallGraph *CG);
362 bool propagateThroughEdges(Function &F, bool UpdateBlockCount);
363 void computeDominanceAndLoopInfo(Function &F);
364 void clearFunctionData();
365 bool callsiteIsHot(const FunctionSamples *CallsiteFS,
366 ProfileSummaryInfo *PSI);
367
368 /// Map basic blocks to their computed weights.
369 ///
370 /// The weight of a basic block is defined to be the maximum
371 /// of all the instruction weights in that block.
372 BlockWeightMap BlockWeights;
373
374 /// Map edges to their computed weights.
375 ///
376 /// Edge weights are computed by propagating basic block weights in
377 /// SampleProfile::propagateWeights.
378 EdgeWeightMap EdgeWeights;
379
380 /// Set of visited blocks during propagation.
381 SmallPtrSet<const BasicBlock *, 32> VisitedBlocks;
382
383 /// Set of visited edges during propagation.
384 SmallSet<Edge, 32> VisitedEdges;
385
386 /// Equivalence classes for block weights.
387 ///
388 /// Two blocks BB1 and BB2 are in the same equivalence class if they
389 /// dominate and post-dominate each other, and they are in the same loop
390 /// nest. When this happens, the two blocks are guaranteed to execute
391 /// the same number of times.
392 EquivalenceClassMap EquivalenceClass;
393
394 /// Map from function name to Function *. Used to find the function from
395 /// the function name. If the function name contains suffix, additional
396 /// entry is added to map from the stripped name to the function if there
397 /// is one-to-one mapping.
398 StringMap<Function *> SymbolMap;
399
400 /// Dominance, post-dominance and loop information.
401 std::unique_ptr<DominatorTree> DT;
402 std::unique_ptr<PostDominatorTree> PDT;
403 std::unique_ptr<LoopInfo> LI;
404
405 std::function<AssumptionCache &(Function &)> GetAC;
406 std::function<TargetTransformInfo &(Function &)> GetTTI;
407 std::function<const TargetLibraryInfo &(Function &)> GetTLI;
408
409 /// Predecessors for each basic block in the CFG.
410 BlockEdgeMap Predecessors;
411
412 /// Successors for each basic block in the CFG.
413 BlockEdgeMap Successors;
414
415 SampleCoverageTracker CoverageTracker;
416
417 /// Profile reader object.
418 std::unique_ptr<SampleProfileReader> Reader;
419
420 /// Samples collected for the body of this function.
421 FunctionSamples *Samples = nullptr;
422
423 /// Name of the profile file to load.
424 std::string Filename;
425
426 /// Name of the profile remapping file to load.
427 std::string RemappingFilename;
428
429 /// Flag indicating whether the profile input loaded successfully.
430 bool ProfileIsValid = false;
431
432 /// Flag indicating if the pass is invoked in ThinLTO compile phase.
433 ///
434 /// In this phase, in annotation, we should not promote indirect calls.
435 /// Instead, we will mark GUIDs that needs to be annotated to the function.
436 bool IsThinLTOPreLink;
437
438 /// Profile Summary Info computed from sample profile.
439 ProfileSummaryInfo *PSI = nullptr;
440
441 /// Profle Symbol list tells whether a function name appears in the binary
442 /// used to generate the current profile.
443 std::unique_ptr<ProfileSymbolList> PSL;
444
445 /// Total number of samples collected in this profile.
446 ///
447 /// This is the sum of all the samples collected in all the functions executed
448 /// at runtime.
449 uint64_t TotalCollectedSamples = 0;
450
451 /// Optimization Remark Emitter used to emit diagnostic remarks.
452 OptimizationRemarkEmitter *ORE = nullptr;
453
454 // Information recorded when we declined to inline a call site
455 // because we have determined it is too cold is accumulated for
456 // each callee function. Initially this is just the entry count.
457 struct NotInlinedProfileInfo {
458 uint64_t entryCount;
459 };
460 DenseMap<Function *, NotInlinedProfileInfo> notInlinedCallInfo;
461
462 // GUIDToFuncNameMap saves the mapping from GUID to the symbol name, for
463 // all the function symbols defined or declared in current module.
464 DenseMap<uint64_t, StringRef> GUIDToFuncNameMap;
465
466 // All the Names used in FunctionSamples including outline function
467 // names, inline instance names and call target names.
468 StringSet<> NamesInProfile;
469
470 // For symbol in profile symbol list, whether to regard their profiles
471 // to be accurate. It is mainly decided by existance of profile symbol
472 // list and -profile-accurate-for-symsinlist flag, but it can be
473 // overriden by -profile-sample-accurate or profile-sample-accurate
474 // attribute.
475 bool ProfAccForSymsInList;
476 };
477
478 class SampleProfileLoaderLegacyPass : public ModulePass {
479 public:
480 // Class identification, replacement for typeinfo
481 static char ID;
482
SampleProfileLoaderLegacyPass(StringRef Name=SampleProfileFile,bool IsThinLTOPreLink=false)483 SampleProfileLoaderLegacyPass(StringRef Name = SampleProfileFile,
484 bool IsThinLTOPreLink = false)
485 : ModulePass(ID), SampleLoader(
486 Name, SampleProfileRemappingFile, IsThinLTOPreLink,
487 [&](Function &F) -> AssumptionCache & {
488 return ACT->getAssumptionCache(F);
489 },
__anon649b3f260302(Function &F) 490 [&](Function &F) -> TargetTransformInfo & {
491 return TTIWP->getTTI(F);
492 },
__anon649b3f260402(Function &F) 493 [&](Function &F) -> TargetLibraryInfo & {
494 return TLIWP->getTLI(F);
495 }) {
496 initializeSampleProfileLoaderLegacyPassPass(
497 *PassRegistry::getPassRegistry());
498 }
499
dump()500 void dump() { SampleLoader.dump(); }
501
doInitialization(Module & M)502 bool doInitialization(Module &M) override {
503 return SampleLoader.doInitialization(M);
504 }
505
getPassName() const506 StringRef getPassName() const override { return "Sample profile pass"; }
507 bool runOnModule(Module &M) override;
508
getAnalysisUsage(AnalysisUsage & AU) const509 void getAnalysisUsage(AnalysisUsage &AU) const override {
510 AU.addRequired<AssumptionCacheTracker>();
511 AU.addRequired<TargetTransformInfoWrapperPass>();
512 AU.addRequired<TargetLibraryInfoWrapperPass>();
513 AU.addRequired<ProfileSummaryInfoWrapperPass>();
514 }
515
516 private:
517 SampleProfileLoader SampleLoader;
518 AssumptionCacheTracker *ACT = nullptr;
519 TargetTransformInfoWrapperPass *TTIWP = nullptr;
520 TargetLibraryInfoWrapperPass *TLIWP = nullptr;
521 };
522
523 } // end anonymous namespace
524
525 /// Return true if the given callsite is hot wrt to hot cutoff threshold.
526 ///
527 /// Functions that were inlined in the original binary will be represented
528 /// in the inline stack in the sample profile. If the profile shows that
529 /// the original inline decision was "good" (i.e., the callsite is executed
530 /// frequently), then we will recreate the inline decision and apply the
531 /// profile from the inlined callsite.
532 ///
533 /// To decide whether an inlined callsite is hot, we compare the callsite
534 /// sample count with the hot cutoff computed by ProfileSummaryInfo, it is
535 /// regarded as hot if the count is above the cutoff value.
536 ///
537 /// When ProfileAccurateForSymsInList is enabled and profile symbol list
538 /// is present, functions in the profile symbol list but without profile will
539 /// be regarded as cold and much less inlining will happen in CGSCC inlining
540 /// pass, so we tend to lower the hot criteria here to allow more early
541 /// inlining to happen for warm callsites and it is helpful for performance.
callsiteIsHot(const FunctionSamples * CallsiteFS,ProfileSummaryInfo * PSI)542 bool SampleProfileLoader::callsiteIsHot(const FunctionSamples *CallsiteFS,
543 ProfileSummaryInfo *PSI) {
544 if (!CallsiteFS)
545 return false; // The callsite was not inlined in the original binary.
546
547 assert(PSI && "PSI is expected to be non null");
548 uint64_t CallsiteTotalSamples = CallsiteFS->getTotalSamples();
549 if (ProfAccForSymsInList)
550 return !PSI->isColdCount(CallsiteTotalSamples);
551 else
552 return PSI->isHotCount(CallsiteTotalSamples);
553 }
554
555 /// Mark as used the sample record for the given function samples at
556 /// (LineOffset, Discriminator).
557 ///
558 /// \returns true if this is the first time we mark the given record.
markSamplesUsed(const FunctionSamples * FS,uint32_t LineOffset,uint32_t Discriminator,uint64_t Samples)559 bool SampleCoverageTracker::markSamplesUsed(const FunctionSamples *FS,
560 uint32_t LineOffset,
561 uint32_t Discriminator,
562 uint64_t Samples) {
563 LineLocation Loc(LineOffset, Discriminator);
564 unsigned &Count = SampleCoverage[FS][Loc];
565 bool FirstTime = (++Count == 1);
566 if (FirstTime)
567 TotalUsedSamples += Samples;
568 return FirstTime;
569 }
570
571 /// Return the number of sample records that were applied from this profile.
572 ///
573 /// This count does not include records from cold inlined callsites.
574 unsigned
countUsedRecords(const FunctionSamples * FS,ProfileSummaryInfo * PSI) const575 SampleCoverageTracker::countUsedRecords(const FunctionSamples *FS,
576 ProfileSummaryInfo *PSI) const {
577 auto I = SampleCoverage.find(FS);
578
579 // The size of the coverage map for FS represents the number of records
580 // that were marked used at least once.
581 unsigned Count = (I != SampleCoverage.end()) ? I->second.size() : 0;
582
583 // If there are inlined callsites in this function, count the samples found
584 // in the respective bodies. However, do not bother counting callees with 0
585 // total samples, these are callees that were never invoked at runtime.
586 for (const auto &I : FS->getCallsiteSamples())
587 for (const auto &J : I.second) {
588 const FunctionSamples *CalleeSamples = &J.second;
589 if (SPLoader.callsiteIsHot(CalleeSamples, PSI))
590 Count += countUsedRecords(CalleeSamples, PSI);
591 }
592
593 return Count;
594 }
595
596 /// Return the number of sample records in the body of this profile.
597 ///
598 /// This count does not include records from cold inlined callsites.
599 unsigned
countBodyRecords(const FunctionSamples * FS,ProfileSummaryInfo * PSI) const600 SampleCoverageTracker::countBodyRecords(const FunctionSamples *FS,
601 ProfileSummaryInfo *PSI) const {
602 unsigned Count = FS->getBodySamples().size();
603
604 // Only count records in hot callsites.
605 for (const auto &I : FS->getCallsiteSamples())
606 for (const auto &J : I.second) {
607 const FunctionSamples *CalleeSamples = &J.second;
608 if (SPLoader.callsiteIsHot(CalleeSamples, PSI))
609 Count += countBodyRecords(CalleeSamples, PSI);
610 }
611
612 return Count;
613 }
614
615 /// Return the number of samples collected in the body of this profile.
616 ///
617 /// This count does not include samples from cold inlined callsites.
618 uint64_t
countBodySamples(const FunctionSamples * FS,ProfileSummaryInfo * PSI) const619 SampleCoverageTracker::countBodySamples(const FunctionSamples *FS,
620 ProfileSummaryInfo *PSI) const {
621 uint64_t Total = 0;
622 for (const auto &I : FS->getBodySamples())
623 Total += I.second.getSamples();
624
625 // Only count samples in hot callsites.
626 for (const auto &I : FS->getCallsiteSamples())
627 for (const auto &J : I.second) {
628 const FunctionSamples *CalleeSamples = &J.second;
629 if (SPLoader.callsiteIsHot(CalleeSamples, PSI))
630 Total += countBodySamples(CalleeSamples, PSI);
631 }
632
633 return Total;
634 }
635
636 /// Return the fraction of sample records used in this profile.
637 ///
638 /// The returned value is an unsigned integer in the range 0-100 indicating
639 /// the percentage of sample records that were used while applying this
640 /// profile to the associated function.
computeCoverage(unsigned Used,unsigned Total) const641 unsigned SampleCoverageTracker::computeCoverage(unsigned Used,
642 unsigned Total) const {
643 assert(Used <= Total &&
644 "number of used records cannot exceed the total number of records");
645 return Total > 0 ? Used * 100 / Total : 100;
646 }
647
648 /// Clear all the per-function data used to load samples and propagate weights.
clearFunctionData()649 void SampleProfileLoader::clearFunctionData() {
650 BlockWeights.clear();
651 EdgeWeights.clear();
652 VisitedBlocks.clear();
653 VisitedEdges.clear();
654 EquivalenceClass.clear();
655 DT = nullptr;
656 PDT = nullptr;
657 LI = nullptr;
658 Predecessors.clear();
659 Successors.clear();
660 CoverageTracker.clear();
661 }
662
663 #ifndef NDEBUG
664 /// Print the weight of edge \p E on stream \p OS.
665 ///
666 /// \param OS Stream to emit the output to.
667 /// \param E Edge to print.
printEdgeWeight(raw_ostream & OS,Edge E)668 void SampleProfileLoader::printEdgeWeight(raw_ostream &OS, Edge E) {
669 OS << "weight[" << E.first->getName() << "->" << E.second->getName()
670 << "]: " << EdgeWeights[E] << "\n";
671 }
672
673 /// Print the equivalence class of block \p BB on stream \p OS.
674 ///
675 /// \param OS Stream to emit the output to.
676 /// \param BB Block to print.
printBlockEquivalence(raw_ostream & OS,const BasicBlock * BB)677 void SampleProfileLoader::printBlockEquivalence(raw_ostream &OS,
678 const BasicBlock *BB) {
679 const BasicBlock *Equiv = EquivalenceClass[BB];
680 OS << "equivalence[" << BB->getName()
681 << "]: " << ((Equiv) ? EquivalenceClass[BB]->getName() : "NONE") << "\n";
682 }
683
684 /// Print the weight of block \p BB on stream \p OS.
685 ///
686 /// \param OS Stream to emit the output to.
687 /// \param BB Block to print.
printBlockWeight(raw_ostream & OS,const BasicBlock * BB) const688 void SampleProfileLoader::printBlockWeight(raw_ostream &OS,
689 const BasicBlock *BB) const {
690 const auto &I = BlockWeights.find(BB);
691 uint64_t W = (I == BlockWeights.end() ? 0 : I->second);
692 OS << "weight[" << BB->getName() << "]: " << W << "\n";
693 }
694 #endif
695
696 /// Get the weight for an instruction.
697 ///
698 /// The "weight" of an instruction \p Inst is the number of samples
699 /// collected on that instruction at runtime. To retrieve it, we
700 /// need to compute the line number of \p Inst relative to the start of its
701 /// function. We use HeaderLineno to compute the offset. We then
702 /// look up the samples collected for \p Inst using BodySamples.
703 ///
704 /// \param Inst Instruction to query.
705 ///
706 /// \returns the weight of \p Inst.
getInstWeight(const Instruction & Inst)707 ErrorOr<uint64_t> SampleProfileLoader::getInstWeight(const Instruction &Inst) {
708 const DebugLoc &DLoc = Inst.getDebugLoc();
709 if (!DLoc)
710 return std::error_code();
711
712 const FunctionSamples *FS = findFunctionSamples(Inst);
713 if (!FS)
714 return std::error_code();
715
716 // Ignore all intrinsics, phinodes and branch instructions.
717 // Branch and phinodes instruction usually contains debug info from sources outside of
718 // the residing basic block, thus we ignore them during annotation.
719 if (isa<BranchInst>(Inst) || isa<IntrinsicInst>(Inst) || isa<PHINode>(Inst))
720 return std::error_code();
721
722 // If a direct call/invoke instruction is inlined in profile
723 // (findCalleeFunctionSamples returns non-empty result), but not inlined here,
724 // it means that the inlined callsite has no sample, thus the call
725 // instruction should have 0 count.
726 if (auto *CB = dyn_cast<CallBase>(&Inst))
727 if (!CB->isIndirectCall() && findCalleeFunctionSamples(*CB))
728 return 0;
729
730 const DILocation *DIL = DLoc;
731 uint32_t LineOffset = FunctionSamples::getOffset(DIL);
732 uint32_t Discriminator = DIL->getBaseDiscriminator();
733 ErrorOr<uint64_t> R = FS->findSamplesAt(LineOffset, Discriminator);
734 if (R) {
735 bool FirstMark =
736 CoverageTracker.markSamplesUsed(FS, LineOffset, Discriminator, R.get());
737 if (FirstMark) {
738 ORE->emit([&]() {
739 OptimizationRemarkAnalysis Remark(DEBUG_TYPE, "AppliedSamples", &Inst);
740 Remark << "Applied " << ore::NV("NumSamples", *R);
741 Remark << " samples from profile (offset: ";
742 Remark << ore::NV("LineOffset", LineOffset);
743 if (Discriminator) {
744 Remark << ".";
745 Remark << ore::NV("Discriminator", Discriminator);
746 }
747 Remark << ")";
748 return Remark;
749 });
750 }
751 LLVM_DEBUG(dbgs() << " " << DLoc.getLine() << "."
752 << DIL->getBaseDiscriminator() << ":" << Inst
753 << " (line offset: " << LineOffset << "."
754 << DIL->getBaseDiscriminator() << " - weight: " << R.get()
755 << ")\n");
756 }
757 return R;
758 }
759
760 /// Compute the weight of a basic block.
761 ///
762 /// The weight of basic block \p BB is the maximum weight of all the
763 /// instructions in BB.
764 ///
765 /// \param BB The basic block to query.
766 ///
767 /// \returns the weight for \p BB.
getBlockWeight(const BasicBlock * BB)768 ErrorOr<uint64_t> SampleProfileLoader::getBlockWeight(const BasicBlock *BB) {
769 uint64_t Max = 0;
770 bool HasWeight = false;
771 for (auto &I : BB->getInstList()) {
772 const ErrorOr<uint64_t> &R = getInstWeight(I);
773 if (R) {
774 Max = std::max(Max, R.get());
775 HasWeight = true;
776 }
777 }
778 return HasWeight ? ErrorOr<uint64_t>(Max) : std::error_code();
779 }
780
781 /// Compute and store the weights of every basic block.
782 ///
783 /// This populates the BlockWeights map by computing
784 /// the weights of every basic block in the CFG.
785 ///
786 /// \param F The function to query.
computeBlockWeights(Function & F)787 bool SampleProfileLoader::computeBlockWeights(Function &F) {
788 bool Changed = false;
789 LLVM_DEBUG(dbgs() << "Block weights\n");
790 for (const auto &BB : F) {
791 ErrorOr<uint64_t> Weight = getBlockWeight(&BB);
792 if (Weight) {
793 BlockWeights[&BB] = Weight.get();
794 VisitedBlocks.insert(&BB);
795 Changed = true;
796 }
797 LLVM_DEBUG(printBlockWeight(dbgs(), &BB));
798 }
799
800 return Changed;
801 }
802
803 /// Get the FunctionSamples for a call instruction.
804 ///
805 /// The FunctionSamples of a call/invoke instruction \p Inst is the inlined
806 /// instance in which that call instruction is calling to. It contains
807 /// all samples that resides in the inlined instance. We first find the
808 /// inlined instance in which the call instruction is from, then we
809 /// traverse its children to find the callsite with the matching
810 /// location.
811 ///
812 /// \param Inst Call/Invoke instruction to query.
813 ///
814 /// \returns The FunctionSamples pointer to the inlined instance.
815 const FunctionSamples *
findCalleeFunctionSamples(const CallBase & Inst) const816 SampleProfileLoader::findCalleeFunctionSamples(const CallBase &Inst) const {
817 const DILocation *DIL = Inst.getDebugLoc();
818 if (!DIL) {
819 return nullptr;
820 }
821
822 StringRef CalleeName;
823 if (const CallInst *CI = dyn_cast<CallInst>(&Inst))
824 if (Function *Callee = CI->getCalledFunction())
825 CalleeName = Callee->getName();
826
827 const FunctionSamples *FS = findFunctionSamples(Inst);
828 if (FS == nullptr)
829 return nullptr;
830
831 return FS->findFunctionSamplesAt(LineLocation(FunctionSamples::getOffset(DIL),
832 DIL->getBaseDiscriminator()),
833 CalleeName);
834 }
835
836 /// Returns a vector of FunctionSamples that are the indirect call targets
837 /// of \p Inst. The vector is sorted by the total number of samples. Stores
838 /// the total call count of the indirect call in \p Sum.
839 std::vector<const FunctionSamples *>
findIndirectCallFunctionSamples(const Instruction & Inst,uint64_t & Sum) const840 SampleProfileLoader::findIndirectCallFunctionSamples(
841 const Instruction &Inst, uint64_t &Sum) const {
842 const DILocation *DIL = Inst.getDebugLoc();
843 std::vector<const FunctionSamples *> R;
844
845 if (!DIL) {
846 return R;
847 }
848
849 const FunctionSamples *FS = findFunctionSamples(Inst);
850 if (FS == nullptr)
851 return R;
852
853 uint32_t LineOffset = FunctionSamples::getOffset(DIL);
854 uint32_t Discriminator = DIL->getBaseDiscriminator();
855
856 auto T = FS->findCallTargetMapAt(LineOffset, Discriminator);
857 Sum = 0;
858 if (T)
859 for (const auto &T_C : T.get())
860 Sum += T_C.second;
861 if (const FunctionSamplesMap *M = FS->findFunctionSamplesMapAt(LineLocation(
862 FunctionSamples::getOffset(DIL), DIL->getBaseDiscriminator()))) {
863 if (M->empty())
864 return R;
865 for (const auto &NameFS : *M) {
866 Sum += NameFS.second.getEntrySamples();
867 R.push_back(&NameFS.second);
868 }
869 llvm::sort(R, [](const FunctionSamples *L, const FunctionSamples *R) {
870 if (L->getEntrySamples() != R->getEntrySamples())
871 return L->getEntrySamples() > R->getEntrySamples();
872 return FunctionSamples::getGUID(L->getName()) <
873 FunctionSamples::getGUID(R->getName());
874 });
875 }
876 return R;
877 }
878
879 /// Get the FunctionSamples for an instruction.
880 ///
881 /// The FunctionSamples of an instruction \p Inst is the inlined instance
882 /// in which that instruction is coming from. We traverse the inline stack
883 /// of that instruction, and match it with the tree nodes in the profile.
884 ///
885 /// \param Inst Instruction to query.
886 ///
887 /// \returns the FunctionSamples pointer to the inlined instance.
888 const FunctionSamples *
findFunctionSamples(const Instruction & Inst) const889 SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const {
890 const DILocation *DIL = Inst.getDebugLoc();
891 if (!DIL)
892 return Samples;
893
894 auto it = DILocation2SampleMap.try_emplace(DIL,nullptr);
895 if (it.second)
896 it.first->second = Samples->findFunctionSamples(DIL);
897 return it.first->second;
898 }
899
inlineCallInstruction(CallBase & CB)900 bool SampleProfileLoader::inlineCallInstruction(CallBase &CB) {
901 Function *CalledFunction = CB.getCalledFunction();
902 assert(CalledFunction);
903 DebugLoc DLoc = CB.getDebugLoc();
904 BasicBlock *BB = CB.getParent();
905 InlineParams Params = getInlineParams();
906 Params.ComputeFullInlineCost = true;
907 // Checks if there is anything in the reachable portion of the callee at
908 // this callsite that makes this inlining potentially illegal. Need to
909 // set ComputeFullInlineCost, otherwise getInlineCost may return early
910 // when cost exceeds threshold without checking all IRs in the callee.
911 // The acutal cost does not matter because we only checks isNever() to
912 // see if it is legal to inline the callsite.
913 InlineCost Cost =
914 getInlineCost(CB, Params, GetTTI(*CalledFunction), GetAC, GetTLI);
915 if (Cost.isNever()) {
916 ORE->emit(OptimizationRemarkAnalysis(CSINLINE_DEBUG, "InlineFail", DLoc, BB)
917 << "incompatible inlining");
918 return false;
919 }
920 InlineFunctionInfo IFI(nullptr, GetAC);
921 if (InlineFunction(CB, IFI).isSuccess()) {
922 // The call to InlineFunction erases I, so we can't pass it here.
923 emitInlinedInto(*ORE, DLoc, BB, *CalledFunction, *BB->getParent(), Cost,
924 true, CSINLINE_DEBUG);
925 return true;
926 }
927 return false;
928 }
929
shouldInlineColdCallee(CallBase & CallInst)930 bool SampleProfileLoader::shouldInlineColdCallee(CallBase &CallInst) {
931 if (!ProfileSizeInline)
932 return false;
933
934 Function *Callee = CallInst.getCalledFunction();
935 if (Callee == nullptr)
936 return false;
937
938 InlineCost Cost = getInlineCost(CallInst, getInlineParams(), GetTTI(*Callee),
939 GetAC, GetTLI);
940
941 return Cost.getCost() <= SampleColdCallSiteThreshold;
942 }
943
emitOptimizationRemarksForInlineCandidates(const SmallVectorImpl<CallBase * > & Candidates,const Function & F,bool Hot)944 void SampleProfileLoader::emitOptimizationRemarksForInlineCandidates(
945 const SmallVectorImpl<CallBase *> &Candidates, const Function &F,
946 bool Hot) {
947 for (auto I : Candidates) {
948 Function *CalledFunction = I->getCalledFunction();
949 if (CalledFunction) {
950 ORE->emit(OptimizationRemarkAnalysis(CSINLINE_DEBUG, "InlineAttempt",
951 I->getDebugLoc(), I->getParent())
952 << "previous inlining reattempted for "
953 << (Hot ? "hotness: '" : "size: '")
954 << ore::NV("Callee", CalledFunction) << "' into '"
955 << ore::NV("Caller", &F) << "'");
956 }
957 }
958 }
959
960 /// Iteratively inline hot callsites of a function.
961 ///
962 /// Iteratively traverse all callsites of the function \p F, and find if
963 /// the corresponding inlined instance exists and is hot in profile. If
964 /// it is hot enough, inline the callsites and adds new callsites of the
965 /// callee into the caller. If the call is an indirect call, first promote
966 /// it to direct call. Each indirect call is limited with a single target.
967 ///
968 /// \param F function to perform iterative inlining.
969 /// \param InlinedGUIDs a set to be updated to include all GUIDs that are
970 /// inlined in the profiled binary.
971 ///
972 /// \returns True if there is any inline happened.
inlineHotFunctions(Function & F,DenseSet<GlobalValue::GUID> & InlinedGUIDs)973 bool SampleProfileLoader::inlineHotFunctions(
974 Function &F, DenseSet<GlobalValue::GUID> &InlinedGUIDs) {
975 DenseSet<Instruction *> PromotedInsns;
976
977 // ProfAccForSymsInList is used in callsiteIsHot. The assertion makes sure
978 // Profile symbol list is ignored when profile-sample-accurate is on.
979 assert((!ProfAccForSymsInList ||
980 (!ProfileSampleAccurate &&
981 !F.hasFnAttribute("profile-sample-accurate"))) &&
982 "ProfAccForSymsInList should be false when profile-sample-accurate "
983 "is enabled");
984
985 DenseMap<CallBase *, const FunctionSamples *> localNotInlinedCallSites;
986 bool Changed = false;
987 while (true) {
988 bool LocalChanged = false;
989 SmallVector<CallBase *, 10> CIS;
990 for (auto &BB : F) {
991 bool Hot = false;
992 SmallVector<CallBase *, 10> AllCandidates;
993 SmallVector<CallBase *, 10> ColdCandidates;
994 for (auto &I : BB.getInstList()) {
995 const FunctionSamples *FS = nullptr;
996 if (auto *CB = dyn_cast<CallBase>(&I)) {
997 if (!isa<IntrinsicInst>(I) && (FS = findCalleeFunctionSamples(*CB))) {
998 AllCandidates.push_back(CB);
999 if (FS->getEntrySamples() > 0)
1000 localNotInlinedCallSites.try_emplace(CB, FS);
1001 if (callsiteIsHot(FS, PSI))
1002 Hot = true;
1003 else if (shouldInlineColdCallee(*CB))
1004 ColdCandidates.push_back(CB);
1005 }
1006 }
1007 }
1008 if (Hot) {
1009 CIS.insert(CIS.begin(), AllCandidates.begin(), AllCandidates.end());
1010 emitOptimizationRemarksForInlineCandidates(AllCandidates, F, true);
1011 } else {
1012 CIS.insert(CIS.begin(), ColdCandidates.begin(), ColdCandidates.end());
1013 emitOptimizationRemarksForInlineCandidates(ColdCandidates, F, false);
1014 }
1015 }
1016 for (CallBase *I : CIS) {
1017 Function *CalledFunction = I->getCalledFunction();
1018 // Do not inline recursive calls.
1019 if (CalledFunction == &F)
1020 continue;
1021 if (I->isIndirectCall()) {
1022 if (PromotedInsns.count(I))
1023 continue;
1024 uint64_t Sum;
1025 for (const auto *FS : findIndirectCallFunctionSamples(*I, Sum)) {
1026 if (IsThinLTOPreLink) {
1027 FS->findInlinedFunctions(InlinedGUIDs, F.getParent(),
1028 PSI->getOrCompHotCountThreshold());
1029 continue;
1030 }
1031 auto CalleeFunctionName = FS->getFuncName();
1032 // If it is a recursive call, we do not inline it as it could bloat
1033 // the code exponentially. There is way to better handle this, e.g.
1034 // clone the caller first, and inline the cloned caller if it is
1035 // recursive. As llvm does not inline recursive calls, we will
1036 // simply ignore it instead of handling it explicitly.
1037 if (CalleeFunctionName == F.getName())
1038 continue;
1039
1040 if (!callsiteIsHot(FS, PSI))
1041 continue;
1042
1043 const char *Reason = "Callee function not available";
1044 auto R = SymbolMap.find(CalleeFunctionName);
1045 if (R != SymbolMap.end() && R->getValue() &&
1046 !R->getValue()->isDeclaration() &&
1047 R->getValue()->getSubprogram() &&
1048 R->getValue()->hasFnAttribute("use-sample-profile") &&
1049 isLegalToPromote(*I, R->getValue(), &Reason)) {
1050 uint64_t C = FS->getEntrySamples();
1051 auto &DI =
1052 pgo::promoteIndirectCall(*I, R->getValue(), C, Sum, false, ORE);
1053 Sum -= C;
1054 PromotedInsns.insert(I);
1055 // If profile mismatches, we should not attempt to inline DI.
1056 if ((isa<CallInst>(DI) || isa<InvokeInst>(DI)) &&
1057 inlineCallInstruction(cast<CallBase>(DI))) {
1058 localNotInlinedCallSites.erase(I);
1059 LocalChanged = true;
1060 ++NumCSInlined;
1061 }
1062 } else {
1063 LLVM_DEBUG(dbgs()
1064 << "\nFailed to promote indirect call to "
1065 << CalleeFunctionName << " because " << Reason << "\n");
1066 }
1067 }
1068 } else if (CalledFunction && CalledFunction->getSubprogram() &&
1069 !CalledFunction->isDeclaration()) {
1070 if (inlineCallInstruction(*I)) {
1071 localNotInlinedCallSites.erase(I);
1072 LocalChanged = true;
1073 ++NumCSInlined;
1074 }
1075 } else if (IsThinLTOPreLink) {
1076 findCalleeFunctionSamples(*I)->findInlinedFunctions(
1077 InlinedGUIDs, F.getParent(), PSI->getOrCompHotCountThreshold());
1078 }
1079 }
1080 if (LocalChanged) {
1081 Changed = true;
1082 } else {
1083 break;
1084 }
1085 }
1086
1087 // Accumulate not inlined callsite information into notInlinedSamples
1088 for (const auto &Pair : localNotInlinedCallSites) {
1089 CallBase *I = Pair.getFirst();
1090 Function *Callee = I->getCalledFunction();
1091 if (!Callee || Callee->isDeclaration())
1092 continue;
1093
1094 ORE->emit(OptimizationRemarkAnalysis(CSINLINE_DEBUG, "NotInline",
1095 I->getDebugLoc(), I->getParent())
1096 << "previous inlining not repeated: '"
1097 << ore::NV("Callee", Callee) << "' into '"
1098 << ore::NV("Caller", &F) << "'");
1099
1100 ++NumCSNotInlined;
1101 const FunctionSamples *FS = Pair.getSecond();
1102 if (FS->getTotalSamples() == 0 && FS->getEntrySamples() == 0) {
1103 continue;
1104 }
1105
1106 if (ProfileMergeInlinee) {
1107 // Use entry samples as head samples during the merge, as inlinees
1108 // don't have head samples.
1109 assert(FS->getHeadSamples() == 0 && "Expect 0 head sample for inlinee");
1110 const_cast<FunctionSamples *>(FS)->addHeadSamples(FS->getEntrySamples());
1111
1112 // Note that we have to do the merge right after processing function.
1113 // This allows OutlineFS's profile to be used for annotation during
1114 // top-down processing of functions' annotation.
1115 FunctionSamples *OutlineFS = Reader->getOrCreateSamplesFor(*Callee);
1116 OutlineFS->merge(*FS);
1117 } else {
1118 auto pair =
1119 notInlinedCallInfo.try_emplace(Callee, NotInlinedProfileInfo{0});
1120 pair.first->second.entryCount += FS->getEntrySamples();
1121 }
1122 }
1123 return Changed;
1124 }
1125
1126 /// Find equivalence classes for the given block.
1127 ///
1128 /// This finds all the blocks that are guaranteed to execute the same
1129 /// number of times as \p BB1. To do this, it traverses all the
1130 /// descendants of \p BB1 in the dominator or post-dominator tree.
1131 ///
1132 /// A block BB2 will be in the same equivalence class as \p BB1 if
1133 /// the following holds:
1134 ///
1135 /// 1- \p BB1 is a descendant of BB2 in the opposite tree. So, if BB2
1136 /// is a descendant of \p BB1 in the dominator tree, then BB2 should
1137 /// dominate BB1 in the post-dominator tree.
1138 ///
1139 /// 2- Both BB2 and \p BB1 must be in the same loop.
1140 ///
1141 /// For every block BB2 that meets those two requirements, we set BB2's
1142 /// equivalence class to \p BB1.
1143 ///
1144 /// \param BB1 Block to check.
1145 /// \param Descendants Descendants of \p BB1 in either the dom or pdom tree.
1146 /// \param DomTree Opposite dominator tree. If \p Descendants is filled
1147 /// with blocks from \p BB1's dominator tree, then
1148 /// this is the post-dominator tree, and vice versa.
1149 template <bool IsPostDom>
findEquivalencesFor(BasicBlock * BB1,ArrayRef<BasicBlock * > Descendants,DominatorTreeBase<BasicBlock,IsPostDom> * DomTree)1150 void SampleProfileLoader::findEquivalencesFor(
1151 BasicBlock *BB1, ArrayRef<BasicBlock *> Descendants,
1152 DominatorTreeBase<BasicBlock, IsPostDom> *DomTree) {
1153 const BasicBlock *EC = EquivalenceClass[BB1];
1154 uint64_t Weight = BlockWeights[EC];
1155 for (const auto *BB2 : Descendants) {
1156 bool IsDomParent = DomTree->dominates(BB2, BB1);
1157 bool IsInSameLoop = LI->getLoopFor(BB1) == LI->getLoopFor(BB2);
1158 if (BB1 != BB2 && IsDomParent && IsInSameLoop) {
1159 EquivalenceClass[BB2] = EC;
1160 // If BB2 is visited, then the entire EC should be marked as visited.
1161 if (VisitedBlocks.count(BB2)) {
1162 VisitedBlocks.insert(EC);
1163 }
1164
1165 // If BB2 is heavier than BB1, make BB2 have the same weight
1166 // as BB1.
1167 //
1168 // Note that we don't worry about the opposite situation here
1169 // (when BB2 is lighter than BB1). We will deal with this
1170 // during the propagation phase. Right now, we just want to
1171 // make sure that BB1 has the largest weight of all the
1172 // members of its equivalence set.
1173 Weight = std::max(Weight, BlockWeights[BB2]);
1174 }
1175 }
1176 if (EC == &EC->getParent()->getEntryBlock()) {
1177 BlockWeights[EC] = Samples->getHeadSamples() + 1;
1178 } else {
1179 BlockWeights[EC] = Weight;
1180 }
1181 }
1182
1183 /// Find equivalence classes.
1184 ///
1185 /// Since samples may be missing from blocks, we can fill in the gaps by setting
1186 /// the weights of all the blocks in the same equivalence class to the same
1187 /// weight. To compute the concept of equivalence, we use dominance and loop
1188 /// information. Two blocks B1 and B2 are in the same equivalence class if B1
1189 /// dominates B2, B2 post-dominates B1 and both are in the same loop.
1190 ///
1191 /// \param F The function to query.
findEquivalenceClasses(Function & F)1192 void SampleProfileLoader::findEquivalenceClasses(Function &F) {
1193 SmallVector<BasicBlock *, 8> DominatedBBs;
1194 LLVM_DEBUG(dbgs() << "\nBlock equivalence classes\n");
1195 // Find equivalence sets based on dominance and post-dominance information.
1196 for (auto &BB : F) {
1197 BasicBlock *BB1 = &BB;
1198
1199 // Compute BB1's equivalence class once.
1200 if (EquivalenceClass.count(BB1)) {
1201 LLVM_DEBUG(printBlockEquivalence(dbgs(), BB1));
1202 continue;
1203 }
1204
1205 // By default, blocks are in their own equivalence class.
1206 EquivalenceClass[BB1] = BB1;
1207
1208 // Traverse all the blocks dominated by BB1. We are looking for
1209 // every basic block BB2 such that:
1210 //
1211 // 1- BB1 dominates BB2.
1212 // 2- BB2 post-dominates BB1.
1213 // 3- BB1 and BB2 are in the same loop nest.
1214 //
1215 // If all those conditions hold, it means that BB2 is executed
1216 // as many times as BB1, so they are placed in the same equivalence
1217 // class by making BB2's equivalence class be BB1.
1218 DominatedBBs.clear();
1219 DT->getDescendants(BB1, DominatedBBs);
1220 findEquivalencesFor(BB1, DominatedBBs, PDT.get());
1221
1222 LLVM_DEBUG(printBlockEquivalence(dbgs(), BB1));
1223 }
1224
1225 // Assign weights to equivalence classes.
1226 //
1227 // All the basic blocks in the same equivalence class will execute
1228 // the same number of times. Since we know that the head block in
1229 // each equivalence class has the largest weight, assign that weight
1230 // to all the blocks in that equivalence class.
1231 LLVM_DEBUG(
1232 dbgs() << "\nAssign the same weight to all blocks in the same class\n");
1233 for (auto &BI : F) {
1234 const BasicBlock *BB = &BI;
1235 const BasicBlock *EquivBB = EquivalenceClass[BB];
1236 if (BB != EquivBB)
1237 BlockWeights[BB] = BlockWeights[EquivBB];
1238 LLVM_DEBUG(printBlockWeight(dbgs(), BB));
1239 }
1240 }
1241
1242 /// Visit the given edge to decide if it has a valid weight.
1243 ///
1244 /// If \p E has not been visited before, we copy to \p UnknownEdge
1245 /// and increment the count of unknown edges.
1246 ///
1247 /// \param E Edge to visit.
1248 /// \param NumUnknownEdges Current number of unknown edges.
1249 /// \param UnknownEdge Set if E has not been visited before.
1250 ///
1251 /// \returns E's weight, if known. Otherwise, return 0.
visitEdge(Edge E,unsigned * NumUnknownEdges,Edge * UnknownEdge)1252 uint64_t SampleProfileLoader::visitEdge(Edge E, unsigned *NumUnknownEdges,
1253 Edge *UnknownEdge) {
1254 if (!VisitedEdges.count(E)) {
1255 (*NumUnknownEdges)++;
1256 *UnknownEdge = E;
1257 return 0;
1258 }
1259
1260 return EdgeWeights[E];
1261 }
1262
1263 /// Propagate weights through incoming/outgoing edges.
1264 ///
1265 /// If the weight of a basic block is known, and there is only one edge
1266 /// with an unknown weight, we can calculate the weight of that edge.
1267 ///
1268 /// Similarly, if all the edges have a known count, we can calculate the
1269 /// count of the basic block, if needed.
1270 ///
1271 /// \param F Function to process.
1272 /// \param UpdateBlockCount Whether we should update basic block counts that
1273 /// has already been annotated.
1274 ///
1275 /// \returns True if new weights were assigned to edges or blocks.
propagateThroughEdges(Function & F,bool UpdateBlockCount)1276 bool SampleProfileLoader::propagateThroughEdges(Function &F,
1277 bool UpdateBlockCount) {
1278 bool Changed = false;
1279 LLVM_DEBUG(dbgs() << "\nPropagation through edges\n");
1280 for (const auto &BI : F) {
1281 const BasicBlock *BB = &BI;
1282 const BasicBlock *EC = EquivalenceClass[BB];
1283
1284 // Visit all the predecessor and successor edges to determine
1285 // which ones have a weight assigned already. Note that it doesn't
1286 // matter that we only keep track of a single unknown edge. The
1287 // only case we are interested in handling is when only a single
1288 // edge is unknown (see setEdgeOrBlockWeight).
1289 for (unsigned i = 0; i < 2; i++) {
1290 uint64_t TotalWeight = 0;
1291 unsigned NumUnknownEdges = 0, NumTotalEdges = 0;
1292 Edge UnknownEdge, SelfReferentialEdge, SingleEdge;
1293
1294 if (i == 0) {
1295 // First, visit all predecessor edges.
1296 NumTotalEdges = Predecessors[BB].size();
1297 for (auto *Pred : Predecessors[BB]) {
1298 Edge E = std::make_pair(Pred, BB);
1299 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
1300 if (E.first == E.second)
1301 SelfReferentialEdge = E;
1302 }
1303 if (NumTotalEdges == 1) {
1304 SingleEdge = std::make_pair(Predecessors[BB][0], BB);
1305 }
1306 } else {
1307 // On the second round, visit all successor edges.
1308 NumTotalEdges = Successors[BB].size();
1309 for (auto *Succ : Successors[BB]) {
1310 Edge E = std::make_pair(BB, Succ);
1311 TotalWeight += visitEdge(E, &NumUnknownEdges, &UnknownEdge);
1312 }
1313 if (NumTotalEdges == 1) {
1314 SingleEdge = std::make_pair(BB, Successors[BB][0]);
1315 }
1316 }
1317
1318 // After visiting all the edges, there are three cases that we
1319 // can handle immediately:
1320 //
1321 // - All the edge weights are known (i.e., NumUnknownEdges == 0).
1322 // In this case, we simply check that the sum of all the edges
1323 // is the same as BB's weight. If not, we change BB's weight
1324 // to match. Additionally, if BB had not been visited before,
1325 // we mark it visited.
1326 //
1327 // - Only one edge is unknown and BB has already been visited.
1328 // In this case, we can compute the weight of the edge by
1329 // subtracting the total block weight from all the known
1330 // edge weights. If the edges weight more than BB, then the
1331 // edge of the last remaining edge is set to zero.
1332 //
1333 // - There exists a self-referential edge and the weight of BB is
1334 // known. In this case, this edge can be based on BB's weight.
1335 // We add up all the other known edges and set the weight on
1336 // the self-referential edge as we did in the previous case.
1337 //
1338 // In any other case, we must continue iterating. Eventually,
1339 // all edges will get a weight, or iteration will stop when
1340 // it reaches SampleProfileMaxPropagateIterations.
1341 if (NumUnknownEdges <= 1) {
1342 uint64_t &BBWeight = BlockWeights[EC];
1343 if (NumUnknownEdges == 0) {
1344 if (!VisitedBlocks.count(EC)) {
1345 // If we already know the weight of all edges, the weight of the
1346 // basic block can be computed. It should be no larger than the sum
1347 // of all edge weights.
1348 if (TotalWeight > BBWeight) {
1349 BBWeight = TotalWeight;
1350 Changed = true;
1351 LLVM_DEBUG(dbgs() << "All edge weights for " << BB->getName()
1352 << " known. Set weight for block: ";
1353 printBlockWeight(dbgs(), BB););
1354 }
1355 } else if (NumTotalEdges == 1 &&
1356 EdgeWeights[SingleEdge] < BlockWeights[EC]) {
1357 // If there is only one edge for the visited basic block, use the
1358 // block weight to adjust edge weight if edge weight is smaller.
1359 EdgeWeights[SingleEdge] = BlockWeights[EC];
1360 Changed = true;
1361 }
1362 } else if (NumUnknownEdges == 1 && VisitedBlocks.count(EC)) {
1363 // If there is a single unknown edge and the block has been
1364 // visited, then we can compute E's weight.
1365 if (BBWeight >= TotalWeight)
1366 EdgeWeights[UnknownEdge] = BBWeight - TotalWeight;
1367 else
1368 EdgeWeights[UnknownEdge] = 0;
1369 const BasicBlock *OtherEC;
1370 if (i == 0)
1371 OtherEC = EquivalenceClass[UnknownEdge.first];
1372 else
1373 OtherEC = EquivalenceClass[UnknownEdge.second];
1374 // Edge weights should never exceed the BB weights it connects.
1375 if (VisitedBlocks.count(OtherEC) &&
1376 EdgeWeights[UnknownEdge] > BlockWeights[OtherEC])
1377 EdgeWeights[UnknownEdge] = BlockWeights[OtherEC];
1378 VisitedEdges.insert(UnknownEdge);
1379 Changed = true;
1380 LLVM_DEBUG(dbgs() << "Set weight for edge: ";
1381 printEdgeWeight(dbgs(), UnknownEdge));
1382 }
1383 } else if (VisitedBlocks.count(EC) && BlockWeights[EC] == 0) {
1384 // If a block Weights 0, all its in/out edges should weight 0.
1385 if (i == 0) {
1386 for (auto *Pred : Predecessors[BB]) {
1387 Edge E = std::make_pair(Pred, BB);
1388 EdgeWeights[E] = 0;
1389 VisitedEdges.insert(E);
1390 }
1391 } else {
1392 for (auto *Succ : Successors[BB]) {
1393 Edge E = std::make_pair(BB, Succ);
1394 EdgeWeights[E] = 0;
1395 VisitedEdges.insert(E);
1396 }
1397 }
1398 } else if (SelfReferentialEdge.first && VisitedBlocks.count(EC)) {
1399 uint64_t &BBWeight = BlockWeights[BB];
1400 // We have a self-referential edge and the weight of BB is known.
1401 if (BBWeight >= TotalWeight)
1402 EdgeWeights[SelfReferentialEdge] = BBWeight - TotalWeight;
1403 else
1404 EdgeWeights[SelfReferentialEdge] = 0;
1405 VisitedEdges.insert(SelfReferentialEdge);
1406 Changed = true;
1407 LLVM_DEBUG(dbgs() << "Set self-referential edge weight to: ";
1408 printEdgeWeight(dbgs(), SelfReferentialEdge));
1409 }
1410 if (UpdateBlockCount && !VisitedBlocks.count(EC) && TotalWeight > 0) {
1411 BlockWeights[EC] = TotalWeight;
1412 VisitedBlocks.insert(EC);
1413 Changed = true;
1414 }
1415 }
1416 }
1417
1418 return Changed;
1419 }
1420
1421 /// Build in/out edge lists for each basic block in the CFG.
1422 ///
1423 /// We are interested in unique edges. If a block B1 has multiple
1424 /// edges to another block B2, we only add a single B1->B2 edge.
buildEdges(Function & F)1425 void SampleProfileLoader::buildEdges(Function &F) {
1426 for (auto &BI : F) {
1427 BasicBlock *B1 = &BI;
1428
1429 // Add predecessors for B1.
1430 SmallPtrSet<BasicBlock *, 16> Visited;
1431 if (!Predecessors[B1].empty())
1432 llvm_unreachable("Found a stale predecessors list in a basic block.");
1433 for (pred_iterator PI = pred_begin(B1), PE = pred_end(B1); PI != PE; ++PI) {
1434 BasicBlock *B2 = *PI;
1435 if (Visited.insert(B2).second)
1436 Predecessors[B1].push_back(B2);
1437 }
1438
1439 // Add successors for B1.
1440 Visited.clear();
1441 if (!Successors[B1].empty())
1442 llvm_unreachable("Found a stale successors list in a basic block.");
1443 for (succ_iterator SI = succ_begin(B1), SE = succ_end(B1); SI != SE; ++SI) {
1444 BasicBlock *B2 = *SI;
1445 if (Visited.insert(B2).second)
1446 Successors[B1].push_back(B2);
1447 }
1448 }
1449 }
1450
1451 /// Returns the sorted CallTargetMap \p M by count in descending order.
GetSortedValueDataFromCallTargets(const SampleRecord::CallTargetMap & M)1452 static SmallVector<InstrProfValueData, 2> GetSortedValueDataFromCallTargets(
1453 const SampleRecord::CallTargetMap & M) {
1454 SmallVector<InstrProfValueData, 2> R;
1455 for (const auto &I : SampleRecord::SortCallTargets(M)) {
1456 R.emplace_back(InstrProfValueData{FunctionSamples::getGUID(I.first), I.second});
1457 }
1458 return R;
1459 }
1460
1461 /// Propagate weights into edges
1462 ///
1463 /// The following rules are applied to every block BB in the CFG:
1464 ///
1465 /// - If BB has a single predecessor/successor, then the weight
1466 /// of that edge is the weight of the block.
1467 ///
1468 /// - If all incoming or outgoing edges are known except one, and the
1469 /// weight of the block is already known, the weight of the unknown
1470 /// edge will be the weight of the block minus the sum of all the known
1471 /// edges. If the sum of all the known edges is larger than BB's weight,
1472 /// we set the unknown edge weight to zero.
1473 ///
1474 /// - If there is a self-referential edge, and the weight of the block is
1475 /// known, the weight for that edge is set to the weight of the block
1476 /// minus the weight of the other incoming edges to that block (if
1477 /// known).
propagateWeights(Function & F)1478 void SampleProfileLoader::propagateWeights(Function &F) {
1479 bool Changed = true;
1480 unsigned I = 0;
1481
1482 // If BB weight is larger than its corresponding loop's header BB weight,
1483 // use the BB weight to replace the loop header BB weight.
1484 for (auto &BI : F) {
1485 BasicBlock *BB = &BI;
1486 Loop *L = LI->getLoopFor(BB);
1487 if (!L) {
1488 continue;
1489 }
1490 BasicBlock *Header = L->getHeader();
1491 if (Header && BlockWeights[BB] > BlockWeights[Header]) {
1492 BlockWeights[Header] = BlockWeights[BB];
1493 }
1494 }
1495
1496 // Before propagation starts, build, for each block, a list of
1497 // unique predecessors and successors. This is necessary to handle
1498 // identical edges in multiway branches. Since we visit all blocks and all
1499 // edges of the CFG, it is cleaner to build these lists once at the start
1500 // of the pass.
1501 buildEdges(F);
1502
1503 // Propagate until we converge or we go past the iteration limit.
1504 while (Changed && I++ < SampleProfileMaxPropagateIterations) {
1505 Changed = propagateThroughEdges(F, false);
1506 }
1507
1508 // The first propagation propagates BB counts from annotated BBs to unknown
1509 // BBs. The 2nd propagation pass resets edges weights, and use all BB weights
1510 // to propagate edge weights.
1511 VisitedEdges.clear();
1512 Changed = true;
1513 while (Changed && I++ < SampleProfileMaxPropagateIterations) {
1514 Changed = propagateThroughEdges(F, false);
1515 }
1516
1517 // The 3rd propagation pass allows adjust annotated BB weights that are
1518 // obviously wrong.
1519 Changed = true;
1520 while (Changed && I++ < SampleProfileMaxPropagateIterations) {
1521 Changed = propagateThroughEdges(F, true);
1522 }
1523
1524 // Generate MD_prof metadata for every branch instruction using the
1525 // edge weights computed during propagation.
1526 LLVM_DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
1527 LLVMContext &Ctx = F.getContext();
1528 MDBuilder MDB(Ctx);
1529 for (auto &BI : F) {
1530 BasicBlock *BB = &BI;
1531
1532 if (BlockWeights[BB]) {
1533 for (auto &I : BB->getInstList()) {
1534 if (!isa<CallInst>(I) && !isa<InvokeInst>(I))
1535 continue;
1536 if (!cast<CallBase>(I).getCalledFunction()) {
1537 const DebugLoc &DLoc = I.getDebugLoc();
1538 if (!DLoc)
1539 continue;
1540 const DILocation *DIL = DLoc;
1541 uint32_t LineOffset = FunctionSamples::getOffset(DIL);
1542 uint32_t Discriminator = DIL->getBaseDiscriminator();
1543
1544 const FunctionSamples *FS = findFunctionSamples(I);
1545 if (!FS)
1546 continue;
1547 auto T = FS->findCallTargetMapAt(LineOffset, Discriminator);
1548 if (!T || T.get().empty())
1549 continue;
1550 SmallVector<InstrProfValueData, 2> SortedCallTargets =
1551 GetSortedValueDataFromCallTargets(T.get());
1552 uint64_t Sum;
1553 findIndirectCallFunctionSamples(I, Sum);
1554 annotateValueSite(*I.getParent()->getParent()->getParent(), I,
1555 SortedCallTargets, Sum, IPVK_IndirectCallTarget,
1556 SortedCallTargets.size());
1557 } else if (!isa<IntrinsicInst>(&I)) {
1558 I.setMetadata(LLVMContext::MD_prof,
1559 MDB.createBranchWeights(
1560 {static_cast<uint32_t>(BlockWeights[BB])}));
1561 }
1562 }
1563 }
1564 Instruction *TI = BB->getTerminator();
1565 if (TI->getNumSuccessors() == 1)
1566 continue;
1567 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
1568 continue;
1569
1570 DebugLoc BranchLoc = TI->getDebugLoc();
1571 LLVM_DEBUG(dbgs() << "\nGetting weights for branch at line "
1572 << ((BranchLoc) ? Twine(BranchLoc.getLine())
1573 : Twine("<UNKNOWN LOCATION>"))
1574 << ".\n");
1575 SmallVector<uint32_t, 4> Weights;
1576 uint32_t MaxWeight = 0;
1577 Instruction *MaxDestInst;
1578 for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
1579 BasicBlock *Succ = TI->getSuccessor(I);
1580 Edge E = std::make_pair(BB, Succ);
1581 uint64_t Weight = EdgeWeights[E];
1582 LLVM_DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
1583 // Use uint32_t saturated arithmetic to adjust the incoming weights,
1584 // if needed. Sample counts in profiles are 64-bit unsigned values,
1585 // but internally branch weights are expressed as 32-bit values.
1586 if (Weight > std::numeric_limits<uint32_t>::max()) {
1587 LLVM_DEBUG(dbgs() << " (saturated due to uint32_t overflow)");
1588 Weight = std::numeric_limits<uint32_t>::max();
1589 }
1590 // Weight is added by one to avoid propagation errors introduced by
1591 // 0 weights.
1592 Weights.push_back(static_cast<uint32_t>(Weight + 1));
1593 if (Weight != 0) {
1594 if (Weight > MaxWeight) {
1595 MaxWeight = Weight;
1596 MaxDestInst = Succ->getFirstNonPHIOrDbgOrLifetime();
1597 }
1598 }
1599 }
1600
1601 misexpect::verifyMisExpect(TI, Weights, TI->getContext());
1602
1603 uint64_t TempWeight;
1604 // Only set weights if there is at least one non-zero weight.
1605 // In any other case, let the analyzer set weights.
1606 // Do not set weights if the weights are present. In ThinLTO, the profile
1607 // annotation is done twice. If the first annotation already set the
1608 // weights, the second pass does not need to set it.
1609 if (MaxWeight > 0 && !TI->extractProfTotalWeight(TempWeight)) {
1610 LLVM_DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
1611 TI->setMetadata(LLVMContext::MD_prof,
1612 MDB.createBranchWeights(Weights));
1613 ORE->emit([&]() {
1614 return OptimizationRemark(DEBUG_TYPE, "PopularDest", MaxDestInst)
1615 << "most popular destination for conditional branches at "
1616 << ore::NV("CondBranchesLoc", BranchLoc);
1617 });
1618 } else {
1619 LLVM_DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
1620 }
1621 }
1622 }
1623
1624 /// Get the line number for the function header.
1625 ///
1626 /// This looks up function \p F in the current compilation unit and
1627 /// retrieves the line number where the function is defined. This is
1628 /// line 0 for all the samples read from the profile file. Every line
1629 /// number is relative to this line.
1630 ///
1631 /// \param F Function object to query.
1632 ///
1633 /// \returns the line number where \p F is defined. If it returns 0,
1634 /// it means that there is no debug information available for \p F.
getFunctionLoc(Function & F)1635 unsigned SampleProfileLoader::getFunctionLoc(Function &F) {
1636 if (DISubprogram *S = F.getSubprogram())
1637 return S->getLine();
1638
1639 if (NoWarnSampleUnused)
1640 return 0;
1641
1642 // If the start of \p F is missing, emit a diagnostic to inform the user
1643 // about the missed opportunity.
1644 F.getContext().diagnose(DiagnosticInfoSampleProfile(
1645 "No debug information found in function " + F.getName() +
1646 ": Function profile not used",
1647 DS_Warning));
1648 return 0;
1649 }
1650
computeDominanceAndLoopInfo(Function & F)1651 void SampleProfileLoader::computeDominanceAndLoopInfo(Function &F) {
1652 DT.reset(new DominatorTree);
1653 DT->recalculate(F);
1654
1655 PDT.reset(new PostDominatorTree(F));
1656
1657 LI.reset(new LoopInfo);
1658 LI->analyze(*DT);
1659 }
1660
1661 /// Generate branch weight metadata for all branches in \p F.
1662 ///
1663 /// Branch weights are computed out of instruction samples using a
1664 /// propagation heuristic. Propagation proceeds in 3 phases:
1665 ///
1666 /// 1- Assignment of block weights. All the basic blocks in the function
1667 /// are initial assigned the same weight as their most frequently
1668 /// executed instruction.
1669 ///
1670 /// 2- Creation of equivalence classes. Since samples may be missing from
1671 /// blocks, we can fill in the gaps by setting the weights of all the
1672 /// blocks in the same equivalence class to the same weight. To compute
1673 /// the concept of equivalence, we use dominance and loop information.
1674 /// Two blocks B1 and B2 are in the same equivalence class if B1
1675 /// dominates B2, B2 post-dominates B1 and both are in the same loop.
1676 ///
1677 /// 3- Propagation of block weights into edges. This uses a simple
1678 /// propagation heuristic. The following rules are applied to every
1679 /// block BB in the CFG:
1680 ///
1681 /// - If BB has a single predecessor/successor, then the weight
1682 /// of that edge is the weight of the block.
1683 ///
1684 /// - If all the edges are known except one, and the weight of the
1685 /// block is already known, the weight of the unknown edge will
1686 /// be the weight of the block minus the sum of all the known
1687 /// edges. If the sum of all the known edges is larger than BB's weight,
1688 /// we set the unknown edge weight to zero.
1689 ///
1690 /// - If there is a self-referential edge, and the weight of the block is
1691 /// known, the weight for that edge is set to the weight of the block
1692 /// minus the weight of the other incoming edges to that block (if
1693 /// known).
1694 ///
1695 /// Since this propagation is not guaranteed to finalize for every CFG, we
1696 /// only allow it to proceed for a limited number of iterations (controlled
1697 /// by -sample-profile-max-propagate-iterations).
1698 ///
1699 /// FIXME: Try to replace this propagation heuristic with a scheme
1700 /// that is guaranteed to finalize. A work-list approach similar to
1701 /// the standard value propagation algorithm used by SSA-CCP might
1702 /// work here.
1703 ///
1704 /// Once all the branch weights are computed, we emit the MD_prof
1705 /// metadata on BB using the computed values for each of its branches.
1706 ///
1707 /// \param F The function to query.
1708 ///
1709 /// \returns true if \p F was modified. Returns false, otherwise.
emitAnnotations(Function & F)1710 bool SampleProfileLoader::emitAnnotations(Function &F) {
1711 bool Changed = false;
1712
1713 if (getFunctionLoc(F) == 0)
1714 return false;
1715
1716 LLVM_DEBUG(dbgs() << "Line number for the first instruction in "
1717 << F.getName() << ": " << getFunctionLoc(F) << "\n");
1718
1719 DenseSet<GlobalValue::GUID> InlinedGUIDs;
1720 Changed |= inlineHotFunctions(F, InlinedGUIDs);
1721
1722 // Compute basic block weights.
1723 Changed |= computeBlockWeights(F);
1724
1725 if (Changed) {
1726 // Add an entry count to the function using the samples gathered at the
1727 // function entry.
1728 // Sets the GUIDs that are inlined in the profiled binary. This is used
1729 // for ThinLink to make correct liveness analysis, and also make the IR
1730 // match the profiled binary before annotation.
1731 F.setEntryCount(
1732 ProfileCount(Samples->getHeadSamples() + 1, Function::PCT_Real),
1733 &InlinedGUIDs);
1734
1735 // Compute dominance and loop info needed for propagation.
1736 computeDominanceAndLoopInfo(F);
1737
1738 // Find equivalence classes.
1739 findEquivalenceClasses(F);
1740
1741 // Propagate weights to all edges.
1742 propagateWeights(F);
1743 }
1744
1745 // If coverage checking was requested, compute it now.
1746 if (SampleProfileRecordCoverage) {
1747 unsigned Used = CoverageTracker.countUsedRecords(Samples, PSI);
1748 unsigned Total = CoverageTracker.countBodyRecords(Samples, PSI);
1749 unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
1750 if (Coverage < SampleProfileRecordCoverage) {
1751 F.getContext().diagnose(DiagnosticInfoSampleProfile(
1752 F.getSubprogram()->getFilename(), getFunctionLoc(F),
1753 Twine(Used) + " of " + Twine(Total) + " available profile records (" +
1754 Twine(Coverage) + "%) were applied",
1755 DS_Warning));
1756 }
1757 }
1758
1759 if (SampleProfileSampleCoverage) {
1760 uint64_t Used = CoverageTracker.getTotalUsedSamples();
1761 uint64_t Total = CoverageTracker.countBodySamples(Samples, PSI);
1762 unsigned Coverage = CoverageTracker.computeCoverage(Used, Total);
1763 if (Coverage < SampleProfileSampleCoverage) {
1764 F.getContext().diagnose(DiagnosticInfoSampleProfile(
1765 F.getSubprogram()->getFilename(), getFunctionLoc(F),
1766 Twine(Used) + " of " + Twine(Total) + " available profile samples (" +
1767 Twine(Coverage) + "%) were applied",
1768 DS_Warning));
1769 }
1770 }
1771 return Changed;
1772 }
1773
1774 char SampleProfileLoaderLegacyPass::ID = 0;
1775
1776 INITIALIZE_PASS_BEGIN(SampleProfileLoaderLegacyPass, "sample-profile",
1777 "Sample Profile loader", false, false)
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)1778 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1779 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
1780 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1781 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
1782 INITIALIZE_PASS_END(SampleProfileLoaderLegacyPass, "sample-profile",
1783 "Sample Profile loader", false, false)
1784
1785 std::vector<Function *>
1786 SampleProfileLoader::buildFunctionOrder(Module &M, CallGraph *CG) {
1787 std::vector<Function *> FunctionOrderList;
1788 FunctionOrderList.reserve(M.size());
1789
1790 if (!ProfileTopDownLoad || CG == nullptr) {
1791 if (ProfileMergeInlinee) {
1792 // Disable ProfileMergeInlinee if profile is not loaded in top down order,
1793 // because the profile for a function may be used for the profile
1794 // annotation of its outline copy before the profile merging of its
1795 // non-inlined inline instances, and that is not the way how
1796 // ProfileMergeInlinee is supposed to work.
1797 ProfileMergeInlinee = false;
1798 }
1799
1800 for (Function &F : M)
1801 if (!F.isDeclaration() && F.hasFnAttribute("use-sample-profile"))
1802 FunctionOrderList.push_back(&F);
1803 return FunctionOrderList;
1804 }
1805
1806 assert(&CG->getModule() == &M);
1807 scc_iterator<CallGraph *> CGI = scc_begin(CG);
1808 while (!CGI.isAtEnd()) {
1809 for (CallGraphNode *node : *CGI) {
1810 auto F = node->getFunction();
1811 if (F && !F->isDeclaration() && F->hasFnAttribute("use-sample-profile"))
1812 FunctionOrderList.push_back(F);
1813 }
1814 ++CGI;
1815 }
1816
1817 std::reverse(FunctionOrderList.begin(), FunctionOrderList.end());
1818 return FunctionOrderList;
1819 }
1820
doInitialization(Module & M)1821 bool SampleProfileLoader::doInitialization(Module &M) {
1822 auto &Ctx = M.getContext();
1823
1824 std::unique_ptr<SampleProfileReaderItaniumRemapper> RemapReader;
1825 auto ReaderOrErr =
1826 SampleProfileReader::create(Filename, Ctx, RemappingFilename);
1827 if (std::error_code EC = ReaderOrErr.getError()) {
1828 std::string Msg = "Could not open profile: " + EC.message();
1829 Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
1830 return false;
1831 }
1832 Reader = std::move(ReaderOrErr.get());
1833 Reader->collectFuncsFrom(M);
1834 ProfileIsValid = (Reader->read() == sampleprof_error::success);
1835 PSL = Reader->getProfileSymbolList();
1836
1837 // While profile-sample-accurate is on, ignore symbol list.
1838 ProfAccForSymsInList =
1839 ProfileAccurateForSymsInList && PSL && !ProfileSampleAccurate;
1840 if (ProfAccForSymsInList) {
1841 NamesInProfile.clear();
1842 if (auto NameTable = Reader->getNameTable())
1843 NamesInProfile.insert(NameTable->begin(), NameTable->end());
1844 }
1845
1846 return true;
1847 }
1848
createSampleProfileLoaderPass()1849 ModulePass *llvm::createSampleProfileLoaderPass() {
1850 return new SampleProfileLoaderLegacyPass();
1851 }
1852
createSampleProfileLoaderPass(StringRef Name)1853 ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) {
1854 return new SampleProfileLoaderLegacyPass(Name);
1855 }
1856
runOnModule(Module & M,ModuleAnalysisManager * AM,ProfileSummaryInfo * _PSI,CallGraph * CG)1857 bool SampleProfileLoader::runOnModule(Module &M, ModuleAnalysisManager *AM,
1858 ProfileSummaryInfo *_PSI, CallGraph *CG) {
1859 if (!ProfileIsValid)
1860 return false;
1861 GUIDToFuncNameMapper Mapper(M, *Reader, GUIDToFuncNameMap);
1862
1863 PSI = _PSI;
1864 if (M.getProfileSummary(/* IsCS */ false) == nullptr) {
1865 M.setProfileSummary(Reader->getSummary().getMD(M.getContext()),
1866 ProfileSummary::PSK_Sample);
1867 PSI->refresh();
1868 }
1869 // Compute the total number of samples collected in this profile.
1870 for (const auto &I : Reader->getProfiles())
1871 TotalCollectedSamples += I.second.getTotalSamples();
1872
1873 // Populate the symbol map.
1874 for (const auto &N_F : M.getValueSymbolTable()) {
1875 StringRef OrigName = N_F.getKey();
1876 Function *F = dyn_cast<Function>(N_F.getValue());
1877 if (F == nullptr)
1878 continue;
1879 SymbolMap[OrigName] = F;
1880 auto pos = OrigName.find('.');
1881 if (pos != StringRef::npos) {
1882 StringRef NewName = OrigName.substr(0, pos);
1883 auto r = SymbolMap.insert(std::make_pair(NewName, F));
1884 // Failiing to insert means there is already an entry in SymbolMap,
1885 // thus there are multiple functions that are mapped to the same
1886 // stripped name. In this case of name conflicting, set the value
1887 // to nullptr to avoid confusion.
1888 if (!r.second)
1889 r.first->second = nullptr;
1890 }
1891 }
1892
1893 bool retval = false;
1894 for (auto F : buildFunctionOrder(M, CG)) {
1895 assert(!F->isDeclaration());
1896 clearFunctionData();
1897 retval |= runOnFunction(*F, AM);
1898 }
1899
1900 // Account for cold calls not inlined....
1901 for (const std::pair<Function *, NotInlinedProfileInfo> &pair :
1902 notInlinedCallInfo)
1903 updateProfileCallee(pair.first, pair.second.entryCount);
1904
1905 return retval;
1906 }
1907
runOnModule(Module & M)1908 bool SampleProfileLoaderLegacyPass::runOnModule(Module &M) {
1909 ACT = &getAnalysis<AssumptionCacheTracker>();
1910 TTIWP = &getAnalysis<TargetTransformInfoWrapperPass>();
1911 TLIWP = &getAnalysis<TargetLibraryInfoWrapperPass>();
1912 ProfileSummaryInfo *PSI =
1913 &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
1914 return SampleLoader.runOnModule(M, nullptr, PSI, nullptr);
1915 }
1916
runOnFunction(Function & F,ModuleAnalysisManager * AM)1917 bool SampleProfileLoader::runOnFunction(Function &F, ModuleAnalysisManager *AM) {
1918
1919 DILocation2SampleMap.clear();
1920 // By default the entry count is initialized to -1, which will be treated
1921 // conservatively by getEntryCount as the same as unknown (None). This is
1922 // to avoid newly added code to be treated as cold. If we have samples
1923 // this will be overwritten in emitAnnotations.
1924 uint64_t initialEntryCount = -1;
1925
1926 ProfAccForSymsInList = ProfileAccurateForSymsInList && PSL;
1927 if (ProfileSampleAccurate || F.hasFnAttribute("profile-sample-accurate")) {
1928 // initialize all the function entry counts to 0. It means all the
1929 // functions without profile will be regarded as cold.
1930 initialEntryCount = 0;
1931 // profile-sample-accurate is a user assertion which has a higher precedence
1932 // than symbol list. When profile-sample-accurate is on, ignore symbol list.
1933 ProfAccForSymsInList = false;
1934 }
1935
1936 // PSL -- profile symbol list include all the symbols in sampled binary.
1937 // If ProfileAccurateForSymsInList is enabled, PSL is used to treat
1938 // old functions without samples being cold, without having to worry
1939 // about new and hot functions being mistakenly treated as cold.
1940 if (ProfAccForSymsInList) {
1941 // Initialize the entry count to 0 for functions in the list.
1942 if (PSL->contains(F.getName()))
1943 initialEntryCount = 0;
1944
1945 // Function in the symbol list but without sample will be regarded as
1946 // cold. To minimize the potential negative performance impact it could
1947 // have, we want to be a little conservative here saying if a function
1948 // shows up in the profile, no matter as outline function, inline instance
1949 // or call targets, treat the function as not being cold. This will handle
1950 // the cases such as most callsites of a function are inlined in sampled
1951 // binary but not inlined in current build (because of source code drift,
1952 // imprecise debug information, or the callsites are all cold individually
1953 // but not cold accumulatively...), so the outline function showing up as
1954 // cold in sampled binary will actually not be cold after current build.
1955 StringRef CanonName = FunctionSamples::getCanonicalFnName(F);
1956 if (NamesInProfile.count(CanonName))
1957 initialEntryCount = -1;
1958 }
1959
1960 F.setEntryCount(ProfileCount(initialEntryCount, Function::PCT_Real));
1961 std::unique_ptr<OptimizationRemarkEmitter> OwnedORE;
1962 if (AM) {
1963 auto &FAM =
1964 AM->getResult<FunctionAnalysisManagerModuleProxy>(*F.getParent())
1965 .getManager();
1966 ORE = &FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
1967 } else {
1968 OwnedORE = std::make_unique<OptimizationRemarkEmitter>(&F);
1969 ORE = OwnedORE.get();
1970 }
1971 Samples = Reader->getSamplesFor(F);
1972 if (Samples && !Samples->empty())
1973 return emitAnnotations(F);
1974 return false;
1975 }
1976
run(Module & M,ModuleAnalysisManager & AM)1977 PreservedAnalyses SampleProfileLoaderPass::run(Module &M,
1978 ModuleAnalysisManager &AM) {
1979 FunctionAnalysisManager &FAM =
1980 AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1981
1982 auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & {
1983 return FAM.getResult<AssumptionAnalysis>(F);
1984 };
1985 auto GetTTI = [&](Function &F) -> TargetTransformInfo & {
1986 return FAM.getResult<TargetIRAnalysis>(F);
1987 };
1988 auto GetTLI = [&](Function &F) -> const TargetLibraryInfo & {
1989 return FAM.getResult<TargetLibraryAnalysis>(F);
1990 };
1991
1992 SampleProfileLoader SampleLoader(
1993 ProfileFileName.empty() ? SampleProfileFile : ProfileFileName,
1994 ProfileRemappingFileName.empty() ? SampleProfileRemappingFile
1995 : ProfileRemappingFileName,
1996 IsThinLTOPreLink, GetAssumptionCache, GetTTI, GetTLI);
1997
1998 if (!SampleLoader.doInitialization(M))
1999 return PreservedAnalyses::all();
2000
2001 ProfileSummaryInfo *PSI = &AM.getResult<ProfileSummaryAnalysis>(M);
2002 CallGraph &CG = AM.getResult<CallGraphAnalysis>(M);
2003 if (!SampleLoader.runOnModule(M, &AM, PSI, &CG))
2004 return PreservedAnalyses::all();
2005
2006 return PreservedAnalyses::none();
2007 }
2008