1 //===- bolt/Passes/IndirectCallPromotion.cpp ------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the IndirectCallPromotion class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "bolt/Passes/IndirectCallPromotion.h"
14 #include "bolt/Passes/BinaryFunctionCallGraph.h"
15 #include "bolt/Passes/DataflowInfoManager.h"
16 #include "llvm/Support/CommandLine.h"
17 
18 #define DEBUG_TYPE "ICP"
19 #define DEBUG_VERBOSE(Level, X)                                                \
20   if (opts::Verbosity >= (Level)) {                                            \
21     X;                                                                         \
22   }
23 
24 using namespace llvm;
25 using namespace bolt;
26 
27 namespace opts {
28 
29 extern cl::OptionCategory BoltOptCategory;
30 
31 extern cl::opt<IndirectCallPromotionType> ICP;
32 extern cl::opt<unsigned> Verbosity;
33 extern cl::opt<unsigned> ExecutionCountThreshold;
34 
35 static cl::opt<unsigned> ICPJTRemainingPercentThreshold(
36     "icp-jt-remaining-percent-threshold",
37     cl::desc("The percentage threshold against remaining unpromoted indirect "
38              "call count for the promotion for jump tables"),
39     cl::init(30), cl::ZeroOrMore, cl::Hidden, cl::cat(BoltOptCategory));
40 
41 static cl::opt<unsigned> ICPJTTotalPercentThreshold(
42     "icp-jt-total-percent-threshold",
43     cl::desc(
44         "The percentage threshold against total count for the promotion for "
45         "jump tables"),
46     cl::init(5), cl::ZeroOrMore, cl::Hidden, cl::cat(BoltOptCategory));
47 
48 static cl::opt<unsigned> ICPCallsRemainingPercentThreshold(
49     "icp-calls-remaining-percent-threshold",
50     cl::desc("The percentage threshold against remaining unpromoted indirect "
51              "call count for the promotion for calls"),
52     cl::init(50), cl::ZeroOrMore, cl::Hidden, cl::cat(BoltOptCategory));
53 
54 static cl::opt<unsigned> ICPCallsTotalPercentThreshold(
55     "icp-calls-total-percent-threshold",
56     cl::desc(
57         "The percentage threshold against total count for the promotion for "
58         "calls"),
59     cl::init(30), cl::ZeroOrMore, cl::Hidden, cl::cat(BoltOptCategory));
60 
61 static cl::opt<unsigned> ICPMispredictThreshold(
62     "indirect-call-promotion-mispredict-threshold",
63     cl::desc("misprediction threshold for skipping ICP on an "
64              "indirect call"),
65     cl::init(0), cl::ZeroOrMore, cl::cat(BoltOptCategory));
66 
67 static cl::opt<bool> ICPUseMispredicts(
68     "indirect-call-promotion-use-mispredicts",
69     cl::desc("use misprediction frequency for determining whether or not ICP "
70              "should be applied at a callsite.  The "
71              "-indirect-call-promotion-mispredict-threshold value will be used "
72              "by this heuristic"),
73     cl::ZeroOrMore, cl::cat(BoltOptCategory));
74 
75 static cl::opt<unsigned>
76     ICPTopN("indirect-call-promotion-topn",
77             cl::desc("limit number of targets to consider when doing indirect "
78                      "call promotion. 0 = no limit"),
79             cl::init(3), cl::ZeroOrMore, cl::cat(BoltOptCategory));
80 
81 static cl::opt<unsigned> ICPCallsTopN(
82     "indirect-call-promotion-calls-topn",
83     cl::desc("limit number of targets to consider when doing indirect "
84              "call promotion on calls. 0 = no limit"),
85     cl::init(0), cl::ZeroOrMore, cl::cat(BoltOptCategory));
86 
87 static cl::opt<unsigned> ICPJumpTablesTopN(
88     "indirect-call-promotion-jump-tables-topn",
89     cl::desc("limit number of targets to consider when doing indirect "
90              "call promotion on jump tables. 0 = no limit"),
91     cl::init(0), cl::ZeroOrMore, cl::cat(BoltOptCategory));
92 
93 static cl::opt<bool> EliminateLoads(
94     "icp-eliminate-loads",
95     cl::desc("enable load elimination using memory profiling data when "
96              "performing ICP"),
97     cl::init(true), cl::ZeroOrMore, cl::cat(BoltOptCategory));
98 
99 static cl::opt<unsigned> ICPTopCallsites(
100     "icp-top-callsites",
101     cl::desc("optimize hottest calls until at least this percentage of all "
102              "indirect calls frequency is covered. 0 = all callsites"),
103     cl::init(99), cl::Hidden, cl::ZeroOrMore, cl::cat(BoltOptCategory));
104 
105 static cl::list<std::string>
106     ICPFuncsList("icp-funcs", cl::CommaSeparated,
107                  cl::desc("list of functions to enable ICP for"),
108                  cl::value_desc("func1,func2,func3,..."), cl::Hidden,
109                  cl::cat(BoltOptCategory));
110 
111 static cl::opt<bool>
112     ICPOldCodeSequence("icp-old-code-sequence",
113                        cl::desc("use old code sequence for promoted calls"),
114                        cl::init(false), cl::ZeroOrMore, cl::Hidden,
115                        cl::cat(BoltOptCategory));
116 
117 static cl::opt<bool> ICPJumpTablesByTarget(
118     "icp-jump-tables-targets",
119     cl::desc(
120         "for jump tables, optimize indirect jmp targets instead of indices"),
121     cl::init(false), cl::ZeroOrMore, cl::Hidden, cl::cat(BoltOptCategory));
122 
123 } // namespace opts
124 
125 namespace llvm {
126 namespace bolt {
127 
128 namespace {
129 
130 bool verifyProfile(std::map<uint64_t, BinaryFunction> &BFs) {
131   bool IsValid = true;
132   for (auto &BFI : BFs) {
133     BinaryFunction &BF = BFI.second;
134     if (!BF.isSimple())
135       continue;
136     for (BinaryBasicBlock *BB : BF.layout()) {
137       auto BI = BB->branch_info_begin();
138       for (BinaryBasicBlock *SuccBB : BB->successors()) {
139         if (BI->Count != BinaryBasicBlock::COUNT_NO_PROFILE && BI->Count > 0) {
140           if (BB->getKnownExecutionCount() == 0 ||
141               SuccBB->getKnownExecutionCount() == 0) {
142             errs() << "BOLT-WARNING: profile verification failed after ICP for "
143                       "function "
144                    << BF << '\n';
145             IsValid = false;
146           }
147         }
148         ++BI;
149       }
150     }
151   }
152   return IsValid;
153 }
154 
155 } // namespace
156 
157 IndirectCallPromotion::Callsite::Callsite(BinaryFunction &BF,
158                                           const IndirectCallProfile &ICP)
159     : From(BF.getSymbol()), To(ICP.Offset), Mispreds(ICP.Mispreds),
160       Branches(ICP.Count) {
161   if (ICP.Symbol) {
162     To.Sym = ICP.Symbol;
163     To.Addr = 0;
164   }
165 }
166 
167 void IndirectCallPromotion::printDecision(
168     llvm::raw_ostream &OS,
169     std::vector<IndirectCallPromotion::Callsite> &Targets, unsigned N) const {
170   uint64_t TotalCount = 0;
171   uint64_t TotalMispreds = 0;
172   for (const Callsite &S : Targets) {
173     TotalCount += S.Branches;
174     TotalMispreds += S.Mispreds;
175   }
176   if (!TotalCount)
177     TotalCount = 1;
178   if (!TotalMispreds)
179     TotalMispreds = 1;
180 
181   OS << "BOLT-INFO: ICP decision for call site with " << Targets.size()
182      << " targets, Count = " << TotalCount << ", Mispreds = " << TotalMispreds
183      << "\n";
184 
185   size_t I = 0;
186   for (const Callsite &S : Targets) {
187     OS << "Count = " << S.Branches << ", "
188        << format("%.1f", (100.0 * S.Branches) / TotalCount) << ", "
189        << "Mispreds = " << S.Mispreds << ", "
190        << format("%.1f", (100.0 * S.Mispreds) / TotalMispreds);
191     if (I < N)
192       OS << " * to be optimized *";
193     if (!S.JTIndices.empty()) {
194       OS << " Indices:";
195       for (const uint64_t Idx : S.JTIndices)
196         OS << " " << Idx;
197     }
198     OS << "\n";
199     I += S.JTIndices.empty() ? 1 : S.JTIndices.size();
200   }
201 }
202 
203 // Get list of targets for a given call sorted by most frequently
204 // called first.
205 std::vector<IndirectCallPromotion::Callsite>
206 IndirectCallPromotion::getCallTargets(BinaryBasicBlock &BB,
207                                       const MCInst &Inst) const {
208   BinaryFunction &BF = *BB.getFunction();
209   BinaryContext &BC = BF.getBinaryContext();
210   std::vector<Callsite> Targets;
211 
212   if (const JumpTable *JT = BF.getJumpTable(Inst)) {
213     // Don't support PIC jump tables for now
214     if (!opts::ICPJumpTablesByTarget && JT->Type == JumpTable::JTT_PIC)
215       return Targets;
216     const Location From(BF.getSymbol());
217     const std::pair<size_t, size_t> Range =
218         JT->getEntriesForAddress(BC.MIB->getJumpTable(Inst));
219     assert(JT->Counts.empty() || JT->Counts.size() >= Range.second);
220     JumpTable::JumpInfo DefaultJI;
221     const JumpTable::JumpInfo *JI =
222         JT->Counts.empty() ? &DefaultJI : &JT->Counts[Range.first];
223     const size_t JIAdj = JT->Counts.empty() ? 0 : 1;
224     assert(JT->Type == JumpTable::JTT_PIC ||
225            JT->EntrySize == BC.AsmInfo->getCodePointerSize());
226     for (size_t I = Range.first; I < Range.second; ++I, JI += JIAdj) {
227       MCSymbol *Entry = JT->Entries[I];
228       assert(BF.getBasicBlockForLabel(Entry) ||
229              Entry == BF.getFunctionEndLabel() ||
230              Entry == BF.getFunctionColdEndLabel());
231       if (Entry == BF.getFunctionEndLabel() ||
232           Entry == BF.getFunctionColdEndLabel())
233         continue;
234       const Location To(Entry);
235       const BinaryBasicBlock::BinaryBranchInfo &BI = BB.getBranchInfo(Entry);
236       Targets.emplace_back(From, To, BI.MispredictedCount, BI.Count,
237                            I - Range.first);
238     }
239 
240     // Sort by symbol then addr.
241     std::sort(Targets.begin(), Targets.end(),
242               [](const Callsite &A, const Callsite &B) {
243                 if (A.To.Sym && B.To.Sym)
244                   return A.To.Sym < B.To.Sym;
245                 else if (A.To.Sym && !B.To.Sym)
246                   return true;
247                 else if (!A.To.Sym && B.To.Sym)
248                   return false;
249                 else
250                   return A.To.Addr < B.To.Addr;
251               });
252 
253     // Targets may contain multiple entries to the same target, but using
254     // different indices. Their profile will report the same number of branches
255     // for different indices if the target is the same. That's because we don't
256     // profile the index value, but only the target via LBR.
257     auto First = Targets.begin();
258     auto Last = Targets.end();
259     auto Result = First;
260     while (++First != Last) {
261       Callsite &A = *Result;
262       const Callsite &B = *First;
263       if (A.To.Sym && B.To.Sym && A.To.Sym == B.To.Sym)
264         A.JTIndices.insert(A.JTIndices.end(), B.JTIndices.begin(),
265                            B.JTIndices.end());
266       else
267         *(++Result) = *First;
268     }
269     ++Result;
270 
271     LLVM_DEBUG(if (Targets.end() - Result > 0) {
272       dbgs() << "BOLT-INFO: ICP: " << (Targets.end() - Result)
273              << " duplicate targets removed\n";
274     });
275 
276     Targets.erase(Result, Targets.end());
277   } else {
278     // Don't try to optimize PC relative indirect calls.
279     if (Inst.getOperand(0).isReg() &&
280         Inst.getOperand(0).getReg() == BC.MRI->getProgramCounter())
281       return Targets;
282 
283     const auto ICSP = BC.MIB->tryGetAnnotationAs<IndirectCallSiteProfile>(
284         Inst, "CallProfile");
285     if (ICSP) {
286       for (const IndirectCallProfile &CSP : ICSP.get()) {
287         Callsite Site(BF, CSP);
288         if (Site.isValid())
289           Targets.emplace_back(std::move(Site));
290       }
291     }
292   }
293 
294   // Sort by target count, number of indices in case of jump table, and
295   // mispredicts. We prioritize targets with high count, small number of indices
296   // and high mispredicts. Break ties by selecting targets with lower addresses.
297   std::stable_sort(Targets.begin(), Targets.end(),
298                    [](const Callsite &A, const Callsite &B) {
299                      if (A.Branches != B.Branches)
300                        return A.Branches > B.Branches;
301                      if (A.JTIndices.size() != B.JTIndices.size())
302                        return A.JTIndices.size() < B.JTIndices.size();
303                      if (A.Mispreds != B.Mispreds)
304                        return A.Mispreds > B.Mispreds;
305                      return A.To.Addr < B.To.Addr;
306                    });
307 
308   // Remove non-symbol targets
309   auto Last = std::remove_if(Targets.begin(), Targets.end(),
310                              [](const Callsite &CS) { return !CS.To.Sym; });
311   Targets.erase(Last, Targets.end());
312 
313   LLVM_DEBUG(if (BF.getJumpTable(Inst)) {
314     uint64_t TotalCount = 0;
315     uint64_t TotalMispreds = 0;
316     for (const Callsite &S : Targets) {
317       TotalCount += S.Branches;
318       TotalMispreds += S.Mispreds;
319     }
320     if (!TotalCount)
321       TotalCount = 1;
322     if (!TotalMispreds)
323       TotalMispreds = 1;
324 
325     dbgs() << "BOLT-INFO: ICP: jump table size = " << Targets.size()
326            << ", Count = " << TotalCount << ", Mispreds = " << TotalMispreds
327            << "\n";
328 
329     size_t I = 0;
330     for (const Callsite &S : Targets) {
331       dbgs() << "Count[" << I << "] = " << S.Branches << ", "
332              << format("%.1f", (100.0 * S.Branches) / TotalCount) << ", "
333              << "Mispreds[" << I << "] = " << S.Mispreds << ", "
334              << format("%.1f", (100.0 * S.Mispreds) / TotalMispreds) << "\n";
335       ++I;
336     }
337   });
338 
339   return Targets;
340 }
341 
342 IndirectCallPromotion::JumpTableInfoType
343 IndirectCallPromotion::maybeGetHotJumpTableTargets(BinaryBasicBlock &BB,
344                                                    MCInst &CallInst,
345                                                    MCInst *&TargetFetchInst,
346                                                    const JumpTable *JT) const {
347   assert(JT && "Can't get jump table addrs for non-jump tables.");
348 
349   BinaryFunction &Function = *BB.getFunction();
350   BinaryContext &BC = Function.getBinaryContext();
351 
352   if (!Function.hasMemoryProfile() || !opts::EliminateLoads)
353     return JumpTableInfoType();
354 
355   JumpTableInfoType HotTargets;
356   MCInst *MemLocInstr;
357   MCInst *PCRelBaseOut;
358   unsigned BaseReg, IndexReg;
359   int64_t DispValue;
360   const MCExpr *DispExpr;
361   MutableArrayRef<MCInst> Insts(&BB.front(), &CallInst);
362   const IndirectBranchType Type = BC.MIB->analyzeIndirectBranch(
363       CallInst, Insts.begin(), Insts.end(), BC.AsmInfo->getCodePointerSize(),
364       MemLocInstr, BaseReg, IndexReg, DispValue, DispExpr, PCRelBaseOut);
365 
366   assert(MemLocInstr && "There should always be a load for jump tables");
367   if (!MemLocInstr)
368     return JumpTableInfoType();
369 
370   LLVM_DEBUG({
371     dbgs() << "BOLT-INFO: ICP attempting to find memory profiling data for "
372            << "jump table in " << Function << " at @ "
373            << (&CallInst - &BB.front()) << "\n"
374            << "BOLT-INFO: ICP target fetch instructions:\n";
375     BC.printInstruction(dbgs(), *MemLocInstr, 0, &Function);
376     if (MemLocInstr != &CallInst)
377       BC.printInstruction(dbgs(), CallInst, 0, &Function);
378   });
379 
380   DEBUG_VERBOSE(1, {
381     dbgs() << "Jmp info: Type = " << (unsigned)Type << ", "
382            << "BaseReg = " << BC.MRI->getName(BaseReg) << ", "
383            << "IndexReg = " << BC.MRI->getName(IndexReg) << ", "
384            << "DispValue = " << Twine::utohexstr(DispValue) << ", "
385            << "DispExpr = " << DispExpr << ", "
386            << "MemLocInstr = ";
387     BC.printInstruction(dbgs(), *MemLocInstr, 0, &Function);
388     dbgs() << "\n";
389   });
390 
391   ++TotalIndexBasedCandidates;
392 
393   auto ErrorOrMemAccesssProfile =
394       BC.MIB->tryGetAnnotationAs<MemoryAccessProfile>(*MemLocInstr,
395                                                       "MemoryAccessProfile");
396   if (!ErrorOrMemAccesssProfile) {
397     DEBUG_VERBOSE(1, dbgs()
398                          << "BOLT-INFO: ICP no memory profiling data found\n");
399     return JumpTableInfoType();
400   }
401   MemoryAccessProfile &MemAccessProfile = ErrorOrMemAccesssProfile.get();
402 
403   uint64_t ArrayStart;
404   if (DispExpr) {
405     ErrorOr<uint64_t> DispValueOrError =
406         BC.getSymbolValue(*BC.MIB->getTargetSymbol(DispExpr));
407     assert(DispValueOrError && "global symbol needs a value");
408     ArrayStart = *DispValueOrError;
409   } else {
410     ArrayStart = static_cast<uint64_t>(DispValue);
411   }
412 
413   if (BaseReg == BC.MRI->getProgramCounter())
414     ArrayStart += Function.getAddress() + MemAccessProfile.NextInstrOffset;
415 
416   // This is a map of [symbol] -> [count, index] and is used to combine indices
417   // into the jump table since there may be multiple addresses that all have the
418   // same entry.
419   std::map<MCSymbol *, std::pair<uint64_t, uint64_t>> HotTargetMap;
420   const std::pair<size_t, size_t> Range = JT->getEntriesForAddress(ArrayStart);
421 
422   for (const AddressAccess &AccessInfo : MemAccessProfile.AddressAccessInfo) {
423     size_t Index;
424     // Mem data occasionally includes nullprs, ignore them.
425     if (!AccessInfo.MemoryObject && !AccessInfo.Offset)
426       continue;
427 
428     if (AccessInfo.Offset % JT->EntrySize != 0) // ignore bogus data
429       return JumpTableInfoType();
430 
431     if (AccessInfo.MemoryObject) {
432       // Deal with bad/stale data
433       if (!AccessInfo.MemoryObject->getName().startswith(
434               "JUMP_TABLE/" + Function.getOneName().str()))
435         return JumpTableInfoType();
436       Index =
437           (AccessInfo.Offset - (ArrayStart - JT->getAddress())) / JT->EntrySize;
438     } else {
439       Index = (AccessInfo.Offset - ArrayStart) / JT->EntrySize;
440     }
441 
442     // If Index is out of range it probably means the memory profiling data is
443     // wrong for this instruction, bail out.
444     if (Index >= Range.second) {
445       LLVM_DEBUG(dbgs() << "BOLT-INFO: Index out of range of " << Range.first
446                         << ", " << Range.second << "\n");
447       return JumpTableInfoType();
448     }
449 
450     // Make sure the hot index points at a legal label corresponding to a BB,
451     // e.g. not the end of function (unreachable) label.
452     if (!Function.getBasicBlockForLabel(JT->Entries[Index + Range.first])) {
453       LLVM_DEBUG({
454         dbgs() << "BOLT-INFO: hot index " << Index << " pointing at bogus "
455                << "label " << JT->Entries[Index + Range.first]->getName()
456                << " in jump table:\n";
457         JT->print(dbgs());
458         dbgs() << "HotTargetMap:\n";
459         for (std::pair<MCSymbol *const, std::pair<uint64_t, uint64_t>> &HT :
460              HotTargetMap)
461           dbgs() << "BOLT-INFO: " << HT.first->getName()
462                  << " = (count=" << HT.second.first
463                  << ", index=" << HT.second.second << ")\n";
464       });
465       return JumpTableInfoType();
466     }
467 
468     std::pair<uint64_t, uint64_t> &HotTarget =
469         HotTargetMap[JT->Entries[Index + Range.first]];
470     HotTarget.first += AccessInfo.Count;
471     HotTarget.second = Index;
472   }
473 
474   std::transform(
475       HotTargetMap.begin(), HotTargetMap.end(), std::back_inserter(HotTargets),
476       [](const std::pair<MCSymbol *, std::pair<uint64_t, uint64_t>> &A) {
477         return A.second;
478       });
479 
480   // Sort with highest counts first.
481   std::sort(HotTargets.rbegin(), HotTargets.rend());
482 
483   LLVM_DEBUG({
484     dbgs() << "BOLT-INFO: ICP jump table hot targets:\n";
485     for (const std::pair<uint64_t, uint64_t> &Target : HotTargets)
486       dbgs() << "BOLT-INFO:  Idx = " << Target.second << ", "
487              << "Count = " << Target.first << "\n";
488   });
489 
490   BC.MIB->getOrCreateAnnotationAs<uint16_t>(CallInst, "JTIndexReg") = IndexReg;
491 
492   TargetFetchInst = MemLocInstr;
493 
494   return HotTargets;
495 }
496 
497 IndirectCallPromotion::SymTargetsType
498 IndirectCallPromotion::findCallTargetSymbols(std::vector<Callsite> &Targets,
499                                              size_t &N, BinaryBasicBlock &BB,
500                                              MCInst &CallInst,
501                                              MCInst *&TargetFetchInst) const {
502   const JumpTable *JT = BB.getFunction()->getJumpTable(CallInst);
503   SymTargetsType SymTargets;
504 
505   if (!JT) {
506     for (size_t I = 0; I < N; ++I) {
507       assert(Targets[I].To.Sym && "All ICP targets must be to known symbols");
508       assert(Targets[I].JTIndices.empty() &&
509              "Can't have jump table indices for non-jump tables");
510       SymTargets.emplace_back(Targets[I].To.Sym, 0);
511     }
512     return SymTargets;
513   }
514 
515   JumpTableInfoType HotTargets =
516       maybeGetHotJumpTableTargets(BB, CallInst, TargetFetchInst, JT);
517 
518   auto findTargetsIndex = [&](uint64_t JTIndex) {
519     for (size_t I = 0; I < Targets.size(); ++I)
520       if (llvm::is_contained(Targets[I].JTIndices, JTIndex))
521         return I;
522     LLVM_DEBUG(dbgs() << "BOLT-ERROR: Unable to find target index for hot jump "
523                       << " table entry in " << *BB.getFunction() << "\n");
524     llvm_unreachable("Hot indices must be referred to by at least one "
525                      "callsite");
526   };
527 
528   if (!HotTargets.empty()) {
529     if (opts::Verbosity >= 1)
530       for (size_t I = 0; I < HotTargets.size(); ++I)
531         outs() << "BOLT-INFO: HotTarget[" << I << "] = (" << HotTargets[I].first
532                << ", " << HotTargets[I].second << ")\n";
533 
534     // Recompute hottest targets, now discriminating which index is hot
535     // NOTE: This is a tradeoff. On one hand, we get index information. On the
536     // other hand, info coming from the memory profile is much less accurate
537     // than LBRs. So we may actually end up working with more coarse
538     // profile granularity in exchange for information about indices.
539     std::vector<Callsite> NewTargets;
540     std::map<const MCSymbol *, uint32_t> IndicesPerTarget;
541     uint64_t TotalMemAccesses = 0;
542     for (size_t I = 0; I < HotTargets.size(); ++I) {
543       const uint64_t TargetIndex = findTargetsIndex(HotTargets[I].second);
544       ++IndicesPerTarget[Targets[TargetIndex].To.Sym];
545       TotalMemAccesses += HotTargets[I].first;
546     }
547     uint64_t RemainingMemAccesses = TotalMemAccesses;
548     const size_t TopN =
549         opts::ICPJumpTablesTopN ? opts::ICPJumpTablesTopN : opts::ICPTopN;
550     size_t I = 0;
551     for (; I < HotTargets.size(); ++I) {
552       const uint64_t MemAccesses = HotTargets[I].first;
553       if (100 * MemAccesses <
554           TotalMemAccesses * opts::ICPJTTotalPercentThreshold)
555         break;
556       if (100 * MemAccesses <
557           RemainingMemAccesses * opts::ICPJTRemainingPercentThreshold)
558         break;
559       if (TopN && I >= TopN)
560         break;
561       RemainingMemAccesses -= MemAccesses;
562 
563       const uint64_t JTIndex = HotTargets[I].second;
564       Callsite &Target = Targets[findTargetsIndex(JTIndex)];
565 
566       NewTargets.push_back(Target);
567       std::vector<uint64_t>({JTIndex}).swap(NewTargets.back().JTIndices);
568       Target.JTIndices.erase(std::remove(Target.JTIndices.begin(),
569                                          Target.JTIndices.end(), JTIndex),
570                              Target.JTIndices.end());
571 
572       // Keep fixCFG counts sane if more indices use this same target later
573       assert(IndicesPerTarget[Target.To.Sym] > 0 && "wrong map");
574       NewTargets.back().Branches =
575           Target.Branches / IndicesPerTarget[Target.To.Sym];
576       NewTargets.back().Mispreds =
577           Target.Mispreds / IndicesPerTarget[Target.To.Sym];
578       assert(Target.Branches >= NewTargets.back().Branches);
579       assert(Target.Mispreds >= NewTargets.back().Mispreds);
580       Target.Branches -= NewTargets.back().Branches;
581       Target.Mispreds -= NewTargets.back().Mispreds;
582     }
583     std::copy(Targets.begin(), Targets.end(), std::back_inserter(NewTargets));
584     std::swap(NewTargets, Targets);
585     N = I;
586 
587     if (N == 0 && opts::Verbosity >= 1) {
588       outs() << "BOLT-INFO: ICP failed in " << *BB.getFunction() << " in "
589              << BB.getName() << ": failed to meet thresholds after memory "
590              << "profile data was loaded.\n";
591       return SymTargets;
592     }
593   }
594 
595   for (size_t I = 0, TgtIdx = 0; I < N; ++TgtIdx) {
596     Callsite &Target = Targets[TgtIdx];
597     assert(Target.To.Sym && "All ICP targets must be to known symbols");
598     assert(!Target.JTIndices.empty() && "Jump tables must have indices");
599     for (uint64_t Idx : Target.JTIndices) {
600       SymTargets.emplace_back(Target.To.Sym, Idx);
601       ++I;
602     }
603   }
604 
605   return SymTargets;
606 }
607 
608 IndirectCallPromotion::MethodInfoType IndirectCallPromotion::maybeGetVtableSyms(
609     BinaryBasicBlock &BB, MCInst &Inst,
610     const SymTargetsType &SymTargets) const {
611   BinaryFunction &Function = *BB.getFunction();
612   BinaryContext &BC = Function.getBinaryContext();
613   std::vector<std::pair<MCSymbol *, uint64_t>> VtableSyms;
614   std::vector<MCInst *> MethodFetchInsns;
615   unsigned VtableReg, MethodReg;
616   uint64_t MethodOffset;
617 
618   assert(!Function.getJumpTable(Inst) &&
619          "Can't get vtable addrs for jump tables.");
620 
621   if (!Function.hasMemoryProfile() || !opts::EliminateLoads)
622     return MethodInfoType();
623 
624   MutableArrayRef<MCInst> Insts(&BB.front(), &Inst + 1);
625   if (!BC.MIB->analyzeVirtualMethodCall(Insts.begin(), Insts.end(),
626                                         MethodFetchInsns, VtableReg, MethodReg,
627                                         MethodOffset)) {
628     DEBUG_VERBOSE(
629         1, dbgs() << "BOLT-INFO: ICP unable to analyze method call in "
630                   << Function << " at @ " << (&Inst - &BB.front()) << "\n");
631     return MethodInfoType();
632   }
633 
634   ++TotalMethodLoadEliminationCandidates;
635 
636   DEBUG_VERBOSE(1, {
637     dbgs() << "BOLT-INFO: ICP found virtual method call in " << Function
638            << " at @ " << (&Inst - &BB.front()) << "\n";
639     dbgs() << "BOLT-INFO: ICP method fetch instructions:\n";
640     for (MCInst *Inst : MethodFetchInsns)
641       BC.printInstruction(dbgs(), *Inst, 0, &Function);
642 
643     if (MethodFetchInsns.back() != &Inst)
644       BC.printInstruction(dbgs(), Inst, 0, &Function);
645   });
646 
647   // Try to get value profiling data for the method load instruction.
648   auto ErrorOrMemAccesssProfile =
649       BC.MIB->tryGetAnnotationAs<MemoryAccessProfile>(*MethodFetchInsns.back(),
650                                                       "MemoryAccessProfile");
651   if (!ErrorOrMemAccesssProfile) {
652     DEBUG_VERBOSE(1, dbgs()
653                          << "BOLT-INFO: ICP no memory profiling data found\n");
654     return MethodInfoType();
655   }
656   MemoryAccessProfile &MemAccessProfile = ErrorOrMemAccesssProfile.get();
657 
658   // Find the vtable that each method belongs to.
659   std::map<const MCSymbol *, uint64_t> MethodToVtable;
660 
661   for (const AddressAccess &AccessInfo : MemAccessProfile.AddressAccessInfo) {
662     uint64_t Address = AccessInfo.Offset;
663     if (AccessInfo.MemoryObject)
664       Address += AccessInfo.MemoryObject->getAddress();
665 
666     // Ignore bogus data.
667     if (!Address)
668       continue;
669 
670     const uint64_t VtableBase = Address - MethodOffset;
671 
672     DEBUG_VERBOSE(1, dbgs() << "BOLT-INFO: ICP vtable = "
673                             << Twine::utohexstr(VtableBase) << "+"
674                             << MethodOffset << "/" << AccessInfo.Count << "\n");
675 
676     if (ErrorOr<uint64_t> MethodAddr = BC.getPointerAtAddress(Address)) {
677       BinaryData *MethodBD = BC.getBinaryDataAtAddress(MethodAddr.get());
678       if (!MethodBD) // skip unknown methods
679         continue;
680       MCSymbol *MethodSym = MethodBD->getSymbol();
681       MethodToVtable[MethodSym] = VtableBase;
682       DEBUG_VERBOSE(1, {
683         const BinaryFunction *Method = BC.getFunctionForSymbol(MethodSym);
684         dbgs() << "BOLT-INFO: ICP found method = "
685                << Twine::utohexstr(MethodAddr.get()) << "/"
686                << (Method ? Method->getPrintName() : "") << "\n";
687       });
688     }
689   }
690 
691   // Find the vtable for each target symbol.
692   for (size_t I = 0; I < SymTargets.size(); ++I) {
693     auto Itr = MethodToVtable.find(SymTargets[I].first);
694     if (Itr != MethodToVtable.end()) {
695       if (BinaryData *BD = BC.getBinaryDataContainingAddress(Itr->second)) {
696         const uint64_t Addend = Itr->second - BD->getAddress();
697         VtableSyms.emplace_back(BD->getSymbol(), Addend);
698         continue;
699       }
700     }
701     // Give up if we can't find the vtable for a method.
702     DEBUG_VERBOSE(1, dbgs() << "BOLT-INFO: ICP can't find vtable for "
703                             << SymTargets[I].first->getName() << "\n");
704     return MethodInfoType();
705   }
706 
707   // Make sure the vtable reg is not clobbered by the argument passing code
708   if (VtableReg != MethodReg) {
709     for (MCInst *CurInst = MethodFetchInsns.front(); CurInst < &Inst;
710          ++CurInst) {
711       const MCInstrDesc &InstrInfo = BC.MII->get(CurInst->getOpcode());
712       if (InstrInfo.hasDefOfPhysReg(*CurInst, VtableReg, *BC.MRI))
713         return MethodInfoType();
714     }
715   }
716 
717   return MethodInfoType(VtableSyms, MethodFetchInsns);
718 }
719 
720 std::vector<std::unique_ptr<BinaryBasicBlock>>
721 IndirectCallPromotion::rewriteCall(
722     BinaryBasicBlock &IndCallBlock, const MCInst &CallInst,
723     MCPlusBuilder::BlocksVectorTy &&ICPcode,
724     const std::vector<MCInst *> &MethodFetchInsns) const {
725   BinaryFunction &Function = *IndCallBlock.getFunction();
726   MCPlusBuilder *MIB = Function.getBinaryContext().MIB.get();
727 
728   // Create new basic blocks with correct code in each one first.
729   std::vector<std::unique_ptr<BinaryBasicBlock>> NewBBs;
730   const bool IsTailCallOrJT =
731       (MIB->isTailCall(CallInst) || Function.getJumpTable(CallInst));
732 
733   // Move instructions from the tail of the original call block
734   // to the merge block.
735 
736   // Remember any pseudo instructions following a tail call.  These
737   // must be preserved and moved to the original block.
738   InstructionListType TailInsts;
739   const MCInst *TailInst = &CallInst;
740   if (IsTailCallOrJT)
741     while (TailInst + 1 < &(*IndCallBlock.end()) &&
742            MIB->isPseudo(*(TailInst + 1)))
743       TailInsts.push_back(*++TailInst);
744 
745   InstructionListType MovedInst = IndCallBlock.splitInstructions(&CallInst);
746   // Link new BBs to the original input offset of the BB where the indirect
747   // call site is, so we can map samples recorded in new BBs back to the
748   // original BB seen in the input binary (if using BAT)
749   const uint32_t OrigOffset = IndCallBlock.getInputOffset();
750 
751   IndCallBlock.eraseInstructions(MethodFetchInsns.begin(),
752                                  MethodFetchInsns.end());
753   if (IndCallBlock.empty() ||
754       (!MethodFetchInsns.empty() && MethodFetchInsns.back() == &CallInst))
755     IndCallBlock.addInstructions(ICPcode.front().second.begin(),
756                                  ICPcode.front().second.end());
757   else
758     IndCallBlock.replaceInstruction(std::prev(IndCallBlock.end()),
759                                     ICPcode.front().second);
760   IndCallBlock.addInstructions(TailInsts.begin(), TailInsts.end());
761 
762   for (auto Itr = ICPcode.begin() + 1; Itr != ICPcode.end(); ++Itr) {
763     MCSymbol *&Sym = Itr->first;
764     InstructionListType &Insts = Itr->second;
765     assert(Sym);
766     std::unique_ptr<BinaryBasicBlock> TBB =
767         Function.createBasicBlock(OrigOffset, Sym);
768     for (MCInst &Inst : Insts) // sanitize new instructions.
769       if (MIB->isCall(Inst))
770         MIB->removeAnnotation(Inst, "CallProfile");
771     TBB->addInstructions(Insts.begin(), Insts.end());
772     NewBBs.emplace_back(std::move(TBB));
773   }
774 
775   // Move tail of instructions from after the original call to
776   // the merge block.
777   if (!IsTailCallOrJT)
778     NewBBs.back()->addInstructions(MovedInst.begin(), MovedInst.end());
779 
780   return NewBBs;
781 }
782 
783 BinaryBasicBlock *
784 IndirectCallPromotion::fixCFG(BinaryBasicBlock &IndCallBlock,
785                               const bool IsTailCall, const bool IsJumpTable,
786                               IndirectCallPromotion::BasicBlocksVector &&NewBBs,
787                               const std::vector<Callsite> &Targets) const {
788   BinaryFunction &Function = *IndCallBlock.getFunction();
789   using BinaryBranchInfo = BinaryBasicBlock::BinaryBranchInfo;
790   BinaryBasicBlock *MergeBlock = nullptr;
791 
792   // Scale indirect call counts to the execution count of the original
793   // basic block containing the indirect call.
794   uint64_t TotalCount = IndCallBlock.getKnownExecutionCount();
795   uint64_t TotalIndirectBranches = 0;
796   for (const Callsite &Target : Targets)
797     TotalIndirectBranches += Target.Branches;
798   if (TotalIndirectBranches == 0)
799     TotalIndirectBranches = 1;
800   BinaryBasicBlock::BranchInfoType BBI;
801   BinaryBasicBlock::BranchInfoType ScaledBBI;
802   for (const Callsite &Target : Targets) {
803     const size_t NumEntries =
804         std::max(static_cast<std::size_t>(1UL), Target.JTIndices.size());
805     for (size_t I = 0; I < NumEntries; ++I) {
806       BBI.push_back(
807           BinaryBranchInfo{(Target.Branches + NumEntries - 1) / NumEntries,
808                            (Target.Mispreds + NumEntries - 1) / NumEntries});
809       ScaledBBI.push_back(
810           BinaryBranchInfo{uint64_t(TotalCount * Target.Branches /
811                                     (NumEntries * TotalIndirectBranches)),
812                            uint64_t(TotalCount * Target.Mispreds /
813                                     (NumEntries * TotalIndirectBranches))});
814     }
815   }
816 
817   if (IsJumpTable) {
818     BinaryBasicBlock *NewIndCallBlock = NewBBs.back().get();
819     IndCallBlock.moveAllSuccessorsTo(NewIndCallBlock);
820 
821     std::vector<MCSymbol *> SymTargets;
822     for (const Callsite &Target : Targets) {
823       const size_t NumEntries =
824           std::max(static_cast<std::size_t>(1UL), Target.JTIndices.size());
825       for (size_t I = 0; I < NumEntries; ++I)
826         SymTargets.push_back(Target.To.Sym);
827     }
828     assert(SymTargets.size() > NewBBs.size() - 1 &&
829            "There must be a target symbol associated with each new BB.");
830 
831     for (uint64_t I = 0; I < NewBBs.size(); ++I) {
832       BinaryBasicBlock *SourceBB = I ? NewBBs[I - 1].get() : &IndCallBlock;
833       SourceBB->setExecutionCount(TotalCount);
834 
835       BinaryBasicBlock *TargetBB =
836           Function.getBasicBlockForLabel(SymTargets[I]);
837       SourceBB->addSuccessor(TargetBB, ScaledBBI[I]); // taken
838 
839       TotalCount -= ScaledBBI[I].Count;
840       SourceBB->addSuccessor(NewBBs[I].get(), TotalCount); // fall-through
841 
842       // Update branch info for the indirect jump.
843       BinaryBasicBlock::BinaryBranchInfo &BranchInfo =
844           NewIndCallBlock->getBranchInfo(*TargetBB);
845       if (BranchInfo.Count > BBI[I].Count)
846         BranchInfo.Count -= BBI[I].Count;
847       else
848         BranchInfo.Count = 0;
849 
850       if (BranchInfo.MispredictedCount > BBI[I].MispredictedCount)
851         BranchInfo.MispredictedCount -= BBI[I].MispredictedCount;
852       else
853         BranchInfo.MispredictedCount = 0;
854     }
855   } else {
856     assert(NewBBs.size() >= 2);
857     assert(NewBBs.size() % 2 == 1 || IndCallBlock.succ_empty());
858     assert(NewBBs.size() % 2 == 1 || IsTailCall);
859 
860     auto ScaledBI = ScaledBBI.begin();
861     auto updateCurrentBranchInfo = [&] {
862       assert(ScaledBI != ScaledBBI.end());
863       TotalCount -= ScaledBI->Count;
864       ++ScaledBI;
865     };
866 
867     if (!IsTailCall) {
868       MergeBlock = NewBBs.back().get();
869       IndCallBlock.moveAllSuccessorsTo(MergeBlock);
870     }
871 
872     // Fix up successors and execution counts.
873     updateCurrentBranchInfo();
874     IndCallBlock.addSuccessor(NewBBs[1].get(), TotalCount);
875     IndCallBlock.addSuccessor(NewBBs[0].get(), ScaledBBI[0]);
876 
877     const size_t Adj = IsTailCall ? 1 : 2;
878     for (size_t I = 0; I < NewBBs.size() - Adj; ++I) {
879       assert(TotalCount <= IndCallBlock.getExecutionCount() ||
880              TotalCount <= uint64_t(TotalIndirectBranches));
881       uint64_t ExecCount = ScaledBBI[(I + 1) / 2].Count;
882       if (I % 2 == 0) {
883         if (MergeBlock)
884           NewBBs[I]->addSuccessor(MergeBlock, ScaledBBI[(I + 1) / 2].Count);
885       } else {
886         assert(I + 2 < NewBBs.size());
887         updateCurrentBranchInfo();
888         NewBBs[I]->addSuccessor(NewBBs[I + 2].get(), TotalCount);
889         NewBBs[I]->addSuccessor(NewBBs[I + 1].get(), ScaledBBI[(I + 1) / 2]);
890         ExecCount += TotalCount;
891       }
892       NewBBs[I]->setExecutionCount(ExecCount);
893     }
894 
895     if (MergeBlock) {
896       // Arrange for the MergeBlock to be the fallthrough for the first
897       // promoted call block.
898       std::unique_ptr<BinaryBasicBlock> MBPtr;
899       std::swap(MBPtr, NewBBs.back());
900       NewBBs.pop_back();
901       NewBBs.emplace(NewBBs.begin() + 1, std::move(MBPtr));
902       // TODO: is COUNT_FALLTHROUGH_EDGE the right thing here?
903       NewBBs.back()->addSuccessor(MergeBlock, TotalCount); // uncond branch
904     }
905   }
906 
907   // Update the execution count.
908   NewBBs.back()->setExecutionCount(TotalCount);
909 
910   // Update BB and BB layout.
911   Function.insertBasicBlocks(&IndCallBlock, std::move(NewBBs));
912   assert(Function.validateCFG());
913 
914   return MergeBlock;
915 }
916 
917 size_t IndirectCallPromotion::canPromoteCallsite(
918     const BinaryBasicBlock &BB, const MCInst &Inst,
919     const std::vector<Callsite> &Targets, uint64_t NumCalls) {
920   if (BB.getKnownExecutionCount() < opts::ExecutionCountThreshold)
921     return 0;
922 
923   const bool IsJumpTable = BB.getFunction()->getJumpTable(Inst);
924 
925   auto computeStats = [&](size_t N) {
926     for (size_t I = 0; I < N; ++I)
927       if (!IsJumpTable)
928         TotalNumFrequentCalls += Targets[I].Branches;
929       else
930         TotalNumFrequentJmps += Targets[I].Branches;
931   };
932 
933   // If we have no targets (or no calls), skip this callsite.
934   if (Targets.empty() || !NumCalls) {
935     if (opts::Verbosity >= 1) {
936       const ptrdiff_t InstIdx = &Inst - &(*BB.begin());
937       outs() << "BOLT-INFO: ICP failed in " << *BB.getFunction() << " @ "
938              << InstIdx << " in " << BB.getName() << ", calls = " << NumCalls
939              << ", targets empty or NumCalls == 0.\n";
940     }
941     return 0;
942   }
943 
944   size_t TopN = opts::ICPTopN;
945   if (IsJumpTable)
946     TopN = opts::ICPJumpTablesTopN ? opts::ICPJumpTablesTopN : TopN;
947   else
948     TopN = opts::ICPCallsTopN ? opts::ICPCallsTopN : TopN;
949 
950   const size_t TrialN = TopN ? std::min(TopN, Targets.size()) : Targets.size();
951 
952   if (opts::ICPTopCallsites > 0) {
953     BinaryContext &BC = BB.getFunction()->getBinaryContext();
954     if (!BC.MIB->hasAnnotation(Inst, "DoICP"))
955       return 0;
956   }
957 
958   // Pick the top N targets.
959   uint64_t TotalMispredictsTopN = 0;
960   size_t N = 0;
961 
962   if (opts::ICPUseMispredicts &&
963       (!IsJumpTable || opts::ICPJumpTablesByTarget)) {
964     // Count total number of mispredictions for (at most) the top N targets.
965     // We may choose a smaller N (TrialN vs. N) if the frequency threshold
966     // is exceeded by fewer targets.
967     double Threshold = double(opts::ICPMispredictThreshold);
968     for (size_t I = 0; I < TrialN && Threshold > 0; ++I, ++N) {
969       Threshold -= (100.0 * Targets[I].Mispreds) / NumCalls;
970       TotalMispredictsTopN += Targets[I].Mispreds;
971     }
972     computeStats(N);
973 
974     // Compute the misprediction frequency of the top N call targets.  If this
975     // frequency is greater than the threshold, we should try ICP on this
976     // callsite.
977     const double TopNFrequency = (100.0 * TotalMispredictsTopN) / NumCalls;
978     if (TopNFrequency == 0 || TopNFrequency < opts::ICPMispredictThreshold) {
979       if (opts::Verbosity >= 1) {
980         const ptrdiff_t InstIdx = &Inst - &(*BB.begin());
981         outs() << "BOLT-INFO: ICP failed in " << *BB.getFunction() << " @ "
982                << InstIdx << " in " << BB.getName() << ", calls = " << NumCalls
983                << ", top N mis. frequency " << format("%.1f", TopNFrequency)
984                << "% < " << opts::ICPMispredictThreshold << "%\n";
985       }
986       return 0;
987     }
988   } else {
989     size_t MaxTargets = 0;
990 
991     // Count total number of calls for (at most) the top N targets.
992     // We may choose a smaller N (TrialN vs. N) if the frequency threshold
993     // is exceeded by fewer targets.
994     const unsigned TotalThreshold = IsJumpTable
995                                         ? opts::ICPJTTotalPercentThreshold
996                                         : opts::ICPCallsTotalPercentThreshold;
997     const unsigned RemainingThreshold =
998         IsJumpTable ? opts::ICPJTRemainingPercentThreshold
999                     : opts::ICPCallsRemainingPercentThreshold;
1000     uint64_t NumRemainingCalls = NumCalls;
1001     for (size_t I = 0; I < TrialN; ++I, ++MaxTargets) {
1002       if (100 * Targets[I].Branches < NumCalls * TotalThreshold)
1003         break;
1004       if (100 * Targets[I].Branches < NumRemainingCalls * RemainingThreshold)
1005         break;
1006       if (N + (Targets[I].JTIndices.empty() ? 1 : Targets[I].JTIndices.size()) >
1007           TrialN)
1008         break;
1009       TotalMispredictsTopN += Targets[I].Mispreds;
1010       NumRemainingCalls -= Targets[I].Branches;
1011       N += Targets[I].JTIndices.empty() ? 1 : Targets[I].JTIndices.size();
1012     }
1013     computeStats(MaxTargets);
1014 
1015     // Don't check misprediction frequency for jump tables -- we don't really
1016     // care as long as we are saving loads from the jump table.
1017     if (!IsJumpTable || opts::ICPJumpTablesByTarget) {
1018       // Compute the misprediction frequency of the top N call targets.  If
1019       // this frequency is less than the threshold, we should skip ICP at
1020       // this callsite.
1021       const double TopNMispredictFrequency =
1022           (100.0 * TotalMispredictsTopN) / NumCalls;
1023 
1024       if (TopNMispredictFrequency < opts::ICPMispredictThreshold) {
1025         if (opts::Verbosity >= 1) {
1026           const ptrdiff_t InstIdx = &Inst - &(*BB.begin());
1027           outs() << "BOLT-INFO: ICP failed in " << *BB.getFunction() << " @ "
1028                  << InstIdx << " in " << BB.getName()
1029                  << ", calls = " << NumCalls << ", top N mispredict frequency "
1030                  << format("%.1f", TopNMispredictFrequency) << "% < "
1031                  << opts::ICPMispredictThreshold << "%\n";
1032         }
1033         return 0;
1034       }
1035     }
1036   }
1037 
1038   // Filter functions that can have ICP applied (for debugging)
1039   if (!opts::ICPFuncsList.empty()) {
1040     for (std::string &Name : opts::ICPFuncsList)
1041       if (BB.getFunction()->hasName(Name))
1042         return N;
1043     return 0;
1044   }
1045 
1046   return N;
1047 }
1048 
1049 void IndirectCallPromotion::printCallsiteInfo(
1050     const BinaryBasicBlock &BB, const MCInst &Inst,
1051     const std::vector<Callsite> &Targets, const size_t N,
1052     uint64_t NumCalls) const {
1053   BinaryContext &BC = BB.getFunction()->getBinaryContext();
1054   const bool IsTailCall = BC.MIB->isTailCall(Inst);
1055   const bool IsJumpTable = BB.getFunction()->getJumpTable(Inst);
1056   const ptrdiff_t InstIdx = &Inst - &(*BB.begin());
1057 
1058   outs() << "BOLT-INFO: ICP candidate branch info: " << *BB.getFunction()
1059          << " @ " << InstIdx << " in " << BB.getName()
1060          << " -> calls = " << NumCalls
1061          << (IsTailCall ? " (tail)" : (IsJumpTable ? " (jump table)" : ""))
1062          << "\n";
1063   for (size_t I = 0; I < N; I++) {
1064     const double Frequency = 100.0 * Targets[I].Branches / NumCalls;
1065     const double MisFrequency = 100.0 * Targets[I].Mispreds / NumCalls;
1066     outs() << "BOLT-INFO:   ";
1067     if (Targets[I].To.Sym)
1068       outs() << Targets[I].To.Sym->getName();
1069     else
1070       outs() << Targets[I].To.Addr;
1071     outs() << ", calls = " << Targets[I].Branches
1072            << ", mispreds = " << Targets[I].Mispreds
1073            << ", taken freq = " << format("%.1f", Frequency) << "%"
1074            << ", mis. freq = " << format("%.1f", MisFrequency) << "%";
1075     bool First = true;
1076     for (uint64_t JTIndex : Targets[I].JTIndices) {
1077       outs() << (First ? ", indices = " : ", ") << JTIndex;
1078       First = false;
1079     }
1080     outs() << "\n";
1081   }
1082 
1083   LLVM_DEBUG({
1084     dbgs() << "BOLT-INFO: ICP original call instruction:";
1085     BC.printInstruction(dbgs(), Inst, Targets[0].From.Addr, nullptr, true);
1086   });
1087 }
1088 
1089 void IndirectCallPromotion::runOnFunctions(BinaryContext &BC) {
1090   if (opts::ICP == ICP_NONE)
1091     return;
1092 
1093   auto &BFs = BC.getBinaryFunctions();
1094 
1095   const bool OptimizeCalls = (opts::ICP == ICP_CALLS || opts::ICP == ICP_ALL);
1096   const bool OptimizeJumpTables =
1097       (opts::ICP == ICP_JUMP_TABLES || opts::ICP == ICP_ALL);
1098 
1099   std::unique_ptr<RegAnalysis> RA;
1100   std::unique_ptr<BinaryFunctionCallGraph> CG;
1101   if (OptimizeJumpTables) {
1102     CG.reset(new BinaryFunctionCallGraph(buildCallGraph(BC)));
1103     RA.reset(new RegAnalysis(BC, &BFs, &*CG));
1104   }
1105 
1106   // If icp-top-callsites is enabled, compute the total number of indirect
1107   // calls and then optimize the hottest callsites that contribute to that
1108   // total.
1109   SetVector<BinaryFunction *> Functions;
1110   if (opts::ICPTopCallsites == 0) {
1111     for (auto &KV : BFs)
1112       Functions.insert(&KV.second);
1113   } else {
1114     using IndirectCallsite = std::tuple<uint64_t, MCInst *, BinaryFunction *>;
1115     std::vector<IndirectCallsite> IndirectCalls;
1116     size_t TotalIndirectCalls = 0;
1117 
1118     // Find all the indirect callsites.
1119     for (auto &BFIt : BFs) {
1120       BinaryFunction &Function = BFIt.second;
1121 
1122       if (!Function.isSimple() || Function.isIgnored() ||
1123           !Function.hasProfile())
1124         continue;
1125 
1126       const bool HasLayout = !Function.layout_empty();
1127 
1128       for (BinaryBasicBlock &BB : Function) {
1129         if (HasLayout && Function.isSplit() && BB.isCold())
1130           continue;
1131 
1132         for (MCInst &Inst : BB) {
1133           const bool IsJumpTable = Function.getJumpTable(Inst);
1134           const bool HasIndirectCallProfile =
1135               BC.MIB->hasAnnotation(Inst, "CallProfile");
1136           const bool IsDirectCall =
1137               (BC.MIB->isCall(Inst) && BC.MIB->getTargetSymbol(Inst, 0));
1138 
1139           if (!IsDirectCall &&
1140               ((HasIndirectCallProfile && !IsJumpTable && OptimizeCalls) ||
1141                (IsJumpTable && OptimizeJumpTables))) {
1142             uint64_t NumCalls = 0;
1143             for (const Callsite &BInfo : getCallTargets(BB, Inst))
1144               NumCalls += BInfo.Branches;
1145             IndirectCalls.push_back(
1146                 std::make_tuple(NumCalls, &Inst, &Function));
1147             TotalIndirectCalls += NumCalls;
1148           }
1149         }
1150       }
1151     }
1152 
1153     // Sort callsites by execution count.
1154     std::sort(IndirectCalls.rbegin(), IndirectCalls.rend());
1155 
1156     // Find callsites that contribute to the top "opts::ICPTopCallsites"%
1157     // number of calls.
1158     const float TopPerc = opts::ICPTopCallsites / 100.0f;
1159     int64_t MaxCalls = TotalIndirectCalls * TopPerc;
1160     uint64_t LastFreq = std::numeric_limits<uint64_t>::max();
1161     size_t Num = 0;
1162     for (const IndirectCallsite &IC : IndirectCalls) {
1163       const uint64_t CurFreq = std::get<0>(IC);
1164       // Once we decide to stop, include at least all branches that share the
1165       // same frequency of the last one to avoid non-deterministic behavior
1166       // (e.g. turning on/off ICP depending on the order of functions)
1167       if (MaxCalls <= 0 && CurFreq != LastFreq)
1168         break;
1169       MaxCalls -= CurFreq;
1170       LastFreq = CurFreq;
1171       BC.MIB->addAnnotation(*std::get<1>(IC), "DoICP", true);
1172       Functions.insert(std::get<2>(IC));
1173       ++Num;
1174     }
1175     outs() << "BOLT-INFO: ICP Total indirect calls = " << TotalIndirectCalls
1176            << ", " << Num << " callsites cover " << opts::ICPTopCallsites
1177            << "% of all indirect calls\n";
1178   }
1179 
1180   for (BinaryFunction *FuncPtr : Functions) {
1181     BinaryFunction &Function = *FuncPtr;
1182 
1183     if (!Function.isSimple() || Function.isIgnored() || !Function.hasProfile())
1184       continue;
1185 
1186     const bool HasLayout = !Function.layout_empty();
1187 
1188     // Total number of indirect calls issued from the current Function.
1189     // (a fraction of TotalIndirectCalls)
1190     uint64_t FuncTotalIndirectCalls = 0;
1191     uint64_t FuncTotalIndirectJmps = 0;
1192 
1193     std::vector<BinaryBasicBlock *> BBs;
1194     for (BinaryBasicBlock &BB : Function) {
1195       // Skip indirect calls in cold blocks.
1196       if (!HasLayout || !Function.isSplit() || !BB.isCold())
1197         BBs.push_back(&BB);
1198     }
1199     if (BBs.empty())
1200       continue;
1201 
1202     DataflowInfoManager Info(Function, RA.get(), nullptr);
1203     while (!BBs.empty()) {
1204       BinaryBasicBlock *BB = BBs.back();
1205       BBs.pop_back();
1206 
1207       for (unsigned Idx = 0; Idx < BB->size(); ++Idx) {
1208         MCInst &Inst = BB->getInstructionAtIndex(Idx);
1209         const ptrdiff_t InstIdx = &Inst - &(*BB->begin());
1210         const bool IsTailCall = BC.MIB->isTailCall(Inst);
1211         const bool HasIndirectCallProfile =
1212             BC.MIB->hasAnnotation(Inst, "CallProfile");
1213         const bool IsJumpTable = Function.getJumpTable(Inst);
1214 
1215         if (BC.MIB->isCall(Inst))
1216           TotalCalls += BB->getKnownExecutionCount();
1217 
1218         if (IsJumpTable && !OptimizeJumpTables)
1219           continue;
1220 
1221         if (!IsJumpTable && (!HasIndirectCallProfile || !OptimizeCalls))
1222           continue;
1223 
1224         // Ignore direct calls.
1225         if (BC.MIB->isCall(Inst) && BC.MIB->getTargetSymbol(Inst, 0))
1226           continue;
1227 
1228         assert((BC.MIB->isCall(Inst) || BC.MIB->isIndirectBranch(Inst)) &&
1229                "expected a call or an indirect jump instruction");
1230 
1231         if (IsJumpTable)
1232           ++TotalJumpTableCallsites;
1233         else
1234           ++TotalIndirectCallsites;
1235 
1236         std::vector<Callsite> Targets = getCallTargets(*BB, Inst);
1237 
1238         // Compute the total number of calls from this particular callsite.
1239         uint64_t NumCalls = 0;
1240         for (const Callsite &BInfo : Targets)
1241           NumCalls += BInfo.Branches;
1242         if (!IsJumpTable)
1243           FuncTotalIndirectCalls += NumCalls;
1244         else
1245           FuncTotalIndirectJmps += NumCalls;
1246 
1247         // If FLAGS regs is alive after this jmp site, do not try
1248         // promoting because we will clobber FLAGS.
1249         if (IsJumpTable) {
1250           ErrorOr<const BitVector &> State =
1251               Info.getLivenessAnalysis().getStateBefore(Inst);
1252           if (!State || (State && (*State)[BC.MIB->getFlagsReg()])) {
1253             if (opts::Verbosity >= 1)
1254               outs() << "BOLT-INFO: ICP failed in " << Function << " @ "
1255                      << InstIdx << " in " << BB->getName()
1256                      << ", calls = " << NumCalls
1257                      << (State ? ", cannot clobber flags reg.\n"
1258                                : ", no liveness data available.\n");
1259             continue;
1260           }
1261         }
1262 
1263         // Should this callsite be optimized?  Return the number of targets
1264         // to use when promoting this call.  A value of zero means to skip
1265         // this callsite.
1266         size_t N = canPromoteCallsite(*BB, Inst, Targets, NumCalls);
1267 
1268         // If it is a jump table and it failed to meet our initial threshold,
1269         // proceed to findCallTargetSymbols -- it may reevaluate N if
1270         // memory profile is present
1271         if (!N && !IsJumpTable)
1272           continue;
1273 
1274         if (opts::Verbosity >= 1)
1275           printCallsiteInfo(*BB, Inst, Targets, N, NumCalls);
1276 
1277         // Find MCSymbols or absolute addresses for each call target.
1278         MCInst *TargetFetchInst = nullptr;
1279         const SymTargetsType SymTargets =
1280             findCallTargetSymbols(Targets, N, *BB, Inst, TargetFetchInst);
1281 
1282         // findCallTargetSymbols may have changed N if mem profile is available
1283         // for jump tables
1284         if (!N)
1285           continue;
1286 
1287         LLVM_DEBUG(printDecision(dbgs(), Targets, N));
1288 
1289         // If we can't resolve any of the target symbols, punt on this callsite.
1290         // TODO: can this ever happen?
1291         if (SymTargets.size() < N) {
1292           const size_t LastTarget = SymTargets.size();
1293           if (opts::Verbosity >= 1)
1294             outs() << "BOLT-INFO: ICP failed in " << Function << " @ "
1295                    << InstIdx << " in " << BB->getName()
1296                    << ", calls = " << NumCalls
1297                    << ", ICP failed to find target symbol for "
1298                    << Targets[LastTarget].To.Sym->getName() << "\n";
1299           continue;
1300         }
1301 
1302         MethodInfoType MethodInfo;
1303 
1304         if (!IsJumpTable) {
1305           MethodInfo = maybeGetVtableSyms(*BB, Inst, SymTargets);
1306           TotalMethodLoadsEliminated += MethodInfo.first.empty() ? 0 : 1;
1307           LLVM_DEBUG(dbgs()
1308                      << "BOLT-INFO: ICP "
1309                      << (!MethodInfo.first.empty() ? "found" : "did not find")
1310                      << " vtables for all methods.\n");
1311         } else if (TargetFetchInst) {
1312           ++TotalIndexBasedJumps;
1313           MethodInfo.second.push_back(TargetFetchInst);
1314         }
1315 
1316         // Generate new promoted call code for this callsite.
1317         MCPlusBuilder::BlocksVectorTy ICPcode =
1318             (IsJumpTable && !opts::ICPJumpTablesByTarget)
1319                 ? BC.MIB->jumpTablePromotion(Inst, SymTargets,
1320                                              MethodInfo.second, BC.Ctx.get())
1321                 : BC.MIB->indirectCallPromotion(
1322                       Inst, SymTargets, MethodInfo.first, MethodInfo.second,
1323                       opts::ICPOldCodeSequence, BC.Ctx.get());
1324 
1325         if (ICPcode.empty()) {
1326           if (opts::Verbosity >= 1)
1327             outs() << "BOLT-INFO: ICP failed in " << Function << " @ "
1328                    << InstIdx << " in " << BB->getName()
1329                    << ", calls = " << NumCalls
1330                    << ", unable to generate promoted call code.\n";
1331           continue;
1332         }
1333 
1334         LLVM_DEBUG({
1335           uint64_t Offset = Targets[0].From.Addr;
1336           dbgs() << "BOLT-INFO: ICP indirect call code:\n";
1337           for (const auto &entry : ICPcode) {
1338             const MCSymbol *const &Sym = entry.first;
1339             const InstructionListType &Insts = entry.second;
1340             if (Sym)
1341               dbgs() << Sym->getName() << ":\n";
1342             Offset = BC.printInstructions(dbgs(), Insts.begin(), Insts.end(),
1343                                           Offset);
1344           }
1345           dbgs() << "---------------------------------------------------\n";
1346         });
1347 
1348         // Rewrite the CFG with the newly generated ICP code.
1349         std::vector<std::unique_ptr<BinaryBasicBlock>> NewBBs =
1350             rewriteCall(*BB, Inst, std::move(ICPcode), MethodInfo.second);
1351 
1352         // Fix the CFG after inserting the new basic blocks.
1353         BinaryBasicBlock *MergeBlock =
1354             fixCFG(*BB, IsTailCall, IsJumpTable, std::move(NewBBs), Targets);
1355 
1356         // Since the tail of the original block was split off and it may contain
1357         // additional indirect calls, we must add the merge block to the set of
1358         // blocks to process.
1359         if (MergeBlock)
1360           BBs.push_back(MergeBlock);
1361 
1362         if (opts::Verbosity >= 1)
1363           outs() << "BOLT-INFO: ICP succeeded in " << Function << " @ "
1364                  << InstIdx << " in " << BB->getName()
1365                  << " -> calls = " << NumCalls << "\n";
1366 
1367         if (IsJumpTable)
1368           ++TotalOptimizedJumpTableCallsites;
1369         else
1370           ++TotalOptimizedIndirectCallsites;
1371 
1372         Modified.insert(&Function);
1373       }
1374     }
1375     TotalIndirectCalls += FuncTotalIndirectCalls;
1376     TotalIndirectJmps += FuncTotalIndirectJmps;
1377   }
1378 
1379   outs() << "BOLT-INFO: ICP total indirect callsites with profile = "
1380          << TotalIndirectCallsites << "\n"
1381          << "BOLT-INFO: ICP total jump table callsites = "
1382          << TotalJumpTableCallsites << "\n"
1383          << "BOLT-INFO: ICP total number of calls = " << TotalCalls << "\n"
1384          << "BOLT-INFO: ICP percentage of calls that are indirect = "
1385          << format("%.1f", (100.0 * TotalIndirectCalls) / TotalCalls) << "%\n"
1386          << "BOLT-INFO: ICP percentage of indirect calls that can be "
1387             "optimized = "
1388          << format("%.1f", (100.0 * TotalNumFrequentCalls) /
1389                                std::max<size_t>(TotalIndirectCalls, 1))
1390          << "%\n"
1391          << "BOLT-INFO: ICP percentage of indirect callsites that are "
1392             "optimized = "
1393          << format("%.1f", (100.0 * TotalOptimizedIndirectCallsites) /
1394                                std::max<uint64_t>(TotalIndirectCallsites, 1))
1395          << "%\n"
1396          << "BOLT-INFO: ICP number of method load elimination candidates = "
1397          << TotalMethodLoadEliminationCandidates << "\n"
1398          << "BOLT-INFO: ICP percentage of method calls candidates that have "
1399             "loads eliminated = "
1400          << format("%.1f", (100.0 * TotalMethodLoadsEliminated) /
1401                                std::max<uint64_t>(
1402                                    TotalMethodLoadEliminationCandidates, 1))
1403          << "%\n"
1404          << "BOLT-INFO: ICP percentage of indirect branches that are "
1405             "optimized = "
1406          << format("%.1f", (100.0 * TotalNumFrequentJmps) /
1407                                std::max<uint64_t>(TotalIndirectJmps, 1))
1408          << "%\n"
1409          << "BOLT-INFO: ICP percentage of jump table callsites that are "
1410          << "optimized = "
1411          << format("%.1f", (100.0 * TotalOptimizedJumpTableCallsites) /
1412                                std::max<uint64_t>(TotalJumpTableCallsites, 1))
1413          << "%\n"
1414          << "BOLT-INFO: ICP number of jump table callsites that can use hot "
1415          << "indices = " << TotalIndexBasedCandidates << "\n"
1416          << "BOLT-INFO: ICP percentage of jump table callsites that use hot "
1417             "indices = "
1418          << format("%.1f", (100.0 * TotalIndexBasedJumps) /
1419                                std::max<uint64_t>(TotalIndexBasedCandidates, 1))
1420          << "%\n";
1421 
1422   (void)verifyProfile;
1423 #ifndef NDEBUG
1424   verifyProfile(BFs);
1425 #endif
1426 }
1427 
1428 } // namespace bolt
1429 } // namespace llvm
1430