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