1dd58ef01SDimitry Andric //===- SampleProfile.cpp - Incorporate sample profiles into the IR --------===//
2dd58ef01SDimitry Andric //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6dd58ef01SDimitry Andric //
7dd58ef01SDimitry Andric //===----------------------------------------------------------------------===//
8dd58ef01SDimitry Andric //
9dd58ef01SDimitry Andric // This file implements the SampleProfileLoader transformation. This pass
10dd58ef01SDimitry Andric // reads a profile file generated by a sampling profiler (e.g. Linux Perf -
11dd58ef01SDimitry Andric // http://perf.wiki.kernel.org/) and generates IR metadata to reflect the
12dd58ef01SDimitry Andric // profile information in the given profile.
13dd58ef01SDimitry Andric //
14dd58ef01SDimitry Andric // This pass generates branch weight annotations on the IR:
15dd58ef01SDimitry Andric //
16dd58ef01SDimitry Andric // - prof: Represents branch weights. This annotation is added to branches
17dd58ef01SDimitry Andric // to indicate the weights of each edge coming out of the branch.
18dd58ef01SDimitry Andric // The weight of each edge is the weight of the target block for
19dd58ef01SDimitry Andric // that edge. The weight of a block B is computed as the maximum
20dd58ef01SDimitry Andric // number of samples found in B.
21dd58ef01SDimitry Andric //
22dd58ef01SDimitry Andric //===----------------------------------------------------------------------===//
23dd58ef01SDimitry Andric
24eb11fae6SDimitry Andric #include "llvm/Transforms/IPO/SampleProfile.h"
25044eb2f6SDimitry Andric #include "llvm/ADT/ArrayRef.h"
26dd58ef01SDimitry Andric #include "llvm/ADT/DenseMap.h"
27044eb2f6SDimitry Andric #include "llvm/ADT/DenseSet.h"
28e3b55780SDimitry Andric #include "llvm/ADT/MapVector.h"
29344a3780SDimitry Andric #include "llvm/ADT/PriorityQueue.h"
30706b4fc4SDimitry Andric #include "llvm/ADT/SCCIterator.h"
31044eb2f6SDimitry Andric #include "llvm/ADT/SmallVector.h"
32706b4fc4SDimitry Andric #include "llvm/ADT/Statistic.h"
33044eb2f6SDimitry Andric #include "llvm/ADT/StringMap.h"
34dd58ef01SDimitry Andric #include "llvm/ADT/StringRef.h"
35044eb2f6SDimitry Andric #include "llvm/ADT/Twine.h"
3601095a5dSDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
37344a3780SDimitry Andric #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
38cfca06d7SDimitry Andric #include "llvm/Analysis/InlineAdvisor.h"
39044eb2f6SDimitry Andric #include "llvm/Analysis/InlineCost.h"
407fa27ce4SDimitry Andric #include "llvm/Analysis/LazyCallGraph.h"
41044eb2f6SDimitry Andric #include "llvm/Analysis/OptimizationRemarkEmitter.h"
42eb11fae6SDimitry Andric #include "llvm/Analysis/ProfileSummaryInfo.h"
43b60736ecSDimitry Andric #include "llvm/Analysis/ReplayInlineAdvisor.h"
44cfca06d7SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
45044eb2f6SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
46044eb2f6SDimitry Andric #include "llvm/IR/BasicBlock.h"
47044eb2f6SDimitry Andric #include "llvm/IR/DebugLoc.h"
48dd58ef01SDimitry Andric #include "llvm/IR/DiagnosticInfo.h"
49dd58ef01SDimitry Andric #include "llvm/IR/Function.h"
5071d5a254SDimitry Andric #include "llvm/IR/GlobalValue.h"
51044eb2f6SDimitry Andric #include "llvm/IR/InstrTypes.h"
52044eb2f6SDimitry Andric #include "llvm/IR/Instruction.h"
53dd58ef01SDimitry Andric #include "llvm/IR/Instructions.h"
5401095a5dSDimitry Andric #include "llvm/IR/IntrinsicInst.h"
55dd58ef01SDimitry Andric #include "llvm/IR/LLVMContext.h"
56dd58ef01SDimitry Andric #include "llvm/IR/MDBuilder.h"
57dd58ef01SDimitry Andric #include "llvm/IR/Module.h"
58044eb2f6SDimitry Andric #include "llvm/IR/PassManager.h"
59b1c73532SDimitry Andric #include "llvm/IR/ProfDataUtils.h"
60145449b1SDimitry Andric #include "llvm/IR/PseudoProbe.h"
61d99dafe2SDimitry Andric #include "llvm/IR/ValueSymbolTable.h"
6271d5a254SDimitry Andric #include "llvm/ProfileData/InstrProf.h"
63044eb2f6SDimitry Andric #include "llvm/ProfileData/SampleProf.h"
64dd58ef01SDimitry Andric #include "llvm/ProfileData/SampleProfReader.h"
65044eb2f6SDimitry Andric #include "llvm/Support/Casting.h"
66dd58ef01SDimitry Andric #include "llvm/Support/CommandLine.h"
67dd58ef01SDimitry Andric #include "llvm/Support/Debug.h"
68dd58ef01SDimitry Andric #include "llvm/Support/ErrorOr.h"
697fa27ce4SDimitry Andric #include "llvm/Support/VirtualFileSystem.h"
70dd58ef01SDimitry Andric #include "llvm/Support/raw_ostream.h"
71dd58ef01SDimitry Andric #include "llvm/Transforms/IPO.h"
72344a3780SDimitry Andric #include "llvm/Transforms/IPO/ProfiledCallGraph.h"
73b60736ecSDimitry Andric #include "llvm/Transforms/IPO/SampleContextTracker.h"
74ac9a064cSDimitry Andric #include "llvm/Transforms/IPO/SampleProfileMatcher.h"
75b60736ecSDimitry Andric #include "llvm/Transforms/IPO/SampleProfileProbe.h"
7671d5a254SDimitry Andric #include "llvm/Transforms/Instrumentation.h"
77044eb2f6SDimitry Andric #include "llvm/Transforms/Utils/CallPromotionUtils.h"
78dd58ef01SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
79e3b55780SDimitry Andric #include "llvm/Transforms/Utils/MisExpect.h"
80344a3780SDimitry Andric #include "llvm/Transforms/Utils/SampleProfileLoaderBaseImpl.h"
81344a3780SDimitry Andric #include "llvm/Transforms/Utils/SampleProfileLoaderBaseUtil.h"
82044eb2f6SDimitry Andric #include <algorithm>
83044eb2f6SDimitry Andric #include <cassert>
84044eb2f6SDimitry Andric #include <cstdint>
85044eb2f6SDimitry Andric #include <functional>
86044eb2f6SDimitry Andric #include <limits>
87044eb2f6SDimitry Andric #include <map>
88044eb2f6SDimitry Andric #include <memory>
891d5ae102SDimitry Andric #include <queue>
90044eb2f6SDimitry Andric #include <string>
91044eb2f6SDimitry Andric #include <system_error>
92044eb2f6SDimitry Andric #include <utility>
93044eb2f6SDimitry Andric #include <vector>
94dd58ef01SDimitry Andric
95dd58ef01SDimitry Andric using namespace llvm;
96dd58ef01SDimitry Andric using namespace sampleprof;
97344a3780SDimitry Andric using namespace llvm::sampleprofutil;
98eb11fae6SDimitry Andric using ProfileCount = Function::ProfileCount;
99dd58ef01SDimitry Andric #define DEBUG_TYPE "sample-profile"
100706b4fc4SDimitry Andric #define CSINLINE_DEBUG DEBUG_TYPE "-inline"
101706b4fc4SDimitry Andric
102706b4fc4SDimitry Andric STATISTIC(NumCSInlined,
103706b4fc4SDimitry Andric "Number of functions inlined with context sensitive profile");
104706b4fc4SDimitry Andric STATISTIC(NumCSNotInlined,
105706b4fc4SDimitry Andric "Number of functions not inlined with context sensitive profile");
106b60736ecSDimitry Andric STATISTIC(NumMismatchedProfile,
107b60736ecSDimitry Andric "Number of functions with CFG mismatched profile");
108b60736ecSDimitry Andric STATISTIC(NumMatchedProfile, "Number of functions with CFG matched profile");
109344a3780SDimitry Andric STATISTIC(NumDuplicatedInlinesite,
110344a3780SDimitry Andric "Number of inlined callsites with a partial distribution factor");
111344a3780SDimitry Andric
112344a3780SDimitry Andric STATISTIC(NumCSInlinedHitMinLimit,
113344a3780SDimitry Andric "Number of functions with FDO inline stopped due to min size limit");
114344a3780SDimitry Andric STATISTIC(NumCSInlinedHitMaxLimit,
115344a3780SDimitry Andric "Number of functions with FDO inline stopped due to max size limit");
116344a3780SDimitry Andric STATISTIC(
117344a3780SDimitry Andric NumCSInlinedHitGrowthLimit,
118344a3780SDimitry Andric "Number of functions with FDO inline stopped due to growth size limit");
119dd58ef01SDimitry Andric
120dd58ef01SDimitry Andric // Command line option to specify the file to read samples from. This is
121dd58ef01SDimitry Andric // mainly used for debugging.
122dd58ef01SDimitry Andric static cl::opt<std::string> SampleProfileFile(
123dd58ef01SDimitry Andric "sample-profile-file", cl::init(""), cl::value_desc("filename"),
124dd58ef01SDimitry Andric cl::desc("Profile file loaded by -sample-profile"), cl::Hidden);
125044eb2f6SDimitry Andric
126d8e91e46SDimitry Andric // The named file contains a set of transformations that may have been applied
127d8e91e46SDimitry Andric // to the symbol names between the program from which the sample data was
128d8e91e46SDimitry Andric // collected and the current program's symbols.
129d8e91e46SDimitry Andric static cl::opt<std::string> SampleProfileRemappingFile(
130d8e91e46SDimitry Andric "sample-profile-remapping-file", cl::init(""), cl::value_desc("filename"),
131d8e91e46SDimitry Andric cl::desc("Profile remapping file loaded by -sample-profile"), cl::Hidden);
132d8e91e46SDimitry Andric
133ac9a064cSDimitry Andric cl::opt<bool> SalvageStaleProfile(
1347fa27ce4SDimitry Andric "salvage-stale-profile", cl::Hidden, cl::init(false),
1357fa27ce4SDimitry Andric cl::desc("Salvage stale profile by fuzzy matching and use the remapped "
1367fa27ce4SDimitry Andric "location for sample profile query."));
137ac9a064cSDimitry Andric cl::opt<bool>
138ac9a064cSDimitry Andric SalvageUnusedProfile("salvage-unused-profile", cl::Hidden, cl::init(false),
139ac9a064cSDimitry Andric cl::desc("Salvage unused profile by matching with new "
140ac9a064cSDimitry Andric "functions on call graph."));
1417fa27ce4SDimitry Andric
142ac9a064cSDimitry Andric cl::opt<bool> ReportProfileStaleness(
143e3b55780SDimitry Andric "report-profile-staleness", cl::Hidden, cl::init(false),
144e3b55780SDimitry Andric cl::desc("Compute and report stale profile statistical metrics."));
145e3b55780SDimitry Andric
146ac9a064cSDimitry Andric cl::opt<bool> PersistProfileStaleness(
147e3b55780SDimitry Andric "persist-profile-staleness", cl::Hidden, cl::init(false),
148e3b55780SDimitry Andric cl::desc("Compute stale profile statistical metrics and write it into the "
149e3b55780SDimitry Andric "native object file(.llvm_stats section)."));
150e3b55780SDimitry Andric
151d8e91e46SDimitry Andric static cl::opt<bool> ProfileSampleAccurate(
152d8e91e46SDimitry Andric "profile-sample-accurate", cl::Hidden, cl::init(false),
153d8e91e46SDimitry Andric cl::desc("If the sample profile is accurate, we will mark all un-sampled "
154d8e91e46SDimitry Andric "callsite and function as having 0 samples. Otherwise, treat "
155d8e91e46SDimitry Andric "un-sampled callsites and functions conservatively as unknown. "));
156d8e91e46SDimitry Andric
157c0981da4SDimitry Andric static cl::opt<bool> ProfileSampleBlockAccurate(
158c0981da4SDimitry Andric "profile-sample-block-accurate", cl::Hidden, cl::init(false),
159c0981da4SDimitry Andric cl::desc("If the sample profile is accurate, we will mark all un-sampled "
160c0981da4SDimitry Andric "branches and calls as having 0 samples. Otherwise, treat "
161c0981da4SDimitry Andric "them conservatively as unknown. "));
162c0981da4SDimitry Andric
1631d5ae102SDimitry Andric static cl::opt<bool> ProfileAccurateForSymsInList(
164145449b1SDimitry Andric "profile-accurate-for-symsinlist", cl::Hidden, cl::init(true),
1651d5ae102SDimitry Andric cl::desc("For symbols in profile symbol list, regard their profiles to "
1661d5ae102SDimitry Andric "be accurate. It may be overriden by profile-sample-accurate. "));
1671d5ae102SDimitry Andric
168706b4fc4SDimitry Andric static cl::opt<bool> ProfileMergeInlinee(
169cfca06d7SDimitry Andric "sample-profile-merge-inlinee", cl::Hidden, cl::init(true),
170706b4fc4SDimitry Andric cl::desc("Merge past inlinee's profile to outline version if sample "
171cfca06d7SDimitry Andric "profile loader decided not to inline a call site. It will "
172cfca06d7SDimitry Andric "only be enabled when top-down order of profile loading is "
173cfca06d7SDimitry Andric "enabled. "));
174706b4fc4SDimitry Andric
175706b4fc4SDimitry Andric static cl::opt<bool> ProfileTopDownLoad(
176cfca06d7SDimitry Andric "sample-profile-top-down-load", cl::Hidden, cl::init(true),
177706b4fc4SDimitry Andric cl::desc("Do profile annotation and inlining for functions in top-down "
178cfca06d7SDimitry Andric "order of call graph during sample profile loading. It only "
179cfca06d7SDimitry Andric "works for new pass manager. "));
180706b4fc4SDimitry Andric
181344a3780SDimitry Andric static cl::opt<bool>
182344a3780SDimitry Andric UseProfiledCallGraph("use-profiled-call-graph", cl::init(true), cl::Hidden,
183344a3780SDimitry Andric cl::desc("Process functions in a top-down order "
184344a3780SDimitry Andric "defined by the profiled call graph when "
185344a3780SDimitry Andric "-sample-profile-top-down-load is on."));
186344a3780SDimitry Andric
187706b4fc4SDimitry Andric static cl::opt<bool> ProfileSizeInline(
188706b4fc4SDimitry Andric "sample-profile-inline-size", cl::Hidden, cl::init(false),
189706b4fc4SDimitry Andric cl::desc("Inline cold call sites in profile loader if it's beneficial "
190706b4fc4SDimitry Andric "for code size."));
191706b4fc4SDimitry Andric
192145449b1SDimitry Andric // Since profiles are consumed by many passes, turning on this option has
193145449b1SDimitry Andric // side effects. For instance, pre-link SCC inliner would see merged profiles
194145449b1SDimitry Andric // and inline the hot functions (that are skipped in this pass).
195145449b1SDimitry Andric static cl::opt<bool> DisableSampleLoaderInlining(
196145449b1SDimitry Andric "disable-sample-loader-inlining", cl::Hidden, cl::init(false),
197145449b1SDimitry Andric cl::desc("If true, artifically skip inline transformation in sample-loader "
198145449b1SDimitry Andric "pass, and merge (or scale) profiles (as configured by "
199145449b1SDimitry Andric "--sample-profile-merge-inlinee)."));
200145449b1SDimitry Andric
2017fa27ce4SDimitry Andric namespace llvm {
2027fa27ce4SDimitry Andric cl::opt<bool>
2037fa27ce4SDimitry Andric SortProfiledSCC("sort-profiled-scc-member", cl::init(true), cl::Hidden,
2047fa27ce4SDimitry Andric cl::desc("Sort profiled recursion by edge weights."));
2057fa27ce4SDimitry Andric
206344a3780SDimitry Andric cl::opt<int> ProfileInlineGrowthLimit(
207344a3780SDimitry Andric "sample-profile-inline-growth-limit", cl::Hidden, cl::init(12),
208344a3780SDimitry Andric cl::desc("The size growth ratio limit for proirity-based sample profile "
209344a3780SDimitry Andric "loader inlining."));
210344a3780SDimitry Andric
211344a3780SDimitry Andric cl::opt<int> ProfileInlineLimitMin(
212344a3780SDimitry Andric "sample-profile-inline-limit-min", cl::Hidden, cl::init(100),
213344a3780SDimitry Andric cl::desc("The lower bound of size growth limit for "
214344a3780SDimitry Andric "proirity-based sample profile loader inlining."));
215344a3780SDimitry Andric
216344a3780SDimitry Andric cl::opt<int> ProfileInlineLimitMax(
217344a3780SDimitry Andric "sample-profile-inline-limit-max", cl::Hidden, cl::init(10000),
218344a3780SDimitry Andric cl::desc("The upper bound of size growth limit for "
219344a3780SDimitry Andric "proirity-based sample profile loader inlining."));
220344a3780SDimitry Andric
221344a3780SDimitry Andric cl::opt<int> SampleHotCallSiteThreshold(
222344a3780SDimitry Andric "sample-profile-hot-inline-threshold", cl::Hidden, cl::init(3000),
223344a3780SDimitry Andric cl::desc("Hot callsite threshold for proirity-based sample profile loader "
224344a3780SDimitry Andric "inlining."));
225344a3780SDimitry Andric
226344a3780SDimitry Andric cl::opt<int> SampleColdCallSiteThreshold(
227706b4fc4SDimitry Andric "sample-profile-cold-inline-threshold", cl::Hidden, cl::init(45),
228706b4fc4SDimitry Andric cl::desc("Threshold for inlining cold callsites"));
2297fa27ce4SDimitry Andric } // namespace llvm
230706b4fc4SDimitry Andric
231344a3780SDimitry Andric static cl::opt<unsigned> ProfileICPRelativeHotness(
232344a3780SDimitry Andric "sample-profile-icp-relative-hotness", cl::Hidden, cl::init(25),
233344a3780SDimitry Andric cl::desc(
234344a3780SDimitry Andric "Relative hotness percentage threshold for indirect "
235344a3780SDimitry Andric "call promotion in proirity-based sample profile loader inlining."));
236344a3780SDimitry Andric
237344a3780SDimitry Andric static cl::opt<unsigned> ProfileICPRelativeHotnessSkip(
238344a3780SDimitry Andric "sample-profile-icp-relative-hotness-skip", cl::Hidden, cl::init(1),
239344a3780SDimitry Andric cl::desc(
240344a3780SDimitry Andric "Skip relative hotness check for ICP up to given number of targets."));
241344a3780SDimitry Andric
242ac9a064cSDimitry Andric static cl::opt<unsigned> HotFuncCutoffForStalenessError(
243ac9a064cSDimitry Andric "hot-func-cutoff-for-staleness-error", cl::Hidden, cl::init(800000),
244ac9a064cSDimitry Andric cl::desc("A function is considered hot for staleness error check if its "
245ac9a064cSDimitry Andric "total sample count is above the specified percentile"));
246ac9a064cSDimitry Andric
247ac9a064cSDimitry Andric static cl::opt<unsigned> MinfuncsForStalenessError(
248ac9a064cSDimitry Andric "min-functions-for-staleness-error", cl::Hidden, cl::init(50),
249ac9a064cSDimitry Andric cl::desc("Skip the check if the number of hot functions is smaller than "
250ac9a064cSDimitry Andric "the specified number."));
251ac9a064cSDimitry Andric
252ac9a064cSDimitry Andric static cl::opt<unsigned> PrecentMismatchForStalenessError(
253ac9a064cSDimitry Andric "precent-mismatch-for-staleness-error", cl::Hidden, cl::init(80),
254ac9a064cSDimitry Andric cl::desc("Reject the profile if the mismatch percent is higher than the "
255ac9a064cSDimitry Andric "given number."));
256ac9a064cSDimitry Andric
257344a3780SDimitry Andric static cl::opt<bool> CallsitePrioritizedInline(
258145449b1SDimitry Andric "sample-profile-prioritized-inline", cl::Hidden,
259344a3780SDimitry Andric cl::desc("Use call site prioritized inlining for sample profile loader."
260344a3780SDimitry Andric "Currently only CSSPGO is supported."));
261344a3780SDimitry Andric
262c0981da4SDimitry Andric static cl::opt<bool> UsePreInlinerDecision(
263145449b1SDimitry Andric "sample-profile-use-preinliner", cl::Hidden,
264c0981da4SDimitry Andric cl::desc("Use the preinliner decisions stored in profile context."));
265c0981da4SDimitry Andric
266c0981da4SDimitry Andric static cl::opt<bool> AllowRecursiveInline(
267145449b1SDimitry Andric "sample-profile-recursive-inline", cl::Hidden,
268c0981da4SDimitry Andric cl::desc("Allow sample loader inliner to inline recursive calls."));
269c0981da4SDimitry Andric
270ac9a064cSDimitry Andric static cl::opt<bool> RemoveProbeAfterProfileAnnotation(
271ac9a064cSDimitry Andric "sample-profile-remove-probe", cl::Hidden, cl::init(false),
272ac9a064cSDimitry Andric cl::desc("Remove pseudo-probe after sample profile annotation."));
273ac9a064cSDimitry Andric
274b60736ecSDimitry Andric static cl::opt<std::string> ProfileInlineReplayFile(
275b60736ecSDimitry Andric "sample-profile-inline-replay", cl::init(""), cl::value_desc("filename"),
276b60736ecSDimitry Andric cl::desc(
277b60736ecSDimitry Andric "Optimization remarks file containing inline remarks to be replayed "
278b60736ecSDimitry Andric "by inlining from sample profile loader."),
279b60736ecSDimitry Andric cl::Hidden);
280b60736ecSDimitry Andric
281c0981da4SDimitry Andric static cl::opt<ReplayInlinerSettings::Scope> ProfileInlineReplayScope(
282c0981da4SDimitry Andric "sample-profile-inline-replay-scope",
283c0981da4SDimitry Andric cl::init(ReplayInlinerSettings::Scope::Function),
284c0981da4SDimitry Andric cl::values(clEnumValN(ReplayInlinerSettings::Scope::Function, "Function",
285c0981da4SDimitry Andric "Replay on functions that have remarks associated "
286c0981da4SDimitry Andric "with them (default)"),
287c0981da4SDimitry Andric clEnumValN(ReplayInlinerSettings::Scope::Module, "Module",
288c0981da4SDimitry Andric "Replay on the entire module")),
289c0981da4SDimitry Andric cl::desc("Whether inline replay should be applied to the entire "
290c0981da4SDimitry Andric "Module or just the Functions (default) that are present as "
291c0981da4SDimitry Andric "callers in remarks during sample profile inlining."),
292c0981da4SDimitry Andric cl::Hidden);
293c0981da4SDimitry Andric
294c0981da4SDimitry Andric static cl::opt<ReplayInlinerSettings::Fallback> ProfileInlineReplayFallback(
295c0981da4SDimitry Andric "sample-profile-inline-replay-fallback",
296c0981da4SDimitry Andric cl::init(ReplayInlinerSettings::Fallback::Original),
297c0981da4SDimitry Andric cl::values(
298c0981da4SDimitry Andric clEnumValN(
299c0981da4SDimitry Andric ReplayInlinerSettings::Fallback::Original, "Original",
300c0981da4SDimitry Andric "All decisions not in replay send to original advisor (default)"),
301c0981da4SDimitry Andric clEnumValN(ReplayInlinerSettings::Fallback::AlwaysInline,
302c0981da4SDimitry Andric "AlwaysInline", "All decisions not in replay are inlined"),
303c0981da4SDimitry Andric clEnumValN(ReplayInlinerSettings::Fallback::NeverInline, "NeverInline",
304c0981da4SDimitry Andric "All decisions not in replay are not inlined")),
305c0981da4SDimitry Andric cl::desc("How sample profile inline replay treats sites that don't come "
306c0981da4SDimitry Andric "from the replay. Original: defers to original advisor, "
307c0981da4SDimitry Andric "AlwaysInline: inline all sites not in replay, NeverInline: "
308c0981da4SDimitry Andric "inline no sites not in replay"),
309c0981da4SDimitry Andric cl::Hidden);
310c0981da4SDimitry Andric
311c0981da4SDimitry Andric static cl::opt<CallSiteFormat::Format> ProfileInlineReplayFormat(
312c0981da4SDimitry Andric "sample-profile-inline-replay-format",
313c0981da4SDimitry Andric cl::init(CallSiteFormat::Format::LineColumnDiscriminator),
314c0981da4SDimitry Andric cl::values(
315c0981da4SDimitry Andric clEnumValN(CallSiteFormat::Format::Line, "Line", "<Line Number>"),
316c0981da4SDimitry Andric clEnumValN(CallSiteFormat::Format::LineColumn, "LineColumn",
317c0981da4SDimitry Andric "<Line Number>:<Column Number>"),
318c0981da4SDimitry Andric clEnumValN(CallSiteFormat::Format::LineDiscriminator,
319c0981da4SDimitry Andric "LineDiscriminator", "<Line Number>.<Discriminator>"),
320c0981da4SDimitry Andric clEnumValN(CallSiteFormat::Format::LineColumnDiscriminator,
321c0981da4SDimitry Andric "LineColumnDiscriminator",
322c0981da4SDimitry Andric "<Line Number>:<Column Number>.<Discriminator> (default)")),
323c0981da4SDimitry Andric cl::desc("How sample profile inline replay file is formatted"), cl::Hidden);
324c0981da4SDimitry Andric
325344a3780SDimitry Andric static cl::opt<unsigned>
326344a3780SDimitry Andric MaxNumPromotions("sample-profile-icp-max-prom", cl::init(3), cl::Hidden,
327344a3780SDimitry Andric cl::desc("Max number of promotions for a single indirect "
328344a3780SDimitry Andric "call callsite in sample profile loader"));
329344a3780SDimitry Andric
330344a3780SDimitry Andric static cl::opt<bool> OverwriteExistingWeights(
331344a3780SDimitry Andric "overwrite-existing-weights", cl::Hidden, cl::init(false),
332344a3780SDimitry Andric cl::desc("Ignore existing branch weights on IR and always overwrite."));
333344a3780SDimitry Andric
334145449b1SDimitry Andric static cl::opt<bool> AnnotateSampleProfileInlinePhase(
335145449b1SDimitry Andric "annotate-sample-profile-inline-phase", cl::Hidden, cl::init(false),
336145449b1SDimitry Andric cl::desc("Annotate LTO phase (prelink / postlink), or main (no LTO) for "
337145449b1SDimitry Andric "sample-profile inline pass name."));
338145449b1SDimitry Andric
3397fa27ce4SDimitry Andric namespace llvm {
340145449b1SDimitry Andric extern cl::opt<bool> EnableExtTspBlockPlacement;
3417fa27ce4SDimitry Andric }
342145449b1SDimitry Andric
343dd58ef01SDimitry Andric namespace {
344044eb2f6SDimitry Andric
345044eb2f6SDimitry Andric using BlockWeightMap = DenseMap<const BasicBlock *, uint64_t>;
346044eb2f6SDimitry Andric using EquivalenceClassMap = DenseMap<const BasicBlock *, const BasicBlock *>;
347044eb2f6SDimitry Andric using Edge = std::pair<const BasicBlock *, const BasicBlock *>;
348044eb2f6SDimitry Andric using EdgeWeightMap = DenseMap<Edge, uint64_t>;
349044eb2f6SDimitry Andric using BlockEdgeMap =
350044eb2f6SDimitry Andric DenseMap<const BasicBlock *, SmallVector<const BasicBlock *, 8>>;
351dd58ef01SDimitry Andric
3521d5ae102SDimitry Andric class GUIDToFuncNameMapper {
3531d5ae102SDimitry Andric public:
GUIDToFuncNameMapper(Module & M,SampleProfileReader & Reader,DenseMap<uint64_t,StringRef> & GUIDToFuncNameMap)3541d5ae102SDimitry Andric GUIDToFuncNameMapper(Module &M, SampleProfileReader &Reader,
3551d5ae102SDimitry Andric DenseMap<uint64_t, StringRef> &GUIDToFuncNameMap)
3561d5ae102SDimitry Andric : CurrentReader(Reader), CurrentModule(M),
3571d5ae102SDimitry Andric CurrentGUIDToFuncNameMap(GUIDToFuncNameMap) {
358cfca06d7SDimitry Andric if (!CurrentReader.useMD5())
3591d5ae102SDimitry Andric return;
3601d5ae102SDimitry Andric
3611d5ae102SDimitry Andric for (const auto &F : CurrentModule) {
3621d5ae102SDimitry Andric StringRef OrigName = F.getName();
3631d5ae102SDimitry Andric CurrentGUIDToFuncNameMap.insert(
3641d5ae102SDimitry Andric {Function::getGUID(OrigName), OrigName});
3651d5ae102SDimitry Andric
3661d5ae102SDimitry Andric // Local to global var promotion used by optimization like thinlto
3671d5ae102SDimitry Andric // will rename the var and add suffix like ".llvm.xxx" to the
3681d5ae102SDimitry Andric // original local name. In sample profile, the suffixes of function
3691d5ae102SDimitry Andric // names are all stripped. Since it is possible that the mapper is
3701d5ae102SDimitry Andric // built in post-thin-link phase and var promotion has been done,
3711d5ae102SDimitry Andric // we need to add the substring of function name without the suffix
3721d5ae102SDimitry Andric // into the GUIDToFuncNameMap.
3731d5ae102SDimitry Andric StringRef CanonName = FunctionSamples::getCanonicalFnName(F);
3741d5ae102SDimitry Andric if (CanonName != OrigName)
3751d5ae102SDimitry Andric CurrentGUIDToFuncNameMap.insert(
3761d5ae102SDimitry Andric {Function::getGUID(CanonName), CanonName});
3771d5ae102SDimitry Andric }
3781d5ae102SDimitry Andric
3791d5ae102SDimitry Andric // Update GUIDToFuncNameMap for each function including inlinees.
3801d5ae102SDimitry Andric SetGUIDToFuncNameMapForAll(&CurrentGUIDToFuncNameMap);
3811d5ae102SDimitry Andric }
3821d5ae102SDimitry Andric
~GUIDToFuncNameMapper()3831d5ae102SDimitry Andric ~GUIDToFuncNameMapper() {
384cfca06d7SDimitry Andric if (!CurrentReader.useMD5())
3851d5ae102SDimitry Andric return;
3861d5ae102SDimitry Andric
3871d5ae102SDimitry Andric CurrentGUIDToFuncNameMap.clear();
3881d5ae102SDimitry Andric
3891d5ae102SDimitry Andric // Reset GUIDToFuncNameMap for of each function as they're no
3901d5ae102SDimitry Andric // longer valid at this point.
3911d5ae102SDimitry Andric SetGUIDToFuncNameMapForAll(nullptr);
3921d5ae102SDimitry Andric }
3931d5ae102SDimitry Andric
3941d5ae102SDimitry Andric private:
SetGUIDToFuncNameMapForAll(DenseMap<uint64_t,StringRef> * Map)3951d5ae102SDimitry Andric void SetGUIDToFuncNameMapForAll(DenseMap<uint64_t, StringRef> *Map) {
3961d5ae102SDimitry Andric std::queue<FunctionSamples *> FSToUpdate;
3971d5ae102SDimitry Andric for (auto &IFS : CurrentReader.getProfiles()) {
3981d5ae102SDimitry Andric FSToUpdate.push(&IFS.second);
3991d5ae102SDimitry Andric }
4001d5ae102SDimitry Andric
4011d5ae102SDimitry Andric while (!FSToUpdate.empty()) {
4021d5ae102SDimitry Andric FunctionSamples *FS = FSToUpdate.front();
4031d5ae102SDimitry Andric FSToUpdate.pop();
4041d5ae102SDimitry Andric FS->GUIDToFuncNameMap = Map;
4051d5ae102SDimitry Andric for (const auto &ICS : FS->getCallsiteSamples()) {
4061d5ae102SDimitry Andric const FunctionSamplesMap &FSMap = ICS.second;
407e3b55780SDimitry Andric for (const auto &IFS : FSMap) {
4081d5ae102SDimitry Andric FunctionSamples &FS = const_cast<FunctionSamples &>(IFS.second);
4091d5ae102SDimitry Andric FSToUpdate.push(&FS);
4101d5ae102SDimitry Andric }
4111d5ae102SDimitry Andric }
4121d5ae102SDimitry Andric }
4131d5ae102SDimitry Andric }
4141d5ae102SDimitry Andric
4151d5ae102SDimitry Andric SampleProfileReader &CurrentReader;
4161d5ae102SDimitry Andric Module &CurrentModule;
4171d5ae102SDimitry Andric DenseMap<uint64_t, StringRef> &CurrentGUIDToFuncNameMap;
418dd58ef01SDimitry Andric };
419dd58ef01SDimitry Andric
420344a3780SDimitry Andric // Inline candidate used by iterative callsite prioritized inliner
421344a3780SDimitry Andric struct InlineCandidate {
422344a3780SDimitry Andric CallBase *CallInstr;
423344a3780SDimitry Andric const FunctionSamples *CalleeSamples;
424344a3780SDimitry Andric // Prorated callsite count, which will be used to guide inlining. For example,
425344a3780SDimitry Andric // if a callsite is duplicated in LTO prelink, then in LTO postlink the two
426344a3780SDimitry Andric // copies will get their own distribution factors and their prorated counts
427344a3780SDimitry Andric // will be used to decide if they should be inlined independently.
428344a3780SDimitry Andric uint64_t CallsiteCount;
429344a3780SDimitry Andric // Call site distribution factor to prorate the profile samples for a
430344a3780SDimitry Andric // duplicated callsite. Default value is 1.0.
431344a3780SDimitry Andric float CallsiteDistribution;
432344a3780SDimitry Andric };
433344a3780SDimitry Andric
434344a3780SDimitry Andric // Inline candidate comparer using call site weight
435344a3780SDimitry Andric struct CandidateComparer {
operator ()__anon3721952d0111::CandidateComparer436344a3780SDimitry Andric bool operator()(const InlineCandidate &LHS, const InlineCandidate &RHS) {
437344a3780SDimitry Andric if (LHS.CallsiteCount != RHS.CallsiteCount)
438344a3780SDimitry Andric return LHS.CallsiteCount < RHS.CallsiteCount;
439344a3780SDimitry Andric
440344a3780SDimitry Andric const FunctionSamples *LCS = LHS.CalleeSamples;
441344a3780SDimitry Andric const FunctionSamples *RCS = RHS.CalleeSamples;
442ac9a064cSDimitry Andric // In inline replay mode, CalleeSamples may be null and the order doesn't
443ac9a064cSDimitry Andric // matter.
444ac9a064cSDimitry Andric if (!LCS || !RCS)
445ac9a064cSDimitry Andric return LCS;
446344a3780SDimitry Andric
447344a3780SDimitry Andric // Tie breaker using number of samples try to favor smaller functions first
448344a3780SDimitry Andric if (LCS->getBodySamples().size() != RCS->getBodySamples().size())
449344a3780SDimitry Andric return LCS->getBodySamples().size() > RCS->getBodySamples().size();
450344a3780SDimitry Andric
451344a3780SDimitry Andric // Tie breaker using GUID so we have stable/deterministic inlining order
452b1c73532SDimitry Andric return LCS->getGUID() < RCS->getGUID();
453344a3780SDimitry Andric }
454344a3780SDimitry Andric };
455344a3780SDimitry Andric
456344a3780SDimitry Andric using CandidateQueue =
457344a3780SDimitry Andric PriorityQueue<InlineCandidate, std::vector<InlineCandidate>,
458344a3780SDimitry Andric CandidateComparer>;
459344a3780SDimitry Andric
460eb11fae6SDimitry Andric /// Sample profile pass.
461b915e9e0SDimitry Andric ///
462b915e9e0SDimitry Andric /// This pass reads profile data from the file specified by
463b915e9e0SDimitry Andric /// -sample-profile-file and annotates every affected function with the
464b915e9e0SDimitry Andric /// profile information found in that file.
4657fa27ce4SDimitry Andric class SampleProfileLoader final : public SampleProfileLoaderBaseImpl<Function> {
466b915e9e0SDimitry Andric public:
SampleProfileLoader(StringRef Name,StringRef RemapName,ThinOrFullLTOPhase LTOPhase,IntrusiveRefCntPtr<vfs::FileSystem> FS,std::function<AssumptionCache & (Function &)> GetAssumptionCache,std::function<TargetTransformInfo & (Function &)> GetTargetTransformInfo,std::function<const TargetLibraryInfo & (Function &)> GetTLI,LazyCallGraph & CG)467044eb2f6SDimitry Andric SampleProfileLoader(
468b60736ecSDimitry Andric StringRef Name, StringRef RemapName, ThinOrFullLTOPhase LTOPhase,
4697fa27ce4SDimitry Andric IntrusiveRefCntPtr<vfs::FileSystem> FS,
470044eb2f6SDimitry Andric std::function<AssumptionCache &(Function &)> GetAssumptionCache,
471cfca06d7SDimitry Andric std::function<TargetTransformInfo &(Function &)> GetTargetTransformInfo,
472ac9a064cSDimitry Andric std::function<const TargetLibraryInfo &(Function &)> GetTLI,
473ac9a064cSDimitry Andric LazyCallGraph &CG)
4747fa27ce4SDimitry Andric : SampleProfileLoaderBaseImpl(std::string(Name), std::string(RemapName),
4757fa27ce4SDimitry Andric std::move(FS)),
476344a3780SDimitry Andric GetAC(std::move(GetAssumptionCache)),
477cfca06d7SDimitry Andric GetTTI(std::move(GetTargetTransformInfo)), GetTLI(std::move(GetTLI)),
478ac9a064cSDimitry Andric CG(CG), LTOPhase(LTOPhase),
479145449b1SDimitry Andric AnnotatedPassName(AnnotateSampleProfileInlinePhase
480145449b1SDimitry Andric ? llvm::AnnotateInlinePassName(InlineContext{
481145449b1SDimitry Andric LTOPhase, InlinePass::SampleProfileInliner})
482145449b1SDimitry Andric : CSINLINE_DEBUG) {}
483b915e9e0SDimitry Andric
484b60736ecSDimitry Andric bool doInitialization(Module &M, FunctionAnalysisManager *FAM = nullptr);
485eb11fae6SDimitry Andric bool runOnModule(Module &M, ModuleAnalysisManager *AM,
486ac9a064cSDimitry Andric ProfileSummaryInfo *_PSI);
487b915e9e0SDimitry Andric
488b915e9e0SDimitry Andric protected:
489044eb2f6SDimitry Andric bool runOnFunction(Function &F, ModuleAnalysisManager *AM);
490b915e9e0SDimitry Andric bool emitAnnotations(Function &F);
491344a3780SDimitry Andric ErrorOr<uint64_t> getInstWeight(const Instruction &I) override;
492cfca06d7SDimitry Andric const FunctionSamples *findCalleeFunctionSamples(const CallBase &I) const;
493344a3780SDimitry Andric const FunctionSamples *
494344a3780SDimitry Andric findFunctionSamples(const Instruction &I) const override;
49571d5a254SDimitry Andric std::vector<const FunctionSamples *>
496044eb2f6SDimitry Andric findIndirectCallFunctionSamples(const Instruction &I, uint64_t &Sum) const;
497c0981da4SDimitry Andric void findExternalInlineCandidate(CallBase *CB, const FunctionSamples *Samples,
498344a3780SDimitry Andric DenseSet<GlobalValue::GUID> &InlinedGUIDs,
499344a3780SDimitry Andric uint64_t Threshold);
500344a3780SDimitry Andric // Attempt to promote indirect call and also inline the promoted call
501344a3780SDimitry Andric bool tryPromoteAndInlineCandidate(
502344a3780SDimitry Andric Function &F, InlineCandidate &Candidate, uint64_t SumOrigin,
503344a3780SDimitry Andric uint64_t &Sum, SmallVector<CallBase *, 8> *InlinedCallSites = nullptr);
504c0981da4SDimitry Andric
50571d5a254SDimitry Andric bool inlineHotFunctions(Function &F,
506044eb2f6SDimitry Andric DenseSet<GlobalValue::GUID> &InlinedGUIDs);
507e3b55780SDimitry Andric std::optional<InlineCost> getExternalInlineAdvisorCost(CallBase &CB);
508c0981da4SDimitry Andric bool getExternalInlineAdvisorShouldInline(CallBase &CB);
509344a3780SDimitry Andric InlineCost shouldInlineCandidate(InlineCandidate &Candidate);
510344a3780SDimitry Andric bool getInlineCandidate(InlineCandidate *NewCandidate, CallBase *CB);
511344a3780SDimitry Andric bool
512344a3780SDimitry Andric tryInlineCandidate(InlineCandidate &Candidate,
513344a3780SDimitry Andric SmallVector<CallBase *, 8> *InlinedCallSites = nullptr);
514344a3780SDimitry Andric bool
515344a3780SDimitry Andric inlineHotFunctionsWithPriority(Function &F,
516344a3780SDimitry Andric DenseSet<GlobalValue::GUID> &InlinedGUIDs);
517706b4fc4SDimitry Andric // Inline cold/small functions in addition to hot ones
518cfca06d7SDimitry Andric bool shouldInlineColdCallee(CallBase &CallInst);
519706b4fc4SDimitry Andric void emitOptimizationRemarksForInlineCandidates(
520cfca06d7SDimitry Andric const SmallVectorImpl<CallBase *> &Candidates, const Function &F,
521cfca06d7SDimitry Andric bool Hot);
52277fc4c14SDimitry Andric void promoteMergeNotInlinedContextSamples(
523e3b55780SDimitry Andric MapVector<CallBase *, const FunctionSamples *> NonInlinedCallSites,
52477fc4c14SDimitry Andric const Function &F);
5257fa27ce4SDimitry Andric std::vector<Function *> buildFunctionOrder(Module &M, LazyCallGraph &CG);
5267fa27ce4SDimitry Andric std::unique_ptr<ProfiledCallGraph> buildProfiledCallGraph(Module &M);
527344a3780SDimitry Andric void generateMDProfMetadata(Function &F);
528ac9a064cSDimitry Andric bool rejectHighStalenessProfile(Module &M, ProfileSummaryInfo *PSI,
529ac9a064cSDimitry Andric const SampleProfileMap &Profiles);
530ac9a064cSDimitry Andric void removePseudoProbeInsts(Module &M);
531b915e9e0SDimitry Andric
532d99dafe2SDimitry Andric /// Map from function name to Function *. Used to find the function from
533d99dafe2SDimitry Andric /// the function name. If the function name contains suffix, additional
534d99dafe2SDimitry Andric /// entry is added to map from the stripped name to the function if there
535d99dafe2SDimitry Andric /// is one-to-one mapping.
536b1c73532SDimitry Andric HashKeyMap<std::unordered_map, FunctionId, Function *> SymbolMap;
537d99dafe2SDimitry Andric
538ac9a064cSDimitry Andric /// Map from function name to profile name generated by call-graph based
539ac9a064cSDimitry Andric /// profile fuzzy matching(--salvage-unused-profile).
540ac9a064cSDimitry Andric HashKeyMap<std::unordered_map, FunctionId, FunctionId> FuncNameToProfNameMap;
541ac9a064cSDimitry Andric
542044eb2f6SDimitry Andric std::function<AssumptionCache &(Function &)> GetAC;
543044eb2f6SDimitry Andric std::function<TargetTransformInfo &(Function &)> GetTTI;
544cfca06d7SDimitry Andric std::function<const TargetLibraryInfo &(Function &)> GetTLI;
545ac9a064cSDimitry Andric LazyCallGraph &CG;
546b915e9e0SDimitry Andric
547b60736ecSDimitry Andric /// Profile tracker for different context.
548b60736ecSDimitry Andric std::unique_ptr<SampleContextTracker> ContextTracker;
549b60736ecSDimitry Andric
550b60736ecSDimitry Andric /// Flag indicating which LTO/ThinLTO phase the pass is invoked in.
551044eb2f6SDimitry Andric ///
552b60736ecSDimitry Andric /// We need to know the LTO phase because for example in ThinLTOPrelink
553b60736ecSDimitry Andric /// phase, in annotation, we should not promote indirect calls. Instead,
554b60736ecSDimitry Andric /// we will mark GUIDs that needs to be annotated to the function.
555145449b1SDimitry Andric const ThinOrFullLTOPhase LTOPhase;
556145449b1SDimitry Andric const std::string AnnotatedPassName;
557b915e9e0SDimitry Andric
5581d5ae102SDimitry Andric /// Profle Symbol list tells whether a function name appears in the binary
5591d5ae102SDimitry Andric /// used to generate the current profile.
560ac9a064cSDimitry Andric std::shared_ptr<ProfileSymbolList> PSL;
5611d5ae102SDimitry Andric
562eb11fae6SDimitry Andric /// Total number of samples collected in this profile.
563b915e9e0SDimitry Andric ///
564b915e9e0SDimitry Andric /// This is the sum of all the samples collected in all the functions executed
565b915e9e0SDimitry Andric /// at runtime.
566044eb2f6SDimitry Andric uint64_t TotalCollectedSamples = 0;
567044eb2f6SDimitry Andric
568e6d15924SDimitry Andric // Information recorded when we declined to inline a call site
569e6d15924SDimitry Andric // because we have determined it is too cold is accumulated for
570e6d15924SDimitry Andric // each callee function. Initially this is just the entry count.
571e6d15924SDimitry Andric struct NotInlinedProfileInfo {
572e6d15924SDimitry Andric uint64_t entryCount;
573e6d15924SDimitry Andric };
574e6d15924SDimitry Andric DenseMap<Function *, NotInlinedProfileInfo> notInlinedCallInfo;
5751d5ae102SDimitry Andric
5761d5ae102SDimitry Andric // GUIDToFuncNameMap saves the mapping from GUID to the symbol name, for
5771d5ae102SDimitry Andric // all the function symbols defined or declared in current module.
5781d5ae102SDimitry Andric DenseMap<uint64_t, StringRef> GUIDToFuncNameMap;
5791d5ae102SDimitry Andric
5801d5ae102SDimitry Andric // All the Names used in FunctionSamples including outline function
5811d5ae102SDimitry Andric // names, inline instance names and call target names.
5821d5ae102SDimitry Andric StringSet<> NamesInProfile;
583b1c73532SDimitry Andric // MD5 version of NamesInProfile. Either NamesInProfile or GUIDsInProfile is
584b1c73532SDimitry Andric // populated, depends on whether the profile uses MD5. Because the name table
585b1c73532SDimitry Andric // generally contains several magnitude more entries than the number of
586b1c73532SDimitry Andric // functions, we do not want to convert all names from one form to another.
587b1c73532SDimitry Andric llvm::DenseSet<uint64_t> GUIDsInProfile;
5881d5ae102SDimitry Andric
5891d5ae102SDimitry Andric // For symbol in profile symbol list, whether to regard their profiles
5901d5ae102SDimitry Andric // to be accurate. It is mainly decided by existance of profile symbol
5911d5ae102SDimitry Andric // list and -profile-accurate-for-symsinlist flag, but it can be
5921d5ae102SDimitry Andric // overriden by -profile-sample-accurate or profile-sample-accurate
5931d5ae102SDimitry Andric // attribute.
5941d5ae102SDimitry Andric bool ProfAccForSymsInList;
595b60736ecSDimitry Andric
596b60736ecSDimitry Andric // External inline advisor used to replay inline decision from remarks.
597c0981da4SDimitry Andric std::unique_ptr<InlineAdvisor> ExternalInlineAdvisor;
598b60736ecSDimitry Andric
599e3b55780SDimitry Andric // A helper to implement the sample profile matching algorithm.
600e3b55780SDimitry Andric std::unique_ptr<SampleProfileMatcher> MatchingManager;
601e3b55780SDimitry Andric
602145449b1SDimitry Andric private:
getAnnotatedRemarkPassName() const603145449b1SDimitry Andric const char *getAnnotatedRemarkPassName() const {
604145449b1SDimitry Andric return AnnotatedPassName.c_str();
605145449b1SDimitry Andric }
606b915e9e0SDimitry Andric };
607044eb2f6SDimitry Andric } // end anonymous namespace
608044eb2f6SDimitry Andric
6097fa27ce4SDimitry Andric namespace llvm {
6107fa27ce4SDimitry Andric template <>
isExit(const BasicBlock * BB)6117fa27ce4SDimitry Andric inline bool SampleProfileInference<Function>::isExit(const BasicBlock *BB) {
6127fa27ce4SDimitry Andric return succ_empty(BB);
6137fa27ce4SDimitry Andric }
6147fa27ce4SDimitry Andric
6157fa27ce4SDimitry Andric template <>
findUnlikelyJumps(const std::vector<const BasicBlockT * > & BasicBlocks,BlockEdgeMap & Successors,FlowFunction & Func)6167fa27ce4SDimitry Andric inline void SampleProfileInference<Function>::findUnlikelyJumps(
6177fa27ce4SDimitry Andric const std::vector<const BasicBlockT *> &BasicBlocks,
6187fa27ce4SDimitry Andric BlockEdgeMap &Successors, FlowFunction &Func) {
6197fa27ce4SDimitry Andric for (auto &Jump : Func.Jumps) {
6207fa27ce4SDimitry Andric const auto *BB = BasicBlocks[Jump.Source];
6217fa27ce4SDimitry Andric const auto *Succ = BasicBlocks[Jump.Target];
6227fa27ce4SDimitry Andric const Instruction *TI = BB->getTerminator();
6237fa27ce4SDimitry Andric // Check if a block ends with InvokeInst and mark non-taken branch unlikely.
6247fa27ce4SDimitry Andric // In that case block Succ should be a landing pad
6257fa27ce4SDimitry Andric if (Successors[BB].size() == 2 && Successors[BB].back() == Succ) {
6267fa27ce4SDimitry Andric if (isa<InvokeInst>(TI)) {
6277fa27ce4SDimitry Andric Jump.IsUnlikely = true;
6287fa27ce4SDimitry Andric }
6297fa27ce4SDimitry Andric }
6307fa27ce4SDimitry Andric const Instruction *SuccTI = Succ->getTerminator();
6317fa27ce4SDimitry Andric // Check if the target block contains UnreachableInst and mark it unlikely
6327fa27ce4SDimitry Andric if (SuccTI->getNumSuccessors() == 0) {
6337fa27ce4SDimitry Andric if (isa<UnreachableInst>(SuccTI)) {
6347fa27ce4SDimitry Andric Jump.IsUnlikely = true;
6357fa27ce4SDimitry Andric }
6367fa27ce4SDimitry Andric }
6377fa27ce4SDimitry Andric }
6387fa27ce4SDimitry Andric }
6397fa27ce4SDimitry Andric
6407fa27ce4SDimitry Andric template <>
computeDominanceAndLoopInfo(Function & F)6417fa27ce4SDimitry Andric void SampleProfileLoaderBaseImpl<Function>::computeDominanceAndLoopInfo(
6427fa27ce4SDimitry Andric Function &F) {
6437fa27ce4SDimitry Andric DT.reset(new DominatorTree);
6447fa27ce4SDimitry Andric DT->recalculate(F);
6457fa27ce4SDimitry Andric
6467fa27ce4SDimitry Andric PDT.reset(new PostDominatorTree(F));
6477fa27ce4SDimitry Andric
6487fa27ce4SDimitry Andric LI.reset(new LoopInfo);
6497fa27ce4SDimitry Andric LI->analyze(*DT);
6507fa27ce4SDimitry Andric }
6517fa27ce4SDimitry Andric } // namespace llvm
6527fa27ce4SDimitry Andric
getInstWeight(const Instruction & Inst)65371d5a254SDimitry Andric ErrorOr<uint64_t> SampleProfileLoader::getInstWeight(const Instruction &Inst) {
654b60736ecSDimitry Andric if (FunctionSamples::ProfileIsProbeBased)
655b60736ecSDimitry Andric return getProbeWeight(Inst);
656b60736ecSDimitry Andric
65701095a5dSDimitry Andric const DebugLoc &DLoc = Inst.getDebugLoc();
658dd58ef01SDimitry Andric if (!DLoc)
659dd58ef01SDimitry Andric return std::error_code();
660dd58ef01SDimitry Andric
661d8e91e46SDimitry Andric // Ignore all intrinsics, phinodes and branch instructions.
662344a3780SDimitry Andric // Branch and phinodes instruction usually contains debug info from sources
663344a3780SDimitry Andric // outside of the residing basic block, thus we ignore them during annotation.
664d8e91e46SDimitry Andric if (isa<BranchInst>(Inst) || isa<IntrinsicInst>(Inst) || isa<PHINode>(Inst))
66501095a5dSDimitry Andric return std::error_code();
66601095a5dSDimitry Andric
667344a3780SDimitry Andric // For non-CS profile, if a direct call/invoke instruction is inlined in
668344a3780SDimitry Andric // profile (findCalleeFunctionSamples returns non-empty result), but not
669344a3780SDimitry Andric // inlined here, it means that the inlined callsite has no sample, thus the
670344a3780SDimitry Andric // call instruction should have 0 count.
671344a3780SDimitry Andric // For CS profile, the callsite count of previously inlined callees is
672344a3780SDimitry Andric // populated with the entry count of the callees.
673145449b1SDimitry Andric if (!FunctionSamples::ProfileIsCS)
674b60736ecSDimitry Andric if (const auto *CB = dyn_cast<CallBase>(&Inst))
675cfca06d7SDimitry Andric if (!CB->isIndirectCall() && findCalleeFunctionSamples(*CB))
676b915e9e0SDimitry Andric return 0;
677b915e9e0SDimitry Andric
678344a3780SDimitry Andric return getInstWeightImpl(Inst);
679dd58ef01SDimitry Andric }
680dd58ef01SDimitry Andric
681eb11fae6SDimitry Andric /// Get the FunctionSamples for a call instruction.
682dd58ef01SDimitry Andric ///
683b915e9e0SDimitry Andric /// The FunctionSamples of a call/invoke instruction \p Inst is the inlined
684dd58ef01SDimitry Andric /// instance in which that call instruction is calling to. It contains
685dd58ef01SDimitry Andric /// all samples that resides in the inlined instance. We first find the
686dd58ef01SDimitry Andric /// inlined instance in which the call instruction is from, then we
687dd58ef01SDimitry Andric /// traverse its children to find the callsite with the matching
688b915e9e0SDimitry Andric /// location.
689dd58ef01SDimitry Andric ///
690b915e9e0SDimitry Andric /// \param Inst Call/Invoke instruction to query.
691dd58ef01SDimitry Andric ///
692dd58ef01SDimitry Andric /// \returns The FunctionSamples pointer to the inlined instance.
693dd58ef01SDimitry Andric const FunctionSamples *
findCalleeFunctionSamples(const CallBase & Inst) const694cfca06d7SDimitry Andric SampleProfileLoader::findCalleeFunctionSamples(const CallBase &Inst) const {
695dd58ef01SDimitry Andric const DILocation *DIL = Inst.getDebugLoc();
696dd58ef01SDimitry Andric if (!DIL) {
697dd58ef01SDimitry Andric return nullptr;
698dd58ef01SDimitry Andric }
69971d5a254SDimitry Andric
70071d5a254SDimitry Andric StringRef CalleeName;
701b60736ecSDimitry Andric if (Function *Callee = Inst.getCalledFunction())
702344a3780SDimitry Andric CalleeName = Callee->getName();
703b60736ecSDimitry Andric
704145449b1SDimitry Andric if (FunctionSamples::ProfileIsCS)
705b60736ecSDimitry Andric return ContextTracker->getCalleeContextSamplesFor(Inst, CalleeName);
706dd58ef01SDimitry Andric
707dd58ef01SDimitry Andric const FunctionSamples *FS = findFunctionSamples(Inst);
708dd58ef01SDimitry Andric if (FS == nullptr)
709dd58ef01SDimitry Andric return nullptr;
710dd58ef01SDimitry Andric
711b60736ecSDimitry Andric return FS->findFunctionSamplesAt(FunctionSamples::getCallSiteIdentifier(DIL),
712ac9a064cSDimitry Andric CalleeName, Reader->getRemapper(),
713ac9a064cSDimitry Andric &FuncNameToProfNameMap);
71471d5a254SDimitry Andric }
71571d5a254SDimitry Andric
71671d5a254SDimitry Andric /// Returns a vector of FunctionSamples that are the indirect call targets
717044eb2f6SDimitry Andric /// of \p Inst. The vector is sorted by the total number of samples. Stores
718044eb2f6SDimitry Andric /// the total call count of the indirect call in \p Sum.
71971d5a254SDimitry Andric std::vector<const FunctionSamples *>
findIndirectCallFunctionSamples(const Instruction & Inst,uint64_t & Sum) const72071d5a254SDimitry Andric SampleProfileLoader::findIndirectCallFunctionSamples(
721044eb2f6SDimitry Andric const Instruction &Inst, uint64_t &Sum) const {
72271d5a254SDimitry Andric const DILocation *DIL = Inst.getDebugLoc();
72371d5a254SDimitry Andric std::vector<const FunctionSamples *> R;
72471d5a254SDimitry Andric
72571d5a254SDimitry Andric if (!DIL) {
72671d5a254SDimitry Andric return R;
72771d5a254SDimitry Andric }
72871d5a254SDimitry Andric
729344a3780SDimitry Andric auto FSCompare = [](const FunctionSamples *L, const FunctionSamples *R) {
730344a3780SDimitry Andric assert(L && R && "Expect non-null FunctionSamples");
7314b4fe385SDimitry Andric if (L->getHeadSamplesEstimate() != R->getHeadSamplesEstimate())
7324b4fe385SDimitry Andric return L->getHeadSamplesEstimate() > R->getHeadSamplesEstimate();
733b1c73532SDimitry Andric return L->getGUID() < R->getGUID();
734344a3780SDimitry Andric };
735344a3780SDimitry Andric
736145449b1SDimitry Andric if (FunctionSamples::ProfileIsCS) {
737344a3780SDimitry Andric auto CalleeSamples =
738344a3780SDimitry Andric ContextTracker->getIndirectCalleeContextSamplesFor(DIL);
739344a3780SDimitry Andric if (CalleeSamples.empty())
740344a3780SDimitry Andric return R;
741344a3780SDimitry Andric
742344a3780SDimitry Andric // For CSSPGO, we only use target context profile's entry count
743344a3780SDimitry Andric // as that already includes both inlined callee and non-inlined ones..
744344a3780SDimitry Andric Sum = 0;
745344a3780SDimitry Andric for (const auto *const FS : CalleeSamples) {
7464b4fe385SDimitry Andric Sum += FS->getHeadSamplesEstimate();
747344a3780SDimitry Andric R.push_back(FS);
748344a3780SDimitry Andric }
749344a3780SDimitry Andric llvm::sort(R, FSCompare);
750344a3780SDimitry Andric return R;
751344a3780SDimitry Andric }
752344a3780SDimitry Andric
75371d5a254SDimitry Andric const FunctionSamples *FS = findFunctionSamples(Inst);
75471d5a254SDimitry Andric if (FS == nullptr)
75571d5a254SDimitry Andric return R;
75671d5a254SDimitry Andric
757b60736ecSDimitry Andric auto CallSite = FunctionSamples::getCallSiteIdentifier(DIL);
758044eb2f6SDimitry Andric Sum = 0;
75999aabd70SDimitry Andric if (auto T = FS->findCallTargetMapAt(CallSite))
76099aabd70SDimitry Andric for (const auto &T_C : *T)
761044eb2f6SDimitry Andric Sum += T_C.second;
762b60736ecSDimitry Andric if (const FunctionSamplesMap *M = FS->findFunctionSamplesMapAt(CallSite)) {
763044eb2f6SDimitry Andric if (M->empty())
76471d5a254SDimitry Andric return R;
76571d5a254SDimitry Andric for (const auto &NameFS : *M) {
7664b4fe385SDimitry Andric Sum += NameFS.second.getHeadSamplesEstimate();
76771d5a254SDimitry Andric R.push_back(&NameFS.second);
76871d5a254SDimitry Andric }
769344a3780SDimitry Andric llvm::sort(R, FSCompare);
77071d5a254SDimitry Andric }
77171d5a254SDimitry Andric return R;
772dd58ef01SDimitry Andric }
773dd58ef01SDimitry Andric
774dd58ef01SDimitry Andric const FunctionSamples *
findFunctionSamples(const Instruction & Inst) const775dd58ef01SDimitry Andric SampleProfileLoader::findFunctionSamples(const Instruction &Inst) const {
776b60736ecSDimitry Andric if (FunctionSamples::ProfileIsProbeBased) {
777e3b55780SDimitry Andric std::optional<PseudoProbe> Probe = extractProbe(Inst);
778b60736ecSDimitry Andric if (!Probe)
779b60736ecSDimitry Andric return nullptr;
780b60736ecSDimitry Andric }
781b60736ecSDimitry Andric
782dd58ef01SDimitry Andric const DILocation *DIL = Inst.getDebugLoc();
78371d5a254SDimitry Andric if (!DIL)
784dd58ef01SDimitry Andric return Samples;
78571d5a254SDimitry Andric
786d8e91e46SDimitry Andric auto it = DILocation2SampleMap.try_emplace(DIL,nullptr);
787b60736ecSDimitry Andric if (it.second) {
788145449b1SDimitry Andric if (FunctionSamples::ProfileIsCS)
789b60736ecSDimitry Andric it.first->second = ContextTracker->getContextSamplesFor(DIL);
790b60736ecSDimitry Andric else
791ac9a064cSDimitry Andric it.first->second = Samples->findFunctionSamples(
792ac9a064cSDimitry Andric DIL, Reader->getRemapper(), &FuncNameToProfNameMap);
793b60736ecSDimitry Andric }
794d8e91e46SDimitry Andric return it.first->second;
795dd58ef01SDimitry Andric }
796dd58ef01SDimitry Andric
797344a3780SDimitry Andric /// Check whether the indirect call promotion history of \p Inst allows
798344a3780SDimitry Andric /// the promotion for \p Candidate.
799344a3780SDimitry Andric /// If the profile count for the promotion candidate \p Candidate is
800344a3780SDimitry Andric /// NOMORE_ICP_MAGICNUM, it means \p Candidate has already been promoted
801344a3780SDimitry Andric /// for \p Inst. If we already have at least MaxNumPromotions
802344a3780SDimitry Andric /// NOMORE_ICP_MAGICNUM count values in the value profile of \p Inst, we
803344a3780SDimitry Andric /// cannot promote for \p Inst anymore.
doesHistoryAllowICP(const Instruction & Inst,StringRef Candidate)804344a3780SDimitry Andric static bool doesHistoryAllowICP(const Instruction &Inst, StringRef Candidate) {
805344a3780SDimitry Andric uint64_t TotalCount = 0;
806ac9a064cSDimitry Andric auto ValueData = getValueProfDataFromInst(Inst, IPVK_IndirectCallTarget,
807ac9a064cSDimitry Andric MaxNumPromotions, TotalCount, true);
808344a3780SDimitry Andric // No valid value profile so no promoted targets have been recorded
809344a3780SDimitry Andric // before. Ok to do ICP.
810ac9a064cSDimitry Andric if (ValueData.empty())
811344a3780SDimitry Andric return true;
812344a3780SDimitry Andric
813344a3780SDimitry Andric unsigned NumPromoted = 0;
814ac9a064cSDimitry Andric for (const auto &V : ValueData) {
815ac9a064cSDimitry Andric if (V.Count != NOMORE_ICP_MAGICNUM)
816344a3780SDimitry Andric continue;
817344a3780SDimitry Andric
818344a3780SDimitry Andric // If the promotion candidate has NOMORE_ICP_MAGICNUM count in the
819344a3780SDimitry Andric // metadata, it means the candidate has been promoted for this
820344a3780SDimitry Andric // indirect call.
821ac9a064cSDimitry Andric if (V.Value == Function::getGUID(Candidate))
822344a3780SDimitry Andric return false;
823344a3780SDimitry Andric NumPromoted++;
824344a3780SDimitry Andric // If already have MaxNumPromotions promotion, don't do it anymore.
825344a3780SDimitry Andric if (NumPromoted == MaxNumPromotions)
826b60736ecSDimitry Andric return false;
827b60736ecSDimitry Andric }
828344a3780SDimitry Andric return true;
829b60736ecSDimitry Andric }
830b60736ecSDimitry Andric
831344a3780SDimitry Andric /// Update indirect call target profile metadata for \p Inst.
832344a3780SDimitry Andric /// Usually \p Sum is the sum of counts of all the targets for \p Inst.
833344a3780SDimitry Andric /// If it is 0, it means updateIDTMetaData is used to mark a
834344a3780SDimitry Andric /// certain target to be promoted already. If it is not zero,
835344a3780SDimitry Andric /// we expect to use it to update the total count in the value profile.
836344a3780SDimitry Andric static void
updateIDTMetaData(Instruction & Inst,const SmallVectorImpl<InstrProfValueData> & CallTargets,uint64_t Sum)837344a3780SDimitry Andric updateIDTMetaData(Instruction &Inst,
838344a3780SDimitry Andric const SmallVectorImpl<InstrProfValueData> &CallTargets,
839344a3780SDimitry Andric uint64_t Sum) {
840145449b1SDimitry Andric // Bail out early if MaxNumPromotions is zero.
841145449b1SDimitry Andric // This prevents allocating an array of zero length below.
842145449b1SDimitry Andric //
843145449b1SDimitry Andric // Note `updateIDTMetaData` is called in two places so check
844145449b1SDimitry Andric // `MaxNumPromotions` inside it.
845145449b1SDimitry Andric if (MaxNumPromotions == 0)
846145449b1SDimitry Andric return;
847344a3780SDimitry Andric // OldSum is the existing total count in the value profile data.
848344a3780SDimitry Andric uint64_t OldSum = 0;
849ac9a064cSDimitry Andric auto ValueData = getValueProfDataFromInst(Inst, IPVK_IndirectCallTarget,
850ac9a064cSDimitry Andric MaxNumPromotions, OldSum, true);
851344a3780SDimitry Andric
852344a3780SDimitry Andric DenseMap<uint64_t, uint64_t> ValueCountMap;
853344a3780SDimitry Andric if (Sum == 0) {
854344a3780SDimitry Andric assert((CallTargets.size() == 1 &&
855344a3780SDimitry Andric CallTargets[0].Count == NOMORE_ICP_MAGICNUM) &&
856344a3780SDimitry Andric "If sum is 0, assume only one element in CallTargets "
857344a3780SDimitry Andric "with count being NOMORE_ICP_MAGICNUM");
858344a3780SDimitry Andric // Initialize ValueCountMap with existing value profile data.
859ac9a064cSDimitry Andric for (const auto &V : ValueData)
860ac9a064cSDimitry Andric ValueCountMap[V.Value] = V.Count;
861344a3780SDimitry Andric auto Pair =
862344a3780SDimitry Andric ValueCountMap.try_emplace(CallTargets[0].Value, CallTargets[0].Count);
863344a3780SDimitry Andric // If the target already exists in value profile, decrease the total
864344a3780SDimitry Andric // count OldSum and reset the target's count to NOMORE_ICP_MAGICNUM.
865344a3780SDimitry Andric if (!Pair.second) {
866344a3780SDimitry Andric OldSum -= Pair.first->second;
867344a3780SDimitry Andric Pair.first->second = NOMORE_ICP_MAGICNUM;
868344a3780SDimitry Andric }
869344a3780SDimitry Andric Sum = OldSum;
870344a3780SDimitry Andric } else {
871344a3780SDimitry Andric // Initialize ValueCountMap with existing NOMORE_ICP_MAGICNUM
872344a3780SDimitry Andric // counts in the value profile.
873ac9a064cSDimitry Andric for (const auto &V : ValueData) {
874ac9a064cSDimitry Andric if (V.Count == NOMORE_ICP_MAGICNUM)
875ac9a064cSDimitry Andric ValueCountMap[V.Value] = V.Count;
876344a3780SDimitry Andric }
877344a3780SDimitry Andric
878344a3780SDimitry Andric for (const auto &Data : CallTargets) {
879344a3780SDimitry Andric auto Pair = ValueCountMap.try_emplace(Data.Value, Data.Count);
880344a3780SDimitry Andric if (Pair.second)
881344a3780SDimitry Andric continue;
882344a3780SDimitry Andric // The target represented by Data.Value has already been promoted.
883344a3780SDimitry Andric // Keep the count as NOMORE_ICP_MAGICNUM in the profile and decrease
884344a3780SDimitry Andric // Sum by Data.Count.
885344a3780SDimitry Andric assert(Sum >= Data.Count && "Sum should never be less than Data.Count");
886344a3780SDimitry Andric Sum -= Data.Count;
887344a3780SDimitry Andric }
888344a3780SDimitry Andric }
889344a3780SDimitry Andric
890344a3780SDimitry Andric SmallVector<InstrProfValueData, 8> NewCallTargets;
891344a3780SDimitry Andric for (const auto &ValueCount : ValueCountMap) {
892344a3780SDimitry Andric NewCallTargets.emplace_back(
893344a3780SDimitry Andric InstrProfValueData{ValueCount.first, ValueCount.second});
894344a3780SDimitry Andric }
895344a3780SDimitry Andric
896344a3780SDimitry Andric llvm::sort(NewCallTargets,
897344a3780SDimitry Andric [](const InstrProfValueData &L, const InstrProfValueData &R) {
898344a3780SDimitry Andric if (L.Count != R.Count)
899344a3780SDimitry Andric return L.Count > R.Count;
900344a3780SDimitry Andric return L.Value > R.Value;
901344a3780SDimitry Andric });
902344a3780SDimitry Andric
903344a3780SDimitry Andric uint32_t MaxMDCount =
904344a3780SDimitry Andric std::min(NewCallTargets.size(), static_cast<size_t>(MaxNumPromotions));
905344a3780SDimitry Andric annotateValueSite(*Inst.getParent()->getParent()->getParent(), Inst,
906344a3780SDimitry Andric NewCallTargets, Sum, IPVK_IndirectCallTarget, MaxMDCount);
907344a3780SDimitry Andric }
908344a3780SDimitry Andric
909344a3780SDimitry Andric /// Attempt to promote indirect call and also inline the promoted call.
910344a3780SDimitry Andric ///
911344a3780SDimitry Andric /// \param F Caller function.
912344a3780SDimitry Andric /// \param Candidate ICP and inline candidate.
913344a3780SDimitry Andric /// \param SumOrigin Original sum of target counts for indirect call before
914344a3780SDimitry Andric /// promoting given candidate.
915344a3780SDimitry Andric /// \param Sum Prorated sum of remaining target counts for indirect call
916344a3780SDimitry Andric /// after promoting given candidate.
917344a3780SDimitry Andric /// \param InlinedCallSite Output vector for new call sites exposed after
918344a3780SDimitry Andric /// inlining.
tryPromoteAndInlineCandidate(Function & F,InlineCandidate & Candidate,uint64_t SumOrigin,uint64_t & Sum,SmallVector<CallBase *,8> * InlinedCallSite)919344a3780SDimitry Andric bool SampleProfileLoader::tryPromoteAndInlineCandidate(
920344a3780SDimitry Andric Function &F, InlineCandidate &Candidate, uint64_t SumOrigin, uint64_t &Sum,
921344a3780SDimitry Andric SmallVector<CallBase *, 8> *InlinedCallSite) {
922145449b1SDimitry Andric // Bail out early if sample-loader inliner is disabled.
923145449b1SDimitry Andric if (DisableSampleLoaderInlining)
924145449b1SDimitry Andric return false;
925145449b1SDimitry Andric
926145449b1SDimitry Andric // Bail out early if MaxNumPromotions is zero.
927145449b1SDimitry Andric // This prevents allocating an array of zero length in callees below.
928145449b1SDimitry Andric if (MaxNumPromotions == 0)
929145449b1SDimitry Andric return false;
930b1c73532SDimitry Andric auto CalleeFunctionName = Candidate.CalleeSamples->getFunction();
931344a3780SDimitry Andric auto R = SymbolMap.find(CalleeFunctionName);
932b1c73532SDimitry Andric if (R == SymbolMap.end() || !R->second)
933344a3780SDimitry Andric return false;
934344a3780SDimitry Andric
935344a3780SDimitry Andric auto &CI = *Candidate.CallInstr;
936b1c73532SDimitry Andric if (!doesHistoryAllowICP(CI, R->second->getName()))
937344a3780SDimitry Andric return false;
938344a3780SDimitry Andric
939344a3780SDimitry Andric const char *Reason = "Callee function not available";
940344a3780SDimitry Andric // R->getValue() != &F is to prevent promoting a recursive call.
941344a3780SDimitry Andric // If it is a recursive call, we do not inline it as it could bloat
942344a3780SDimitry Andric // the code exponentially. There is way to better handle this, e.g.
943344a3780SDimitry Andric // clone the caller first, and inline the cloned caller if it is
944344a3780SDimitry Andric // recursive. As llvm does not inline recursive calls, we will
945344a3780SDimitry Andric // simply ignore it instead of handling it explicitly.
946b1c73532SDimitry Andric if (!R->second->isDeclaration() && R->second->getSubprogram() &&
947b1c73532SDimitry Andric R->second->hasFnAttribute("use-sample-profile") &&
948b1c73532SDimitry Andric R->second != &F && isLegalToPromote(CI, R->second, &Reason)) {
949344a3780SDimitry Andric // For promoted target, set its value with NOMORE_ICP_MAGICNUM count
950344a3780SDimitry Andric // in the value profile metadata so the target won't be promoted again.
951344a3780SDimitry Andric SmallVector<InstrProfValueData, 1> SortedCallTargets = {InstrProfValueData{
952b1c73532SDimitry Andric Function::getGUID(R->second->getName()), NOMORE_ICP_MAGICNUM}};
953344a3780SDimitry Andric updateIDTMetaData(CI, SortedCallTargets, 0);
954344a3780SDimitry Andric
955344a3780SDimitry Andric auto *DI = &pgo::promoteIndirectCall(
956b1c73532SDimitry Andric CI, R->second, Candidate.CallsiteCount, Sum, false, ORE);
957344a3780SDimitry Andric if (DI) {
958344a3780SDimitry Andric Sum -= Candidate.CallsiteCount;
959344a3780SDimitry Andric // Do not prorate the indirect callsite distribution since the original
960344a3780SDimitry Andric // distribution will be used to scale down non-promoted profile target
961344a3780SDimitry Andric // counts later. By doing this we lose track of the real callsite count
962344a3780SDimitry Andric // for the leftover indirect callsite as a trade off for accurate call
963344a3780SDimitry Andric // target counts.
964344a3780SDimitry Andric // TODO: Ideally we would have two separate factors, one for call site
965344a3780SDimitry Andric // counts and one is used to prorate call target counts.
966344a3780SDimitry Andric // Do not update the promoted direct callsite distribution at this
967344a3780SDimitry Andric // point since the original distribution combined with the callee profile
968344a3780SDimitry Andric // will be used to prorate callsites from the callee if inlined. Once not
969344a3780SDimitry Andric // inlined, the direct callsite distribution should be prorated so that
970344a3780SDimitry Andric // the it will reflect the real callsite counts.
971344a3780SDimitry Andric Candidate.CallInstr = DI;
972344a3780SDimitry Andric if (isa<CallInst>(DI) || isa<InvokeInst>(DI)) {
973344a3780SDimitry Andric bool Inlined = tryInlineCandidate(Candidate, InlinedCallSite);
974344a3780SDimitry Andric if (!Inlined) {
975344a3780SDimitry Andric // Prorate the direct callsite distribution so that it reflects real
976344a3780SDimitry Andric // callsite counts.
977344a3780SDimitry Andric setProbeDistributionFactor(
978344a3780SDimitry Andric *DI, static_cast<float>(Candidate.CallsiteCount) / SumOrigin);
979344a3780SDimitry Andric }
980344a3780SDimitry Andric return Inlined;
981344a3780SDimitry Andric }
982344a3780SDimitry Andric }
983344a3780SDimitry Andric } else {
984344a3780SDimitry Andric LLVM_DEBUG(dbgs() << "\nFailed to promote indirect call to "
985b1c73532SDimitry Andric << FunctionSamples::getCanonicalFnName(
986b1c73532SDimitry Andric Candidate.CallInstr->getName())<< " because "
987344a3780SDimitry Andric << Reason << "\n");
988044eb2f6SDimitry Andric }
989044eb2f6SDimitry Andric return false;
990044eb2f6SDimitry Andric }
991044eb2f6SDimitry Andric
shouldInlineColdCallee(CallBase & CallInst)992cfca06d7SDimitry Andric bool SampleProfileLoader::shouldInlineColdCallee(CallBase &CallInst) {
993706b4fc4SDimitry Andric if (!ProfileSizeInline)
994706b4fc4SDimitry Andric return false;
995706b4fc4SDimitry Andric
996cfca06d7SDimitry Andric Function *Callee = CallInst.getCalledFunction();
997706b4fc4SDimitry Andric if (Callee == nullptr)
998706b4fc4SDimitry Andric return false;
999706b4fc4SDimitry Andric
1000cfca06d7SDimitry Andric InlineCost Cost = getInlineCost(CallInst, getInlineParams(), GetTTI(*Callee),
1001cfca06d7SDimitry Andric GetAC, GetTLI);
1002706b4fc4SDimitry Andric
1003b60736ecSDimitry Andric if (Cost.isNever())
1004b60736ecSDimitry Andric return false;
1005b60736ecSDimitry Andric
1006b60736ecSDimitry Andric if (Cost.isAlways())
1007b60736ecSDimitry Andric return true;
1008b60736ecSDimitry Andric
1009706b4fc4SDimitry Andric return Cost.getCost() <= SampleColdCallSiteThreshold;
1010706b4fc4SDimitry Andric }
1011706b4fc4SDimitry Andric
emitOptimizationRemarksForInlineCandidates(const SmallVectorImpl<CallBase * > & Candidates,const Function & F,bool Hot)1012706b4fc4SDimitry Andric void SampleProfileLoader::emitOptimizationRemarksForInlineCandidates(
1013cfca06d7SDimitry Andric const SmallVectorImpl<CallBase *> &Candidates, const Function &F,
1014706b4fc4SDimitry Andric bool Hot) {
1015e3b55780SDimitry Andric for (auto *I : Candidates) {
1016cfca06d7SDimitry Andric Function *CalledFunction = I->getCalledFunction();
1017706b4fc4SDimitry Andric if (CalledFunction) {
1018145449b1SDimitry Andric ORE->emit(OptimizationRemarkAnalysis(getAnnotatedRemarkPassName(),
1019145449b1SDimitry Andric "InlineAttempt", I->getDebugLoc(),
1020145449b1SDimitry Andric I->getParent())
1021706b4fc4SDimitry Andric << "previous inlining reattempted for "
1022706b4fc4SDimitry Andric << (Hot ? "hotness: '" : "size: '")
1023706b4fc4SDimitry Andric << ore::NV("Callee", CalledFunction) << "' into '"
1024706b4fc4SDimitry Andric << ore::NV("Caller", &F) << "'");
1025706b4fc4SDimitry Andric }
1026706b4fc4SDimitry Andric }
1027706b4fc4SDimitry Andric }
1028706b4fc4SDimitry Andric
findExternalInlineCandidate(CallBase * CB,const FunctionSamples * Samples,DenseSet<GlobalValue::GUID> & InlinedGUIDs,uint64_t Threshold)1029344a3780SDimitry Andric void SampleProfileLoader::findExternalInlineCandidate(
1030c0981da4SDimitry Andric CallBase *CB, const FunctionSamples *Samples,
1031b1c73532SDimitry Andric DenseSet<GlobalValue::GUID> &InlinedGUIDs, uint64_t Threshold) {
1032c0981da4SDimitry Andric
10337fa27ce4SDimitry Andric // If ExternalInlineAdvisor(ReplayInlineAdvisor) wants to inline an external
10347fa27ce4SDimitry Andric // function make sure it's imported
1035c0981da4SDimitry Andric if (CB && getExternalInlineAdvisorShouldInline(*CB)) {
1036c0981da4SDimitry Andric // Samples may not exist for replayed function, if so
1037c0981da4SDimitry Andric // just add the direct GUID and move on
1038c0981da4SDimitry Andric if (!Samples) {
1039c0981da4SDimitry Andric InlinedGUIDs.insert(
1040b1c73532SDimitry Andric Function::getGUID(CB->getCalledFunction()->getName()));
1041c0981da4SDimitry Andric return;
1042c0981da4SDimitry Andric }
1043c0981da4SDimitry Andric // Otherwise, drop the threshold to import everything that we can
1044c0981da4SDimitry Andric Threshold = 0;
1045c0981da4SDimitry Andric }
1046c0981da4SDimitry Andric
10477fa27ce4SDimitry Andric // In some rare cases, call instruction could be changed after being pushed
10487fa27ce4SDimitry Andric // into inline candidate queue, this is because earlier inlining may expose
10497fa27ce4SDimitry Andric // constant propagation which can change indirect call to direct call. When
10507fa27ce4SDimitry Andric // this happens, we may fail to find matching function samples for the
10517fa27ce4SDimitry Andric // candidate later, even if a match was found when the candidate was enqueued.
10527fa27ce4SDimitry Andric if (!Samples)
10537fa27ce4SDimitry Andric return;
1054344a3780SDimitry Andric
1055344a3780SDimitry Andric // For AutoFDO profile, retrieve candidate profiles by walking over
1056344a3780SDimitry Andric // the nested inlinee profiles.
1057145449b1SDimitry Andric if (!FunctionSamples::ProfileIsCS) {
1058ac9a064cSDimitry Andric // Set threshold to zero to honor pre-inliner decision.
1059ac9a064cSDimitry Andric if (UsePreInlinerDecision)
1060ac9a064cSDimitry Andric Threshold = 0;
1061344a3780SDimitry Andric Samples->findInlinedFunctions(InlinedGUIDs, SymbolMap, Threshold);
1062344a3780SDimitry Andric return;
1063344a3780SDimitry Andric }
1064344a3780SDimitry Andric
1065145449b1SDimitry Andric ContextTrieNode *Caller = ContextTracker->getContextNodeForProfile(Samples);
1066344a3780SDimitry Andric std::queue<ContextTrieNode *> CalleeList;
1067344a3780SDimitry Andric CalleeList.push(Caller);
1068344a3780SDimitry Andric while (!CalleeList.empty()) {
1069344a3780SDimitry Andric ContextTrieNode *Node = CalleeList.front();
1070344a3780SDimitry Andric CalleeList.pop();
1071344a3780SDimitry Andric FunctionSamples *CalleeSample = Node->getFunctionSamples();
1072344a3780SDimitry Andric // For CSSPGO profile, retrieve candidate profile by walking over the
1073344a3780SDimitry Andric // trie built for context profile. Note that also take call targets
1074344a3780SDimitry Andric // even if callee doesn't have a corresponding context profile.
1075c0981da4SDimitry Andric if (!CalleeSample)
1076c0981da4SDimitry Andric continue;
1077c0981da4SDimitry Andric
1078c0981da4SDimitry Andric // If pre-inliner decision is used, honor that for importing as well.
1079c0981da4SDimitry Andric bool PreInline =
1080c0981da4SDimitry Andric UsePreInlinerDecision &&
1081c0981da4SDimitry Andric CalleeSample->getContext().hasAttribute(ContextShouldBeInlined);
10824b4fe385SDimitry Andric if (!PreInline && CalleeSample->getHeadSamplesEstimate() < Threshold)
1083344a3780SDimitry Andric continue;
1084344a3780SDimitry Andric
1085b1c73532SDimitry Andric Function *Func = SymbolMap.lookup(CalleeSample->getFunction());
1086344a3780SDimitry Andric // Add to the import list only when it's defined out of module.
1087344a3780SDimitry Andric if (!Func || Func->isDeclaration())
1088b1c73532SDimitry Andric InlinedGUIDs.insert(CalleeSample->getGUID());
1089344a3780SDimitry Andric
1090344a3780SDimitry Andric // Import hot CallTargets, which may not be available in IR because full
1091344a3780SDimitry Andric // profile annotation cannot be done until backend compilation in ThinLTO.
1092344a3780SDimitry Andric for (const auto &BS : CalleeSample->getBodySamples())
1093344a3780SDimitry Andric for (const auto &TS : BS.second.getCallTargets())
1094b1c73532SDimitry Andric if (TS.second > Threshold) {
1095b1c73532SDimitry Andric const Function *Callee = SymbolMap.lookup(TS.first);
1096344a3780SDimitry Andric if (!Callee || Callee->isDeclaration())
1097b1c73532SDimitry Andric InlinedGUIDs.insert(TS.first.getHashCode());
1098344a3780SDimitry Andric }
1099344a3780SDimitry Andric
1100344a3780SDimitry Andric // Import hot child context profile associted with callees. Note that this
1101344a3780SDimitry Andric // may have some overlap with the call target loop above, but doing this
1102344a3780SDimitry Andric // based child context profile again effectively allow us to use the max of
1103344a3780SDimitry Andric // entry count and call target count to determine importing.
1104344a3780SDimitry Andric for (auto &Child : Node->getAllChildContext()) {
1105344a3780SDimitry Andric ContextTrieNode *CalleeNode = &Child.second;
1106344a3780SDimitry Andric CalleeList.push(CalleeNode);
1107344a3780SDimitry Andric }
1108344a3780SDimitry Andric }
1109344a3780SDimitry Andric }
1110344a3780SDimitry Andric
1111eb11fae6SDimitry Andric /// Iteratively inline hot callsites of a function.
1112dd58ef01SDimitry Andric ///
1113145449b1SDimitry Andric /// Iteratively traverse all callsites of the function \p F, so as to
1114145449b1SDimitry Andric /// find out callsites with corresponding inline instances.
1115145449b1SDimitry Andric ///
1116145449b1SDimitry Andric /// For such callsites,
1117145449b1SDimitry Andric /// - If it is hot enough, inline the callsites and adds callsites of the callee
1118145449b1SDimitry Andric /// into the caller. If the call is an indirect call, first promote
111971d5a254SDimitry Andric /// it to direct call. Each indirect call is limited with a single target.
1120dd58ef01SDimitry Andric ///
1121145449b1SDimitry Andric /// - If a callsite is not inlined, merge the its profile to the outline
1122145449b1SDimitry Andric /// version (if --sample-profile-merge-inlinee is true), or scale the
1123145449b1SDimitry Andric /// counters of standalone function based on the profile of inlined
1124145449b1SDimitry Andric /// instances (if --sample-profile-merge-inlinee is false).
1125145449b1SDimitry Andric ///
1126145449b1SDimitry Andric /// Later passes may consume the updated profiles.
1127145449b1SDimitry Andric ///
1128dd58ef01SDimitry Andric /// \param F function to perform iterative inlining.
1129044eb2f6SDimitry Andric /// \param InlinedGUIDs a set to be updated to include all GUIDs that are
1130044eb2f6SDimitry Andric /// inlined in the profiled binary.
1131dd58ef01SDimitry Andric ///
1132dd58ef01SDimitry Andric /// \returns True if there is any inline happened.
inlineHotFunctions(Function & F,DenseSet<GlobalValue::GUID> & InlinedGUIDs)113371d5a254SDimitry Andric bool SampleProfileLoader::inlineHotFunctions(
1134044eb2f6SDimitry Andric Function &F, DenseSet<GlobalValue::GUID> &InlinedGUIDs) {
11351d5ae102SDimitry Andric // ProfAccForSymsInList is used in callsiteIsHot. The assertion makes sure
11361d5ae102SDimitry Andric // Profile symbol list is ignored when profile-sample-accurate is on.
11371d5ae102SDimitry Andric assert((!ProfAccForSymsInList ||
11381d5ae102SDimitry Andric (!ProfileSampleAccurate &&
11391d5ae102SDimitry Andric !F.hasFnAttribute("profile-sample-accurate"))) &&
11401d5ae102SDimitry Andric "ProfAccForSymsInList should be false when profile-sample-accurate "
11411d5ae102SDimitry Andric "is enabled");
11421d5ae102SDimitry Andric
1143e3b55780SDimitry Andric MapVector<CallBase *, const FunctionSamples *> LocalNotInlinedCallSites;
1144dd58ef01SDimitry Andric bool Changed = false;
1145344a3780SDimitry Andric bool LocalChanged = true;
1146344a3780SDimitry Andric while (LocalChanged) {
1147344a3780SDimitry Andric LocalChanged = false;
1148cfca06d7SDimitry Andric SmallVector<CallBase *, 10> CIS;
1149dd58ef01SDimitry Andric for (auto &BB : F) {
1150b915e9e0SDimitry Andric bool Hot = false;
1151cfca06d7SDimitry Andric SmallVector<CallBase *, 10> AllCandidates;
1152cfca06d7SDimitry Andric SmallVector<CallBase *, 10> ColdCandidates;
1153e3b55780SDimitry Andric for (auto &I : BB) {
1154b915e9e0SDimitry Andric const FunctionSamples *FS = nullptr;
1155cfca06d7SDimitry Andric if (auto *CB = dyn_cast<CallBase>(&I)) {
1156c0981da4SDimitry Andric if (!isa<IntrinsicInst>(I)) {
1157c0981da4SDimitry Andric if ((FS = findCalleeFunctionSamples(*CB))) {
1158b60736ecSDimitry Andric assert((!FunctionSamples::UseMD5 || FS->GUIDToFuncNameMap) &&
1159b60736ecSDimitry Andric "GUIDToFuncNameMap has to be populated");
1160cfca06d7SDimitry Andric AllCandidates.push_back(CB);
11614b4fe385SDimitry Andric if (FS->getHeadSamplesEstimate() > 0 ||
11624b4fe385SDimitry Andric FunctionSamples::ProfileIsCS)
1163e3b55780SDimitry Andric LocalNotInlinedCallSites.insert({CB, FS});
1164344a3780SDimitry Andric if (callsiteIsHot(FS, PSI, ProfAccForSymsInList))
1165b915e9e0SDimitry Andric Hot = true;
1166cfca06d7SDimitry Andric else if (shouldInlineColdCallee(*CB))
1167cfca06d7SDimitry Andric ColdCandidates.push_back(CB);
1168c0981da4SDimitry Andric } else if (getExternalInlineAdvisorShouldInline(*CB)) {
1169c0981da4SDimitry Andric AllCandidates.push_back(CB);
1170c0981da4SDimitry Andric }
1171cfca06d7SDimitry Andric }
1172dd58ef01SDimitry Andric }
1173dd58ef01SDimitry Andric }
1174b60736ecSDimitry Andric if (Hot || ExternalInlineAdvisor) {
1175706b4fc4SDimitry Andric CIS.insert(CIS.begin(), AllCandidates.begin(), AllCandidates.end());
1176706b4fc4SDimitry Andric emitOptimizationRemarksForInlineCandidates(AllCandidates, F, true);
1177cfca06d7SDimitry Andric } else {
1178706b4fc4SDimitry Andric CIS.insert(CIS.begin(), ColdCandidates.begin(), ColdCandidates.end());
1179706b4fc4SDimitry Andric emitOptimizationRemarksForInlineCandidates(ColdCandidates, F, false);
1180b915e9e0SDimitry Andric }
1181b915e9e0SDimitry Andric }
1182cfca06d7SDimitry Andric for (CallBase *I : CIS) {
1183cfca06d7SDimitry Andric Function *CalledFunction = I->getCalledFunction();
118477fc4c14SDimitry Andric InlineCandidate Candidate = {I, LocalNotInlinedCallSites.lookup(I),
118577fc4c14SDimitry Andric 0 /* dummy count */,
118677fc4c14SDimitry Andric 1.0 /* dummy distribution factor */};
118708bbd35aSDimitry Andric // Do not inline recursive calls.
118808bbd35aSDimitry Andric if (CalledFunction == &F)
118908bbd35aSDimitry Andric continue;
1190cfca06d7SDimitry Andric if (I->isIndirectCall()) {
1191044eb2f6SDimitry Andric uint64_t Sum;
1192044eb2f6SDimitry Andric for (const auto *FS : findIndirectCallFunctionSamples(*I, Sum)) {
1193344a3780SDimitry Andric uint64_t SumOrigin = Sum;
1194b60736ecSDimitry Andric if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
1195b1c73532SDimitry Andric findExternalInlineCandidate(I, FS, InlinedGUIDs,
1196d8e91e46SDimitry Andric PSI->getOrCompHotCountThreshold());
1197044eb2f6SDimitry Andric continue;
1198044eb2f6SDimitry Andric }
1199344a3780SDimitry Andric if (!callsiteIsHot(FS, PSI, ProfAccForSymsInList))
1200b60736ecSDimitry Andric continue;
1201b60736ecSDimitry Andric
12024b4fe385SDimitry Andric Candidate = {I, FS, FS->getHeadSamplesEstimate(), 1.0};
1203344a3780SDimitry Andric if (tryPromoteAndInlineCandidate(F, Candidate, SumOrigin, Sum)) {
1204344a3780SDimitry Andric LocalNotInlinedCallSites.erase(I);
1205dd58ef01SDimitry Andric LocalChanged = true;
1206044eb2f6SDimitry Andric }
1207044eb2f6SDimitry Andric }
1208044eb2f6SDimitry Andric } else if (CalledFunction && CalledFunction->getSubprogram() &&
1209044eb2f6SDimitry Andric !CalledFunction->isDeclaration()) {
1210344a3780SDimitry Andric if (tryInlineCandidate(Candidate)) {
1211344a3780SDimitry Andric LocalNotInlinedCallSites.erase(I);
1212044eb2f6SDimitry Andric LocalChanged = true;
1213e6d15924SDimitry Andric }
1214b60736ecSDimitry Andric } else if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
1215c0981da4SDimitry Andric findExternalInlineCandidate(I, findCalleeFunctionSamples(*I),
1216b1c73532SDimitry Andric InlinedGUIDs,
1217344a3780SDimitry Andric PSI->getOrCompHotCountThreshold());
1218dd58ef01SDimitry Andric }
1219dd58ef01SDimitry Andric }
1220344a3780SDimitry Andric Changed |= LocalChanged;
1221dd58ef01SDimitry Andric }
1222e6d15924SDimitry Andric
1223344a3780SDimitry Andric // For CS profile, profile for not inlined context will be merged when
122477fc4c14SDimitry Andric // base profile is being retrieved.
1225145449b1SDimitry Andric if (!FunctionSamples::ProfileIsCS)
122677fc4c14SDimitry Andric promoteMergeNotInlinedContextSamples(LocalNotInlinedCallSites, F);
1227dd58ef01SDimitry Andric return Changed;
1228dd58ef01SDimitry Andric }
1229dd58ef01SDimitry Andric
tryInlineCandidate(InlineCandidate & Candidate,SmallVector<CallBase *,8> * InlinedCallSites)1230344a3780SDimitry Andric bool SampleProfileLoader::tryInlineCandidate(
1231344a3780SDimitry Andric InlineCandidate &Candidate, SmallVector<CallBase *, 8> *InlinedCallSites) {
1232145449b1SDimitry Andric // Do not attempt to inline a candidate if
1233145449b1SDimitry Andric // --disable-sample-loader-inlining is true.
1234145449b1SDimitry Andric if (DisableSampleLoaderInlining)
1235145449b1SDimitry Andric return false;
1236344a3780SDimitry Andric
1237344a3780SDimitry Andric CallBase &CB = *Candidate.CallInstr;
1238344a3780SDimitry Andric Function *CalledFunction = CB.getCalledFunction();
1239344a3780SDimitry Andric assert(CalledFunction && "Expect a callee with definition");
1240344a3780SDimitry Andric DebugLoc DLoc = CB.getDebugLoc();
1241344a3780SDimitry Andric BasicBlock *BB = CB.getParent();
1242344a3780SDimitry Andric
1243344a3780SDimitry Andric InlineCost Cost = shouldInlineCandidate(Candidate);
1244344a3780SDimitry Andric if (Cost.isNever()) {
1245145449b1SDimitry Andric ORE->emit(OptimizationRemarkAnalysis(getAnnotatedRemarkPassName(),
1246145449b1SDimitry Andric "InlineFail", DLoc, BB)
1247344a3780SDimitry Andric << "incompatible inlining");
1248344a3780SDimitry Andric return false;
1249b915e9e0SDimitry Andric }
1250dd58ef01SDimitry Andric
1251344a3780SDimitry Andric if (!Cost)
1252344a3780SDimitry Andric return false;
1253344a3780SDimitry Andric
12547fa27ce4SDimitry Andric InlineFunctionInfo IFI(GetAC);
1255344a3780SDimitry Andric IFI.UpdateProfile = false;
1256e3b55780SDimitry Andric InlineResult IR = InlineFunction(CB, IFI,
1257e3b55780SDimitry Andric /*MergeAttributes=*/true);
1258e3b55780SDimitry Andric if (!IR.isSuccess())
1259145449b1SDimitry Andric return false;
1260145449b1SDimitry Andric
1261344a3780SDimitry Andric // The call to InlineFunction erases I, so we can't pass it here.
1262145449b1SDimitry Andric emitInlinedIntoBasedOnCost(*ORE, DLoc, BB, *CalledFunction, *BB->getParent(),
1263145449b1SDimitry Andric Cost, true, getAnnotatedRemarkPassName());
1264344a3780SDimitry Andric
1265344a3780SDimitry Andric // Now populate the list of newly exposed call sites.
1266344a3780SDimitry Andric if (InlinedCallSites) {
1267344a3780SDimitry Andric InlinedCallSites->clear();
1268344a3780SDimitry Andric for (auto &I : IFI.InlinedCallSites)
1269344a3780SDimitry Andric InlinedCallSites->push_back(I);
1270b915e9e0SDimitry Andric }
1271dd58ef01SDimitry Andric
1272145449b1SDimitry Andric if (FunctionSamples::ProfileIsCS)
1273344a3780SDimitry Andric ContextTracker->markContextSamplesInlined(Candidate.CalleeSamples);
1274344a3780SDimitry Andric ++NumCSInlined;
1275344a3780SDimitry Andric
1276344a3780SDimitry Andric // Prorate inlined probes for a duplicated inlining callsite which probably
1277344a3780SDimitry Andric // has a distribution less than 100%. Samples for an inlinee should be
1278344a3780SDimitry Andric // distributed among the copies of the original callsite based on each
1279344a3780SDimitry Andric // callsite's distribution factor for counts accuracy. Note that an inlined
1280344a3780SDimitry Andric // probe may come with its own distribution factor if it has been duplicated
1281344a3780SDimitry Andric // in the inlinee body. The two factor are multiplied to reflect the
1282344a3780SDimitry Andric // aggregation of duplication.
1283344a3780SDimitry Andric if (Candidate.CallsiteDistribution < 1) {
1284344a3780SDimitry Andric for (auto &I : IFI.InlinedCallSites) {
1285e3b55780SDimitry Andric if (std::optional<PseudoProbe> Probe = extractProbe(*I))
1286344a3780SDimitry Andric setProbeDistributionFactor(*I, Probe->Factor *
1287344a3780SDimitry Andric Candidate.CallsiteDistribution);
1288344a3780SDimitry Andric }
1289344a3780SDimitry Andric NumDuplicatedInlinesite++;
1290344a3780SDimitry Andric }
1291344a3780SDimitry Andric
1292344a3780SDimitry Andric return true;
1293344a3780SDimitry Andric }
1294344a3780SDimitry Andric
getInlineCandidate(InlineCandidate * NewCandidate,CallBase * CB)1295344a3780SDimitry Andric bool SampleProfileLoader::getInlineCandidate(InlineCandidate *NewCandidate,
1296344a3780SDimitry Andric CallBase *CB) {
1297344a3780SDimitry Andric assert(CB && "Expect non-null call instruction");
1298344a3780SDimitry Andric
1299344a3780SDimitry Andric if (isa<IntrinsicInst>(CB))
1300344a3780SDimitry Andric return false;
1301344a3780SDimitry Andric
1302344a3780SDimitry Andric // Find the callee's profile. For indirect call, find hottest target profile.
1303344a3780SDimitry Andric const FunctionSamples *CalleeSamples = findCalleeFunctionSamples(*CB);
1304c0981da4SDimitry Andric // If ExternalInlineAdvisor wants to inline this site, do so even
1305c0981da4SDimitry Andric // if Samples are not present.
1306c0981da4SDimitry Andric if (!CalleeSamples && !getExternalInlineAdvisorShouldInline(*CB))
1307344a3780SDimitry Andric return false;
1308344a3780SDimitry Andric
1309344a3780SDimitry Andric float Factor = 1.0;
1310e3b55780SDimitry Andric if (std::optional<PseudoProbe> Probe = extractProbe(*CB))
1311344a3780SDimitry Andric Factor = Probe->Factor;
1312344a3780SDimitry Andric
1313145449b1SDimitry Andric uint64_t CallsiteCount =
13144b4fe385SDimitry Andric CalleeSamples ? CalleeSamples->getHeadSamplesEstimate() * Factor : 0;
1315344a3780SDimitry Andric *NewCandidate = {CB, CalleeSamples, CallsiteCount, Factor};
1316344a3780SDimitry Andric return true;
1317344a3780SDimitry Andric }
1318344a3780SDimitry Andric
1319e3b55780SDimitry Andric std::optional<InlineCost>
getExternalInlineAdvisorCost(CallBase & CB)1320c0981da4SDimitry Andric SampleProfileLoader::getExternalInlineAdvisorCost(CallBase &CB) {
1321344a3780SDimitry Andric std::unique_ptr<InlineAdvice> Advice = nullptr;
1322344a3780SDimitry Andric if (ExternalInlineAdvisor) {
1323c0981da4SDimitry Andric Advice = ExternalInlineAdvisor->getAdvice(CB);
1324c0981da4SDimitry Andric if (Advice) {
1325344a3780SDimitry Andric if (!Advice->isInliningRecommended()) {
1326344a3780SDimitry Andric Advice->recordUnattemptedInlining();
1327344a3780SDimitry Andric return InlineCost::getNever("not previously inlined");
1328344a3780SDimitry Andric }
1329344a3780SDimitry Andric Advice->recordInlining();
1330344a3780SDimitry Andric return InlineCost::getAlways("previously inlined");
1331344a3780SDimitry Andric }
1332c0981da4SDimitry Andric }
1333344a3780SDimitry Andric
1334c0981da4SDimitry Andric return {};
1335c0981da4SDimitry Andric }
1336c0981da4SDimitry Andric
getExternalInlineAdvisorShouldInline(CallBase & CB)1337c0981da4SDimitry Andric bool SampleProfileLoader::getExternalInlineAdvisorShouldInline(CallBase &CB) {
1338e3b55780SDimitry Andric std::optional<InlineCost> Cost = getExternalInlineAdvisorCost(CB);
1339e3b55780SDimitry Andric return Cost ? !!*Cost : false;
1340c0981da4SDimitry Andric }
1341c0981da4SDimitry Andric
1342c0981da4SDimitry Andric InlineCost
shouldInlineCandidate(InlineCandidate & Candidate)1343c0981da4SDimitry Andric SampleProfileLoader::shouldInlineCandidate(InlineCandidate &Candidate) {
1344e3b55780SDimitry Andric if (std::optional<InlineCost> ReplayCost =
1345c0981da4SDimitry Andric getExternalInlineAdvisorCost(*Candidate.CallInstr))
1346e3b55780SDimitry Andric return *ReplayCost;
1347344a3780SDimitry Andric // Adjust threshold based on call site hotness, only do this for callsite
1348344a3780SDimitry Andric // prioritized inliner because otherwise cost-benefit check is done earlier.
1349344a3780SDimitry Andric int SampleThreshold = SampleColdCallSiteThreshold;
1350344a3780SDimitry Andric if (CallsitePrioritizedInline) {
1351344a3780SDimitry Andric if (Candidate.CallsiteCount > PSI->getHotCountThreshold())
1352344a3780SDimitry Andric SampleThreshold = SampleHotCallSiteThreshold;
1353344a3780SDimitry Andric else if (!ProfileSizeInline)
1354344a3780SDimitry Andric return InlineCost::getNever("cold callsite");
1355344a3780SDimitry Andric }
1356344a3780SDimitry Andric
1357344a3780SDimitry Andric Function *Callee = Candidate.CallInstr->getCalledFunction();
1358344a3780SDimitry Andric assert(Callee && "Expect a definition for inline candidate of direct call");
1359344a3780SDimitry Andric
1360344a3780SDimitry Andric InlineParams Params = getInlineParams();
1361c0981da4SDimitry Andric // We will ignore the threshold from inline cost, so always get full cost.
1362344a3780SDimitry Andric Params.ComputeFullInlineCost = true;
1363c0981da4SDimitry Andric Params.AllowRecursiveCall = AllowRecursiveInline;
1364344a3780SDimitry Andric // Checks if there is anything in the reachable portion of the callee at
1365344a3780SDimitry Andric // this callsite that makes this inlining potentially illegal. Need to
1366344a3780SDimitry Andric // set ComputeFullInlineCost, otherwise getInlineCost may return early
1367344a3780SDimitry Andric // when cost exceeds threshold without checking all IRs in the callee.
1368344a3780SDimitry Andric // The acutal cost does not matter because we only checks isNever() to
1369344a3780SDimitry Andric // see if it is legal to inline the callsite.
1370344a3780SDimitry Andric InlineCost Cost = getInlineCost(*Candidate.CallInstr, Callee, Params,
1371344a3780SDimitry Andric GetTTI(*Callee), GetAC, GetTLI);
1372344a3780SDimitry Andric
1373344a3780SDimitry Andric // Honor always inline and never inline from call analyzer
1374344a3780SDimitry Andric if (Cost.isNever() || Cost.isAlways())
1375344a3780SDimitry Andric return Cost;
1376344a3780SDimitry Andric
1377c0981da4SDimitry Andric // With CSSPGO, the preinliner in llvm-profgen can estimate global inline
1378c0981da4SDimitry Andric // decisions based on hotness as well as accurate function byte sizes for
1379c0981da4SDimitry Andric // given context using function/inlinee sizes from previous build. It
1380c0981da4SDimitry Andric // stores the decision in profile, and also adjust/merge context profile
1381c0981da4SDimitry Andric // aiming at better context-sensitive post-inline profile quality, assuming
1382c0981da4SDimitry Andric // all inline decision estimates are going to be honored by compiler. Here
1383c0981da4SDimitry Andric // we replay that inline decision under `sample-profile-use-preinliner`.
1384c0981da4SDimitry Andric // Note that we don't need to handle negative decision from preinliner as
1385c0981da4SDimitry Andric // context profile for not inlined calls are merged by preinliner already.
1386c0981da4SDimitry Andric if (UsePreInlinerDecision && Candidate.CalleeSamples) {
1387c0981da4SDimitry Andric // Once two node are merged due to promotion, we're losing some context
1388c0981da4SDimitry Andric // so the original context-sensitive preinliner decision should be ignored
1389c0981da4SDimitry Andric // for SyntheticContext.
1390c0981da4SDimitry Andric SampleContext &Context = Candidate.CalleeSamples->getContext();
1391c0981da4SDimitry Andric if (!Context.hasState(SyntheticContext) &&
1392c0981da4SDimitry Andric Context.hasAttribute(ContextShouldBeInlined))
1393c0981da4SDimitry Andric return InlineCost::getAlways("preinliner");
1394c0981da4SDimitry Andric }
1395c0981da4SDimitry Andric
1396ac9a064cSDimitry Andric // For old FDO inliner, we inline the call site if it is below hot threshold,
1397ac9a064cSDimitry Andric // even if the function is hot based on sample profile data. This is to
1398ac9a064cSDimitry Andric // prevent huge functions from being inlined.
1399344a3780SDimitry Andric if (!CallsitePrioritizedInline) {
1400ac9a064cSDimitry Andric return InlineCost::get(Cost.getCost(), SampleHotCallSiteThreshold);
1401344a3780SDimitry Andric }
1402344a3780SDimitry Andric
1403344a3780SDimitry Andric // Otherwise only use the cost from call analyzer, but overwite threshold with
1404344a3780SDimitry Andric // Sample PGO threshold.
1405344a3780SDimitry Andric return InlineCost::get(Cost.getCost(), SampleThreshold);
1406344a3780SDimitry Andric }
1407344a3780SDimitry Andric
inlineHotFunctionsWithPriority(Function & F,DenseSet<GlobalValue::GUID> & InlinedGUIDs)1408344a3780SDimitry Andric bool SampleProfileLoader::inlineHotFunctionsWithPriority(
1409344a3780SDimitry Andric Function &F, DenseSet<GlobalValue::GUID> &InlinedGUIDs) {
1410344a3780SDimitry Andric // ProfAccForSymsInList is used in callsiteIsHot. The assertion makes sure
1411344a3780SDimitry Andric // Profile symbol list is ignored when profile-sample-accurate is on.
1412344a3780SDimitry Andric assert((!ProfAccForSymsInList ||
1413344a3780SDimitry Andric (!ProfileSampleAccurate &&
1414344a3780SDimitry Andric !F.hasFnAttribute("profile-sample-accurate"))) &&
1415344a3780SDimitry Andric "ProfAccForSymsInList should be false when profile-sample-accurate "
1416344a3780SDimitry Andric "is enabled");
1417344a3780SDimitry Andric
1418344a3780SDimitry Andric // Populating worklist with initial call sites from root inliner, along
1419344a3780SDimitry Andric // with call site weights.
1420344a3780SDimitry Andric CandidateQueue CQueue;
1421344a3780SDimitry Andric InlineCandidate NewCandidate;
1422dd58ef01SDimitry Andric for (auto &BB : F) {
1423e3b55780SDimitry Andric for (auto &I : BB) {
1424344a3780SDimitry Andric auto *CB = dyn_cast<CallBase>(&I);
1425344a3780SDimitry Andric if (!CB)
1426344a3780SDimitry Andric continue;
1427344a3780SDimitry Andric if (getInlineCandidate(&NewCandidate, CB))
1428344a3780SDimitry Andric CQueue.push(NewCandidate);
1429344a3780SDimitry Andric }
1430344a3780SDimitry Andric }
1431dd58ef01SDimitry Andric
1432344a3780SDimitry Andric // Cap the size growth from profile guided inlining. This is needed even
1433344a3780SDimitry Andric // though cost of each inline candidate already accounts for callee size,
1434344a3780SDimitry Andric // because with top-down inlining, we can grow inliner size significantly
1435344a3780SDimitry Andric // with large number of smaller inlinees each pass the cost check.
1436344a3780SDimitry Andric assert(ProfileInlineLimitMax >= ProfileInlineLimitMin &&
1437344a3780SDimitry Andric "Max inline size limit should not be smaller than min inline size "
1438344a3780SDimitry Andric "limit.");
1439344a3780SDimitry Andric unsigned SizeLimit = F.getInstructionCount() * ProfileInlineGrowthLimit;
1440344a3780SDimitry Andric SizeLimit = std::min(SizeLimit, (unsigned)ProfileInlineLimitMax);
1441344a3780SDimitry Andric SizeLimit = std::max(SizeLimit, (unsigned)ProfileInlineLimitMin);
1442344a3780SDimitry Andric if (ExternalInlineAdvisor)
1443344a3780SDimitry Andric SizeLimit = std::numeric_limits<unsigned>::max();
1444344a3780SDimitry Andric
1445e3b55780SDimitry Andric MapVector<CallBase *, const FunctionSamples *> LocalNotInlinedCallSites;
144677fc4c14SDimitry Andric
1447344a3780SDimitry Andric // Perform iterative BFS call site prioritized inlining
1448344a3780SDimitry Andric bool Changed = false;
1449344a3780SDimitry Andric while (!CQueue.empty() && F.getInstructionCount() < SizeLimit) {
1450344a3780SDimitry Andric InlineCandidate Candidate = CQueue.top();
1451344a3780SDimitry Andric CQueue.pop();
1452344a3780SDimitry Andric CallBase *I = Candidate.CallInstr;
1453344a3780SDimitry Andric Function *CalledFunction = I->getCalledFunction();
1454344a3780SDimitry Andric
1455344a3780SDimitry Andric if (CalledFunction == &F)
1456344a3780SDimitry Andric continue;
1457344a3780SDimitry Andric if (I->isIndirectCall()) {
1458344a3780SDimitry Andric uint64_t Sum = 0;
1459344a3780SDimitry Andric auto CalleeSamples = findIndirectCallFunctionSamples(*I, Sum);
1460344a3780SDimitry Andric uint64_t SumOrigin = Sum;
1461344a3780SDimitry Andric Sum *= Candidate.CallsiteDistribution;
1462344a3780SDimitry Andric unsigned ICPCount = 0;
1463344a3780SDimitry Andric for (const auto *FS : CalleeSamples) {
1464344a3780SDimitry Andric // TODO: Consider disable pre-lTO ICP for MonoLTO as well
1465344a3780SDimitry Andric if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
1466b1c73532SDimitry Andric findExternalInlineCandidate(I, FS, InlinedGUIDs,
1467344a3780SDimitry Andric PSI->getOrCompHotCountThreshold());
1468dd58ef01SDimitry Andric continue;
1469dd58ef01SDimitry Andric }
1470344a3780SDimitry Andric uint64_t EntryCountDistributed =
14714b4fe385SDimitry Andric FS->getHeadSamplesEstimate() * Candidate.CallsiteDistribution;
1472344a3780SDimitry Andric // In addition to regular inline cost check, we also need to make sure
1473344a3780SDimitry Andric // ICP isn't introducing excessive speculative checks even if individual
1474344a3780SDimitry Andric // target looks beneficial to promote and inline. That means we should
1475344a3780SDimitry Andric // only do ICP when there's a small number dominant targets.
1476344a3780SDimitry Andric if (ICPCount >= ProfileICPRelativeHotnessSkip &&
1477344a3780SDimitry Andric EntryCountDistributed * 100 < SumOrigin * ProfileICPRelativeHotness)
1478344a3780SDimitry Andric break;
1479344a3780SDimitry Andric // TODO: Fix CallAnalyzer to handle all indirect calls.
1480344a3780SDimitry Andric // For indirect call, we don't run CallAnalyzer to get InlineCost
1481344a3780SDimitry Andric // before actual inlining. This is because we could see two different
1482344a3780SDimitry Andric // types from the same definition, which makes CallAnalyzer choke as
1483344a3780SDimitry Andric // it's expecting matching parameter type on both caller and callee
1484344a3780SDimitry Andric // side. See example from PR18962 for the triggering cases (the bug was
1485344a3780SDimitry Andric // fixed, but we generate different types).
1486344a3780SDimitry Andric if (!PSI->isHotCount(EntryCountDistributed))
1487344a3780SDimitry Andric break;
1488344a3780SDimitry Andric SmallVector<CallBase *, 8> InlinedCallSites;
1489344a3780SDimitry Andric // Attach function profile for promoted indirect callee, and update
1490344a3780SDimitry Andric // call site count for the promoted inline candidate too.
1491344a3780SDimitry Andric Candidate = {I, FS, EntryCountDistributed,
1492344a3780SDimitry Andric Candidate.CallsiteDistribution};
1493344a3780SDimitry Andric if (tryPromoteAndInlineCandidate(F, Candidate, SumOrigin, Sum,
1494344a3780SDimitry Andric &InlinedCallSites)) {
1495344a3780SDimitry Andric for (auto *CB : InlinedCallSites) {
1496344a3780SDimitry Andric if (getInlineCandidate(&NewCandidate, CB))
1497344a3780SDimitry Andric CQueue.emplace(NewCandidate);
1498dd58ef01SDimitry Andric }
1499344a3780SDimitry Andric ICPCount++;
1500dd58ef01SDimitry Andric Changed = true;
150177fc4c14SDimitry Andric } else if (!ContextTracker) {
1502e3b55780SDimitry Andric LocalNotInlinedCallSites.insert({I, FS});
150301095a5dSDimitry Andric }
1504344a3780SDimitry Andric }
1505344a3780SDimitry Andric } else if (CalledFunction && CalledFunction->getSubprogram() &&
1506344a3780SDimitry Andric !CalledFunction->isDeclaration()) {
1507344a3780SDimitry Andric SmallVector<CallBase *, 8> InlinedCallSites;
1508344a3780SDimitry Andric if (tryInlineCandidate(Candidate, &InlinedCallSites)) {
1509344a3780SDimitry Andric for (auto *CB : InlinedCallSites) {
1510344a3780SDimitry Andric if (getInlineCandidate(&NewCandidate, CB))
1511344a3780SDimitry Andric CQueue.emplace(NewCandidate);
1512344a3780SDimitry Andric }
1513344a3780SDimitry Andric Changed = true;
151477fc4c14SDimitry Andric } else if (!ContextTracker) {
1515e3b55780SDimitry Andric LocalNotInlinedCallSites.insert({I, Candidate.CalleeSamples});
1516344a3780SDimitry Andric }
1517344a3780SDimitry Andric } else if (LTOPhase == ThinOrFullLTOPhase::ThinLTOPreLink) {
1518c0981da4SDimitry Andric findExternalInlineCandidate(I, findCalleeFunctionSamples(*I),
1519b1c73532SDimitry Andric InlinedGUIDs,
1520c0981da4SDimitry Andric PSI->getOrCompHotCountThreshold());
1521344a3780SDimitry Andric }
1522344a3780SDimitry Andric }
1523344a3780SDimitry Andric
1524344a3780SDimitry Andric if (!CQueue.empty()) {
1525344a3780SDimitry Andric if (SizeLimit == (unsigned)ProfileInlineLimitMax)
1526344a3780SDimitry Andric ++NumCSInlinedHitMaxLimit;
1527344a3780SDimitry Andric else if (SizeLimit == (unsigned)ProfileInlineLimitMin)
1528344a3780SDimitry Andric ++NumCSInlinedHitMinLimit;
1529dd58ef01SDimitry Andric else
1530344a3780SDimitry Andric ++NumCSInlinedHitGrowthLimit;
1531dd58ef01SDimitry Andric }
1532dd58ef01SDimitry Andric
153377fc4c14SDimitry Andric // For CS profile, profile for not inlined context will be merged when
153477fc4c14SDimitry Andric // base profile is being retrieved.
1535145449b1SDimitry Andric if (!FunctionSamples::ProfileIsCS)
153677fc4c14SDimitry Andric promoteMergeNotInlinedContextSamples(LocalNotInlinedCallSites, F);
1537dd58ef01SDimitry Andric return Changed;
1538dd58ef01SDimitry Andric }
1539dd58ef01SDimitry Andric
promoteMergeNotInlinedContextSamples(MapVector<CallBase *,const FunctionSamples * > NonInlinedCallSites,const Function & F)154077fc4c14SDimitry Andric void SampleProfileLoader::promoteMergeNotInlinedContextSamples(
1541e3b55780SDimitry Andric MapVector<CallBase *, const FunctionSamples *> NonInlinedCallSites,
154277fc4c14SDimitry Andric const Function &F) {
154377fc4c14SDimitry Andric // Accumulate not inlined callsite information into notInlinedSamples
154477fc4c14SDimitry Andric for (const auto &Pair : NonInlinedCallSites) {
1545e3b55780SDimitry Andric CallBase *I = Pair.first;
154677fc4c14SDimitry Andric Function *Callee = I->getCalledFunction();
154777fc4c14SDimitry Andric if (!Callee || Callee->isDeclaration())
154877fc4c14SDimitry Andric continue;
154977fc4c14SDimitry Andric
1550145449b1SDimitry Andric ORE->emit(
1551145449b1SDimitry Andric OptimizationRemarkAnalysis(getAnnotatedRemarkPassName(), "NotInline",
155277fc4c14SDimitry Andric I->getDebugLoc(), I->getParent())
1553145449b1SDimitry Andric << "previous inlining not repeated: '" << ore::NV("Callee", Callee)
1554145449b1SDimitry Andric << "' into '" << ore::NV("Caller", &F) << "'");
155577fc4c14SDimitry Andric
155677fc4c14SDimitry Andric ++NumCSNotInlined;
1557e3b55780SDimitry Andric const FunctionSamples *FS = Pair.second;
15584b4fe385SDimitry Andric if (FS->getTotalSamples() == 0 && FS->getHeadSamplesEstimate() == 0) {
155977fc4c14SDimitry Andric continue;
156077fc4c14SDimitry Andric }
156177fc4c14SDimitry Andric
1562145449b1SDimitry Andric // Do not merge a context that is already duplicated into the base profile.
1563145449b1SDimitry Andric if (FS->getContext().hasAttribute(sampleprof::ContextDuplicatedIntoBase))
1564145449b1SDimitry Andric continue;
1565145449b1SDimitry Andric
156677fc4c14SDimitry Andric if (ProfileMergeInlinee) {
156777fc4c14SDimitry Andric // A function call can be replicated by optimizations like callsite
156877fc4c14SDimitry Andric // splitting or jump threading and the replicates end up sharing the
156977fc4c14SDimitry Andric // sample nested callee profile instead of slicing the original
157077fc4c14SDimitry Andric // inlinee's profile. We want to do merge exactly once by filtering out
157177fc4c14SDimitry Andric // callee profiles with a non-zero head sample count.
157277fc4c14SDimitry Andric if (FS->getHeadSamples() == 0) {
157377fc4c14SDimitry Andric // Use entry samples as head samples during the merge, as inlinees
157477fc4c14SDimitry Andric // don't have head samples.
157577fc4c14SDimitry Andric const_cast<FunctionSamples *>(FS)->addHeadSamples(
15764b4fe385SDimitry Andric FS->getHeadSamplesEstimate());
157777fc4c14SDimitry Andric
157877fc4c14SDimitry Andric // Note that we have to do the merge right after processing function.
157977fc4c14SDimitry Andric // This allows OutlineFS's profile to be used for annotation during
158077fc4c14SDimitry Andric // top-down processing of functions' annotation.
1581b1c73532SDimitry Andric FunctionSamples *OutlineFS = Reader->getSamplesFor(*Callee);
1582b1c73532SDimitry Andric // If outlined function does not exist in the profile, add it to a
1583b1c73532SDimitry Andric // separate map so that it does not rehash the original profile.
1584b1c73532SDimitry Andric if (!OutlineFS)
1585b1c73532SDimitry Andric OutlineFS = &OutlineFunctionSamples[
1586b1c73532SDimitry Andric FunctionId(FunctionSamples::getCanonicalFnName(Callee->getName()))];
158777fc4c14SDimitry Andric OutlineFS->merge(*FS, 1);
158877fc4c14SDimitry Andric // Set outlined profile to be synthetic to not bias the inliner.
1589ac9a064cSDimitry Andric OutlineFS->setContextSynthetic();
159077fc4c14SDimitry Andric }
159177fc4c14SDimitry Andric } else {
159277fc4c14SDimitry Andric auto pair =
159377fc4c14SDimitry Andric notInlinedCallInfo.try_emplace(Callee, NotInlinedProfileInfo{0});
15944b4fe385SDimitry Andric pair.first->second.entryCount += FS->getHeadSamplesEstimate();
159577fc4c14SDimitry Andric }
159677fc4c14SDimitry Andric }
159777fc4c14SDimitry Andric }
159877fc4c14SDimitry Andric
1599044eb2f6SDimitry Andric /// Returns the sorted CallTargetMap \p M by count in descending order.
1600344a3780SDimitry Andric static SmallVector<InstrProfValueData, 2>
GetSortedValueDataFromCallTargets(const SampleRecord::CallTargetMap & M)1601344a3780SDimitry Andric GetSortedValueDataFromCallTargets(const SampleRecord::CallTargetMap &M) {
1602044eb2f6SDimitry Andric SmallVector<InstrProfValueData, 2> R;
1603ac9a064cSDimitry Andric for (const auto &I : SampleRecord::sortCallTargets(M)) {
1604344a3780SDimitry Andric R.emplace_back(
1605b1c73532SDimitry Andric InstrProfValueData{I.first.getHashCode(), I.second});
16061d5ae102SDimitry Andric }
1607044eb2f6SDimitry Andric return R;
160871d5a254SDimitry Andric }
160971d5a254SDimitry Andric
1610344a3780SDimitry Andric // Generate MD_prof metadata for every branch instruction using the
1611344a3780SDimitry Andric // edge weights computed during propagation.
generateMDProfMetadata(Function & F)1612344a3780SDimitry Andric void SampleProfileLoader::generateMDProfMetadata(Function &F) {
1613dd58ef01SDimitry Andric // Generate MD_prof metadata for every branch instruction using the
1614dd58ef01SDimitry Andric // edge weights computed during propagation.
1615eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "\nPropagation complete. Setting branch weights\n");
1616dd58ef01SDimitry Andric LLVMContext &Ctx = F.getContext();
1617dd58ef01SDimitry Andric MDBuilder MDB(Ctx);
1618dd58ef01SDimitry Andric for (auto &BI : F) {
1619dd58ef01SDimitry Andric BasicBlock *BB = &BI;
162001095a5dSDimitry Andric
162101095a5dSDimitry Andric if (BlockWeights[BB]) {
1622e3b55780SDimitry Andric for (auto &I : *BB) {
162371d5a254SDimitry Andric if (!isa<CallInst>(I) && !isa<InvokeInst>(I))
162471d5a254SDimitry Andric continue;
1625cfca06d7SDimitry Andric if (!cast<CallBase>(I).getCalledFunction()) {
162671d5a254SDimitry Andric const DebugLoc &DLoc = I.getDebugLoc();
162771d5a254SDimitry Andric if (!DLoc)
162871d5a254SDimitry Andric continue;
162971d5a254SDimitry Andric const DILocation *DIL = DLoc;
163071d5a254SDimitry Andric const FunctionSamples *FS = findFunctionSamples(I);
163171d5a254SDimitry Andric if (!FS)
163271d5a254SDimitry Andric continue;
1633b60736ecSDimitry Andric auto CallSite = FunctionSamples::getCallSiteIdentifier(DIL);
163499aabd70SDimitry Andric ErrorOr<SampleRecord::CallTargetMap> T =
163599aabd70SDimitry Andric FS->findCallTargetMapAt(CallSite);
1636044eb2f6SDimitry Andric if (!T || T.get().empty())
163771d5a254SDimitry Andric continue;
1638344a3780SDimitry Andric if (FunctionSamples::ProfileIsProbeBased) {
1639344a3780SDimitry Andric // Prorate the callsite counts based on the pre-ICP distribution
1640344a3780SDimitry Andric // factor to reflect what is already done to the callsite before
1641344a3780SDimitry Andric // ICP, such as calliste cloning.
1642e3b55780SDimitry Andric if (std::optional<PseudoProbe> Probe = extractProbe(I)) {
1643344a3780SDimitry Andric if (Probe->Factor < 1)
1644344a3780SDimitry Andric T = SampleRecord::adjustCallTargets(T.get(), Probe->Factor);
1645344a3780SDimitry Andric }
1646344a3780SDimitry Andric }
1647044eb2f6SDimitry Andric SmallVector<InstrProfValueData, 2> SortedCallTargets =
16481d5ae102SDimitry Andric GetSortedValueDataFromCallTargets(T.get());
1649344a3780SDimitry Andric uint64_t Sum = 0;
1650344a3780SDimitry Andric for (const auto &C : T.get())
1651344a3780SDimitry Andric Sum += C.second;
1652344a3780SDimitry Andric // With CSSPGO all indirect call targets are counted torwards the
1653344a3780SDimitry Andric // original indirect call site in the profile, including both
1654344a3780SDimitry Andric // inlined and non-inlined targets.
1655145449b1SDimitry Andric if (!FunctionSamples::ProfileIsCS) {
1656344a3780SDimitry Andric if (const FunctionSamplesMap *M =
1657344a3780SDimitry Andric FS->findFunctionSamplesMapAt(CallSite)) {
1658344a3780SDimitry Andric for (const auto &NameFS : *M)
16594b4fe385SDimitry Andric Sum += NameFS.second.getHeadSamplesEstimate();
1660344a3780SDimitry Andric }
1661344a3780SDimitry Andric }
1662344a3780SDimitry Andric if (Sum)
1663344a3780SDimitry Andric updateIDTMetaData(I, SortedCallTargets, Sum);
1664344a3780SDimitry Andric else if (OverwriteExistingWeights)
1665344a3780SDimitry Andric I.setMetadata(LLVMContext::MD_prof, nullptr);
1666e6d15924SDimitry Andric } else if (!isa<IntrinsicInst>(&I)) {
1667ac9a064cSDimitry Andric setBranchWeights(I, {static_cast<uint32_t>(BlockWeights[BB])},
1668ac9a064cSDimitry Andric /*IsExpected=*/false);
166901095a5dSDimitry Andric }
167001095a5dSDimitry Andric }
1671c0981da4SDimitry Andric } else if (OverwriteExistingWeights || ProfileSampleBlockAccurate) {
1672344a3780SDimitry Andric // Set profile metadata (possibly annotated by LTO prelink) to zero or
1673344a3780SDimitry Andric // clear it for cold code.
1674e3b55780SDimitry Andric for (auto &I : *BB) {
1675344a3780SDimitry Andric if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
1676b1c73532SDimitry Andric if (cast<CallBase>(I).isIndirectCall()) {
1677344a3780SDimitry Andric I.setMetadata(LLVMContext::MD_prof, nullptr);
1678b1c73532SDimitry Andric } else {
1679ac9a064cSDimitry Andric setBranchWeights(I, {uint32_t(0)}, /*IsExpected=*/false);
1680b1c73532SDimitry Andric }
168101095a5dSDimitry Andric }
1682344a3780SDimitry Andric }
1683344a3780SDimitry Andric }
1684344a3780SDimitry Andric
1685d8e91e46SDimitry Andric Instruction *TI = BB->getTerminator();
1686dd58ef01SDimitry Andric if (TI->getNumSuccessors() == 1)
1687dd58ef01SDimitry Andric continue;
1688344a3780SDimitry Andric if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI) &&
1689344a3780SDimitry Andric !isa<IndirectBrInst>(TI))
1690dd58ef01SDimitry Andric continue;
1691dd58ef01SDimitry Andric
1692d99dafe2SDimitry Andric DebugLoc BranchLoc = TI->getDebugLoc();
1693eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "\nGetting weights for branch at line "
1694d99dafe2SDimitry Andric << ((BranchLoc) ? Twine(BranchLoc.getLine())
1695d99dafe2SDimitry Andric : Twine("<UNKNOWN LOCATION>"))
1696d99dafe2SDimitry Andric << ".\n");
1697dd58ef01SDimitry Andric SmallVector<uint32_t, 4> Weights;
1698dd58ef01SDimitry Andric uint32_t MaxWeight = 0;
1699044eb2f6SDimitry Andric Instruction *MaxDestInst;
1700f65dcba8SDimitry Andric // Since profi treats multiple edges (multiway branches) as a single edge,
1701f65dcba8SDimitry Andric // we need to distribute the computed weight among the branches. We do
1702f65dcba8SDimitry Andric // this by evenly splitting the edge weight among destinations.
1703f65dcba8SDimitry Andric DenseMap<const BasicBlock *, uint64_t> EdgeMultiplicity;
1704f65dcba8SDimitry Andric std::vector<uint64_t> EdgeIndex;
1705f65dcba8SDimitry Andric if (SampleProfileUseProfi) {
1706f65dcba8SDimitry Andric EdgeIndex.resize(TI->getNumSuccessors());
1707f65dcba8SDimitry Andric for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
1708f65dcba8SDimitry Andric const BasicBlock *Succ = TI->getSuccessor(I);
1709f65dcba8SDimitry Andric EdgeIndex[I] = EdgeMultiplicity[Succ];
1710f65dcba8SDimitry Andric EdgeMultiplicity[Succ]++;
1711f65dcba8SDimitry Andric }
1712f65dcba8SDimitry Andric }
1713dd58ef01SDimitry Andric for (unsigned I = 0; I < TI->getNumSuccessors(); ++I) {
1714dd58ef01SDimitry Andric BasicBlock *Succ = TI->getSuccessor(I);
1715dd58ef01SDimitry Andric Edge E = std::make_pair(BB, Succ);
1716dd58ef01SDimitry Andric uint64_t Weight = EdgeWeights[E];
1717eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "\t"; printEdgeWeight(dbgs(), E));
1718dd58ef01SDimitry Andric // Use uint32_t saturated arithmetic to adjust the incoming weights,
1719dd58ef01SDimitry Andric // if needed. Sample counts in profiles are 64-bit unsigned values,
1720dd58ef01SDimitry Andric // but internally branch weights are expressed as 32-bit values.
1721dd58ef01SDimitry Andric if (Weight > std::numeric_limits<uint32_t>::max()) {
1722ac9a064cSDimitry Andric LLVM_DEBUG(dbgs() << " (saturated due to uint32_t overflow)\n");
1723dd58ef01SDimitry Andric Weight = std::numeric_limits<uint32_t>::max();
1724dd58ef01SDimitry Andric }
1725f65dcba8SDimitry Andric if (!SampleProfileUseProfi) {
1726b915e9e0SDimitry Andric // Weight is added by one to avoid propagation errors introduced by
1727b915e9e0SDimitry Andric // 0 weights.
1728ac9a064cSDimitry Andric Weights.push_back(static_cast<uint32_t>(
1729ac9a064cSDimitry Andric Weight == std::numeric_limits<uint32_t>::max() ? Weight
1730ac9a064cSDimitry Andric : Weight + 1));
1731f65dcba8SDimitry Andric } else {
1732f65dcba8SDimitry Andric // Profi creates proper weights that do not require "+1" adjustments but
1733f65dcba8SDimitry Andric // we evenly split the weight among branches with the same destination.
1734f65dcba8SDimitry Andric uint64_t W = Weight / EdgeMultiplicity[Succ];
1735f65dcba8SDimitry Andric // Rounding up, if needed, so that first branches are hotter.
1736f65dcba8SDimitry Andric if (EdgeIndex[I] < Weight % EdgeMultiplicity[Succ])
1737f65dcba8SDimitry Andric W++;
1738f65dcba8SDimitry Andric Weights.push_back(static_cast<uint32_t>(W));
1739f65dcba8SDimitry Andric }
1740dd58ef01SDimitry Andric if (Weight != 0) {
1741dd58ef01SDimitry Andric if (Weight > MaxWeight) {
1742dd58ef01SDimitry Andric MaxWeight = Weight;
1743044eb2f6SDimitry Andric MaxDestInst = Succ->getFirstNonPHIOrDbgOrLifetime();
1744dd58ef01SDimitry Andric }
1745dd58ef01SDimitry Andric }
1746dd58ef01SDimitry Andric }
1747dd58ef01SDimitry Andric
1748e3b55780SDimitry Andric misexpect::checkExpectAnnotations(*TI, Weights, /*IsFrontend=*/false);
1749145449b1SDimitry Andric
175071d5a254SDimitry Andric uint64_t TempWeight;
1751dd58ef01SDimitry Andric // Only set weights if there is at least one non-zero weight.
1752dd58ef01SDimitry Andric // In any other case, let the analyzer set weights.
1753344a3780SDimitry Andric // Do not set weights if the weights are present unless under
1754344a3780SDimitry Andric // OverwriteExistingWeights. In ThinLTO, the profile annotation is done
1755344a3780SDimitry Andric // twice. If the first annotation already set the weights, the second pass
1756344a3780SDimitry Andric // does not need to set it. With OverwriteExistingWeights, Blocks with zero
1757344a3780SDimitry Andric // weight should have their existing metadata (possibly annotated by LTO
1758344a3780SDimitry Andric // prelink) cleared.
1759344a3780SDimitry Andric if (MaxWeight > 0 &&
1760344a3780SDimitry Andric (!TI->extractProfTotalWeight(TempWeight) || OverwriteExistingWeights)) {
1761eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "SUCCESS. Found non-zero weights.\n");
1762ac9a064cSDimitry Andric setBranchWeights(*TI, Weights, /*IsExpected=*/false);
1763044eb2f6SDimitry Andric ORE->emit([&]() {
1764044eb2f6SDimitry Andric return OptimizationRemark(DEBUG_TYPE, "PopularDest", MaxDestInst)
1765044eb2f6SDimitry Andric << "most popular destination for conditional branches at "
1766044eb2f6SDimitry Andric << ore::NV("CondBranchesLoc", BranchLoc);
1767044eb2f6SDimitry Andric });
1768dd58ef01SDimitry Andric } else {
1769344a3780SDimitry Andric if (OverwriteExistingWeights) {
1770344a3780SDimitry Andric TI->setMetadata(LLVMContext::MD_prof, nullptr);
1771344a3780SDimitry Andric LLVM_DEBUG(dbgs() << "CLEARED. All branch weights are zero.\n");
1772344a3780SDimitry Andric } else {
1773eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "SKIPPED. All branch weights are zero.\n");
1774dd58ef01SDimitry Andric }
1775dd58ef01SDimitry Andric }
1776dd58ef01SDimitry Andric }
1777dd58ef01SDimitry Andric }
1778dd58ef01SDimitry Andric
1779dd58ef01SDimitry Andric /// Once all the branch weights are computed, we emit the MD_prof
1780dd58ef01SDimitry Andric /// metadata on BB using the computed values for each of its branches.
1781dd58ef01SDimitry Andric ///
1782dd58ef01SDimitry Andric /// \param F The function to query.
1783dd58ef01SDimitry Andric ///
1784dd58ef01SDimitry Andric /// \returns true if \p F was modified. Returns false, otherwise.
emitAnnotations(Function & F)1785dd58ef01SDimitry Andric bool SampleProfileLoader::emitAnnotations(Function &F) {
1786dd58ef01SDimitry Andric bool Changed = false;
1787dd58ef01SDimitry Andric
1788b60736ecSDimitry Andric if (FunctionSamples::ProfileIsProbeBased) {
1789ac9a064cSDimitry Andric LLVM_DEBUG({
1790ac9a064cSDimitry Andric if (!ProbeManager->getDesc(F))
1791ac9a064cSDimitry Andric dbgs() << "Probe descriptor missing for Function " << F.getName()
1792ac9a064cSDimitry Andric << "\n";
1793ac9a064cSDimitry Andric });
1794ac9a064cSDimitry Andric
1795ac9a064cSDimitry Andric if (ProbeManager->profileIsValid(F, *Samples)) {
1796ac9a064cSDimitry Andric ++NumMatchedProfile;
1797ac9a064cSDimitry Andric } else {
1798ac9a064cSDimitry Andric ++NumMismatchedProfile;
1799b60736ecSDimitry Andric LLVM_DEBUG(
1800b60736ecSDimitry Andric dbgs() << "Profile is invalid due to CFG mismatch for Function "
18017fa27ce4SDimitry Andric << F.getName() << "\n");
18027fa27ce4SDimitry Andric if (!SalvageStaleProfile)
1803b60736ecSDimitry Andric return false;
1804b60736ecSDimitry Andric }
1805b60736ecSDimitry Andric } else {
1806dd58ef01SDimitry Andric if (getFunctionLoc(F) == 0)
1807dd58ef01SDimitry Andric return false;
1808dd58ef01SDimitry Andric
1809eb11fae6SDimitry Andric LLVM_DEBUG(dbgs() << "Line number for the first instruction in "
1810eb11fae6SDimitry Andric << F.getName() << ": " << getFunctionLoc(F) << "\n");
1811b60736ecSDimitry Andric }
1812dd58ef01SDimitry Andric
1813044eb2f6SDimitry Andric DenseSet<GlobalValue::GUID> InlinedGUIDs;
181477fc4c14SDimitry Andric if (CallsitePrioritizedInline)
1815344a3780SDimitry Andric Changed |= inlineHotFunctionsWithPriority(F, InlinedGUIDs);
1816344a3780SDimitry Andric else
1817044eb2f6SDimitry Andric Changed |= inlineHotFunctions(F, InlinedGUIDs);
1818dd58ef01SDimitry Andric
1819344a3780SDimitry Andric Changed |= computeAndPropagateWeights(F, InlinedGUIDs);
1820dd58ef01SDimitry Andric
1821344a3780SDimitry Andric if (Changed)
1822344a3780SDimitry Andric generateMDProfMetadata(F);
182371d5a254SDimitry Andric
1824344a3780SDimitry Andric emitCoverageRemarks(F);
1825dd58ef01SDimitry Andric return Changed;
1826dd58ef01SDimitry Andric }
1827dd58ef01SDimitry Andric
1828344a3780SDimitry Andric std::unique_ptr<ProfiledCallGraph>
buildProfiledCallGraph(Module & M)18297fa27ce4SDimitry Andric SampleProfileLoader::buildProfiledCallGraph(Module &M) {
1830344a3780SDimitry Andric std::unique_ptr<ProfiledCallGraph> ProfiledCG;
1831145449b1SDimitry Andric if (FunctionSamples::ProfileIsCS)
1832344a3780SDimitry Andric ProfiledCG = std::make_unique<ProfiledCallGraph>(*ContextTracker);
1833344a3780SDimitry Andric else
1834344a3780SDimitry Andric ProfiledCG = std::make_unique<ProfiledCallGraph>(Reader->getProfiles());
1835344a3780SDimitry Andric
1836344a3780SDimitry Andric // Add all functions into the profiled call graph even if they are not in
1837344a3780SDimitry Andric // the profile. This makes sure functions missing from the profile still
1838344a3780SDimitry Andric // gets a chance to be processed.
18397fa27ce4SDimitry Andric for (Function &F : M) {
1840ac9a064cSDimitry Andric if (skipProfileForFunction(F))
1841344a3780SDimitry Andric continue;
1842b1c73532SDimitry Andric ProfiledCG->addProfiledFunction(
1843b1c73532SDimitry Andric getRepInFormat(FunctionSamples::getCanonicalFnName(F)));
1844344a3780SDimitry Andric }
1845344a3780SDimitry Andric
1846344a3780SDimitry Andric return ProfiledCG;
1847344a3780SDimitry Andric }
1848344a3780SDimitry Andric
1849706b4fc4SDimitry Andric std::vector<Function *>
buildFunctionOrder(Module & M,LazyCallGraph & CG)18507fa27ce4SDimitry Andric SampleProfileLoader::buildFunctionOrder(Module &M, LazyCallGraph &CG) {
1851706b4fc4SDimitry Andric std::vector<Function *> FunctionOrderList;
1852706b4fc4SDimitry Andric FunctionOrderList.reserve(M.size());
1853706b4fc4SDimitry Andric
1854344a3780SDimitry Andric if (!ProfileTopDownLoad && UseProfiledCallGraph)
1855344a3780SDimitry Andric errs() << "WARNING: -use-profiled-call-graph ignored, should be used "
1856344a3780SDimitry Andric "together with -sample-profile-top-down-load.\n";
1857344a3780SDimitry Andric
18587fa27ce4SDimitry Andric if (!ProfileTopDownLoad) {
1859cfca06d7SDimitry Andric if (ProfileMergeInlinee) {
1860cfca06d7SDimitry Andric // Disable ProfileMergeInlinee if profile is not loaded in top down order,
1861cfca06d7SDimitry Andric // because the profile for a function may be used for the profile
1862cfca06d7SDimitry Andric // annotation of its outline copy before the profile merging of its
1863cfca06d7SDimitry Andric // non-inlined inline instances, and that is not the way how
1864cfca06d7SDimitry Andric // ProfileMergeInlinee is supposed to work.
1865cfca06d7SDimitry Andric ProfileMergeInlinee = false;
1866cfca06d7SDimitry Andric }
1867cfca06d7SDimitry Andric
1868706b4fc4SDimitry Andric for (Function &F : M)
1869ac9a064cSDimitry Andric if (!skipProfileForFunction(F))
1870706b4fc4SDimitry Andric FunctionOrderList.push_back(&F);
1871706b4fc4SDimitry Andric return FunctionOrderList;
1872706b4fc4SDimitry Andric }
1873706b4fc4SDimitry Andric
1874145449b1SDimitry Andric if (UseProfiledCallGraph || (FunctionSamples::ProfileIsCS &&
1875145449b1SDimitry Andric !UseProfiledCallGraph.getNumOccurrences())) {
1876344a3780SDimitry Andric // Use profiled call edges to augment the top-down order. There are cases
1877344a3780SDimitry Andric // that the top-down order computed based on the static call graph doesn't
1878344a3780SDimitry Andric // reflect real execution order. For example
1879344a3780SDimitry Andric //
1880344a3780SDimitry Andric // 1. Incomplete static call graph due to unknown indirect call targets.
1881344a3780SDimitry Andric // Adjusting the order by considering indirect call edges from the
1882344a3780SDimitry Andric // profile can enable the inlining of indirect call targets by allowing
1883344a3780SDimitry Andric // the caller processed before them.
1884344a3780SDimitry Andric // 2. Mutual call edges in an SCC. The static processing order computed for
1885344a3780SDimitry Andric // an SCC may not reflect the call contexts in the context-sensitive
1886344a3780SDimitry Andric // profile, thus may cause potential inlining to be overlooked. The
1887344a3780SDimitry Andric // function order in one SCC is being adjusted to a top-down order based
1888344a3780SDimitry Andric // on the profile to favor more inlining. This is only a problem with CS
1889344a3780SDimitry Andric // profile.
1890344a3780SDimitry Andric // 3. Transitive indirect call edges due to inlining. When a callee function
1891b1c73532SDimitry Andric // (say B) is inlined into a caller function (say A) in LTO prelink,
1892344a3780SDimitry Andric // every call edge originated from the callee B will be transferred to
1893344a3780SDimitry Andric // the caller A. If any transferred edge (say A->C) is indirect, the
1894344a3780SDimitry Andric // original profiled indirect edge B->C, even if considered, would not
1895344a3780SDimitry Andric // enforce a top-down order from the caller A to the potential indirect
1896344a3780SDimitry Andric // call target C in LTO postlink since the inlined callee B is gone from
1897344a3780SDimitry Andric // the static call graph.
1898344a3780SDimitry Andric // 4. #3 can happen even for direct call targets, due to functions defined
1899344a3780SDimitry Andric // in header files. A header function (say A), when included into source
1900344a3780SDimitry Andric // files, is defined multiple times but only one definition survives due
1901344a3780SDimitry Andric // to ODR. Therefore, the LTO prelink inlining done on those dropped
1902344a3780SDimitry Andric // definitions can be useless based on a local file scope. More
1903344a3780SDimitry Andric // importantly, the inlinee (say B), once fully inlined to a
1904344a3780SDimitry Andric // to-be-dropped A, will have no profile to consume when its outlined
1905344a3780SDimitry Andric // version is compiled. This can lead to a profile-less prelink
1906344a3780SDimitry Andric // compilation for the outlined version of B which may be called from
1907344a3780SDimitry Andric // external modules. while this isn't easy to fix, we rely on the
1908344a3780SDimitry Andric // postlink AutoFDO pipeline to optimize B. Since the survived copy of
1909344a3780SDimitry Andric // the A can be inlined in its local scope in prelink, it may not exist
1910344a3780SDimitry Andric // in the merged IR in postlink, and we'll need the profiled call edges
1911344a3780SDimitry Andric // to enforce a top-down order for the rest of the functions.
1912344a3780SDimitry Andric //
1913344a3780SDimitry Andric // Considering those cases, a profiled call graph completely independent of
1914344a3780SDimitry Andric // the static call graph is constructed based on profile data, where
1915344a3780SDimitry Andric // function objects are not even needed to handle case #3 and case 4.
1916344a3780SDimitry Andric //
1917344a3780SDimitry Andric // Note that static callgraph edges are completely ignored since they
1918344a3780SDimitry Andric // can be conflicting with profiled edges for cyclic SCCs and may result in
1919344a3780SDimitry Andric // an SCC order incompatible with profile-defined one. Using strictly
1920344a3780SDimitry Andric // profile order ensures a maximum inlining experience. On the other hand,
1921344a3780SDimitry Andric // static call edges are not so important when they don't correspond to a
1922344a3780SDimitry Andric // context in the profile.
1923344a3780SDimitry Andric
19247fa27ce4SDimitry Andric std::unique_ptr<ProfiledCallGraph> ProfiledCG = buildProfiledCallGraph(M);
1925344a3780SDimitry Andric scc_iterator<ProfiledCallGraph *> CGI = scc_begin(ProfiledCG.get());
1926706b4fc4SDimitry Andric while (!CGI.isAtEnd()) {
1927f65dcba8SDimitry Andric auto Range = *CGI;
1928f65dcba8SDimitry Andric if (SortProfiledSCC) {
1929f65dcba8SDimitry Andric // Sort nodes in one SCC based on callsite hotness.
1930f65dcba8SDimitry Andric scc_member_iterator<ProfiledCallGraph *> SI(*CGI);
1931f65dcba8SDimitry Andric Range = *SI;
1932f65dcba8SDimitry Andric }
1933f65dcba8SDimitry Andric for (auto *Node : Range) {
1934344a3780SDimitry Andric Function *F = SymbolMap.lookup(Node->Name);
1935ac9a064cSDimitry Andric if (F && !skipProfileForFunction(*F))
1936706b4fc4SDimitry Andric FunctionOrderList.push_back(F);
1937706b4fc4SDimitry Andric }
1938706b4fc4SDimitry Andric ++CGI;
1939706b4fc4SDimitry Andric }
19407fa27ce4SDimitry Andric std::reverse(FunctionOrderList.begin(), FunctionOrderList.end());
1941ac9a064cSDimitry Andric } else
1942ac9a064cSDimitry Andric buildTopDownFuncOrder(CG, FunctionOrderList);
19437fa27ce4SDimitry Andric
1944344a3780SDimitry Andric LLVM_DEBUG({
1945344a3780SDimitry Andric dbgs() << "Function processing order:\n";
19467fa27ce4SDimitry Andric for (auto F : FunctionOrderList) {
1947344a3780SDimitry Andric dbgs() << F->getName() << "\n";
1948344a3780SDimitry Andric }
1949344a3780SDimitry Andric });
1950706b4fc4SDimitry Andric
1951706b4fc4SDimitry Andric return FunctionOrderList;
1952706b4fc4SDimitry Andric }
1953706b4fc4SDimitry Andric
doInitialization(Module & M,FunctionAnalysisManager * FAM)1954b60736ecSDimitry Andric bool SampleProfileLoader::doInitialization(Module &M,
1955b60736ecSDimitry Andric FunctionAnalysisManager *FAM) {
1956dd58ef01SDimitry Andric auto &Ctx = M.getContext();
19571d5ae102SDimitry Andric
1958344a3780SDimitry Andric auto ReaderOrErr = SampleProfileReader::create(
19597fa27ce4SDimitry Andric Filename, Ctx, *FS, FSDiscriminatorPass::Base, RemappingFilename);
1960dd58ef01SDimitry Andric if (std::error_code EC = ReaderOrErr.getError()) {
1961dd58ef01SDimitry Andric std::string Msg = "Could not open profile: " + EC.message();
1962dd58ef01SDimitry Andric Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
1963dd58ef01SDimitry Andric return false;
1964dd58ef01SDimitry Andric }
1965dd58ef01SDimitry Andric Reader = std::move(ReaderOrErr.get());
1966b60736ecSDimitry Andric Reader->setSkipFlatProf(LTOPhase == ThinOrFullLTOPhase::ThinLTOPostLink);
1967344a3780SDimitry Andric // set module before reading the profile so reader may be able to only
1968344a3780SDimitry Andric // read the function profiles which are used by the current module.
1969344a3780SDimitry Andric Reader->setModule(&M);
1970b60736ecSDimitry Andric if (std::error_code EC = Reader->read()) {
1971b60736ecSDimitry Andric std::string Msg = "profile reading failed: " + EC.message();
1972b60736ecSDimitry Andric Ctx.diagnose(DiagnosticInfoSampleProfile(Filename, Msg));
1973b60736ecSDimitry Andric return false;
1974b60736ecSDimitry Andric }
1975b60736ecSDimitry Andric
19761d5ae102SDimitry Andric PSL = Reader->getProfileSymbolList();
1977d8e91e46SDimitry Andric
19781d5ae102SDimitry Andric // While profile-sample-accurate is on, ignore symbol list.
19791d5ae102SDimitry Andric ProfAccForSymsInList =
19801d5ae102SDimitry Andric ProfileAccurateForSymsInList && PSL && !ProfileSampleAccurate;
19811d5ae102SDimitry Andric if (ProfAccForSymsInList) {
19821d5ae102SDimitry Andric NamesInProfile.clear();
1983b1c73532SDimitry Andric GUIDsInProfile.clear();
1984b1c73532SDimitry Andric if (auto NameTable = Reader->getNameTable()) {
1985b1c73532SDimitry Andric if (FunctionSamples::UseMD5) {
1986b1c73532SDimitry Andric for (auto Name : *NameTable)
1987b1c73532SDimitry Andric GUIDsInProfile.insert(Name.getHashCode());
1988b1c73532SDimitry Andric } else {
1989b1c73532SDimitry Andric for (auto Name : *NameTable)
1990b1c73532SDimitry Andric NamesInProfile.insert(Name.stringRef());
1991b1c73532SDimitry Andric }
1992b1c73532SDimitry Andric }
1993344a3780SDimitry Andric CoverageTracker.setProfAccForSymsInList(true);
1994d8e91e46SDimitry Andric }
19951d5ae102SDimitry Andric
1996b60736ecSDimitry Andric if (FAM && !ProfileInlineReplayFile.empty()) {
1997c0981da4SDimitry Andric ExternalInlineAdvisor = getReplayInlineAdvisor(
1998c0981da4SDimitry Andric M, *FAM, Ctx, /*OriginalAdvisor=*/nullptr,
1999c0981da4SDimitry Andric ReplayInlinerSettings{ProfileInlineReplayFile,
2000c0981da4SDimitry Andric ProfileInlineReplayScope,
2001c0981da4SDimitry Andric ProfileInlineReplayFallback,
2002c0981da4SDimitry Andric {ProfileInlineReplayFormat}},
2003145449b1SDimitry Andric /*EmitRemarks=*/false, InlineContext{LTOPhase, InlinePass::ReplaySampleProfileInliner});
2004b60736ecSDimitry Andric }
2005b60736ecSDimitry Andric
2006145449b1SDimitry Andric // Apply tweaks if context-sensitive or probe-based profile is available.
2007145449b1SDimitry Andric if (Reader->profileIsCS() || Reader->profileIsPreInlined() ||
2008145449b1SDimitry Andric Reader->profileIsProbeBased()) {
2009145449b1SDimitry Andric if (!UseIterativeBFIInference.getNumOccurrences())
2010145449b1SDimitry Andric UseIterativeBFIInference = true;
2011145449b1SDimitry Andric if (!SampleProfileUseProfi.getNumOccurrences())
2012145449b1SDimitry Andric SampleProfileUseProfi = true;
2013145449b1SDimitry Andric if (!EnableExtTspBlockPlacement.getNumOccurrences())
2014145449b1SDimitry Andric EnableExtTspBlockPlacement = true;
2015344a3780SDimitry Andric // Enable priority-base inliner and size inline by default for CSSPGO.
2016344a3780SDimitry Andric if (!ProfileSizeInline.getNumOccurrences())
2017344a3780SDimitry Andric ProfileSizeInline = true;
2018344a3780SDimitry Andric if (!CallsitePrioritizedInline.getNumOccurrences())
2019344a3780SDimitry Andric CallsitePrioritizedInline = true;
2020c0981da4SDimitry Andric // For CSSPGO, we also allow recursive inline to best use context profile.
2021c0981da4SDimitry Andric if (!AllowRecursiveInline.getNumOccurrences())
2022c0981da4SDimitry Andric AllowRecursiveInline = true;
2023c0981da4SDimitry Andric
2024145449b1SDimitry Andric if (Reader->profileIsPreInlined()) {
2025145449b1SDimitry Andric if (!UsePreInlinerDecision.getNumOccurrences())
2026145449b1SDimitry Andric UsePreInlinerDecision = true;
2027145449b1SDimitry Andric }
2028344a3780SDimitry Andric
20297fa27ce4SDimitry Andric // Enable stale profile matching by default for probe-based profile.
20307fa27ce4SDimitry Andric // Currently the matching relies on if the checksum mismatch is detected,
20317fa27ce4SDimitry Andric // which is currently only available for pseudo-probe mode. Removing the
20327fa27ce4SDimitry Andric // checksum check could cause regressions for some cases, so further tuning
20337fa27ce4SDimitry Andric // might be needed if we want to enable it for all cases.
20347fa27ce4SDimitry Andric if (Reader->profileIsProbeBased() &&
20357fa27ce4SDimitry Andric !SalvageStaleProfile.getNumOccurrences()) {
20367fa27ce4SDimitry Andric SalvageStaleProfile = true;
20377fa27ce4SDimitry Andric }
20387fa27ce4SDimitry Andric
2039145449b1SDimitry Andric if (!Reader->profileIsCS()) {
2040145449b1SDimitry Andric // Non-CS profile should be fine without a function size budget for the
2041145449b1SDimitry Andric // inliner since the contexts in the profile are either all from inlining
2042145449b1SDimitry Andric // in the prevoius build or pre-computed by the preinliner with a size
2043145449b1SDimitry Andric // cap, thus they are bounded.
2044145449b1SDimitry Andric if (!ProfileInlineLimitMin.getNumOccurrences())
2045145449b1SDimitry Andric ProfileInlineLimitMin = std::numeric_limits<unsigned>::max();
2046145449b1SDimitry Andric if (!ProfileInlineLimitMax.getNumOccurrences())
2047145449b1SDimitry Andric ProfileInlineLimitMax = std::numeric_limits<unsigned>::max();
2048145449b1SDimitry Andric }
2049145449b1SDimitry Andric }
2050145449b1SDimitry Andric
2051145449b1SDimitry Andric if (Reader->profileIsCS()) {
2052b60736ecSDimitry Andric // Tracker for profiles under different context
2053c0981da4SDimitry Andric ContextTracker = std::make_unique<SampleContextTracker>(
2054c0981da4SDimitry Andric Reader->getProfiles(), &GUIDToFuncNameMap);
2055b60736ecSDimitry Andric }
2056b60736ecSDimitry Andric
2057b60736ecSDimitry Andric // Load pseudo probe descriptors for probe-based function samples.
2058b60736ecSDimitry Andric if (Reader->profileIsProbeBased()) {
2059b60736ecSDimitry Andric ProbeManager = std::make_unique<PseudoProbeManager>(M);
2060b60736ecSDimitry Andric if (!ProbeManager->moduleIsProbed(M)) {
2061b60736ecSDimitry Andric const char *Msg =
2062b60736ecSDimitry Andric "Pseudo-probe-based profile requires SampleProfileProbePass";
206377fc4c14SDimitry Andric Ctx.diagnose(DiagnosticInfoSampleProfile(M.getModuleIdentifier(), Msg,
206477fc4c14SDimitry Andric DS_Warning));
2065b60736ecSDimitry Andric return false;
2066b60736ecSDimitry Andric }
2067b60736ecSDimitry Andric }
2068b60736ecSDimitry Andric
20697fa27ce4SDimitry Andric if (ReportProfileStaleness || PersistProfileStaleness ||
20707fa27ce4SDimitry Andric SalvageStaleProfile) {
2071ac9a064cSDimitry Andric MatchingManager = std::make_unique<SampleProfileMatcher>(
2072ac9a064cSDimitry Andric M, *Reader, CG, ProbeManager.get(), LTOPhase, SymbolMap, PSL,
2073ac9a064cSDimitry Andric FuncNameToProfNameMap);
2074e3b55780SDimitry Andric }
2075e3b55780SDimitry Andric
2076dd58ef01SDimitry Andric return true;
2077dd58ef01SDimitry Andric }
2078dd58ef01SDimitry Andric
2079ac9a064cSDimitry Andric // Note that this is a module-level check. Even if one module is errored out,
2080ac9a064cSDimitry Andric // the entire build will be errored out. However, the user could make big
2081ac9a064cSDimitry Andric // changes to functions in single module but those changes might not be
2082ac9a064cSDimitry Andric // performance significant to the whole binary. Therefore, to avoid those false
2083ac9a064cSDimitry Andric // positives, we select a reasonable big set of hot functions that are supposed
2084ac9a064cSDimitry Andric // to be globally performance significant, only compute and check the mismatch
2085ac9a064cSDimitry Andric // within those functions. The function selection is based on two criteria:
2086ac9a064cSDimitry Andric // 1) The function is hot enough, which is tuned by a hotness-based
2087ac9a064cSDimitry Andric // flag(HotFuncCutoffForStalenessError). 2) The num of function is large enough
2088ac9a064cSDimitry Andric // which is tuned by the MinfuncsForStalenessError flag.
rejectHighStalenessProfile(Module & M,ProfileSummaryInfo * PSI,const SampleProfileMap & Profiles)2089ac9a064cSDimitry Andric bool SampleProfileLoader::rejectHighStalenessProfile(
2090ac9a064cSDimitry Andric Module &M, ProfileSummaryInfo *PSI, const SampleProfileMap &Profiles) {
2091ac9a064cSDimitry Andric assert(FunctionSamples::ProfileIsProbeBased &&
2092ac9a064cSDimitry Andric "Only support for probe-based profile");
2093ac9a064cSDimitry Andric uint64_t TotalHotFunc = 0;
2094ac9a064cSDimitry Andric uint64_t NumMismatchedFunc = 0;
2095ac9a064cSDimitry Andric for (const auto &I : Profiles) {
2096ac9a064cSDimitry Andric const auto &FS = I.second;
2097ac9a064cSDimitry Andric const auto *FuncDesc = ProbeManager->getDesc(FS.getGUID());
2098ac9a064cSDimitry Andric if (!FuncDesc)
2099ac9a064cSDimitry Andric continue;
2100b1c73532SDimitry Andric
2101ac9a064cSDimitry Andric // Use a hotness-based threshold to control the function selection.
2102ac9a064cSDimitry Andric if (!PSI->isHotCountNthPercentile(HotFuncCutoffForStalenessError,
2103ac9a064cSDimitry Andric FS.getTotalSamples()))
2104ac9a064cSDimitry Andric continue;
2105b1c73532SDimitry Andric
2106ac9a064cSDimitry Andric TotalHotFunc++;
2107ac9a064cSDimitry Andric if (ProbeManager->profileIsHashMismatched(*FuncDesc, FS))
2108ac9a064cSDimitry Andric NumMismatchedFunc++;
2109ac9a064cSDimitry Andric }
2110ac9a064cSDimitry Andric // Make sure that the num of selected function is not too small to distinguish
2111ac9a064cSDimitry Andric // from the user's benign changes.
2112ac9a064cSDimitry Andric if (TotalHotFunc < MinfuncsForStalenessError)
2113ac9a064cSDimitry Andric return false;
2114b1c73532SDimitry Andric
2115ac9a064cSDimitry Andric // Finally check the mismatch percentage against the threshold.
2116ac9a064cSDimitry Andric if (NumMismatchedFunc * 100 >=
2117ac9a064cSDimitry Andric TotalHotFunc * PrecentMismatchForStalenessError) {
2118ac9a064cSDimitry Andric auto &Ctx = M.getContext();
2119ac9a064cSDimitry Andric const char *Msg =
2120ac9a064cSDimitry Andric "The input profile significantly mismatches current source code. "
2121ac9a064cSDimitry Andric "Please recollect profile to avoid performance regression.";
2122ac9a064cSDimitry Andric Ctx.diagnose(DiagnosticInfoSampleProfile(M.getModuleIdentifier(), Msg));
2123ac9a064cSDimitry Andric return true;
2124ac9a064cSDimitry Andric }
2125ac9a064cSDimitry Andric return false;
2126ac9a064cSDimitry Andric }
2127ac9a064cSDimitry Andric
removePseudoProbeInsts(Module & M)2128ac9a064cSDimitry Andric void SampleProfileLoader::removePseudoProbeInsts(Module &M) {
2129ac9a064cSDimitry Andric for (auto &F : M) {
2130ac9a064cSDimitry Andric std::vector<Instruction *> InstsToDel;
2131b1c73532SDimitry Andric for (auto &BB : F) {
2132b1c73532SDimitry Andric for (auto &I : BB) {
2133ac9a064cSDimitry Andric if (isa<PseudoProbeInst>(&I))
2134ac9a064cSDimitry Andric InstsToDel.push_back(&I);
2135b1c73532SDimitry Andric }
2136b1c73532SDimitry Andric }
2137ac9a064cSDimitry Andric for (auto *I : InstsToDel)
2138ac9a064cSDimitry Andric I->eraseFromParent();
21397fa27ce4SDimitry Andric }
21407fa27ce4SDimitry Andric }
21417fa27ce4SDimitry Andric
runOnModule(Module & M,ModuleAnalysisManager * AM,ProfileSummaryInfo * _PSI)2142eb11fae6SDimitry Andric bool SampleProfileLoader::runOnModule(Module &M, ModuleAnalysisManager *AM,
2143ac9a064cSDimitry Andric ProfileSummaryInfo *_PSI) {
2144cfca06d7SDimitry Andric GUIDToFuncNameMapper Mapper(M, *Reader, GUIDToFuncNameMap);
2145dd58ef01SDimitry Andric
2146eb11fae6SDimitry Andric PSI = _PSI;
2147cfca06d7SDimitry Andric if (M.getProfileSummary(/* IsCS */ false) == nullptr) {
2148e6d15924SDimitry Andric M.setProfileSummary(Reader->getSummary().getMD(M.getContext()),
2149e6d15924SDimitry Andric ProfileSummary::PSK_Sample);
2150cfca06d7SDimitry Andric PSI->refresh();
2151cfca06d7SDimitry Andric }
2152ac9a064cSDimitry Andric
2153ac9a064cSDimitry Andric if (FunctionSamples::ProfileIsProbeBased &&
2154ac9a064cSDimitry Andric rejectHighStalenessProfile(M, PSI, Reader->getProfiles()))
2155ac9a064cSDimitry Andric return false;
2156ac9a064cSDimitry Andric
2157dd58ef01SDimitry Andric // Compute the total number of samples collected in this profile.
2158dd58ef01SDimitry Andric for (const auto &I : Reader->getProfiles())
2159dd58ef01SDimitry Andric TotalCollectedSamples += I.second.getTotalSamples();
2160dd58ef01SDimitry Andric
2161b60736ecSDimitry Andric auto Remapper = Reader->getRemapper();
2162d99dafe2SDimitry Andric // Populate the symbol map.
2163d99dafe2SDimitry Andric for (const auto &N_F : M.getValueSymbolTable()) {
2164b2b7c066SDimitry Andric StringRef OrigName = N_F.getKey();
2165d99dafe2SDimitry Andric Function *F = dyn_cast<Function>(N_F.getValue());
2166344a3780SDimitry Andric if (F == nullptr || OrigName.empty())
2167d99dafe2SDimitry Andric continue;
2168b1c73532SDimitry Andric SymbolMap[FunctionId(OrigName)] = F;
2169344a3780SDimitry Andric StringRef NewName = FunctionSamples::getCanonicalFnName(*F);
2170344a3780SDimitry Andric if (OrigName != NewName && !NewName.empty()) {
2171b1c73532SDimitry Andric auto r = SymbolMap.emplace(FunctionId(NewName), F);
2172d99dafe2SDimitry Andric // Failiing to insert means there is already an entry in SymbolMap,
2173d99dafe2SDimitry Andric // thus there are multiple functions that are mapped to the same
2174d99dafe2SDimitry Andric // stripped name. In this case of name conflicting, set the value
2175d99dafe2SDimitry Andric // to nullptr to avoid confusion.
2176d99dafe2SDimitry Andric if (!r.second)
2177d99dafe2SDimitry Andric r.first->second = nullptr;
2178b60736ecSDimitry Andric OrigName = NewName;
2179b60736ecSDimitry Andric }
2180b60736ecSDimitry Andric // Insert the remapped names into SymbolMap.
2181b60736ecSDimitry Andric if (Remapper) {
2182b60736ecSDimitry Andric if (auto MapName = Remapper->lookUpNameInProfile(OrigName)) {
2183344a3780SDimitry Andric if (*MapName != OrigName && !MapName->empty())
2184b1c73532SDimitry Andric SymbolMap.emplace(FunctionId(*MapName), F);
2185b60736ecSDimitry Andric }
2186d99dafe2SDimitry Andric }
2187d99dafe2SDimitry Andric }
2188d99dafe2SDimitry Andric
2189ac9a064cSDimitry Andric // Stale profile matching.
21907fa27ce4SDimitry Andric if (ReportProfileStaleness || PersistProfileStaleness ||
21917fa27ce4SDimitry Andric SalvageStaleProfile) {
21927fa27ce4SDimitry Andric MatchingManager->runOnModule();
2193ac9a064cSDimitry Andric MatchingManager->clearMatchingData();
21947fa27ce4SDimitry Andric }
2195ac9a064cSDimitry Andric assert(SymbolMap.count(FunctionId()) == 0 &&
2196ac9a064cSDimitry Andric "No empty StringRef should be added in SymbolMap");
2197ac9a064cSDimitry Andric assert((SalvageUnusedProfile || FuncNameToProfNameMap.empty()) &&
2198ac9a064cSDimitry Andric "FuncNameToProfNameMap is not empty when --salvage-unused-profile is "
2199ac9a064cSDimitry Andric "not enabled");
2200e3b55780SDimitry Andric
2201dd58ef01SDimitry Andric bool retval = false;
2202e3b55780SDimitry Andric for (auto *F : buildFunctionOrder(M, CG)) {
2203706b4fc4SDimitry Andric assert(!F->isDeclaration());
2204dd58ef01SDimitry Andric clearFunctionData();
2205706b4fc4SDimitry Andric retval |= runOnFunction(*F, AM);
2206dd58ef01SDimitry Andric }
2207e6d15924SDimitry Andric
2208e6d15924SDimitry Andric // Account for cold calls not inlined....
2209145449b1SDimitry Andric if (!FunctionSamples::ProfileIsCS)
2210e6d15924SDimitry Andric for (const std::pair<Function *, NotInlinedProfileInfo> &pair :
2211e6d15924SDimitry Andric notInlinedCallInfo)
2212e6d15924SDimitry Andric updateProfileCallee(pair.first, pair.second.entryCount);
2213e6d15924SDimitry Andric
2214ac9a064cSDimitry Andric if (RemoveProbeAfterProfileAnnotation && FunctionSamples::ProfileIsProbeBased)
2215ac9a064cSDimitry Andric removePseudoProbeInsts(M);
2216ac9a064cSDimitry Andric
2217dd58ef01SDimitry Andric return retval;
2218dd58ef01SDimitry Andric }
2219dd58ef01SDimitry Andric
runOnFunction(Function & F,ModuleAnalysisManager * AM)2220044eb2f6SDimitry Andric bool SampleProfileLoader::runOnFunction(Function &F, ModuleAnalysisManager *AM) {
2221344a3780SDimitry Andric LLVM_DEBUG(dbgs() << "\n\nProcessing Function " << F.getName() << "\n");
2222d8e91e46SDimitry Andric DILocation2SampleMap.clear();
2223d8e91e46SDimitry Andric // By default the entry count is initialized to -1, which will be treated
2224d8e91e46SDimitry Andric // conservatively by getEntryCount as the same as unknown (None). This is
2225d8e91e46SDimitry Andric // to avoid newly added code to be treated as cold. If we have samples
2226d8e91e46SDimitry Andric // this will be overwritten in emitAnnotations.
22271d5ae102SDimitry Andric uint64_t initialEntryCount = -1;
22281d5ae102SDimitry Andric
22291d5ae102SDimitry Andric ProfAccForSymsInList = ProfileAccurateForSymsInList && PSL;
22301d5ae102SDimitry Andric if (ProfileSampleAccurate || F.hasFnAttribute("profile-sample-accurate")) {
22311d5ae102SDimitry Andric // initialize all the function entry counts to 0. It means all the
22321d5ae102SDimitry Andric // functions without profile will be regarded as cold.
22331d5ae102SDimitry Andric initialEntryCount = 0;
22341d5ae102SDimitry Andric // profile-sample-accurate is a user assertion which has a higher precedence
22351d5ae102SDimitry Andric // than symbol list. When profile-sample-accurate is on, ignore symbol list.
22361d5ae102SDimitry Andric ProfAccForSymsInList = false;
22371d5ae102SDimitry Andric }
2238344a3780SDimitry Andric CoverageTracker.setProfAccForSymsInList(ProfAccForSymsInList);
22391d5ae102SDimitry Andric
22401d5ae102SDimitry Andric // PSL -- profile symbol list include all the symbols in sampled binary.
22411d5ae102SDimitry Andric // If ProfileAccurateForSymsInList is enabled, PSL is used to treat
22421d5ae102SDimitry Andric // old functions without samples being cold, without having to worry
22431d5ae102SDimitry Andric // about new and hot functions being mistakenly treated as cold.
22441d5ae102SDimitry Andric if (ProfAccForSymsInList) {
22451d5ae102SDimitry Andric // Initialize the entry count to 0 for functions in the list.
22461d5ae102SDimitry Andric if (PSL->contains(F.getName()))
22471d5ae102SDimitry Andric initialEntryCount = 0;
22481d5ae102SDimitry Andric
22491d5ae102SDimitry Andric // Function in the symbol list but without sample will be regarded as
22501d5ae102SDimitry Andric // cold. To minimize the potential negative performance impact it could
22511d5ae102SDimitry Andric // have, we want to be a little conservative here saying if a function
22521d5ae102SDimitry Andric // shows up in the profile, no matter as outline function, inline instance
22531d5ae102SDimitry Andric // or call targets, treat the function as not being cold. This will handle
22541d5ae102SDimitry Andric // the cases such as most callsites of a function are inlined in sampled
22551d5ae102SDimitry Andric // binary but not inlined in current build (because of source code drift,
22561d5ae102SDimitry Andric // imprecise debug information, or the callsites are all cold individually
22571d5ae102SDimitry Andric // but not cold accumulatively...), so the outline function showing up as
22581d5ae102SDimitry Andric // cold in sampled binary will actually not be cold after current build.
22591d5ae102SDimitry Andric StringRef CanonName = FunctionSamples::getCanonicalFnName(F);
2260b1c73532SDimitry Andric if ((FunctionSamples::UseMD5 &&
2261b1c73532SDimitry Andric GUIDsInProfile.count(Function::getGUID(CanonName))) ||
2262b1c73532SDimitry Andric (!FunctionSamples::UseMD5 && NamesInProfile.count(CanonName)))
22631d5ae102SDimitry Andric initialEntryCount = -1;
22641d5ae102SDimitry Andric }
22651d5ae102SDimitry Andric
2266b60736ecSDimitry Andric // Initialize entry count when the function has no existing entry
2267b60736ecSDimitry Andric // count value.
2268145449b1SDimitry Andric if (!F.getEntryCount())
2269d8e91e46SDimitry Andric F.setEntryCount(ProfileCount(initialEntryCount, Function::PCT_Real));
2270044eb2f6SDimitry Andric std::unique_ptr<OptimizationRemarkEmitter> OwnedORE;
2271044eb2f6SDimitry Andric if (AM) {
2272044eb2f6SDimitry Andric auto &FAM =
2273044eb2f6SDimitry Andric AM->getResult<FunctionAnalysisManagerModuleProxy>(*F.getParent())
2274044eb2f6SDimitry Andric .getManager();
2275044eb2f6SDimitry Andric ORE = &FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
2276044eb2f6SDimitry Andric } else {
22771d5ae102SDimitry Andric OwnedORE = std::make_unique<OptimizationRemarkEmitter>(&F);
2278044eb2f6SDimitry Andric ORE = OwnedORE.get();
2279044eb2f6SDimitry Andric }
2280b60736ecSDimitry Andric
2281145449b1SDimitry Andric if (FunctionSamples::ProfileIsCS)
2282b60736ecSDimitry Andric Samples = ContextTracker->getBaseSamplesFor(F);
2283b1c73532SDimitry Andric else {
2284dd58ef01SDimitry Andric Samples = Reader->getSamplesFor(F);
2285b1c73532SDimitry Andric // Try search in previously inlined functions that were split or duplicated
2286b1c73532SDimitry Andric // into base.
2287b1c73532SDimitry Andric if (!Samples) {
2288b1c73532SDimitry Andric StringRef CanonName = FunctionSamples::getCanonicalFnName(F);
2289b1c73532SDimitry Andric auto It = OutlineFunctionSamples.find(FunctionId(CanonName));
2290b1c73532SDimitry Andric if (It != OutlineFunctionSamples.end()) {
2291b1c73532SDimitry Andric Samples = &It->second;
2292b1c73532SDimitry Andric } else if (auto Remapper = Reader->getRemapper()) {
2293b1c73532SDimitry Andric if (auto RemppedName = Remapper->lookUpNameInProfile(CanonName)) {
2294b1c73532SDimitry Andric It = OutlineFunctionSamples.find(FunctionId(*RemppedName));
2295b1c73532SDimitry Andric if (It != OutlineFunctionSamples.end())
2296b1c73532SDimitry Andric Samples = &It->second;
2297b1c73532SDimitry Andric }
2298b1c73532SDimitry Andric }
2299b1c73532SDimitry Andric }
2300b1c73532SDimitry Andric }
2301b60736ecSDimitry Andric
230271d5a254SDimitry Andric if (Samples && !Samples->empty())
2303dd58ef01SDimitry Andric return emitAnnotations(F);
2304dd58ef01SDimitry Andric return false;
2305dd58ef01SDimitry Andric }
SampleProfileLoaderPass(std::string File,std::string RemappingFile,ThinOrFullLTOPhase LTOPhase,IntrusiveRefCntPtr<vfs::FileSystem> FS)23067fa27ce4SDimitry Andric SampleProfileLoaderPass::SampleProfileLoaderPass(
23077fa27ce4SDimitry Andric std::string File, std::string RemappingFile, ThinOrFullLTOPhase LTOPhase,
23087fa27ce4SDimitry Andric IntrusiveRefCntPtr<vfs::FileSystem> FS)
23097fa27ce4SDimitry Andric : ProfileFileName(File), ProfileRemappingFileName(RemappingFile),
23107fa27ce4SDimitry Andric LTOPhase(LTOPhase), FS(std::move(FS)) {}
231101095a5dSDimitry Andric
run(Module & M,ModuleAnalysisManager & AM)231201095a5dSDimitry Andric PreservedAnalyses SampleProfileLoaderPass::run(Module &M,
2313b915e9e0SDimitry Andric ModuleAnalysisManager &AM) {
2314044eb2f6SDimitry Andric FunctionAnalysisManager &FAM =
2315044eb2f6SDimitry Andric AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
2316044eb2f6SDimitry Andric
2317044eb2f6SDimitry Andric auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & {
2318044eb2f6SDimitry Andric return FAM.getResult<AssumptionAnalysis>(F);
2319044eb2f6SDimitry Andric };
2320044eb2f6SDimitry Andric auto GetTTI = [&](Function &F) -> TargetTransformInfo & {
2321044eb2f6SDimitry Andric return FAM.getResult<TargetIRAnalysis>(F);
2322044eb2f6SDimitry Andric };
2323cfca06d7SDimitry Andric auto GetTLI = [&](Function &F) -> const TargetLibraryInfo & {
2324cfca06d7SDimitry Andric return FAM.getResult<TargetLibraryAnalysis>(F);
2325cfca06d7SDimitry Andric };
232601095a5dSDimitry Andric
23277fa27ce4SDimitry Andric if (!FS)
23287fa27ce4SDimitry Andric FS = vfs::getRealFileSystem();
2329ac9a064cSDimitry Andric LazyCallGraph &CG = AM.getResult<LazyCallGraphAnalysis>(M);
23307fa27ce4SDimitry Andric
23319df3605dSDimitry Andric SampleProfileLoader SampleLoader(
2332044eb2f6SDimitry Andric ProfileFileName.empty() ? SampleProfileFile : ProfileFileName,
2333d8e91e46SDimitry Andric ProfileRemappingFileName.empty() ? SampleProfileRemappingFile
2334d8e91e46SDimitry Andric : ProfileRemappingFileName,
2335ac9a064cSDimitry Andric LTOPhase, FS, GetAssumptionCache, GetTTI, GetTLI, CG);
2336b60736ecSDimitry Andric if (!SampleLoader.doInitialization(M, &FAM))
2337706b4fc4SDimitry Andric return PreservedAnalyses::all();
233801095a5dSDimitry Andric
2339eb11fae6SDimitry Andric ProfileSummaryInfo *PSI = &AM.getResult<ProfileSummaryAnalysis>(M);
2340ac9a064cSDimitry Andric if (!SampleLoader.runOnModule(M, &AM, PSI))
234101095a5dSDimitry Andric return PreservedAnalyses::all();
234201095a5dSDimitry Andric
234301095a5dSDimitry Andric return PreservedAnalyses::none();
234401095a5dSDimitry Andric }
2345