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