xref: /llvm-project/llvm/lib/Transforms/IPO/FunctionSpecialization.cpp (revision 5bfefff1c44fd992b673e1ff9c9f1865f9d81af1)
1 //===- FunctionSpecialization.cpp - Function Specialization ---------------===//
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 specialises functions with constant parameters. Constant parameters
10 // like function pointers and constant globals are propagated to the callee by
11 // specializing the function. The main benefit of this pass at the moment is
12 // that indirect calls are transformed into direct calls, which provides inline
13 // opportunities that the inliner would not have been able to achieve. That's
14 // why function specialisation is run before the inliner in the optimisation
15 // pipeline; that is by design. Otherwise, we would only benefit from constant
16 // passing, which is a valid use-case too, but hasn't been explored much in
17 // terms of performance uplifts, cost-model and compile-time impact.
18 //
19 // Current limitations:
20 // - It does not yet handle integer ranges. We do support "literal constants",
21 //   but that's off by default under an option.
22 // - The cost-model could be further looked into (it mainly focuses on inlining
23 //   benefits),
24 //
25 // Ideas:
26 // - With a function specialization attribute for arguments, we could have
27 //   a direct way to steer function specialization, avoiding the cost-model,
28 //   and thus control compile-times / code-size.
29 //
30 // Todos:
31 // - Specializing recursive functions relies on running the transformation a
32 //   number of times, which is controlled by option
33 //   `func-specialization-max-iters`. Thus, increasing this value and the
34 //   number of iterations, will linearly increase the number of times recursive
35 //   functions get specialized, see also the discussion in
36 //   https://reviews.llvm.org/D106426 for details. Perhaps there is a
37 //   compile-time friendlier way to control/limit the number of specialisations
38 //   for recursive functions.
39 // - Don't transform the function if function specialization does not trigger;
40 //   the SCCPSolver may make IR changes.
41 //
42 // References:
43 // - 2021 LLVM Dev Mtg “Introducing function specialisation, and can we enable
44 //   it by default?”, https://www.youtube.com/watch?v=zJiCjeXgV5Q
45 //
46 //===----------------------------------------------------------------------===//
47 
48 #include "llvm/Transforms/IPO/FunctionSpecialization.h"
49 #include "llvm/ADT/Statistic.h"
50 #include "llvm/Analysis/CodeMetrics.h"
51 #include "llvm/Analysis/ConstantFolding.h"
52 #include "llvm/Analysis/InlineCost.h"
53 #include "llvm/Analysis/InstructionSimplify.h"
54 #include "llvm/Analysis/TargetTransformInfo.h"
55 #include "llvm/Analysis/ValueLattice.h"
56 #include "llvm/Analysis/ValueLatticeUtils.h"
57 #include "llvm/Analysis/ValueTracking.h"
58 #include "llvm/IR/IntrinsicInst.h"
59 #include "llvm/Transforms/Scalar/SCCP.h"
60 #include "llvm/Transforms/Utils/Cloning.h"
61 #include "llvm/Transforms/Utils/SCCPSolver.h"
62 #include "llvm/Transforms/Utils/SizeOpts.h"
63 #include <cmath>
64 
65 using namespace llvm;
66 
67 #define DEBUG_TYPE "function-specialization"
68 
69 STATISTIC(NumSpecsCreated, "Number of specializations created");
70 
71 static cl::opt<bool> ForceSpecialization(
72     "force-specialization", cl::init(false), cl::Hidden, cl::desc(
73     "Force function specialization for every call site with a constant "
74     "argument"));
75 
76 static cl::opt<unsigned> MaxClones(
77     "funcspec-max-clones", cl::init(3), cl::Hidden, cl::desc(
78     "The maximum number of clones allowed for a single function "
79     "specialization"));
80 
81 static cl::opt<unsigned> MaxIncomingPhiValues(
82     "funcspec-max-incoming-phi-values", cl::init(4), cl::Hidden, cl::desc(
83     "The maximum number of incoming values a PHI node can have to be "
84     "considered during the specialization bonus estimation"));
85 
86 static cl::opt<unsigned> MinFunctionSize(
87     "funcspec-min-function-size", cl::init(100), cl::Hidden, cl::desc(
88     "Don't specialize functions that have less than this number of "
89     "instructions"));
90 
91 static cl::opt<bool> SpecializeOnAddress(
92     "funcspec-on-address", cl::init(false), cl::Hidden, cl::desc(
93     "Enable function specialization on the address of global values"));
94 
95 // Disabled by default as it can significantly increase compilation times.
96 //
97 // https://llvm-compile-time-tracker.com
98 // https://github.com/nikic/llvm-compile-time-tracker
99 static cl::opt<bool> SpecializeLiteralConstant(
100     "funcspec-for-literal-constant", cl::init(false), cl::Hidden, cl::desc(
101     "Enable specialization of functions that take a literal constant as an "
102     "argument"));
103 
104 // Estimates the codesize savings due to dead code after constant propagation.
105 // \p WorkList represents the basic blocks of a specialization which will
106 // eventually become dead once we replace instructions that are known to be
107 // constants. The successors of such blocks are added to the list as long as
108 // the \p Solver found they were executable prior to specialization, and only
109 // if they have a unique predecessor.
110 static Cost estimateBasicBlocks(SmallVectorImpl<BasicBlock *> &WorkList,
111                                 DenseSet<BasicBlock *> &DeadBlocks,
112                                 ConstMap &KnownConstants, SCCPSolver &Solver,
113                                 TargetTransformInfo &TTI) {
114   Cost CodeSize = 0;
115   // Accumulate the instruction cost of each basic block weighted by frequency.
116   while (!WorkList.empty()) {
117     BasicBlock *BB = WorkList.pop_back_val();
118 
119     // These blocks are considered dead as far as the InstCostVisitor
120     // is concerned. They haven't been proven dead yet by the Solver,
121     // but may become if we propagate the specialization arguments.
122     if (!DeadBlocks.insert(BB).second)
123       continue;
124 
125     for (Instruction &I : *BB) {
126       // Disregard SSA copies.
127       if (auto *II = dyn_cast<IntrinsicInst>(&I))
128         if (II->getIntrinsicID() == Intrinsic::ssa_copy)
129           continue;
130       // If it's a known constant we have already accounted for it.
131       if (KnownConstants.contains(&I))
132         continue;
133 
134       Cost C = TTI.getInstructionCost(&I, TargetTransformInfo::TCK_CodeSize);
135 
136       LLVM_DEBUG(dbgs() << "FnSpecialization:     CodeSize " << C
137                         << " for user " << I << "\n");
138       CodeSize += C;
139     }
140 
141     // Keep adding dead successors to the list as long as they are
142     // executable and they have a unique predecessor.
143     for (BasicBlock *SuccBB : successors(BB))
144       if (Solver.isBlockExecutable(SuccBB) &&
145           SuccBB->getUniquePredecessor() == BB)
146         WorkList.push_back(SuccBB);
147   }
148   return CodeSize;
149 }
150 
151 static Constant *findConstantFor(Value *V, ConstMap &KnownConstants) {
152   if (auto *C = dyn_cast<Constant>(V))
153     return C;
154   if (auto It = KnownConstants.find(V); It != KnownConstants.end())
155     return It->second;
156   return nullptr;
157 }
158 
159 Bonus InstCostVisitor::getBonusFromPendingPHIs() {
160   Bonus B;
161   while (!PendingPHIs.empty()) {
162     Instruction *Phi = PendingPHIs.pop_back_val();
163     // The pending PHIs could have been proven dead by now.
164     if (isBlockExecutable(Phi->getParent()))
165       B += getUserBonus(Phi);
166   }
167   return B;
168 }
169 
170 Bonus InstCostVisitor::getUserBonus(Instruction *User, Value *Use, Constant *C) {
171   // We have already propagated a constant for this user.
172   if (KnownConstants.contains(User))
173     return {0, 0};
174 
175   // Cache the iterator before visiting.
176   LastVisited = Use ? KnownConstants.insert({Use, C}).first
177                     : KnownConstants.end();
178 
179   Cost CodeSize = 0;
180   if (auto *I = dyn_cast<SwitchInst>(User)) {
181     CodeSize = estimateSwitchInst(*I);
182   } else if (auto *I = dyn_cast<BranchInst>(User)) {
183     CodeSize = estimateBranchInst(*I);
184   } else {
185     C = visit(*User);
186     if (!C)
187       return {0, 0};
188     KnownConstants.insert({User, C});
189   }
190 
191   CodeSize += TTI.getInstructionCost(User, TargetTransformInfo::TCK_CodeSize);
192 
193   uint64_t Weight = BFI.getBlockFreq(User->getParent()).getFrequency() /
194                     BFI.getEntryFreq();
195 
196   Cost Latency = Weight *
197       TTI.getInstructionCost(User, TargetTransformInfo::TCK_Latency);
198 
199   LLVM_DEBUG(dbgs() << "FnSpecialization:     {CodeSize = " << CodeSize
200                     << ", Latency = " << Latency << "} for user "
201                     << *User << "\n");
202 
203   Bonus B(CodeSize, Latency);
204   for (auto *U : User->users())
205     if (auto *UI = dyn_cast<Instruction>(U))
206       if (UI != User && isBlockExecutable(UI->getParent()))
207         B += getUserBonus(UI, User, C);
208 
209   return B;
210 }
211 
212 Cost InstCostVisitor::estimateSwitchInst(SwitchInst &I) {
213   assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
214 
215   if (I.getCondition() != LastVisited->first)
216     return 0;
217 
218   auto *C = dyn_cast<ConstantInt>(LastVisited->second);
219   if (!C)
220     return 0;
221 
222   BasicBlock *Succ = I.findCaseValue(C)->getCaseSuccessor();
223   // Initialize the worklist with the dead basic blocks. These are the
224   // destination labels which are different from the one corresponding
225   // to \p C. They should be executable and have a unique predecessor.
226   SmallVector<BasicBlock *> WorkList;
227   for (const auto &Case : I.cases()) {
228     BasicBlock *BB = Case.getCaseSuccessor();
229     if (BB == Succ || !Solver.isBlockExecutable(BB) ||
230         BB->getUniquePredecessor() != I.getParent())
231       continue;
232     WorkList.push_back(BB);
233   }
234 
235   return estimateBasicBlocks(WorkList, DeadBlocks, KnownConstants, Solver, TTI);
236 }
237 
238 Cost InstCostVisitor::estimateBranchInst(BranchInst &I) {
239   assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
240 
241   if (I.getCondition() != LastVisited->first)
242     return 0;
243 
244   BasicBlock *Succ = I.getSuccessor(LastVisited->second->isOneValue());
245   // Initialize the worklist with the dead successor as long as
246   // it is executable and has a unique predecessor.
247   SmallVector<BasicBlock *> WorkList;
248   if (Solver.isBlockExecutable(Succ) &&
249       Succ->getUniquePredecessor() == I.getParent())
250     WorkList.push_back(Succ);
251 
252   return estimateBasicBlocks(WorkList, DeadBlocks, KnownConstants, Solver, TTI);
253 }
254 
255 Constant *InstCostVisitor::visitPHINode(PHINode &I) {
256   if (I.getNumIncomingValues() > MaxIncomingPhiValues)
257     return nullptr;
258 
259   bool Inserted = VisitedPHIs.insert(&I).second;
260   Constant *Const = nullptr;
261 
262   for (unsigned Idx = 0, E = I.getNumIncomingValues(); Idx != E; ++Idx) {
263     Value *V = I.getIncomingValue(Idx);
264     if (auto *Inst = dyn_cast<Instruction>(V))
265       if (Inst == &I || DeadBlocks.contains(I.getIncomingBlock(Idx)))
266         continue;
267     Constant *C = findConstantFor(V, KnownConstants);
268     if (!C) {
269       if (Inserted)
270         PendingPHIs.push_back(&I);
271       return nullptr;
272     }
273     if (!Const)
274       Const = C;
275     else if (C != Const)
276       return nullptr;
277   }
278   return Const;
279 }
280 
281 Constant *InstCostVisitor::visitFreezeInst(FreezeInst &I) {
282   assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
283 
284   if (isGuaranteedNotToBeUndefOrPoison(LastVisited->second))
285     return LastVisited->second;
286   return nullptr;
287 }
288 
289 Constant *InstCostVisitor::visitCallBase(CallBase &I) {
290   Function *F = I.getCalledFunction();
291   if (!F || !canConstantFoldCallTo(&I, F))
292     return nullptr;
293 
294   SmallVector<Constant *, 8> Operands;
295   Operands.reserve(I.getNumOperands());
296 
297   for (unsigned Idx = 0, E = I.getNumOperands() - 1; Idx != E; ++Idx) {
298     Value *V = I.getOperand(Idx);
299     Constant *C = findConstantFor(V, KnownConstants);
300     if (!C)
301       return nullptr;
302     Operands.push_back(C);
303   }
304 
305   auto Ops = ArrayRef(Operands.begin(), Operands.end());
306   return ConstantFoldCall(&I, F, Ops);
307 }
308 
309 Constant *InstCostVisitor::visitLoadInst(LoadInst &I) {
310   assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
311 
312   if (isa<ConstantPointerNull>(LastVisited->second))
313     return nullptr;
314   return ConstantFoldLoadFromConstPtr(LastVisited->second, I.getType(), DL);
315 }
316 
317 Constant *InstCostVisitor::visitGetElementPtrInst(GetElementPtrInst &I) {
318   SmallVector<Constant *, 8> Operands;
319   Operands.reserve(I.getNumOperands());
320 
321   for (unsigned Idx = 0, E = I.getNumOperands(); Idx != E; ++Idx) {
322     Value *V = I.getOperand(Idx);
323     Constant *C = findConstantFor(V, KnownConstants);
324     if (!C)
325       return nullptr;
326     Operands.push_back(C);
327   }
328 
329   auto Ops = ArrayRef(Operands.begin(), Operands.end());
330   return ConstantFoldInstOperands(&I, Ops, DL);
331 }
332 
333 Constant *InstCostVisitor::visitSelectInst(SelectInst &I) {
334   assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
335 
336   if (I.getCondition() != LastVisited->first)
337     return nullptr;
338 
339   Value *V = LastVisited->second->isZeroValue() ? I.getFalseValue()
340                                                 : I.getTrueValue();
341   Constant *C = findConstantFor(V, KnownConstants);
342   return C;
343 }
344 
345 Constant *InstCostVisitor::visitCastInst(CastInst &I) {
346   return ConstantFoldCastOperand(I.getOpcode(), LastVisited->second,
347                                  I.getType(), DL);
348 }
349 
350 Constant *InstCostVisitor::visitCmpInst(CmpInst &I) {
351   assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
352 
353   bool Swap = I.getOperand(1) == LastVisited->first;
354   Value *V = Swap ? I.getOperand(0) : I.getOperand(1);
355   Constant *Other = findConstantFor(V, KnownConstants);
356   if (!Other)
357     return nullptr;
358 
359   Constant *Const = LastVisited->second;
360   return Swap ?
361         ConstantFoldCompareInstOperands(I.getPredicate(), Other, Const, DL)
362       : ConstantFoldCompareInstOperands(I.getPredicate(), Const, Other, DL);
363 }
364 
365 Constant *InstCostVisitor::visitUnaryOperator(UnaryOperator &I) {
366   assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
367 
368   return ConstantFoldUnaryOpOperand(I.getOpcode(), LastVisited->second, DL);
369 }
370 
371 Constant *InstCostVisitor::visitBinaryOperator(BinaryOperator &I) {
372   assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
373 
374   bool Swap = I.getOperand(1) == LastVisited->first;
375   Value *V = Swap ? I.getOperand(0) : I.getOperand(1);
376   Constant *Other = findConstantFor(V, KnownConstants);
377   if (!Other)
378     return nullptr;
379 
380   Constant *Const = LastVisited->second;
381   return dyn_cast_or_null<Constant>(Swap ?
382         simplifyBinOp(I.getOpcode(), Other, Const, SimplifyQuery(DL))
383       : simplifyBinOp(I.getOpcode(), Const, Other, SimplifyQuery(DL)));
384 }
385 
386 Constant *FunctionSpecializer::getPromotableAlloca(AllocaInst *Alloca,
387                                                    CallInst *Call) {
388   Value *StoreValue = nullptr;
389   for (auto *User : Alloca->users()) {
390     // We can't use llvm::isAllocaPromotable() as that would fail because of
391     // the usage in the CallInst, which is what we check here.
392     if (User == Call)
393       continue;
394     if (auto *Bitcast = dyn_cast<BitCastInst>(User)) {
395       if (!Bitcast->hasOneUse() || *Bitcast->user_begin() != Call)
396         return nullptr;
397       continue;
398     }
399 
400     if (auto *Store = dyn_cast<StoreInst>(User)) {
401       // This is a duplicate store, bail out.
402       if (StoreValue || Store->isVolatile())
403         return nullptr;
404       StoreValue = Store->getValueOperand();
405       continue;
406     }
407     // Bail if there is any other unknown usage.
408     return nullptr;
409   }
410 
411   if (!StoreValue)
412     return nullptr;
413 
414   return getCandidateConstant(StoreValue);
415 }
416 
417 // A constant stack value is an AllocaInst that has a single constant
418 // value stored to it. Return this constant if such an alloca stack value
419 // is a function argument.
420 Constant *FunctionSpecializer::getConstantStackValue(CallInst *Call,
421                                                      Value *Val) {
422   if (!Val)
423     return nullptr;
424   Val = Val->stripPointerCasts();
425   if (auto *ConstVal = dyn_cast<ConstantInt>(Val))
426     return ConstVal;
427   auto *Alloca = dyn_cast<AllocaInst>(Val);
428   if (!Alloca || !Alloca->getAllocatedType()->isIntegerTy())
429     return nullptr;
430   return getPromotableAlloca(Alloca, Call);
431 }
432 
433 // To support specializing recursive functions, it is important to propagate
434 // constant arguments because after a first iteration of specialisation, a
435 // reduced example may look like this:
436 //
437 //     define internal void @RecursiveFn(i32* arg1) {
438 //       %temp = alloca i32, align 4
439 //       store i32 2 i32* %temp, align 4
440 //       call void @RecursiveFn.1(i32* nonnull %temp)
441 //       ret void
442 //     }
443 //
444 // Before a next iteration, we need to propagate the constant like so
445 // which allows further specialization in next iterations.
446 //
447 //     @funcspec.arg = internal constant i32 2
448 //
449 //     define internal void @someFunc(i32* arg1) {
450 //       call void @otherFunc(i32* nonnull @funcspec.arg)
451 //       ret void
452 //     }
453 //
454 // See if there are any new constant values for the callers of \p F via
455 // stack variables and promote them to global variables.
456 void FunctionSpecializer::promoteConstantStackValues(Function *F) {
457   for (User *U : F->users()) {
458 
459     auto *Call = dyn_cast<CallInst>(U);
460     if (!Call)
461       continue;
462 
463     if (!Solver.isBlockExecutable(Call->getParent()))
464       continue;
465 
466     for (const Use &U : Call->args()) {
467       unsigned Idx = Call->getArgOperandNo(&U);
468       Value *ArgOp = Call->getArgOperand(Idx);
469       Type *ArgOpType = ArgOp->getType();
470 
471       if (!Call->onlyReadsMemory(Idx) || !ArgOpType->isPointerTy())
472         continue;
473 
474       auto *ConstVal = getConstantStackValue(Call, ArgOp);
475       if (!ConstVal)
476         continue;
477 
478       Value *GV = new GlobalVariable(M, ConstVal->getType(), true,
479                                      GlobalValue::InternalLinkage, ConstVal,
480                                      "funcspec.arg");
481       if (ArgOpType != ConstVal->getType())
482         GV = ConstantExpr::getBitCast(cast<Constant>(GV), ArgOpType);
483 
484       Call->setArgOperand(Idx, GV);
485     }
486   }
487 }
488 
489 // ssa_copy intrinsics are introduced by the SCCP solver. These intrinsics
490 // interfere with the promoteConstantStackValues() optimization.
491 static void removeSSACopy(Function &F) {
492   for (BasicBlock &BB : F) {
493     for (Instruction &Inst : llvm::make_early_inc_range(BB)) {
494       auto *II = dyn_cast<IntrinsicInst>(&Inst);
495       if (!II)
496         continue;
497       if (II->getIntrinsicID() != Intrinsic::ssa_copy)
498         continue;
499       Inst.replaceAllUsesWith(II->getOperand(0));
500       Inst.eraseFromParent();
501     }
502   }
503 }
504 
505 /// Remove any ssa_copy intrinsics that may have been introduced.
506 void FunctionSpecializer::cleanUpSSA() {
507   for (Function *F : Specializations)
508     removeSSACopy(*F);
509 }
510 
511 
512 template <> struct llvm::DenseMapInfo<SpecSig> {
513   static inline SpecSig getEmptyKey() { return {~0U, {}}; }
514 
515   static inline SpecSig getTombstoneKey() { return {~1U, {}}; }
516 
517   static unsigned getHashValue(const SpecSig &S) {
518     return static_cast<unsigned>(hash_value(S));
519   }
520 
521   static bool isEqual(const SpecSig &LHS, const SpecSig &RHS) {
522     return LHS == RHS;
523   }
524 };
525 
526 FunctionSpecializer::~FunctionSpecializer() {
527   LLVM_DEBUG(
528     if (NumSpecsCreated > 0)
529       dbgs() << "FnSpecialization: Created " << NumSpecsCreated
530              << " specializations in module " << M.getName() << "\n");
531   // Eliminate dead code.
532   removeDeadFunctions();
533   cleanUpSSA();
534 }
535 
536 /// Attempt to specialize functions in the module to enable constant
537 /// propagation across function boundaries.
538 ///
539 /// \returns true if at least one function is specialized.
540 bool FunctionSpecializer::run() {
541   // Find possible specializations for each function.
542   SpecMap SM;
543   SmallVector<Spec, 32> AllSpecs;
544   unsigned NumCandidates = 0;
545   for (Function &F : M) {
546     if (!isCandidateFunction(&F))
547       continue;
548 
549     auto [It, Inserted] = FunctionMetrics.try_emplace(&F);
550     CodeMetrics &Metrics = It->second;
551     //Analyze the function.
552     if (Inserted) {
553       SmallPtrSet<const Value *, 32> EphValues;
554       CodeMetrics::collectEphemeralValues(&F, &GetAC(F), EphValues);
555       for (BasicBlock &BB : F)
556         Metrics.analyzeBasicBlock(&BB, GetTTI(F), EphValues);
557     }
558 
559     // If the code metrics reveal that we shouldn't duplicate the function,
560     // or if the code size implies that this function is easy to get inlined,
561     // then we shouldn't specialize it.
562     if (Metrics.notDuplicatable || !Metrics.NumInsts.isValid() ||
563         (!ForceSpecialization && !F.hasFnAttribute(Attribute::NoInline) &&
564          Metrics.NumInsts < MinFunctionSize))
565       continue;
566 
567     // TODO: For now only consider recursive functions when running multiple
568     // times. This should change if specialization on literal constants gets
569     // enabled.
570     if (!Inserted && !Metrics.isRecursive && !SpecializeLiteralConstant)
571       continue;
572 
573     int64_t Sz = *Metrics.NumInsts.getValue();
574     assert(Sz > 0 && "CodeSize should be positive");
575     // It is safe to down cast from int64_t, NumInsts is always positive.
576     unsigned SpecCost = static_cast<unsigned>(Sz);
577 
578     LLVM_DEBUG(dbgs() << "FnSpecialization: Specialization cost for "
579                       << F.getName() << " is " << SpecCost << "\n");
580 
581     if (Inserted && Metrics.isRecursive)
582       promoteConstantStackValues(&F);
583 
584     if (!findSpecializations(&F, SpecCost, AllSpecs, SM)) {
585       LLVM_DEBUG(
586           dbgs() << "FnSpecialization: No possible specializations found for "
587                  << F.getName() << "\n");
588       continue;
589     }
590 
591     ++NumCandidates;
592   }
593 
594   if (!NumCandidates) {
595     LLVM_DEBUG(
596         dbgs()
597         << "FnSpecialization: No possible specializations found in module\n");
598     return false;
599   }
600 
601   // Choose the most profitable specialisations, which fit in the module
602   // specialization budget, which is derived from maximum number of
603   // specializations per specialization candidate function.
604   auto CompareScore = [&AllSpecs](unsigned I, unsigned J) {
605     return AllSpecs[I].Score > AllSpecs[J].Score;
606   };
607   const unsigned NSpecs =
608       std::min(NumCandidates * MaxClones, unsigned(AllSpecs.size()));
609   SmallVector<unsigned> BestSpecs(NSpecs + 1);
610   std::iota(BestSpecs.begin(), BestSpecs.begin() + NSpecs, 0);
611   if (AllSpecs.size() > NSpecs) {
612     LLVM_DEBUG(dbgs() << "FnSpecialization: Number of candidates exceed "
613                       << "the maximum number of clones threshold.\n"
614                       << "FnSpecialization: Specializing the "
615                       << NSpecs
616                       << " most profitable candidates.\n");
617     std::make_heap(BestSpecs.begin(), BestSpecs.begin() + NSpecs, CompareScore);
618     for (unsigned I = NSpecs, N = AllSpecs.size(); I < N; ++I) {
619       BestSpecs[NSpecs] = I;
620       std::push_heap(BestSpecs.begin(), BestSpecs.end(), CompareScore);
621       std::pop_heap(BestSpecs.begin(), BestSpecs.end(), CompareScore);
622     }
623   }
624 
625   LLVM_DEBUG(dbgs() << "FnSpecialization: List of specializations \n";
626              for (unsigned I = 0; I < NSpecs; ++I) {
627                const Spec &S = AllSpecs[BestSpecs[I]];
628                dbgs() << "FnSpecialization: Function " << S.F->getName()
629                       << " , score " << S.Score << "\n";
630                for (const ArgInfo &Arg : S.Sig.Args)
631                  dbgs() << "FnSpecialization:   FormalArg = "
632                         << Arg.Formal->getNameOrAsOperand()
633                         << ", ActualArg = " << Arg.Actual->getNameOrAsOperand()
634                         << "\n";
635              });
636 
637   // Create the chosen specializations.
638   SmallPtrSet<Function *, 8> OriginalFuncs;
639   SmallVector<Function *> Clones;
640   for (unsigned I = 0; I < NSpecs; ++I) {
641     Spec &S = AllSpecs[BestSpecs[I]];
642     S.Clone = createSpecialization(S.F, S.Sig);
643 
644     // Update the known call sites to call the clone.
645     for (CallBase *Call : S.CallSites) {
646       LLVM_DEBUG(dbgs() << "FnSpecialization: Redirecting " << *Call
647                         << " to call " << S.Clone->getName() << "\n");
648       Call->setCalledFunction(S.Clone);
649     }
650 
651     Clones.push_back(S.Clone);
652     OriginalFuncs.insert(S.F);
653   }
654 
655   Solver.solveWhileResolvedUndefsIn(Clones);
656 
657   // Update the rest of the call sites - these are the recursive calls, calls
658   // to discarded specialisations and calls that may match a specialisation
659   // after the solver runs.
660   for (Function *F : OriginalFuncs) {
661     auto [Begin, End] = SM[F];
662     updateCallSites(F, AllSpecs.begin() + Begin, AllSpecs.begin() + End);
663   }
664 
665   for (Function *F : Clones) {
666     if (F->getReturnType()->isVoidTy())
667       continue;
668     if (F->getReturnType()->isStructTy()) {
669       auto *STy = cast<StructType>(F->getReturnType());
670       if (!Solver.isStructLatticeConstant(F, STy))
671         continue;
672     } else {
673       auto It = Solver.getTrackedRetVals().find(F);
674       assert(It != Solver.getTrackedRetVals().end() &&
675              "Return value ought to be tracked");
676       if (SCCPSolver::isOverdefined(It->second))
677         continue;
678     }
679     for (User *U : F->users()) {
680       if (auto *CS = dyn_cast<CallBase>(U)) {
681         //The user instruction does not call our function.
682         if (CS->getCalledFunction() != F)
683           continue;
684         Solver.resetLatticeValueFor(CS);
685       }
686     }
687   }
688 
689   // Rerun the solver to notify the users of the modified callsites.
690   Solver.solveWhileResolvedUndefs();
691 
692   for (Function *F : OriginalFuncs)
693     if (FunctionMetrics[F].isRecursive)
694       promoteConstantStackValues(F);
695 
696   return true;
697 }
698 
699 void FunctionSpecializer::removeDeadFunctions() {
700   for (Function *F : FullySpecialized) {
701     LLVM_DEBUG(dbgs() << "FnSpecialization: Removing dead function "
702                       << F->getName() << "\n");
703     if (FAM)
704       FAM->clear(*F, F->getName());
705     F->eraseFromParent();
706   }
707   FullySpecialized.clear();
708 }
709 
710 /// Clone the function \p F and remove the ssa_copy intrinsics added by
711 /// the SCCPSolver in the cloned version.
712 static Function *cloneCandidateFunction(Function *F) {
713   ValueToValueMapTy Mappings;
714   Function *Clone = CloneFunction(F, Mappings);
715   removeSSACopy(*Clone);
716   return Clone;
717 }
718 
719 bool FunctionSpecializer::findSpecializations(Function *F, unsigned SpecCost,
720                                               SmallVectorImpl<Spec> &AllSpecs,
721                                               SpecMap &SM) {
722   // A mapping from a specialisation signature to the index of the respective
723   // entry in the all specialisation array. Used to ensure uniqueness of
724   // specialisations.
725   DenseMap<SpecSig, unsigned> UniqueSpecs;
726 
727   // Get a list of interesting arguments.
728   SmallVector<Argument *> Args;
729   for (Argument &Arg : F->args())
730     if (isArgumentInteresting(&Arg))
731       Args.push_back(&Arg);
732 
733   if (Args.empty())
734     return false;
735 
736   for (User *U : F->users()) {
737     if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
738       continue;
739     auto &CS = *cast<CallBase>(U);
740 
741     // The user instruction does not call our function.
742     if (CS.getCalledFunction() != F)
743       continue;
744 
745     // If the call site has attribute minsize set, that callsite won't be
746     // specialized.
747     if (CS.hasFnAttr(Attribute::MinSize))
748       continue;
749 
750     // If the parent of the call site will never be executed, we don't need
751     // to worry about the passed value.
752     if (!Solver.isBlockExecutable(CS.getParent()))
753       continue;
754 
755     // Examine arguments and create a specialisation candidate from the
756     // constant operands of this call site.
757     SpecSig S;
758     for (Argument *A : Args) {
759       Constant *C = getCandidateConstant(CS.getArgOperand(A->getArgNo()));
760       if (!C)
761         continue;
762       LLVM_DEBUG(dbgs() << "FnSpecialization: Found interesting argument "
763                         << A->getName() << " : " << C->getNameOrAsOperand()
764                         << "\n");
765       S.Args.push_back({A, C});
766     }
767 
768     if (S.Args.empty())
769       continue;
770 
771     // Check if we have encountered the same specialisation already.
772     if (auto It = UniqueSpecs.find(S); It != UniqueSpecs.end()) {
773       // Existing specialisation. Add the call to the list to rewrite, unless
774       // it's a recursive call. A specialisation, generated because of a
775       // recursive call may end up as not the best specialisation for all
776       // the cloned instances of this call, which result from specialising
777       // functions. Hence we don't rewrite the call directly, but match it with
778       // the best specialisation once all specialisations are known.
779       if (CS.getFunction() == F)
780         continue;
781       const unsigned Index = It->second;
782       AllSpecs[Index].CallSites.push_back(&CS);
783     } else {
784       // Calculate the specialisation gain.
785       Bonus B;
786       InstCostVisitor Visitor = getInstCostVisitorFor(F);
787       for (ArgInfo &A : S.Args)
788         B += getSpecializationBonus(A.Formal, A.Actual, Visitor);
789       B += Visitor.getBonusFromPendingPHIs();
790 
791       LLVM_DEBUG(dbgs() << "FnSpecialization: Specialization score {CodeSize = "
792                         << B.CodeSize << ", Latency = " << B.Latency
793                         << "}\n");
794 
795       // Discard unprofitable specialisations.
796       if (!ForceSpecialization && B.Latency <= SpecCost - B.CodeSize)
797         continue;
798 
799       // Create a new specialisation entry.
800       auto &Spec = AllSpecs.emplace_back(F, S, B.Latency);
801       if (CS.getFunction() != F)
802         Spec.CallSites.push_back(&CS);
803       const unsigned Index = AllSpecs.size() - 1;
804       UniqueSpecs[S] = Index;
805       if (auto [It, Inserted] = SM.try_emplace(F, Index, Index + 1); !Inserted)
806         It->second.second = Index + 1;
807     }
808   }
809 
810   return !UniqueSpecs.empty();
811 }
812 
813 bool FunctionSpecializer::isCandidateFunction(Function *F) {
814   if (F->isDeclaration() || F->arg_empty())
815     return false;
816 
817   if (F->hasFnAttribute(Attribute::NoDuplicate))
818     return false;
819 
820   // Do not specialize the cloned function again.
821   if (Specializations.contains(F))
822     return false;
823 
824   // If we're optimizing the function for size, we shouldn't specialize it.
825   if (F->hasOptSize() ||
826       shouldOptimizeForSize(F, nullptr, nullptr, PGSOQueryType::IRPass))
827     return false;
828 
829   // Exit if the function is not executable. There's no point in specializing
830   // a dead function.
831   if (!Solver.isBlockExecutable(&F->getEntryBlock()))
832     return false;
833 
834   // It wastes time to specialize a function which would get inlined finally.
835   if (F->hasFnAttribute(Attribute::AlwaysInline))
836     return false;
837 
838   LLVM_DEBUG(dbgs() << "FnSpecialization: Try function: " << F->getName()
839                     << "\n");
840   return true;
841 }
842 
843 Function *FunctionSpecializer::createSpecialization(Function *F,
844                                                     const SpecSig &S) {
845   Function *Clone = cloneCandidateFunction(F);
846 
847   // The original function does not neccessarily have internal linkage, but the
848   // clone must.
849   Clone->setLinkage(GlobalValue::InternalLinkage);
850 
851   // Initialize the lattice state of the arguments of the function clone,
852   // marking the argument on which we specialized the function constant
853   // with the given value.
854   Solver.setLatticeValueForSpecializationArguments(Clone, S.Args);
855   Solver.markBlockExecutable(&Clone->front());
856   Solver.addArgumentTrackedFunction(Clone);
857   Solver.addTrackedFunction(Clone);
858 
859   // Mark all the specialized functions
860   Specializations.insert(Clone);
861   ++NumSpecsCreated;
862 
863   return Clone;
864 }
865 
866 /// Compute a bonus for replacing argument \p A with constant \p C.
867 Bonus FunctionSpecializer::getSpecializationBonus(Argument *A, Constant *C,
868                                                  InstCostVisitor &Visitor) {
869   LLVM_DEBUG(dbgs() << "FnSpecialization: Analysing bonus for constant: "
870                     << C->getNameOrAsOperand() << "\n");
871 
872   Bonus B;
873   for (auto *U : A->users())
874     if (auto *UI = dyn_cast<Instruction>(U))
875       if (Visitor.isBlockExecutable(UI->getParent()))
876         B += Visitor.getUserBonus(UI, A, C);
877 
878   LLVM_DEBUG(dbgs() << "FnSpecialization:   Accumulated bonus {CodeSize = "
879                     << B.CodeSize << ", Latency = " << B.Latency
880                     << "} for argument " << *A << "\n");
881 
882   // The below heuristic is only concerned with exposing inlining
883   // opportunities via indirect call promotion. If the argument is not a
884   // (potentially casted) function pointer, give up.
885   //
886   // TODO: Perhaps we should consider checking such inlining opportunities
887   // while traversing the users of the specialization arguments ?
888   Function *CalledFunction = dyn_cast<Function>(C->stripPointerCasts());
889   if (!CalledFunction)
890     return B;
891 
892   // Get TTI for the called function (used for the inline cost).
893   auto &CalleeTTI = (GetTTI)(*CalledFunction);
894 
895   // Look at all the call sites whose called value is the argument.
896   // Specializing the function on the argument would allow these indirect
897   // calls to be promoted to direct calls. If the indirect call promotion
898   // would likely enable the called function to be inlined, specializing is a
899   // good idea.
900   int InliningBonus = 0;
901   for (User *U : A->users()) {
902     if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
903       continue;
904     auto *CS = cast<CallBase>(U);
905     if (CS->getCalledOperand() != A)
906       continue;
907     if (CS->getFunctionType() != CalledFunction->getFunctionType())
908       continue;
909 
910     // Get the cost of inlining the called function at this call site. Note
911     // that this is only an estimate. The called function may eventually
912     // change in a way that leads to it not being inlined here, even though
913     // inlining looks profitable now. For example, one of its called
914     // functions may be inlined into it, making the called function too large
915     // to be inlined into this call site.
916     //
917     // We apply a boost for performing indirect call promotion by increasing
918     // the default threshold by the threshold for indirect calls.
919     auto Params = getInlineParams();
920     Params.DefaultThreshold += InlineConstants::IndirectCallThreshold;
921     InlineCost IC =
922         getInlineCost(*CS, CalledFunction, Params, CalleeTTI, GetAC, GetTLI);
923 
924     // We clamp the bonus for this call to be between zero and the default
925     // threshold.
926     if (IC.isAlways())
927       InliningBonus += Params.DefaultThreshold;
928     else if (IC.isVariable() && IC.getCostDelta() > 0)
929       InliningBonus += IC.getCostDelta();
930 
931     LLVM_DEBUG(dbgs() << "FnSpecialization:   Inlining bonus " << InliningBonus
932                       << " for user " << *U << "\n");
933   }
934 
935   return B += {0, InliningBonus};
936 }
937 
938 /// Determine if it is possible to specialise the function for constant values
939 /// of the formal parameter \p A.
940 bool FunctionSpecializer::isArgumentInteresting(Argument *A) {
941   // No point in specialization if the argument is unused.
942   if (A->user_empty())
943     return false;
944 
945   Type *Ty = A->getType();
946   if (!Ty->isPointerTy() && (!SpecializeLiteralConstant ||
947       (!Ty->isIntegerTy() && !Ty->isFloatingPointTy() && !Ty->isStructTy())))
948     return false;
949 
950   // SCCP solver does not record an argument that will be constructed on
951   // stack.
952   if (A->hasByValAttr() && !A->getParent()->onlyReadsMemory())
953     return false;
954 
955   // For non-argument-tracked functions every argument is overdefined.
956   if (!Solver.isArgumentTrackedFunction(A->getParent()))
957     return true;
958 
959   // Check the lattice value and decide if we should attemt to specialize,
960   // based on this argument. No point in specialization, if the lattice value
961   // is already a constant.
962   bool IsOverdefined = Ty->isStructTy()
963     ? any_of(Solver.getStructLatticeValueFor(A), SCCPSolver::isOverdefined)
964     : SCCPSolver::isOverdefined(Solver.getLatticeValueFor(A));
965 
966   LLVM_DEBUG(
967     if (IsOverdefined)
968       dbgs() << "FnSpecialization: Found interesting parameter "
969              << A->getNameOrAsOperand() << "\n";
970     else
971       dbgs() << "FnSpecialization: Nothing to do, parameter "
972              << A->getNameOrAsOperand() << " is already constant\n";
973   );
974   return IsOverdefined;
975 }
976 
977 /// Check if the value \p V  (an actual argument) is a constant or can only
978 /// have a constant value. Return that constant.
979 Constant *FunctionSpecializer::getCandidateConstant(Value *V) {
980   if (isa<PoisonValue>(V))
981     return nullptr;
982 
983   // Select for possible specialisation values that are constants or
984   // are deduced to be constants or constant ranges with a single element.
985   Constant *C = dyn_cast<Constant>(V);
986   if (!C)
987     C = Solver.getConstantOrNull(V);
988 
989   // Don't specialize on (anything derived from) the address of a non-constant
990   // global variable, unless explicitly enabled.
991   if (C && C->getType()->isPointerTy() && !C->isNullValue())
992     if (auto *GV = dyn_cast<GlobalVariable>(getUnderlyingObject(C));
993         GV && !(GV->isConstant() || SpecializeOnAddress))
994       return nullptr;
995 
996   return C;
997 }
998 
999 void FunctionSpecializer::updateCallSites(Function *F, const Spec *Begin,
1000                                           const Spec *End) {
1001   // Collect the call sites that need updating.
1002   SmallVector<CallBase *> ToUpdate;
1003   for (User *U : F->users())
1004     if (auto *CS = dyn_cast<CallBase>(U);
1005         CS && CS->getCalledFunction() == F &&
1006         Solver.isBlockExecutable(CS->getParent()))
1007       ToUpdate.push_back(CS);
1008 
1009   unsigned NCallsLeft = ToUpdate.size();
1010   for (CallBase *CS : ToUpdate) {
1011     bool ShouldDecrementCount = CS->getFunction() == F;
1012 
1013     // Find the best matching specialisation.
1014     const Spec *BestSpec = nullptr;
1015     for (const Spec &S : make_range(Begin, End)) {
1016       if (!S.Clone || (BestSpec && S.Score <= BestSpec->Score))
1017         continue;
1018 
1019       if (any_of(S.Sig.Args, [CS, this](const ArgInfo &Arg) {
1020             unsigned ArgNo = Arg.Formal->getArgNo();
1021             return getCandidateConstant(CS->getArgOperand(ArgNo)) != Arg.Actual;
1022           }))
1023         continue;
1024 
1025       BestSpec = &S;
1026     }
1027 
1028     if (BestSpec) {
1029       LLVM_DEBUG(dbgs() << "FnSpecialization: Redirecting " << *CS
1030                         << " to call " << BestSpec->Clone->getName() << "\n");
1031       CS->setCalledFunction(BestSpec->Clone);
1032       ShouldDecrementCount = true;
1033     }
1034 
1035     if (ShouldDecrementCount)
1036       --NCallsLeft;
1037   }
1038 
1039   // If the function has been completely specialized, the original function
1040   // is no longer needed. Mark it unreachable.
1041   if (NCallsLeft == 0 && Solver.isArgumentTrackedFunction(F)) {
1042     Solver.markFunctionUnreachable(F);
1043     FullySpecialized.insert(F);
1044   }
1045 }
1046