LLVM 22.0.0git
FunctionSpecialization.cpp
Go to the documentation of this file.
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
10#include "llvm/ADT/Statistic.h"
23#include <cmath>
24
25using namespace llvm;
26
27#define DEBUG_TYPE "function-specialization"
28
29STATISTIC(NumSpecsCreated, "Number of specializations created");
30
32 "force-specialization", cl::init(false), cl::Hidden, cl::desc(
33 "Force function specialization for every call site with a constant "
34 "argument"));
35
37 "funcspec-max-clones", cl::init(3), cl::Hidden, cl::desc(
38 "The maximum number of clones allowed for a single function "
39 "specialization"));
40
42 MaxDiscoveryIterations("funcspec-max-discovery-iterations", cl::init(100),
44 cl::desc("The maximum number of iterations allowed "
45 "when searching for transitive "
46 "phis"));
47
49 "funcspec-max-incoming-phi-values", cl::init(8), cl::Hidden,
50 cl::desc("The maximum number of incoming values a PHI node can have to be "
51 "considered during the specialization bonus estimation"));
52
54 "funcspec-max-block-predecessors", cl::init(2), cl::Hidden, cl::desc(
55 "The maximum number of predecessors a basic block can have to be "
56 "considered during the estimation of dead code"));
57
59 "funcspec-min-function-size", cl::init(500), cl::Hidden,
60 cl::desc("Don't specialize functions that have less than this number of "
61 "instructions"));
62
64 "funcspec-max-codesize-growth", cl::init(3), cl::Hidden, cl::desc(
65 "Maximum codesize growth allowed per function"));
66
68 "funcspec-min-codesize-savings", cl::init(20), cl::Hidden,
69 cl::desc("Reject specializations whose codesize savings are less than this "
70 "much percent of the original function size"));
71
73 "funcspec-min-latency-savings", cl::init(20), cl::Hidden,
74 cl::desc("Reject specializations whose latency savings are less than this "
75 "much percent of the original function size"));
76
78 "funcspec-min-inlining-bonus", cl::init(300), cl::Hidden,
79 cl::desc("Reject specializations whose inlining bonus is less than this "
80 "much percent of the original function size"));
81
83 "funcspec-on-address", cl::init(false), cl::Hidden, cl::desc(
84 "Enable function specialization on the address of global values"));
85
87 "funcspec-for-literal-constant", cl::init(true), cl::Hidden,
89 "Enable specialization of functions that take a literal constant as an "
90 "argument"));
91
93
94bool InstCostVisitor::canEliminateSuccessor(BasicBlock *BB,
95 BasicBlock *Succ) const {
96 unsigned I = 0;
97 return all_of(predecessors(Succ), [&I, BB, Succ, this](BasicBlock *Pred) {
98 return I++ < MaxBlockPredecessors &&
99 (Pred == BB || Pred == Succ || !isBlockExecutable(Pred));
100 });
101}
102
103// Estimates the codesize savings due to dead code after constant propagation.
104// \p WorkList represents the basic blocks of a specialization which will
105// eventually become dead once we replace instructions that are known to be
106// constants. The successors of such blocks are added to the list as long as
107// the \p Solver found they were executable prior to specialization, and only
108// if all their predecessors are dead.
109Cost InstCostVisitor::estimateBasicBlocks(
111 Cost CodeSize = 0;
112 // Accumulate the codesize savings of each basic block.
113 while (!WorkList.empty()) {
114 BasicBlock *BB = WorkList.pop_back_val();
115
116 // These blocks are considered dead as far as the InstCostVisitor
117 // is concerned. They haven't been proven dead yet by the Solver,
118 // but may become if we propagate the specialization arguments.
119 assert(Solver.isBlockExecutable(BB) && "BB already found dead by IPSCCP!");
120 if (!DeadBlocks.insert(BB).second)
121 continue;
122
123 for (Instruction &I : *BB) {
124 // If it's a known constant we have already accounted for it.
125 if (KnownConstants.contains(&I))
126 continue;
127
128 Cost C = TTI.getInstructionCost(&I, TargetTransformInfo::TCK_CodeSize);
129
130 LLVM_DEBUG(dbgs() << "FnSpecialization: CodeSize " << C
131 << " for user " << I << "\n");
132 CodeSize += C;
133 }
134
135 // Keep adding dead successors to the list as long as they are
136 // executable and only reachable from dead blocks.
137 for (BasicBlock *SuccBB : successors(BB))
138 if (isBlockExecutable(SuccBB) && canEliminateSuccessor(BB, SuccBB))
139 WorkList.push_back(SuccBB);
140 }
141 return CodeSize;
142}
143
144Constant *InstCostVisitor::findConstantFor(Value *V) const {
145 if (auto *C = dyn_cast<Constant>(V))
146 return C;
147 if (auto *C = Solver.getConstantOrNull(V))
148 return C;
149 return KnownConstants.lookup(V);
150}
151
154 while (!PendingPHIs.empty()) {
155 Instruction *Phi = PendingPHIs.pop_back_val();
156 // The pending PHIs could have been proven dead by now.
157 if (isBlockExecutable(Phi->getParent()))
158 CodeSize += getCodeSizeSavingsForUser(Phi);
159 }
160 return CodeSize;
161}
162
163/// Compute the codesize savings for replacing argument \p A with constant \p C.
165 LLVM_DEBUG(dbgs() << "FnSpecialization: Analysing bonus for constant: "
166 << C->getNameOrAsOperand() << "\n");
168 for (auto *U : A->users())
169 if (auto *UI = dyn_cast<Instruction>(U))
170 if (isBlockExecutable(UI->getParent()))
171 CodeSize += getCodeSizeSavingsForUser(UI, A, C);
172
173 LLVM_DEBUG(dbgs() << "FnSpecialization: Accumulated bonus {CodeSize = "
174 << CodeSize << "} for argument " << *A << "\n");
175 return CodeSize;
176}
177
178/// Compute the latency savings from replacing all arguments with constants for
179/// a specialization candidate. As this function computes the latency savings
180/// for all Instructions in KnownConstants at once, it should be called only
181/// after every instruction has been visited, i.e. after:
182///
183/// * getCodeSizeSavingsForArg has been run for every constant argument of a
184/// specialization candidate
185///
186/// * getCodeSizeSavingsFromPendingPHIs has been run
187///
188/// to ensure that the latency savings are calculated for all Instructions we
189/// have visited and found to be constant.
191 auto &BFI = GetBFI(*F);
192 Cost TotalLatency = 0;
193
194 for (auto Pair : KnownConstants) {
195 Instruction *I = dyn_cast<Instruction>(Pair.first);
196 if (!I)
197 continue;
198
199 uint64_t Weight = BFI.getBlockFreq(I->getParent()).getFrequency() /
200 BFI.getEntryFreq().getFrequency();
201
202 Cost Latency =
203 Weight * TTI.getInstructionCost(I, TargetTransformInfo::TCK_Latency);
204
205 LLVM_DEBUG(dbgs() << "FnSpecialization: {Latency = " << Latency
206 << "} for instruction " << *I << "\n");
207
208 TotalLatency += Latency;
209 }
210
211 return TotalLatency;
212}
213
214Cost InstCostVisitor::getCodeSizeSavingsForUser(Instruction *User, Value *Use,
215 Constant *C) {
216 // We have already propagated a constant for this user.
217 if (KnownConstants.contains(User))
218 return 0;
219
220 // Cache the iterator before visiting.
221 LastVisited = Use ? KnownConstants.insert({Use, C}).first
222 : KnownConstants.end();
223
224 Cost CodeSize = 0;
225 if (auto *I = dyn_cast<SwitchInst>(User)) {
226 CodeSize = estimateSwitchInst(*I);
227 } else if (auto *I = dyn_cast<BranchInst>(User)) {
228 CodeSize = estimateBranchInst(*I);
229 } else {
230 C = visit(*User);
231 if (!C)
232 return 0;
233 }
234
235 // Even though it doesn't make sense to bind switch and branch instructions
236 // with a constant, unlike any other instruction type, it prevents estimating
237 // their bonus multiple times.
238 KnownConstants.insert({User, C});
239
240 CodeSize += TTI.getInstructionCost(User, TargetTransformInfo::TCK_CodeSize);
241
242 LLVM_DEBUG(dbgs() << "FnSpecialization: {CodeSize = " << CodeSize
243 << "} for user " << *User << "\n");
244
245 for (auto *U : User->users())
246 if (auto *UI = dyn_cast<Instruction>(U))
247 if (UI != User && isBlockExecutable(UI->getParent()))
248 CodeSize += getCodeSizeSavingsForUser(UI, User, C);
249
250 return CodeSize;
251}
252
253Cost InstCostVisitor::estimateSwitchInst(SwitchInst &I) {
254 assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
255
256 if (I.getCondition() != LastVisited->first)
257 return 0;
258
259 auto *C = dyn_cast<ConstantInt>(LastVisited->second);
260 if (!C)
261 return 0;
262
263 BasicBlock *Succ = I.findCaseValue(C)->getCaseSuccessor();
264 // Initialize the worklist with the dead basic blocks. These are the
265 // destination labels which are different from the one corresponding
266 // to \p C. They should be executable and have a unique predecessor.
268 for (const auto &Case : I.cases()) {
269 BasicBlock *BB = Case.getCaseSuccessor();
270 if (BB != Succ && isBlockExecutable(BB) &&
271 canEliminateSuccessor(I.getParent(), BB))
272 WorkList.push_back(BB);
273 }
274
275 return estimateBasicBlocks(WorkList);
276}
277
278Cost InstCostVisitor::estimateBranchInst(BranchInst &I) {
279 assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
280
281 if (I.getCondition() != LastVisited->first)
282 return 0;
283
284 BasicBlock *Succ = I.getSuccessor(LastVisited->second->isOneValue());
285 // Initialize the worklist with the dead successor as long as
286 // it is executable and has a unique predecessor.
288 if (isBlockExecutable(Succ) && canEliminateSuccessor(I.getParent(), Succ))
289 WorkList.push_back(Succ);
290
291 return estimateBasicBlocks(WorkList);
292}
293
294bool InstCostVisitor::discoverTransitivelyIncomingValues(
295 Constant *Const, PHINode *Root, DenseSet<PHINode *> &TransitivePHIs) {
296
298 WorkList.push_back(Root);
299 unsigned Iter = 0;
300
301 while (!WorkList.empty()) {
302 PHINode *PN = WorkList.pop_back_val();
303
304 if (++Iter > MaxDiscoveryIterations ||
306 return false;
307
308 if (!TransitivePHIs.insert(PN).second)
309 continue;
310
311 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
312 Value *V = PN->getIncomingValue(I);
313
314 // Disregard self-references and dead incoming values.
315 if (auto *Inst = dyn_cast<Instruction>(V))
316 if (Inst == PN || !isBlockExecutable(PN->getIncomingBlock(I)))
317 continue;
318
319 if (Constant *C = findConstantFor(V)) {
320 // Not all incoming values are the same constant. Bail immediately.
321 if (C != Const)
322 return false;
323 continue;
324 }
325
326 if (auto *Phi = dyn_cast<PHINode>(V)) {
327 WorkList.push_back(Phi);
328 continue;
329 }
330
331 // We can't reason about anything else.
332 return false;
333 }
334 }
335 return true;
336}
337
338Constant *InstCostVisitor::visitPHINode(PHINode &I) {
339 if (I.getNumIncomingValues() > MaxIncomingPhiValues)
340 return nullptr;
341
342 bool Inserted = VisitedPHIs.insert(&I).second;
343 Constant *Const = nullptr;
344 bool HaveSeenIncomingPHI = false;
345
346 for (unsigned Idx = 0, E = I.getNumIncomingValues(); Idx != E; ++Idx) {
347 Value *V = I.getIncomingValue(Idx);
348
349 // Disregard self-references and dead incoming values.
350 if (auto *Inst = dyn_cast<Instruction>(V))
351 if (Inst == &I || !isBlockExecutable(I.getIncomingBlock(Idx)))
352 continue;
353
354 if (Constant *C = findConstantFor(V)) {
355 if (!Const)
356 Const = C;
357 // Not all incoming values are the same constant. Bail immediately.
358 if (C != Const)
359 return nullptr;
360 continue;
361 }
362
363 if (Inserted) {
364 // First time we are seeing this phi. We will retry later, after
365 // all the constant arguments have been propagated. Bail for now.
366 PendingPHIs.push_back(&I);
367 return nullptr;
368 }
369
370 if (isa<PHINode>(V)) {
371 // Perhaps it is a Transitive Phi. We will confirm later.
372 HaveSeenIncomingPHI = true;
373 continue;
374 }
375
376 // We can't reason about anything else.
377 return nullptr;
378 }
379
380 if (!Const)
381 return nullptr;
382
383 if (!HaveSeenIncomingPHI)
384 return Const;
385
386 DenseSet<PHINode *> TransitivePHIs;
387 if (!discoverTransitivelyIncomingValues(Const, &I, TransitivePHIs))
388 return nullptr;
389
390 return Const;
391}
392
393Constant *InstCostVisitor::visitFreezeInst(FreezeInst &I) {
394 assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
395
396 if (isGuaranteedNotToBeUndefOrPoison(LastVisited->second))
397 return LastVisited->second;
398 return nullptr;
399}
400
401Constant *InstCostVisitor::visitCallBase(CallBase &I) {
402 assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
403
404 Function *F = I.getCalledFunction();
405 if (!F || !canConstantFoldCallTo(&I, F))
406 return nullptr;
407
409 Operands.reserve(I.getNumOperands());
410
411 for (unsigned Idx = 0, E = I.getNumOperands() - 1; Idx != E; ++Idx) {
412 Value *V = I.getOperand(Idx);
414 return nullptr;
415 Constant *C = findConstantFor(V);
416 if (!C)
417 return nullptr;
418 Operands.push_back(C);
419 }
420
421 auto Ops = ArrayRef(Operands.begin(), Operands.end());
422 return ConstantFoldCall(&I, F, Ops);
423}
424
425Constant *InstCostVisitor::visitLoadInst(LoadInst &I) {
426 assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
427
428 if (isa<ConstantPointerNull>(LastVisited->second))
429 return nullptr;
430 return ConstantFoldLoadFromConstPtr(LastVisited->second, I.getType(), DL);
431}
432
433Constant *InstCostVisitor::visitGetElementPtrInst(GetElementPtrInst &I) {
435 Operands.reserve(I.getNumOperands());
436
437 for (unsigned Idx = 0, E = I.getNumOperands(); Idx != E; ++Idx) {
438 Value *V = I.getOperand(Idx);
439 Constant *C = findConstantFor(V);
440 if (!C)
441 return nullptr;
442 Operands.push_back(C);
443 }
444
445 auto Ops = ArrayRef(Operands.begin(), Operands.end());
446 return ConstantFoldInstOperands(&I, Ops, DL);
447}
448
449Constant *InstCostVisitor::visitSelectInst(SelectInst &I) {
450 assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
451
452 if (I.getCondition() == LastVisited->first) {
453 Value *V = LastVisited->second->isZeroValue() ? I.getFalseValue()
454 : I.getTrueValue();
455 return findConstantFor(V);
456 }
457 if (Constant *Condition = findConstantFor(I.getCondition()))
458 if ((I.getTrueValue() == LastVisited->first && Condition->isOneValue()) ||
459 (I.getFalseValue() == LastVisited->first && Condition->isZeroValue()))
460 return LastVisited->second;
461 return nullptr;
462}
463
464Constant *InstCostVisitor::visitCastInst(CastInst &I) {
465 return ConstantFoldCastOperand(I.getOpcode(), LastVisited->second,
466 I.getType(), DL);
467}
468
469Constant *InstCostVisitor::visitCmpInst(CmpInst &I) {
470 assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
471
472 Constant *Const = LastVisited->second;
473 bool ConstOnRHS = I.getOperand(1) == LastVisited->first;
474 Value *V = ConstOnRHS ? I.getOperand(0) : I.getOperand(1);
475 Constant *Other = findConstantFor(V);
476
477 if (Other) {
478 if (ConstOnRHS)
479 std::swap(Const, Other);
480 return ConstantFoldCompareInstOperands(I.getPredicate(), Const, Other, DL);
481 }
482
483 // If we haven't found Other to be a specific constant value, we may still be
484 // able to constant fold using information from the lattice value.
485 const ValueLatticeElement &ConstLV = ValueLatticeElement::get(Const);
486 const ValueLatticeElement &OtherLV = Solver.getLatticeValueFor(V);
487 auto &V1State = ConstOnRHS ? OtherLV : ConstLV;
488 auto &V2State = ConstOnRHS ? ConstLV : OtherLV;
489 return V1State.getCompare(I.getPredicate(), I.getType(), V2State, DL);
490}
491
492Constant *InstCostVisitor::visitUnaryOperator(UnaryOperator &I) {
493 assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
494
495 return ConstantFoldUnaryOpOperand(I.getOpcode(), LastVisited->second, DL);
496}
497
498Constant *InstCostVisitor::visitBinaryOperator(BinaryOperator &I) {
499 assert(LastVisited != KnownConstants.end() && "Invalid iterator!");
500
501 bool ConstOnRHS = I.getOperand(1) == LastVisited->first;
502 Value *V = ConstOnRHS ? I.getOperand(0) : I.getOperand(1);
503 Constant *Other = findConstantFor(V);
504 Value *OtherVal = Other ? Other : V;
505 Value *ConstVal = LastVisited->second;
506
507 if (ConstOnRHS)
508 std::swap(ConstVal, OtherVal);
509
511 simplifyBinOp(I.getOpcode(), ConstVal, OtherVal, SimplifyQuery(DL)));
512}
513
514Constant *FunctionSpecializer::getPromotableAlloca(AllocaInst *Alloca,
515 CallInst *Call) {
516 Value *StoreValue = nullptr;
517 for (auto *User : Alloca->users()) {
518 // We can't use llvm::isAllocaPromotable() as that would fail because of
519 // the usage in the CallInst, which is what we check here.
520 if (User == Call)
521 continue;
522
523 if (auto *Store = dyn_cast<StoreInst>(User)) {
524 // This is a duplicate store, bail out.
525 if (StoreValue || Store->isVolatile())
526 return nullptr;
527 StoreValue = Store->getValueOperand();
528 continue;
529 }
530 // Bail if there is any other unknown usage.
531 return nullptr;
532 }
533
534 if (!StoreValue)
535 return nullptr;
536
537 return getCandidateConstant(StoreValue);
538}
539
540// A constant stack value is an AllocaInst that has a single constant
541// value stored to it. Return this constant if such an alloca stack value
542// is a function argument.
543Constant *FunctionSpecializer::getConstantStackValue(CallInst *Call,
544 Value *Val) {
545 if (!Val)
546 return nullptr;
547 Val = Val->stripPointerCasts();
548 if (auto *ConstVal = dyn_cast<ConstantInt>(Val))
549 return ConstVal;
550 auto *Alloca = dyn_cast<AllocaInst>(Val);
551 if (!Alloca || !Alloca->getAllocatedType()->isIntegerTy())
552 return nullptr;
553 return getPromotableAlloca(Alloca, Call);
554}
555
556// To support specializing recursive functions, it is important to propagate
557// constant arguments because after a first iteration of specialisation, a
558// reduced example may look like this:
559//
560// define internal void @RecursiveFn(i32* arg1) {
561// %temp = alloca i32, align 4
562// store i32 2 i32* %temp, align 4
563// call void @RecursiveFn.1(i32* nonnull %temp)
564// ret void
565// }
566//
567// Before a next iteration, we need to propagate the constant like so
568// which allows further specialization in next iterations.
569//
570// @funcspec.arg = internal constant i32 2
571//
572// define internal void @someFunc(i32* arg1) {
573// call void @otherFunc(i32* nonnull @funcspec.arg)
574// ret void
575// }
576//
577// See if there are any new constant values for the callers of \p F via
578// stack variables and promote them to global variables.
579void FunctionSpecializer::promoteConstantStackValues(Function *F) {
580 for (User *U : F->users()) {
581
582 auto *Call = dyn_cast<CallInst>(U);
583 if (!Call)
584 continue;
585
586 if (!Solver.isBlockExecutable(Call->getParent()))
587 continue;
588
589 for (const Use &U : Call->args()) {
590 unsigned Idx = Call->getArgOperandNo(&U);
591 Value *ArgOp = Call->getArgOperand(Idx);
592 Type *ArgOpType = ArgOp->getType();
593
594 if (!Call->onlyReadsMemory(Idx) || !ArgOpType->isPointerTy())
595 continue;
596
597 auto *ConstVal = getConstantStackValue(Call, ArgOp);
598 if (!ConstVal)
599 continue;
600
601 Value *GV = new GlobalVariable(M, ConstVal->getType(), true,
603 "specialized.arg." + Twine(++NGlobals));
604 Call->setArgOperand(Idx, GV);
605 }
606 }
607}
608
609// The SCCP solver inserts bitcasts for PredicateInfo. These interfere with the
610// promoteConstantStackValues() optimization.
611static void removeSSACopy(Function &F) {
612 for (BasicBlock &BB : F) {
613 for (Instruction &Inst : llvm::make_early_inc_range(BB)) {
614 auto *BC = dyn_cast<BitCastInst>(&Inst);
615 if (!BC || BC->getType() != BC->getOperand(0)->getType())
616 continue;
617 Inst.replaceAllUsesWith(BC->getOperand(0));
618 Inst.eraseFromParent();
619 }
620 }
621}
622
623/// Remove any ssa_copy intrinsics that may have been introduced.
624void FunctionSpecializer::cleanUpSSA() {
625 for (Function *F : Specializations)
627}
628
629
630template <> struct llvm::DenseMapInfo<SpecSig> {
631 static inline SpecSig getEmptyKey() { return {~0U, {}}; }
632
633 static inline SpecSig getTombstoneKey() { return {~1U, {}}; }
634
635 static unsigned getHashValue(const SpecSig &S) {
636 return static_cast<unsigned>(hash_value(S));
637 }
638
639 static bool isEqual(const SpecSig &LHS, const SpecSig &RHS) {
640 return LHS == RHS;
641 }
642};
643
646 if (NumSpecsCreated > 0)
647 dbgs() << "FnSpecialization: Created " << NumSpecsCreated
648 << " specializations in module " << M.getName() << "\n");
649 // Eliminate dead code.
650 removeDeadFunctions();
651 cleanUpSSA();
652}
653
654/// Get the unsigned Value of given Cost object. Assumes the Cost is always
655/// non-negative, which is true for both TCK_CodeSize and TCK_Latency, and
656/// always Valid.
657static unsigned getCostValue(const Cost &C) {
658 int64_t Value = C.getValue();
659
660 assert(Value >= 0 && "CodeSize and Latency cannot be negative");
661 // It is safe to down cast since we know the arguments cannot be negative and
662 // Cost is of type int64_t.
663 return static_cast<unsigned>(Value);
664}
665
666/// Attempt to specialize functions in the module to enable constant
667/// propagation across function boundaries.
668///
669/// \returns true if at least one function is specialized.
671 // Find possible specializations for each function.
672 SpecMap SM;
673 SmallVector<Spec, 32> AllSpecs;
674 unsigned NumCandidates = 0;
675 for (Function &F : M) {
676 if (!isCandidateFunction(&F))
677 continue;
678
679 auto [It, Inserted] = FunctionMetrics.try_emplace(&F);
680 CodeMetrics &Metrics = It->second;
681 //Analyze the function.
682 if (Inserted) {
684 CodeMetrics::collectEphemeralValues(&F, &GetAC(F), EphValues);
685 for (BasicBlock &BB : F)
686 Metrics.analyzeBasicBlock(&BB, GetTTI(F), EphValues);
687 }
688
689 // When specializing literal constants is enabled, always require functions
690 // to be larger than MinFunctionSize, to prevent excessive specialization.
691 const bool RequireMinSize =
693 (SpecializeLiteralConstant || !F.hasFnAttribute(Attribute::NoInline));
694
695 // If the code metrics reveal that we shouldn't duplicate the function,
696 // or if the code size implies that this function is easy to get inlined,
697 // then we shouldn't specialize it.
698 if (Metrics.notDuplicatable || !Metrics.NumInsts.isValid() ||
699 (RequireMinSize && Metrics.NumInsts < MinFunctionSize))
700 continue;
701
702 // When specialization on literal constants is disabled, only consider
703 // recursive functions when running multiple times to save wasted analysis,
704 // as we will not be able to specialize on any newly found literal constant
705 // return values.
706 if (!SpecializeLiteralConstant && !Inserted && !Metrics.isRecursive)
707 continue;
708
709 int64_t Sz = Metrics.NumInsts.getValue();
710 assert(Sz > 0 && "CodeSize should be positive");
711 // It is safe to down cast from int64_t, NumInsts is always positive.
712 unsigned FuncSize = static_cast<unsigned>(Sz);
713
714 LLVM_DEBUG(dbgs() << "FnSpecialization: Specialization cost for "
715 << F.getName() << " is " << FuncSize << "\n");
716
717 if (Inserted && Metrics.isRecursive)
718 promoteConstantStackValues(&F);
719
720 if (!findSpecializations(&F, FuncSize, AllSpecs, SM)) {
722 dbgs() << "FnSpecialization: No possible specializations found for "
723 << F.getName() << "\n");
724 continue;
725 }
726
727 ++NumCandidates;
728 }
729
730 if (!NumCandidates) {
732 dbgs()
733 << "FnSpecialization: No possible specializations found in module\n");
734 return false;
735 }
736
737 // Choose the most profitable specialisations, which fit in the module
738 // specialization budget, which is derived from maximum number of
739 // specializations per specialization candidate function.
740 auto CompareScore = [&AllSpecs](unsigned I, unsigned J) {
741 if (AllSpecs[I].Score != AllSpecs[J].Score)
742 return AllSpecs[I].Score > AllSpecs[J].Score;
743 return I > J;
744 };
745 const unsigned NSpecs =
746 std::min(NumCandidates * MaxClones, unsigned(AllSpecs.size()));
747 SmallVector<unsigned> BestSpecs(NSpecs + 1);
748 std::iota(BestSpecs.begin(), BestSpecs.begin() + NSpecs, 0);
749 if (AllSpecs.size() > NSpecs) {
750 LLVM_DEBUG(dbgs() << "FnSpecialization: Number of candidates exceed "
751 << "the maximum number of clones threshold.\n"
752 << "FnSpecialization: Specializing the "
753 << NSpecs
754 << " most profitable candidates.\n");
755 std::make_heap(BestSpecs.begin(), BestSpecs.begin() + NSpecs, CompareScore);
756 for (unsigned I = NSpecs, N = AllSpecs.size(); I < N; ++I) {
757 BestSpecs[NSpecs] = I;
758 std::push_heap(BestSpecs.begin(), BestSpecs.end(), CompareScore);
759 std::pop_heap(BestSpecs.begin(), BestSpecs.end(), CompareScore);
760 }
761 }
762
763 LLVM_DEBUG(dbgs() << "FnSpecialization: List of specializations \n";
764 for (unsigned I = 0; I < NSpecs; ++I) {
765 const Spec &S = AllSpecs[BestSpecs[I]];
766 dbgs() << "FnSpecialization: Function " << S.F->getName()
767 << " , score " << S.Score << "\n";
768 for (const ArgInfo &Arg : S.Sig.Args)
769 dbgs() << "FnSpecialization: FormalArg = "
770 << Arg.Formal->getNameOrAsOperand()
771 << ", ActualArg = " << Arg.Actual->getNameOrAsOperand()
772 << "\n";
773 });
774
775 // Create the chosen specializations.
776 SmallPtrSet<Function *, 8> OriginalFuncs;
778 for (unsigned I = 0; I < NSpecs; ++I) {
779 Spec &S = AllSpecs[BestSpecs[I]];
780
781 // Accumulate the codesize growth for the function, now we are creating the
782 // specialization.
783 FunctionGrowth[S.F] += S.CodeSize;
784
785 S.Clone = createSpecialization(S.F, S.Sig);
786
787 // Update the known call sites to call the clone.
788 for (CallBase *Call : S.CallSites) {
789 Function *Clone = S.Clone;
790 LLVM_DEBUG(dbgs() << "FnSpecialization: Redirecting " << *Call
791 << " to call " << Clone->getName() << "\n");
792 Call->setCalledFunction(S.Clone);
793 auto &BFI = GetBFI(*Call->getFunction());
794 std::optional<uint64_t> Count =
795 BFI.getBlockProfileCount(Call->getParent());
797 std::optional<llvm::Function::ProfileCount> MaybeCloneCount =
798 Clone->getEntryCount();
799 if (MaybeCloneCount) {
800 uint64_t CallCount = *Count + MaybeCloneCount->getCount();
801 Clone->setEntryCount(CallCount);
802 if (std::optional<llvm::Function::ProfileCount> MaybeOriginalCount =
803 S.F->getEntryCount()) {
804 uint64_t OriginalCount = MaybeOriginalCount->getCount();
805 if (OriginalCount >= *Count) {
806 S.F->setEntryCount(OriginalCount - *Count);
807 } else {
808 // This should generally not happen as that would mean there are
809 // more computed calls to the function than what was recorded.
811 }
812 }
813 }
814 }
815 }
816
817 Clones.push_back(S.Clone);
818 OriginalFuncs.insert(S.F);
819 }
820
821 Solver.solveWhileResolvedUndefsIn(Clones);
822
823 // Update the rest of the call sites - these are the recursive calls, calls
824 // to discarded specialisations and calls that may match a specialisation
825 // after the solver runs.
826 for (Function *F : OriginalFuncs) {
827 auto [Begin, End] = SM[F];
828 updateCallSites(F, AllSpecs.begin() + Begin, AllSpecs.begin() + End);
829 }
830
831 for (Function *F : Clones) {
832 if (F->getReturnType()->isVoidTy())
833 continue;
834 if (F->getReturnType()->isStructTy()) {
835 auto *STy = cast<StructType>(F->getReturnType());
836 if (!Solver.isStructLatticeConstant(F, STy))
837 continue;
838 } else {
839 auto It = Solver.getTrackedRetVals().find(F);
840 assert(It != Solver.getTrackedRetVals().end() &&
841 "Return value ought to be tracked");
842 if (SCCPSolver::isOverdefined(It->second))
843 continue;
844 }
845 for (User *U : F->users()) {
846 if (auto *CS = dyn_cast<CallBase>(U)) {
847 //The user instruction does not call our function.
848 if (CS->getCalledFunction() != F)
849 continue;
850 Solver.resetLatticeValueFor(CS);
851 }
852 }
853 }
854
855 // Rerun the solver to notify the users of the modified callsites.
856 Solver.solveWhileResolvedUndefs();
857
858 for (Function *F : OriginalFuncs)
859 if (FunctionMetrics[F].isRecursive)
860 promoteConstantStackValues(F);
861
862 return true;
863}
864
865void FunctionSpecializer::removeDeadFunctions() {
866 for (Function *F : DeadFunctions) {
867 LLVM_DEBUG(dbgs() << "FnSpecialization: Removing dead function "
868 << F->getName() << "\n");
869 if (FAM)
870 FAM->clear(*F, F->getName());
871
872 // Remove all the callsites that were proven unreachable once, and replace
873 // them with poison.
874 for (User *U : make_early_inc_range(F->users())) {
876 "User of dead function must be call or invoke");
879 CS->eraseFromParent();
880 }
881 F->eraseFromParent();
882 }
883 DeadFunctions.clear();
884}
885
886/// Clone the function \p F and remove the ssa_copy intrinsics added by
887/// the SCCPSolver in the cloned version.
888static Function *cloneCandidateFunction(Function *F, unsigned NSpecs) {
889 ValueToValueMapTy Mappings;
890 Function *Clone = CloneFunction(F, Mappings);
891 Clone->setName(F->getName() + ".specialized." + Twine(NSpecs));
892 removeSSACopy(*Clone);
893 return Clone;
894}
895
896bool FunctionSpecializer::findSpecializations(Function *F, unsigned FuncSize,
897 SmallVectorImpl<Spec> &AllSpecs,
898 SpecMap &SM) {
899 // A mapping from a specialisation signature to the index of the respective
900 // entry in the all specialisation array. Used to ensure uniqueness of
901 // specialisations.
902 DenseMap<SpecSig, unsigned> UniqueSpecs;
903
904 // Get a list of interesting arguments.
906 for (Argument &Arg : F->args())
907 if (isArgumentInteresting(&Arg))
908 Args.push_back(&Arg);
909
910 if (Args.empty())
911 return false;
912
913 for (User *U : F->users()) {
914 if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
915 continue;
916 auto &CS = *cast<CallBase>(U);
917
918 // The user instruction does not call our function.
919 if (CS.getCalledFunction() != F)
920 continue;
921
922 // If the call site has attribute minsize set, that callsite won't be
923 // specialized.
924 if (CS.hasFnAttr(Attribute::MinSize))
925 continue;
926
927 // If the parent of the call site will never be executed, we don't need
928 // to worry about the passed value.
929 if (!Solver.isBlockExecutable(CS.getParent()))
930 continue;
931
932 // Examine arguments and create a specialisation candidate from the
933 // constant operands of this call site.
934 SpecSig S;
935 for (Argument *A : Args) {
936 Constant *C = getCandidateConstant(CS.getArgOperand(A->getArgNo()));
937 if (!C)
938 continue;
939 LLVM_DEBUG(dbgs() << "FnSpecialization: Found interesting argument "
940 << A->getName() << " : " << C->getNameOrAsOperand()
941 << "\n");
942 S.Args.push_back({A, C});
943 }
944
945 if (S.Args.empty())
946 continue;
947
948 // Check if we have encountered the same specialisation already.
949 if (auto It = UniqueSpecs.find(S); It != UniqueSpecs.end()) {
950 // Existing specialisation. Add the call to the list to rewrite, unless
951 // it's a recursive call. A specialisation, generated because of a
952 // recursive call may end up as not the best specialisation for all
953 // the cloned instances of this call, which result from specialising
954 // functions. Hence we don't rewrite the call directly, but match it with
955 // the best specialisation once all specialisations are known.
956 if (CS.getFunction() == F)
957 continue;
958 const unsigned Index = It->second;
959 AllSpecs[Index].CallSites.push_back(&CS);
960 } else {
961 // Calculate the specialisation gain.
963 unsigned Score = 0;
964 InstCostVisitor Visitor = getInstCostVisitorFor(F);
965 for (ArgInfo &A : S.Args) {
966 CodeSize += Visitor.getCodeSizeSavingsForArg(A.Formal, A.Actual);
967 Score += getInliningBonus(A.Formal, A.Actual);
968 }
970
971 unsigned CodeSizeSavings = getCostValue(CodeSize);
972 unsigned SpecSize = FuncSize - CodeSizeSavings;
973
974 auto IsProfitable = [&]() -> bool {
975 // No check required.
977 return true;
978
980 dbgs() << "FnSpecialization: Specialization bonus {Inlining = "
981 << Score << " (" << (Score * 100 / FuncSize) << "%)}\n");
982
983 // Minimum inlining bonus.
984 if (Score > MinInliningBonus * FuncSize / 100)
985 return true;
986
988 dbgs() << "FnSpecialization: Specialization bonus {CodeSize = "
989 << CodeSizeSavings << " ("
990 << (CodeSizeSavings * 100 / FuncSize) << "%)}\n");
991
992 // Minimum codesize savings.
993 if (CodeSizeSavings < MinCodeSizeSavings * FuncSize / 100)
994 return false;
995
996 // Lazily compute the Latency, to avoid unnecessarily computing BFI.
997 unsigned LatencySavings =
999
1000 LLVM_DEBUG(
1001 dbgs() << "FnSpecialization: Specialization bonus {Latency = "
1002 << LatencySavings << " ("
1003 << (LatencySavings * 100 / FuncSize) << "%)}\n");
1004
1005 // Minimum latency savings.
1006 if (LatencySavings < MinLatencySavings * FuncSize / 100)
1007 return false;
1008 // Maximum codesize growth.
1009 if ((FunctionGrowth[F] + SpecSize) / FuncSize > MaxCodeSizeGrowth)
1010 return false;
1011
1012 Score += std::max(CodeSizeSavings, LatencySavings);
1013 return true;
1014 };
1015
1016 // Discard unprofitable specialisations.
1017 if (!IsProfitable())
1018 continue;
1019
1020 // Create a new specialisation entry.
1021 auto &Spec = AllSpecs.emplace_back(F, S, Score, SpecSize);
1022 if (CS.getFunction() != F)
1023 Spec.CallSites.push_back(&CS);
1024 const unsigned Index = AllSpecs.size() - 1;
1025 UniqueSpecs[S] = Index;
1026 if (auto [It, Inserted] = SM.try_emplace(F, Index, Index + 1); !Inserted)
1027 It->second.second = Index + 1;
1028 }
1029 }
1030
1031 return !UniqueSpecs.empty();
1032}
1033
1034bool FunctionSpecializer::isCandidateFunction(Function *F) {
1035 if (F->isDeclaration() || F->arg_empty())
1036 return false;
1037
1038 if (F->hasFnAttribute(Attribute::NoDuplicate))
1039 return false;
1040
1041 // Do not specialize the cloned function again.
1042 if (Specializations.contains(F))
1043 return false;
1044
1045 // If we're optimizing the function for size, we shouldn't specialize it.
1046 if (shouldOptimizeForSize(F, nullptr, nullptr, PGSOQueryType::IRPass))
1047 return false;
1048
1049 // Exit if the function is not executable. There's no point in specializing
1050 // a dead function.
1051 if (!Solver.isBlockExecutable(&F->getEntryBlock()))
1052 return false;
1053
1054 // It wastes time to specialize a function which would get inlined finally.
1055 if (F->hasFnAttribute(Attribute::AlwaysInline))
1056 return false;
1057
1058 LLVM_DEBUG(dbgs() << "FnSpecialization: Try function: " << F->getName()
1059 << "\n");
1060 return true;
1061}
1062
1063Function *FunctionSpecializer::createSpecialization(Function *F,
1064 const SpecSig &S) {
1065 Function *Clone = cloneCandidateFunction(F, Specializations.size() + 1);
1066
1067 // The original function does not neccessarily have internal linkage, but the
1068 // clone must.
1070
1071 if (F->getEntryCount() && !ProfcheckDisableMetadataFixes)
1072 Clone->setEntryCount(0);
1073
1074 // Initialize the lattice state of the arguments of the function clone,
1075 // marking the argument on which we specialized the function constant
1076 // with the given value.
1077 Solver.setLatticeValueForSpecializationArguments(Clone, S.Args);
1078 Solver.markBlockExecutable(&Clone->front());
1079 Solver.addArgumentTrackedFunction(Clone);
1080 Solver.addTrackedFunction(Clone);
1081
1082 // Mark all the specialized functions
1083 Specializations.insert(Clone);
1084 ++NumSpecsCreated;
1085
1086 return Clone;
1087}
1088
1089/// Compute the inlining bonus for replacing argument \p A with constant \p C.
1090/// The below heuristic is only concerned with exposing inlining
1091/// opportunities via indirect call promotion. If the argument is not a
1092/// (potentially casted) function pointer, give up.
1093unsigned FunctionSpecializer::getInliningBonus(Argument *A, Constant *C) {
1094 Function *CalledFunction = dyn_cast<Function>(C->stripPointerCasts());
1095 if (!CalledFunction)
1096 return 0;
1097
1098 // Get TTI for the called function (used for the inline cost).
1099 auto &CalleeTTI = (GetTTI)(*CalledFunction);
1100
1101 // Look at all the call sites whose called value is the argument.
1102 // Specializing the function on the argument would allow these indirect
1103 // calls to be promoted to direct calls. If the indirect call promotion
1104 // would likely enable the called function to be inlined, specializing is a
1105 // good idea.
1106 int InliningBonus = 0;
1107 for (User *U : A->users()) {
1108 if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
1109 continue;
1110 auto *CS = cast<CallBase>(U);
1111 if (CS->getCalledOperand() != A)
1112 continue;
1113 if (CS->getFunctionType() != CalledFunction->getFunctionType())
1114 continue;
1115
1116 // Get the cost of inlining the called function at this call site. Note
1117 // that this is only an estimate. The called function may eventually
1118 // change in a way that leads to it not being inlined here, even though
1119 // inlining looks profitable now. For example, one of its called
1120 // functions may be inlined into it, making the called function too large
1121 // to be inlined into this call site.
1122 //
1123 // We apply a boost for performing indirect call promotion by increasing
1124 // the default threshold by the threshold for indirect calls.
1125 auto Params = getInlineParams();
1126 Params.DefaultThreshold += InlineConstants::IndirectCallThreshold;
1127 InlineCost IC =
1128 getInlineCost(*CS, CalledFunction, Params, CalleeTTI, GetAC, GetTLI);
1129
1130 // We clamp the bonus for this call to be between zero and the default
1131 // threshold.
1132 if (IC.isAlways())
1133 InliningBonus += Params.DefaultThreshold;
1134 else if (IC.isVariable() && IC.getCostDelta() > 0)
1135 InliningBonus += IC.getCostDelta();
1136
1137 LLVM_DEBUG(dbgs() << "FnSpecialization: Inlining bonus " << InliningBonus
1138 << " for user " << *U << "\n");
1139 }
1140
1141 return InliningBonus > 0 ? static_cast<unsigned>(InliningBonus) : 0;
1142}
1143
1144/// Determine if it is possible to specialise the function for constant values
1145/// of the formal parameter \p A.
1146bool FunctionSpecializer::isArgumentInteresting(Argument *A) {
1147 // No point in specialization if the argument is unused.
1148 if (A->user_empty())
1149 return false;
1150
1151 Type *Ty = A->getType();
1152 if (!Ty->isPointerTy() && (!SpecializeLiteralConstant ||
1153 (!Ty->isIntegerTy() && !Ty->isFloatingPointTy() && !Ty->isStructTy())))
1154 return false;
1155
1156 // SCCP solver does not record an argument that will be constructed on
1157 // stack.
1158 if (A->hasByValAttr() && !A->getParent()->onlyReadsMemory())
1159 return false;
1160
1161 // For non-argument-tracked functions every argument is overdefined.
1162 if (!Solver.isArgumentTrackedFunction(A->getParent()))
1163 return true;
1164
1165 // Check the lattice value and decide if we should attemt to specialize,
1166 // based on this argument. No point in specialization, if the lattice value
1167 // is already a constant.
1168 bool IsOverdefined = Ty->isStructTy()
1169 ? any_of(Solver.getStructLatticeValueFor(A), SCCPSolver::isOverdefined)
1170 : SCCPSolver::isOverdefined(Solver.getLatticeValueFor(A));
1171
1172 LLVM_DEBUG(
1173 if (IsOverdefined)
1174 dbgs() << "FnSpecialization: Found interesting parameter "
1175 << A->getNameOrAsOperand() << "\n";
1176 else
1177 dbgs() << "FnSpecialization: Nothing to do, parameter "
1178 << A->getNameOrAsOperand() << " is already constant\n";
1179 );
1180 return IsOverdefined;
1181}
1182
1183/// Check if the value \p V (an actual argument) is a constant or can only
1184/// have a constant value. Return that constant.
1185Constant *FunctionSpecializer::getCandidateConstant(Value *V) {
1186 if (isa<PoisonValue>(V))
1187 return nullptr;
1188
1189 // Select for possible specialisation values that are constants or
1190 // are deduced to be constants or constant ranges with a single element.
1192 if (!C)
1193 C = Solver.getConstantOrNull(V);
1194
1195 // Don't specialize on (anything derived from) the address of a non-constant
1196 // global variable, unless explicitly enabled.
1197 if (C && C->getType()->isPointerTy() && !C->isNullValue())
1199 GV && !(GV->isConstant() || SpecializeOnAddress))
1200 return nullptr;
1201
1202 return C;
1203}
1204
1205void FunctionSpecializer::updateCallSites(Function *F, const Spec *Begin,
1206 const Spec *End) {
1207 // Collect the call sites that need updating.
1208 SmallVector<CallBase *> ToUpdate;
1209 for (User *U : F->users())
1210 if (auto *CS = dyn_cast<CallBase>(U);
1211 CS && CS->getCalledFunction() == F &&
1212 Solver.isBlockExecutable(CS->getParent()))
1213 ToUpdate.push_back(CS);
1214
1215 unsigned NCallsLeft = ToUpdate.size();
1216 for (CallBase *CS : ToUpdate) {
1217 bool ShouldDecrementCount = CS->getFunction() == F;
1218
1219 // Find the best matching specialisation.
1220 const Spec *BestSpec = nullptr;
1221 for (const Spec &S : make_range(Begin, End)) {
1222 if (!S.Clone || (BestSpec && S.Score <= BestSpec->Score))
1223 continue;
1224
1225 if (any_of(S.Sig.Args, [CS, this](const ArgInfo &Arg) {
1226 unsigned ArgNo = Arg.Formal->getArgNo();
1227 return getCandidateConstant(CS->getArgOperand(ArgNo)) != Arg.Actual;
1228 }))
1229 continue;
1230
1231 BestSpec = &S;
1232 }
1233
1234 if (BestSpec) {
1235 LLVM_DEBUG(dbgs() << "FnSpecialization: Redirecting " << *CS
1236 << " to call " << BestSpec->Clone->getName() << "\n");
1237 CS->setCalledFunction(BestSpec->Clone);
1238 ShouldDecrementCount = true;
1239 }
1240
1241 if (ShouldDecrementCount)
1242 --NCallsLeft;
1243 }
1244
1245 // If the function has been completely specialized, the original function
1246 // is no longer needed. Mark it unreachable.
1247 // NOTE: If the address of a function is taken, we cannot treat it as dead
1248 // function.
1249 if (NCallsLeft == 0 && Solver.isArgumentTrackedFunction(F) &&
1250 !F->hasAddressTaken()) {
1251 Solver.markFunctionUnreachable(F);
1252 DeadFunctions.insert(F);
1253 }
1254}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static cl::opt< bool > ForceSpecialization("force-specialization", cl::init(false), cl::Hidden, cl::desc("Force function specialization for every call site with a constant " "argument"))
static cl::opt< unsigned > MaxDiscoveryIterations("funcspec-max-discovery-iterations", cl::init(100), cl::Hidden, cl::desc("The maximum number of iterations allowed " "when searching for transitive " "phis"))
static cl::opt< unsigned > MinFunctionSize("funcspec-min-function-size", cl::init(500), cl::Hidden, cl::desc("Don't specialize functions that have less than this number of " "instructions"))
static cl::opt< bool > SpecializeLiteralConstant("funcspec-for-literal-constant", cl::init(true), cl::Hidden, cl::desc("Enable specialization of functions that take a literal constant as an " "argument"))
static Function * cloneCandidateFunction(Function *F, unsigned NSpecs)
Clone the function F and remove the ssa_copy intrinsics added by the SCCPSolver in the cloned version...
static void removeSSACopy(Function &F)
static cl::opt< unsigned > MaxCodeSizeGrowth("funcspec-max-codesize-growth", cl::init(3), cl::Hidden, cl::desc("Maximum codesize growth allowed per function"))
static cl::opt< unsigned > MaxClones("funcspec-max-clones", cl::init(3), cl::Hidden, cl::desc("The maximum number of clones allowed for a single function " "specialization"))
static cl::opt< unsigned > MinCodeSizeSavings("funcspec-min-codesize-savings", cl::init(20), cl::Hidden, cl::desc("Reject specializations whose codesize savings are less than this " "much percent of the original function size"))
static cl::opt< unsigned > MinInliningBonus("funcspec-min-inlining-bonus", cl::init(300), cl::Hidden, cl::desc("Reject specializations whose inlining bonus is less than this " "much percent of the original function size"))
static cl::opt< unsigned > MaxIncomingPhiValues("funcspec-max-incoming-phi-values", cl::init(8), cl::Hidden, cl::desc("The maximum number of incoming values a PHI node can have to be " "considered during the specialization bonus estimation"))
static cl::opt< unsigned > MaxBlockPredecessors("funcspec-max-block-predecessors", cl::init(2), cl::Hidden, cl::desc("The maximum number of predecessors a basic block can have to be " "considered during the estimation of dead code"))
static cl::opt< bool > SpecializeOnAddress("funcspec-on-address", cl::init(false), cl::Hidden, cl::desc("Enable function specialization on the address of global values"))
static unsigned getCostValue(const Cost &C)
Get the unsigned Value of given Cost object.
static cl::opt< unsigned > MinLatencySavings("funcspec-min-latency-savings", cl::init(20), cl::Hidden, cl::desc("Reject specializations whose latency savings are less than this " "much percent of the original function size"))
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define F(x, y, z)
Definition MD5.cpp:55
#define I(x, y, z)
Definition MD5.cpp:58
mir Rename Register Operands
Machine Trace Metrics
FunctionAnalysisManager FAM
cl::opt< bool > ProfcheckDisableMetadataFixes("profcheck-disable-metadata-fixes", cl::Hidden, cl::init(false), cl::desc("Disable metadata propagation fixes discovered through Issue #147390"))
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:114
This pass exposes codegen information to IR-level passes.
an instruction to allocate memory on the stack
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
LLVM Basic Block Representation.
Definition BasicBlock.h:62
Conditional or Unconditional Branch instruction.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
bool onlyReadsMemory(unsigned OpNo) const
Value * getArgOperand(unsigned i) const
void setArgOperand(unsigned i, Value *v)
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
unsigned getArgOperandNo(const Use *U) const
Given a use for a arg operand, get the arg operand number that corresponds to it.
This class represents a function call, abstracting a target machine's calling convention.
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:448
This class is the base class for the comparison instructions.
Definition InstrTypes.h:666
This is an important base class in LLVM.
Definition Constant.h:43
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:165
bool empty() const
Definition DenseMap.h:107
iterator end()
Definition DenseMap.h:81
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:156
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:214
Implements a dense probed hash-table based set.
Definition DenseSet.h:269
This class represents a freeze function that returns random concrete value if an operand is either a ...
LLVM_ABI bool run()
Attempt to specialize functions in the module to enable constant propagation across function boundari...
InstCostVisitor getInstCostVisitorFor(Function *F)
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:209
const BasicBlock & front() const
Definition Function.h:858
std::optional< ProfileCount > getEntryCount(bool AllowSynthetic=false) const
Get the entry count for this function.
void setEntryCount(ProfileCount Count, const DenseSet< GlobalValue::GUID > *Imports=nullptr)
Set the entry count for this function.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
void setLinkage(LinkageTypes LT)
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
bool isAlways() const
Definition InlineCost.h:140
int getCostDelta() const
Get the cost delta from the threshold for inlining.
Definition InlineCost.h:176
bool isVariable() const
Definition InlineCost.h:142
LLVM_ABI Cost getLatencySavingsForKnownConstants()
Compute the latency savings from replacing all arguments with constants for a specialization candidat...
LLVM_ABI Cost getCodeSizeSavingsForArg(Argument *A, Constant *C)
Compute the codesize savings for replacing argument A with constant C.
LLVM_ABI Cost getCodeSizeSavingsFromPendingPHIs()
bool isBlockExecutable(BasicBlock *BB) const
void visit(Iterator Start, Iterator End)
Definition InstVisitor.h:87
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
An instruction for reading from memory.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
static LLVM_ABI bool isOverdefined(const ValueLatticeElement &LV)
This class represents the LLVM 'select' instruction.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Multiway switch.
@ TCK_CodeSize
Instruction code size.
@ TCK_Latency
The latency of instruction.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:267
bool isStructTy() const
True if this is an instance of StructType.
Definition Type.h:261
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:184
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:240
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM_ABI Constant * getCompare(CmpInst::Predicate Pred, Type *Ty, const ValueLatticeElement &Other, const DataLayout &DL) const
true, false or undef constants, or nullptr if the comparison cannot be evaluated.
static ValueLatticeElement get(Constant *C)
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:256
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:390
LLVM_ABI std::string getNameOrAsOperand() const
Definition Value.cpp:457
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:546
iterator_range< user_iterator > users()
Definition Value.h:426
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:701
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:194
const ParentTy * getParent() const
Definition ilist_node.h:34
CallInst * Call
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
const int IndirectCallThreshold
Definition InlineCost.h:50
initializer< Ty > init(const Ty &Val)
@ User
could "use" a pointer
This is an optimization pass for GlobalISel generic memory operations.
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1705
hash_code hash_value(const FixedPointSemantics &Val)
InstructionCost Cost
LLVM_ABI bool canConstantFoldCallTo(const CallBase *Call, const Function *F)
canConstantFoldCallTo - Return true if its even possible to fold a call to the specified function.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:649
auto successors(const MachineBasicBlock *BB)
DenseMap< Function *, std::pair< unsigned, unsigned > > SpecMap
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI bool shouldOptimizeForSize(const MachineFunction *MF, ProfileSummaryInfo *PSI, const MachineBlockFrequencyInfo *BFI, PGSOQueryType QueryType=PGSOQueryType::Other)
Returns true if machine function MF is suggested to be size-optimized based on the profile.
LLVM_ABI Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const Instruction *I=nullptr)
Attempt to constant fold a compare instruction (icmp/fcmp) with the specified operands.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:634
LLVM_ABI Constant * ConstantFoldCall(const CallBase *Call, Function *F, ArrayRef< Constant * > Operands, const TargetLibraryInfo *TLI=nullptr, bool AllowNonDeterministic=true)
ConstantFoldCall - Attempt to constant fold a call to the specified function with the specified argum...
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:759
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1712
LLVM_ABI Constant * ConstantFoldUnaryOpOperand(unsigned Opcode, Constant *Op, const DataLayout &DL)
Attempt to constant fold a unary operation with the specified operand.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
LLVM_ABI Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:548
LLVM_ABI InlineCost getInlineCost(CallBase &Call, const InlineParams &Params, TargetTransformInfo &CalleeTTI, function_ref< AssumptionCache &(Function &)> GetAssumptionCache, function_ref< const TargetLibraryInfo &(Function &)> GetTLI, function_ref< BlockFrequencyInfo &(Function &)> GetBFI=nullptr, ProfileSummaryInfo *PSI=nullptr, OptimizationRemarkEmitter *ORE=nullptr, function_ref< EphemeralValuesCache &(Function &)> GetEphValuesCache=nullptr)
Get an InlineCost object representing the cost of inlining this callsite.
@ Other
Any other memory.
Definition ModRef.h:68
LLVM_ABI Value * simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a BinaryOperator, fold the result or return null.
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI InlineParams getInlineParams()
Generate the parameters to tune the inline cost analysis based only on the commandline options.
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:565
auto predecessors(const MachineBasicBlock *BB)
LLVM_ABI Constant * ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty, APInt Offset, const DataLayout &DL)
Return the value that a load from C with offset Offset would produce if it is constant and determinab...
LLVM_ABI Constant * ConstantFoldInstOperands(const Instruction *I, ArrayRef< Constant * > Ops, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, bool AllowNonDeterministic=true)
ConstantFoldInstOperands - Attempt to constant fold an instruction with the specified operands.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
LLVM_ABI Function * CloneFunction(Function *F, ValueToValueMapTy &VMap, ClonedCodeInfo *CodeInfo=nullptr)
Return a copy of the specified function and add it to that function's module.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:853
#define N
Helper struct shared between Function Specialization and SCCP Solver.
Definition SCCPSolver.h:42
Argument * Formal
Definition SCCPSolver.h:43
Constant * Actual
Definition SCCPSolver.h:44
Utility to calculate the size and a few similar metrics for a set of basic blocks.
Definition CodeMetrics.h:34
static LLVM_ABI void collectEphemeralValues(const Loop *L, AssumptionCache *AC, SmallPtrSetImpl< const Value * > &EphValues)
Collect a loop's ephemeral values (those used only by an assume or similar intrinsics in the loop).
static unsigned getHashValue(const SpecSig &S)
static bool isEqual(const SpecSig &LHS, const SpecSig &RHS)
An information struct used to provide DenseMap with the various necessary components for a given valu...
SmallVector< ArgInfo, 4 > Args
SmallVector< CallBase * > CallSites