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