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 // - Only 1 argument per function is specialised,
23 // - The cost-model could be further looked into (it mainly focuses on inlining
24 //   benefits),
25 // - We are not yet caching analysis results, but profiling and checking where
26 //   extra compile time is spent didn't suggest this to be a problem.
27 //
28 // Ideas:
29 // - With a function specialization attribute for arguments, we could have
30 //   a direct way to steer function specialization, avoiding the cost-model,
31 //   and thus control compile-times / code-size.
32 //
33 // Todos:
34 // - Specializing recursive functions relies on running the transformation a
35 //   number of times, which is controlled by option
36 //   `func-specialization-max-iters`. Thus, increasing this value and the
37 //   number of iterations, will linearly increase the number of times recursive
38 //   functions get specialized, see also the discussion in
39 //   https://reviews.llvm.org/D106426 for details. Perhaps there is a
40 //   compile-time friendlier way to control/limit the number of specialisations
41 //   for recursive functions.
42 // - Don't transform the function if function specialization does not trigger;
43 //   the SCCPSolver may make IR changes.
44 //
45 // References:
46 // - 2021 LLVM Dev Mtg “Introducing function specialisation, and can we enable
47 //   it by default?”, https://www.youtube.com/watch?v=zJiCjeXgV5Q
48 //
49 //===----------------------------------------------------------------------===//
50 
51 #include "llvm/ADT/Statistic.h"
52 #include "llvm/Analysis/AssumptionCache.h"
53 #include "llvm/Analysis/CodeMetrics.h"
54 #include "llvm/Analysis/DomTreeUpdater.h"
55 #include "llvm/Analysis/InlineCost.h"
56 #include "llvm/Analysis/LoopInfo.h"
57 #include "llvm/Analysis/TargetLibraryInfo.h"
58 #include "llvm/Analysis/TargetTransformInfo.h"
59 #include "llvm/Transforms/Scalar/SCCP.h"
60 #include "llvm/Transforms/Utils/Cloning.h"
61 #include "llvm/Transforms/Utils/SizeOpts.h"
62 #include <cmath>
63 
64 using namespace llvm;
65 
66 #define DEBUG_TYPE "function-specialization"
67 
68 STATISTIC(NumFuncSpecialized, "Number of functions specialized");
69 
70 static cl::opt<bool> ForceFunctionSpecialization(
71     "force-function-specialization", cl::init(false), cl::Hidden,
72     cl::desc("Force function specialization for every call site with a "
73              "constant argument"));
74 
75 static cl::opt<unsigned> FuncSpecializationMaxIters(
76     "func-specialization-max-iters", cl::Hidden,
77     cl::desc("The maximum number of iterations function specialization is run"),
78     cl::init(1));
79 
80 static cl::opt<unsigned> MaxClonesThreshold(
81     "func-specialization-max-clones", cl::Hidden,
82     cl::desc("The maximum number of clones allowed for a single function "
83              "specialization"),
84     cl::init(3));
85 
86 static cl::opt<unsigned> SmallFunctionThreshold(
87     "func-specialization-size-threshold", cl::Hidden,
88     cl::desc("Don't specialize functions that have less than this theshold "
89              "number of instructions"),
90     cl::init(100));
91 
92 static cl::opt<unsigned>
93     AvgLoopIterationCount("func-specialization-avg-iters-cost", cl::Hidden,
94                           cl::desc("Average loop iteration count cost"),
95                           cl::init(10));
96 
97 static cl::opt<bool> SpecializeOnAddresses(
98     "func-specialization-on-address", cl::init(false), cl::Hidden,
99     cl::desc("Enable function specialization on the address of global values"));
100 
101 // TODO: This needs checking to see the impact on compile-times, which is why
102 // this is off by default for now.
103 static cl::opt<bool> EnableSpecializationForLiteralConstant(
104     "function-specialization-for-literal-constant", cl::init(false), cl::Hidden,
105     cl::desc("Enable specialization of functions that take a literal constant "
106              "as an argument."));
107 
108 namespace {
109 // Bookkeeping struct to pass data from the analysis and profitability phase
110 // to the actual transform helper functions.
111 struct ArgInfo {
112   Function *Fn;         // The function to perform specialisation on.
113   Argument *Arg;        // The Formal argument being analysed.
114   Constant *Const;      // A corresponding actual constant argument.
115   InstructionCost Gain; // Profitability: Gain = Bonus - Cost.
116 
117   // Flag if this will be a partial specialization, in which case we will need
118   // to keep the original function around in addition to the added
119   // specializations.
120   bool Partial = false;
121 
122   ArgInfo(Function *F, Argument *A, Constant *C, InstructionCost G)
123       : Fn(F), Arg(A), Const(C), Gain(G){};
124 };
125 } // Anonymous namespace
126 
127 using FuncList = SmallVectorImpl<Function *>;
128 using ConstList = SmallVectorImpl<Constant *>;
129 
130 // Helper to check if \p LV is either a constant or a constant
131 // range with a single element. This should cover exactly the same cases as the
132 // old ValueLatticeElement::isConstant() and is intended to be used in the
133 // transition to ValueLatticeElement.
134 static bool isConstant(const ValueLatticeElement &LV) {
135   return LV.isConstant() ||
136          (LV.isConstantRange() && LV.getConstantRange().isSingleElement());
137 }
138 
139 // Helper to check if \p LV is either overdefined or a constant int.
140 static bool isOverdefined(const ValueLatticeElement &LV) {
141   return !LV.isUnknownOrUndef() && !isConstant(LV);
142 }
143 
144 static Constant *getPromotableAlloca(AllocaInst *Alloca, CallInst *Call) {
145   Value *StoreValue = nullptr;
146   for (auto *User : Alloca->users()) {
147     // We can't use llvm::isAllocaPromotable() as that would fail because of
148     // the usage in the CallInst, which is what we check here.
149     if (User == Call)
150       continue;
151     if (auto *Bitcast = dyn_cast<BitCastInst>(User)) {
152       if (!Bitcast->hasOneUse() || *Bitcast->user_begin() != Call)
153         return nullptr;
154       continue;
155     }
156 
157     if (auto *Store = dyn_cast<StoreInst>(User)) {
158       // This is a duplicate store, bail out.
159       if (StoreValue || Store->isVolatile())
160         return nullptr;
161       StoreValue = Store->getValueOperand();
162       continue;
163     }
164     // Bail if there is any other unknown usage.
165     return nullptr;
166   }
167   return dyn_cast_or_null<Constant>(StoreValue);
168 }
169 
170 // A constant stack value is an AllocaInst that has a single constant
171 // value stored to it. Return this constant if such an alloca stack value
172 // is a function argument.
173 static Constant *getConstantStackValue(CallInst *Call, Value *Val,
174                                        SCCPSolver &Solver) {
175   if (!Val)
176     return nullptr;
177   Val = Val->stripPointerCasts();
178   if (auto *ConstVal = dyn_cast<ConstantInt>(Val))
179     return ConstVal;
180   auto *Alloca = dyn_cast<AllocaInst>(Val);
181   if (!Alloca || !Alloca->getAllocatedType()->isIntegerTy())
182     return nullptr;
183   return getPromotableAlloca(Alloca, Call);
184 }
185 
186 // To support specializing recursive functions, it is important to propagate
187 // constant arguments because after a first iteration of specialisation, a
188 // reduced example may look like this:
189 //
190 //     define internal void @RecursiveFn(i32* arg1) {
191 //       %temp = alloca i32, align 4
192 //       store i32 2 i32* %temp, align 4
193 //       call void @RecursiveFn.1(i32* nonnull %temp)
194 //       ret void
195 //     }
196 //
197 // Before a next iteration, we need to propagate the constant like so
198 // which allows further specialization in next iterations.
199 //
200 //     @funcspec.arg = internal constant i32 2
201 //
202 //     define internal void @someFunc(i32* arg1) {
203 //       call void @otherFunc(i32* nonnull @funcspec.arg)
204 //       ret void
205 //     }
206 //
207 static void constantArgPropagation(FuncList &WorkList,
208                                    Module &M, SCCPSolver &Solver) {
209   // Iterate over the argument tracked functions see if there
210   // are any new constant values for the call instruction via
211   // stack variables.
212   for (auto *F : WorkList) {
213     // TODO: Generalize for any read only arguments.
214     if (F->arg_size() != 1)
215       continue;
216 
217     auto &Arg = *F->arg_begin();
218     if (!Arg.onlyReadsMemory() || !Arg.getType()->isPointerTy())
219       continue;
220 
221     for (auto *User : F->users()) {
222       auto *Call = dyn_cast<CallInst>(User);
223       if (!Call)
224         break;
225       auto *ArgOp = Call->getArgOperand(0);
226       auto *ArgOpType = ArgOp->getType();
227       auto *ConstVal = getConstantStackValue(Call, ArgOp, Solver);
228       if (!ConstVal)
229         break;
230 
231       Value *GV = new GlobalVariable(M, ConstVal->getType(), true,
232                                      GlobalValue::InternalLinkage, ConstVal,
233                                      "funcspec.arg");
234 
235       if (ArgOpType != ConstVal->getType())
236         GV = ConstantExpr::getBitCast(cast<Constant>(GV), ArgOp->getType());
237 
238       Call->setArgOperand(0, GV);
239 
240       // Add the changed CallInst to Solver Worklist
241       Solver.visitCall(*Call);
242     }
243   }
244 }
245 
246 // ssa_copy intrinsics are introduced by the SCCP solver. These intrinsics
247 // interfere with the constantArgPropagation optimization.
248 static void removeSSACopy(Function &F) {
249   for (BasicBlock &BB : F) {
250     for (Instruction &Inst : llvm::make_early_inc_range(BB)) {
251       auto *II = dyn_cast<IntrinsicInst>(&Inst);
252       if (!II)
253         continue;
254       if (II->getIntrinsicID() != Intrinsic::ssa_copy)
255         continue;
256       Inst.replaceAllUsesWith(II->getOperand(0));
257       Inst.eraseFromParent();
258     }
259   }
260 }
261 
262 static void removeSSACopy(Module &M) {
263   for (Function &F : M)
264     removeSSACopy(F);
265 }
266 
267 namespace {
268 class FunctionSpecializer {
269 
270   /// The IPSCCP Solver.
271   SCCPSolver &Solver;
272 
273   /// Analyses used to help determine if a function should be specialized.
274   std::function<AssumptionCache &(Function &)> GetAC;
275   std::function<TargetTransformInfo &(Function &)> GetTTI;
276   std::function<TargetLibraryInfo &(Function &)> GetTLI;
277 
278   SmallPtrSet<Function *, 2> SpecializedFuncs;
279   SmallVector<Instruction *> ReplacedWithConstant;
280 
281 public:
282   FunctionSpecializer(SCCPSolver &Solver,
283                       std::function<AssumptionCache &(Function &)> GetAC,
284                       std::function<TargetTransformInfo &(Function &)> GetTTI,
285                       std::function<TargetLibraryInfo &(Function &)> GetTLI)
286       : Solver(Solver), GetAC(GetAC), GetTTI(GetTTI), GetTLI(GetTLI) {}
287 
288   /// Attempt to specialize functions in the module to enable constant
289   /// propagation across function boundaries.
290   ///
291   /// \returns true if at least one function is specialized.
292   bool
293   specializeFunctions(FuncList &FuncDecls,
294                       FuncList &CurrentSpecializations) {
295     bool Changed = false;
296     for (auto *F : FuncDecls) {
297       if (!isCandidateFunction(F, CurrentSpecializations))
298         continue;
299 
300       auto Cost = getSpecializationCost(F);
301       if (!Cost.isValid()) {
302         LLVM_DEBUG(
303             dbgs() << "FnSpecialization: Invalid specialisation cost.\n");
304         continue;
305       }
306 
307       auto ConstArgs = calculateGains(F, Cost);
308       if (ConstArgs.empty()) {
309         LLVM_DEBUG(dbgs() << "FnSpecialization: no possible constants found\n");
310         continue;
311       }
312 
313       for (auto &CA : ConstArgs) {
314         specializeFunction(CA, CurrentSpecializations);
315         Changed = true;
316       }
317     }
318 
319     updateSpecializedFuncs(FuncDecls, CurrentSpecializations);
320     NumFuncSpecialized += NbFunctionsSpecialized;
321     return Changed;
322   }
323 
324   void removeDeadInstructions() {
325     for (auto *I : ReplacedWithConstant) {
326       LLVM_DEBUG(dbgs() << "FnSpecialization: Removing dead instruction "
327                         << *I << "\n");
328       I->eraseFromParent();
329     }
330     ReplacedWithConstant.clear();
331   }
332 
333   bool tryToReplaceWithConstant(Value *V) {
334     if (!V->getType()->isSingleValueType() || isa<CallBase>(V) ||
335         V->user_empty())
336       return false;
337 
338     const ValueLatticeElement &IV = Solver.getLatticeValueFor(V);
339     if (isOverdefined(IV))
340       return false;
341     auto *Const =
342         isConstant(IV) ? Solver.getConstant(IV) : UndefValue::get(V->getType());
343 
344     LLVM_DEBUG(dbgs() << "FnSpecialization: Replacing " << *V
345                       << "\nFnSpecialization: with " << *Const << "\n");
346 
347     // Record uses of V to avoid visiting irrelevant uses of const later.
348     SmallVector<Instruction *> UseInsts;
349     for (auto *U : V->users())
350       if (auto *I = dyn_cast<Instruction>(U))
351         if (Solver.isBlockExecutable(I->getParent()))
352           UseInsts.push_back(I);
353 
354     V->replaceAllUsesWith(Const);
355 
356     for (auto *I : UseInsts)
357       Solver.visit(I);
358 
359     // Remove the instruction from Block and Solver.
360     if (auto *I = dyn_cast<Instruction>(V)) {
361       if (I->isSafeToRemove()) {
362         ReplacedWithConstant.push_back(I);
363         Solver.removeLatticeValueFor(I);
364       }
365     }
366     return true;
367   }
368 
369 private:
370   // The number of functions specialised, used for collecting statistics and
371   // also in the cost model.
372   unsigned NbFunctionsSpecialized = 0;
373 
374   /// Clone the function \p F and remove the ssa_copy intrinsics added by
375   /// the SCCPSolver in the cloned version.
376   Function *cloneCandidateFunction(Function *F) {
377     ValueToValueMapTy EmptyMap;
378     Function *Clone = CloneFunction(F, EmptyMap);
379     removeSSACopy(*Clone);
380     return Clone;
381   }
382 
383   /// This function decides whether it's worthwhile to specialize function \p F
384   /// based on the known constant values its arguments can take on, i.e. it
385   /// calculates a gain and returns a list of actual arguments that are deemed
386   /// profitable to specialize. Specialization is performed on the first
387   /// interesting argument. Specializations based on additional arguments will
388   /// be evaluated on following iterations of the main IPSCCP solve loop.
389   SmallVector<ArgInfo> calculateGains(Function *F, InstructionCost Cost) {
390     SmallVector<ArgInfo> Worklist;
391     // Determine if we should specialize the function based on the values the
392     // argument can take on. If specialization is not profitable, we continue
393     // on to the next argument.
394     for (Argument &FormalArg : F->args()) {
395       LLVM_DEBUG(dbgs() << "FnSpecialization: Analysing arg: "
396                         << FormalArg.getName() << "\n");
397       // Determine if this argument is interesting. If we know the argument can
398       // take on any constant values, they are collected in Constants. If the
399       // argument can only ever equal a constant value in Constants, the
400       // function will be completely specialized, and the IsPartial flag will
401       // be set to false by isArgumentInteresting (that function only adds
402       // values to the Constants list that are deemed profitable).
403       bool IsPartial = true;
404       SmallVector<Constant *> ActualConstArg;
405       if (!isArgumentInteresting(&FormalArg, ActualConstArg, IsPartial)) {
406         LLVM_DEBUG(dbgs() << "FnSpecialization: Argument is not interesting\n");
407         continue;
408       }
409 
410       for (auto *ActualArg : ActualConstArg) {
411         InstructionCost Gain =
412             ForceFunctionSpecialization
413                 ? 1
414                 : getSpecializationBonus(&FormalArg, ActualArg) - Cost;
415 
416         if (Gain <= 0)
417           continue;
418         Worklist.push_back({F, &FormalArg, ActualArg, Gain});
419       }
420 
421       if (Worklist.empty())
422         continue;
423 
424       // Sort the candidates in descending order.
425       llvm::stable_sort(Worklist, [](const ArgInfo &L, const ArgInfo &R) {
426         return L.Gain > R.Gain;
427       });
428 
429       // Truncate the worklist to 'MaxClonesThreshold' candidates if
430       // necessary.
431       if (Worklist.size() > MaxClonesThreshold) {
432         LLVM_DEBUG(dbgs() << "FnSpecialization: number of candidates exceed "
433                     << "the maximum number of clones threshold.\n"
434                     << "Truncating worklist to " << MaxClonesThreshold
435                     << " candidates.\n");
436         Worklist.erase(Worklist.begin() + MaxClonesThreshold,
437                        Worklist.end());
438       }
439 
440       if (IsPartial || Worklist.size() < ActualConstArg.size())
441         for (auto &ActualArg : Worklist)
442           ActualArg.Partial = true;
443 
444       LLVM_DEBUG(dbgs() << "Sorted list of candidates by gain:\n";
445                  for (auto &C
446                       : Worklist) {
447                    dbgs() << "- Function = " << C.Fn->getName() << ", ";
448                    dbgs() << "FormalArg = " << C.Arg->getName() << ", ";
449                    dbgs() << "ActualArg = " << C.Const->getName() << ", ";
450                    dbgs() << "Gain = " << C.Gain << "\n";
451                  });
452 
453       // FIXME: Only one argument per function.
454       break;
455     }
456     return Worklist;
457   }
458 
459   bool isCandidateFunction(Function *F, FuncList &Specializations) {
460     // Do not specialize the cloned function again.
461     if (SpecializedFuncs.contains(F))
462       return false;
463 
464     // If we're optimizing the function for size, we shouldn't specialize it.
465     if (F->hasOptSize() ||
466         shouldOptimizeForSize(F, nullptr, nullptr, PGSOQueryType::IRPass))
467       return false;
468 
469     // Exit if the function is not executable. There's no point in specializing
470     // a dead function.
471     if (!Solver.isBlockExecutable(&F->getEntryBlock()))
472       return false;
473 
474     // It wastes time to specialize a function which would get inlined finally.
475     if (F->hasFnAttribute(Attribute::AlwaysInline))
476       return false;
477 
478     LLVM_DEBUG(dbgs() << "FnSpecialization: Try function: " << F->getName()
479                       << "\n");
480     return true;
481   }
482 
483   void specializeFunction(ArgInfo &AI, FuncList &Specializations) {
484     Function *Clone = cloneCandidateFunction(AI.Fn);
485     Argument *ClonedArg = Clone->getArg(AI.Arg->getArgNo());
486 
487     // Rewrite calls to the function so that they call the clone instead.
488     rewriteCallSites(AI.Fn, Clone, *ClonedArg, AI.Const);
489 
490     // Initialize the lattice state of the arguments of the function clone,
491     // marking the argument on which we specialized the function constant
492     // with the given value.
493     Solver.markArgInFuncSpecialization(AI.Fn, ClonedArg, AI.Const);
494 
495     // Mark all the specialized functions
496     Specializations.push_back(Clone);
497     NbFunctionsSpecialized++;
498 
499     // If the function has been completely specialized, the original function
500     // is no longer needed. Mark it unreachable.
501     if (!AI.Partial)
502       Solver.markFunctionUnreachable(AI.Fn);
503   }
504 
505   /// Compute and return the cost of specializing function \p F.
506   InstructionCost getSpecializationCost(Function *F) {
507     // Compute the code metrics for the function.
508     SmallPtrSet<const Value *, 32> EphValues;
509     CodeMetrics::collectEphemeralValues(F, &(GetAC)(*F), EphValues);
510     CodeMetrics Metrics;
511     for (BasicBlock &BB : *F)
512       Metrics.analyzeBasicBlock(&BB, (GetTTI)(*F), EphValues);
513 
514     // If the code metrics reveal that we shouldn't duplicate the function, we
515     // shouldn't specialize it. Set the specialization cost to Invalid.
516     // Or if the lines of codes implies that this function is easy to get
517     // inlined so that we shouldn't specialize it.
518     if (Metrics.notDuplicatable ||
519         (!ForceFunctionSpecialization &&
520          Metrics.NumInsts < SmallFunctionThreshold)) {
521       InstructionCost C{};
522       C.setInvalid();
523       return C;
524     }
525 
526     // Otherwise, set the specialization cost to be the cost of all the
527     // instructions in the function and penalty for specializing more functions.
528     unsigned Penalty = NbFunctionsSpecialized + 1;
529     return Metrics.NumInsts * InlineConstants::InstrCost * Penalty;
530   }
531 
532   InstructionCost getUserBonus(User *U, llvm::TargetTransformInfo &TTI,
533                                LoopInfo &LI) {
534     auto *I = dyn_cast_or_null<Instruction>(U);
535     // If not an instruction we do not know how to evaluate.
536     // Keep minimum possible cost for now so that it doesnt affect
537     // specialization.
538     if (!I)
539       return std::numeric_limits<unsigned>::min();
540 
541     auto Cost = TTI.getUserCost(U, TargetTransformInfo::TCK_SizeAndLatency);
542 
543     // Traverse recursively if there are more uses.
544     // TODO: Any other instructions to be added here?
545     if (I->mayReadFromMemory() || I->isCast())
546       for (auto *User : I->users())
547         Cost += getUserBonus(User, TTI, LI);
548 
549     // Increase the cost if it is inside the loop.
550     auto LoopDepth = LI.getLoopDepth(I->getParent());
551     Cost *= std::pow((double)AvgLoopIterationCount, LoopDepth);
552     return Cost;
553   }
554 
555   /// Compute a bonus for replacing argument \p A with constant \p C.
556   InstructionCost getSpecializationBonus(Argument *A, Constant *C) {
557     Function *F = A->getParent();
558     DominatorTree DT(*F);
559     LoopInfo LI(DT);
560     auto &TTI = (GetTTI)(*F);
561     LLVM_DEBUG(dbgs() << "FnSpecialization: Analysing bonus for: " << *A
562                       << "\n");
563 
564     InstructionCost TotalCost = 0;
565     for (auto *U : A->users()) {
566       TotalCost += getUserBonus(U, TTI, LI);
567       LLVM_DEBUG(dbgs() << "FnSpecialization: User cost ";
568                  TotalCost.print(dbgs()); dbgs() << " for: " << *U << "\n");
569     }
570 
571     // The below heuristic is only concerned with exposing inlining
572     // opportunities via indirect call promotion. If the argument is not a
573     // function pointer, give up.
574     if (!isa<PointerType>(A->getType()) ||
575         !isa<FunctionType>(A->getType()->getPointerElementType()))
576       return TotalCost;
577 
578     // Since the argument is a function pointer, its incoming constant values
579     // should be functions or constant expressions. The code below attempts to
580     // look through cast expressions to find the function that will be called.
581     Value *CalledValue = C;
582     while (isa<ConstantExpr>(CalledValue) &&
583            cast<ConstantExpr>(CalledValue)->isCast())
584       CalledValue = cast<User>(CalledValue)->getOperand(0);
585     Function *CalledFunction = dyn_cast<Function>(CalledValue);
586     if (!CalledFunction)
587       return TotalCost;
588 
589     // Get TTI for the called function (used for the inline cost).
590     auto &CalleeTTI = (GetTTI)(*CalledFunction);
591 
592     // Look at all the call sites whose called value is the argument.
593     // Specializing the function on the argument would allow these indirect
594     // calls to be promoted to direct calls. If the indirect call promotion
595     // would likely enable the called function to be inlined, specializing is a
596     // good idea.
597     int Bonus = 0;
598     for (User *U : A->users()) {
599       if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
600         continue;
601       auto *CS = cast<CallBase>(U);
602       if (CS->getCalledOperand() != A)
603         continue;
604 
605       // Get the cost of inlining the called function at this call site. Note
606       // that this is only an estimate. The called function may eventually
607       // change in a way that leads to it not being inlined here, even though
608       // inlining looks profitable now. For example, one of its called
609       // functions may be inlined into it, making the called function too large
610       // to be inlined into this call site.
611       //
612       // We apply a boost for performing indirect call promotion by increasing
613       // the default threshold by the threshold for indirect calls.
614       auto Params = getInlineParams();
615       Params.DefaultThreshold += InlineConstants::IndirectCallThreshold;
616       InlineCost IC =
617           getInlineCost(*CS, CalledFunction, Params, CalleeTTI, GetAC, GetTLI);
618 
619       // We clamp the bonus for this call to be between zero and the default
620       // threshold.
621       if (IC.isAlways())
622         Bonus += Params.DefaultThreshold;
623       else if (IC.isVariable() && IC.getCostDelta() > 0)
624         Bonus += IC.getCostDelta();
625     }
626 
627     return TotalCost + Bonus;
628   }
629 
630   /// Determine if we should specialize a function based on the incoming values
631   /// of the given argument.
632   ///
633   /// This function implements the goal-directed heuristic. It determines if
634   /// specializing the function based on the incoming values of argument \p A
635   /// would result in any significant optimization opportunities. If
636   /// optimization opportunities exist, the constant values of \p A on which to
637   /// specialize the function are collected in \p Constants. If the values in
638   /// \p Constants represent the complete set of values that \p A can take on,
639   /// the function will be completely specialized, and the \p IsPartial flag is
640   /// set to false.
641   ///
642   /// \returns true if the function should be specialized on the given
643   /// argument.
644   bool isArgumentInteresting(Argument *A, ConstList &Constants,
645                              bool &IsPartial) {
646     // For now, don't attempt to specialize functions based on the values of
647     // composite types.
648     if (!A->getType()->isSingleValueType() || A->user_empty())
649       return false;
650 
651     // If the argument isn't overdefined, there's nothing to do. It should
652     // already be constant.
653     if (!Solver.getLatticeValueFor(A).isOverdefined()) {
654       LLVM_DEBUG(dbgs() << "FnSpecialization: nothing to do, arg is already "
655                         << "constant?\n");
656       return false;
657     }
658 
659     // Collect the constant values that the argument can take on. If the
660     // argument can't take on any constant values, we aren't going to
661     // specialize the function. While it's possible to specialize the function
662     // based on non-constant arguments, there's likely not much benefit to
663     // constant propagation in doing so.
664     //
665     // TODO 1: currently it won't specialize if there are over the threshold of
666     // calls using the same argument, e.g foo(a) x 4 and foo(b) x 1, but it
667     // might be beneficial to take the occurrences into account in the cost
668     // model, so we would need to find the unique constants.
669     //
670     // TODO 2: this currently does not support constants, i.e. integer ranges.
671     //
672     IsPartial = !getPossibleConstants(A, Constants);
673     LLVM_DEBUG(dbgs() << "FnSpecialization: interesting arg: " << *A << "\n");
674     return true;
675   }
676 
677   /// Collect in \p Constants all the constant values that argument \p A can
678   /// take on.
679   ///
680   /// \returns true if all of the values the argument can take on are constant
681   /// (e.g., the argument's parent function cannot be called with an
682   /// overdefined value).
683   bool getPossibleConstants(Argument *A, ConstList &Constants) {
684     Function *F = A->getParent();
685     bool AllConstant = true;
686 
687     // Iterate over all the call sites of the argument's parent function.
688     for (User *U : F->users()) {
689       if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
690         continue;
691       auto &CS = *cast<CallBase>(U);
692       // If the call site has attribute minsize set, that callsite won't be
693       // specialized.
694       if (CS.hasFnAttr(Attribute::MinSize)) {
695         AllConstant = false;
696         continue;
697       }
698 
699       // If the parent of the call site will never be executed, we don't need
700       // to worry about the passed value.
701       if (!Solver.isBlockExecutable(CS.getParent()))
702         continue;
703 
704       auto *V = CS.getArgOperand(A->getArgNo());
705       if (isa<PoisonValue>(V))
706         return false;
707 
708       // For now, constant expressions are fine but only if they are function
709       // calls.
710       if (auto *CE = dyn_cast<ConstantExpr>(V))
711         if (!isa<Function>(CE->getOperand(0)))
712           return false;
713 
714       // TrackValueOfGlobalVariable only tracks scalar global variables.
715       if (auto *GV = dyn_cast<GlobalVariable>(V)) {
716         // Check if we want to specialize on the address of non-constant
717         // global values.
718         if (!GV->isConstant())
719           if (!SpecializeOnAddresses)
720             return false;
721 
722         if (!GV->getValueType()->isSingleValueType())
723           return false;
724       }
725 
726       if (isa<Constant>(V) && (Solver.getLatticeValueFor(V).isConstant() ||
727                                EnableSpecializationForLiteralConstant))
728         Constants.push_back(cast<Constant>(V));
729       else
730         AllConstant = false;
731     }
732 
733     // If the argument can only take on constant values, AllConstant will be
734     // true.
735     return AllConstant;
736   }
737 
738   /// Rewrite calls to function \p F to call function \p Clone instead.
739   ///
740   /// This function modifies calls to function \p F whose argument at index \p
741   /// ArgNo is equal to constant \p C. The calls are rewritten to call function
742   /// \p Clone instead.
743   ///
744   /// Callsites that have been marked with the MinSize function attribute won't
745   /// be specialized and rewritten.
746   void rewriteCallSites(Function *F, Function *Clone, Argument &Arg,
747                         Constant *C) {
748     unsigned ArgNo = Arg.getArgNo();
749     SmallVector<CallBase *, 4> CallSitesToRewrite;
750     for (auto *U : F->users()) {
751       if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
752         continue;
753       auto &CS = *cast<CallBase>(U);
754       if (!CS.getCalledFunction() || CS.getCalledFunction() != F)
755         continue;
756       CallSitesToRewrite.push_back(&CS);
757     }
758     for (auto *CS : CallSitesToRewrite) {
759       if ((CS->getFunction() == Clone && CS->getArgOperand(ArgNo) == &Arg) ||
760           CS->getArgOperand(ArgNo) == C) {
761         CS->setCalledFunction(Clone);
762         Solver.markOverdefined(CS);
763       }
764     }
765   }
766 
767   void updateSpecializedFuncs(FuncList &FuncDecls,
768                               FuncList &CurrentSpecializations) {
769     for (auto *SpecializedFunc : CurrentSpecializations) {
770       SpecializedFuncs.insert(SpecializedFunc);
771 
772       // Initialize the state of the newly created functions, marking them
773       // argument-tracked and executable.
774       if (SpecializedFunc->hasExactDefinition() &&
775           !SpecializedFunc->hasFnAttribute(Attribute::Naked))
776         Solver.addTrackedFunction(SpecializedFunc);
777 
778       Solver.addArgumentTrackedFunction(SpecializedFunc);
779       FuncDecls.push_back(SpecializedFunc);
780       Solver.markBlockExecutable(&SpecializedFunc->front());
781 
782       // Replace the function arguments for the specialized functions.
783       for (Argument &Arg : SpecializedFunc->args())
784         if (!Arg.use_empty() && tryToReplaceWithConstant(&Arg))
785           LLVM_DEBUG(dbgs() << "FnSpecialization: Replaced constant argument: "
786                             << Arg.getName() << "\n");
787     }
788   }
789 };
790 } // namespace
791 
792 bool llvm::runFunctionSpecialization(
793     Module &M, const DataLayout &DL,
794     std::function<TargetLibraryInfo &(Function &)> GetTLI,
795     std::function<TargetTransformInfo &(Function &)> GetTTI,
796     std::function<AssumptionCache &(Function &)> GetAC,
797     function_ref<AnalysisResultsForFn(Function &)> GetAnalysis) {
798   SCCPSolver Solver(DL, GetTLI, M.getContext());
799   FunctionSpecializer FS(Solver, GetAC, GetTTI, GetTLI);
800   bool Changed = false;
801 
802   // Loop over all functions, marking arguments to those with their addresses
803   // taken or that are external as overdefined.
804   for (Function &F : M) {
805     if (F.isDeclaration())
806       continue;
807     if (F.hasFnAttribute(Attribute::NoDuplicate))
808       continue;
809 
810     LLVM_DEBUG(dbgs() << "\nFnSpecialization: Analysing decl: " << F.getName()
811                       << "\n");
812     Solver.addAnalysis(F, GetAnalysis(F));
813 
814     // Determine if we can track the function's arguments. If so, add the
815     // function to the solver's set of argument-tracked functions.
816     if (canTrackArgumentsInterprocedurally(&F)) {
817       LLVM_DEBUG(dbgs() << "FnSpecialization: Can track arguments\n");
818       Solver.addArgumentTrackedFunction(&F);
819       continue;
820     } else {
821       LLVM_DEBUG(dbgs() << "FnSpecialization: Can't track arguments!\n"
822                         << "FnSpecialization: Doesn't have local linkage, or "
823                         << "has its address taken\n");
824     }
825 
826     // Assume the function is called.
827     Solver.markBlockExecutable(&F.front());
828 
829     // Assume nothing about the incoming arguments.
830     for (Argument &AI : F.args())
831       Solver.markOverdefined(&AI);
832   }
833 
834   // Determine if we can track any of the module's global variables. If so, add
835   // the global variables we can track to the solver's set of tracked global
836   // variables.
837   for (GlobalVariable &G : M.globals()) {
838     G.removeDeadConstantUsers();
839     if (canTrackGlobalVariableInterprocedurally(&G))
840       Solver.trackValueOfGlobalVariable(&G);
841   }
842 
843   auto &TrackedFuncs = Solver.getArgumentTrackedFunctions();
844   SmallVector<Function *, 16> FuncDecls(TrackedFuncs.begin(),
845                                         TrackedFuncs.end());
846 
847   // No tracked functions, so nothing to do: don't run the solver and remove
848   // the ssa_copy intrinsics that may have been introduced.
849   if (TrackedFuncs.empty()) {
850     removeSSACopy(M);
851     return false;
852   }
853 
854   // Solve for constants.
855   auto RunSCCPSolver = [&](auto &WorkList) {
856     bool ResolvedUndefs = true;
857 
858     while (ResolvedUndefs) {
859       // Not running the solver unnecessary is checked in regression test
860       // nothing-to-do.ll, so if this debug message is changed, this regression
861       // test needs updating too.
862       LLVM_DEBUG(dbgs() << "FnSpecialization: Running solver\n");
863 
864       Solver.solve();
865       LLVM_DEBUG(dbgs() << "FnSpecialization: Resolving undefs\n");
866       ResolvedUndefs = false;
867       for (Function *F : WorkList)
868         if (Solver.resolvedUndefsIn(*F))
869           ResolvedUndefs = true;
870     }
871 
872     for (auto *F : WorkList) {
873       for (BasicBlock &BB : *F) {
874         if (!Solver.isBlockExecutable(&BB))
875           continue;
876         // FIXME: The solver may make changes to the function here, so set
877         // Changed, even if later function specialization does not trigger.
878         for (auto &I : make_early_inc_range(BB))
879           Changed |= FS.tryToReplaceWithConstant(&I);
880       }
881     }
882   };
883 
884 #ifndef NDEBUG
885   LLVM_DEBUG(dbgs() << "FnSpecialization: Worklist fn decls:\n");
886   for (auto *F : FuncDecls)
887     LLVM_DEBUG(dbgs() << "FnSpecialization: *) " << F->getName() << "\n");
888 #endif
889 
890   // Initially resolve the constants in all the argument tracked functions.
891   RunSCCPSolver(FuncDecls);
892 
893   SmallVector<Function *, 2> CurrentSpecializations;
894   unsigned I = 0;
895   while (FuncSpecializationMaxIters != I++ &&
896          FS.specializeFunctions(FuncDecls, CurrentSpecializations)) {
897 
898     // Run the solver for the specialized functions.
899     RunSCCPSolver(CurrentSpecializations);
900 
901     // Replace some unresolved constant arguments.
902     constantArgPropagation(FuncDecls, M, Solver);
903 
904     CurrentSpecializations.clear();
905     Changed = true;
906   }
907 
908   // Clean up the IR by removing dead instructions and ssa_copy intrinsics.
909   FS.removeDeadInstructions();
910   removeSSACopy(M);
911   return Changed;
912 }
913