LLVM 24.0.0git
TailRecursionElimination.cpp
Go to the documentation of this file.
1//===- TailRecursionElimination.cpp - Eliminate Tail Calls ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file transforms calls of the current function (self recursion) followed
10// by a return instruction with a branch to the entry of the function, creating
11// a loop. This pass also implements the following extensions to the basic
12// algorithm:
13//
14// 1. Trivial instructions between the call and return do not prevent the
15// transformation from taking place, though currently the analysis cannot
16// support moving any really useful instructions (only dead ones).
17// 2. This pass transforms functions that are prevented from being tail
18// recursive by an associative and commutative expression to use an
19// accumulator variable, thus compiling the typical naive factorial or
20// 'fib' implementation into efficient code.
21// 3. TRE is performed if the function returns void, if the return
22// returns the result returned by the call, or if the function returns a
23// run-time constant on all exits from the function. It is possible, though
24// unlikely, that the return returns something else (like constant 0), and
25// can still be TRE'd. It can be TRE'd if ALL OTHER return instructions in
26// the function return the exact same value.
27// 4. If it can prove that callees do not access their caller stack frame,
28// they are marked as eligible for tail call elimination (by the code
29// generator).
30//
31// There are several improvements that could be made:
32//
33// 1. If the function has any alloca instructions, these instructions will be
34// moved out of the entry block of the function, causing them to be
35// evaluated each time through the tail recursion. Safely keeping allocas
36// in the entry block requires analysis to proves that the tail-called
37// function does not read or write the stack object.
38// 2. Tail recursion is only performed if the call immediately precedes the
39// return instruction. It's possible that there could be a jump between
40// the call and the return.
41// 3. There can be intervening operations between the call and the return that
42// prevent the TRE from occurring. For example, there could be GEP's and
43// stores to memory that will not be read or written by the call. This
44// requires some substantial analysis (such as with DSA) to prove safe to
45// move ahead of the call, but doing so could allow many more TREs to be
46// performed, for example in TreeAdd/TreeAlloc from the treeadd benchmark.
47// 4. The algorithm we use to detect if callees access their caller stack
48// frames is very primitive.
49//
50//===----------------------------------------------------------------------===//
51
53#include "llvm/ADT/STLExtras.h"
55#include "llvm/ADT/Statistic.h"
61#include "llvm/Analysis/Loads.h"
67#include "llvm/IR/CFG.h"
68#include "llvm/IR/Constants.h"
69#include "llvm/IR/DataLayout.h"
72#include "llvm/IR/Dominators.h"
73#include "llvm/IR/Function.h"
74#include "llvm/IR/IRBuilder.h"
78#include "llvm/IR/MDBuilder.h"
79#include "llvm/IR/Module.h"
82#include "llvm/Pass.h"
85#include "llvm/Support/Debug.h"
89#include <cmath>
90using namespace llvm;
91
92#define DEBUG_TYPE "tailcallelim"
93
94STATISTIC(NumEliminated, "Number of tail calls removed");
95STATISTIC(NumRetDuped, "Number of return duplicated");
96STATISTIC(NumAccumAdded, "Number of accumulators introduced");
97STATISTIC(NumTREPreventedCold,
98 "Number of tail calls/recursion eliminations prevented due to cold "
99 "calling convention or attribute");
100
102 "tre-disable-entrycount-recompute", cl::init(false), cl::Hidden,
103 cl::desc("Force disabling recomputing of function entry count, on "
104 "successful tail recursion elimination."));
105
107 "disable-tail-call-elim-for-cold-calls", cl::Hidden, cl::init(false),
108 cl::desc("Disable tail call elimination and optimization for cold calls or "
109 "in cold functions"));
110
112 const Function *Caller,
113 const ProfileSummaryInfo *PSI,
114 BlockFrequencyInfo *BFI) {
116 return false;
117
118 if (CB && CB->isMustTailCall())
119 return false;
120
121 if (Caller && (Caller->hasFnAttribute(Attribute::Cold) ||
122 Caller->getCallingConv() == CallingConv::Cold))
123 return true;
124
125 if (!PSI || !PSI->hasProfileSummary())
126 return false;
127
128 // We require both the function entry and the call site/block/callee to be
129 // cold.
130 // 1. Checking that the function entry is cold ensures we don't disable tail
131 // call elimination in hot functions (with calls on cold conditional
132 // paths), which would force stack frame setup and teardown on hot paths.
133 // 2. Checking that the call site/block/callee is also cold ensures that if a
134 // function has a cold entry count but contains a hot loop, we don't
135 // disable tail call elimination for calls within that hot loop.
136 if (Caller && PSI->isFunctionEntryCold(Caller) && CB) {
137 if (CB->hasFnAttr(Attribute::Cold) ||
139 return true;
140 if (BFI && (PSI->isColdCallSite(*CB, BFI) ||
141 PSI->isColdBlock(CB->getParent(), BFI)))
142 return true;
143 }
144
145 return false;
146}
147
148/// Scan the specified function for alloca instructions.
149/// If it contains any dynamic allocas, returns false.
150static bool canTRE(Function &F) {
151 // TODO: We don't do TRE if dynamic allocas are used.
152 // Dynamic allocas allocate stack space which should be
153 // deallocated before new iteration started. That is
154 // currently not implemented.
155 return llvm::all_of(instructions(F), [](Instruction &I) {
156 auto *AI = dyn_cast<AllocaInst>(&I);
157 return !AI || AI->isStaticAlloca();
158 });
159}
160
161namespace {
162struct AllocaDerivedValueTracker {
163 // Start at a root value and walk its use-def chain to mark calls that use the
164 // value or a derived value in AllocaUsers, and places where it may escape in
165 // EscapePoints.
166 void walk(Value *Root) {
167 SmallVector<Use *, 32> Worklist;
168 SmallPtrSet<Use *, 32> Visited;
169
170 auto AddUsesToWorklist = [&](Value *V) {
171 for (auto &U : V->uses()) {
172 if (!Visited.insert(&U).second)
173 continue;
174 Worklist.push_back(&U);
175 }
176 };
177
178 AddUsesToWorklist(Root);
179
180 while (!Worklist.empty()) {
181 Use *U = Worklist.pop_back_val();
182 Instruction *I = cast<Instruction>(U->getUser());
183
184 switch (I->getOpcode()) {
185 case Instruction::Call:
186 case Instruction::Invoke: {
187 auto &CB = cast<CallBase>(*I);
188 // If the alloca-derived argument is passed byval it is not an escape
189 // point, or a use of an alloca. Calling with byval copies the contents
190 // of the alloca into argument registers or stack slots, which exist
191 // beyond the lifetime of the current frame.
192 if (CB.isArgOperand(U) && CB.isByValArgument(CB.getArgOperandNo(U)))
193 continue;
194 bool IsNocapture =
195 CB.isDataOperand(U) && CB.doesNotCapture(CB.getDataOperandNo(U));
196 callUsesLocalStack(CB, IsNocapture);
197 if (IsNocapture) {
198 // If the alloca-derived argument is passed in as nocapture, then it
199 // can't propagate to the call's return. That would be capturing.
200 continue;
201 }
202 break;
203 }
204 case Instruction::Load: {
205 // The result of a load is not alloca-derived (unless an alloca has
206 // otherwise escaped, but this is a local analysis).
207 continue;
208 }
209 case Instruction::Store: {
210 if (U->getOperandNo() == 0)
211 EscapePoints.insert(I);
212 continue; // Stores have no users to analyze.
213 }
214 case Instruction::BitCast:
215 case Instruction::GetElementPtr:
216 case Instruction::PHI:
217 case Instruction::Select:
218 case Instruction::AddrSpaceCast:
219 break;
220 default:
221 EscapePoints.insert(I);
222 break;
223 }
224
225 AddUsesToWorklist(I);
226 }
227 }
228
229 void callUsesLocalStack(CallBase &CB, bool IsNocapture) {
230 // Add it to the list of alloca users.
231 AllocaUsers.insert(&CB);
232
233 // If it's nocapture then it can't capture this alloca.
234 if (IsNocapture)
235 return;
236
237 // If it can write to memory, it can leak the alloca value.
238 if (!CB.onlyReadsMemory())
239 EscapePoints.insert(&CB);
240 }
241
242 SmallPtrSet<Instruction *, 32> AllocaUsers;
243 SmallPtrSet<Instruction *, 32> EscapePoints;
244};
245} // namespace
246
249 if (F.callsFunctionThatReturnsTwice())
250 return false;
251
252 // The local stack holds all alloca instructions and all byval arguments.
253 AllocaDerivedValueTracker Tracker;
254 for (Argument &Arg : F.args()) {
255 if (Arg.hasByValAttr())
256 Tracker.walk(&Arg);
257 }
258 for (auto &BB : F) {
259 for (auto &I : BB)
261 Tracker.walk(AI);
262 }
263
264 bool Modified = false;
265
266 // Track whether a block is reachable after an alloca has escaped. Blocks that
267 // contain the escaping instruction will be marked as being visited without an
268 // escaped alloca, since that is how the block began.
269 enum VisitType {
270 UNVISITED,
271 UNESCAPED,
272 ESCAPED
273 };
275
276 // We propagate the fact that an alloca has escaped from block to successor.
277 // Visit the blocks that are propagating the escapedness first. To do this, we
278 // maintain two worklists.
279 SmallVector<BasicBlock *, 32> WorklistUnescaped, WorklistEscaped;
280
281 // We may enter a block and visit it thinking that no alloca has escaped yet,
282 // then see an escape point and go back around a loop edge and come back to
283 // the same block twice. Because of this, we defer setting tail on calls when
284 // we first encounter them in a block. Every entry in this list does not
285 // statically use an alloca via use-def chain analysis, but may find an alloca
286 // through other means if the block turns out to be reachable after an escape
287 // point.
288 SmallVector<CallInst *, 32> DeferredTails;
289
290 BasicBlock *BB = &F.getEntryBlock();
291 VisitType Escaped = UNESCAPED;
292 do {
293 for (auto &I : *BB) {
294 if (Tracker.EscapePoints.count(&I))
295 Escaped = ESCAPED;
296
298 // A PseudoProbeInst has the IntrInaccessibleMemOnly tag hence it is
299 // considered accessing memory and will be marked as a tail call if we
300 // don't bail out here.
301 if (!CI || CI->isTailCall() || isa<PseudoProbeInst>(&I))
302 continue;
303
304 // Bail out for intrinsic stackrestore call because it can modify
305 // unescaped allocas.
306 if (auto *II = dyn_cast<IntrinsicInst>(CI))
307 if (II->getIntrinsicID() == Intrinsic::stackrestore)
308 continue;
309
310 // Special-case operand bundles "clang.arc.attachedcall", "ptrauth", and
311 // "kcfi".
312 bool DisableForCold = shouldDisableTailCallsForCold(CI, &F, PSI, BFI);
313 bool IsNoTail = CI->isNoTailCall() || DisableForCold ||
317 if (!CI->isNoTailCall() && DisableForCold)
318 ++NumTREPreventedCold;
319
320 if (!IsNoTail && CI->doesNotAccessMemory()) {
321 // A call to a readnone function whose arguments are all things computed
322 // outside this function can be marked tail. Even if you stored the
323 // alloca address into a global, a readnone function can't load the
324 // global anyhow.
325 //
326 // Note that this runs whether we know an alloca has escaped or not. If
327 // it has, then we can't trust Tracker.AllocaUsers to be accurate.
328 bool SafeToTail = true;
329 for (auto &Arg : CI->args()) {
330 if (isa<Constant>(Arg.getUser()))
331 continue;
332 if (Argument *A = dyn_cast<Argument>(Arg.getUser()))
333 if (!A->hasByValAttr())
334 continue;
335 SafeToTail = false;
336 break;
337 }
338 if (SafeToTail) {
339 using namespace ore;
340 ORE->emit([&]() {
341 return OptimizationRemark(DEBUG_TYPE, "tailcall-readnone", CI)
342 << "marked as tail call candidate (readnone)";
343 });
344 CI->setTailCall();
345 Modified = true;
346 continue;
347 }
348 }
349
350 if (!IsNoTail && Escaped == UNESCAPED && !Tracker.AllocaUsers.count(CI))
351 DeferredTails.push_back(CI);
352 }
353
354 for (auto *SuccBB : successors(BB)) {
355 auto &State = Visited[SuccBB];
356 if (State < Escaped) {
357 State = Escaped;
358 if (State == ESCAPED)
359 WorklistEscaped.push_back(SuccBB);
360 else
361 WorklistUnescaped.push_back(SuccBB);
362 }
363 }
364
365 if (!WorklistEscaped.empty()) {
366 BB = WorklistEscaped.pop_back_val();
367 Escaped = ESCAPED;
368 } else {
369 BB = nullptr;
370 while (!WorklistUnescaped.empty()) {
371 auto *NextBB = WorklistUnescaped.pop_back_val();
372 if (Visited[NextBB] == UNESCAPED) {
373 BB = NextBB;
374 Escaped = UNESCAPED;
375 break;
376 }
377 }
378 }
379 } while (BB);
380
381 for (CallInst *CI : DeferredTails) {
382 if (Visited[CI->getParent()] != ESCAPED) {
383 // If the escape point was part way through the block, calls after the
384 // escape point wouldn't have been put into DeferredTails.
385 LLVM_DEBUG(dbgs() << "Marked as tail call candidate: " << *CI << "\n");
386 CI->setTailCall();
387 Modified = true;
388 }
389 }
390
391 return Modified;
392}
393
394/// Return true if it is safe to move the specified
395/// instruction from after the call to before the call, assuming that all
396/// instructions between the call and this instruction are movable.
397///
400 if (II->getIntrinsicID() == Intrinsic::lifetime_end)
401 return true;
402
403 // FIXME: We can move load/store/call/free instructions above the call if the
404 // call does not mod/ref the memory location being processed.
405 if (I->mayHaveSideEffects()) // This also handles volatile loads.
406 return false;
407
408 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
409 // Loads may always be moved above calls without side effects.
410 if (CI->mayHaveSideEffects()) {
411 // Non-volatile loads may be moved above a call with side effects if it
412 // does not write to memory and the load provably won't trap.
413 // Writes to memory only matter if they may alias the pointer
414 // being loaded from.
415 const DataLayout &DL = L->getDataLayout();
416 if (isModSet(AA->getModRefInfo(CI, MemoryLocation::get(L))) ||
417 !isSafeToLoadUnconditionally(L->getPointerOperand(), L->getType(),
418 L->getAlign(), SimplifyQuery(DL, L)))
419 return false;
420 }
421 }
422
423 // Otherwise, if this is a side-effect free instruction, check to make sure
424 // that it does not use the return value of the call. If it doesn't use the
425 // return value of the call, it must only use things that are defined before
426 // the call, or movable instructions between the call and the instruction
427 // itself.
428 return !is_contained(I->operands(), CI);
429}
430
431// Return true if I is a unary accumulator recurrence: a chain of
432// applications of a unary function `g` composed with itself,
433// `g(g(...g(Base)...))`, which is equivalent to a single application of the
434// N-times-composed function when `g` is pure. Neither associative nor
435// commutative, this differs from the ordinary accumulator recurrence handled
436// below, which requires I to be associative and commutative.
437//
438// TODO: Generalize this beyond shifts by a constant amount to arbitrary pure
439// unary functions (e.g., `f(x) = x == 0 ? Base : g(f(x - 1))` for any pure
440// unary `g`).
442 if (!I->isShift())
443 return false;
444
445 // A chain of shifts by a constant amount C is equivalent to a single shift
446 // by the sum of the amounts:
447 // ... (Base << C) << C) ... << C == Base << (C * Iterations)
448 // This relation applies to left shifts as well as arithmetic/logical right
449 // shifts when the shift amount is a constant.
450 return isa<ConstantInt>(I->getOperand(1));
451}
452
453namespace {
454class TailRecursionEliminator {
455 Function &F;
456 const TargetTransformInfo *TTI;
457 AliasAnalysis *AA;
458 OptimizationRemarkEmitter *ORE;
459 DomTreeUpdater &DTU;
460 BlockFrequencyInfo *const BFI;
461 ProfileSummaryInfo *const PSI;
462 const bool UpdateFunctionEntryCount;
463 const uint64_t OrigEntryBBFreq;
464 const uint64_t OrigEntryCount;
465
466 // The below are shared state we want to have available when eliminating any
467 // calls in the function. There values should be populated by
468 // createTailRecurseLoopHeader the first time we find a call we can eliminate.
469 BasicBlock *HeaderBB = nullptr;
470 SmallVector<PHINode *, 8> ArgumentPHIs;
471
472 // PHI node to store our return value.
473 PHINode *RetPN = nullptr;
474
475 // i1 PHI node to track if we have a valid return value stored in RetPN.
476 PHINode *RetKnownPN = nullptr;
477
478 // Vector of select instructions we insereted. These selects use RetKnownPN
479 // to either propagate RetPN or select a new return value.
481
482 // Keep track of the sum of frequencies of blocks that have calls eliminated
483 // so we can synthesize branch weights later that require information on
484 // recursion frequency.
485 uint64_t EliminateBlocksFrequencySum = 0;
486
487 // The below are shared state needed when performing accumulator recursion.
488 // There values should be populated by insertAccumulator the first time we
489 // find an elimination that requires an accumulator.
490
491 // PHI node to store our current accumulated value.
492 PHINode *AccPN = nullptr;
493
494 // The instruction doing the accumulating.
495 Instruction *AccumulatorRecursionInstr = nullptr;
496
497 Constant *AccumulatorInitialValue = nullptr;
498
499 TailRecursionEliminator(Function &F, const TargetTransformInfo *TTI,
500 AliasAnalysis *AA, OptimizationRemarkEmitter *ORE,
501 DomTreeUpdater &DTU, BlockFrequencyInfo *BFI,
502 ProfileSummaryInfo *PSI,
503 bool UpdateFunctionEntryCount)
504 : F(F), TTI(TTI), AA(AA), ORE(ORE), DTU(DTU), BFI(BFI), PSI(PSI),
505 UpdateFunctionEntryCount(UpdateFunctionEntryCount),
506 OrigEntryBBFreq(
507 BFI ? BFI->getBlockFreq(&F.getEntryBlock()).getFrequency() : 0U),
508 OrigEntryCount(F.getEntryCount() ? *F.getEntryCount() : 0) {
509 if (BFI) {
510 // The assert is meant as API documentation for the caller.
511 assert(OrigEntryBBFreq != 0 &&
512 "If a BFI was provided, the function should have an entry "
513 "basic block with a non-zero frequency.");
514 }
515 }
516
517 Constant *findBaseCaseRetConstant(Instruction *AccRecInstr);
518
519 Constant *canTransformAccumulatorRecursion(Instruction *I, CallInst *CI);
520
521 CallInst *findTRECandidate(BasicBlock *BB);
522
523 void createTailRecurseLoopHeader(CallInst *CI);
524
525 void insertAccumulator(Instruction *AccRecInstr);
526
527 bool eliminateCall(CallInst *CI);
528
529 void cleanupAndFinalize();
530
531 bool processBlock(BasicBlock &BB);
532
533 void copyByValueOperandIntoLocalTemp(CallInst *CI, int OpndIdx);
534
535 void copyLocalTempOfByValueOperandIntoArguments(CallInst *CI, int OpndIdx);
536
537public:
538 static bool eliminate(Function &F, const TargetTransformInfo *TTI,
539 AliasAnalysis *AA, OptimizationRemarkEmitter *ORE,
540 DomTreeUpdater &DTU, BlockFrequencyInfo *BFI,
541 ProfileSummaryInfo *PSI, bool UpdateFunctionEntryCount);
542};
543} // namespace
544
545// Find the base-case return value for the function, given the accumulator
546// recursion instruction AccRecInstr that is about to be eliminated. Every
547// return other than the one fed by AccRecInstr survives the transformation and
548// will be rewritten to return the accumulator, so all of them have to yield the
549// same base-case constant. Return that constant, or nullptr on failure.
550//
551// RetSelects are the selects already inserted for call sites eliminated via
552// the "found return value" mechanism instead of the accumulator one. Their
553// original `ret` is gone, so they'd otherwise be invisible to the scan below,
554// but they still have to agree on the same base-case constant.
555//
556// FIXME: There is a room for improvement here in the future, e.g., consider
557// non-constant values and multiple base cases -- e.g., we want to be able to
558// handle code like:
559// ```
560// int f(int x) {
561// if (x == 1) return 1;
562// if (x == 10) return 10;
563// return f(x-1) << 1;
564// }
565// ```
566Constant *
567TailRecursionEliminator::findBaseCaseRetConstant(Instruction *AccRecInstr) {
568 Constant *BaseCaseVal = nullptr;
569
570 // Records C as the base-case constant the first time it's seen, and
571 // otherwise checks that it agrees with the one already on record.
572 auto SetOrMatchBaseCase = [&](Constant *C) {
573 if (!BaseCaseVal)
574 BaseCaseVal = C;
575 return BaseCaseVal == C;
576 };
577
578 for (BasicBlock &BB : F) {
579 auto *RI = dyn_cast<ReturnInst>(BB.getTerminator());
580 if (!RI || !RI->getReturnValue())
581 continue;
582
583 Value *RV = RI->getReturnValue();
584
585 // This is the recursive case being turned into a loop: the return goes
586 // away along with AccRecInstr.
587 if (RV == AccRecInstr)
588 continue;
589
590 // Anything else has to be the base case. In particular a return still
591 // computing from a recursive call (e.g. a second recursion site that is
592 // not eliminated) must be rejected: returning the accumulator in its place
593 // would drop that computation.
594 auto *C = dyn_cast<Constant>(RV);
595 if (!C || !SetOrMatchBaseCase(C))
596 return nullptr;
597 }
598
599 for (SelectInst *SI : RetSelects) {
600 auto *C = dyn_cast<Constant>(SI->getFalseValue());
601 if (!C || !SetOrMatchBaseCase(C))
602 return nullptr;
603 }
604
605 return BaseCaseVal;
606}
607
608// This function checks whether the instruction I can be used
609// to perform accumulator recursion elimination for the
610// call instruction CI.
611Constant *
612TailRecursionEliminator::canTransformAccumulatorRecursion(Instruction *I,
613 CallInst *CI) {
614 bool IsUnaryAccumulatorRecurrence = isUnaryAccumulatorRecurrence(I);
615 if ((!I->isAssociative() || !I->isCommutative()) &&
616 !IsUnaryAccumulatorRecurrence)
617 return nullptr;
618
619 assert(I->getNumOperands() >= 2 &&
620 "Associative/commutative operations should have at least 2 args!");
621
622 Constant *AccInitVal = nullptr;
623 if (IsUnaryAccumulatorRecurrence) {
624 // For unary accumulator recurrences, we require that the recursive call
625 // is always on the first operand.
626 if (I->getOperand(0) != CI)
627 return nullptr;
628
629 // findTRECandidate guarantees CI is a recursive call to its own
630 // function, so scan the enclosing function for the base-case return.
631 AccInitVal = findBaseCaseRetConstant(/*AccRecInstr=*/I);
632 if (!AccInitVal)
633 return nullptr;
634 } else {
635 AccInitVal = ConstantExpr::getIdentity(I, I->getType());
636 if (!AccInitVal)
637 return nullptr;
638
639 // Exactly one operand should be the result of the call instruction.
640 if ((I->getOperand(0) == CI && I->getOperand(1) == CI) ||
641 (I->getOperand(0) != CI && I->getOperand(1) != CI))
642 return nullptr;
643 }
644
645 // The only user of this instruction we allow is a single return instruction.
646 if (!I->hasOneUse() || !isa<ReturnInst>(I->user_back()))
647 return nullptr;
648
649 return AccInitVal;
650}
651
652CallInst *TailRecursionEliminator::findTRECandidate(BasicBlock *BB) {
653 Instruction *TI = BB->getTerminator();
654
655 if (&BB->front() == TI) // Make sure there is something before the terminator.
656 return nullptr;
657
658 // Scan backwards from the return, checking to see if there is a tail call in
659 // this block. If so, set CI to it.
660 CallInst *CI = nullptr;
661 BasicBlock::iterator BBI(TI);
662 while (true) {
663 CI = dyn_cast<CallInst>(BBI);
664 if (CI && CI->getCalledFunction() == &F)
665 break;
666
667 if (BBI == BB->begin())
668 return nullptr; // Didn't find a potential tail call.
669 --BBI;
670 }
671
672 assert((!CI->isTailCall() || !CI->isNoTailCall()) &&
673 "Incompatible call site attributes(Tail,NoTail)");
674 if (!CI->isTailCall() || shouldDisableTailCallsForCold(CI, &F, PSI, BFI))
675 return nullptr;
676
677 // As a special case, detect code like this:
678 // double fabs(double f) { return __builtin_fabs(f); } // a 'fabs' call
679 // and disable this xform in this case, because the code generator will
680 // lower the call to fabs into inline code.
681 if (BB == &F.getEntryBlock() && &BB->front() == CI &&
682 &*std::next(BB->begin()) == TI && CI->getCalledFunction() &&
684 // A single-block function with just a call and a return. Check that
685 // the arguments match.
686 auto I = CI->arg_begin(), E = CI->arg_end();
687 Function::arg_iterator FI = F.arg_begin(), FE = F.arg_end();
688 for (; I != E && FI != FE; ++I, ++FI)
689 if (*I != &*FI) break;
690 if (I == E && FI == FE)
691 return nullptr;
692 }
693
694 return CI;
695}
696
697void TailRecursionEliminator::createTailRecurseLoopHeader(CallInst *CI) {
698 HeaderBB = &F.getEntryBlock();
699 BasicBlock *NewEntry = BasicBlock::Create(F.getContext(), "", &F, HeaderBB);
700 NewEntry->takeName(HeaderBB);
701 HeaderBB->setName("tailrecurse");
702 auto *BI = UncondBrInst::Create(HeaderBB, NewEntry);
703 BI->setDebugLoc(DebugLoc::getCompilerGenerated());
704 // If the new branch preserves the debug location of CI, it could result in
705 // misleading stepping, if CI is located in a conditional branch.
706 // So, here we don't give any debug location to the new branch.
707
708 // Move all fixed sized allocas from HeaderBB to NewEntry.
709 for (BasicBlock::iterator OEBI = HeaderBB->begin(), E = HeaderBB->end(),
710 NEBI = NewEntry->begin();
711 OEBI != E;)
712 if (AllocaInst *AI = dyn_cast<AllocaInst>(OEBI++))
713 if (isa<ConstantInt>(AI->getArraySize()))
714 AI->moveBefore(NEBI);
715
716 // Now that we have created a new block, which jumps to the entry
717 // block, insert a PHI node for each argument of the function.
718 // For now, we initialize each PHI to only have the real arguments
719 // which are passed in.
720 BasicBlock::iterator InsertPos = HeaderBB->begin();
721 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
722 PHINode *PN = PHINode::Create(I->getType(), 2, I->getName() + ".tr");
723 PN->insertBefore(InsertPos);
724 I->replaceAllUsesWith(PN); // Everyone use the PHI node now!
725 PN->addIncoming(&*I, NewEntry);
726 ArgumentPHIs.push_back(PN);
727 }
728
729 // If the function doen't return void, create the RetPN and RetKnownPN PHI
730 // nodes to track our return value. We initialize RetPN with poison and
731 // RetKnownPN with false since we can't know our return value at function
732 // entry.
733 Type *RetType = F.getReturnType();
734 if (!RetType->isVoidTy()) {
735 Type *BoolType = Type::getInt1Ty(F.getContext());
736 RetPN = PHINode::Create(RetType, 2, "ret.tr");
737 RetPN->insertBefore(InsertPos);
738 RetKnownPN = PHINode::Create(BoolType, 2, "ret.known.tr");
739 RetKnownPN->insertBefore(InsertPos);
740
741 RetPN->addIncoming(PoisonValue::get(RetType), NewEntry);
742 RetKnownPN->addIncoming(ConstantInt::getFalse(BoolType), NewEntry);
743 }
744
745 // The entry block was changed from HeaderBB to NewEntry.
746 // The forward DominatorTree needs to be recalculated when the EntryBB is
747 // changed. In this corner-case we recalculate the entire tree.
748 DTU.recalculate(*NewEntry->getParent());
749}
750
751void TailRecursionEliminator::insertAccumulator(Instruction *AccRecInstr) {
752 assert(!AccPN && "Trying to insert multiple accumulators");
753
754 AccumulatorRecursionInstr = AccRecInstr;
755
756 // Start by inserting a new PHI node for the accumulator.
757 pred_iterator PB = pred_begin(HeaderBB), PE = pred_end(HeaderBB);
758 AccPN = PHINode::Create(F.getReturnType(), std::distance(PB, PE) + 1,
759 "accumulator.tr");
760 AccPN->insertBefore(HeaderBB->begin());
761
762 // Loop over all of the predecessors of the tail recursion block. For the
763 // real entry into the function we seed the PHI with the identity constant for
764 // the accumulation operation. For any other existing branches to this block
765 // (due to other tail recursions eliminated) the accumulator is not modified.
766 // Because we haven't added the branch in the current block to HeaderBB yet,
767 // it will not show up as a predecessor.
768 for (pred_iterator PI = PB; PI != PE; ++PI) {
769 BasicBlock *P = *PI;
770 if (P == &F.getEntryBlock()) {
771 AccPN->addIncoming(AccumulatorInitialValue, P);
772 } else {
773 AccPN->addIncoming(AccPN, P);
774 }
775 }
776
777 ++NumAccumAdded;
778}
779
780// Creates a copy of contents of ByValue operand of the specified
781// call instruction into the newly created temporarily variable.
782void TailRecursionEliminator::copyByValueOperandIntoLocalTemp(CallInst *CI,
783 int OpndIdx) {
784 Type *AggTy = CI->getParamByValType(OpndIdx);
785 assert(AggTy);
786 const DataLayout &DL = F.getDataLayout();
787
788 // Get alignment of byVal operand.
789 Align Alignment(CI->getParamAlign(OpndIdx).valueOrOne());
790
791 // Create alloca for temporarily byval operands.
792 // Put alloca into the entry block.
793 Value *NewAlloca = new AllocaInst(
794 AggTy, DL.getAllocaAddrSpace(), nullptr, Alignment,
795 CI->getArgOperand(OpndIdx)->getName(), F.getEntryBlock().begin());
796
797 IRBuilder<> Builder(CI);
798 Value *Size = Builder.getInt64(DL.getTypeAllocSize(AggTy));
799
800 // Copy data from byvalue operand into the temporarily variable.
801 Builder.CreateMemCpy(NewAlloca, /*DstAlign*/ Alignment,
802 CI->getArgOperand(OpndIdx),
803 /*SrcAlign*/ Alignment, Size);
804 CI->setArgOperand(OpndIdx, NewAlloca);
805}
806
807// Creates a copy from temporarily variable(keeping value of ByVal argument)
808// into the corresponding function argument location.
809void TailRecursionEliminator::copyLocalTempOfByValueOperandIntoArguments(
810 CallInst *CI, int OpndIdx) {
811 Type *AggTy = CI->getParamByValType(OpndIdx);
812 assert(AggTy);
813 const DataLayout &DL = F.getDataLayout();
814
815 // Get alignment of byVal operand.
816 Align Alignment(CI->getParamAlign(OpndIdx).valueOrOne());
817
818 IRBuilder<> Builder(CI);
819 Value *Size = Builder.getInt64(DL.getTypeAllocSize(AggTy));
820
821 // Copy data from the temporarily variable into corresponding
822 // function argument location.
823 Builder.CreateMemCpy(F.getArg(OpndIdx), /*DstAlign*/ Alignment,
824 CI->getArgOperand(OpndIdx),
825 /*SrcAlign*/ Alignment, Size);
826}
827
828bool TailRecursionEliminator::eliminateCall(CallInst *CI) {
829 ReturnInst *Ret = cast<ReturnInst>(CI->getParent()->getTerminator());
830
831 // Ok, we found a potential tail call. We can currently only transform the
832 // tail call if all of the instructions between the call and the return are
833 // movable to above the call itself, leaving the call next to the return.
834 // Check that this is the case now.
835 Instruction *AccRecInstr = nullptr;
836 BasicBlock::iterator BBI(CI);
837 for (++BBI; &*BBI != Ret; ++BBI) {
838 if (canMoveAboveCall(&*BBI, CI, AA))
839 continue;
840
841 // If we can't move the instruction above the call, it might be because it
842 // is an (associative and commutative) or unary accumulator recurrence
843 // arithmetic operation that could be transformed using accumulator
844 // recursion elimination. Check to see if this is the case, and if so,
845 // remember which instruction accumulates for later.
846 Constant *AccInitVal = canTransformAccumulatorRecursion(&*BBI, CI);
847
848 if (AccPN || !AccInitVal)
849 return false; // We cannot eliminate the tail recursion!
850
851 // Yes, this is accumulator recursion. Remember which instruction
852 // accumulates.
853 AccRecInstr = &*BBI;
854
855 // Keep track of the base case (i.e., initial value) of the accumulator
856 // return value if any.
857 AccumulatorInitialValue = AccInitVal;
858 }
859
860 BasicBlock *BB = Ret->getParent();
861
862 if (BFI)
863 EliminateBlocksFrequencySum += BFI->getBlockFreq(BB).getFrequency();
864
865 using namespace ore;
866 ORE->emit([&]() {
867 return OptimizationRemark(DEBUG_TYPE, "tailcall-recursion", CI)
868 << "transforming tail recursion into loop";
869 });
870
871 // OK! We can transform this tail call. If this is the first one found,
872 // create the new entry block, allowing us to branch back to the old entry.
873 if (!HeaderBB)
874 createTailRecurseLoopHeader(CI);
875
876 // Copy values of ByVal operands into local temporarily variables.
877 for (unsigned I = 0, E = CI->arg_size(); I != E; ++I) {
878 if (CI->isByValArgument(I))
879 copyByValueOperandIntoLocalTemp(CI, I);
880 }
881
882 // Ok, now that we know we have a pseudo-entry block WITH all of the
883 // required PHI nodes, add entries into the PHI node for the actual
884 // parameters passed into the tail-recursive call.
885 for (unsigned I = 0, E = CI->arg_size(); I != E; ++I) {
886 if (CI->isByValArgument(I)) {
887 copyLocalTempOfByValueOperandIntoArguments(CI, I);
888 // When eliminating a tail call, we modify the values of the arguments.
889 // Therefore, if the byval parameter has a readonly attribute, we have to
890 // remove it. It is safe because, from the perspective of a caller, the
891 // byval parameter is always treated as "readonly," even if the readonly
892 // attribute is removed.
893 F.removeParamAttr(I, Attribute::ReadOnly);
894 ArgumentPHIs[I]->addIncoming(F.getArg(I), BB);
895 } else
896 ArgumentPHIs[I]->addIncoming(CI->getArgOperand(I), BB);
897 }
898
899 if (AccRecInstr) {
900 insertAccumulator(AccRecInstr);
901
902 // Rewrite the accumulator recursion instruction so that it does not use
903 // the result of the call anymore, instead, use the PHI node we just
904 // inserted.
905 AccRecInstr->setOperand(AccRecInstr->getOperand(0) != CI, AccPN);
906
907 // Reassociating into the loop reorders the operands, so flags from the
908 // original order (nsw/nuw/exact/...) may no longer hold.
909 AccRecInstr->dropPoisonGeneratingFlags();
910 }
911
912 // Update our return value tracking
913 if (RetPN) {
914 if (Ret->getReturnValue() == CI || AccRecInstr) {
915 // Defer selecting a return value
916 RetPN->addIncoming(RetPN, BB);
917 RetKnownPN->addIncoming(RetKnownPN, BB);
918 } else {
919 // We found a return value we want to use, insert a select instruction to
920 // select it if we don't already know what our return value will be and
921 // store the result in our return value PHI node.
922 SelectInst *SI =
923 SelectInst::Create(RetKnownPN, RetPN, Ret->getReturnValue(),
924 "current.ret.tr", Ret->getIterator());
925 SI->setDebugLoc(Ret->getDebugLoc());
926 RetSelects.push_back(SI);
927
928 RetPN->addIncoming(SI, BB);
929 RetKnownPN->addIncoming(ConstantInt::getTrue(RetKnownPN->getType()), BB);
930 }
931
932 if (AccPN)
933 AccPN->addIncoming(AccRecInstr ? AccRecInstr : AccPN, BB);
934 }
935
936 // Now that all of the PHI nodes are in place, remove the call and
937 // ret instructions, replacing them with an unconditional branch.
938 UncondBrInst *NewBI = UncondBrInst::Create(HeaderBB, Ret->getIterator());
939 NewBI->setDebugLoc(CI->getDebugLoc());
940
941 Ret->eraseFromParent(); // Remove return.
942 CI->eraseFromParent(); // Remove call.
943 DTU.applyUpdates({{DominatorTree::Insert, BB, HeaderBB}});
944 ++NumEliminated;
945 if (!DisableEntryCountRecompute && UpdateFunctionEntryCount &&
946 OrigEntryBBFreq) {
947 assert(F.getEntryCount().has_value());
948 // This pass is not expected to remove BBs, only add an entry BB. For that
949 // reason, and because the BB here isn't the new entry BB, the BFI lookup is
950 // expected to succeed.
951 assert(&F.getEntryBlock() != BB);
952 auto RelativeBBFreq =
953 static_cast<double>(BFI->getBlockFreq(BB).getFrequency()) /
954 static_cast<double>(OrigEntryBBFreq);
955 auto ToSubtract =
956 static_cast<uint64_t>(std::round(RelativeBBFreq * OrigEntryCount));
957 auto OldEntryCount = *F.getEntryCount();
958 if (OldEntryCount <= ToSubtract) {
960 errs() << "[TRE] The entrycount attributable to the recursive call, "
961 << ToSubtract
962 << ", should be strictly lower than the function entry count, "
963 << OldEntryCount << "\n");
964 } else {
965 F.setEntryCount(OldEntryCount - ToSubtract);
966 }
967 }
968 return true;
969}
970
971void TailRecursionEliminator::cleanupAndFinalize() {
972 // If we eliminated any tail recursions, it's possible that we inserted some
973 // silly PHI nodes which just merge an initial value (the incoming operand)
974 // with themselves. Check to see if we did and clean up our mess if so. This
975 // occurs when a function passes an argument straight through to its tail
976 // call.
977 for (PHINode *PN : ArgumentPHIs) {
978 // If the PHI Node is a dynamic constant, replace it with the value it is.
979 if (Value *PNV = simplifyInstruction(PN, F.getDataLayout())) {
980 PN->replaceAllUsesWith(PNV);
981 PN->eraseFromParent();
982 }
983 }
984
985 if (RetPN) {
986 Instruction *AccRecInstr = AccumulatorRecursionInstr;
987 auto MaterializeAccumulator = [&](Value *OtherVal,
988 BasicBlock::iterator InsertPt) {
989 Instruction *New = AccRecInstr->clone();
990 New->setName("accumulator.ret.tr");
991 New->setOperand(AccRecInstr->getOperand(0) == AccPN, OtherVal);
992 New->insertBefore(InsertPt);
993 New->dropLocation();
994 return New;
995 };
996
997 if (RetSelects.empty()) {
998 // If we didn't insert any select instructions, then we know we didn't
999 // store a return value and we can remove the PHI nodes we inserted.
1000 RetPN->dropAllReferences();
1001 RetPN->eraseFromParent();
1002
1003 RetKnownPN->dropAllReferences();
1004 RetKnownPN->eraseFromParent();
1005
1006 if (AccPN) {
1007 // We need to insert a copy of our accumulator instruction before any
1008 // return in the function, and return its result instead.
1009 for (BasicBlock &BB : F) {
1010 ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator());
1011 if (!RI)
1012 continue;
1013
1014 if (isUnaryAccumulatorRecurrence(AccRecInstr)) {
1015 // Base-case initialization: the accumulator PHI already holds the
1016 // final result, so return it directly.
1017 RI->setOperand(0, AccPN);
1018 } else {
1019 // Since the accumulator starts with the identity value, before the
1020 // return we need to apply the accumulation instruction one more
1021 // time to combine the last value with the result of the recursive
1022 // call.
1023 RI->setOperand(0, MaterializeAccumulator(RI->getOperand(0),
1024 RI->getIterator()));
1025 }
1026 }
1027 }
1028 } else {
1029 // We need to insert a select instruction before any return left in the
1030 // function to select our stored return value if we have one.
1031 for (BasicBlock &BB : F) {
1032 ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator());
1033 if (!RI)
1034 continue;
1035
1036 SelectInst *SI =
1037 SelectInst::Create(RetKnownPN, RetPN, RI->getOperand(0),
1038 "current.ret.tr", RI->getIterator());
1039 SI->setDebugLoc(DebugLoc::getCompilerGenerated());
1040 RetSelects.push_back(SI);
1041 RI->setOperand(0, SI);
1042 }
1043
1044 if (AccPN) {
1045 // We need to insert a copy of our accumulator instruction before any
1046 // of the selects we inserted, and select its result instead.
1047 for (SelectInst *SI : RetSelects) {
1048 if (isUnaryAccumulatorRecurrence(AccRecInstr)) {
1049 SI->setFalseValue(AccPN);
1050 } else {
1051 SI->setFalseValue(
1052 MaterializeAccumulator(SI->getFalseValue(), SI->getIterator()));
1053 }
1054 }
1055 }
1056 }
1057
1058 if (BFI) {
1059 uint64_t BaseCaseBlocksFrequencySum = 0;
1060 for (BasicBlock &BB : F)
1062 BaseCaseBlocksFrequencySum += BFI->getBlockFreq(&BB).getFrequency();
1063
1064 if (EliminateBlocksFrequencySum + BaseCaseBlocksFrequencySum == 0)
1065 return;
1066 SmallVector<uint32_t> Testing = fitWeights({EliminateBlocksFrequencySum, BaseCaseBlocksFrequencySum});
1067 MDBuilder MDB(F.getContext());
1068 MDNode *BranchWeights = MDB.createBranchWeights(
1069 {Testing[0], Testing[1]},
1070 false);
1071 for (SelectInst *SI : RetSelects)
1072 SI->setMetadata(LLVMContext::MD_prof, BranchWeights);
1073 }
1074 }
1075}
1076
1077bool TailRecursionEliminator::processBlock(BasicBlock &BB) {
1078 Instruction *TI = BB.getTerminator();
1079
1080 if (UncondBrInst *BI = dyn_cast<UncondBrInst>(TI)) {
1081 BasicBlock *Succ = BI->getSuccessor();
1082 ReturnInst *Ret = dyn_cast<ReturnInst>(Succ->getFirstNonPHIOrDbg(true));
1083
1084 if (!Ret)
1085 return false;
1086
1087 CallInst *CI = findTRECandidate(&BB);
1088
1089 if (!CI)
1090 return false;
1091
1092 LLVM_DEBUG(dbgs() << "FOLDING: " << *Succ
1093 << "INTO UNCOND BRANCH PRED: " << BB);
1094 FoldReturnIntoUncondBranch(Ret, Succ, &BB, &DTU);
1095 ++NumRetDuped;
1096
1097 // If all predecessors of Succ have been eliminated by
1098 // FoldReturnIntoUncondBranch, delete it. It is important to empty it,
1099 // because the ret instruction in there is still using a value which
1100 // eliminateCall will attempt to remove. This block can only contain
1101 // instructions that can't have uses, therefore it is safe to remove.
1102 if (pred_empty(Succ))
1103 DTU.deleteBB(Succ);
1104
1105 eliminateCall(CI);
1106 return true;
1107 }
1108
1109 if (isa<ReturnInst>(TI)) {
1110 CallInst *CI = findTRECandidate(&BB);
1111
1112 if (CI)
1113 return eliminateCall(CI);
1114 }
1115
1116 return false;
1117}
1118
1119bool TailRecursionEliminator::eliminate(
1120 Function &F, const TargetTransformInfo *TTI, AliasAnalysis *AA,
1121 OptimizationRemarkEmitter *ORE, DomTreeUpdater &DTU,
1122 BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
1123 bool UpdateFunctionEntryCount) {
1124 if (F.getFnAttribute("disable-tail-calls").getValueAsBool())
1125 return false;
1126
1127 bool MadeChange = false;
1128 MadeChange |= markTails(F, ORE, PSI, BFI);
1129
1130 // If this function is a varargs function, we won't be able to PHI the args
1131 // right, so don't even try to convert it...
1132 if (F.getFunctionType()->isVarArg())
1133 return MadeChange;
1134
1135 if (!canTRE(F))
1136 return MadeChange;
1137
1138 // Change any tail recursive calls to loops.
1139 TailRecursionEliminator TRE(F, TTI, AA, ORE, DTU, BFI, PSI,
1140 UpdateFunctionEntryCount);
1141
1142 for (BasicBlock &BB : F)
1143 MadeChange |= TRE.processBlock(BB);
1144
1145 TRE.cleanupAndFinalize();
1146
1147 return MadeChange;
1148}
1149
1150namespace {
1151struct TailCallElim : public FunctionPass {
1152 static char ID; // Pass identification, replacement for typeid
1153 TailCallElim() : FunctionPass(ID) {
1155 }
1156
1157 void getAnalysisUsage(AnalysisUsage &AU) const override {
1158 AU.addRequired<TargetTransformInfoWrapperPass>();
1159 AU.addRequired<AAResultsWrapperPass>();
1160 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
1161 AU.addPreserved<GlobalsAAWrapperPass>();
1162 AU.addPreserved<DominatorTreeWrapperPass>();
1163 AU.addPreserved<PostDominatorTreeWrapperPass>();
1164 }
1165
1166 bool runOnFunction(Function &F) override {
1167 if (skipFunction(F))
1168 return false;
1169
1170 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1171 auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
1172 auto *PDTWP = getAnalysisIfAvailable<PostDominatorTreeWrapperPass>();
1173 auto *PDT = PDTWP ? &PDTWP->getPostDomTree() : nullptr;
1174 // There is no noticable performance difference here between Lazy and Eager
1175 // UpdateStrategy based on some test results. It is feasible to switch the
1176 // UpdateStrategy to Lazy if we find it profitable later.
1177 DomTreeUpdater DTU(DT, PDT, DomTreeUpdater::UpdateStrategy::Eager);
1178
1179 return TailRecursionEliminator::eliminate(
1180 F, &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F),
1181 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
1182 &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(), DTU,
1183 /*BFI=*/nullptr, /*PSI=*/nullptr, /*UpdateFunctionEntryCount=*/false);
1184 }
1185};
1186} // namespace
1187
1188char TailCallElim::ID = 0;
1189INITIALIZE_PASS_BEGIN(TailCallElim, "tailcallelim", "Tail Call Elimination",
1190 false, false)
1193INITIALIZE_PASS_END(TailCallElim, "tailcallelim", "Tail Call Elimination",
1195
1196// Public interface to the TailCallElimination pass
1198 return new TailCallElim();
1199}
1200
1203
1206 // This must come first. It needs the 2 analyses, meaning, if it came after
1207 // the lines asking for the cached result, should they be nullptr (which, in
1208 // the case of the PDT, is likely), updates to the trees would be missed.
1209 auto *BFI = F.getEntryCount().has_value()
1211 : nullptr;
1212 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
1213 auto *PSI = MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
1215 auto *DT = AM.getCachedResult<DominatorTreeAnalysis>(F);
1217 // There is no noticable performance difference here between Lazy and Eager
1218 // UpdateStrategy based on some test results. It is feasible to switch the
1219 // UpdateStrategy to Lazy if we find it profitable later.
1220 DomTreeUpdater DTU(DT, PDT, DomTreeUpdater::UpdateStrategy::Eager);
1221 bool Changed = TailRecursionEliminator::eliminate(
1222 F, &TTI, &AA, &ORE, DTU, BFI, PSI, UpdateFunctionEntryCount);
1223
1224 if (!Changed)
1225 return PreservedAnalyses::all();
1229 return PA;
1230}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static bool runOnFunction(Function &F, bool PostInlining)
#define DEBUG_TYPE
This is the interface for a simple mod/ref and alias analysis over globals.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t IntrinsicInst * II
#define P(N)
PassBuilder PB(Machine, PassOpts->PTO, std::nullopt, &PIC)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file contains the declarations for profiling metadata utility functions.
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallPtrSet class.
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:119
static bool canTRE(Function &F)
Scan the specified function for alloca instructions.
static bool isUnaryAccumulatorRecurrence(Instruction *I)
static cl::opt< bool > DisableTailCallElimForColdCalls("disable-tail-call-elim-for-cold-calls", cl::Hidden, cl::init(false), cl::desc("Disable tail call elimination and optimization for cold calls or " "in cold functions"))
static bool canMoveAboveCall(Instruction *I, CallInst *CI, AliasAnalysis *AA)
Return true if it is safe to move the specified instruction from after the call to before the call,...
static cl::opt< bool > DisableEntryCountRecompute("tre-disable-entrycount-recompute", cl::init(false), cl::Hidden, cl::desc("Force disabling recomputing of function entry count, on " "successful tail recursion elimination."))
static bool markTails(Function &F, OptimizationRemarkEmitter *ORE, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI)
static bool shouldDisableTailCallsForCold(const CallBase *CB, const Function *Caller, const ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI)
This pass exposes codegen information to IR-level passes.
A manager for alias analyses.
an instruction to allocate memory on the stack
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:459
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:446
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
LLVM_ABI InstListType::const_iterator getFirstNonPHIOrDbg(bool SkipPseudoOp=true) const
Returns a pointer to the first instruction in this block that is not a PHINode or a debug intrinsic,...
const Instruction & front() const
Definition BasicBlock.h:469
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
LLVM_ABI BlockFrequency getBlockFreq(const BasicBlock *BB) const
getblockFreq - Return block frequency.
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
bool doesNotAccessMemory(unsigned OpNo) const
bool hasFnAttr(Attribute::AttrKind Kind) const
Determine whether this call has the given attribute.
CallingConv::ID getCallingConv() const
User::op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
LLVM_ABI bool isMustTailCall() const
Tests if this call site must be tail call optimized.
bool isByValArgument(unsigned ArgNo) const
Determine whether this argument is passed by value.
MaybeAlign getParamAlign(unsigned ArgNo) const
Extract the alignment for a call or parameter (0=unknown).
bool onlyReadsMemory(unsigned OpNo) const
Type * getParamByValType(unsigned ArgNo) const
Extract the byval type for a call or parameter.
bool hasOperandBundlesOtherThan(ArrayRef< uint32_t > IDs) const
Return true if this operand bundle user contains operand bundles with tags other than those specified...
Value * getArgOperand(unsigned i) const
void setArgOperand(unsigned i, Value *v)
User::op_iterator arg_end()
Return the iterator pointing to the end of the argument list.
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
unsigned arg_size() const
This class represents a function call, abstracting a target machine's calling convention.
bool isNoTailCall() const
bool isTailCall() const
void setTailCall(bool IsTc=true)
static LLVM_ABI Constant * getIdentity(Instruction *I, Type *Ty, bool AllowRHSConstant=false, bool NSZ=false)
Return the identity constant for a binary or intrinsic Instruction.
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
This is an important base class in LLVM.
Definition Constant.h:43
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
static DebugLoc getCompilerGenerated()
Definition DebugLoc.h:154
LLVM_ABI void deleteBB(BasicBlock *DelBB)
Delete DelBB.
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
Argument * arg_iterator
Definition Function.h:73
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
void recalculate(FuncT &F)
Notify DTU that the entry block was replaced.
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI bool mayHaveSideEffects() const LLVM_READONLY
Return true if the instruction may have side effects.
LLVM_ABI void dropPoisonGeneratingFlags()
Drops flags that may cause this instruction to evaluate to poison despite having non-poison inputs.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
A wrapper class for inspecting calls to intrinsic functions.
An instruction for reading from memory.
static LLVM_ABI MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
OptimizationRemarkEmitter legacy analysis pass.
The optimization diagnostic interface.
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Diagnostic information for applied optimization remarks.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Analysis pass which computes a PostDominatorTree.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
Analysis providing profile information.
bool hasProfileSummary() const
Returns true if profile summary is available.
bool isColdBlock(const BBType *BB, BFIT *BFI) const
Returns true if BasicBlock BB is considered cold.
LLVM_ABI bool isColdCallSite(const CallBase &CB, BlockFrequencyInfo *BFI) const
Returns true if call site CB is considered cold.
LLVM_ABI bool isFunctionEntryCold(const Function *F) const
Returns true if F has cold function entry.
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
iterator begin() const
Definition StringRef.h:114
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Analysis pass providing the TargetTransformInfo.
Wrapper pass for TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
LLVM_ABI bool isLoweredToCall(const Function *F) const
Test whether calls to a function lower to actual program function calls.
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
void dropAllReferences()
Drop all references to operands.
Definition User.h:324
void setOperand(unsigned i, Value *Val)
Definition User.h:212
Value * getOperand(unsigned i) const
Definition User.h:207
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:394
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:400
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
Changed
Abstract Attribute helper functions.
Definition Attributor.h:165
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ Cold
Attempts to make code in the caller as efficient as possible under the assumption that the call is no...
Definition CallingConv.h:47
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
initializer< Ty > init(const Ty &Val)
Add a small namespace to avoid name clashes with the classes used in the streaming interface.
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
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:1755
LLVM_ABI FunctionPass * createTailCallEliminationPass()
auto pred_end(const MachineBasicBlock *BB)
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
OuterAnalysisManagerProxy< ModuleAnalysisManager, Function > ModuleAnalysisManagerFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
LLVM_ABI ReturnInst * FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB, BasicBlock *Pred, DomTreeUpdater *DTU=nullptr)
This method duplicates the specified return instruction into a predecessor which ends in an unconditi...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
LLVM_ABI SmallVector< uint32_t > fitWeights(ArrayRef< uint64_t > Weights)
Push the weights right to fit in uint32_t.
bool isModSet(const ModRefInfo MRI)
Definition ModRef.h:49
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
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:547
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
TargetTransformInfo TTI
PredIterator< BasicBlock, Value::user_iterator > pred_iterator
Definition CFG.h:93
auto pred_begin(const MachineBasicBlock *BB)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isSafeToLoadUnconditionally(Value *V, Align Alignment, const APInt &Size, const SimplifyQuery &SQ)
Return true if we know that executing a load from this value cannot trap.
Definition Loads.cpp:456
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
bool pred_empty(const BasicBlock *BB)
Definition CFG.h:107
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI void initializeTailCallElimPass(PassRegistry &)
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
Align valueOrOne() const
For convenience, returns a valid alignment or 1 if undefined.
Definition Alignment.h:130