xref: /openbsd-src/gnu/llvm/llvm/lib/Transforms/IPO/FunctionSpecialization.cpp (revision d415bd752c734aee168c4ee86ff32e8cc249eb16)
173471bf0Spatrick //===- FunctionSpecialization.cpp - Function Specialization ---------------===//
273471bf0Spatrick //
373471bf0Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
473471bf0Spatrick // See https://llvm.org/LICENSE.txt for license information.
573471bf0Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
673471bf0Spatrick //
773471bf0Spatrick //===----------------------------------------------------------------------===//
873471bf0Spatrick //
9*d415bd75Srobert // This specialises functions with constant parameters. Constant parameters
10*d415bd75Srobert // like function pointers and constant globals are propagated to the callee by
11*d415bd75Srobert // specializing the function. The main benefit of this pass at the moment is
12*d415bd75Srobert // that indirect calls are transformed into direct calls, which provides inline
13*d415bd75Srobert // opportunities that the inliner would not have been able to achieve. That's
14*d415bd75Srobert // why function specialisation is run before the inliner in the optimisation
15*d415bd75Srobert // pipeline; that is by design. Otherwise, we would only benefit from constant
16*d415bd75Srobert // passing, which is a valid use-case too, but hasn't been explored much in
17*d415bd75Srobert // terms of performance uplifts, cost-model and compile-time impact.
1873471bf0Spatrick //
1973471bf0Spatrick // Current limitations:
20*d415bd75Srobert // - It does not yet handle integer ranges. We do support "literal constants",
21*d415bd75Srobert //   but that's off by default under an option.
22*d415bd75Srobert // - The cost-model could be further looked into (it mainly focuses on inlining
23*d415bd75Srobert //   benefits),
2473471bf0Spatrick //
2573471bf0Spatrick // Ideas:
2673471bf0Spatrick // - With a function specialization attribute for arguments, we could have
2773471bf0Spatrick //   a direct way to steer function specialization, avoiding the cost-model,
2873471bf0Spatrick //   and thus control compile-times / code-size.
2973471bf0Spatrick //
30*d415bd75Srobert // Todos:
31*d415bd75Srobert // - Specializing recursive functions relies on running the transformation a
32*d415bd75Srobert //   number of times, which is controlled by option
33*d415bd75Srobert //   `func-specialization-max-iters`. Thus, increasing this value and the
34*d415bd75Srobert //   number of iterations, will linearly increase the number of times recursive
35*d415bd75Srobert //   functions get specialized, see also the discussion in
36*d415bd75Srobert //   https://reviews.llvm.org/D106426 for details. Perhaps there is a
37*d415bd75Srobert //   compile-time friendlier way to control/limit the number of specialisations
38*d415bd75Srobert //   for recursive functions.
39*d415bd75Srobert // - Don't transform the function if function specialization does not trigger;
40*d415bd75Srobert //   the SCCPSolver may make IR changes.
41*d415bd75Srobert //
42*d415bd75Srobert // References:
43*d415bd75Srobert // - 2021 LLVM Dev Mtg “Introducing function specialisation, and can we enable
44*d415bd75Srobert //   it by default?”, https://www.youtube.com/watch?v=zJiCjeXgV5Q
45*d415bd75Srobert //
4673471bf0Spatrick //===----------------------------------------------------------------------===//
4773471bf0Spatrick 
48*d415bd75Srobert #include "llvm/Transforms/IPO/FunctionSpecialization.h"
4973471bf0Spatrick #include "llvm/ADT/Statistic.h"
5073471bf0Spatrick #include "llvm/Analysis/CodeMetrics.h"
5173471bf0Spatrick #include "llvm/Analysis/InlineCost.h"
5273471bf0Spatrick #include "llvm/Analysis/LoopInfo.h"
5373471bf0Spatrick #include "llvm/Analysis/TargetTransformInfo.h"
54*d415bd75Srobert #include "llvm/Analysis/ValueLattice.h"
55*d415bd75Srobert #include "llvm/Analysis/ValueLatticeUtils.h"
56*d415bd75Srobert #include "llvm/IR/IntrinsicInst.h"
5773471bf0Spatrick #include "llvm/Transforms/Scalar/SCCP.h"
5873471bf0Spatrick #include "llvm/Transforms/Utils/Cloning.h"
59*d415bd75Srobert #include "llvm/Transforms/Utils/SCCPSolver.h"
6073471bf0Spatrick #include "llvm/Transforms/Utils/SizeOpts.h"
6173471bf0Spatrick #include <cmath>
6273471bf0Spatrick 
6373471bf0Spatrick using namespace llvm;
6473471bf0Spatrick 
6573471bf0Spatrick #define DEBUG_TYPE "function-specialization"
6673471bf0Spatrick 
6773471bf0Spatrick STATISTIC(NumFuncSpecialized, "Number of functions specialized");
6873471bf0Spatrick 
6973471bf0Spatrick static cl::opt<bool> ForceFunctionSpecialization(
7073471bf0Spatrick     "force-function-specialization", cl::init(false), cl::Hidden,
7173471bf0Spatrick     cl::desc("Force function specialization for every call site with a "
7273471bf0Spatrick              "constant argument"));
7373471bf0Spatrick 
74*d415bd75Srobert static cl::opt<unsigned> MaxClonesThreshold(
75*d415bd75Srobert     "func-specialization-max-clones", cl::Hidden,
7673471bf0Spatrick     cl::desc("The maximum number of clones allowed for a single function "
7773471bf0Spatrick              "specialization"),
7873471bf0Spatrick     cl::init(3));
7973471bf0Spatrick 
80*d415bd75Srobert static cl::opt<unsigned> SmallFunctionThreshold(
81*d415bd75Srobert     "func-specialization-size-threshold", cl::Hidden,
82*d415bd75Srobert     cl::desc("Don't specialize functions that have less than this theshold "
83*d415bd75Srobert              "number of instructions"),
84*d415bd75Srobert     cl::init(100));
85*d415bd75Srobert 
8673471bf0Spatrick static cl::opt<unsigned>
8773471bf0Spatrick     AvgLoopIterationCount("func-specialization-avg-iters-cost", cl::Hidden,
8873471bf0Spatrick                           cl::desc("Average loop iteration count cost"),
8973471bf0Spatrick                           cl::init(10));
9073471bf0Spatrick 
91*d415bd75Srobert static cl::opt<bool> SpecializeOnAddresses(
92*d415bd75Srobert     "func-specialization-on-address", cl::init(false), cl::Hidden,
93*d415bd75Srobert     cl::desc("Enable function specialization on the address of global values"));
94*d415bd75Srobert 
95*d415bd75Srobert // Disabled by default as it can significantly increase compilation times.
96*d415bd75Srobert //
97*d415bd75Srobert // https://llvm-compile-time-tracker.com
98*d415bd75Srobert // https://github.com/nikic/llvm-compile-time-tracker
9973471bf0Spatrick static cl::opt<bool> EnableSpecializationForLiteralConstant(
10073471bf0Spatrick     "function-specialization-for-literal-constant", cl::init(false), cl::Hidden,
101*d415bd75Srobert     cl::desc("Enable specialization of functions that take a literal constant "
102*d415bd75Srobert              "as an argument."));
10373471bf0Spatrick 
getPromotableAlloca(AllocaInst * Alloca,CallInst * Call)104*d415bd75Srobert Constant *FunctionSpecializer::getPromotableAlloca(AllocaInst *Alloca,
105*d415bd75Srobert                                                    CallInst *Call) {
106*d415bd75Srobert   Value *StoreValue = nullptr;
107*d415bd75Srobert   for (auto *User : Alloca->users()) {
108*d415bd75Srobert     // We can't use llvm::isAllocaPromotable() as that would fail because of
109*d415bd75Srobert     // the usage in the CallInst, which is what we check here.
110*d415bd75Srobert     if (User == Call)
111*d415bd75Srobert       continue;
112*d415bd75Srobert     if (auto *Bitcast = dyn_cast<BitCastInst>(User)) {
113*d415bd75Srobert       if (!Bitcast->hasOneUse() || *Bitcast->user_begin() != Call)
114*d415bd75Srobert         return nullptr;
115*d415bd75Srobert       continue;
11673471bf0Spatrick     }
11773471bf0Spatrick 
118*d415bd75Srobert     if (auto *Store = dyn_cast<StoreInst>(User)) {
119*d415bd75Srobert       // This is a duplicate store, bail out.
120*d415bd75Srobert       if (StoreValue || Store->isVolatile())
121*d415bd75Srobert         return nullptr;
122*d415bd75Srobert       StoreValue = Store->getValueOperand();
123*d415bd75Srobert       continue;
124*d415bd75Srobert     }
125*d415bd75Srobert     // Bail if there is any other unknown usage.
126*d415bd75Srobert     return nullptr;
127*d415bd75Srobert   }
128*d415bd75Srobert   return getCandidateConstant(StoreValue);
129*d415bd75Srobert }
13073471bf0Spatrick 
131*d415bd75Srobert // A constant stack value is an AllocaInst that has a single constant
132*d415bd75Srobert // value stored to it. Return this constant if such an alloca stack value
133*d415bd75Srobert // is a function argument.
getConstantStackValue(CallInst * Call,Value * Val)134*d415bd75Srobert Constant *FunctionSpecializer::getConstantStackValue(CallInst *Call,
135*d415bd75Srobert                                                      Value *Val) {
136*d415bd75Srobert   if (!Val)
137*d415bd75Srobert     return nullptr;
138*d415bd75Srobert   Val = Val->stripPointerCasts();
139*d415bd75Srobert   if (auto *ConstVal = dyn_cast<ConstantInt>(Val))
140*d415bd75Srobert     return ConstVal;
141*d415bd75Srobert   auto *Alloca = dyn_cast<AllocaInst>(Val);
142*d415bd75Srobert   if (!Alloca || !Alloca->getAllocatedType()->isIntegerTy())
143*d415bd75Srobert     return nullptr;
144*d415bd75Srobert   return getPromotableAlloca(Alloca, Call);
145*d415bd75Srobert }
14673471bf0Spatrick 
147*d415bd75Srobert // To support specializing recursive functions, it is important to propagate
148*d415bd75Srobert // constant arguments because after a first iteration of specialisation, a
149*d415bd75Srobert // reduced example may look like this:
150*d415bd75Srobert //
151*d415bd75Srobert //     define internal void @RecursiveFn(i32* arg1) {
152*d415bd75Srobert //       %temp = alloca i32, align 4
153*d415bd75Srobert //       store i32 2 i32* %temp, align 4
154*d415bd75Srobert //       call void @RecursiveFn.1(i32* nonnull %temp)
155*d415bd75Srobert //       ret void
156*d415bd75Srobert //     }
157*d415bd75Srobert //
158*d415bd75Srobert // Before a next iteration, we need to propagate the constant like so
159*d415bd75Srobert // which allows further specialization in next iterations.
160*d415bd75Srobert //
161*d415bd75Srobert //     @funcspec.arg = internal constant i32 2
162*d415bd75Srobert //
163*d415bd75Srobert //     define internal void @someFunc(i32* arg1) {
164*d415bd75Srobert //       call void @otherFunc(i32* nonnull @funcspec.arg)
165*d415bd75Srobert //       ret void
166*d415bd75Srobert //     }
167*d415bd75Srobert //
promoteConstantStackValues()168*d415bd75Srobert void FunctionSpecializer::promoteConstantStackValues() {
169*d415bd75Srobert   // Iterate over the argument tracked functions see if there
170*d415bd75Srobert   // are any new constant values for the call instruction via
171*d415bd75Srobert   // stack variables.
172*d415bd75Srobert   for (Function &F : M) {
173*d415bd75Srobert     if (!Solver.isArgumentTrackedFunction(&F))
174*d415bd75Srobert       continue;
17573471bf0Spatrick 
176*d415bd75Srobert     for (auto *User : F.users()) {
17773471bf0Spatrick 
178*d415bd75Srobert       auto *Call = dyn_cast<CallInst>(User);
179*d415bd75Srobert       if (!Call)
180*d415bd75Srobert         continue;
181*d415bd75Srobert 
182*d415bd75Srobert       if (!Solver.isBlockExecutable(Call->getParent()))
183*d415bd75Srobert         continue;
184*d415bd75Srobert 
185*d415bd75Srobert       bool Changed = false;
186*d415bd75Srobert       for (const Use &U : Call->args()) {
187*d415bd75Srobert         unsigned Idx = Call->getArgOperandNo(&U);
188*d415bd75Srobert         Value *ArgOp = Call->getArgOperand(Idx);
189*d415bd75Srobert         Type *ArgOpType = ArgOp->getType();
190*d415bd75Srobert 
191*d415bd75Srobert         if (!Call->onlyReadsMemory(Idx) || !ArgOpType->isPointerTy())
192*d415bd75Srobert           continue;
193*d415bd75Srobert 
194*d415bd75Srobert         auto *ConstVal = getConstantStackValue(Call, ArgOp);
195*d415bd75Srobert         if (!ConstVal)
196*d415bd75Srobert           continue;
197*d415bd75Srobert 
198*d415bd75Srobert         Value *GV = new GlobalVariable(M, ConstVal->getType(), true,
199*d415bd75Srobert                                        GlobalValue::InternalLinkage, ConstVal,
200*d415bd75Srobert                                        "funcspec.arg");
201*d415bd75Srobert         if (ArgOpType != ConstVal->getType())
202*d415bd75Srobert           GV = ConstantExpr::getBitCast(cast<Constant>(GV), ArgOpType);
203*d415bd75Srobert 
204*d415bd75Srobert         Call->setArgOperand(Idx, GV);
205*d415bd75Srobert         Changed = true;
206*d415bd75Srobert       }
207*d415bd75Srobert 
208*d415bd75Srobert       // Add the changed CallInst to Solver Worklist
209*d415bd75Srobert       if (Changed)
210*d415bd75Srobert         Solver.visitCall(*Call);
211*d415bd75Srobert     }
212*d415bd75Srobert   }
213*d415bd75Srobert }
214*d415bd75Srobert 
215*d415bd75Srobert // ssa_copy intrinsics are introduced by the SCCP solver. These intrinsics
216*d415bd75Srobert // interfere with the promoteConstantStackValues() optimization.
removeSSACopy(Function & F)217*d415bd75Srobert static void removeSSACopy(Function &F) {
218*d415bd75Srobert   for (BasicBlock &BB : F) {
219*d415bd75Srobert     for (Instruction &Inst : llvm::make_early_inc_range(BB)) {
220*d415bd75Srobert       auto *II = dyn_cast<IntrinsicInst>(&Inst);
221*d415bd75Srobert       if (!II)
222*d415bd75Srobert         continue;
223*d415bd75Srobert       if (II->getIntrinsicID() != Intrinsic::ssa_copy)
224*d415bd75Srobert         continue;
225*d415bd75Srobert       Inst.replaceAllUsesWith(II->getOperand(0));
226*d415bd75Srobert       Inst.eraseFromParent();
227*d415bd75Srobert     }
228*d415bd75Srobert   }
229*d415bd75Srobert }
230*d415bd75Srobert 
231*d415bd75Srobert /// Remove any ssa_copy intrinsics that may have been introduced.
cleanUpSSA()232*d415bd75Srobert void FunctionSpecializer::cleanUpSSA() {
233*d415bd75Srobert   for (Function *F : SpecializedFuncs)
234*d415bd75Srobert     removeSSACopy(*F);
235*d415bd75Srobert }
236*d415bd75Srobert 
237*d415bd75Srobert 
238*d415bd75Srobert template <> struct llvm::DenseMapInfo<SpecSig> {
getEmptyKeyllvm::DenseMapInfo239*d415bd75Srobert   static inline SpecSig getEmptyKey() { return {~0U, {}}; }
240*d415bd75Srobert 
getTombstoneKeyllvm::DenseMapInfo241*d415bd75Srobert   static inline SpecSig getTombstoneKey() { return {~1U, {}}; }
242*d415bd75Srobert 
getHashValuellvm::DenseMapInfo243*d415bd75Srobert   static unsigned getHashValue(const SpecSig &S) {
244*d415bd75Srobert     return static_cast<unsigned>(hash_value(S));
245*d415bd75Srobert   }
246*d415bd75Srobert 
isEqualllvm::DenseMapInfo247*d415bd75Srobert   static bool isEqual(const SpecSig &LHS, const SpecSig &RHS) {
248*d415bd75Srobert     return LHS == RHS;
249*d415bd75Srobert   }
250*d415bd75Srobert };
25173471bf0Spatrick 
25273471bf0Spatrick /// Attempt to specialize functions in the module to enable constant
25373471bf0Spatrick /// propagation across function boundaries.
25473471bf0Spatrick ///
25573471bf0Spatrick /// \returns true if at least one function is specialized.
run()256*d415bd75Srobert bool FunctionSpecializer::run() {
257*d415bd75Srobert   // Find possible specializations for each function.
258*d415bd75Srobert   SpecMap SM;
259*d415bd75Srobert   SmallVector<Spec, 32> AllSpecs;
260*d415bd75Srobert   unsigned NumCandidates = 0;
261*d415bd75Srobert   for (Function &F : M) {
262*d415bd75Srobert     if (!isCandidateFunction(&F))
263*d415bd75Srobert       continue;
26473471bf0Spatrick 
265*d415bd75Srobert     auto Cost = getSpecializationCost(&F);
266*d415bd75Srobert     if (!Cost.isValid()) {
267*d415bd75Srobert       LLVM_DEBUG(dbgs() << "FnSpecialization: Invalid specialization cost for "
268*d415bd75Srobert                         << F.getName() << "\n");
269*d415bd75Srobert       continue;
270*d415bd75Srobert     }
271*d415bd75Srobert 
272*d415bd75Srobert     LLVM_DEBUG(dbgs() << "FnSpecialization: Specialization cost for "
273*d415bd75Srobert                       << F.getName() << " is " << Cost << "\n");
274*d415bd75Srobert 
275*d415bd75Srobert     if (!findSpecializations(&F, Cost, AllSpecs, SM)) {
27673471bf0Spatrick       LLVM_DEBUG(
277*d415bd75Srobert           dbgs() << "FnSpecialization: No possible specializations found for "
278*d415bd75Srobert                  << F.getName() << "\n");
279*d415bd75Srobert       continue;
280*d415bd75Srobert     }
281*d415bd75Srobert 
282*d415bd75Srobert     ++NumCandidates;
283*d415bd75Srobert   }
284*d415bd75Srobert 
285*d415bd75Srobert   if (!NumCandidates) {
286*d415bd75Srobert     LLVM_DEBUG(
287*d415bd75Srobert         dbgs()
288*d415bd75Srobert         << "FnSpecialization: No possible specializations found in module\n");
289*d415bd75Srobert     return false;
290*d415bd75Srobert   }
291*d415bd75Srobert 
292*d415bd75Srobert   // Choose the most profitable specialisations, which fit in the module
293*d415bd75Srobert   // specialization budget, which is derived from maximum number of
294*d415bd75Srobert   // specializations per specialization candidate function.
295*d415bd75Srobert   auto CompareGain = [&AllSpecs](unsigned I, unsigned J) {
296*d415bd75Srobert     return AllSpecs[I].Gain > AllSpecs[J].Gain;
297*d415bd75Srobert   };
298*d415bd75Srobert   const unsigned NSpecs =
299*d415bd75Srobert       std::min(NumCandidates * MaxClonesThreshold, unsigned(AllSpecs.size()));
300*d415bd75Srobert   SmallVector<unsigned> BestSpecs(NSpecs + 1);
301*d415bd75Srobert   std::iota(BestSpecs.begin(), BestSpecs.begin() + NSpecs, 0);
302*d415bd75Srobert   if (AllSpecs.size() > NSpecs) {
303*d415bd75Srobert     LLVM_DEBUG(dbgs() << "FnSpecialization: Number of candidates exceed "
304*d415bd75Srobert                       << "the maximum number of clones threshold.\n"
305*d415bd75Srobert                       << "FnSpecialization: Specializing the "
306*d415bd75Srobert                       << NSpecs
307*d415bd75Srobert                       << " most profitable candidates.\n");
308*d415bd75Srobert     std::make_heap(BestSpecs.begin(), BestSpecs.begin() + NSpecs, CompareGain);
309*d415bd75Srobert     for (unsigned I = NSpecs, N = AllSpecs.size(); I < N; ++I) {
310*d415bd75Srobert       BestSpecs[NSpecs] = I;
311*d415bd75Srobert       std::push_heap(BestSpecs.begin(), BestSpecs.end(), CompareGain);
312*d415bd75Srobert       std::pop_heap(BestSpecs.begin(), BestSpecs.end(), CompareGain);
31373471bf0Spatrick     }
31473471bf0Spatrick   }
31573471bf0Spatrick 
316*d415bd75Srobert   LLVM_DEBUG(dbgs() << "FnSpecialization: List of specializations \n";
317*d415bd75Srobert              for (unsigned I = 0; I < NSpecs; ++I) {
318*d415bd75Srobert                const Spec &S = AllSpecs[BestSpecs[I]];
319*d415bd75Srobert                dbgs() << "FnSpecialization: Function " << S.F->getName()
320*d415bd75Srobert                       << " , gain " << S.Gain << "\n";
321*d415bd75Srobert                for (const ArgInfo &Arg : S.Sig.Args)
322*d415bd75Srobert                  dbgs() << "FnSpecialization:   FormalArg = "
323*d415bd75Srobert                         << Arg.Formal->getNameOrAsOperand()
324*d415bd75Srobert                         << ", ActualArg = " << Arg.Actual->getNameOrAsOperand()
325*d415bd75Srobert                         << "\n";
326*d415bd75Srobert              });
32773471bf0Spatrick 
328*d415bd75Srobert   // Create the chosen specializations.
329*d415bd75Srobert   SmallPtrSet<Function *, 8> OriginalFuncs;
330*d415bd75Srobert   SmallVector<Function *> Clones;
331*d415bd75Srobert   for (unsigned I = 0; I < NSpecs; ++I) {
332*d415bd75Srobert     Spec &S = AllSpecs[BestSpecs[I]];
333*d415bd75Srobert     S.Clone = createSpecialization(S.F, S.Sig);
33473471bf0Spatrick 
335*d415bd75Srobert     // Update the known call sites to call the clone.
336*d415bd75Srobert     for (CallBase *Call : S.CallSites) {
337*d415bd75Srobert       LLVM_DEBUG(dbgs() << "FnSpecialization: Redirecting " << *Call
338*d415bd75Srobert                         << " to call " << S.Clone->getName() << "\n");
339*d415bd75Srobert       Call->setCalledFunction(S.Clone);
34073471bf0Spatrick     }
34173471bf0Spatrick 
342*d415bd75Srobert     Clones.push_back(S.Clone);
343*d415bd75Srobert     OriginalFuncs.insert(S.F);
344*d415bd75Srobert   }
345*d415bd75Srobert 
346*d415bd75Srobert   Solver.solveWhileResolvedUndefsIn(Clones);
347*d415bd75Srobert 
348*d415bd75Srobert   // Update the rest of the call sites - these are the recursive calls, calls
349*d415bd75Srobert   // to discarded specialisations and calls that may match a specialisation
350*d415bd75Srobert   // after the solver runs.
351*d415bd75Srobert   for (Function *F : OriginalFuncs) {
352*d415bd75Srobert     auto [Begin, End] = SM[F];
353*d415bd75Srobert     updateCallSites(F, AllSpecs.begin() + Begin, AllSpecs.begin() + End);
354*d415bd75Srobert   }
355*d415bd75Srobert 
356*d415bd75Srobert   promoteConstantStackValues();
357*d415bd75Srobert   LLVM_DEBUG(if (NbFunctionsSpecialized) dbgs()
358*d415bd75Srobert              << "FnSpecialization: Specialized " << NbFunctionsSpecialized
359*d415bd75Srobert              << " functions in module " << M.getName() << "\n");
360*d415bd75Srobert 
36173471bf0Spatrick   NumFuncSpecialized += NbFunctionsSpecialized;
36273471bf0Spatrick   return true;
36373471bf0Spatrick }
36473471bf0Spatrick 
removeDeadFunctions()365*d415bd75Srobert void FunctionSpecializer::removeDeadFunctions() {
366*d415bd75Srobert   for (Function *F : FullySpecialized) {
367*d415bd75Srobert     LLVM_DEBUG(dbgs() << "FnSpecialization: Removing dead function "
368*d415bd75Srobert                       << F->getName() << "\n");
369*d415bd75Srobert     if (FAM)
370*d415bd75Srobert       FAM->clear(*F, F->getName());
371*d415bd75Srobert     F->eraseFromParent();
372*d415bd75Srobert   }
373*d415bd75Srobert   FullySpecialized.clear();
374*d415bd75Srobert }
37573471bf0Spatrick 
376*d415bd75Srobert // Compute the code metrics for function \p F.
analyzeFunction(Function * F)377*d415bd75Srobert CodeMetrics &FunctionSpecializer::analyzeFunction(Function *F) {
378*d415bd75Srobert   auto I = FunctionMetrics.insert({F, CodeMetrics()});
379*d415bd75Srobert   CodeMetrics &Metrics = I.first->second;
380*d415bd75Srobert   if (I.second) {
381*d415bd75Srobert     // The code metrics were not cached.
382*d415bd75Srobert     SmallPtrSet<const Value *, 32> EphValues;
383*d415bd75Srobert     CodeMetrics::collectEphemeralValues(F, &(GetAC)(*F), EphValues);
384*d415bd75Srobert     for (BasicBlock &BB : *F)
385*d415bd75Srobert       Metrics.analyzeBasicBlock(&BB, (GetTTI)(*F), EphValues);
386*d415bd75Srobert 
387*d415bd75Srobert     LLVM_DEBUG(dbgs() << "FnSpecialization: Code size of function "
388*d415bd75Srobert                       << F->getName() << " is " << Metrics.NumInsts
389*d415bd75Srobert                       << " instructions\n");
390*d415bd75Srobert   }
391*d415bd75Srobert   return Metrics;
392*d415bd75Srobert }
393*d415bd75Srobert 
394*d415bd75Srobert /// Clone the function \p F and remove the ssa_copy intrinsics added by
395*d415bd75Srobert /// the SCCPSolver in the cloned version.
cloneCandidateFunction(Function * F)396*d415bd75Srobert static Function *cloneCandidateFunction(Function *F) {
397*d415bd75Srobert   ValueToValueMapTy Mappings;
398*d415bd75Srobert   Function *Clone = CloneFunction(F, Mappings);
399*d415bd75Srobert   removeSSACopy(*Clone);
400*d415bd75Srobert   return Clone;
401*d415bd75Srobert }
402*d415bd75Srobert 
findSpecializations(Function * F,InstructionCost Cost,SmallVectorImpl<Spec> & AllSpecs,SpecMap & SM)403*d415bd75Srobert bool FunctionSpecializer::findSpecializations(Function *F, InstructionCost Cost,
404*d415bd75Srobert                                               SmallVectorImpl<Spec> &AllSpecs,
405*d415bd75Srobert                                               SpecMap &SM) {
406*d415bd75Srobert   // A mapping from a specialisation signature to the index of the respective
407*d415bd75Srobert   // entry in the all specialisation array. Used to ensure uniqueness of
408*d415bd75Srobert   // specialisations.
409*d415bd75Srobert   DenseMap<SpecSig, unsigned> UM;
410*d415bd75Srobert 
411*d415bd75Srobert   // Get a list of interesting arguments.
412*d415bd75Srobert   SmallVector<Argument *> Args;
413*d415bd75Srobert   for (Argument &Arg : F->args())
414*d415bd75Srobert     if (isArgumentInteresting(&Arg))
415*d415bd75Srobert       Args.push_back(&Arg);
416*d415bd75Srobert 
417*d415bd75Srobert   if (Args.empty())
418*d415bd75Srobert     return false;
419*d415bd75Srobert 
420*d415bd75Srobert   bool Found = false;
421*d415bd75Srobert   for (User *U : F->users()) {
422*d415bd75Srobert     if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
423*d415bd75Srobert       continue;
424*d415bd75Srobert     auto &CS = *cast<CallBase>(U);
425*d415bd75Srobert 
426*d415bd75Srobert     // The user instruction does not call our function.
427*d415bd75Srobert     if (CS.getCalledFunction() != F)
428*d415bd75Srobert       continue;
429*d415bd75Srobert 
430*d415bd75Srobert     // If the call site has attribute minsize set, that callsite won't be
431*d415bd75Srobert     // specialized.
432*d415bd75Srobert     if (CS.hasFnAttr(Attribute::MinSize))
433*d415bd75Srobert       continue;
434*d415bd75Srobert 
435*d415bd75Srobert     // If the parent of the call site will never be executed, we don't need
436*d415bd75Srobert     // to worry about the passed value.
437*d415bd75Srobert     if (!Solver.isBlockExecutable(CS.getParent()))
438*d415bd75Srobert       continue;
439*d415bd75Srobert 
440*d415bd75Srobert     // Examine arguments and create a specialisation candidate from the
441*d415bd75Srobert     // constant operands of this call site.
442*d415bd75Srobert     SpecSig S;
443*d415bd75Srobert     for (Argument *A : Args) {
444*d415bd75Srobert       Constant *C = getCandidateConstant(CS.getArgOperand(A->getArgNo()));
445*d415bd75Srobert       if (!C)
446*d415bd75Srobert         continue;
447*d415bd75Srobert       LLVM_DEBUG(dbgs() << "FnSpecialization: Found interesting argument "
448*d415bd75Srobert                         << A->getName() << " : " << C->getNameOrAsOperand()
449*d415bd75Srobert                         << "\n");
450*d415bd75Srobert       S.Args.push_back({A, C});
451*d415bd75Srobert     }
452*d415bd75Srobert 
453*d415bd75Srobert     if (S.Args.empty())
454*d415bd75Srobert       continue;
455*d415bd75Srobert 
456*d415bd75Srobert     // Check if we have encountered the same specialisation already.
457*d415bd75Srobert     if (auto It = UM.find(S); It != UM.end()) {
458*d415bd75Srobert       // Existing specialisation. Add the call to the list to rewrite, unless
459*d415bd75Srobert       // it's a recursive call. A specialisation, generated because of a
460*d415bd75Srobert       // recursive call may end up as not the best specialisation for all
461*d415bd75Srobert       // the cloned instances of this call, which result from specialising
462*d415bd75Srobert       // functions. Hence we don't rewrite the call directly, but match it with
463*d415bd75Srobert       // the best specialisation once all specialisations are known.
464*d415bd75Srobert       if (CS.getFunction() == F)
465*d415bd75Srobert         continue;
466*d415bd75Srobert       const unsigned Index = It->second;
467*d415bd75Srobert       AllSpecs[Index].CallSites.push_back(&CS);
468*d415bd75Srobert     } else {
469*d415bd75Srobert       // Calculate the specialisation gain.
470*d415bd75Srobert       InstructionCost Gain = 0 - Cost;
471*d415bd75Srobert       for (ArgInfo &A : S.Args)
472*d415bd75Srobert         Gain +=
473*d415bd75Srobert             getSpecializationBonus(A.Formal, A.Actual, Solver.getLoopInfo(*F));
474*d415bd75Srobert 
475*d415bd75Srobert       // Discard unprofitable specialisations.
476*d415bd75Srobert       if (!ForceFunctionSpecialization && Gain <= 0)
477*d415bd75Srobert         continue;
478*d415bd75Srobert 
479*d415bd75Srobert       // Create a new specialisation entry.
480*d415bd75Srobert       auto &Spec = AllSpecs.emplace_back(F, S, Gain);
481*d415bd75Srobert       if (CS.getFunction() != F)
482*d415bd75Srobert         Spec.CallSites.push_back(&CS);
483*d415bd75Srobert       const unsigned Index = AllSpecs.size() - 1;
484*d415bd75Srobert       UM[S] = Index;
485*d415bd75Srobert       if (auto [It, Inserted] = SM.try_emplace(F, Index, Index + 1); !Inserted)
486*d415bd75Srobert         It->second.second = Index + 1;
487*d415bd75Srobert       Found = true;
488*d415bd75Srobert     }
489*d415bd75Srobert   }
490*d415bd75Srobert 
491*d415bd75Srobert   return Found;
492*d415bd75Srobert }
493*d415bd75Srobert 
isCandidateFunction(Function * F)494*d415bd75Srobert bool FunctionSpecializer::isCandidateFunction(Function *F) {
495*d415bd75Srobert   if (F->isDeclaration())
496*d415bd75Srobert     return false;
497*d415bd75Srobert 
498*d415bd75Srobert   if (F->hasFnAttribute(Attribute::NoDuplicate))
499*d415bd75Srobert     return false;
500*d415bd75Srobert 
501*d415bd75Srobert   if (!Solver.isArgumentTrackedFunction(F))
502*d415bd75Srobert     return false;
50373471bf0Spatrick 
50473471bf0Spatrick   // Do not specialize the cloned function again.
505*d415bd75Srobert   if (SpecializedFuncs.contains(F))
50673471bf0Spatrick     return false;
50773471bf0Spatrick 
50873471bf0Spatrick   // If we're optimizing the function for size, we shouldn't specialize it.
50973471bf0Spatrick   if (F->hasOptSize() ||
51073471bf0Spatrick       shouldOptimizeForSize(F, nullptr, nullptr, PGSOQueryType::IRPass))
51173471bf0Spatrick     return false;
51273471bf0Spatrick 
51373471bf0Spatrick   // Exit if the function is not executable. There's no point in specializing
51473471bf0Spatrick   // a dead function.
51573471bf0Spatrick   if (!Solver.isBlockExecutable(&F->getEntryBlock()))
51673471bf0Spatrick     return false;
51773471bf0Spatrick 
518*d415bd75Srobert   // It wastes time to specialize a function which would get inlined finally.
519*d415bd75Srobert   if (F->hasFnAttribute(Attribute::AlwaysInline))
520*d415bd75Srobert     return false;
521*d415bd75Srobert 
52273471bf0Spatrick   LLVM_DEBUG(dbgs() << "FnSpecialization: Try function: " << F->getName()
52373471bf0Spatrick                     << "\n");
524*d415bd75Srobert   return true;
52573471bf0Spatrick }
52673471bf0Spatrick 
createSpecialization(Function * F,const SpecSig & S)527*d415bd75Srobert Function *FunctionSpecializer::createSpecialization(Function *F, const SpecSig &S) {
528*d415bd75Srobert   Function *Clone = cloneCandidateFunction(F);
52973471bf0Spatrick 
53073471bf0Spatrick   // Initialize the lattice state of the arguments of the function clone,
53173471bf0Spatrick   // marking the argument on which we specialized the function constant
53273471bf0Spatrick   // with the given value.
533*d415bd75Srobert   Solver.markArgInFuncSpecialization(Clone, S.Args);
534*d415bd75Srobert 
535*d415bd75Srobert   Solver.addArgumentTrackedFunction(Clone);
536*d415bd75Srobert   Solver.markBlockExecutable(&Clone->front());
53773471bf0Spatrick 
53873471bf0Spatrick   // Mark all the specialized functions
539*d415bd75Srobert   SpecializedFuncs.insert(Clone);
54073471bf0Spatrick   NbFunctionsSpecialized++;
541*d415bd75Srobert 
542*d415bd75Srobert   return Clone;
54373471bf0Spatrick }
54473471bf0Spatrick 
545*d415bd75Srobert /// Compute and return the cost of specializing function \p F.
getSpecializationCost(Function * F)546*d415bd75Srobert InstructionCost FunctionSpecializer::getSpecializationCost(Function *F) {
547*d415bd75Srobert   CodeMetrics &Metrics = analyzeFunction(F);
54873471bf0Spatrick   // If the code metrics reveal that we shouldn't duplicate the function, we
54973471bf0Spatrick   // shouldn't specialize it. Set the specialization cost to Invalid.
550*d415bd75Srobert   // Or if the lines of codes implies that this function is easy to get
551*d415bd75Srobert   // inlined so that we shouldn't specialize it.
552*d415bd75Srobert   if (Metrics.notDuplicatable || !Metrics.NumInsts.isValid() ||
553*d415bd75Srobert       (!ForceFunctionSpecialization &&
554*d415bd75Srobert        !F->hasFnAttribute(Attribute::NoInline) &&
555*d415bd75Srobert        Metrics.NumInsts < SmallFunctionThreshold))
556*d415bd75Srobert     return InstructionCost::getInvalid();
55773471bf0Spatrick 
55873471bf0Spatrick   // Otherwise, set the specialization cost to be the cost of all the
559*d415bd75Srobert   // instructions in the function.
560*d415bd75Srobert   return Metrics.NumInsts * InlineConstants::getInstrCost();
56173471bf0Spatrick }
56273471bf0Spatrick 
getUserBonus(User * U,llvm::TargetTransformInfo & TTI,const LoopInfo & LI)563*d415bd75Srobert static InstructionCost getUserBonus(User *U, llvm::TargetTransformInfo &TTI,
564*d415bd75Srobert                                     const LoopInfo &LI) {
56573471bf0Spatrick   auto *I = dyn_cast_or_null<Instruction>(U);
56673471bf0Spatrick   // If not an instruction we do not know how to evaluate.
56773471bf0Spatrick   // Keep minimum possible cost for now so that it doesnt affect
56873471bf0Spatrick   // specialization.
56973471bf0Spatrick   if (!I)
57073471bf0Spatrick     return std::numeric_limits<unsigned>::min();
57173471bf0Spatrick 
572*d415bd75Srobert   InstructionCost Cost =
573*d415bd75Srobert       TTI.getInstructionCost(U, TargetTransformInfo::TCK_SizeAndLatency);
574*d415bd75Srobert 
575*d415bd75Srobert   // Increase the cost if it is inside the loop.
576*d415bd75Srobert   unsigned LoopDepth = LI.getLoopDepth(I->getParent());
577*d415bd75Srobert   Cost *= std::pow((double)AvgLoopIterationCount, LoopDepth);
57873471bf0Spatrick 
57973471bf0Spatrick   // Traverse recursively if there are more uses.
58073471bf0Spatrick   // TODO: Any other instructions to be added here?
58173471bf0Spatrick   if (I->mayReadFromMemory() || I->isCast())
58273471bf0Spatrick     for (auto *User : I->users())
58373471bf0Spatrick       Cost += getUserBonus(User, TTI, LI);
58473471bf0Spatrick 
58573471bf0Spatrick   return Cost;
58673471bf0Spatrick }
58773471bf0Spatrick 
58873471bf0Spatrick /// Compute a bonus for replacing argument \p A with constant \p C.
589*d415bd75Srobert InstructionCost
getSpecializationBonus(Argument * A,Constant * C,const LoopInfo & LI)590*d415bd75Srobert FunctionSpecializer::getSpecializationBonus(Argument *A, Constant *C,
591*d415bd75Srobert                                             const LoopInfo &LI) {
59273471bf0Spatrick   Function *F = A->getParent();
59373471bf0Spatrick   auto &TTI = (GetTTI)(*F);
594*d415bd75Srobert   LLVM_DEBUG(dbgs() << "FnSpecialization: Analysing bonus for constant: "
595*d415bd75Srobert                     << C->getNameOrAsOperand() << "\n");
59673471bf0Spatrick 
59773471bf0Spatrick   InstructionCost TotalCost = 0;
59873471bf0Spatrick   for (auto *U : A->users()) {
59973471bf0Spatrick     TotalCost += getUserBonus(U, TTI, LI);
60073471bf0Spatrick     LLVM_DEBUG(dbgs() << "FnSpecialization:   User cost ";
60173471bf0Spatrick                TotalCost.print(dbgs()); dbgs() << " for: " << *U << "\n");
60273471bf0Spatrick   }
60373471bf0Spatrick 
60473471bf0Spatrick   // The below heuristic is only concerned with exposing inlining
60573471bf0Spatrick   // opportunities via indirect call promotion. If the argument is not a
606*d415bd75Srobert   // (potentially casted) function pointer, give up.
607*d415bd75Srobert   Function *CalledFunction = dyn_cast<Function>(C->stripPointerCasts());
60873471bf0Spatrick   if (!CalledFunction)
60973471bf0Spatrick     return TotalCost;
61073471bf0Spatrick 
61173471bf0Spatrick   // Get TTI for the called function (used for the inline cost).
61273471bf0Spatrick   auto &CalleeTTI = (GetTTI)(*CalledFunction);
61373471bf0Spatrick 
61473471bf0Spatrick   // Look at all the call sites whose called value is the argument.
61573471bf0Spatrick   // Specializing the function on the argument would allow these indirect
61673471bf0Spatrick   // calls to be promoted to direct calls. If the indirect call promotion
61773471bf0Spatrick   // would likely enable the called function to be inlined, specializing is a
61873471bf0Spatrick   // good idea.
61973471bf0Spatrick   int Bonus = 0;
62073471bf0Spatrick   for (User *U : A->users()) {
62173471bf0Spatrick     if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
62273471bf0Spatrick       continue;
62373471bf0Spatrick     auto *CS = cast<CallBase>(U);
62473471bf0Spatrick     if (CS->getCalledOperand() != A)
62573471bf0Spatrick       continue;
626*d415bd75Srobert     if (CS->getFunctionType() != CalledFunction->getFunctionType())
627*d415bd75Srobert       continue;
62873471bf0Spatrick 
62973471bf0Spatrick     // Get the cost of inlining the called function at this call site. Note
63073471bf0Spatrick     // that this is only an estimate. The called function may eventually
63173471bf0Spatrick     // change in a way that leads to it not being inlined here, even though
63273471bf0Spatrick     // inlining looks profitable now. For example, one of its called
63373471bf0Spatrick     // functions may be inlined into it, making the called function too large
63473471bf0Spatrick     // to be inlined into this call site.
63573471bf0Spatrick     //
63673471bf0Spatrick     // We apply a boost for performing indirect call promotion by increasing
63773471bf0Spatrick     // the default threshold by the threshold for indirect calls.
63873471bf0Spatrick     auto Params = getInlineParams();
63973471bf0Spatrick     Params.DefaultThreshold += InlineConstants::IndirectCallThreshold;
64073471bf0Spatrick     InlineCost IC =
64173471bf0Spatrick         getInlineCost(*CS, CalledFunction, Params, CalleeTTI, GetAC, GetTLI);
64273471bf0Spatrick 
64373471bf0Spatrick     // We clamp the bonus for this call to be between zero and the default
64473471bf0Spatrick     // threshold.
64573471bf0Spatrick     if (IC.isAlways())
64673471bf0Spatrick       Bonus += Params.DefaultThreshold;
64773471bf0Spatrick     else if (IC.isVariable() && IC.getCostDelta() > 0)
64873471bf0Spatrick       Bonus += IC.getCostDelta();
649*d415bd75Srobert 
650*d415bd75Srobert     LLVM_DEBUG(dbgs() << "FnSpecialization:   Inlining bonus " << Bonus
651*d415bd75Srobert                       << " for user " << *U << "\n");
65273471bf0Spatrick   }
65373471bf0Spatrick 
65473471bf0Spatrick   return TotalCost + Bonus;
65573471bf0Spatrick }
65673471bf0Spatrick 
657*d415bd75Srobert /// Determine if it is possible to specialise the function for constant values
658*d415bd75Srobert /// of the formal parameter \p A.
isArgumentInteresting(Argument * A)659*d415bd75Srobert bool FunctionSpecializer::isArgumentInteresting(Argument *A) {
660*d415bd75Srobert   // No point in specialization if the argument is unused.
661*d415bd75Srobert   if (A->user_empty())
662*d415bd75Srobert     return false;
66373471bf0Spatrick 
66473471bf0Spatrick   // For now, don't attempt to specialize functions based on the values of
66573471bf0Spatrick   // composite types.
666*d415bd75Srobert   Type *ArgTy = A->getType();
667*d415bd75Srobert   if (!ArgTy->isSingleValueType())
66873471bf0Spatrick     return false;
66973471bf0Spatrick 
670*d415bd75Srobert   // Specialization of integer and floating point types needs to be explicitly
671*d415bd75Srobert   // enabled.
672*d415bd75Srobert   if (!EnableSpecializationForLiteralConstant &&
673*d415bd75Srobert       (ArgTy->isIntegerTy() || ArgTy->isFloatingPointTy()))
674*d415bd75Srobert     return false;
675*d415bd75Srobert 
676*d415bd75Srobert   // SCCP solver does not record an argument that will be constructed on
677*d415bd75Srobert   // stack.
678*d415bd75Srobert   if (A->hasByValAttr() && !A->getParent()->onlyReadsMemory())
679*d415bd75Srobert     return false;
680*d415bd75Srobert 
681*d415bd75Srobert   // Check the lattice value and decide if we should attemt to specialize,
682*d415bd75Srobert   // based on this argument. No point in specialization, if the lattice value
683*d415bd75Srobert   // is already a constant.
684*d415bd75Srobert   const ValueLatticeElement &LV = Solver.getLatticeValueFor(A);
685*d415bd75Srobert   if (LV.isUnknownOrUndef() || LV.isConstant() ||
686*d415bd75Srobert       (LV.isConstantRange() && LV.getConstantRange().isSingleElement())) {
687*d415bd75Srobert     LLVM_DEBUG(dbgs() << "FnSpecialization: Nothing to do, parameter "
688*d415bd75Srobert                       << A->getNameOrAsOperand() << " is already constant\n");
68973471bf0Spatrick     return false;
69073471bf0Spatrick   }
69173471bf0Spatrick 
692*d415bd75Srobert   LLVM_DEBUG(dbgs() << "FnSpecialization: Found interesting parameter "
693*d415bd75Srobert                     << A->getNameOrAsOperand() << "\n");
69473471bf0Spatrick 
69573471bf0Spatrick   return true;
69673471bf0Spatrick }
69773471bf0Spatrick 
698*d415bd75Srobert /// Check if the valuy \p V  (an actual argument) is a constant or can only
699*d415bd75Srobert /// have a constant value. Return that constant.
getCandidateConstant(Value * V)700*d415bd75Srobert Constant *FunctionSpecializer::getCandidateConstant(Value *V) {
701*d415bd75Srobert   if (isa<PoisonValue>(V))
702*d415bd75Srobert     return nullptr;
70373471bf0Spatrick 
70473471bf0Spatrick   // TrackValueOfGlobalVariable only tracks scalar global variables.
70573471bf0Spatrick   if (auto *GV = dyn_cast<GlobalVariable>(V)) {
706*d415bd75Srobert     // Check if we want to specialize on the address of non-constant
707*d415bd75Srobert     // global values.
708*d415bd75Srobert     if (!GV->isConstant() && !SpecializeOnAddresses)
709*d415bd75Srobert       return nullptr;
710*d415bd75Srobert 
711*d415bd75Srobert     if (!GV->getValueType()->isSingleValueType())
712*d415bd75Srobert       return nullptr;
71373471bf0Spatrick   }
71473471bf0Spatrick 
715*d415bd75Srobert   // Select for possible specialisation values that are constants or
716*d415bd75Srobert   // are deduced to be constants or constant ranges with a single element.
717*d415bd75Srobert   Constant *C = dyn_cast<Constant>(V);
718*d415bd75Srobert   if (!C) {
719*d415bd75Srobert     const ValueLatticeElement &LV = Solver.getLatticeValueFor(V);
720*d415bd75Srobert     if (LV.isConstant())
721*d415bd75Srobert       C = LV.getConstant();
722*d415bd75Srobert     else if (LV.isConstantRange() && LV.getConstantRange().isSingleElement()) {
723*d415bd75Srobert       assert(V->getType()->isIntegerTy() && "Non-integral constant range");
724*d415bd75Srobert       C = Constant::getIntegerValue(V->getType(),
725*d415bd75Srobert                                     *LV.getConstantRange().getSingleElement());
726*d415bd75Srobert     } else
727*d415bd75Srobert       return nullptr;
72873471bf0Spatrick   }
72973471bf0Spatrick 
730*d415bd75Srobert   return C;
73173471bf0Spatrick }
73273471bf0Spatrick 
updateCallSites(Function * F,const Spec * Begin,const Spec * End)733*d415bd75Srobert void FunctionSpecializer::updateCallSites(Function *F, const Spec *Begin,
734*d415bd75Srobert                                           const Spec *End) {
735*d415bd75Srobert   // Collect the call sites that need updating.
736*d415bd75Srobert   SmallVector<CallBase *> ToUpdate;
737*d415bd75Srobert   for (User *U : F->users())
738*d415bd75Srobert     if (auto *CS = dyn_cast<CallBase>(U);
739*d415bd75Srobert         CS && CS->getCalledFunction() == F &&
740*d415bd75Srobert         Solver.isBlockExecutable(CS->getParent()))
741*d415bd75Srobert       ToUpdate.push_back(CS);
74273471bf0Spatrick 
743*d415bd75Srobert   unsigned NCallsLeft = ToUpdate.size();
744*d415bd75Srobert   for (CallBase *CS : ToUpdate) {
745*d415bd75Srobert     bool ShouldDecrementCount = CS->getFunction() == F;
74673471bf0Spatrick 
747*d415bd75Srobert     // Find the best matching specialisation.
748*d415bd75Srobert     const Spec *BestSpec = nullptr;
749*d415bd75Srobert     for (const Spec &S : make_range(Begin, End)) {
750*d415bd75Srobert       if (!S.Clone || (BestSpec && S.Gain <= BestSpec->Gain))
75173471bf0Spatrick         continue;
75273471bf0Spatrick 
753*d415bd75Srobert       if (any_of(S.Sig.Args, [CS, this](const ArgInfo &Arg) {
754*d415bd75Srobert             unsigned ArgNo = Arg.Formal->getArgNo();
755*d415bd75Srobert             return getCandidateConstant(CS->getArgOperand(ArgNo)) != Arg.Actual;
756*d415bd75Srobert           }))
75773471bf0Spatrick         continue;
758*d415bd75Srobert 
759*d415bd75Srobert       BestSpec = &S;
76073471bf0Spatrick     }
76173471bf0Spatrick 
762*d415bd75Srobert     if (BestSpec) {
763*d415bd75Srobert       LLVM_DEBUG(dbgs() << "FnSpecialization: Redirecting " << *CS
764*d415bd75Srobert                         << " to call " << BestSpec->Clone->getName() << "\n");
765*d415bd75Srobert       CS->setCalledFunction(BestSpec->Clone);
766*d415bd75Srobert       ShouldDecrementCount = true;
76773471bf0Spatrick     }
76873471bf0Spatrick 
769*d415bd75Srobert     if (ShouldDecrementCount)
770*d415bd75Srobert       --NCallsLeft;
77173471bf0Spatrick   }
77273471bf0Spatrick 
773*d415bd75Srobert   // If the function has been completely specialized, the original function
774*d415bd75Srobert   // is no longer needed. Mark it unreachable.
775*d415bd75Srobert   if (NCallsLeft == 0) {
776*d415bd75Srobert     Solver.markFunctionUnreachable(F);
777*d415bd75Srobert     FullySpecialized.insert(F);
77873471bf0Spatrick   }
77973471bf0Spatrick }
780