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/PriorityQueue.h"
30 #include "llvm/ADT/SCCIterator.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/SmallSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/StringMap.h"
36 #include "llvm/ADT/StringRef.h"
37 #include "llvm/ADT/Twine.h"
38 #include "llvm/Analysis/AssumptionCache.h"
39 #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
40 #include "llvm/Analysis/CallGraph.h"
41 #include "llvm/Analysis/CallGraphSCCPass.h"
42 #include "llvm/Analysis/InlineAdvisor.h"
43 #include "llvm/Analysis/InlineCost.h"
44 #include "llvm/Analysis/LoopInfo.h"
45 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
46 #include "llvm/Analysis/PostDominators.h"
47 #include "llvm/Analysis/ProfileSummaryInfo.h"
48 #include "llvm/Analysis/ReplayInlineAdvisor.h"
49 #include "llvm/Analysis/TargetLibraryInfo.h"
50 #include "llvm/Analysis/TargetTransformInfo.h"
51 #include "llvm/IR/BasicBlock.h"
52 #include "llvm/IR/CFG.h"
53 #include "llvm/IR/DebugInfoMetadata.h"
54 #include "llvm/IR/DebugLoc.h"
55 #include "llvm/IR/DiagnosticInfo.h"
56 #include "llvm/IR/Dominators.h"
57 #include "llvm/IR/Function.h"
58 #include "llvm/IR/GlobalValue.h"
59 #include "llvm/IR/InstrTypes.h"
60 #include "llvm/IR/Instruction.h"
61 #include "llvm/IR/Instructions.h"
62 #include "llvm/IR/IntrinsicInst.h"
63 #include "llvm/IR/LLVMContext.h"
64 #include "llvm/IR/MDBuilder.h"
65 #include "llvm/IR/Module.h"
66 #include "llvm/IR/PassManager.h"
67 #include "llvm/IR/ValueSymbolTable.h"
68 #include "llvm/InitializePasses.h"
69 #include "llvm/Pass.h"
70 #include "llvm/ProfileData/InstrProf.h"
71 #include "llvm/ProfileData/SampleProf.h"
72 #include "llvm/ProfileData/SampleProfReader.h"
73 #include "llvm/Support/Casting.h"
74 #include "llvm/Support/CommandLine.h"
75 #include "llvm/Support/Debug.h"
76 #include "llvm/Support/ErrorHandling.h"
77 #include "llvm/Support/ErrorOr.h"
78 #include "llvm/Support/GenericDomTree.h"
79 #include "llvm/Support/raw_ostream.h"
80 #include "llvm/Transforms/IPO.h"
81 #include "llvm/Transforms/IPO/ProfiledCallGraph.h"
82 #include "llvm/Transforms/IPO/SampleContextTracker.h"
83 #include "llvm/Transforms/IPO/SampleProfileProbe.h"
84 #include "llvm/Transforms/Instrumentation.h"
85 #include "llvm/Transforms/Utils/CallPromotionUtils.h"
86 #include "llvm/Transforms/Utils/Cloning.h"
87 #include "llvm/Transforms/Utils/SampleProfileLoaderBaseImpl.h"
88 #include "llvm/Transforms/Utils/SampleProfileLoaderBaseUtil.h"
89 #include <algorithm>
90 #include <cassert>
91 #include <cstdint>
92 #include <functional>
93 #include <limits>
94 #include <map>
95 #include <memory>
96 #include <queue>
97 #include <string>
98 #include <system_error>
99 #include <utility>
100 #include <vector>
101
102 using namespace llvm;
103 using namespace sampleprof;
104 using namespace llvm::sampleprofutil;
105 using ProfileCount = Function::ProfileCount;
106 #define DEBUG_TYPE "sample-profile"
107 #define CSINLINE_DEBUG DEBUG_TYPE "-inline"
108
109 STATISTIC(NumCSInlined,
110 "Number of functions inlined with context sensitive profile");
111 STATISTIC(NumCSNotInlined,
112 "Number of functions not inlined with context sensitive profile");
113 STATISTIC(NumMismatchedProfile,
114 "Number of functions with CFG mismatched profile");
115 STATISTIC(NumMatchedProfile, "Number of functions with CFG matched profile");
116 STATISTIC(NumDuplicatedInlinesite,
117 "Number of inlined callsites with a partial distribution factor");
118
119 STATISTIC(NumCSInlinedHitMinLimit,
120 "Number of functions with FDO inline stopped due to min size limit");
121 STATISTIC(NumCSInlinedHitMaxLimit,
122 "Number of functions with FDO inline stopped due to max size limit");
123 STATISTIC(
124 NumCSInlinedHitGrowthLimit,
125 "Number of functions with FDO inline stopped due to growth size limit");
126
127 // Command line option to specify the file to read samples from. This is
128 // mainly used for debugging.
129 static cl::opt<std::string> SampleProfileFile(
130 "sample-profile-file", cl::init(""), cl::value_desc("filename"),
131 cl::desc("Profile file loaded by -sample-profile"), cl::Hidden);
132
133 // The named file contains a set of transformations that may have been applied
134 // to the symbol names between the program from which the sample data was
135 // collected and the current program's symbols.
136 static cl::opt<std::string> SampleProfileRemappingFile(
137 "sample-profile-remapping-file", cl::init(""), cl::value_desc("filename"),
138 cl::desc("Profile remapping file loaded by -sample-profile"), cl::Hidden);
139
140 static cl::opt<bool> ProfileSampleAccurate(
141 "profile-sample-accurate", cl::Hidden, cl::init(false),
142 cl::desc("If the sample profile is accurate, we will mark all un-sampled "
143 "callsite and function as having 0 samples. Otherwise, treat "
144 "un-sampled callsites and functions conservatively as unknown. "));
145
146 static cl::opt<bool> ProfileAccurateForSymsInList(
147 "profile-accurate-for-symsinlist", cl::Hidden, cl::ZeroOrMore,
148 cl::init(true),
149 cl::desc("For symbols in profile symbol list, regard their profiles to "
150 "be accurate. It may be overriden by profile-sample-accurate. "));
151
152 static cl::opt<bool> ProfileMergeInlinee(
153 "sample-profile-merge-inlinee", cl::Hidden, cl::init(true),
154 cl::desc("Merge past inlinee's profile to outline version if sample "
155 "profile loader decided not to inline a call site. It will "
156 "only be enabled when top-down order of profile loading is "
157 "enabled. "));
158
159 static cl::opt<bool> ProfileTopDownLoad(
160 "sample-profile-top-down-load", cl::Hidden, cl::init(true),
161 cl::desc("Do profile annotation and inlining for functions in top-down "
162 "order of call graph during sample profile loading. It only "
163 "works for new pass manager. "));
164
165 static cl::opt<bool>
166 UseProfiledCallGraph("use-profiled-call-graph", cl::init(true), cl::Hidden,
167 cl::desc("Process functions in a top-down order "
168 "defined by the profiled call graph when "
169 "-sample-profile-top-down-load is on."));
170
171 static cl::opt<bool> ProfileSizeInline(
172 "sample-profile-inline-size", cl::Hidden, cl::init(false),
173 cl::desc("Inline cold call sites in profile loader if it's beneficial "
174 "for code size."));
175
176 cl::opt<int> ProfileInlineGrowthLimit(
177 "sample-profile-inline-growth-limit", cl::Hidden, cl::init(12),
178 cl::desc("The size growth ratio limit for proirity-based sample profile "
179 "loader inlining."));
180
181 cl::opt<int> ProfileInlineLimitMin(
182 "sample-profile-inline-limit-min", cl::Hidden, cl::init(100),
183 cl::desc("The lower bound of size growth limit for "
184 "proirity-based sample profile loader inlining."));
185
186 cl::opt<int> ProfileInlineLimitMax(
187 "sample-profile-inline-limit-max", cl::Hidden, cl::init(10000),
188 cl::desc("The upper bound of size growth limit for "
189 "proirity-based sample profile loader inlining."));
190
191 cl::opt<int> SampleHotCallSiteThreshold(
192 "sample-profile-hot-inline-threshold", cl::Hidden, cl::init(3000),
193 cl::desc("Hot callsite threshold for proirity-based sample profile loader "
194 "inlining."));
195
196 cl::opt<int> SampleColdCallSiteThreshold(
197 "sample-profile-cold-inline-threshold", cl::Hidden, cl::init(45),
198 cl::desc("Threshold for inlining cold callsites"));
199
200 static cl::opt<unsigned> ProfileICPRelativeHotness(
201 "sample-profile-icp-relative-hotness", cl::Hidden, cl::init(25),
202 cl::desc(
203 "Relative hotness percentage threshold for indirect "
204 "call promotion in proirity-based sample profile loader inlining."));
205
206 static cl::opt<unsigned> ProfileICPRelativeHotnessSkip(
207 "sample-profile-icp-relative-hotness-skip", cl::Hidden, cl::init(1),
208 cl::desc(
209 "Skip relative hotness check for ICP up to given number of targets."));
210
211 static cl::opt<bool> CallsitePrioritizedInline(
212 "sample-profile-prioritized-inline", cl::Hidden, cl::ZeroOrMore,
213 cl::init(false),
214 cl::desc("Use call site prioritized inlining for sample profile loader."
215 "Currently only CSSPGO is supported."));
216
217 static cl::opt<std::string> ProfileInlineReplayFile(
218 "sample-profile-inline-replay", cl::init(""), cl::value_desc("filename"),
219 cl::desc(
220 "Optimization remarks file containing inline remarks to be replayed "
221 "by inlining from sample profile loader."),
222 cl::Hidden);
223
224 static cl::opt<unsigned>
225 MaxNumPromotions("sample-profile-icp-max-prom", cl::init(3), cl::Hidden,
226 cl::ZeroOrMore,
227 cl::desc("Max number of promotions for a single indirect "
228 "call callsite in sample profile loader"));
229
230 static cl::opt<bool> OverwriteExistingWeights(
231 "overwrite-existing-weights", cl::Hidden, cl::init(false),
232 cl::desc("Ignore existing branch weights on IR and always overwrite."));
233
234 namespace {
235
236 using BlockWeightMap = DenseMap<const BasicBlock *, uint64_t>;
237 using EquivalenceClassMap = DenseMap<const BasicBlock *, const BasicBlock *>;
238 using Edge = std::pair<const BasicBlock *, const BasicBlock *>;
239 using EdgeWeightMap = DenseMap<Edge, uint64_t>;
240 using BlockEdgeMap =
241 DenseMap<const BasicBlock *, SmallVector<const BasicBlock *, 8>>;
242
243 class GUIDToFuncNameMapper {
244 public:
GUIDToFuncNameMapper(Module & M,SampleProfileReader & Reader,DenseMap<uint64_t,StringRef> & GUIDToFuncNameMap)245 GUIDToFuncNameMapper(Module &M, SampleProfileReader &Reader,
246 DenseMap<uint64_t, StringRef> &GUIDToFuncNameMap)
247 : CurrentReader(Reader), CurrentModule(M),
248 CurrentGUIDToFuncNameMap(GUIDToFuncNameMap) {
249 if (!CurrentReader.useMD5())
250 return;
251
252 for (const auto &F : CurrentModule) {
253 StringRef OrigName = F.getName();
254 CurrentGUIDToFuncNameMap.insert(
255 {Function::getGUID(OrigName), OrigName});
256
257 // Local to global var promotion used by optimization like thinlto
258 // will rename the var and add suffix like ".llvm.xxx" to the
259 // original local name. In sample profile, the suffixes of function
260 // names are all stripped. Since it is possible that the mapper is
261 // built in post-thin-link phase and var promotion has been done,
262 // we need to add the substring of function name without the suffix
263 // into the GUIDToFuncNameMap.
264 StringRef CanonName = FunctionSamples::getCanonicalFnName(F);
265 if (CanonName != OrigName)
266 CurrentGUIDToFuncNameMap.insert(
267 {Function::getGUID(CanonName), CanonName});
268 }
269
270 // Update GUIDToFuncNameMap for each function including inlinees.
271 SetGUIDToFuncNameMapForAll(&CurrentGUIDToFuncNameMap);
272 }
273
~GUIDToFuncNameMapper()274 ~GUIDToFuncNameMapper() {
275 if (!CurrentReader.useMD5())
276 return;
277
278 CurrentGUIDToFuncNameMap.clear();
279
280 // Reset GUIDToFuncNameMap for of each function as they're no
281 // longer valid at this point.
282 SetGUIDToFuncNameMapForAll(nullptr);
283 }
284
285 private:
SetGUIDToFuncNameMapForAll(DenseMap<uint64_t,StringRef> * Map)286 void SetGUIDToFuncNameMapForAll(DenseMap<uint64_t, StringRef> *Map) {
287 std::queue<FunctionSamples *> FSToUpdate;
288 for (auto &IFS : CurrentReader.getProfiles()) {
289 FSToUpdate.push(&IFS.second);
290 }
291
292 while (!FSToUpdate.empty()) {
293 FunctionSamples *FS = FSToUpdate.front();
294 FSToUpdate.pop();
295 FS->GUIDToFuncNameMap = Map;
296 for (const auto &ICS : FS->getCallsiteSamples()) {
297 const FunctionSamplesMap &FSMap = ICS.second;
298 for (auto &IFS : FSMap) {
299 FunctionSamples &FS = const_cast<FunctionSamples &>(IFS.second);
300 FSToUpdate.push(&FS);
301 }
302 }
303 }
304 }
305
306 SampleProfileReader &CurrentReader;
307 Module &CurrentModule;
308 DenseMap<uint64_t, StringRef> &CurrentGUIDToFuncNameMap;
309 };
310
311 // Inline candidate used by iterative callsite prioritized inliner
312 struct InlineCandidate {
313 CallBase *CallInstr;
314 const FunctionSamples *CalleeSamples;
315 // Prorated callsite count, which will be used to guide inlining. For example,
316 // if a callsite is duplicated in LTO prelink, then in LTO postlink the two
317 // copies will get their own distribution factors and their prorated counts
318 // will be used to decide if they should be inlined independently.
319 uint64_t CallsiteCount;
320 // Call site distribution factor to prorate the profile samples for a
321 // duplicated callsite. Default value is 1.0.
322 float CallsiteDistribution;
323 };
324
325 // Inline candidate comparer using call site weight
326 struct CandidateComparer {
operator ()__anonae0656530111::CandidateComparer327 bool operator()(const InlineCandidate &LHS, const InlineCandidate &RHS) {
328 if (LHS.CallsiteCount != RHS.CallsiteCount)
329 return LHS.CallsiteCount < RHS.CallsiteCount;
330
331 const FunctionSamples *LCS = LHS.CalleeSamples;
332 const FunctionSamples *RCS = RHS.CalleeSamples;
333 assert(LCS && RCS && "Expect non-null FunctionSamples");
334
335 // Tie breaker using number of samples try to favor smaller functions first
336 if (LCS->getBodySamples().size() != RCS->getBodySamples().size())
337 return LCS->getBodySamples().size() > RCS->getBodySamples().size();
338
339 // Tie breaker using GUID so we have stable/deterministic inlining order
340 return LCS->getGUID(LCS->getName()) < RCS->getGUID(RCS->getName());
341 }
342 };
343
344 using CandidateQueue =
345 PriorityQueue<InlineCandidate, std::vector<InlineCandidate>,
346 CandidateComparer>;
347
348 /// Sample profile pass.
349 ///
350 /// This pass reads profile data from the file specified by
351 /// -sample-profile-file and annotates every affected function with the
352 /// profile information found in that file.
353 class SampleProfileLoader final
354 : public SampleProfileLoaderBaseImpl<BasicBlock> {
355 public:
SampleProfileLoader(StringRef Name,StringRef RemapName,ThinOrFullLTOPhase LTOPhase,std::function<AssumptionCache & (Function &)> GetAssumptionCache,std::function<TargetTransformInfo & (Function &)> GetTargetTransformInfo,std::function<const TargetLibraryInfo & (Function &)> GetTLI)356 SampleProfileLoader(
357 StringRef Name, StringRef RemapName, ThinOrFullLTOPhase LTOPhase,
358 std::function<AssumptionCache &(Function &)> GetAssumptionCache,
359 std::function<TargetTransformInfo &(Function &)> GetTargetTransformInfo,
360 std::function<const TargetLibraryInfo &(Function &)> GetTLI)
361 : SampleProfileLoaderBaseImpl(std::string(Name)),
362 GetAC(std::move(GetAssumptionCache)),
363 GetTTI(std::move(GetTargetTransformInfo)), GetTLI(std::move(GetTLI)),
364 RemappingFilename(std::string(RemapName)), LTOPhase(LTOPhase) {}
365
366 bool doInitialization(Module &M, FunctionAnalysisManager *FAM = nullptr);
367 bool runOnModule(Module &M, ModuleAnalysisManager *AM,
368 ProfileSummaryInfo *_PSI, CallGraph *CG);
369
370 protected:
371 bool runOnFunction(Function &F, ModuleAnalysisManager *AM);
372 bool emitAnnotations(Function &F);
373 ErrorOr<uint64_t> getInstWeight(const Instruction &I) override;
374 ErrorOr<uint64_t> getProbeWeight(const Instruction &I);
375 const FunctionSamples *findCalleeFunctionSamples(const CallBase &I) const;
376 const FunctionSamples *
377 findFunctionSamples(const Instruction &I) const override;
378 std::vector<const FunctionSamples *>
379 findIndirectCallFunctionSamples(const Instruction &I, uint64_t &Sum) const;
380 void findExternalInlineCandidate(const FunctionSamples *Samples,
381 DenseSet<GlobalValue::GUID> &InlinedGUIDs,
382 const StringMap<Function *> &SymbolMap,
383 uint64_t Threshold);
384 // Attempt to promote indirect call and also inline the promoted call
385 bool tryPromoteAndInlineCandidate(
386 Function &F, InlineCandidate &Candidate, uint64_t SumOrigin,
387 uint64_t &Sum, SmallVector<CallBase *, 8> *InlinedCallSites = nullptr);
388 bool inlineHotFunctions(Function &F,
389 DenseSet<GlobalValue::GUID> &InlinedGUIDs);
390 InlineCost shouldInlineCandidate(InlineCandidate &Candidate);
391 bool getInlineCandidate(InlineCandidate *NewCandidate, CallBase *CB);
392 bool
393 tryInlineCandidate(InlineCandidate &Candidate,
394 SmallVector<CallBase *, 8> *InlinedCallSites = nullptr);
395 bool
396 inlineHotFunctionsWithPriority(Function &F,
397 DenseSet<GlobalValue::GUID> &InlinedGUIDs);
398 // Inline cold/small functions in addition to hot ones
399 bool shouldInlineColdCallee(CallBase &CallInst);
400 void emitOptimizationRemarksForInlineCandidates(
401 const SmallVectorImpl<CallBase *> &Candidates, const Function &F,
402 bool Hot);
403 std::vector<Function *> buildFunctionOrder(Module &M, CallGraph *CG);
404 std::unique_ptr<ProfiledCallGraph> buildProfiledCallGraph(CallGraph &CG);
405 void generateMDProfMetadata(Function &F);
406
407 /// Map from function name to Function *. Used to find the function from
408 /// the function name. If the function name contains suffix, additional
409 /// entry is added to map from the stripped name to the function if there
410 /// is one-to-one mapping.
411 StringMap<Function *> SymbolMap;
412
413 std::function<AssumptionCache &(Function &)> GetAC;
414 std::function<TargetTransformInfo &(Function &)> GetTTI;
415 std::function<const TargetLibraryInfo &(Function &)> GetTLI;
416
417 /// Profile tracker for different context.
418 std::unique_ptr<SampleContextTracker> ContextTracker;
419
420 /// Name of the profile remapping file to load.
421 std::string RemappingFilename;
422
423 /// Flag indicating whether input profile is context-sensitive
424 bool ProfileIsCS = false;
425
426 /// Flag indicating which LTO/ThinLTO phase the pass is invoked in.
427 ///
428 /// We need to know the LTO phase because for example in ThinLTOPrelink
429 /// phase, in annotation, we should not promote indirect calls. Instead,
430 /// we will mark GUIDs that needs to be annotated to the function.
431 ThinOrFullLTOPhase LTOPhase;
432
433 /// Profle Symbol list tells whether a function name appears in the binary
434 /// used to generate the current profile.
435 std::unique_ptr<ProfileSymbolList> PSL;
436
437 /// Total number of samples collected in this profile.
438 ///
439 /// This is the sum of all the samples collected in all the functions executed
440 /// at runtime.
441 uint64_t TotalCollectedSamples = 0;
442
443 // Information recorded when we declined to inline a call site
444 // because we have determined it is too cold is accumulated for
445 // each callee function. Initially this is just the entry count.
446 struct NotInlinedProfileInfo {
447 uint64_t entryCount;
448 };
449 DenseMap<Function *, NotInlinedProfileInfo> notInlinedCallInfo;
450
451 // GUIDToFuncNameMap saves the mapping from GUID to the symbol name, for
452 // all the function symbols defined or declared in current module.
453 DenseMap<uint64_t, StringRef> GUIDToFuncNameMap;
454
455 // All the Names used in FunctionSamples including outline function
456 // names, inline instance names and call target names.
457 StringSet<> NamesInProfile;
458
459 // For symbol in profile symbol list, whether to regard their profiles
460 // to be accurate. It is mainly decided by existance of profile symbol
461 // list and -profile-accurate-for-symsinlist flag, but it can be
462 // overriden by -profile-sample-accurate or profile-sample-accurate
463 // attribute.
464 bool ProfAccForSymsInList;
465
466 // External inline advisor used to replay inline decision from remarks.
467 std::unique_ptr<ReplayInlineAdvisor> ExternalInlineAdvisor;
468
469 // A pseudo probe helper to correlate the imported sample counts.
470 std::unique_ptr<PseudoProbeManager> ProbeManager;
471 };
472
473 class SampleProfileLoaderLegacyPass : public ModulePass {
474 public:
475 // Class identification, replacement for typeinfo
476 static char ID;
477
SampleProfileLoaderLegacyPass(StringRef Name=SampleProfileFile,ThinOrFullLTOPhase LTOPhase=ThinOrFullLTOPhase::None)478 SampleProfileLoaderLegacyPass(
479 StringRef Name = SampleProfileFile,
480 ThinOrFullLTOPhase LTOPhase = ThinOrFullLTOPhase::None)
481 : ModulePass(ID), SampleLoader(
482 Name, SampleProfileRemappingFile, LTOPhase,
483 [&](Function &F) -> AssumptionCache & {
484 return ACT->getAssumptionCache(F);
485 },
__anonae0656530302(Function &F) 486 [&](Function &F) -> TargetTransformInfo & {
487 return TTIWP->getTTI(F);
488 },
__anonae0656530402(Function &F) 489 [&](Function &F) -> TargetLibraryInfo & {
490 return TLIWP->getTLI(F);
491 }) {
492 initializeSampleProfileLoaderLegacyPassPass(
493 *PassRegistry::getPassRegistry());
494 }
495
dump()496 void dump() { SampleLoader.dump(); }
497
doInitialization(Module & M)498 bool doInitialization(Module &M) override {
499 return SampleLoader.doInitialization(M);
500 }
501
getPassName() const502 StringRef getPassName() const override { return "Sample profile pass"; }
503 bool runOnModule(Module &M) override;
504
getAnalysisUsage(AnalysisUsage & AU) const505 void getAnalysisUsage(AnalysisUsage &AU) const override {
506 AU.addRequired<AssumptionCacheTracker>();
507 AU.addRequired<TargetTransformInfoWrapperPass>();
508 AU.addRequired<TargetLibraryInfoWrapperPass>();
509 AU.addRequired<ProfileSummaryInfoWrapperPass>();
510 }
511
512 private:
513 SampleProfileLoader SampleLoader;
514 AssumptionCacheTracker *ACT = nullptr;
515 TargetTransformInfoWrapperPass *TTIWP = nullptr;
516 TargetLibraryInfoWrapperPass *TLIWP = nullptr;
517 };
518
519 } // end anonymous namespace
520
getInstWeight(const Instruction & Inst)521 ErrorOr<uint64_t> SampleProfileLoader::getInstWeight(const Instruction &Inst) {
522 if (FunctionSamples::ProfileIsProbeBased)
523 return getProbeWeight(Inst);
524
525 const DebugLoc &DLoc = Inst.getDebugLoc();
526 if (!DLoc)
527 return std::error_code();
528
529 // Ignore all intrinsics, phinodes and branch instructions.
530 // Branch and phinodes instruction usually contains debug info from sources
531 // outside of the residing basic block, thus we ignore them during annotation.
532 if (isa<BranchInst>(Inst) || isa<IntrinsicInst>(Inst) || isa<PHINode>(Inst))
533 return std::error_code();
534
535 // For non-CS profile, if a direct call/invoke instruction is inlined in
536 // profile (findCalleeFunctionSamples returns non-empty result), but not
537 // inlined here, it means that the inlined callsite has no sample, thus the
538 // call instruction should have 0 count.
539 // For CS profile, the callsite count of previously inlined callees is
540 // populated with the entry count of the callees.
541 if (!ProfileIsCS)
542 if (const auto *CB = dyn_cast<CallBase>(&Inst))
543 if (!CB->isIndirectCall() && findCalleeFunctionSamples(*CB))
544 return 0;
545
546 return getInstWeightImpl(Inst);
547 }
548
549 // Here use error_code to represent: 1) The dangling probe. 2) Ignore the weight
550 // of non-probe instruction. So if all instructions of the BB give error_code,
551 // tell the inference algorithm to infer the BB weight.
getProbeWeight(const Instruction & Inst)552 ErrorOr<uint64_t> SampleProfileLoader::getProbeWeight(const Instruction &Inst) {
553 assert(FunctionSamples::ProfileIsProbeBased &&
554 "Profile is not pseudo probe based");
555 Optional<PseudoProbe> Probe = extractProbe(Inst);
556 // Ignore the non-probe instruction. If none of the instruction in the BB is
557 // probe, we choose to infer the BB's weight.
558 if (!Probe)
559 return std::error_code();
560
561 const FunctionSamples *FS = findFunctionSamples(Inst);
562 // If none of the instruction has FunctionSample, we choose to return zero
563 // value sample to indicate the BB is cold. This could happen when the
564 // instruction is from inlinee and no profile data is found.
565 // FIXME: This should not be affected by the source drift issue as 1) if the
566 // newly added function is top-level inliner, it won't match the CFG checksum
567 // in the function profile or 2) if it's the inlinee, the inlinee should have
568 // a profile, otherwise it wouldn't be inlined. For non-probe based profile,
569 // we can improve it by adding a switch for profile-sample-block-accurate for
570 // block level counts in the future.
571 if (!FS)
572 return 0;
573
574 // For non-CS profile, If a direct call/invoke instruction is inlined in
575 // profile (findCalleeFunctionSamples returns non-empty result), but not
576 // inlined here, it means that the inlined callsite has no sample, thus the
577 // call instruction should have 0 count.
578 // For CS profile, the callsite count of previously inlined callees is
579 // populated with the entry count of the callees.
580 if (!ProfileIsCS)
581 if (const auto *CB = dyn_cast<CallBase>(&Inst))
582 if (!CB->isIndirectCall() && findCalleeFunctionSamples(*CB))
583 return 0;
584
585 const ErrorOr<uint64_t> &R = FS->findSamplesAt(Probe->Id, 0);
586 if (R) {
587 uint64_t Samples = R.get() * Probe->Factor;
588 bool FirstMark = CoverageTracker.markSamplesUsed(FS, Probe->Id, 0, Samples);
589 if (FirstMark) {
590 ORE->emit([&]() {
591 OptimizationRemarkAnalysis Remark(DEBUG_TYPE, "AppliedSamples", &Inst);
592 Remark << "Applied " << ore::NV("NumSamples", Samples);
593 Remark << " samples from profile (ProbeId=";
594 Remark << ore::NV("ProbeId", Probe->Id);
595 Remark << ", Factor=";
596 Remark << ore::NV("Factor", Probe->Factor);
597 Remark << ", OriginalSamples=";
598 Remark << ore::NV("OriginalSamples", R.get());
599 Remark << ")";
600 return Remark;
601 });
602 }
603 LLVM_DEBUG(dbgs() << " " << Probe->Id << ":" << Inst
604 << " - weight: " << R.get() << " - factor: "
605 << format("%0.2f", Probe->Factor) << ")\n");
606 return Samples;
607 }
608 return R;
609 }
610
611 /// Get the FunctionSamples for a call instruction.
612 ///
613 /// The FunctionSamples of a call/invoke instruction \p Inst is the inlined
614 /// instance in which that call instruction is calling to. It contains
615 /// all samples that resides in the inlined instance. We first find the
616 /// inlined instance in which the call instruction is from, then we
617 /// traverse its children to find the callsite with the matching
618 /// location.
619 ///
620 /// \param Inst Call/Invoke instruction to query.
621 ///
622 /// \returns The FunctionSamples pointer to the inlined instance.
623 const FunctionSamples *
findCalleeFunctionSamples(const CallBase & Inst) const624 SampleProfileLoader::findCalleeFunctionSamples(const CallBase &Inst) const {
625 const DILocation *DIL = Inst.getDebugLoc();
626 if (!DIL) {
627 return nullptr;
628 }
629
630 StringRef CalleeName;
631 if (Function *Callee = Inst.getCalledFunction())
632 CalleeName = Callee->getName();
633
634 if (ProfileIsCS)
635 return ContextTracker->getCalleeContextSamplesFor(Inst, CalleeName);
636
637 const FunctionSamples *FS = findFunctionSamples(Inst);
638 if (FS == nullptr)
639 return nullptr;
640
641 return FS->findFunctionSamplesAt(FunctionSamples::getCallSiteIdentifier(DIL),
642 CalleeName, Reader->getRemapper());
643 }
644
645 /// Returns a vector of FunctionSamples that are the indirect call targets
646 /// of \p Inst. The vector is sorted by the total number of samples. Stores
647 /// the total call count of the indirect call in \p Sum.
648 std::vector<const FunctionSamples *>
findIndirectCallFunctionSamples(const Instruction & Inst,uint64_t & Sum) const649 SampleProfileLoader::findIndirectCallFunctionSamples(
650 const Instruction &Inst, uint64_t &Sum) const {
651 const DILocation *DIL = Inst.getDebugLoc();
652 std::vector<const FunctionSamples *> R;
653
654 if (!DIL) {
655 return R;
656 }
657
658 auto FSCompare = [](const FunctionSamples *L, const FunctionSamples *R) {
659 assert(L && R && "Expect non-null FunctionSamples");
660 if (L->getEntrySamples() != R->getEntrySamples())
661 return L->getEntrySamples() > R->getEntrySamples();
662 return FunctionSamples::getGUID(L->getName()) <
663 FunctionSamples::getGUID(R->getName());
664 };
665
666 if (ProfileIsCS) {
667 auto CalleeSamples =
668 ContextTracker->getIndirectCalleeContextSamplesFor(DIL);
669 if (CalleeSamples.empty())
670 return R;
671
672 // For CSSPGO, we only use target context profile's entry count
673 // as that already includes both inlined callee and non-inlined ones..
674 Sum = 0;
675 for (const auto *const FS : CalleeSamples) {
676 Sum += FS->getEntrySamples();
677 R.push_back(FS);
678 }
679 llvm::sort(R, FSCompare);
680 return R;
681 }
682
683 const FunctionSamples *FS = findFunctionSamples(Inst);
684 if (FS == nullptr)
685 return R;
686
687 auto CallSite = FunctionSamples::getCallSiteIdentifier(DIL);
688 auto T = FS->findCallTargetMapAt(CallSite);
689 Sum = 0;
690 if (T)
691 for (const auto &T_C : T.get())
692 Sum += T_C.second;
693 if (const FunctionSamplesMap *M = FS->findFunctionSamplesMapAt(CallSite)) {
694 if (M->empty())
695 return R;
696 for (const auto &NameFS : *M) {
697 Sum += NameFS.second.getEntrySamples();
698 R.push_back(&NameFS.second);
699 }
700 llvm::sort(R, FSCompare);
701 }
702 return R;
703 }
704
705 const FunctionSamples *
findFunctionSamples(const Instruction & Inst) const706 SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const {
707 if (FunctionSamples::ProfileIsProbeBased) {
708 Optional<PseudoProbe> Probe = extractProbe(Inst);
709 if (!Probe)
710 return nullptr;
711 }
712
713 const DILocation *DIL = Inst.getDebugLoc();
714 if (!DIL)
715 return Samples;
716
717 auto it = DILocation2SampleMap.try_emplace(DIL,nullptr);
718 if (it.second) {
719 if (ProfileIsCS)
720 it.first->second = ContextTracker->getContextSamplesFor(DIL);
721 else
722 it.first->second =
723 Samples->findFunctionSamples(DIL, Reader->getRemapper());
724 }
725 return it.first->second;
726 }
727
728 /// Check whether the indirect call promotion history of \p Inst allows
729 /// the promotion for \p Candidate.
730 /// If the profile count for the promotion candidate \p Candidate is
731 /// NOMORE_ICP_MAGICNUM, it means \p Candidate has already been promoted
732 /// for \p Inst. If we already have at least MaxNumPromotions
733 /// NOMORE_ICP_MAGICNUM count values in the value profile of \p Inst, we
734 /// cannot promote for \p Inst anymore.
doesHistoryAllowICP(const Instruction & Inst,StringRef Candidate)735 static bool doesHistoryAllowICP(const Instruction &Inst, StringRef Candidate) {
736 uint32_t NumVals = 0;
737 uint64_t TotalCount = 0;
738 std::unique_ptr<InstrProfValueData[]> ValueData =
739 std::make_unique<InstrProfValueData[]>(MaxNumPromotions);
740 bool Valid =
741 getValueProfDataFromInst(Inst, IPVK_IndirectCallTarget, MaxNumPromotions,
742 ValueData.get(), NumVals, TotalCount, true);
743 // No valid value profile so no promoted targets have been recorded
744 // before. Ok to do ICP.
745 if (!Valid)
746 return true;
747
748 unsigned NumPromoted = 0;
749 for (uint32_t I = 0; I < NumVals; I++) {
750 if (ValueData[I].Count != NOMORE_ICP_MAGICNUM)
751 continue;
752
753 // If the promotion candidate has NOMORE_ICP_MAGICNUM count in the
754 // metadata, it means the candidate has been promoted for this
755 // indirect call.
756 if (ValueData[I].Value == Function::getGUID(Candidate))
757 return false;
758 NumPromoted++;
759 // If already have MaxNumPromotions promotion, don't do it anymore.
760 if (NumPromoted == MaxNumPromotions)
761 return false;
762 }
763 return true;
764 }
765
766 /// Update indirect call target profile metadata for \p Inst.
767 /// Usually \p Sum is the sum of counts of all the targets for \p Inst.
768 /// If it is 0, it means updateIDTMetaData is used to mark a
769 /// certain target to be promoted already. If it is not zero,
770 /// we expect to use it to update the total count in the value profile.
771 static void
updateIDTMetaData(Instruction & Inst,const SmallVectorImpl<InstrProfValueData> & CallTargets,uint64_t Sum)772 updateIDTMetaData(Instruction &Inst,
773 const SmallVectorImpl<InstrProfValueData> &CallTargets,
774 uint64_t Sum) {
775 uint32_t NumVals = 0;
776 // OldSum is the existing total count in the value profile data.
777 uint64_t OldSum = 0;
778 std::unique_ptr<InstrProfValueData[]> ValueData =
779 std::make_unique<InstrProfValueData[]>(MaxNumPromotions);
780 bool Valid =
781 getValueProfDataFromInst(Inst, IPVK_IndirectCallTarget, MaxNumPromotions,
782 ValueData.get(), NumVals, OldSum, true);
783
784 DenseMap<uint64_t, uint64_t> ValueCountMap;
785 if (Sum == 0) {
786 assert((CallTargets.size() == 1 &&
787 CallTargets[0].Count == NOMORE_ICP_MAGICNUM) &&
788 "If sum is 0, assume only one element in CallTargets "
789 "with count being NOMORE_ICP_MAGICNUM");
790 // Initialize ValueCountMap with existing value profile data.
791 if (Valid) {
792 for (uint32_t I = 0; I < NumVals; I++)
793 ValueCountMap[ValueData[I].Value] = ValueData[I].Count;
794 }
795 auto Pair =
796 ValueCountMap.try_emplace(CallTargets[0].Value, CallTargets[0].Count);
797 // If the target already exists in value profile, decrease the total
798 // count OldSum and reset the target's count to NOMORE_ICP_MAGICNUM.
799 if (!Pair.second) {
800 OldSum -= Pair.first->second;
801 Pair.first->second = NOMORE_ICP_MAGICNUM;
802 }
803 Sum = OldSum;
804 } else {
805 // Initialize ValueCountMap with existing NOMORE_ICP_MAGICNUM
806 // counts in the value profile.
807 if (Valid) {
808 for (uint32_t I = 0; I < NumVals; I++) {
809 if (ValueData[I].Count == NOMORE_ICP_MAGICNUM)
810 ValueCountMap[ValueData[I].Value] = ValueData[I].Count;
811 }
812 }
813
814 for (const auto &Data : CallTargets) {
815 auto Pair = ValueCountMap.try_emplace(Data.Value, Data.Count);
816 if (Pair.second)
817 continue;
818 // The target represented by Data.Value has already been promoted.
819 // Keep the count as NOMORE_ICP_MAGICNUM in the profile and decrease
820 // Sum by Data.Count.
821 assert(Sum >= Data.Count && "Sum should never be less than Data.Count");
822 Sum -= Data.Count;
823 }
824 }
825
826 SmallVector<InstrProfValueData, 8> NewCallTargets;
827 for (const auto &ValueCount : ValueCountMap) {
828 NewCallTargets.emplace_back(
829 InstrProfValueData{ValueCount.first, ValueCount.second});
830 }
831
832 llvm::sort(NewCallTargets,
833 [](const InstrProfValueData &L, const InstrProfValueData &R) {
834 if (L.Count != R.Count)
835 return L.Count > R.Count;
836 return L.Value > R.Value;
837 });
838
839 uint32_t MaxMDCount =
840 std::min(NewCallTargets.size(), static_cast<size_t>(MaxNumPromotions));
841 annotateValueSite(*Inst.getParent()->getParent()->getParent(), Inst,
842 NewCallTargets, Sum, IPVK_IndirectCallTarget, MaxMDCount);
843 }
844
845 /// Attempt to promote indirect call and also inline the promoted call.
846 ///
847 /// \param F Caller function.
848 /// \param Candidate ICP and inline candidate.
849 /// \param SumOrigin Original sum of target counts for indirect call before
850 /// promoting given candidate.
851 /// \param Sum Prorated sum of remaining target counts for indirect call
852 /// after promoting given candidate.
853 /// \param InlinedCallSite Output vector for new call sites exposed after
854 /// inlining.
tryPromoteAndInlineCandidate(Function & F,InlineCandidate & Candidate,uint64_t SumOrigin,uint64_t & Sum,SmallVector<CallBase *,8> * InlinedCallSite)855 bool SampleProfileLoader::tryPromoteAndInlineCandidate(
856 Function &F, InlineCandidate &Candidate, uint64_t SumOrigin, uint64_t &Sum,
857 SmallVector<CallBase *, 8> *InlinedCallSite) {
858 auto CalleeFunctionName = Candidate.CalleeSamples->getFuncName();
859 auto R = SymbolMap.find(CalleeFunctionName);
860 if (R == SymbolMap.end() || !R->getValue())
861 return false;
862
863 auto &CI = *Candidate.CallInstr;
864 if (!doesHistoryAllowICP(CI, R->getValue()->getName()))
865 return false;
866
867 const char *Reason = "Callee function not available";
868 // R->getValue() != &F is to prevent promoting a recursive call.
869 // If it is a recursive call, we do not inline it as it could bloat
870 // the code exponentially. There is way to better handle this, e.g.
871 // clone the caller first, and inline the cloned caller if it is
872 // recursive. As llvm does not inline recursive calls, we will
873 // simply ignore it instead of handling it explicitly.
874 if (!R->getValue()->isDeclaration() && R->getValue()->getSubprogram() &&
875 R->getValue()->hasFnAttribute("use-sample-profile") &&
876 R->getValue() != &F && isLegalToPromote(CI, R->getValue(), &Reason)) {
877 // For promoted target, set its value with NOMORE_ICP_MAGICNUM count
878 // in the value profile metadata so the target won't be promoted again.
879 SmallVector<InstrProfValueData, 1> SortedCallTargets = {InstrProfValueData{
880 Function::getGUID(R->getValue()->getName()), NOMORE_ICP_MAGICNUM}};
881 updateIDTMetaData(CI, SortedCallTargets, 0);
882
883 auto *DI = &pgo::promoteIndirectCall(
884 CI, R->getValue(), Candidate.CallsiteCount, Sum, false, ORE);
885 if (DI) {
886 Sum -= Candidate.CallsiteCount;
887 // Do not prorate the indirect callsite distribution since the original
888 // distribution will be used to scale down non-promoted profile target
889 // counts later. By doing this we lose track of the real callsite count
890 // for the leftover indirect callsite as a trade off for accurate call
891 // target counts.
892 // TODO: Ideally we would have two separate factors, one for call site
893 // counts and one is used to prorate call target counts.
894 // Do not update the promoted direct callsite distribution at this
895 // point since the original distribution combined with the callee profile
896 // will be used to prorate callsites from the callee if inlined. Once not
897 // inlined, the direct callsite distribution should be prorated so that
898 // the it will reflect the real callsite counts.
899 Candidate.CallInstr = DI;
900 if (isa<CallInst>(DI) || isa<InvokeInst>(DI)) {
901 bool Inlined = tryInlineCandidate(Candidate, InlinedCallSite);
902 if (!Inlined) {
903 // Prorate the direct callsite distribution so that it reflects real
904 // callsite counts.
905 setProbeDistributionFactor(
906 *DI, static_cast<float>(Candidate.CallsiteCount) / SumOrigin);
907 }
908 return Inlined;
909 }
910 }
911 } else {
912 LLVM_DEBUG(dbgs() << "\nFailed to promote indirect call to "
913 << Candidate.CalleeSamples->getFuncName() << " because "
914 << Reason << "\n");
915 }
916 return false;
917 }
918
shouldInlineColdCallee(CallBase & CallInst)919 bool SampleProfileLoader::shouldInlineColdCallee(CallBase &CallInst) {
920 if (!ProfileSizeInline)
921 return false;
922
923 Function *Callee = CallInst.getCalledFunction();
924 if (Callee == nullptr)
925 return false;
926
927 InlineCost Cost = getInlineCost(CallInst, getInlineParams(), GetTTI(*Callee),
928 GetAC, GetTLI);
929
930 if (Cost.isNever())
931 return false;
932
933 if (Cost.isAlways())
934 return true;
935
936 return Cost.getCost() <= SampleColdCallSiteThreshold;
937 }
938
emitOptimizationRemarksForInlineCandidates(const SmallVectorImpl<CallBase * > & Candidates,const Function & F,bool Hot)939 void SampleProfileLoader::emitOptimizationRemarksForInlineCandidates(
940 const SmallVectorImpl<CallBase *> &Candidates, const Function &F,
941 bool Hot) {
942 for (auto I : Candidates) {
943 Function *CalledFunction = I->getCalledFunction();
944 if (CalledFunction) {
945 ORE->emit(OptimizationRemarkAnalysis(CSINLINE_DEBUG, "InlineAttempt",
946 I->getDebugLoc(), I->getParent())
947 << "previous inlining reattempted for "
948 << (Hot ? "hotness: '" : "size: '")
949 << ore::NV("Callee", CalledFunction) << "' into '"
950 << ore::NV("Caller", &F) << "'");
951 }
952 }
953 }
954
findExternalInlineCandidate(const FunctionSamples * Samples,DenseSet<GlobalValue::GUID> & InlinedGUIDs,const StringMap<Function * > & SymbolMap,uint64_t Threshold)955 void SampleProfileLoader::findExternalInlineCandidate(
956 const FunctionSamples *Samples, DenseSet<GlobalValue::GUID> &InlinedGUIDs,
957 const StringMap<Function *> &SymbolMap, uint64_t Threshold) {
958 assert(Samples && "expect non-null caller profile");
959
960 // For AutoFDO profile, retrieve candidate profiles by walking over
961 // the nested inlinee profiles.
962 if (!ProfileIsCS) {
963 Samples->findInlinedFunctions(InlinedGUIDs, SymbolMap, Threshold);
964 return;
965 }
966
967 ContextTrieNode *Caller =
968 ContextTracker->getContextFor(Samples->getContext());
969 std::queue<ContextTrieNode *> CalleeList;
970 CalleeList.push(Caller);
971 while (!CalleeList.empty()) {
972 ContextTrieNode *Node = CalleeList.front();
973 CalleeList.pop();
974 FunctionSamples *CalleeSample = Node->getFunctionSamples();
975 // For CSSPGO profile, retrieve candidate profile by walking over the
976 // trie built for context profile. Note that also take call targets
977 // even if callee doesn't have a corresponding context profile.
978 if (!CalleeSample || CalleeSample->getEntrySamples() < Threshold)
979 continue;
980
981 StringRef Name = CalleeSample->getFuncName();
982 Function *Func = SymbolMap.lookup(Name);
983 // Add to the import list only when it's defined out of module.
984 if (!Func || Func->isDeclaration())
985 InlinedGUIDs.insert(FunctionSamples::getGUID(Name));
986
987 // Import hot CallTargets, which may not be available in IR because full
988 // profile annotation cannot be done until backend compilation in ThinLTO.
989 for (const auto &BS : CalleeSample->getBodySamples())
990 for (const auto &TS : BS.second.getCallTargets())
991 if (TS.getValue() > Threshold) {
992 StringRef CalleeName = CalleeSample->getFuncName(TS.getKey());
993 const Function *Callee = SymbolMap.lookup(CalleeName);
994 if (!Callee || Callee->isDeclaration())
995 InlinedGUIDs.insert(FunctionSamples::getGUID(CalleeName));
996 }
997
998 // Import hot child context profile associted with callees. Note that this
999 // may have some overlap with the call target loop above, but doing this
1000 // based child context profile again effectively allow us to use the max of
1001 // entry count and call target count to determine importing.
1002 for (auto &Child : Node->getAllChildContext()) {
1003 ContextTrieNode *CalleeNode = &Child.second;
1004 CalleeList.push(CalleeNode);
1005 }
1006 }
1007 }
1008
1009 /// Iteratively inline hot callsites of a function.
1010 ///
1011 /// Iteratively traverse all callsites of the function \p F, and find if
1012 /// the corresponding inlined instance exists and is hot in profile. If
1013 /// it is hot enough, inline the callsites and adds new callsites of the
1014 /// callee into the caller. If the call is an indirect call, first promote
1015 /// it to direct call. Each indirect call is limited with a single target.
1016 ///
1017 /// \param F function to perform iterative inlining.
1018 /// \param InlinedGUIDs a set to be updated to include all GUIDs that are
1019 /// inlined in the profiled binary.
1020 ///
1021 /// \returns True if there is any inline happened.
inlineHotFunctions(Function & F,DenseSet<GlobalValue::GUID> & InlinedGUIDs)1022 bool SampleProfileLoader::inlineHotFunctions(
1023 Function &F, DenseSet<GlobalValue::GUID> &InlinedGUIDs) {
1024 // ProfAccForSymsInList is used in callsiteIsHot. The assertion makes sure
1025 // Profile symbol list is ignored when profile-sample-accurate is on.
1026 assert((!ProfAccForSymsInList ||
1027 (!ProfileSampleAccurate &&
1028 !F.hasFnAttribute("profile-sample-accurate"))) &&
1029 "ProfAccForSymsInList should be false when profile-sample-accurate "
1030 "is enabled");
1031
1032 DenseMap<CallBase *, const FunctionSamples *> LocalNotInlinedCallSites;
1033 bool Changed = false;
1034 bool LocalChanged = true;
1035 while (LocalChanged) {
1036 LocalChanged = false;
1037 SmallVector<CallBase *, 10> CIS;
1038 for (auto &BB : F) {
1039 bool Hot = false;
1040 SmallVector<CallBase *, 10> AllCandidates;
1041 SmallVector<CallBase *, 10> ColdCandidates;
1042 for (auto &I : BB.getInstList()) {
1043 const FunctionSamples *FS = nullptr;
1044 if (auto *CB = dyn_cast<CallBase>(&I)) {
1045 if (!isa<IntrinsicInst>(I) && (FS = findCalleeFunctionSamples(*CB))) {
1046 assert((!FunctionSamples::UseMD5 || FS->GUIDToFuncNameMap) &&
1047 "GUIDToFuncNameMap has to be populated");
1048 AllCandidates.push_back(CB);
1049 if (FS->getEntrySamples() > 0 || ProfileIsCS)
1050 LocalNotInlinedCallSites.try_emplace(CB, FS);
1051 if (callsiteIsHot(FS, PSI, ProfAccForSymsInList))
1052 Hot = true;
1053 else if (shouldInlineColdCallee(*CB))
1054 ColdCandidates.push_back(CB);
1055 }
1056 }
1057 }
1058 if (Hot || ExternalInlineAdvisor) {
1059 CIS.insert(CIS.begin(), AllCandidates.begin(), AllCandidates.end());
1060 emitOptimizationRemarksForInlineCandidates(AllCandidates, F, true);
1061 } else {
1062 CIS.insert(CIS.begin(), ColdCandidates.begin(), ColdCandidates.end());
1063 emitOptimizationRemarksForInlineCandidates(ColdCandidates, F, false);
1064 }
1065 }
1066 for (CallBase *I : CIS) {
1067 Function *CalledFunction = I->getCalledFunction();
1068 InlineCandidate Candidate = {
1069 I,
1070 LocalNotInlinedCallSites.count(I) ? LocalNotInlinedCallSites[I]
1071 : nullptr,
1072 0 /* dummy count */, 1.0 /* dummy distribution factor */};
1073 // Do not inline recursive calls.
1074 if (CalledFunction == &F)
1075 continue;
1076 if (I->isIndirectCall()) {
1077 uint64_t Sum;
1078 for (const auto *FS : findIndirectCallFunctionSamples(*I, Sum)) {
1079 uint64_t SumOrigin = Sum;
1080 if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
1081 findExternalInlineCandidate(FS, InlinedGUIDs, SymbolMap,
1082 PSI->getOrCompHotCountThreshold());
1083 continue;
1084 }
1085 if (!callsiteIsHot(FS, PSI, ProfAccForSymsInList))
1086 continue;
1087
1088 Candidate = {I, FS, FS->getEntrySamples(), 1.0};
1089 if (tryPromoteAndInlineCandidate(F, Candidate, SumOrigin, Sum)) {
1090 LocalNotInlinedCallSites.erase(I);
1091 LocalChanged = true;
1092 }
1093 }
1094 } else if (CalledFunction && CalledFunction->getSubprogram() &&
1095 !CalledFunction->isDeclaration()) {
1096 if (tryInlineCandidate(Candidate)) {
1097 LocalNotInlinedCallSites.erase(I);
1098 LocalChanged = true;
1099 }
1100 } else if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
1101 findExternalInlineCandidate(findCalleeFunctionSamples(*I), InlinedGUIDs,
1102 SymbolMap,
1103 PSI->getOrCompHotCountThreshold());
1104 }
1105 }
1106 Changed |= LocalChanged;
1107 }
1108
1109 // For CS profile, profile for not inlined context will be merged when
1110 // base profile is being trieved
1111 if (ProfileIsCS)
1112 return Changed;
1113
1114 // Accumulate not inlined callsite information into notInlinedSamples
1115 for (const auto &Pair : LocalNotInlinedCallSites) {
1116 CallBase *I = Pair.getFirst();
1117 Function *Callee = I->getCalledFunction();
1118 if (!Callee || Callee->isDeclaration())
1119 continue;
1120
1121 ORE->emit(OptimizationRemarkAnalysis(CSINLINE_DEBUG, "NotInline",
1122 I->getDebugLoc(), I->getParent())
1123 << "previous inlining not repeated: '"
1124 << ore::NV("Callee", Callee) << "' into '"
1125 << ore::NV("Caller", &F) << "'");
1126
1127 ++NumCSNotInlined;
1128 const FunctionSamples *FS = Pair.getSecond();
1129 if (FS->getTotalSamples() == 0 && FS->getEntrySamples() == 0) {
1130 continue;
1131 }
1132
1133 if (ProfileMergeInlinee) {
1134 // A function call can be replicated by optimizations like callsite
1135 // splitting or jump threading and the replicates end up sharing the
1136 // sample nested callee profile instead of slicing the original inlinee's
1137 // profile. We want to do merge exactly once by filtering out callee
1138 // profiles with a non-zero head sample count.
1139 if (FS->getHeadSamples() == 0) {
1140 // Use entry samples as head samples during the merge, as inlinees
1141 // don't have head samples.
1142 const_cast<FunctionSamples *>(FS)->addHeadSamples(
1143 FS->getEntrySamples());
1144
1145 // Note that we have to do the merge right after processing function.
1146 // This allows OutlineFS's profile to be used for annotation during
1147 // top-down processing of functions' annotation.
1148 FunctionSamples *OutlineFS = Reader->getOrCreateSamplesFor(*Callee);
1149 OutlineFS->merge(*FS);
1150 }
1151 } else {
1152 auto pair =
1153 notInlinedCallInfo.try_emplace(Callee, NotInlinedProfileInfo{0});
1154 pair.first->second.entryCount += FS->getEntrySamples();
1155 }
1156 }
1157 return Changed;
1158 }
1159
tryInlineCandidate(InlineCandidate & Candidate,SmallVector<CallBase *,8> * InlinedCallSites)1160 bool SampleProfileLoader::tryInlineCandidate(
1161 InlineCandidate &Candidate, SmallVector<CallBase *, 8> *InlinedCallSites) {
1162
1163 CallBase &CB = *Candidate.CallInstr;
1164 Function *CalledFunction = CB.getCalledFunction();
1165 assert(CalledFunction && "Expect a callee with definition");
1166 DebugLoc DLoc = CB.getDebugLoc();
1167 BasicBlock *BB = CB.getParent();
1168
1169 InlineCost Cost = shouldInlineCandidate(Candidate);
1170 if (Cost.isNever()) {
1171 ORE->emit(OptimizationRemarkAnalysis(CSINLINE_DEBUG, "InlineFail", DLoc, BB)
1172 << "incompatible inlining");
1173 return false;
1174 }
1175
1176 if (!Cost)
1177 return false;
1178
1179 InlineFunctionInfo IFI(nullptr, GetAC);
1180 IFI.UpdateProfile = false;
1181 if (InlineFunction(CB, IFI).isSuccess()) {
1182 // Merge the attributes based on the inlining.
1183 AttributeFuncs::mergeAttributesForInlining(*BB->getParent(),
1184 *CalledFunction);
1185
1186 // The call to InlineFunction erases I, so we can't pass it here.
1187 emitInlinedInto(*ORE, DLoc, BB, *CalledFunction, *BB->getParent(), Cost,
1188 true, CSINLINE_DEBUG);
1189
1190 // Now populate the list of newly exposed call sites.
1191 if (InlinedCallSites) {
1192 InlinedCallSites->clear();
1193 for (auto &I : IFI.InlinedCallSites)
1194 InlinedCallSites->push_back(I);
1195 }
1196
1197 if (ProfileIsCS)
1198 ContextTracker->markContextSamplesInlined(Candidate.CalleeSamples);
1199 ++NumCSInlined;
1200
1201 // Prorate inlined probes for a duplicated inlining callsite which probably
1202 // has a distribution less than 100%. Samples for an inlinee should be
1203 // distributed among the copies of the original callsite based on each
1204 // callsite's distribution factor for counts accuracy. Note that an inlined
1205 // probe may come with its own distribution factor if it has been duplicated
1206 // in the inlinee body. The two factor are multiplied to reflect the
1207 // aggregation of duplication.
1208 if (Candidate.CallsiteDistribution < 1) {
1209 for (auto &I : IFI.InlinedCallSites) {
1210 if (Optional<PseudoProbe> Probe = extractProbe(*I))
1211 setProbeDistributionFactor(*I, Probe->Factor *
1212 Candidate.CallsiteDistribution);
1213 }
1214 NumDuplicatedInlinesite++;
1215 }
1216
1217 return true;
1218 }
1219 return false;
1220 }
1221
getInlineCandidate(InlineCandidate * NewCandidate,CallBase * CB)1222 bool SampleProfileLoader::getInlineCandidate(InlineCandidate *NewCandidate,
1223 CallBase *CB) {
1224 assert(CB && "Expect non-null call instruction");
1225
1226 if (isa<IntrinsicInst>(CB))
1227 return false;
1228
1229 // Find the callee's profile. For indirect call, find hottest target profile.
1230 const FunctionSamples *CalleeSamples = findCalleeFunctionSamples(*CB);
1231 if (!CalleeSamples)
1232 return false;
1233
1234 float Factor = 1.0;
1235 if (Optional<PseudoProbe> Probe = extractProbe(*CB))
1236 Factor = Probe->Factor;
1237
1238 uint64_t CallsiteCount = 0;
1239 ErrorOr<uint64_t> Weight = getBlockWeight(CB->getParent());
1240 if (Weight)
1241 CallsiteCount = Weight.get();
1242 if (CalleeSamples)
1243 CallsiteCount = std::max(
1244 CallsiteCount, uint64_t(CalleeSamples->getEntrySamples() * Factor));
1245
1246 *NewCandidate = {CB, CalleeSamples, CallsiteCount, Factor};
1247 return true;
1248 }
1249
1250 InlineCost
shouldInlineCandidate(InlineCandidate & Candidate)1251 SampleProfileLoader::shouldInlineCandidate(InlineCandidate &Candidate) {
1252 std::unique_ptr<InlineAdvice> Advice = nullptr;
1253 if (ExternalInlineAdvisor) {
1254 Advice = ExternalInlineAdvisor->getAdvice(*Candidate.CallInstr);
1255 if (!Advice->isInliningRecommended()) {
1256 Advice->recordUnattemptedInlining();
1257 return InlineCost::getNever("not previously inlined");
1258 }
1259 Advice->recordInlining();
1260 return InlineCost::getAlways("previously inlined");
1261 }
1262
1263 // Adjust threshold based on call site hotness, only do this for callsite
1264 // prioritized inliner because otherwise cost-benefit check is done earlier.
1265 int SampleThreshold = SampleColdCallSiteThreshold;
1266 if (CallsitePrioritizedInline) {
1267 if (Candidate.CallsiteCount > PSI->getHotCountThreshold())
1268 SampleThreshold = SampleHotCallSiteThreshold;
1269 else if (!ProfileSizeInline)
1270 return InlineCost::getNever("cold callsite");
1271 }
1272
1273 Function *Callee = Candidate.CallInstr->getCalledFunction();
1274 assert(Callee && "Expect a definition for inline candidate of direct call");
1275
1276 InlineParams Params = getInlineParams();
1277 Params.ComputeFullInlineCost = true;
1278 // Checks if there is anything in the reachable portion of the callee at
1279 // this callsite that makes this inlining potentially illegal. Need to
1280 // set ComputeFullInlineCost, otherwise getInlineCost may return early
1281 // when cost exceeds threshold without checking all IRs in the callee.
1282 // The acutal cost does not matter because we only checks isNever() to
1283 // see if it is legal to inline the callsite.
1284 InlineCost Cost = getInlineCost(*Candidate.CallInstr, Callee, Params,
1285 GetTTI(*Callee), GetAC, GetTLI);
1286
1287 // Honor always inline and never inline from call analyzer
1288 if (Cost.isNever() || Cost.isAlways())
1289 return Cost;
1290
1291 // For old FDO inliner, we inline the call site as long as cost is not
1292 // "Never". The cost-benefit check is done earlier.
1293 if (!CallsitePrioritizedInline) {
1294 return InlineCost::get(Cost.getCost(), INT_MAX);
1295 }
1296
1297 // Otherwise only use the cost from call analyzer, but overwite threshold with
1298 // Sample PGO threshold.
1299 return InlineCost::get(Cost.getCost(), SampleThreshold);
1300 }
1301
inlineHotFunctionsWithPriority(Function & F,DenseSet<GlobalValue::GUID> & InlinedGUIDs)1302 bool SampleProfileLoader::inlineHotFunctionsWithPriority(
1303 Function &F, DenseSet<GlobalValue::GUID> &InlinedGUIDs) {
1304 assert(ProfileIsCS && "Prioritiy based inliner only works with CSSPGO now");
1305
1306 // ProfAccForSymsInList is used in callsiteIsHot. The assertion makes sure
1307 // Profile symbol list is ignored when profile-sample-accurate is on.
1308 assert((!ProfAccForSymsInList ||
1309 (!ProfileSampleAccurate &&
1310 !F.hasFnAttribute("profile-sample-accurate"))) &&
1311 "ProfAccForSymsInList should be false when profile-sample-accurate "
1312 "is enabled");
1313
1314 // Populating worklist with initial call sites from root inliner, along
1315 // with call site weights.
1316 CandidateQueue CQueue;
1317 InlineCandidate NewCandidate;
1318 for (auto &BB : F) {
1319 for (auto &I : BB.getInstList()) {
1320 auto *CB = dyn_cast<CallBase>(&I);
1321 if (!CB)
1322 continue;
1323 if (getInlineCandidate(&NewCandidate, CB))
1324 CQueue.push(NewCandidate);
1325 }
1326 }
1327
1328 // Cap the size growth from profile guided inlining. This is needed even
1329 // though cost of each inline candidate already accounts for callee size,
1330 // because with top-down inlining, we can grow inliner size significantly
1331 // with large number of smaller inlinees each pass the cost check.
1332 assert(ProfileInlineLimitMax >= ProfileInlineLimitMin &&
1333 "Max inline size limit should not be smaller than min inline size "
1334 "limit.");
1335 unsigned SizeLimit = F.getInstructionCount() * ProfileInlineGrowthLimit;
1336 SizeLimit = std::min(SizeLimit, (unsigned)ProfileInlineLimitMax);
1337 SizeLimit = std::max(SizeLimit, (unsigned)ProfileInlineLimitMin);
1338 if (ExternalInlineAdvisor)
1339 SizeLimit = std::numeric_limits<unsigned>::max();
1340
1341 // Perform iterative BFS call site prioritized inlining
1342 bool Changed = false;
1343 while (!CQueue.empty() && F.getInstructionCount() < SizeLimit) {
1344 InlineCandidate Candidate = CQueue.top();
1345 CQueue.pop();
1346 CallBase *I = Candidate.CallInstr;
1347 Function *CalledFunction = I->getCalledFunction();
1348
1349 if (CalledFunction == &F)
1350 continue;
1351 if (I->isIndirectCall()) {
1352 uint64_t Sum = 0;
1353 auto CalleeSamples = findIndirectCallFunctionSamples(*I, Sum);
1354 uint64_t SumOrigin = Sum;
1355 Sum *= Candidate.CallsiteDistribution;
1356 unsigned ICPCount = 0;
1357 for (const auto *FS : CalleeSamples) {
1358 // TODO: Consider disable pre-lTO ICP for MonoLTO as well
1359 if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
1360 findExternalInlineCandidate(FS, InlinedGUIDs, SymbolMap,
1361 PSI->getOrCompHotCountThreshold());
1362 continue;
1363 }
1364 uint64_t EntryCountDistributed =
1365 FS->getEntrySamples() * Candidate.CallsiteDistribution;
1366 // In addition to regular inline cost check, we also need to make sure
1367 // ICP isn't introducing excessive speculative checks even if individual
1368 // target looks beneficial to promote and inline. That means we should
1369 // only do ICP when there's a small number dominant targets.
1370 if (ICPCount >= ProfileICPRelativeHotnessSkip &&
1371 EntryCountDistributed * 100 < SumOrigin * ProfileICPRelativeHotness)
1372 break;
1373 // TODO: Fix CallAnalyzer to handle all indirect calls.
1374 // For indirect call, we don't run CallAnalyzer to get InlineCost
1375 // before actual inlining. This is because we could see two different
1376 // types from the same definition, which makes CallAnalyzer choke as
1377 // it's expecting matching parameter type on both caller and callee
1378 // side. See example from PR18962 for the triggering cases (the bug was
1379 // fixed, but we generate different types).
1380 if (!PSI->isHotCount(EntryCountDistributed))
1381 break;
1382 SmallVector<CallBase *, 8> InlinedCallSites;
1383 // Attach function profile for promoted indirect callee, and update
1384 // call site count for the promoted inline candidate too.
1385 Candidate = {I, FS, EntryCountDistributed,
1386 Candidate.CallsiteDistribution};
1387 if (tryPromoteAndInlineCandidate(F, Candidate, SumOrigin, Sum,
1388 &InlinedCallSites)) {
1389 for (auto *CB : InlinedCallSites) {
1390 if (getInlineCandidate(&NewCandidate, CB))
1391 CQueue.emplace(NewCandidate);
1392 }
1393 ICPCount++;
1394 Changed = true;
1395 }
1396 }
1397 } else if (CalledFunction && CalledFunction->getSubprogram() &&
1398 !CalledFunction->isDeclaration()) {
1399 SmallVector<CallBase *, 8> InlinedCallSites;
1400 if (tryInlineCandidate(Candidate, &InlinedCallSites)) {
1401 for (auto *CB : InlinedCallSites) {
1402 if (getInlineCandidate(&NewCandidate, CB))
1403 CQueue.emplace(NewCandidate);
1404 }
1405 Changed = true;
1406 }
1407 } else if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
1408 findExternalInlineCandidate(Candidate.CalleeSamples, InlinedGUIDs,
1409 SymbolMap, PSI->getOrCompHotCountThreshold());
1410 }
1411 }
1412
1413 if (!CQueue.empty()) {
1414 if (SizeLimit == (unsigned)ProfileInlineLimitMax)
1415 ++NumCSInlinedHitMaxLimit;
1416 else if (SizeLimit == (unsigned)ProfileInlineLimitMin)
1417 ++NumCSInlinedHitMinLimit;
1418 else
1419 ++NumCSInlinedHitGrowthLimit;
1420 }
1421
1422 return Changed;
1423 }
1424
1425 /// Returns the sorted CallTargetMap \p M by count in descending order.
1426 static SmallVector<InstrProfValueData, 2>
GetSortedValueDataFromCallTargets(const SampleRecord::CallTargetMap & M)1427 GetSortedValueDataFromCallTargets(const SampleRecord::CallTargetMap &M) {
1428 SmallVector<InstrProfValueData, 2> R;
1429 for (const auto &I : SampleRecord::SortCallTargets(M)) {
1430 R.emplace_back(
1431 InstrProfValueData{FunctionSamples::getGUID(I.first), I.second});
1432 }
1433 return R;
1434 }
1435
1436 // Generate MD_prof metadata for every branch instruction using the
1437 // edge weights computed during propagation.
generateMDProfMetadata(Function & F)1438 void SampleProfileLoader::generateMDProfMetadata(Function &F) {
1439 // Generate MD_prof metadata for every branch instruction using the
1440 // edge weights computed during propagation.
1441 LLVM_DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
1442 LLVMContext &Ctx = F.getContext();
1443 MDBuilder MDB(Ctx);
1444 for (auto &BI : F) {
1445 BasicBlock *BB = &BI;
1446
1447 if (BlockWeights[BB]) {
1448 for (auto &I : BB->getInstList()) {
1449 if (!isa<CallInst>(I) && !isa<InvokeInst>(I))
1450 continue;
1451 if (!cast<CallBase>(I).getCalledFunction()) {
1452 const DebugLoc &DLoc = I.getDebugLoc();
1453 if (!DLoc)
1454 continue;
1455 const DILocation *DIL = DLoc;
1456 const FunctionSamples *FS = findFunctionSamples(I);
1457 if (!FS)
1458 continue;
1459 auto CallSite = FunctionSamples::getCallSiteIdentifier(DIL);
1460 auto T = FS->findCallTargetMapAt(CallSite);
1461 if (!T || T.get().empty())
1462 continue;
1463 if (FunctionSamples::ProfileIsProbeBased) {
1464 // Prorate the callsite counts based on the pre-ICP distribution
1465 // factor to reflect what is already done to the callsite before
1466 // ICP, such as calliste cloning.
1467 if (Optional<PseudoProbe> Probe = extractProbe(I)) {
1468 if (Probe->Factor < 1)
1469 T = SampleRecord::adjustCallTargets(T.get(), Probe->Factor);
1470 }
1471 }
1472 SmallVector<InstrProfValueData, 2> SortedCallTargets =
1473 GetSortedValueDataFromCallTargets(T.get());
1474 uint64_t Sum = 0;
1475 for (const auto &C : T.get())
1476 Sum += C.second;
1477 // With CSSPGO all indirect call targets are counted torwards the
1478 // original indirect call site in the profile, including both
1479 // inlined and non-inlined targets.
1480 if (!FunctionSamples::ProfileIsCS) {
1481 if (const FunctionSamplesMap *M =
1482 FS->findFunctionSamplesMapAt(CallSite)) {
1483 for (const auto &NameFS : *M)
1484 Sum += NameFS.second.getEntrySamples();
1485 }
1486 }
1487 if (Sum)
1488 updateIDTMetaData(I, SortedCallTargets, Sum);
1489 else if (OverwriteExistingWeights)
1490 I.setMetadata(LLVMContext::MD_prof, nullptr);
1491 } else if (!isa<IntrinsicInst>(&I)) {
1492 I.setMetadata(LLVMContext::MD_prof,
1493 MDB.createBranchWeights(
1494 {static_cast<uint32_t>(BlockWeights[BB])}));
1495 }
1496 }
1497 } else if (OverwriteExistingWeights) {
1498 // Set profile metadata (possibly annotated by LTO prelink) to zero or
1499 // clear it for cold code.
1500 for (auto &I : BB->getInstList()) {
1501 if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
1502 if (cast<CallBase>(I).isIndirectCall())
1503 I.setMetadata(LLVMContext::MD_prof, nullptr);
1504 else
1505 I.setMetadata(LLVMContext::MD_prof, MDB.createBranchWeights(0));
1506 }
1507 }
1508 }
1509
1510 Instruction *TI = BB->getTerminator();
1511 if (TI->getNumSuccessors() == 1)
1512 continue;
1513 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI) &&
1514 !isa<IndirectBrInst>(TI))
1515 continue;
1516
1517 DebugLoc BranchLoc = TI->getDebugLoc();
1518 LLVM_DEBUG(dbgs() << "\nGetting weights for branch at line "
1519 << ((BranchLoc) ? Twine(BranchLoc.getLine())
1520 : Twine("<UNKNOWN LOCATION>"))
1521 << ".\n");
1522 SmallVector<uint32_t, 4> Weights;
1523 uint32_t MaxWeight = 0;
1524 Instruction *MaxDestInst;
1525 for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
1526 BasicBlock *Succ = TI->getSuccessor(I);
1527 Edge E = std::make_pair(BB, Succ);
1528 uint64_t Weight = EdgeWeights[E];
1529 LLVM_DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
1530 // Use uint32_t saturated arithmetic to adjust the incoming weights,
1531 // if needed. Sample counts in profiles are 64-bit unsigned values,
1532 // but internally branch weights are expressed as 32-bit values.
1533 if (Weight > std::numeric_limits<uint32_t>::max()) {
1534 LLVM_DEBUG(dbgs() << " (saturated due to uint32_t overflow)");
1535 Weight = std::numeric_limits<uint32_t>::max();
1536 }
1537 // Weight is added by one to avoid propagation errors introduced by
1538 // 0 weights.
1539 Weights.push_back(static_cast<uint32_t>(Weight + 1));
1540 if (Weight != 0) {
1541 if (Weight > MaxWeight) {
1542 MaxWeight = Weight;
1543 MaxDestInst = Succ->getFirstNonPHIOrDbgOrLifetime();
1544 }
1545 }
1546 }
1547
1548 uint64_t TempWeight;
1549 // Only set weights if there is at least one non-zero weight.
1550 // In any other case, let the analyzer set weights.
1551 // Do not set weights if the weights are present unless under
1552 // OverwriteExistingWeights. In ThinLTO, the profile annotation is done
1553 // twice. If the first annotation already set the weights, the second pass
1554 // does not need to set it. With OverwriteExistingWeights, Blocks with zero
1555 // weight should have their existing metadata (possibly annotated by LTO
1556 // prelink) cleared.
1557 if (MaxWeight > 0 &&
1558 (!TI->extractProfTotalWeight(TempWeight) || OverwriteExistingWeights)) {
1559 LLVM_DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
1560 TI->setMetadata(LLVMContext::MD_prof, MDB.createBranchWeights(Weights));
1561 ORE->emit([&]() {
1562 return OptimizationRemark(DEBUG_TYPE, "PopularDest", MaxDestInst)
1563 << "most popular destination for conditional branches at "
1564 << ore::NV("CondBranchesLoc", BranchLoc);
1565 });
1566 } else {
1567 if (OverwriteExistingWeights) {
1568 TI->setMetadata(LLVMContext::MD_prof, nullptr);
1569 LLVM_DEBUG(dbgs() << "CLEARED. All branch weights are zero.\n");
1570 } else {
1571 LLVM_DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
1572 }
1573 }
1574 }
1575 }
1576
1577 /// Once all the branch weights are computed, we emit the MD_prof
1578 /// metadata on BB using the computed values for each of its branches.
1579 ///
1580 /// \param F The function to query.
1581 ///
1582 /// \returns true if \p F was modified. Returns false, otherwise.
emitAnnotations(Function & F)1583 bool SampleProfileLoader::emitAnnotations(Function &F) {
1584 bool Changed = false;
1585
1586 if (FunctionSamples::ProfileIsProbeBased) {
1587 if (!ProbeManager->profileIsValid(F, *Samples)) {
1588 LLVM_DEBUG(
1589 dbgs() << "Profile is invalid due to CFG mismatch for Function "
1590 << F.getName());
1591 ++NumMismatchedProfile;
1592 return false;
1593 }
1594 ++NumMatchedProfile;
1595 } else {
1596 if (getFunctionLoc(F) == 0)
1597 return false;
1598
1599 LLVM_DEBUG(dbgs() << "Line number for the first instruction in "
1600 << F.getName() << ": " << getFunctionLoc(F) << "\n");
1601 }
1602
1603 DenseSet<GlobalValue::GUID> InlinedGUIDs;
1604 if (ProfileIsCS && CallsitePrioritizedInline)
1605 Changed |= inlineHotFunctionsWithPriority(F, InlinedGUIDs);
1606 else
1607 Changed |= inlineHotFunctions(F, InlinedGUIDs);
1608
1609 Changed |= computeAndPropagateWeights(F, InlinedGUIDs);
1610
1611 if (Changed)
1612 generateMDProfMetadata(F);
1613
1614 emitCoverageRemarks(F);
1615 return Changed;
1616 }
1617
1618 char SampleProfileLoaderLegacyPass::ID = 0;
1619
1620 INITIALIZE_PASS_BEGIN(SampleProfileLoaderLegacyPass, "sample-profile",
1621 "Sample Profile loader", false, false)
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)1622 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1623 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
1624 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1625 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
1626 INITIALIZE_PASS_END(SampleProfileLoaderLegacyPass, "sample-profile",
1627 "Sample Profile loader", false, false)
1628
1629 std::unique_ptr<ProfiledCallGraph>
1630 SampleProfileLoader::buildProfiledCallGraph(CallGraph &CG) {
1631 std::unique_ptr<ProfiledCallGraph> ProfiledCG;
1632 if (ProfileIsCS)
1633 ProfiledCG = std::make_unique<ProfiledCallGraph>(*ContextTracker);
1634 else
1635 ProfiledCG = std::make_unique<ProfiledCallGraph>(Reader->getProfiles());
1636
1637 // Add all functions into the profiled call graph even if they are not in
1638 // the profile. This makes sure functions missing from the profile still
1639 // gets a chance to be processed.
1640 for (auto &Node : CG) {
1641 const auto *F = Node.first;
1642 if (!F || F->isDeclaration() || !F->hasFnAttribute("use-sample-profile"))
1643 continue;
1644 ProfiledCG->addProfiledFunction(FunctionSamples::getCanonicalFnName(*F));
1645 }
1646
1647 return ProfiledCG;
1648 }
1649
1650 std::vector<Function *>
buildFunctionOrder(Module & M,CallGraph * CG)1651 SampleProfileLoader::buildFunctionOrder(Module &M, CallGraph *CG) {
1652 std::vector<Function *> FunctionOrderList;
1653 FunctionOrderList.reserve(M.size());
1654
1655 if (!ProfileTopDownLoad && UseProfiledCallGraph)
1656 errs() << "WARNING: -use-profiled-call-graph ignored, should be used "
1657 "together with -sample-profile-top-down-load.\n";
1658
1659 if (!ProfileTopDownLoad || CG == nullptr) {
1660 if (ProfileMergeInlinee) {
1661 // Disable ProfileMergeInlinee if profile is not loaded in top down order,
1662 // because the profile for a function may be used for the profile
1663 // annotation of its outline copy before the profile merging of its
1664 // non-inlined inline instances, and that is not the way how
1665 // ProfileMergeInlinee is supposed to work.
1666 ProfileMergeInlinee = false;
1667 }
1668
1669 for (Function &F : M)
1670 if (!F.isDeclaration() && F.hasFnAttribute("use-sample-profile"))
1671 FunctionOrderList.push_back(&F);
1672 return FunctionOrderList;
1673 }
1674
1675 assert(&CG->getModule() == &M);
1676
1677 if (UseProfiledCallGraph ||
1678 (ProfileIsCS && !UseProfiledCallGraph.getNumOccurrences())) {
1679 // Use profiled call edges to augment the top-down order. There are cases
1680 // that the top-down order computed based on the static call graph doesn't
1681 // reflect real execution order. For example
1682 //
1683 // 1. Incomplete static call graph due to unknown indirect call targets.
1684 // Adjusting the order by considering indirect call edges from the
1685 // profile can enable the inlining of indirect call targets by allowing
1686 // the caller processed before them.
1687 // 2. Mutual call edges in an SCC. The static processing order computed for
1688 // an SCC may not reflect the call contexts in the context-sensitive
1689 // profile, thus may cause potential inlining to be overlooked. The
1690 // function order in one SCC is being adjusted to a top-down order based
1691 // on the profile to favor more inlining. This is only a problem with CS
1692 // profile.
1693 // 3. Transitive indirect call edges due to inlining. When a callee function
1694 // (say B) is inlined into into a caller function (say A) in LTO prelink,
1695 // every call edge originated from the callee B will be transferred to
1696 // the caller A. If any transferred edge (say A->C) is indirect, the
1697 // original profiled indirect edge B->C, even if considered, would not
1698 // enforce a top-down order from the caller A to the potential indirect
1699 // call target C in LTO postlink since the inlined callee B is gone from
1700 // the static call graph.
1701 // 4. #3 can happen even for direct call targets, due to functions defined
1702 // in header files. A header function (say A), when included into source
1703 // files, is defined multiple times but only one definition survives due
1704 // to ODR. Therefore, the LTO prelink inlining done on those dropped
1705 // definitions can be useless based on a local file scope. More
1706 // importantly, the inlinee (say B), once fully inlined to a
1707 // to-be-dropped A, will have no profile to consume when its outlined
1708 // version is compiled. This can lead to a profile-less prelink
1709 // compilation for the outlined version of B which may be called from
1710 // external modules. while this isn't easy to fix, we rely on the
1711 // postlink AutoFDO pipeline to optimize B. Since the survived copy of
1712 // the A can be inlined in its local scope in prelink, it may not exist
1713 // in the merged IR in postlink, and we'll need the profiled call edges
1714 // to enforce a top-down order for the rest of the functions.
1715 //
1716 // Considering those cases, a profiled call graph completely independent of
1717 // the static call graph is constructed based on profile data, where
1718 // function objects are not even needed to handle case #3 and case 4.
1719 //
1720 // Note that static callgraph edges are completely ignored since they
1721 // can be conflicting with profiled edges for cyclic SCCs and may result in
1722 // an SCC order incompatible with profile-defined one. Using strictly
1723 // profile order ensures a maximum inlining experience. On the other hand,
1724 // static call edges are not so important when they don't correspond to a
1725 // context in the profile.
1726
1727 std::unique_ptr<ProfiledCallGraph> ProfiledCG = buildProfiledCallGraph(*CG);
1728 scc_iterator<ProfiledCallGraph *> CGI = scc_begin(ProfiledCG.get());
1729 while (!CGI.isAtEnd()) {
1730 for (ProfiledCallGraphNode *Node : *CGI) {
1731 Function *F = SymbolMap.lookup(Node->Name);
1732 if (F && !F->isDeclaration() && F->hasFnAttribute("use-sample-profile"))
1733 FunctionOrderList.push_back(F);
1734 }
1735 ++CGI;
1736 }
1737 } else {
1738 scc_iterator<CallGraph *> CGI = scc_begin(CG);
1739 while (!CGI.isAtEnd()) {
1740 for (CallGraphNode *Node : *CGI) {
1741 auto *F = Node->getFunction();
1742 if (F && !F->isDeclaration() && F->hasFnAttribute("use-sample-profile"))
1743 FunctionOrderList.push_back(F);
1744 }
1745 ++CGI;
1746 }
1747 }
1748
1749 LLVM_DEBUG({
1750 dbgs() << "Function processing order:\n";
1751 for (auto F : reverse(FunctionOrderList)) {
1752 dbgs() << F->getName() << "\n";
1753 }
1754 });
1755
1756 std::reverse(FunctionOrderList.begin(), FunctionOrderList.end());
1757 return FunctionOrderList;
1758 }
1759
doInitialization(Module & M,FunctionAnalysisManager * FAM)1760 bool SampleProfileLoader::doInitialization(Module &M,
1761 FunctionAnalysisManager *FAM) {
1762 auto &Ctx = M.getContext();
1763
1764 auto ReaderOrErr = SampleProfileReader::create(
1765 Filename, Ctx, FSDiscriminatorPass::Base, RemappingFilename);
1766 if (std::error_code EC = ReaderOrErr.getError()) {
1767 std::string Msg = "Could not open profile: " + EC.message();
1768 Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
1769 return false;
1770 }
1771 Reader = std::move(ReaderOrErr.get());
1772 Reader->setSkipFlatProf(LTOPhase == ThinOrFullLTOPhase::ThinLTOPostLink);
1773 // set module before reading the profile so reader may be able to only
1774 // read the function profiles which are used by the current module.
1775 Reader->setModule(&M);
1776 if (std::error_code EC = Reader->read()) {
1777 std::string Msg = "profile reading failed: " + EC.message();
1778 Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
1779 return false;
1780 }
1781
1782 PSL = Reader->getProfileSymbolList();
1783
1784 // While profile-sample-accurate is on, ignore symbol list.
1785 ProfAccForSymsInList =
1786 ProfileAccurateForSymsInList && PSL && !ProfileSampleAccurate;
1787 if (ProfAccForSymsInList) {
1788 NamesInProfile.clear();
1789 if (auto NameTable = Reader->getNameTable())
1790 NamesInProfile.insert(NameTable->begin(), NameTable->end());
1791 CoverageTracker.setProfAccForSymsInList(true);
1792 }
1793
1794 if (FAM && !ProfileInlineReplayFile.empty()) {
1795 ExternalInlineAdvisor = std::make_unique<ReplayInlineAdvisor>(
1796 M, *FAM, Ctx, /*OriginalAdvisor=*/nullptr, ProfileInlineReplayFile,
1797 /*EmitRemarks=*/false);
1798 if (!ExternalInlineAdvisor->areReplayRemarksLoaded())
1799 ExternalInlineAdvisor.reset();
1800 }
1801
1802 // Apply tweaks if context-sensitive profile is available.
1803 if (Reader->profileIsCS()) {
1804 ProfileIsCS = true;
1805 FunctionSamples::ProfileIsCS = true;
1806
1807 // Enable priority-base inliner and size inline by default for CSSPGO.
1808 if (!ProfileSizeInline.getNumOccurrences())
1809 ProfileSizeInline = true;
1810 if (!CallsitePrioritizedInline.getNumOccurrences())
1811 CallsitePrioritizedInline = true;
1812
1813 // Enable iterative-BFI by default for CSSPGO.
1814 if (!UseIterativeBFIInference.getNumOccurrences())
1815 UseIterativeBFIInference = true;
1816
1817 // Tracker for profiles under different context
1818 ContextTracker =
1819 std::make_unique<SampleContextTracker>(Reader->getProfiles());
1820 }
1821
1822 // Load pseudo probe descriptors for probe-based function samples.
1823 if (Reader->profileIsProbeBased()) {
1824 ProbeManager = std::make_unique<PseudoProbeManager>(M);
1825 if (!ProbeManager->moduleIsProbed(M)) {
1826 const char *Msg =
1827 "Pseudo-probe-based profile requires SampleProfileProbePass";
1828 Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
1829 return false;
1830 }
1831 }
1832
1833 return true;
1834 }
1835
createSampleProfileLoaderPass()1836 ModulePass *llvm::createSampleProfileLoaderPass() {
1837 return new SampleProfileLoaderLegacyPass();
1838 }
1839
createSampleProfileLoaderPass(StringRef Name)1840 ModulePass *llvm::createSampleProfileLoaderPass(StringRef Name) {
1841 return new SampleProfileLoaderLegacyPass(Name);
1842 }
1843
runOnModule(Module & M,ModuleAnalysisManager * AM,ProfileSummaryInfo * _PSI,CallGraph * CG)1844 bool SampleProfileLoader::runOnModule(Module &M, ModuleAnalysisManager *AM,
1845 ProfileSummaryInfo *_PSI, CallGraph *CG) {
1846 GUIDToFuncNameMapper Mapper(M, *Reader, GUIDToFuncNameMap);
1847
1848 PSI = _PSI;
1849 if (M.getProfileSummary(/* IsCS */ false) == nullptr) {
1850 M.setProfileSummary(Reader->getSummary().getMD(M.getContext()),
1851 ProfileSummary::PSK_Sample);
1852 PSI->refresh();
1853 }
1854 // Compute the total number of samples collected in this profile.
1855 for (const auto &I : Reader->getProfiles())
1856 TotalCollectedSamples += I.second.getTotalSamples();
1857
1858 auto Remapper = Reader->getRemapper();
1859 // Populate the symbol map.
1860 for (const auto &N_F : M.getValueSymbolTable()) {
1861 StringRef OrigName = N_F.getKey();
1862 Function *F = dyn_cast<Function>(N_F.getValue());
1863 if (F == nullptr || OrigName.empty())
1864 continue;
1865 SymbolMap[OrigName] = F;
1866 StringRef NewName = FunctionSamples::getCanonicalFnName(*F);
1867 if (OrigName != NewName && !NewName.empty()) {
1868 auto r = SymbolMap.insert(std::make_pair(NewName, F));
1869 // Failiing to insert means there is already an entry in SymbolMap,
1870 // thus there are multiple functions that are mapped to the same
1871 // stripped name. In this case of name conflicting, set the value
1872 // to nullptr to avoid confusion.
1873 if (!r.second)
1874 r.first->second = nullptr;
1875 OrigName = NewName;
1876 }
1877 // Insert the remapped names into SymbolMap.
1878 if (Remapper) {
1879 if (auto MapName = Remapper->lookUpNameInProfile(OrigName)) {
1880 if (*MapName != OrigName && !MapName->empty())
1881 SymbolMap.insert(std::make_pair(*MapName, F));
1882 }
1883 }
1884 }
1885 assert(SymbolMap.count(StringRef()) == 0 &&
1886 "No empty StringRef should be added in SymbolMap");
1887
1888 bool retval = false;
1889 for (auto F : buildFunctionOrder(M, CG)) {
1890 assert(!F->isDeclaration());
1891 clearFunctionData();
1892 retval |= runOnFunction(*F, AM);
1893 }
1894
1895 // Account for cold calls not inlined....
1896 if (!ProfileIsCS)
1897 for (const std::pair<Function *, NotInlinedProfileInfo> &pair :
1898 notInlinedCallInfo)
1899 updateProfileCallee(pair.first, pair.second.entryCount);
1900
1901 return retval;
1902 }
1903
runOnModule(Module & M)1904 bool SampleProfileLoaderLegacyPass::runOnModule(Module &M) {
1905 ACT = &getAnalysis<AssumptionCacheTracker>();
1906 TTIWP = &getAnalysis<TargetTransformInfoWrapperPass>();
1907 TLIWP = &getAnalysis<TargetLibraryInfoWrapperPass>();
1908 ProfileSummaryInfo *PSI =
1909 &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
1910 return SampleLoader.runOnModule(M, nullptr, PSI, nullptr);
1911 }
1912
runOnFunction(Function & F,ModuleAnalysisManager * AM)1913 bool SampleProfileLoader::runOnFunction(Function &F, ModuleAnalysisManager *AM) {
1914 LLVM_DEBUG(dbgs() << "\n\nProcessing Function " << F.getName() << "\n");
1915 DILocation2SampleMap.clear();
1916 // By default the entry count is initialized to -1, which will be treated
1917 // conservatively by getEntryCount as the same as unknown (None). This is
1918 // to avoid newly added code to be treated as cold. If we have samples
1919 // this will be overwritten in emitAnnotations.
1920 uint64_t initialEntryCount = -1;
1921
1922 ProfAccForSymsInList = ProfileAccurateForSymsInList && PSL;
1923 if (ProfileSampleAccurate || F.hasFnAttribute("profile-sample-accurate")) {
1924 // initialize all the function entry counts to 0. It means all the
1925 // functions without profile will be regarded as cold.
1926 initialEntryCount = 0;
1927 // profile-sample-accurate is a user assertion which has a higher precedence
1928 // than symbol list. When profile-sample-accurate is on, ignore symbol list.
1929 ProfAccForSymsInList = false;
1930 }
1931 CoverageTracker.setProfAccForSymsInList(ProfAccForSymsInList);
1932
1933 // PSL -- profile symbol list include all the symbols in sampled binary.
1934 // If ProfileAccurateForSymsInList is enabled, PSL is used to treat
1935 // old functions without samples being cold, without having to worry
1936 // about new and hot functions being mistakenly treated as cold.
1937 if (ProfAccForSymsInList) {
1938 // Initialize the entry count to 0 for functions in the list.
1939 if (PSL->contains(F.getName()))
1940 initialEntryCount = 0;
1941
1942 // Function in the symbol list but without sample will be regarded as
1943 // cold. To minimize the potential negative performance impact it could
1944 // have, we want to be a little conservative here saying if a function
1945 // shows up in the profile, no matter as outline function, inline instance
1946 // or call targets, treat the function as not being cold. This will handle
1947 // the cases such as most callsites of a function are inlined in sampled
1948 // binary but not inlined in current build (because of source code drift,
1949 // imprecise debug information, or the callsites are all cold individually
1950 // but not cold accumulatively...), so the outline function showing up as
1951 // cold in sampled binary will actually not be cold after current build.
1952 StringRef CanonName = FunctionSamples::getCanonicalFnName(F);
1953 if (NamesInProfile.count(CanonName))
1954 initialEntryCount = -1;
1955 }
1956
1957 // Initialize entry count when the function has no existing entry
1958 // count value.
1959 if (!F.getEntryCount().hasValue())
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
1972 if (ProfileIsCS)
1973 Samples = ContextTracker->getBaseSamplesFor(F);
1974 else
1975 Samples = Reader->getSamplesFor(F);
1976
1977 if (Samples && !Samples->empty())
1978 return emitAnnotations(F);
1979 return false;
1980 }
1981
run(Module & M,ModuleAnalysisManager & AM)1982 PreservedAnalyses SampleProfileLoaderPass::run(Module &M,
1983 ModuleAnalysisManager &AM) {
1984 FunctionAnalysisManager &FAM =
1985 AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1986
1987 auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & {
1988 return FAM.getResult<AssumptionAnalysis>(F);
1989 };
1990 auto GetTTI = [&](Function &F) -> TargetTransformInfo & {
1991 return FAM.getResult<TargetIRAnalysis>(F);
1992 };
1993 auto GetTLI = [&](Function &F) -> const TargetLibraryInfo & {
1994 return FAM.getResult<TargetLibraryAnalysis>(F);
1995 };
1996
1997 SampleProfileLoader SampleLoader(
1998 ProfileFileName.empty() ? SampleProfileFile : ProfileFileName,
1999 ProfileRemappingFileName.empty() ? SampleProfileRemappingFile
2000 : ProfileRemappingFileName,
2001 LTOPhase, GetAssumptionCache, GetTTI, GetTLI);
2002
2003 if (!SampleLoader.doInitialization(M, &FAM))
2004 return PreservedAnalyses::all();
2005
2006 ProfileSummaryInfo *PSI = &AM.getResult<ProfileSummaryAnalysis>(M);
2007 CallGraph &CG = AM.getResult<CallGraphAnalysis>(M);
2008 if (!SampleLoader.runOnModule(M, &AM, PSI, &CG))
2009 return PreservedAnalyses::all();
2010
2011 return PreservedAnalyses::none();
2012 }
2013