1 //===-- PGOMemOPSizeOpt.cpp - Optimizations based on value profiling ===//
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 transformation that optimizes memory intrinsics
10 // such as memcpy using the size value profile. When memory intrinsic size
11 // value profile metadata is available, a single memory intrinsic is expanded
12 // to a sequence of guarded specialized versions that are called with the
13 // hottest size(s), for later expansion into more optimal inline sequences.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/Analysis/BlockFrequencyInfo.h"
22 #include "llvm/Analysis/DomTreeUpdater.h"
23 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
24 #include "llvm/Analysis/TargetLibraryInfo.h"
25 #include "llvm/IR/BasicBlock.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/Dominators.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/IRBuilder.h"
30 #include "llvm/IR/InstVisitor.h"
31 #include "llvm/IR/Instruction.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/LLVMContext.h"
34 #include "llvm/IR/PassManager.h"
35 #include "llvm/IR/Type.h"
36 #include "llvm/ProfileData/InstrProf.h"
37 #define INSTR_PROF_VALUE_PROF_MEMOP_API
38 #include "llvm/ProfileData/InstrProfData.inc"
39 #include "llvm/Support/Casting.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/MathExtras.h"
44 #include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include <cassert>
47 #include <cstdint>
48 #include <vector>
49 
50 using namespace llvm;
51 
52 #define DEBUG_TYPE "pgo-memop-opt"
53 
54 STATISTIC(NumOfPGOMemOPOpt, "Number of memop intrinsics optimized.");
55 STATISTIC(NumOfPGOMemOPAnnotate, "Number of memop intrinsics annotated.");
56 
57 // The minimum call count to optimize memory intrinsic calls.
58 static cl::opt<unsigned>
59     MemOPCountThreshold("pgo-memop-count-threshold", cl::Hidden, cl::init(1000),
60                         cl::desc("The minimum count to optimize memory "
61                                  "intrinsic calls"));
62 
63 // Command line option to disable memory intrinsic optimization. The default is
64 // false. This is for debug purpose.
65 static cl::opt<bool> DisableMemOPOPT("disable-memop-opt", cl::init(false),
66                                      cl::Hidden, cl::desc("Disable optimize"));
67 
68 // The percent threshold to optimize memory intrinsic calls.
69 static cl::opt<unsigned>
70     MemOPPercentThreshold("pgo-memop-percent-threshold", cl::init(40),
71                           cl::Hidden, cl::ZeroOrMore,
72                           cl::desc("The percentage threshold for the "
73                                    "memory intrinsic calls optimization"));
74 
75 // Maximum number of versions for optimizing memory intrinsic call.
76 static cl::opt<unsigned>
77     MemOPMaxVersion("pgo-memop-max-version", cl::init(3), cl::Hidden,
78                     cl::ZeroOrMore,
79                     cl::desc("The max version for the optimized memory "
80                              " intrinsic calls"));
81 
82 // Scale the counts from the annotation using the BB count value.
83 static cl::opt<bool>
84     MemOPScaleCount("pgo-memop-scale-count", cl::init(true), cl::Hidden,
85                     cl::desc("Scale the memop size counts using the basic "
86                              " block count value"));
87 
88 cl::opt<bool>
89     MemOPOptMemcmpBcmp("pgo-memop-optimize-memcmp-bcmp", cl::init(true),
90                        cl::Hidden,
91                        cl::desc("Size-specialize memcmp and bcmp calls"));
92 
93 static cl::opt<unsigned>
94     MemOpMaxOptSize("memop-value-prof-max-opt-size", cl::Hidden, cl::init(128),
95                     cl::desc("Optimize the memop size <= this value"));
96 
97 namespace {
98 
99 static const char *getMIName(const MemIntrinsic *MI) {
100   switch (MI->getIntrinsicID()) {
101   case Intrinsic::memcpy:
102     return "memcpy";
103   case Intrinsic::memmove:
104     return "memmove";
105   case Intrinsic::memset:
106     return "memset";
107   default:
108     return "unknown";
109   }
110 }
111 
112 // A class that abstracts a memop (memcpy, memmove, memset, memcmp and bcmp).
113 struct MemOp {
114   Instruction *I;
115   MemOp(MemIntrinsic *MI) : I(MI) {}
116   MemOp(CallInst *CI) : I(CI) {}
117   MemIntrinsic *asMI() { return dyn_cast<MemIntrinsic>(I); }
118   CallInst *asCI() { return cast<CallInst>(I); }
119   MemOp clone() {
120     if (auto MI = asMI())
121       return MemOp(cast<MemIntrinsic>(MI->clone()));
122     return MemOp(cast<CallInst>(asCI()->clone()));
123   }
124   Value *getLength() {
125     if (auto MI = asMI())
126       return MI->getLength();
127     return asCI()->getArgOperand(2);
128   }
129   void setLength(Value *Length) {
130     if (auto MI = asMI())
131       return MI->setLength(Length);
132     asCI()->setArgOperand(2, Length);
133   }
134   StringRef getFuncName() {
135     if (auto MI = asMI())
136       return MI->getCalledFunction()->getName();
137     return asCI()->getCalledFunction()->getName();
138   }
139   bool isMemmove() {
140     if (auto MI = asMI())
141       if (MI->getIntrinsicID() == Intrinsic::memmove)
142         return true;
143     return false;
144   }
145   bool isMemcmp(TargetLibraryInfo &TLI) {
146     LibFunc Func;
147     if (asMI() == nullptr && TLI.getLibFunc(*asCI(), Func) &&
148         Func == LibFunc_memcmp) {
149       return true;
150     }
151     return false;
152   }
153   bool isBcmp(TargetLibraryInfo &TLI) {
154     LibFunc Func;
155     if (asMI() == nullptr && TLI.getLibFunc(*asCI(), Func) &&
156         Func == LibFunc_bcmp) {
157       return true;
158     }
159     return false;
160   }
161   const char *getName(TargetLibraryInfo &TLI) {
162     if (auto MI = asMI())
163       return getMIName(MI);
164     LibFunc Func;
165     if (TLI.getLibFunc(*asCI(), Func)) {
166       if (Func == LibFunc_memcmp)
167         return "memcmp";
168       if (Func == LibFunc_bcmp)
169         return "bcmp";
170     }
171     llvm_unreachable("Must be MemIntrinsic or memcmp/bcmp CallInst");
172     return nullptr;
173   }
174 };
175 
176 class MemOPSizeOpt : public InstVisitor<MemOPSizeOpt> {
177 public:
178   MemOPSizeOpt(Function &Func, BlockFrequencyInfo &BFI,
179                OptimizationRemarkEmitter &ORE, DominatorTree *DT,
180                TargetLibraryInfo &TLI)
181       : Func(Func), BFI(BFI), ORE(ORE), DT(DT), TLI(TLI), Changed(false) {
182     ValueDataArray =
183         std::make_unique<InstrProfValueData[]>(INSTR_PROF_NUM_BUCKETS);
184   }
185   bool isChanged() const { return Changed; }
186   void perform() {
187     WorkList.clear();
188     visit(Func);
189 
190     for (auto &MO : WorkList) {
191       ++NumOfPGOMemOPAnnotate;
192       if (perform(MO)) {
193         Changed = true;
194         ++NumOfPGOMemOPOpt;
195         LLVM_DEBUG(dbgs() << "MemOP call: " << MO.getFuncName()
196                           << "is Transformed.\n");
197       }
198     }
199   }
200 
201   void visitMemIntrinsic(MemIntrinsic &MI) {
202     Value *Length = MI.getLength();
203     // Not perform on constant length calls.
204     if (isa<ConstantInt>(Length))
205       return;
206     WorkList.push_back(MemOp(&MI));
207   }
208 
209   void visitCallInst(CallInst &CI) {
210     LibFunc Func;
211     if (TLI.getLibFunc(CI, Func) &&
212         (Func == LibFunc_memcmp || Func == LibFunc_bcmp) &&
213         !isa<ConstantInt>(CI.getArgOperand(2))) {
214       WorkList.push_back(MemOp(&CI));
215     }
216   }
217 
218 private:
219   Function &Func;
220   BlockFrequencyInfo &BFI;
221   OptimizationRemarkEmitter &ORE;
222   DominatorTree *DT;
223   TargetLibraryInfo &TLI;
224   bool Changed;
225   std::vector<MemOp> WorkList;
226   // The space to read the profile annotation.
227   std::unique_ptr<InstrProfValueData[]> ValueDataArray;
228   bool perform(MemOp MO);
229 };
230 
231 static bool isProfitable(uint64_t Count, uint64_t TotalCount) {
232   assert(Count <= TotalCount);
233   if (Count < MemOPCountThreshold)
234     return false;
235   if (Count < TotalCount * MemOPPercentThreshold / 100)
236     return false;
237   return true;
238 }
239 
240 static inline uint64_t getScaledCount(uint64_t Count, uint64_t Num,
241                                       uint64_t Denom) {
242   if (!MemOPScaleCount)
243     return Count;
244   bool Overflowed;
245   uint64_t ScaleCount = SaturatingMultiply(Count, Num, &Overflowed);
246   return ScaleCount / Denom;
247 }
248 
249 bool MemOPSizeOpt::perform(MemOp MO) {
250   assert(MO.I);
251   if (MO.isMemmove())
252     return false;
253   if (!MemOPOptMemcmpBcmp && (MO.isMemcmp(TLI) || MO.isBcmp(TLI)))
254     return false;
255 
256   uint32_t NumVals, MaxNumVals = INSTR_PROF_NUM_BUCKETS;
257   uint64_t TotalCount;
258   if (!getValueProfDataFromInst(*MO.I, IPVK_MemOPSize, MaxNumVals,
259                                 ValueDataArray.get(), NumVals, TotalCount))
260     return false;
261 
262   uint64_t ActualCount = TotalCount;
263   uint64_t SavedTotalCount = TotalCount;
264   if (MemOPScaleCount) {
265     auto BBEdgeCount = BFI.getBlockProfileCount(MO.I->getParent());
266     if (!BBEdgeCount)
267       return false;
268     ActualCount = *BBEdgeCount;
269   }
270 
271   ArrayRef<InstrProfValueData> VDs(ValueDataArray.get(), NumVals);
272   LLVM_DEBUG(dbgs() << "Read one memory intrinsic profile with count "
273                     << ActualCount << "\n");
274   LLVM_DEBUG(
275       for (auto &VD
276            : VDs) { dbgs() << "  (" << VD.Value << "," << VD.Count << ")\n"; });
277 
278   if (ActualCount < MemOPCountThreshold)
279     return false;
280   // Skip if the total value profiled count is 0, in which case we can't
281   // scale up the counts properly (and there is no profitable transformation).
282   if (TotalCount == 0)
283     return false;
284 
285   TotalCount = ActualCount;
286   if (MemOPScaleCount)
287     LLVM_DEBUG(dbgs() << "Scale counts: numerator = " << ActualCount
288                       << " denominator = " << SavedTotalCount << "\n");
289 
290   // Keeping track of the count of the default case:
291   uint64_t RemainCount = TotalCount;
292   uint64_t SavedRemainCount = SavedTotalCount;
293   SmallVector<uint64_t, 16> SizeIds;
294   SmallVector<uint64_t, 16> CaseCounts;
295   uint64_t MaxCount = 0;
296   unsigned Version = 0;
297   int64_t LastV = -1;
298   // Default case is in the front -- save the slot here.
299   CaseCounts.push_back(0);
300   SmallVector<InstrProfValueData, 24> RemainingVDs;
301   for (auto I = VDs.begin(), E = VDs.end(); I != E; ++I) {
302     auto &VD = *I;
303     int64_t V = VD.Value;
304     uint64_t C = VD.Count;
305     if (MemOPScaleCount)
306       C = getScaledCount(C, ActualCount, SavedTotalCount);
307 
308     if (!InstrProfIsSingleValRange(V) || V > MemOpMaxOptSize) {
309       RemainingVDs.push_back(VD);
310       continue;
311     }
312 
313     // ValueCounts are sorted on the count. Break at the first un-profitable
314     // value.
315     if (!isProfitable(C, RemainCount)) {
316       RemainingVDs.insert(RemainingVDs.end(), I, E);
317       break;
318     }
319 
320     if (V == LastV) {
321       LLVM_DEBUG(dbgs() << "Invalid Profile Data in Function " << Func.getName()
322                         << ": Two consecutive, identical values in MemOp value"
323                            "counts.\n");
324       return false;
325     }
326 
327     LastV = V;
328 
329     SizeIds.push_back(V);
330     CaseCounts.push_back(C);
331     if (C > MaxCount)
332       MaxCount = C;
333 
334     assert(RemainCount >= C);
335     RemainCount -= C;
336     assert(SavedRemainCount >= VD.Count);
337     SavedRemainCount -= VD.Count;
338 
339     if (++Version >= MemOPMaxVersion && MemOPMaxVersion != 0) {
340       RemainingVDs.insert(RemainingVDs.end(), I + 1, E);
341       break;
342     }
343   }
344 
345   if (Version == 0)
346     return false;
347 
348   CaseCounts[0] = RemainCount;
349   if (RemainCount > MaxCount)
350     MaxCount = RemainCount;
351 
352   uint64_t SumForOpt = TotalCount - RemainCount;
353 
354   LLVM_DEBUG(dbgs() << "Optimize one memory intrinsic call to " << Version
355                     << " Versions (covering " << SumForOpt << " out of "
356                     << TotalCount << ")\n");
357 
358   // mem_op(..., size)
359   // ==>
360   // switch (size) {
361   //   case s1:
362   //      mem_op(..., s1);
363   //      goto merge_bb;
364   //   case s2:
365   //      mem_op(..., s2);
366   //      goto merge_bb;
367   //   ...
368   //   default:
369   //      mem_op(..., size);
370   //      goto merge_bb;
371   // }
372   // merge_bb:
373 
374   BasicBlock *BB = MO.I->getParent();
375   LLVM_DEBUG(dbgs() << "\n\n== Basic Block Before ==\n");
376   LLVM_DEBUG(dbgs() << *BB << "\n");
377   auto OrigBBFreq = BFI.getBlockFreq(BB);
378 
379   BasicBlock *DefaultBB = SplitBlock(BB, MO.I, DT);
380   BasicBlock::iterator It(*MO.I);
381   ++It;
382   assert(It != DefaultBB->end());
383   BasicBlock *MergeBB = SplitBlock(DefaultBB, &(*It), DT);
384   MergeBB->setName("MemOP.Merge");
385   BFI.setBlockFreq(MergeBB, OrigBBFreq.getFrequency());
386   DefaultBB->setName("MemOP.Default");
387 
388   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
389   auto &Ctx = Func.getContext();
390   IRBuilder<> IRB(BB);
391   BB->getTerminator()->eraseFromParent();
392   Value *SizeVar = MO.getLength();
393   SwitchInst *SI = IRB.CreateSwitch(SizeVar, DefaultBB, SizeIds.size());
394   Type *MemOpTy = MO.I->getType();
395   PHINode *PHI = nullptr;
396   if (!MemOpTy->isVoidTy()) {
397     // Insert a phi for the return values at the merge block.
398     IRBuilder<> IRBM(MergeBB->getFirstNonPHI());
399     PHI = IRBM.CreatePHI(MemOpTy, SizeIds.size() + 1, "MemOP.RVMerge");
400     MO.I->replaceAllUsesWith(PHI);
401     PHI->addIncoming(MO.I, DefaultBB);
402   }
403 
404   // Clear the value profile data.
405   MO.I->setMetadata(LLVMContext::MD_prof, nullptr);
406   // If all promoted, we don't need the MD.prof metadata.
407   if (SavedRemainCount > 0 || Version != NumVals) {
408     // Otherwise we need update with the un-promoted records back.
409     ArrayRef<InstrProfValueData> RemVDs(RemainingVDs);
410     annotateValueSite(*Func.getParent(), *MO.I, RemVDs, SavedRemainCount,
411                       IPVK_MemOPSize, NumVals);
412   }
413 
414   LLVM_DEBUG(dbgs() << "\n\n== Basic Block After==\n");
415 
416   std::vector<DominatorTree::UpdateType> Updates;
417   if (DT)
418     Updates.reserve(2 * SizeIds.size());
419 
420   for (uint64_t SizeId : SizeIds) {
421     BasicBlock *CaseBB = BasicBlock::Create(
422         Ctx, Twine("MemOP.Case.") + Twine(SizeId), &Func, DefaultBB);
423     MemOp NewMO = MO.clone();
424     // Fix the argument.
425     auto *SizeType = dyn_cast<IntegerType>(NewMO.getLength()->getType());
426     assert(SizeType && "Expected integer type size argument.");
427     ConstantInt *CaseSizeId = ConstantInt::get(SizeType, SizeId);
428     NewMO.setLength(CaseSizeId);
429     CaseBB->getInstList().push_back(NewMO.I);
430     IRBuilder<> IRBCase(CaseBB);
431     IRBCase.CreateBr(MergeBB);
432     SI->addCase(CaseSizeId, CaseBB);
433     if (!MemOpTy->isVoidTy())
434       PHI->addIncoming(NewMO.I, CaseBB);
435     if (DT) {
436       Updates.push_back({DominatorTree::Insert, CaseBB, MergeBB});
437       Updates.push_back({DominatorTree::Insert, BB, CaseBB});
438     }
439     LLVM_DEBUG(dbgs() << *CaseBB << "\n");
440   }
441   DTU.applyUpdates(Updates);
442   Updates.clear();
443 
444   setProfMetadata(Func.getParent(), SI, CaseCounts, MaxCount);
445 
446   LLVM_DEBUG(dbgs() << *BB << "\n");
447   LLVM_DEBUG(dbgs() << *DefaultBB << "\n");
448   LLVM_DEBUG(dbgs() << *MergeBB << "\n");
449 
450   ORE.emit([&]() {
451     using namespace ore;
452     return OptimizationRemark(DEBUG_TYPE, "memopt-opt", MO.I)
453            << "optimized " << NV("Memop", MO.getName(TLI)) << " with count "
454            << NV("Count", SumForOpt) << " out of " << NV("Total", TotalCount)
455            << " for " << NV("Versions", Version) << " versions";
456   });
457 
458   return true;
459 }
460 } // namespace
461 
462 static bool PGOMemOPSizeOptImpl(Function &F, BlockFrequencyInfo &BFI,
463                                 OptimizationRemarkEmitter &ORE,
464                                 DominatorTree *DT, TargetLibraryInfo &TLI) {
465   if (DisableMemOPOPT)
466     return false;
467 
468   if (F.hasFnAttribute(Attribute::OptimizeForSize))
469     return false;
470   MemOPSizeOpt MemOPSizeOpt(F, BFI, ORE, DT, TLI);
471   MemOPSizeOpt.perform();
472   return MemOPSizeOpt.isChanged();
473 }
474 
475 PreservedAnalyses PGOMemOPSizeOpt::run(Function &F,
476                                        FunctionAnalysisManager &FAM) {
477   auto &BFI = FAM.getResult<BlockFrequencyAnalysis>(F);
478   auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(F);
479   auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(F);
480   auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
481   bool Changed = PGOMemOPSizeOptImpl(F, BFI, ORE, DT, TLI);
482   if (!Changed)
483     return PreservedAnalyses::all();
484   auto PA = PreservedAnalyses();
485   PA.preserve<DominatorTreeAnalysis>();
486   return PA;
487 }
488