xref: /src/contrib/llvm-project/llvm/lib/Transforms/IPO/FunctionSpecialization.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1344a3780SDimitry Andric //===- FunctionSpecialization.cpp - Function Specialization ---------------===//
2344a3780SDimitry Andric //
3344a3780SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4344a3780SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5344a3780SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6344a3780SDimitry Andric //
7344a3780SDimitry Andric //===----------------------------------------------------------------------===//
8344a3780SDimitry Andric 
9e3b55780SDimitry Andric #include "llvm/Transforms/IPO/FunctionSpecialization.h"
10344a3780SDimitry Andric #include "llvm/ADT/Statistic.h"
11344a3780SDimitry Andric #include "llvm/Analysis/CodeMetrics.h"
127fa27ce4SDimitry Andric #include "llvm/Analysis/ConstantFolding.h"
13344a3780SDimitry Andric #include "llvm/Analysis/InlineCost.h"
147fa27ce4SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
15344a3780SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
16145449b1SDimitry Andric #include "llvm/Analysis/ValueLattice.h"
17145449b1SDimitry Andric #include "llvm/Analysis/ValueLatticeUtils.h"
187fa27ce4SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
19145449b1SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
20344a3780SDimitry Andric #include "llvm/Transforms/Scalar/SCCP.h"
21344a3780SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
22145449b1SDimitry Andric #include "llvm/Transforms/Utils/SCCPSolver.h"
23344a3780SDimitry Andric #include "llvm/Transforms/Utils/SizeOpts.h"
24344a3780SDimitry Andric #include <cmath>
25344a3780SDimitry Andric 
26344a3780SDimitry Andric using namespace llvm;
27344a3780SDimitry Andric 
28344a3780SDimitry Andric #define DEBUG_TYPE "function-specialization"
29344a3780SDimitry Andric 
307fa27ce4SDimitry Andric STATISTIC(NumSpecsCreated, "Number of specializations created");
31344a3780SDimitry Andric 
327fa27ce4SDimitry Andric static cl::opt<bool> ForceSpecialization(
337fa27ce4SDimitry Andric     "force-specialization", cl::init(false), cl::Hidden, cl::desc(
347fa27ce4SDimitry Andric     "Force function specialization for every call site with a constant "
357fa27ce4SDimitry Andric     "argument"));
36344a3780SDimitry Andric 
377fa27ce4SDimitry Andric static cl::opt<unsigned> MaxClones(
387fa27ce4SDimitry Andric     "funcspec-max-clones", cl::init(3), cl::Hidden, cl::desc(
397fa27ce4SDimitry Andric     "The maximum number of clones allowed for a single function "
407fa27ce4SDimitry Andric     "specialization"));
41344a3780SDimitry Andric 
42b1c73532SDimitry Andric static cl::opt<unsigned>
43b1c73532SDimitry Andric     MaxDiscoveryIterations("funcspec-max-discovery-iterations", cl::init(100),
44b1c73532SDimitry Andric                            cl::Hidden,
45b1c73532SDimitry Andric                            cl::desc("The maximum number of iterations allowed "
46b1c73532SDimitry Andric                                     "when searching for transitive "
47b1c73532SDimitry Andric                                     "phis"));
48b1c73532SDimitry Andric 
497fa27ce4SDimitry Andric static cl::opt<unsigned> MaxIncomingPhiValues(
50b1c73532SDimitry Andric     "funcspec-max-incoming-phi-values", cl::init(8), cl::Hidden,
51b1c73532SDimitry Andric     cl::desc("The maximum number of incoming values a PHI node can have to be "
527fa27ce4SDimitry Andric              "considered during the specialization bonus estimation"));
53c0981da4SDimitry Andric 
54b1c73532SDimitry Andric static cl::opt<unsigned> MaxBlockPredecessors(
55b1c73532SDimitry Andric     "funcspec-max-block-predecessors", cl::init(2), cl::Hidden, cl::desc(
56b1c73532SDimitry Andric     "The maximum number of predecessors a basic block can have to be "
57b1c73532SDimitry Andric     "considered during the estimation of dead code"));
58b1c73532SDimitry Andric 
597fa27ce4SDimitry Andric static cl::opt<unsigned> MinFunctionSize(
60b1c73532SDimitry Andric     "funcspec-min-function-size", cl::init(300), cl::Hidden, cl::desc(
617fa27ce4SDimitry Andric     "Don't specialize functions that have less than this number of "
627fa27ce4SDimitry Andric     "instructions"));
63344a3780SDimitry Andric 
64b1c73532SDimitry Andric static cl::opt<unsigned> MaxCodeSizeGrowth(
65b1c73532SDimitry Andric     "funcspec-max-codesize-growth", cl::init(3), cl::Hidden, cl::desc(
66b1c73532SDimitry Andric     "Maximum codesize growth allowed per function"));
67b1c73532SDimitry Andric 
68b1c73532SDimitry Andric static cl::opt<unsigned> MinCodeSizeSavings(
69b1c73532SDimitry Andric     "funcspec-min-codesize-savings", cl::init(20), cl::Hidden, cl::desc(
70b1c73532SDimitry Andric     "Reject specializations whose codesize savings are less than this"
71b1c73532SDimitry Andric     "much percent of the original function size"));
72b1c73532SDimitry Andric 
73b1c73532SDimitry Andric static cl::opt<unsigned> MinLatencySavings(
74b1c73532SDimitry Andric     "funcspec-min-latency-savings", cl::init(40), cl::Hidden,
75b1c73532SDimitry Andric     cl::desc("Reject specializations whose latency savings are less than this"
76b1c73532SDimitry Andric              "much percent of the original function size"));
77b1c73532SDimitry Andric 
78b1c73532SDimitry Andric static cl::opt<unsigned> MinInliningBonus(
79b1c73532SDimitry Andric     "funcspec-min-inlining-bonus", cl::init(300), cl::Hidden, cl::desc(
80b1c73532SDimitry Andric     "Reject specializations whose inlining bonus is less than this"
81b1c73532SDimitry Andric     "much percent of the original function size"));
82b1c73532SDimitry Andric 
837fa27ce4SDimitry Andric static cl::opt<bool> SpecializeOnAddress(
847fa27ce4SDimitry Andric     "funcspec-on-address", cl::init(false), cl::Hidden, cl::desc(
857fa27ce4SDimitry Andric     "Enable function specialization on the address of global values"));
86c0981da4SDimitry Andric 
87145449b1SDimitry Andric // Disabled by default as it can significantly increase compilation times.
88145449b1SDimitry Andric //
89145449b1SDimitry Andric // https://llvm-compile-time-tracker.com
90145449b1SDimitry Andric // https://github.com/nikic/llvm-compile-time-tracker
917fa27ce4SDimitry Andric static cl::opt<bool> SpecializeLiteralConstant(
927fa27ce4SDimitry Andric     "funcspec-for-literal-constant", cl::init(false), cl::Hidden, cl::desc(
937fa27ce4SDimitry Andric     "Enable specialization of functions that take a literal constant as an "
947fa27ce4SDimitry Andric     "argument"));
957fa27ce4SDimitry Andric 
canEliminateSuccessor(BasicBlock * BB,BasicBlock * Succ,DenseSet<BasicBlock * > & DeadBlocks)96b1c73532SDimitry Andric bool InstCostVisitor::canEliminateSuccessor(BasicBlock *BB, BasicBlock *Succ,
97b1c73532SDimitry Andric                                          DenseSet<BasicBlock *> &DeadBlocks) {
98b1c73532SDimitry Andric   unsigned I = 0;
99b1c73532SDimitry Andric   return all_of(predecessors(Succ),
100b1c73532SDimitry Andric     [&I, BB, Succ, &DeadBlocks] (BasicBlock *Pred) {
101b1c73532SDimitry Andric     return I++ < MaxBlockPredecessors &&
102b1c73532SDimitry Andric       (Pred == BB || Pred == Succ || DeadBlocks.contains(Pred));
103b1c73532SDimitry Andric   });
104b1c73532SDimitry Andric }
1057fa27ce4SDimitry Andric 
106b1c73532SDimitry Andric // Estimates the codesize savings due to dead code after constant propagation.
107b1c73532SDimitry Andric // \p WorkList represents the basic blocks of a specialization which will
108b1c73532SDimitry Andric // eventually become dead once we replace instructions that are known to be
109b1c73532SDimitry Andric // constants. The successors of such blocks are added to the list as long as
110b1c73532SDimitry Andric // the \p Solver found they were executable prior to specialization, and only
111b1c73532SDimitry Andric // if all their predecessors are dead.
estimateBasicBlocks(SmallVectorImpl<BasicBlock * > & WorkList)112b1c73532SDimitry Andric Cost InstCostVisitor::estimateBasicBlocks(
113b1c73532SDimitry Andric                           SmallVectorImpl<BasicBlock *> &WorkList) {
114b1c73532SDimitry Andric   Cost CodeSize = 0;
1157fa27ce4SDimitry Andric   // Accumulate the instruction cost of each basic block weighted by frequency.
1167fa27ce4SDimitry Andric   while (!WorkList.empty()) {
1177fa27ce4SDimitry Andric     BasicBlock *BB = WorkList.pop_back_val();
1187fa27ce4SDimitry Andric 
119b1c73532SDimitry Andric     // These blocks are considered dead as far as the InstCostVisitor
120b1c73532SDimitry Andric     // is concerned. They haven't been proven dead yet by the Solver,
121b1c73532SDimitry Andric     // but may become if we propagate the specialization arguments.
1227fa27ce4SDimitry Andric     if (!DeadBlocks.insert(BB).second)
1237fa27ce4SDimitry Andric       continue;
1247fa27ce4SDimitry Andric 
1257fa27ce4SDimitry Andric     for (Instruction &I : *BB) {
1267fa27ce4SDimitry Andric       // Disregard SSA copies.
1277fa27ce4SDimitry Andric       if (auto *II = dyn_cast<IntrinsicInst>(&I))
1287fa27ce4SDimitry Andric         if (II->getIntrinsicID() == Intrinsic::ssa_copy)
1297fa27ce4SDimitry Andric           continue;
1307fa27ce4SDimitry Andric       // If it's a known constant we have already accounted for it.
1317fa27ce4SDimitry Andric       if (KnownConstants.contains(&I))
1327fa27ce4SDimitry Andric         continue;
1337fa27ce4SDimitry Andric 
134b1c73532SDimitry Andric       Cost C = TTI.getInstructionCost(&I, TargetTransformInfo::TCK_CodeSize);
1357fa27ce4SDimitry Andric 
136b1c73532SDimitry Andric       LLVM_DEBUG(dbgs() << "FnSpecialization:     CodeSize " << C
137b1c73532SDimitry Andric                         << " for user " << I << "\n");
138b1c73532SDimitry Andric       CodeSize += C;
1397fa27ce4SDimitry Andric     }
1407fa27ce4SDimitry Andric 
1417fa27ce4SDimitry Andric     // Keep adding dead successors to the list as long as they are
142b1c73532SDimitry Andric     // executable and only reachable from dead blocks.
1437fa27ce4SDimitry Andric     for (BasicBlock *SuccBB : successors(BB))
144b1c73532SDimitry Andric       if (isBlockExecutable(SuccBB) &&
145b1c73532SDimitry Andric           canEliminateSuccessor(BB, SuccBB, DeadBlocks))
1467fa27ce4SDimitry Andric         WorkList.push_back(SuccBB);
1477fa27ce4SDimitry Andric   }
148b1c73532SDimitry Andric   return CodeSize;
1497fa27ce4SDimitry Andric }
1507fa27ce4SDimitry Andric 
findConstantFor(Value * V,ConstMap & KnownConstants)1517fa27ce4SDimitry Andric static Constant *findConstantFor(Value *V, ConstMap &KnownConstants) {
1527fa27ce4SDimitry Andric   if (auto *C = dyn_cast<Constant>(V))
1537fa27ce4SDimitry Andric     return C;
154b1c73532SDimitry Andric   return KnownConstants.lookup(V);
1557fa27ce4SDimitry Andric }
1567fa27ce4SDimitry Andric 
getBonusFromPendingPHIs()157b1c73532SDimitry Andric Bonus InstCostVisitor::getBonusFromPendingPHIs() {
158b1c73532SDimitry Andric   Bonus B;
1597fa27ce4SDimitry Andric   while (!PendingPHIs.empty()) {
1607fa27ce4SDimitry Andric     Instruction *Phi = PendingPHIs.pop_back_val();
161b1c73532SDimitry Andric     // The pending PHIs could have been proven dead by now.
162b1c73532SDimitry Andric     if (isBlockExecutable(Phi->getParent()))
163b1c73532SDimitry Andric       B += getUserBonus(Phi);
1647fa27ce4SDimitry Andric   }
165b1c73532SDimitry Andric   return B;
1667fa27ce4SDimitry Andric }
1677fa27ce4SDimitry Andric 
168b1c73532SDimitry Andric /// Compute a bonus for replacing argument \p A with constant \p C.
getSpecializationBonus(Argument * A,Constant * C)169b1c73532SDimitry Andric Bonus InstCostVisitor::getSpecializationBonus(Argument *A, Constant *C) {
170b1c73532SDimitry Andric   LLVM_DEBUG(dbgs() << "FnSpecialization: Analysing bonus for constant: "
171b1c73532SDimitry Andric                     << C->getNameOrAsOperand() << "\n");
172b1c73532SDimitry Andric   Bonus B;
173b1c73532SDimitry Andric   for (auto *U : A->users())
174b1c73532SDimitry Andric     if (auto *UI = dyn_cast<Instruction>(U))
175b1c73532SDimitry Andric       if (isBlockExecutable(UI->getParent()))
176b1c73532SDimitry Andric         B += getUserBonus(UI, A, C);
177b1c73532SDimitry Andric 
178b1c73532SDimitry Andric   LLVM_DEBUG(dbgs() << "FnSpecialization:   Accumulated bonus {CodeSize = "
179b1c73532SDimitry Andric                     << B.CodeSize << ", Latency = " << B.Latency
180b1c73532SDimitry Andric                     << "} for argument " << *A << "\n");
181b1c73532SDimitry Andric   return B;
182b1c73532SDimitry Andric }
183b1c73532SDimitry Andric 
getUserBonus(Instruction * User,Value * Use,Constant * C)184b1c73532SDimitry Andric Bonus InstCostVisitor::getUserBonus(Instruction *User, Value *Use, Constant *C) {
185b1c73532SDimitry Andric   // We have already propagated a constant for this user.
186b1c73532SDimitry Andric   if (KnownConstants.contains(User))
187b1c73532SDimitry Andric     return {0, 0};
188b1c73532SDimitry Andric 
1897fa27ce4SDimitry Andric   // Cache the iterator before visiting.
1907fa27ce4SDimitry Andric   LastVisited = Use ? KnownConstants.insert({Use, C}).first
1917fa27ce4SDimitry Andric                     : KnownConstants.end();
1927fa27ce4SDimitry Andric 
193b1c73532SDimitry Andric   Cost CodeSize = 0;
194b1c73532SDimitry Andric   if (auto *I = dyn_cast<SwitchInst>(User)) {
195b1c73532SDimitry Andric     CodeSize = estimateSwitchInst(*I);
196b1c73532SDimitry Andric   } else if (auto *I = dyn_cast<BranchInst>(User)) {
197b1c73532SDimitry Andric     CodeSize = estimateBranchInst(*I);
198b1c73532SDimitry Andric   } else {
1997fa27ce4SDimitry Andric     C = visit(*User);
2007fa27ce4SDimitry Andric     if (!C)
201b1c73532SDimitry Andric       return {0, 0};
202b1c73532SDimitry Andric   }
2037fa27ce4SDimitry Andric 
204b1c73532SDimitry Andric   // Even though it doesn't make sense to bind switch and branch instructions
205b1c73532SDimitry Andric   // with a constant, unlike any other instruction type, it prevents estimating
206b1c73532SDimitry Andric   // their bonus multiple times.
2077fa27ce4SDimitry Andric   KnownConstants.insert({User, C});
2087fa27ce4SDimitry Andric 
209b1c73532SDimitry Andric   CodeSize += TTI.getInstructionCost(User, TargetTransformInfo::TCK_CodeSize);
210b1c73532SDimitry Andric 
2117fa27ce4SDimitry Andric   uint64_t Weight = BFI.getBlockFreq(User->getParent()).getFrequency() /
212b1c73532SDimitry Andric                     BFI.getEntryFreq().getFrequency();
2137fa27ce4SDimitry Andric 
214b1c73532SDimitry Andric   Cost Latency = Weight *
215b1c73532SDimitry Andric       TTI.getInstructionCost(User, TargetTransformInfo::TCK_Latency);
2167fa27ce4SDimitry Andric 
217b1c73532SDimitry Andric   LLVM_DEBUG(dbgs() << "FnSpecialization:     {CodeSize = " << CodeSize
218b1c73532SDimitry Andric                     << ", Latency = " << Latency << "} for user "
219b1c73532SDimitry Andric                     << *User << "\n");
2207fa27ce4SDimitry Andric 
221b1c73532SDimitry Andric   Bonus B(CodeSize, Latency);
2227fa27ce4SDimitry Andric   for (auto *U : User->users())
2237fa27ce4SDimitry Andric     if (auto *UI = dyn_cast<Instruction>(U))
224b1c73532SDimitry Andric       if (UI != User && isBlockExecutable(UI->getParent()))
225b1c73532SDimitry Andric         B += getUserBonus(UI, User, C);
2267fa27ce4SDimitry Andric 
227b1c73532SDimitry Andric   return B;
2287fa27ce4SDimitry Andric }
2297fa27ce4SDimitry Andric 
estimateSwitchInst(SwitchInst & I)2307fa27ce4SDimitry Andric Cost InstCostVisitor::estimateSwitchInst(SwitchInst &I) {
2317fa27ce4SDimitry Andric   assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
2327fa27ce4SDimitry Andric 
2337fa27ce4SDimitry Andric   if (I.getCondition() != LastVisited->first)
2347fa27ce4SDimitry Andric     return 0;
2357fa27ce4SDimitry Andric 
2367fa27ce4SDimitry Andric   auto *C = dyn_cast<ConstantInt>(LastVisited->second);
2377fa27ce4SDimitry Andric   if (!C)
2387fa27ce4SDimitry Andric     return 0;
2397fa27ce4SDimitry Andric 
2407fa27ce4SDimitry Andric   BasicBlock *Succ = I.findCaseValue(C)->getCaseSuccessor();
2417fa27ce4SDimitry Andric   // Initialize the worklist with the dead basic blocks. These are the
2427fa27ce4SDimitry Andric   // destination labels which are different from the one corresponding
2437fa27ce4SDimitry Andric   // to \p C. They should be executable and have a unique predecessor.
2447fa27ce4SDimitry Andric   SmallVector<BasicBlock *> WorkList;
2457fa27ce4SDimitry Andric   for (const auto &Case : I.cases()) {
2467fa27ce4SDimitry Andric     BasicBlock *BB = Case.getCaseSuccessor();
247b1c73532SDimitry Andric     if (BB != Succ && isBlockExecutable(BB) &&
248b1c73532SDimitry Andric         canEliminateSuccessor(I.getParent(), BB, DeadBlocks))
2497fa27ce4SDimitry Andric       WorkList.push_back(BB);
2507fa27ce4SDimitry Andric   }
2517fa27ce4SDimitry Andric 
252b1c73532SDimitry Andric   return estimateBasicBlocks(WorkList);
2537fa27ce4SDimitry Andric }
2547fa27ce4SDimitry Andric 
estimateBranchInst(BranchInst & I)2557fa27ce4SDimitry Andric Cost InstCostVisitor::estimateBranchInst(BranchInst &I) {
2567fa27ce4SDimitry Andric   assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
2577fa27ce4SDimitry Andric 
2587fa27ce4SDimitry Andric   if (I.getCondition() != LastVisited->first)
2597fa27ce4SDimitry Andric     return 0;
2607fa27ce4SDimitry Andric 
2617fa27ce4SDimitry Andric   BasicBlock *Succ = I.getSuccessor(LastVisited->second->isOneValue());
2627fa27ce4SDimitry Andric   // Initialize the worklist with the dead successor as long as
2637fa27ce4SDimitry Andric   // it is executable and has a unique predecessor.
2647fa27ce4SDimitry Andric   SmallVector<BasicBlock *> WorkList;
265b1c73532SDimitry Andric   if (isBlockExecutable(Succ) &&
266b1c73532SDimitry Andric       canEliminateSuccessor(I.getParent(), Succ, DeadBlocks))
2677fa27ce4SDimitry Andric     WorkList.push_back(Succ);
2687fa27ce4SDimitry Andric 
269b1c73532SDimitry Andric   return estimateBasicBlocks(WorkList);
270b1c73532SDimitry Andric }
271b1c73532SDimitry Andric 
discoverTransitivelyIncomingValues(Constant * Const,PHINode * Root,DenseSet<PHINode * > & TransitivePHIs)272b1c73532SDimitry Andric bool InstCostVisitor::discoverTransitivelyIncomingValues(
273b1c73532SDimitry Andric     Constant *Const, PHINode *Root, DenseSet<PHINode *> &TransitivePHIs) {
274b1c73532SDimitry Andric 
275b1c73532SDimitry Andric   SmallVector<PHINode *, 64> WorkList;
276b1c73532SDimitry Andric   WorkList.push_back(Root);
277b1c73532SDimitry Andric   unsigned Iter = 0;
278b1c73532SDimitry Andric 
279b1c73532SDimitry Andric   while (!WorkList.empty()) {
280b1c73532SDimitry Andric     PHINode *PN = WorkList.pop_back_val();
281b1c73532SDimitry Andric 
282b1c73532SDimitry Andric     if (++Iter > MaxDiscoveryIterations ||
283b1c73532SDimitry Andric         PN->getNumIncomingValues() > MaxIncomingPhiValues)
284b1c73532SDimitry Andric       return false;
285b1c73532SDimitry Andric 
286b1c73532SDimitry Andric     if (!TransitivePHIs.insert(PN).second)
287b1c73532SDimitry Andric       continue;
288b1c73532SDimitry Andric 
289b1c73532SDimitry Andric     for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
290b1c73532SDimitry Andric       Value *V = PN->getIncomingValue(I);
291b1c73532SDimitry Andric 
292b1c73532SDimitry Andric       // Disregard self-references and dead incoming values.
293b1c73532SDimitry Andric       if (auto *Inst = dyn_cast<Instruction>(V))
294b1c73532SDimitry Andric         if (Inst == PN || DeadBlocks.contains(PN->getIncomingBlock(I)))
295b1c73532SDimitry Andric           continue;
296b1c73532SDimitry Andric 
297b1c73532SDimitry Andric       if (Constant *C = findConstantFor(V, KnownConstants)) {
298b1c73532SDimitry Andric         // Not all incoming values are the same constant. Bail immediately.
299b1c73532SDimitry Andric         if (C != Const)
300b1c73532SDimitry Andric           return false;
301b1c73532SDimitry Andric         continue;
302b1c73532SDimitry Andric       }
303b1c73532SDimitry Andric 
304b1c73532SDimitry Andric       if (auto *Phi = dyn_cast<PHINode>(V)) {
305b1c73532SDimitry Andric         WorkList.push_back(Phi);
306b1c73532SDimitry Andric         continue;
307b1c73532SDimitry Andric       }
308b1c73532SDimitry Andric 
309b1c73532SDimitry Andric       // We can't reason about anything else.
310b1c73532SDimitry Andric       return false;
311b1c73532SDimitry Andric     }
312b1c73532SDimitry Andric   }
313b1c73532SDimitry Andric   return true;
3147fa27ce4SDimitry Andric }
3157fa27ce4SDimitry Andric 
visitPHINode(PHINode & I)3167fa27ce4SDimitry Andric Constant *InstCostVisitor::visitPHINode(PHINode &I) {
3177fa27ce4SDimitry Andric   if (I.getNumIncomingValues() > MaxIncomingPhiValues)
3187fa27ce4SDimitry Andric     return nullptr;
3197fa27ce4SDimitry Andric 
3207fa27ce4SDimitry Andric   bool Inserted = VisitedPHIs.insert(&I).second;
3217fa27ce4SDimitry Andric   Constant *Const = nullptr;
322b1c73532SDimitry Andric   bool HaveSeenIncomingPHI = false;
3237fa27ce4SDimitry Andric 
3247fa27ce4SDimitry Andric   for (unsigned Idx = 0, E = I.getNumIncomingValues(); Idx != E; ++Idx) {
3257fa27ce4SDimitry Andric     Value *V = I.getIncomingValue(Idx);
326b1c73532SDimitry Andric 
327b1c73532SDimitry Andric     // Disregard self-references and dead incoming values.
3287fa27ce4SDimitry Andric     if (auto *Inst = dyn_cast<Instruction>(V))
3297fa27ce4SDimitry Andric       if (Inst == &I || DeadBlocks.contains(I.getIncomingBlock(Idx)))
3307fa27ce4SDimitry Andric         continue;
331b1c73532SDimitry Andric 
332b1c73532SDimitry Andric     if (Constant *C = findConstantFor(V, KnownConstants)) {
333b1c73532SDimitry Andric       if (!Const)
334b1c73532SDimitry Andric         Const = C;
335b1c73532SDimitry Andric       // Not all incoming values are the same constant. Bail immediately.
336b1c73532SDimitry Andric       if (C != Const)
337b1c73532SDimitry Andric         return nullptr;
338b1c73532SDimitry Andric       continue;
339b1c73532SDimitry Andric     }
340b1c73532SDimitry Andric 
341b1c73532SDimitry Andric     if (Inserted) {
342b1c73532SDimitry Andric       // First time we are seeing this phi. We will retry later, after
343b1c73532SDimitry Andric       // all the constant arguments have been propagated. Bail for now.
3447fa27ce4SDimitry Andric       PendingPHIs.push_back(&I);
3457fa27ce4SDimitry Andric       return nullptr;
3467fa27ce4SDimitry Andric     }
347b1c73532SDimitry Andric 
348b1c73532SDimitry Andric     if (isa<PHINode>(V)) {
349b1c73532SDimitry Andric       // Perhaps it is a Transitive Phi. We will confirm later.
350b1c73532SDimitry Andric       HaveSeenIncomingPHI = true;
351b1c73532SDimitry Andric       continue;
352b1c73532SDimitry Andric     }
353b1c73532SDimitry Andric 
354b1c73532SDimitry Andric     // We can't reason about anything else.
3557fa27ce4SDimitry Andric     return nullptr;
3567fa27ce4SDimitry Andric   }
357b1c73532SDimitry Andric 
358b1c73532SDimitry Andric   if (!Const)
359b1c73532SDimitry Andric     return nullptr;
360b1c73532SDimitry Andric 
361b1c73532SDimitry Andric   if (!HaveSeenIncomingPHI)
362b1c73532SDimitry Andric     return Const;
363b1c73532SDimitry Andric 
364b1c73532SDimitry Andric   DenseSet<PHINode *> TransitivePHIs;
365b1c73532SDimitry Andric   if (!discoverTransitivelyIncomingValues(Const, &I, TransitivePHIs))
366b1c73532SDimitry Andric     return nullptr;
367b1c73532SDimitry Andric 
3687fa27ce4SDimitry Andric   return Const;
3697fa27ce4SDimitry Andric }
3707fa27ce4SDimitry Andric 
visitFreezeInst(FreezeInst & I)3717fa27ce4SDimitry Andric Constant *InstCostVisitor::visitFreezeInst(FreezeInst &I) {
3727fa27ce4SDimitry Andric   assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
3737fa27ce4SDimitry Andric 
3747fa27ce4SDimitry Andric   if (isGuaranteedNotToBeUndefOrPoison(LastVisited->second))
3757fa27ce4SDimitry Andric     return LastVisited->second;
3767fa27ce4SDimitry Andric   return nullptr;
3777fa27ce4SDimitry Andric }
3787fa27ce4SDimitry Andric 
visitCallBase(CallBase & I)3797fa27ce4SDimitry Andric Constant *InstCostVisitor::visitCallBase(CallBase &I) {
3807fa27ce4SDimitry Andric   Function *F = I.getCalledFunction();
3817fa27ce4SDimitry Andric   if (!F || !canConstantFoldCallTo(&I, F))
3827fa27ce4SDimitry Andric     return nullptr;
3837fa27ce4SDimitry Andric 
3847fa27ce4SDimitry Andric   SmallVector<Constant *, 8> Operands;
3857fa27ce4SDimitry Andric   Operands.reserve(I.getNumOperands());
3867fa27ce4SDimitry Andric 
3877fa27ce4SDimitry Andric   for (unsigned Idx = 0, E = I.getNumOperands() - 1; Idx != E; ++Idx) {
3887fa27ce4SDimitry Andric     Value *V = I.getOperand(Idx);
3897fa27ce4SDimitry Andric     Constant *C = findConstantFor(V, KnownConstants);
3907fa27ce4SDimitry Andric     if (!C)
3917fa27ce4SDimitry Andric       return nullptr;
3927fa27ce4SDimitry Andric     Operands.push_back(C);
3937fa27ce4SDimitry Andric   }
3947fa27ce4SDimitry Andric 
3957fa27ce4SDimitry Andric   auto Ops = ArrayRef(Operands.begin(), Operands.end());
3967fa27ce4SDimitry Andric   return ConstantFoldCall(&I, F, Ops);
3977fa27ce4SDimitry Andric }
3987fa27ce4SDimitry Andric 
visitLoadInst(LoadInst & I)3997fa27ce4SDimitry Andric Constant *InstCostVisitor::visitLoadInst(LoadInst &I) {
4007fa27ce4SDimitry Andric   assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
4017fa27ce4SDimitry Andric 
4027fa27ce4SDimitry Andric   if (isa<ConstantPointerNull>(LastVisited->second))
4037fa27ce4SDimitry Andric     return nullptr;
4047fa27ce4SDimitry Andric   return ConstantFoldLoadFromConstPtr(LastVisited->second, I.getType(), DL);
4057fa27ce4SDimitry Andric }
4067fa27ce4SDimitry Andric 
visitGetElementPtrInst(GetElementPtrInst & I)4077fa27ce4SDimitry Andric Constant *InstCostVisitor::visitGetElementPtrInst(GetElementPtrInst &I) {
4087fa27ce4SDimitry Andric   SmallVector<Constant *, 8> Operands;
4097fa27ce4SDimitry Andric   Operands.reserve(I.getNumOperands());
4107fa27ce4SDimitry Andric 
4117fa27ce4SDimitry Andric   for (unsigned Idx = 0, E = I.getNumOperands(); Idx != E; ++Idx) {
4127fa27ce4SDimitry Andric     Value *V = I.getOperand(Idx);
4137fa27ce4SDimitry Andric     Constant *C = findConstantFor(V, KnownConstants);
4147fa27ce4SDimitry Andric     if (!C)
4157fa27ce4SDimitry Andric       return nullptr;
4167fa27ce4SDimitry Andric     Operands.push_back(C);
4177fa27ce4SDimitry Andric   }
4187fa27ce4SDimitry Andric 
4197fa27ce4SDimitry Andric   auto Ops = ArrayRef(Operands.begin(), Operands.end());
4207fa27ce4SDimitry Andric   return ConstantFoldInstOperands(&I, Ops, DL);
4217fa27ce4SDimitry Andric }
4227fa27ce4SDimitry Andric 
visitSelectInst(SelectInst & I)4237fa27ce4SDimitry Andric Constant *InstCostVisitor::visitSelectInst(SelectInst &I) {
4247fa27ce4SDimitry Andric   assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
4257fa27ce4SDimitry Andric 
4267fa27ce4SDimitry Andric   if (I.getCondition() != LastVisited->first)
4277fa27ce4SDimitry Andric     return nullptr;
4287fa27ce4SDimitry Andric 
4297fa27ce4SDimitry Andric   Value *V = LastVisited->second->isZeroValue() ? I.getFalseValue()
4307fa27ce4SDimitry Andric                                                 : I.getTrueValue();
4317fa27ce4SDimitry Andric   Constant *C = findConstantFor(V, KnownConstants);
4327fa27ce4SDimitry Andric   return C;
4337fa27ce4SDimitry Andric }
4347fa27ce4SDimitry Andric 
visitCastInst(CastInst & I)4357fa27ce4SDimitry Andric Constant *InstCostVisitor::visitCastInst(CastInst &I) {
4367fa27ce4SDimitry Andric   return ConstantFoldCastOperand(I.getOpcode(), LastVisited->second,
4377fa27ce4SDimitry Andric                                  I.getType(), DL);
4387fa27ce4SDimitry Andric }
4397fa27ce4SDimitry Andric 
visitCmpInst(CmpInst & I)4407fa27ce4SDimitry Andric Constant *InstCostVisitor::visitCmpInst(CmpInst &I) {
4417fa27ce4SDimitry Andric   assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
4427fa27ce4SDimitry Andric 
4437fa27ce4SDimitry Andric   bool Swap = I.getOperand(1) == LastVisited->first;
4447fa27ce4SDimitry Andric   Value *V = Swap ? I.getOperand(0) : I.getOperand(1);
4457fa27ce4SDimitry Andric   Constant *Other = findConstantFor(V, KnownConstants);
4467fa27ce4SDimitry Andric   if (!Other)
4477fa27ce4SDimitry Andric     return nullptr;
4487fa27ce4SDimitry Andric 
4497fa27ce4SDimitry Andric   Constant *Const = LastVisited->second;
4507fa27ce4SDimitry Andric   return Swap ?
4517fa27ce4SDimitry Andric         ConstantFoldCompareInstOperands(I.getPredicate(), Other, Const, DL)
4527fa27ce4SDimitry Andric       : ConstantFoldCompareInstOperands(I.getPredicate(), Const, Other, DL);
4537fa27ce4SDimitry Andric }
4547fa27ce4SDimitry Andric 
visitUnaryOperator(UnaryOperator & I)4557fa27ce4SDimitry Andric Constant *InstCostVisitor::visitUnaryOperator(UnaryOperator &I) {
4567fa27ce4SDimitry Andric   assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
4577fa27ce4SDimitry Andric 
4587fa27ce4SDimitry Andric   return ConstantFoldUnaryOpOperand(I.getOpcode(), LastVisited->second, DL);
4597fa27ce4SDimitry Andric }
4607fa27ce4SDimitry Andric 
visitBinaryOperator(BinaryOperator & I)4617fa27ce4SDimitry Andric Constant *InstCostVisitor::visitBinaryOperator(BinaryOperator &I) {
4627fa27ce4SDimitry Andric   assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
4637fa27ce4SDimitry Andric 
4647fa27ce4SDimitry Andric   bool Swap = I.getOperand(1) == LastVisited->first;
4657fa27ce4SDimitry Andric   Value *V = Swap ? I.getOperand(0) : I.getOperand(1);
4667fa27ce4SDimitry Andric   Constant *Other = findConstantFor(V, KnownConstants);
4677fa27ce4SDimitry Andric   if (!Other)
4687fa27ce4SDimitry Andric     return nullptr;
4697fa27ce4SDimitry Andric 
4707fa27ce4SDimitry Andric   Constant *Const = LastVisited->second;
4717fa27ce4SDimitry Andric   return dyn_cast_or_null<Constant>(Swap ?
4727fa27ce4SDimitry Andric         simplifyBinOp(I.getOpcode(), Other, Const, SimplifyQuery(DL))
4737fa27ce4SDimitry Andric       : simplifyBinOp(I.getOpcode(), Const, Other, SimplifyQuery(DL)));
4747fa27ce4SDimitry Andric }
475c0981da4SDimitry Andric 
getPromotableAlloca(AllocaInst * Alloca,CallInst * Call)476e3b55780SDimitry Andric Constant *FunctionSpecializer::getPromotableAlloca(AllocaInst *Alloca,
477e3b55780SDimitry Andric                                                    CallInst *Call) {
478c0981da4SDimitry Andric   Value *StoreValue = nullptr;
479c0981da4SDimitry Andric   for (auto *User : Alloca->users()) {
480c0981da4SDimitry Andric     // We can't use llvm::isAllocaPromotable() as that would fail because of
481c0981da4SDimitry Andric     // the usage in the CallInst, which is what we check here.
482c0981da4SDimitry Andric     if (User == Call)
483c0981da4SDimitry Andric       continue;
484c0981da4SDimitry Andric     if (auto *Bitcast = dyn_cast<BitCastInst>(User)) {
485c0981da4SDimitry Andric       if (!Bitcast->hasOneUse() || *Bitcast->user_begin() != Call)
486c0981da4SDimitry Andric         return nullptr;
487c0981da4SDimitry Andric       continue;
488c0981da4SDimitry Andric     }
489c0981da4SDimitry Andric 
490c0981da4SDimitry Andric     if (auto *Store = dyn_cast<StoreInst>(User)) {
491c0981da4SDimitry Andric       // This is a duplicate store, bail out.
492c0981da4SDimitry Andric       if (StoreValue || Store->isVolatile())
493c0981da4SDimitry Andric         return nullptr;
494c0981da4SDimitry Andric       StoreValue = Store->getValueOperand();
495c0981da4SDimitry Andric       continue;
496c0981da4SDimitry Andric     }
497c0981da4SDimitry Andric     // Bail if there is any other unknown usage.
498c0981da4SDimitry Andric     return nullptr;
499c0981da4SDimitry Andric   }
5007fa27ce4SDimitry Andric 
5017fa27ce4SDimitry Andric   if (!StoreValue)
5027fa27ce4SDimitry Andric     return nullptr;
5037fa27ce4SDimitry Andric 
504e3b55780SDimitry Andric   return getCandidateConstant(StoreValue);
505c0981da4SDimitry Andric }
506c0981da4SDimitry Andric 
507c0981da4SDimitry Andric // A constant stack value is an AllocaInst that has a single constant
508c0981da4SDimitry Andric // value stored to it. Return this constant if such an alloca stack value
509c0981da4SDimitry Andric // is a function argument.
getConstantStackValue(CallInst * Call,Value * Val)510e3b55780SDimitry Andric Constant *FunctionSpecializer::getConstantStackValue(CallInst *Call,
511e3b55780SDimitry Andric                                                      Value *Val) {
512c0981da4SDimitry Andric   if (!Val)
513c0981da4SDimitry Andric     return nullptr;
514c0981da4SDimitry Andric   Val = Val->stripPointerCasts();
515c0981da4SDimitry Andric   if (auto *ConstVal = dyn_cast<ConstantInt>(Val))
516c0981da4SDimitry Andric     return ConstVal;
517c0981da4SDimitry Andric   auto *Alloca = dyn_cast<AllocaInst>(Val);
518c0981da4SDimitry Andric   if (!Alloca || !Alloca->getAllocatedType()->isIntegerTy())
519c0981da4SDimitry Andric     return nullptr;
520c0981da4SDimitry Andric   return getPromotableAlloca(Alloca, Call);
521c0981da4SDimitry Andric }
522c0981da4SDimitry Andric 
523c0981da4SDimitry Andric // To support specializing recursive functions, it is important to propagate
524c0981da4SDimitry Andric // constant arguments because after a first iteration of specialisation, a
525c0981da4SDimitry Andric // reduced example may look like this:
526c0981da4SDimitry Andric //
527c0981da4SDimitry Andric //     define internal void @RecursiveFn(i32* arg1) {
528c0981da4SDimitry Andric //       %temp = alloca i32, align 4
529c0981da4SDimitry Andric //       store i32 2 i32* %temp, align 4
530c0981da4SDimitry Andric //       call void @RecursiveFn.1(i32* nonnull %temp)
531c0981da4SDimitry Andric //       ret void
532c0981da4SDimitry Andric //     }
533c0981da4SDimitry Andric //
534c0981da4SDimitry Andric // Before a next iteration, we need to propagate the constant like so
535c0981da4SDimitry Andric // which allows further specialization in next iterations.
536c0981da4SDimitry Andric //
537c0981da4SDimitry Andric //     @funcspec.arg = internal constant i32 2
538c0981da4SDimitry Andric //
539c0981da4SDimitry Andric //     define internal void @someFunc(i32* arg1) {
540c0981da4SDimitry Andric //       call void @otherFunc(i32* nonnull @funcspec.arg)
541c0981da4SDimitry Andric //       ret void
542c0981da4SDimitry Andric //     }
543c0981da4SDimitry Andric //
5447fa27ce4SDimitry Andric // See if there are any new constant values for the callers of \p F via
5457fa27ce4SDimitry Andric // stack variables and promote them to global variables.
promoteConstantStackValues(Function * F)5467fa27ce4SDimitry Andric void FunctionSpecializer::promoteConstantStackValues(Function *F) {
5477fa27ce4SDimitry Andric   for (User *U : F->users()) {
548c0981da4SDimitry Andric 
5497fa27ce4SDimitry Andric     auto *Call = dyn_cast<CallInst>(U);
550c0981da4SDimitry Andric     if (!Call)
551145449b1SDimitry Andric       continue;
552145449b1SDimitry Andric 
553e3b55780SDimitry Andric     if (!Solver.isBlockExecutable(Call->getParent()))
554e3b55780SDimitry Andric       continue;
555e3b55780SDimitry Andric 
556145449b1SDimitry Andric     for (const Use &U : Call->args()) {
557145449b1SDimitry Andric       unsigned Idx = Call->getArgOperandNo(&U);
558145449b1SDimitry Andric       Value *ArgOp = Call->getArgOperand(Idx);
559145449b1SDimitry Andric       Type *ArgOpType = ArgOp->getType();
560145449b1SDimitry Andric 
561145449b1SDimitry Andric       if (!Call->onlyReadsMemory(Idx) || !ArgOpType->isPointerTy())
562145449b1SDimitry Andric         continue;
563145449b1SDimitry Andric 
564e3b55780SDimitry Andric       auto *ConstVal = getConstantStackValue(Call, ArgOp);
565c0981da4SDimitry Andric       if (!ConstVal)
566145449b1SDimitry Andric         continue;
567c0981da4SDimitry Andric 
568c0981da4SDimitry Andric       Value *GV = new GlobalVariable(M, ConstVal->getType(), true,
569c0981da4SDimitry Andric                                      GlobalValue::InternalLinkage, ConstVal,
570b1c73532SDimitry Andric                                      "specialized.arg." + Twine(++NGlobals));
571145449b1SDimitry Andric       Call->setArgOperand(Idx, GV);
572c0981da4SDimitry Andric     }
573c0981da4SDimitry Andric   }
574c0981da4SDimitry Andric }
575c0981da4SDimitry Andric 
576c0981da4SDimitry Andric // ssa_copy intrinsics are introduced by the SCCP solver. These intrinsics
577e3b55780SDimitry Andric // interfere with the promoteConstantStackValues() optimization.
removeSSACopy(Function & F)578c0981da4SDimitry Andric static void removeSSACopy(Function &F) {
579c0981da4SDimitry Andric   for (BasicBlock &BB : F) {
580c0981da4SDimitry Andric     for (Instruction &Inst : llvm::make_early_inc_range(BB)) {
581c0981da4SDimitry Andric       auto *II = dyn_cast<IntrinsicInst>(&Inst);
582c0981da4SDimitry Andric       if (!II)
583c0981da4SDimitry Andric         continue;
584c0981da4SDimitry Andric       if (II->getIntrinsicID() != Intrinsic::ssa_copy)
585c0981da4SDimitry Andric         continue;
586c0981da4SDimitry Andric       Inst.replaceAllUsesWith(II->getOperand(0));
587c0981da4SDimitry Andric       Inst.eraseFromParent();
588c0981da4SDimitry Andric     }
589c0981da4SDimitry Andric   }
590c0981da4SDimitry Andric }
591c0981da4SDimitry Andric 
592e3b55780SDimitry Andric /// Remove any ssa_copy intrinsics that may have been introduced.
cleanUpSSA()593e3b55780SDimitry Andric void FunctionSpecializer::cleanUpSSA() {
5947fa27ce4SDimitry Andric   for (Function *F : Specializations)
595e3b55780SDimitry Andric     removeSSACopy(*F);
596c0981da4SDimitry Andric }
597c0981da4SDimitry Andric 
598344a3780SDimitry Andric 
599e3b55780SDimitry Andric template <> struct llvm::DenseMapInfo<SpecSig> {
getEmptyKeyllvm::DenseMapInfo600e3b55780SDimitry Andric   static inline SpecSig getEmptyKey() { return {~0U, {}}; }
601344a3780SDimitry Andric 
getTombstoneKeyllvm::DenseMapInfo602e3b55780SDimitry Andric   static inline SpecSig getTombstoneKey() { return {~1U, {}}; }
603344a3780SDimitry Andric 
getHashValuellvm::DenseMapInfo604e3b55780SDimitry Andric   static unsigned getHashValue(const SpecSig &S) {
605e3b55780SDimitry Andric     return static_cast<unsigned>(hash_value(S));
606145449b1SDimitry Andric   }
607145449b1SDimitry Andric 
isEqualllvm::DenseMapInfo608e3b55780SDimitry Andric   static bool isEqual(const SpecSig &LHS, const SpecSig &RHS) {
609e3b55780SDimitry Andric     return LHS == RHS;
610e3b55780SDimitry Andric   }
611e3b55780SDimitry Andric };
612e3b55780SDimitry Andric 
~FunctionSpecializer()6137fa27ce4SDimitry Andric FunctionSpecializer::~FunctionSpecializer() {
6147fa27ce4SDimitry Andric   LLVM_DEBUG(
6157fa27ce4SDimitry Andric     if (NumSpecsCreated > 0)
6167fa27ce4SDimitry Andric       dbgs() << "FnSpecialization: Created " << NumSpecsCreated
6177fa27ce4SDimitry Andric              << " specializations in module " << M.getName() << "\n");
6187fa27ce4SDimitry Andric   // Eliminate dead code.
6197fa27ce4SDimitry Andric   removeDeadFunctions();
6207fa27ce4SDimitry Andric   cleanUpSSA();
6217fa27ce4SDimitry Andric }
6227fa27ce4SDimitry Andric 
623344a3780SDimitry Andric /// Attempt to specialize functions in the module to enable constant
624344a3780SDimitry Andric /// propagation across function boundaries.
625344a3780SDimitry Andric ///
626344a3780SDimitry Andric /// \returns true if at least one function is specialized.
run()627e3b55780SDimitry Andric bool FunctionSpecializer::run() {
628e3b55780SDimitry Andric   // Find possible specializations for each function.
629e3b55780SDimitry Andric   SpecMap SM;
630e3b55780SDimitry Andric   SmallVector<Spec, 32> AllSpecs;
631e3b55780SDimitry Andric   unsigned NumCandidates = 0;
632e3b55780SDimitry Andric   for (Function &F : M) {
633e3b55780SDimitry Andric     if (!isCandidateFunction(&F))
63477fc4c14SDimitry Andric       continue;
63577fc4c14SDimitry Andric 
6367fa27ce4SDimitry Andric     auto [It, Inserted] = FunctionMetrics.try_emplace(&F);
6377fa27ce4SDimitry Andric     CodeMetrics &Metrics = It->second;
6387fa27ce4SDimitry Andric     //Analyze the function.
6397fa27ce4SDimitry Andric     if (Inserted) {
6407fa27ce4SDimitry Andric       SmallPtrSet<const Value *, 32> EphValues;
6417fa27ce4SDimitry Andric       CodeMetrics::collectEphemeralValues(&F, &GetAC(F), EphValues);
6427fa27ce4SDimitry Andric       for (BasicBlock &BB : F)
6437fa27ce4SDimitry Andric         Metrics.analyzeBasicBlock(&BB, GetTTI(F), EphValues);
64477fc4c14SDimitry Andric     }
64577fc4c14SDimitry Andric 
6467fa27ce4SDimitry Andric     // If the code metrics reveal that we shouldn't duplicate the function,
6477fa27ce4SDimitry Andric     // or if the code size implies that this function is easy to get inlined,
6487fa27ce4SDimitry Andric     // then we shouldn't specialize it.
6497fa27ce4SDimitry Andric     if (Metrics.notDuplicatable || !Metrics.NumInsts.isValid() ||
6507fa27ce4SDimitry Andric         (!ForceSpecialization && !F.hasFnAttribute(Attribute::NoInline) &&
6517fa27ce4SDimitry Andric          Metrics.NumInsts < MinFunctionSize))
6527fa27ce4SDimitry Andric       continue;
653145449b1SDimitry Andric 
6547fa27ce4SDimitry Andric     // TODO: For now only consider recursive functions when running multiple
6557fa27ce4SDimitry Andric     // times. This should change if specialization on literal constants gets
6567fa27ce4SDimitry Andric     // enabled.
6577fa27ce4SDimitry Andric     if (!Inserted && !Metrics.isRecursive && !SpecializeLiteralConstant)
6587fa27ce4SDimitry Andric       continue;
6597fa27ce4SDimitry Andric 
660b1c73532SDimitry Andric     int64_t Sz = *Metrics.NumInsts.getValue();
661b1c73532SDimitry Andric     assert(Sz > 0 && "CodeSize should be positive");
662b1c73532SDimitry Andric     // It is safe to down cast from int64_t, NumInsts is always positive.
663b1c73532SDimitry Andric     unsigned FuncSize = static_cast<unsigned>(Sz);
664b1c73532SDimitry Andric 
6657fa27ce4SDimitry Andric     LLVM_DEBUG(dbgs() << "FnSpecialization: Specialization cost for "
666b1c73532SDimitry Andric                       << F.getName() << " is " << FuncSize << "\n");
6677fa27ce4SDimitry Andric 
6687fa27ce4SDimitry Andric     if (Inserted && Metrics.isRecursive)
6697fa27ce4SDimitry Andric       promoteConstantStackValues(&F);
6707fa27ce4SDimitry Andric 
671b1c73532SDimitry Andric     if (!findSpecializations(&F, FuncSize, AllSpecs, SM)) {
672e3b55780SDimitry Andric       LLVM_DEBUG(
673e3b55780SDimitry Andric           dbgs() << "FnSpecialization: No possible specializations found for "
674e3b55780SDimitry Andric                  << F.getName() << "\n");
67577fc4c14SDimitry Andric       continue;
67677fc4c14SDimitry Andric     }
67777fc4c14SDimitry Andric 
678e3b55780SDimitry Andric     ++NumCandidates;
679344a3780SDimitry Andric   }
680344a3780SDimitry Andric 
681e3b55780SDimitry Andric   if (!NumCandidates) {
682e3b55780SDimitry Andric     LLVM_DEBUG(
683e3b55780SDimitry Andric         dbgs()
684e3b55780SDimitry Andric         << "FnSpecialization: No possible specializations found in module\n");
685e3b55780SDimitry Andric     return false;
686e3b55780SDimitry Andric   }
687e3b55780SDimitry Andric 
688e3b55780SDimitry Andric   // Choose the most profitable specialisations, which fit in the module
689e3b55780SDimitry Andric   // specialization budget, which is derived from maximum number of
690e3b55780SDimitry Andric   // specializations per specialization candidate function.
6917fa27ce4SDimitry Andric   auto CompareScore = [&AllSpecs](unsigned I, unsigned J) {
692ac9a064cSDimitry Andric     if (AllSpecs[I].Score != AllSpecs[J].Score)
6937fa27ce4SDimitry Andric       return AllSpecs[I].Score > AllSpecs[J].Score;
694ac9a064cSDimitry Andric     return I > J;
695e3b55780SDimitry Andric   };
696e3b55780SDimitry Andric   const unsigned NSpecs =
6977fa27ce4SDimitry Andric       std::min(NumCandidates * MaxClones, unsigned(AllSpecs.size()));
698e3b55780SDimitry Andric   SmallVector<unsigned> BestSpecs(NSpecs + 1);
699e3b55780SDimitry Andric   std::iota(BestSpecs.begin(), BestSpecs.begin() + NSpecs, 0);
700e3b55780SDimitry Andric   if (AllSpecs.size() > NSpecs) {
701e3b55780SDimitry Andric     LLVM_DEBUG(dbgs() << "FnSpecialization: Number of candidates exceed "
702e3b55780SDimitry Andric                       << "the maximum number of clones threshold.\n"
703e3b55780SDimitry Andric                       << "FnSpecialization: Specializing the "
704e3b55780SDimitry Andric                       << NSpecs
705e3b55780SDimitry Andric                       << " most profitable candidates.\n");
7067fa27ce4SDimitry Andric     std::make_heap(BestSpecs.begin(), BestSpecs.begin() + NSpecs, CompareScore);
707e3b55780SDimitry Andric     for (unsigned I = NSpecs, N = AllSpecs.size(); I < N; ++I) {
708e3b55780SDimitry Andric       BestSpecs[NSpecs] = I;
7097fa27ce4SDimitry Andric       std::push_heap(BestSpecs.begin(), BestSpecs.end(), CompareScore);
7107fa27ce4SDimitry Andric       std::pop_heap(BestSpecs.begin(), BestSpecs.end(), CompareScore);
711e3b55780SDimitry Andric     }
712e3b55780SDimitry Andric   }
713e3b55780SDimitry Andric 
714e3b55780SDimitry Andric   LLVM_DEBUG(dbgs() << "FnSpecialization: List of specializations \n";
715e3b55780SDimitry Andric              for (unsigned I = 0; I < NSpecs; ++I) {
716e3b55780SDimitry Andric                const Spec &S = AllSpecs[BestSpecs[I]];
717e3b55780SDimitry Andric                dbgs() << "FnSpecialization: Function " << S.F->getName()
7187fa27ce4SDimitry Andric                       << " , score " << S.Score << "\n";
719e3b55780SDimitry Andric                for (const ArgInfo &Arg : S.Sig.Args)
720e3b55780SDimitry Andric                  dbgs() << "FnSpecialization:   FormalArg = "
721e3b55780SDimitry Andric                         << Arg.Formal->getNameOrAsOperand()
722e3b55780SDimitry Andric                         << ", ActualArg = " << Arg.Actual->getNameOrAsOperand()
723e3b55780SDimitry Andric                         << "\n";
724e3b55780SDimitry Andric              });
725e3b55780SDimitry Andric 
726e3b55780SDimitry Andric   // Create the chosen specializations.
727e3b55780SDimitry Andric   SmallPtrSet<Function *, 8> OriginalFuncs;
728e3b55780SDimitry Andric   SmallVector<Function *> Clones;
729e3b55780SDimitry Andric   for (unsigned I = 0; I < NSpecs; ++I) {
730e3b55780SDimitry Andric     Spec &S = AllSpecs[BestSpecs[I]];
731e3b55780SDimitry Andric     S.Clone = createSpecialization(S.F, S.Sig);
732e3b55780SDimitry Andric 
733e3b55780SDimitry Andric     // Update the known call sites to call the clone.
734e3b55780SDimitry Andric     for (CallBase *Call : S.CallSites) {
735e3b55780SDimitry Andric       LLVM_DEBUG(dbgs() << "FnSpecialization: Redirecting " << *Call
736e3b55780SDimitry Andric                         << " to call " << S.Clone->getName() << "\n");
737e3b55780SDimitry Andric       Call->setCalledFunction(S.Clone);
738e3b55780SDimitry Andric     }
739e3b55780SDimitry Andric 
740e3b55780SDimitry Andric     Clones.push_back(S.Clone);
741e3b55780SDimitry Andric     OriginalFuncs.insert(S.F);
742e3b55780SDimitry Andric   }
743e3b55780SDimitry Andric 
744e3b55780SDimitry Andric   Solver.solveWhileResolvedUndefsIn(Clones);
745e3b55780SDimitry Andric 
746e3b55780SDimitry Andric   // Update the rest of the call sites - these are the recursive calls, calls
747e3b55780SDimitry Andric   // to discarded specialisations and calls that may match a specialisation
748e3b55780SDimitry Andric   // after the solver runs.
749e3b55780SDimitry Andric   for (Function *F : OriginalFuncs) {
750e3b55780SDimitry Andric     auto [Begin, End] = SM[F];
751e3b55780SDimitry Andric     updateCallSites(F, AllSpecs.begin() + Begin, AllSpecs.begin() + End);
752e3b55780SDimitry Andric   }
753e3b55780SDimitry Andric 
7547fa27ce4SDimitry Andric   for (Function *F : Clones) {
7557fa27ce4SDimitry Andric     if (F->getReturnType()->isVoidTy())
7567fa27ce4SDimitry Andric       continue;
7577fa27ce4SDimitry Andric     if (F->getReturnType()->isStructTy()) {
7587fa27ce4SDimitry Andric       auto *STy = cast<StructType>(F->getReturnType());
7597fa27ce4SDimitry Andric       if (!Solver.isStructLatticeConstant(F, STy))
7607fa27ce4SDimitry Andric         continue;
7617fa27ce4SDimitry Andric     } else {
7627fa27ce4SDimitry Andric       auto It = Solver.getTrackedRetVals().find(F);
7637fa27ce4SDimitry Andric       assert(It != Solver.getTrackedRetVals().end() &&
7647fa27ce4SDimitry Andric              "Return value ought to be tracked");
7657fa27ce4SDimitry Andric       if (SCCPSolver::isOverdefined(It->second))
7667fa27ce4SDimitry Andric         continue;
7677fa27ce4SDimitry Andric     }
7687fa27ce4SDimitry Andric     for (User *U : F->users()) {
7697fa27ce4SDimitry Andric       if (auto *CS = dyn_cast<CallBase>(U)) {
7707fa27ce4SDimitry Andric         //The user instruction does not call our function.
7717fa27ce4SDimitry Andric         if (CS->getCalledFunction() != F)
7727fa27ce4SDimitry Andric           continue;
7737fa27ce4SDimitry Andric         Solver.resetLatticeValueFor(CS);
7747fa27ce4SDimitry Andric       }
7757fa27ce4SDimitry Andric     }
7767fa27ce4SDimitry Andric   }
777e3b55780SDimitry Andric 
7787fa27ce4SDimitry Andric   // Rerun the solver to notify the users of the modified callsites.
7797fa27ce4SDimitry Andric   Solver.solveWhileResolvedUndefs();
7807fa27ce4SDimitry Andric 
7817fa27ce4SDimitry Andric   for (Function *F : OriginalFuncs)
7827fa27ce4SDimitry Andric     if (FunctionMetrics[F].isRecursive)
7837fa27ce4SDimitry Andric       promoteConstantStackValues(F);
7847fa27ce4SDimitry Andric 
785e3b55780SDimitry Andric   return true;
786344a3780SDimitry Andric }
787344a3780SDimitry Andric 
removeDeadFunctions()788e3b55780SDimitry Andric void FunctionSpecializer::removeDeadFunctions() {
789e3b55780SDimitry Andric   for (Function *F : FullySpecialized) {
790145449b1SDimitry Andric     LLVM_DEBUG(dbgs() << "FnSpecialization: Removing dead function "
791145449b1SDimitry Andric                       << F->getName() << "\n");
792e3b55780SDimitry Andric     if (FAM)
793e3b55780SDimitry Andric       FAM->clear(*F, F->getName());
794145449b1SDimitry Andric     F->eraseFromParent();
795145449b1SDimitry Andric   }
796145449b1SDimitry Andric   FullySpecialized.clear();
797145449b1SDimitry Andric }
798145449b1SDimitry Andric 
799c0981da4SDimitry Andric /// Clone the function \p F and remove the ssa_copy intrinsics added by
800c0981da4SDimitry Andric /// the SCCPSolver in the cloned version.
cloneCandidateFunction(Function * F,unsigned NSpecs)801b1c73532SDimitry Andric static Function *cloneCandidateFunction(Function *F, unsigned NSpecs) {
802e3b55780SDimitry Andric   ValueToValueMapTy Mappings;
803145449b1SDimitry Andric   Function *Clone = CloneFunction(F, Mappings);
804b1c73532SDimitry Andric   Clone->setName(F->getName() + ".specialized." + Twine(NSpecs));
805c0981da4SDimitry Andric   removeSSACopy(*Clone);
806c0981da4SDimitry Andric   return Clone;
807c0981da4SDimitry Andric }
808c0981da4SDimitry Andric 
findSpecializations(Function * F,unsigned FuncSize,SmallVectorImpl<Spec> & AllSpecs,SpecMap & SM)809b1c73532SDimitry Andric bool FunctionSpecializer::findSpecializations(Function *F, unsigned FuncSize,
810e3b55780SDimitry Andric                                               SmallVectorImpl<Spec> &AllSpecs,
811e3b55780SDimitry Andric                                               SpecMap &SM) {
812e3b55780SDimitry Andric   // A mapping from a specialisation signature to the index of the respective
813e3b55780SDimitry Andric   // entry in the all specialisation array. Used to ensure uniqueness of
814e3b55780SDimitry Andric   // specialisations.
8157fa27ce4SDimitry Andric   DenseMap<SpecSig, unsigned> UniqueSpecs;
816e3b55780SDimitry Andric 
817e3b55780SDimitry Andric   // Get a list of interesting arguments.
818e3b55780SDimitry Andric   SmallVector<Argument *> Args;
819e3b55780SDimitry Andric   for (Argument &Arg : F->args())
820e3b55780SDimitry Andric     if (isArgumentInteresting(&Arg))
821e3b55780SDimitry Andric       Args.push_back(&Arg);
822e3b55780SDimitry Andric 
823e3b55780SDimitry Andric   if (Args.empty())
824e3b55780SDimitry Andric     return false;
825e3b55780SDimitry Andric 
826e3b55780SDimitry Andric   for (User *U : F->users()) {
827e3b55780SDimitry Andric     if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
82877fc4c14SDimitry Andric       continue;
829e3b55780SDimitry Andric     auto &CS = *cast<CallBase>(U);
830e3b55780SDimitry Andric 
831e3b55780SDimitry Andric     // The user instruction does not call our function.
832e3b55780SDimitry Andric     if (CS.getCalledFunction() != F)
833e3b55780SDimitry Andric       continue;
834e3b55780SDimitry Andric 
835e3b55780SDimitry Andric     // If the call site has attribute minsize set, that callsite won't be
836e3b55780SDimitry Andric     // specialized.
837e3b55780SDimitry Andric     if (CS.hasFnAttr(Attribute::MinSize))
838e3b55780SDimitry Andric       continue;
839e3b55780SDimitry Andric 
840e3b55780SDimitry Andric     // If the parent of the call site will never be executed, we don't need
841e3b55780SDimitry Andric     // to worry about the passed value.
842e3b55780SDimitry Andric     if (!Solver.isBlockExecutable(CS.getParent()))
843e3b55780SDimitry Andric       continue;
844e3b55780SDimitry Andric 
845e3b55780SDimitry Andric     // Examine arguments and create a specialisation candidate from the
846e3b55780SDimitry Andric     // constant operands of this call site.
847e3b55780SDimitry Andric     SpecSig S;
848e3b55780SDimitry Andric     for (Argument *A : Args) {
849e3b55780SDimitry Andric       Constant *C = getCandidateConstant(CS.getArgOperand(A->getArgNo()));
850e3b55780SDimitry Andric       if (!C)
851e3b55780SDimitry Andric         continue;
852e3b55780SDimitry Andric       LLVM_DEBUG(dbgs() << "FnSpecialization: Found interesting argument "
853e3b55780SDimitry Andric                         << A->getName() << " : " << C->getNameOrAsOperand()
854e3b55780SDimitry Andric                         << "\n");
855e3b55780SDimitry Andric       S.Args.push_back({A, C});
85677fc4c14SDimitry Andric     }
857344a3780SDimitry Andric 
858e3b55780SDimitry Andric     if (S.Args.empty())
859e3b55780SDimitry Andric       continue;
86077fc4c14SDimitry Andric 
861e3b55780SDimitry Andric     // Check if we have encountered the same specialisation already.
8627fa27ce4SDimitry Andric     if (auto It = UniqueSpecs.find(S); It != UniqueSpecs.end()) {
863e3b55780SDimitry Andric       // Existing specialisation. Add the call to the list to rewrite, unless
864e3b55780SDimitry Andric       // it's a recursive call. A specialisation, generated because of a
865e3b55780SDimitry Andric       // recursive call may end up as not the best specialisation for all
866e3b55780SDimitry Andric       // the cloned instances of this call, which result from specialising
867e3b55780SDimitry Andric       // functions. Hence we don't rewrite the call directly, but match it with
868e3b55780SDimitry Andric       // the best specialisation once all specialisations are known.
869e3b55780SDimitry Andric       if (CS.getFunction() == F)
870e3b55780SDimitry Andric         continue;
871e3b55780SDimitry Andric       const unsigned Index = It->second;
872e3b55780SDimitry Andric       AllSpecs[Index].CallSites.push_back(&CS);
873e3b55780SDimitry Andric     } else {
874e3b55780SDimitry Andric       // Calculate the specialisation gain.
875b1c73532SDimitry Andric       Bonus B;
876b1c73532SDimitry Andric       unsigned Score = 0;
8777fa27ce4SDimitry Andric       InstCostVisitor Visitor = getInstCostVisitorFor(F);
878b1c73532SDimitry Andric       for (ArgInfo &A : S.Args) {
879b1c73532SDimitry Andric         B += Visitor.getSpecializationBonus(A.Formal, A.Actual);
880b1c73532SDimitry Andric         Score += getInliningBonus(A.Formal, A.Actual);
881b1c73532SDimitry Andric       }
882b1c73532SDimitry Andric       B += Visitor.getBonusFromPendingPHIs();
8837fa27ce4SDimitry Andric 
884b1c73532SDimitry Andric 
885b1c73532SDimitry Andric       LLVM_DEBUG(dbgs() << "FnSpecialization: Specialization bonus {CodeSize = "
886b1c73532SDimitry Andric                         << B.CodeSize << ", Latency = " << B.Latency
887b1c73532SDimitry Andric                         << ", Inlining = " << Score << "}\n");
888b1c73532SDimitry Andric 
889b1c73532SDimitry Andric       FunctionGrowth[F] += FuncSize - B.CodeSize;
890b1c73532SDimitry Andric 
891b1c73532SDimitry Andric       auto IsProfitable = [](Bonus &B, unsigned Score, unsigned FuncSize,
892b1c73532SDimitry Andric                              unsigned FuncGrowth) -> bool {
893b1c73532SDimitry Andric         // No check required.
894b1c73532SDimitry Andric         if (ForceSpecialization)
895b1c73532SDimitry Andric           return true;
896b1c73532SDimitry Andric         // Minimum inlining bonus.
897b1c73532SDimitry Andric         if (Score > MinInliningBonus * FuncSize / 100)
898b1c73532SDimitry Andric           return true;
899b1c73532SDimitry Andric         // Minimum codesize savings.
900b1c73532SDimitry Andric         if (B.CodeSize < MinCodeSizeSavings * FuncSize / 100)
901b1c73532SDimitry Andric           return false;
902b1c73532SDimitry Andric         // Minimum latency savings.
903b1c73532SDimitry Andric         if (B.Latency < MinLatencySavings * FuncSize / 100)
904b1c73532SDimitry Andric           return false;
905b1c73532SDimitry Andric         // Maximum codesize growth.
906b1c73532SDimitry Andric         if (FuncGrowth / FuncSize > MaxCodeSizeGrowth)
907b1c73532SDimitry Andric           return false;
908b1c73532SDimitry Andric         return true;
909b1c73532SDimitry Andric       };
910145449b1SDimitry Andric 
911e3b55780SDimitry Andric       // Discard unprofitable specialisations.
912b1c73532SDimitry Andric       if (!IsProfitable(B, Score, FuncSize, FunctionGrowth[F]))
913e3b55780SDimitry Andric         continue;
914e3b55780SDimitry Andric 
915e3b55780SDimitry Andric       // Create a new specialisation entry.
916b1c73532SDimitry Andric       Score += std::max(B.CodeSize, B.Latency);
9177fa27ce4SDimitry Andric       auto &Spec = AllSpecs.emplace_back(F, S, Score);
918e3b55780SDimitry Andric       if (CS.getFunction() != F)
919e3b55780SDimitry Andric         Spec.CallSites.push_back(&CS);
920e3b55780SDimitry Andric       const unsigned Index = AllSpecs.size() - 1;
9217fa27ce4SDimitry Andric       UniqueSpecs[S] = Index;
922e3b55780SDimitry Andric       if (auto [It, Inserted] = SM.try_emplace(F, Index, Index + 1); !Inserted)
923e3b55780SDimitry Andric         It->second.second = Index + 1;
924145449b1SDimitry Andric     }
92577fc4c14SDimitry Andric   }
92677fc4c14SDimitry Andric 
9277fa27ce4SDimitry Andric   return !UniqueSpecs.empty();
92877fc4c14SDimitry Andric }
92977fc4c14SDimitry Andric 
isCandidateFunction(Function * F)930e3b55780SDimitry Andric bool FunctionSpecializer::isCandidateFunction(Function *F) {
9317fa27ce4SDimitry Andric   if (F->isDeclaration() || F->arg_empty())
932e3b55780SDimitry Andric     return false;
93377fc4c14SDimitry Andric 
934e3b55780SDimitry Andric   if (F->hasFnAttribute(Attribute::NoDuplicate))
935e3b55780SDimitry Andric     return false;
93677fc4c14SDimitry Andric 
937344a3780SDimitry Andric   // Do not specialize the cloned function again.
9387fa27ce4SDimitry Andric   if (Specializations.contains(F))
939344a3780SDimitry Andric     return false;
940344a3780SDimitry Andric 
941344a3780SDimitry Andric   // If we're optimizing the function for size, we shouldn't specialize it.
942344a3780SDimitry Andric   if (F->hasOptSize() ||
943344a3780SDimitry Andric       shouldOptimizeForSize(F, nullptr, nullptr, PGSOQueryType::IRPass))
944344a3780SDimitry Andric     return false;
945344a3780SDimitry Andric 
946344a3780SDimitry Andric   // Exit if the function is not executable. There's no point in specializing
947344a3780SDimitry Andric   // a dead function.
948344a3780SDimitry Andric   if (!Solver.isBlockExecutable(&F->getEntryBlock()))
949344a3780SDimitry Andric     return false;
950344a3780SDimitry Andric 
951c0981da4SDimitry Andric   // It wastes time to specialize a function which would get inlined finally.
952c0981da4SDimitry Andric   if (F->hasFnAttribute(Attribute::AlwaysInline))
953c0981da4SDimitry Andric     return false;
954c0981da4SDimitry Andric 
955344a3780SDimitry Andric   LLVM_DEBUG(dbgs() << "FnSpecialization: Try function: " << F->getName()
956344a3780SDimitry Andric                     << "\n");
95777fc4c14SDimitry Andric   return true;
958c0981da4SDimitry Andric }
959c0981da4SDimitry Andric 
createSpecialization(Function * F,const SpecSig & S)9607fa27ce4SDimitry Andric Function *FunctionSpecializer::createSpecialization(Function *F,
9617fa27ce4SDimitry Andric                                                     const SpecSig &S) {
962b1c73532SDimitry Andric   Function *Clone = cloneCandidateFunction(F, Specializations.size() + 1);
963344a3780SDimitry Andric 
9647fa27ce4SDimitry Andric   // The original function does not neccessarily have internal linkage, but the
9657fa27ce4SDimitry Andric   // clone must.
9667fa27ce4SDimitry Andric   Clone->setLinkage(GlobalValue::InternalLinkage);
9677fa27ce4SDimitry Andric 
968344a3780SDimitry Andric   // Initialize the lattice state of the arguments of the function clone,
969344a3780SDimitry Andric   // marking the argument on which we specialized the function constant
970344a3780SDimitry Andric   // with the given value.
9717fa27ce4SDimitry Andric   Solver.setLatticeValueForSpecializationArguments(Clone, S.Args);
972e3b55780SDimitry Andric   Solver.markBlockExecutable(&Clone->front());
9737fa27ce4SDimitry Andric   Solver.addArgumentTrackedFunction(Clone);
9747fa27ce4SDimitry Andric   Solver.addTrackedFunction(Clone);
975e3b55780SDimitry Andric 
976344a3780SDimitry Andric   // Mark all the specialized functions
9777fa27ce4SDimitry Andric   Specializations.insert(Clone);
9787fa27ce4SDimitry Andric   ++NumSpecsCreated;
979344a3780SDimitry Andric 
980e3b55780SDimitry Andric   return Clone;
981344a3780SDimitry Andric }
982344a3780SDimitry Andric 
983b1c73532SDimitry Andric /// Compute the inlining bonus for replacing argument \p A with constant \p C.
984b1c73532SDimitry Andric /// The below heuristic is only concerned with exposing inlining
985b1c73532SDimitry Andric /// opportunities via indirect call promotion. If the argument is not a
986b1c73532SDimitry Andric /// (potentially casted) function pointer, give up.
getInliningBonus(Argument * A,Constant * C)987b1c73532SDimitry Andric unsigned FunctionSpecializer::getInliningBonus(Argument *A, Constant *C) {
988145449b1SDimitry Andric   Function *CalledFunction = dyn_cast<Function>(C->stripPointerCasts());
989344a3780SDimitry Andric   if (!CalledFunction)
990b1c73532SDimitry Andric     return 0;
991344a3780SDimitry Andric 
992344a3780SDimitry Andric   // Get TTI for the called function (used for the inline cost).
993344a3780SDimitry Andric   auto &CalleeTTI = (GetTTI)(*CalledFunction);
994344a3780SDimitry Andric 
995344a3780SDimitry Andric   // Look at all the call sites whose called value is the argument.
996344a3780SDimitry Andric   // Specializing the function on the argument would allow these indirect
997344a3780SDimitry Andric   // calls to be promoted to direct calls. If the indirect call promotion
998344a3780SDimitry Andric   // would likely enable the called function to be inlined, specializing is a
999344a3780SDimitry Andric   // good idea.
1000b1c73532SDimitry Andric   int InliningBonus = 0;
1001344a3780SDimitry Andric   for (User *U : A->users()) {
1002344a3780SDimitry Andric     if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
1003344a3780SDimitry Andric       continue;
1004344a3780SDimitry Andric     auto *CS = cast<CallBase>(U);
1005344a3780SDimitry Andric     if (CS->getCalledOperand() != A)
1006344a3780SDimitry Andric       continue;
1007e3b55780SDimitry Andric     if (CS->getFunctionType() != CalledFunction->getFunctionType())
1008e3b55780SDimitry Andric       continue;
1009344a3780SDimitry Andric 
1010344a3780SDimitry Andric     // Get the cost of inlining the called function at this call site. Note
1011344a3780SDimitry Andric     // that this is only an estimate. The called function may eventually
1012344a3780SDimitry Andric     // change in a way that leads to it not being inlined here, even though
1013344a3780SDimitry Andric     // inlining looks profitable now. For example, one of its called
1014344a3780SDimitry Andric     // functions may be inlined into it, making the called function too large
1015344a3780SDimitry Andric     // to be inlined into this call site.
1016344a3780SDimitry Andric     //
1017344a3780SDimitry Andric     // We apply a boost for performing indirect call promotion by increasing
1018344a3780SDimitry Andric     // the default threshold by the threshold for indirect calls.
1019344a3780SDimitry Andric     auto Params = getInlineParams();
1020344a3780SDimitry Andric     Params.DefaultThreshold += InlineConstants::IndirectCallThreshold;
1021344a3780SDimitry Andric     InlineCost IC =
1022344a3780SDimitry Andric         getInlineCost(*CS, CalledFunction, Params, CalleeTTI, GetAC, GetTLI);
1023344a3780SDimitry Andric 
1024344a3780SDimitry Andric     // We clamp the bonus for this call to be between zero and the default
1025344a3780SDimitry Andric     // threshold.
1026344a3780SDimitry Andric     if (IC.isAlways())
1027b1c73532SDimitry Andric       InliningBonus += Params.DefaultThreshold;
1028344a3780SDimitry Andric     else if (IC.isVariable() && IC.getCostDelta() > 0)
1029b1c73532SDimitry Andric       InliningBonus += IC.getCostDelta();
1030145449b1SDimitry Andric 
1031b1c73532SDimitry Andric     LLVM_DEBUG(dbgs() << "FnSpecialization:   Inlining bonus " << InliningBonus
1032145449b1SDimitry Andric                       << " for user " << *U << "\n");
1033344a3780SDimitry Andric   }
1034344a3780SDimitry Andric 
1035b1c73532SDimitry Andric   return InliningBonus > 0 ? static_cast<unsigned>(InliningBonus) : 0;
1036344a3780SDimitry Andric }
1037344a3780SDimitry Andric 
1038e3b55780SDimitry Andric /// Determine if it is possible to specialise the function for constant values
1039e3b55780SDimitry Andric /// of the formal parameter \p A.
isArgumentInteresting(Argument * A)1040e3b55780SDimitry Andric bool FunctionSpecializer::isArgumentInteresting(Argument *A) {
1041e3b55780SDimitry Andric   // No point in specialization if the argument is unused.
1042e3b55780SDimitry Andric   if (A->user_empty())
1043e3b55780SDimitry Andric     return false;
1044e3b55780SDimitry Andric 
10457fa27ce4SDimitry Andric   Type *Ty = A->getType();
10467fa27ce4SDimitry Andric   if (!Ty->isPointerTy() && (!SpecializeLiteralConstant ||
10477fa27ce4SDimitry Andric       (!Ty->isIntegerTy() && !Ty->isFloatingPointTy() && !Ty->isStructTy())))
1048344a3780SDimitry Andric     return false;
1049145449b1SDimitry Andric 
1050145449b1SDimitry Andric   // SCCP solver does not record an argument that will be constructed on
1051145449b1SDimitry Andric   // stack.
1052e3b55780SDimitry Andric   if (A->hasByValAttr() && !A->getParent()->onlyReadsMemory())
1053e3b55780SDimitry Andric     return false;
1054344a3780SDimitry Andric 
10557fa27ce4SDimitry Andric   // For non-argument-tracked functions every argument is overdefined.
10567fa27ce4SDimitry Andric   if (!Solver.isArgumentTrackedFunction(A->getParent()))
10577fa27ce4SDimitry Andric     return true;
10587fa27ce4SDimitry Andric 
1059e3b55780SDimitry Andric   // Check the lattice value and decide if we should attemt to specialize,
1060e3b55780SDimitry Andric   // based on this argument. No point in specialization, if the lattice value
1061e3b55780SDimitry Andric   // is already a constant.
10627fa27ce4SDimitry Andric   bool IsOverdefined = Ty->isStructTy()
10637fa27ce4SDimitry Andric     ? any_of(Solver.getStructLatticeValueFor(A), SCCPSolver::isOverdefined)
10647fa27ce4SDimitry Andric     : SCCPSolver::isOverdefined(Solver.getLatticeValueFor(A));
10657fa27ce4SDimitry Andric 
10667fa27ce4SDimitry Andric   LLVM_DEBUG(
10677fa27ce4SDimitry Andric     if (IsOverdefined)
10687fa27ce4SDimitry Andric       dbgs() << "FnSpecialization: Found interesting parameter "
10697fa27ce4SDimitry Andric              << A->getNameOrAsOperand() << "\n";
10707fa27ce4SDimitry Andric     else
10717fa27ce4SDimitry Andric       dbgs() << "FnSpecialization: Nothing to do, parameter "
10727fa27ce4SDimitry Andric              << A->getNameOrAsOperand() << " is already constant\n";
10737fa27ce4SDimitry Andric   );
10747fa27ce4SDimitry Andric   return IsOverdefined;
1075e3b55780SDimitry Andric }
1076344a3780SDimitry Andric 
10777fa27ce4SDimitry Andric /// Check if the value \p V  (an actual argument) is a constant or can only
1078e3b55780SDimitry Andric /// have a constant value. Return that constant.
getCandidateConstant(Value * V)1079e3b55780SDimitry Andric Constant *FunctionSpecializer::getCandidateConstant(Value *V) {
1080c0981da4SDimitry Andric   if (isa<PoisonValue>(V))
1081e3b55780SDimitry Andric     return nullptr;
1082c0981da4SDimitry Andric 
1083e3b55780SDimitry Andric   // Select for possible specialisation values that are constants or
1084e3b55780SDimitry Andric   // are deduced to be constants or constant ranges with a single element.
1085e3b55780SDimitry Andric   Constant *C = dyn_cast<Constant>(V);
10867fa27ce4SDimitry Andric   if (!C)
10877fa27ce4SDimitry Andric     C = Solver.getConstantOrNull(V);
10887fa27ce4SDimitry Andric 
10897fa27ce4SDimitry Andric   // Don't specialize on (anything derived from) the address of a non-constant
10907fa27ce4SDimitry Andric   // global variable, unless explicitly enabled.
10917fa27ce4SDimitry Andric   if (C && C->getType()->isPointerTy() && !C->isNullValue())
10927fa27ce4SDimitry Andric     if (auto *GV = dyn_cast<GlobalVariable>(getUnderlyingObject(C));
10937fa27ce4SDimitry Andric         GV && !(GV->isConstant() || SpecializeOnAddress))
1094e3b55780SDimitry Andric       return nullptr;
1095344a3780SDimitry Andric 
1096e3b55780SDimitry Andric   return C;
1097e3b55780SDimitry Andric }
1098145449b1SDimitry Andric 
updateCallSites(Function * F,const Spec * Begin,const Spec * End)1099e3b55780SDimitry Andric void FunctionSpecializer::updateCallSites(Function *F, const Spec *Begin,
1100e3b55780SDimitry Andric                                           const Spec *End) {
1101e3b55780SDimitry Andric   // Collect the call sites that need updating.
1102e3b55780SDimitry Andric   SmallVector<CallBase *> ToUpdate;
1103e3b55780SDimitry Andric   for (User *U : F->users())
1104e3b55780SDimitry Andric     if (auto *CS = dyn_cast<CallBase>(U);
1105e3b55780SDimitry Andric         CS && CS->getCalledFunction() == F &&
1106e3b55780SDimitry Andric         Solver.isBlockExecutable(CS->getParent()))
1107e3b55780SDimitry Andric       ToUpdate.push_back(CS);
1108e3b55780SDimitry Andric 
1109e3b55780SDimitry Andric   unsigned NCallsLeft = ToUpdate.size();
1110e3b55780SDimitry Andric   for (CallBase *CS : ToUpdate) {
1111e3b55780SDimitry Andric     bool ShouldDecrementCount = CS->getFunction() == F;
1112e3b55780SDimitry Andric 
1113e3b55780SDimitry Andric     // Find the best matching specialisation.
1114e3b55780SDimitry Andric     const Spec *BestSpec = nullptr;
1115e3b55780SDimitry Andric     for (const Spec &S : make_range(Begin, End)) {
11167fa27ce4SDimitry Andric       if (!S.Clone || (BestSpec && S.Score <= BestSpec->Score))
1117344a3780SDimitry Andric         continue;
1118145449b1SDimitry Andric 
1119e3b55780SDimitry Andric       if (any_of(S.Sig.Args, [CS, this](const ArgInfo &Arg) {
1120145449b1SDimitry Andric             unsigned ArgNo = Arg.Formal->getArgNo();
1121e3b55780SDimitry Andric             return getCandidateConstant(CS->getArgOperand(ArgNo)) != Arg.Actual;
1122e3b55780SDimitry Andric           }))
1123344a3780SDimitry Andric         continue;
1124344a3780SDimitry Andric 
1125e3b55780SDimitry Andric       BestSpec = &S;
1126344a3780SDimitry Andric     }
1127344a3780SDimitry Andric 
1128e3b55780SDimitry Andric     if (BestSpec) {
1129e3b55780SDimitry Andric       LLVM_DEBUG(dbgs() << "FnSpecialization: Redirecting " << *CS
1130e3b55780SDimitry Andric                         << " to call " << BestSpec->Clone->getName() << "\n");
1131e3b55780SDimitry Andric       CS->setCalledFunction(BestSpec->Clone);
1132e3b55780SDimitry Andric       ShouldDecrementCount = true;
1133344a3780SDimitry Andric     }
1134344a3780SDimitry Andric 
1135e3b55780SDimitry Andric     if (ShouldDecrementCount)
1136e3b55780SDimitry Andric       --NCallsLeft;
1137344a3780SDimitry Andric   }
1138344a3780SDimitry Andric 
1139e3b55780SDimitry Andric   // If the function has been completely specialized, the original function
1140e3b55780SDimitry Andric   // is no longer needed. Mark it unreachable.
11417fa27ce4SDimitry Andric   if (NCallsLeft == 0 && Solver.isArgumentTrackedFunction(F)) {
1142e3b55780SDimitry Andric     Solver.markFunctionUnreachable(F);
1143e3b55780SDimitry Andric     FullySpecialized.insert(F);
1144c0981da4SDimitry Andric   }
1145344a3780SDimitry Andric }
1146