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"
60#include "llvm/Analysis/Loads.h"
66#include "llvm/IR/CFG.h"
67#include "llvm/IR/Constants.h"
68#include "llvm/IR/DataLayout.h"
71#include "llvm/IR/Dominators.h"
72#include "llvm/IR/Function.h"
73#include "llvm/IR/IRBuilder.h"
77#include "llvm/IR/Module.h"
79#include "llvm/Pass.h"
81#include "llvm/Support/Debug.h"
85#include <cmath>
86using namespace llvm;
87
88#define DEBUG_TYPE "tailcallelim"
89
90STATISTIC(NumEliminated, "Number of tail calls removed");
91STATISTIC(NumRetDuped, "Number of return duplicated");
92STATISTIC(NumAccumAdded, "Number of accumulators introduced");
93STATISTIC(NumTREPreventedCold,
94 "Number of tail calls/recursion eliminations prevented due to cold "
95 "calling convention or attribute");
96
98 "tre-disable-entrycount-recompute", cl::init(false), cl::Hidden,
99 cl::desc("Force disabling recomputing of function entry count, on "
100 "successful tail recursion elimination."));
101
103 "disable-tail-call-elim-for-cold-calls", cl::Hidden, cl::init(false),
104 cl::desc("Disable tail call elimination and optimization for cold calls or "
105 "in cold functions"));
106
108 const Function *Caller,
109 const ProfileSummaryInfo *PSI,
110 BlockFrequencyInfo *BFI) {
112 return false;
113
114 if (CB && CB->isMustTailCall())
115 return false;
116
117 if (CB && (CB->hasFnAttr(Attribute::Cold) ||
119 return true;
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 if (CB && BFI &&
129 (PSI->isColdCallSite(*CB, BFI) || PSI->isColdBlock(CB->getParent(), BFI)))
130 return true;
131
132 return false;
133}
134
135/// Scan the specified function for alloca instructions.
136/// If it contains any dynamic allocas, returns false.
137static bool canTRE(Function &F) {
138 // TODO: We don't do TRE if dynamic allocas are used.
139 // Dynamic allocas allocate stack space which should be
140 // deallocated before new iteration started. That is
141 // currently not implemented.
142 return llvm::all_of(instructions(F), [](Instruction &I) {
143 auto *AI = dyn_cast<AllocaInst>(&I);
144 return !AI || AI->isStaticAlloca();
145 });
146}
147
148namespace {
149struct AllocaDerivedValueTracker {
150 // Start at a root value and walk its use-def chain to mark calls that use the
151 // value or a derived value in AllocaUsers, and places where it may escape in
152 // EscapePoints.
153 void walk(Value *Root) {
154 SmallVector<Use *, 32> Worklist;
155 SmallPtrSet<Use *, 32> Visited;
156
157 auto AddUsesToWorklist = [&](Value *V) {
158 for (auto &U : V->uses()) {
159 if (!Visited.insert(&U).second)
160 continue;
161 Worklist.push_back(&U);
162 }
163 };
164
165 AddUsesToWorklist(Root);
166
167 while (!Worklist.empty()) {
168 Use *U = Worklist.pop_back_val();
169 Instruction *I = cast<Instruction>(U->getUser());
170
171 switch (I->getOpcode()) {
172 case Instruction::Call:
173 case Instruction::Invoke: {
174 auto &CB = cast<CallBase>(*I);
175 // If the alloca-derived argument is passed byval it is not an escape
176 // point, or a use of an alloca. Calling with byval copies the contents
177 // of the alloca into argument registers or stack slots, which exist
178 // beyond the lifetime of the current frame.
179 if (CB.isArgOperand(U) && CB.isByValArgument(CB.getArgOperandNo(U)))
180 continue;
181 bool IsNocapture =
182 CB.isDataOperand(U) && CB.doesNotCapture(CB.getDataOperandNo(U));
183 callUsesLocalStack(CB, IsNocapture);
184 if (IsNocapture) {
185 // If the alloca-derived argument is passed in as nocapture, then it
186 // can't propagate to the call's return. That would be capturing.
187 continue;
188 }
189 break;
190 }
191 case Instruction::Load: {
192 // The result of a load is not alloca-derived (unless an alloca has
193 // otherwise escaped, but this is a local analysis).
194 continue;
195 }
196 case Instruction::Store: {
197 if (U->getOperandNo() == 0)
198 EscapePoints.insert(I);
199 continue; // Stores have no users to analyze.
200 }
201 case Instruction::BitCast:
202 case Instruction::GetElementPtr:
203 case Instruction::PHI:
204 case Instruction::Select:
205 case Instruction::AddrSpaceCast:
206 break;
207 default:
208 EscapePoints.insert(I);
209 break;
210 }
211
212 AddUsesToWorklist(I);
213 }
214 }
215
216 void callUsesLocalStack(CallBase &CB, bool IsNocapture) {
217 // Add it to the list of alloca users.
218 AllocaUsers.insert(&CB);
219
220 // If it's nocapture then it can't capture this alloca.
221 if (IsNocapture)
222 return;
223
224 // If it can write to memory, it can leak the alloca value.
225 if (!CB.onlyReadsMemory())
226 EscapePoints.insert(&CB);
227 }
228
229 SmallPtrSet<Instruction *, 32> AllocaUsers;
230 SmallPtrSet<Instruction *, 32> EscapePoints;
231};
232} // namespace
233
236 if (F.callsFunctionThatReturnsTwice())
237 return false;
238
239 // The local stack holds all alloca instructions and all byval arguments.
240 AllocaDerivedValueTracker Tracker;
241 for (Argument &Arg : F.args()) {
242 if (Arg.hasByValAttr())
243 Tracker.walk(&Arg);
244 }
245 for (auto &BB : F) {
246 for (auto &I : BB)
248 Tracker.walk(AI);
249 }
250
251 bool Modified = false;
252
253 // Track whether a block is reachable after an alloca has escaped. Blocks that
254 // contain the escaping instruction will be marked as being visited without an
255 // escaped alloca, since that is how the block began.
256 enum VisitType {
257 UNVISITED,
258 UNESCAPED,
259 ESCAPED
260 };
262
263 // We propagate the fact that an alloca has escaped from block to successor.
264 // Visit the blocks that are propagating the escapedness first. To do this, we
265 // maintain two worklists.
266 SmallVector<BasicBlock *, 32> WorklistUnescaped, WorklistEscaped;
267
268 // We may enter a block and visit it thinking that no alloca has escaped yet,
269 // then see an escape point and go back around a loop edge and come back to
270 // the same block twice. Because of this, we defer setting tail on calls when
271 // we first encounter them in a block. Every entry in this list does not
272 // statically use an alloca via use-def chain analysis, but may find an alloca
273 // through other means if the block turns out to be reachable after an escape
274 // point.
275 SmallVector<CallInst *, 32> DeferredTails;
276
277 BasicBlock *BB = &F.getEntryBlock();
278 VisitType Escaped = UNESCAPED;
279 do {
280 for (auto &I : *BB) {
281 if (Tracker.EscapePoints.count(&I))
282 Escaped = ESCAPED;
283
285 // A PseudoProbeInst has the IntrInaccessibleMemOnly tag hence it is
286 // considered accessing memory and will be marked as a tail call if we
287 // don't bail out here.
288 if (!CI || CI->isTailCall() || isa<PseudoProbeInst>(&I))
289 continue;
290
291 // Bail out for intrinsic stackrestore call because it can modify
292 // unescaped allocas.
293 if (auto *II = dyn_cast<IntrinsicInst>(CI))
294 if (II->getIntrinsicID() == Intrinsic::stackrestore)
295 continue;
296
297 // Special-case operand bundles "clang.arc.attachedcall", "ptrauth", and
298 // "kcfi".
299 bool DisableForCold = shouldDisableTailCallsForCold(CI, &F, PSI, BFI);
300 bool IsNoTail = CI->isNoTailCall() || DisableForCold ||
304 if (!CI->isNoTailCall() && DisableForCold)
305 ++NumTREPreventedCold;
306
307 if (!IsNoTail && CI->doesNotAccessMemory()) {
308 // A call to a readnone function whose arguments are all things computed
309 // outside this function can be marked tail. Even if you stored the
310 // alloca address into a global, a readnone function can't load the
311 // global anyhow.
312 //
313 // Note that this runs whether we know an alloca has escaped or not. If
314 // it has, then we can't trust Tracker.AllocaUsers to be accurate.
315 bool SafeToTail = true;
316 for (auto &Arg : CI->args()) {
317 if (isa<Constant>(Arg.getUser()))
318 continue;
319 if (Argument *A = dyn_cast<Argument>(Arg.getUser()))
320 if (!A->hasByValAttr())
321 continue;
322 SafeToTail = false;
323 break;
324 }
325 if (SafeToTail) {
326 using namespace ore;
327 ORE->emit([&]() {
328 return OptimizationRemark(DEBUG_TYPE, "tailcall-readnone", CI)
329 << "marked as tail call candidate (readnone)";
330 });
331 CI->setTailCall();
332 Modified = true;
333 continue;
334 }
335 }
336
337 if (!IsNoTail && Escaped == UNESCAPED && !Tracker.AllocaUsers.count(CI))
338 DeferredTails.push_back(CI);
339 }
340
341 for (auto *SuccBB : successors(BB)) {
342 auto &State = Visited[SuccBB];
343 if (State < Escaped) {
344 State = Escaped;
345 if (State == ESCAPED)
346 WorklistEscaped.push_back(SuccBB);
347 else
348 WorklistUnescaped.push_back(SuccBB);
349 }
350 }
351
352 if (!WorklistEscaped.empty()) {
353 BB = WorklistEscaped.pop_back_val();
354 Escaped = ESCAPED;
355 } else {
356 BB = nullptr;
357 while (!WorklistUnescaped.empty()) {
358 auto *NextBB = WorklistUnescaped.pop_back_val();
359 if (Visited[NextBB] == UNESCAPED) {
360 BB = NextBB;
361 Escaped = UNESCAPED;
362 break;
363 }
364 }
365 }
366 } while (BB);
367
368 for (CallInst *CI : DeferredTails) {
369 if (Visited[CI->getParent()] != ESCAPED) {
370 // If the escape point was part way through the block, calls after the
371 // escape point wouldn't have been put into DeferredTails.
372 LLVM_DEBUG(dbgs() << "Marked as tail call candidate: " << *CI << "\n");
373 CI->setTailCall();
374 Modified = true;
375 }
376 }
377
378 return Modified;
379}
380
381/// Return true if it is safe to move the specified
382/// instruction from after the call to before the call, assuming that all
383/// instructions between the call and this instruction are movable.
384///
387 if (II->getIntrinsicID() == Intrinsic::lifetime_end)
388 return true;
389
390 // FIXME: We can move load/store/call/free instructions above the call if the
391 // call does not mod/ref the memory location being processed.
392 if (I->mayHaveSideEffects()) // This also handles volatile loads.
393 return false;
394
395 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
396 // Loads may always be moved above calls without side effects.
397 if (CI->mayHaveSideEffects()) {
398 // Non-volatile loads may be moved above a call with side effects if it
399 // does not write to memory and the load provably won't trap.
400 // Writes to memory only matter if they may alias the pointer
401 // being loaded from.
402 const DataLayout &DL = L->getDataLayout();
403 if (isModSet(AA->getModRefInfo(CI, MemoryLocation::get(L))) ||
404 !isSafeToLoadUnconditionally(L->getPointerOperand(), L->getType(),
405 L->getAlign(), DL, L))
406 return false;
407 }
408 }
409
410 // Otherwise, if this is a side-effect free instruction, check to make sure
411 // that it does not use the return value of the call. If it doesn't use the
412 // return value of the call, it must only use things that are defined before
413 // the call, or movable instructions between the call and the instruction
414 // itself.
415 return !is_contained(I->operands(), CI);
416}
417
418// Return true if I is a unary accumulator recurrence: a chain of
419// applications of a unary function `g` composed with itself,
420// `g(g(...g(Base)...))`, which is equivalent to a single application of the
421// N-times-composed function when `g` is pure. Neither associative nor
422// commutative, this differs from the ordinary accumulator recurrence handled
423// below, which requires I to be associative and commutative.
424//
425// TODO: Generalize this beyond shifts by a constant amount to arbitrary pure
426// unary functions (e.g., `f(x) = x == 0 ? Base : g(f(x - 1))` for any pure
427// unary `g`).
429 if (!I->isShift())
430 return false;
431
432 // A chain of shifts by a constant amount C is equivalent to a single shift
433 // by the sum of the amounts:
434 // ... (Base << C) << C) ... << C == Base << (C * Iterations)
435 // This relation applies to left shifts as well as arithmetic/logical right
436 // shifts when the shift amount is a constant.
437 return isa<ConstantInt>(I->getOperand(1));
438}
439
440// Find the base-case return value for function F, given the accumulator
441// recursion instruction AccRecInstr that is about to be eliminated. Every
442// return other than the one fed by AccRecInstr survives the transformation and
443// will be rewritten to return the accumulator, so all of them have to yield the
444// same base-case constant. Return that constant, or nullptr on failure.
445//
446// FIXME: There is a room for improvement here in the future, e.g., consider
447// non-constant values and multiple base cases -- e.g., we want to be able to
448// handle code like:
449// ```
450// int f(int x) {
451// if (x == 1) return 1;
452// if (x == 10) return 10;
453// return f(x-1) << 1;
454// }
455// ```
457 Instruction *AccRecInstr) {
458 Constant *BaseCaseVal = nullptr;
459
460 for (BasicBlock &BB : F) {
461 auto *RI = dyn_cast<ReturnInst>(BB.getTerminator());
462 if (!RI || !RI->getReturnValue())
463 continue;
464
465 Value *RV = RI->getReturnValue();
466
467 // This is the recursive case being turned into a loop: the return goes
468 // away along with AccRecInstr.
469 if (RV == AccRecInstr)
470 continue;
471
472 // Anything else has to be the base case. In particular a return still
473 // computing from a recursive call (e.g. a second recursion site that is
474 // not eliminated) must be rejected: returning the accumulator in its place
475 // would drop that computation.
476 auto *C = dyn_cast<Constant>(RV);
477 if (!C)
478 return nullptr;
479
480 if (!BaseCaseVal)
481 BaseCaseVal = C;
482 else if (BaseCaseVal != C)
483 return nullptr;
484 }
485
486 return BaseCaseVal;
487}
488
489// This function checks whether the instruction I can be used
490// to perform accumulator recursion elimination for the
491// call instruction CI.
493 CallInst *CI) {
494 bool IsUnaryAccumulatorRecurrence = isUnaryAccumulatorRecurrence(I);
495 if ((!I->isAssociative() || !I->isCommutative()) &&
496 !IsUnaryAccumulatorRecurrence)
497 return nullptr;
498
499 assert(I->getNumOperands() >= 2 &&
500 "Associative/commutative operations should have at least 2 args!");
501
502 Constant *AccInitVal = nullptr;
503 if (IsUnaryAccumulatorRecurrence) {
504 // For unary accumulator recurrences, we require that the recursive call
505 // is always on the first operand.
506 if (I->getOperand(0) != CI)
507 return nullptr;
508
509 // findTRECandidate guarantees CI is a recursive call to its own
510 // function, so scan the enclosing function for the base-case return.
511 AccInitVal = findBaseCaseRetConstant(*CI->getFunction(), /*AccRecInstr=*/I);
512 if (!AccInitVal)
513 return nullptr;
514 } else {
515 AccInitVal = ConstantExpr::getIdentity(I, I->getType());
516 if (!AccInitVal)
517 return nullptr;
518
519 // Exactly one operand should be the result of the call instruction.
520 if ((I->getOperand(0) == CI && I->getOperand(1) == CI) ||
521 (I->getOperand(0) != CI && I->getOperand(1) != CI))
522 return nullptr;
523 }
524
525 // The only user of this instruction we allow is a single return instruction.
526 if (!I->hasOneUse() || !isa<ReturnInst>(I->user_back()))
527 return nullptr;
528
529 return AccInitVal;
530}
531
532namespace {
533class TailRecursionEliminator {
534 Function &F;
535 const TargetTransformInfo *TTI;
536 AliasAnalysis *AA;
537 OptimizationRemarkEmitter *ORE;
538 DomTreeUpdater &DTU;
539 BlockFrequencyInfo *const BFI;
540 ProfileSummaryInfo *const PSI;
541 const bool UpdateFunctionEntryCount;
542 const uint64_t OrigEntryBBFreq;
543 const uint64_t OrigEntryCount;
544
545 // The below are shared state we want to have available when eliminating any
546 // calls in the function. There values should be populated by
547 // createTailRecurseLoopHeader the first time we find a call we can eliminate.
548 BasicBlock *HeaderBB = nullptr;
549 SmallVector<PHINode *, 8> ArgumentPHIs;
550
551 // PHI node to store our return value.
552 PHINode *RetPN = nullptr;
553
554 // i1 PHI node to track if we have a valid return value stored in RetPN.
555 PHINode *RetKnownPN = nullptr;
556
557 // Vector of select instructions we insereted. These selects use RetKnownPN
558 // to either propagate RetPN or select a new return value.
560
561 // The below are shared state needed when performing accumulator recursion.
562 // There values should be populated by insertAccumulator the first time we
563 // find an elimination that requires an accumulator.
564
565 // PHI node to store our current accumulated value.
566 PHINode *AccPN = nullptr;
567
568 // The instruction doing the accumulating.
569 Instruction *AccumulatorRecursionInstr = nullptr;
570
571 Constant *AccumulatorInitialValue = nullptr;
572
573 TailRecursionEliminator(Function &F, const TargetTransformInfo *TTI,
574 AliasAnalysis *AA, OptimizationRemarkEmitter *ORE,
575 DomTreeUpdater &DTU, BlockFrequencyInfo *BFI,
576 ProfileSummaryInfo *PSI,
577 bool UpdateFunctionEntryCount)
578 : F(F), TTI(TTI), AA(AA), ORE(ORE), DTU(DTU), BFI(BFI), PSI(PSI),
579 UpdateFunctionEntryCount(UpdateFunctionEntryCount),
580 OrigEntryBBFreq(
581 BFI ? BFI->getBlockFreq(&F.getEntryBlock()).getFrequency() : 0U),
582 OrigEntryCount(F.getEntryCount() ? *F.getEntryCount() : 0) {
583 if (BFI) {
584 // The assert is meant as API documentation for the caller.
585 assert(OrigEntryBBFreq != 0 &&
586 "If a BFI was provided, the function should have an entry "
587 "basic block with a non-zero frequency.");
588 }
589 }
590
591 CallInst *findTRECandidate(BasicBlock *BB);
592
593 void createTailRecurseLoopHeader(CallInst *CI);
594
595 void insertAccumulator(Instruction *AccRecInstr);
596
597 bool eliminateCall(CallInst *CI);
598
599 void cleanupAndFinalize();
600
601 bool processBlock(BasicBlock &BB);
602
603 void copyByValueOperandIntoLocalTemp(CallInst *CI, int OpndIdx);
604
605 void copyLocalTempOfByValueOperandIntoArguments(CallInst *CI, int OpndIdx);
606
607public:
608 static bool eliminate(Function &F, const TargetTransformInfo *TTI,
609 AliasAnalysis *AA, OptimizationRemarkEmitter *ORE,
610 DomTreeUpdater &DTU, BlockFrequencyInfo *BFI,
611 ProfileSummaryInfo *PSI, bool UpdateFunctionEntryCount);
612};
613} // namespace
614
615CallInst *TailRecursionEliminator::findTRECandidate(BasicBlock *BB) {
616 Instruction *TI = BB->getTerminator();
617
618 if (&BB->front() == TI) // Make sure there is something before the terminator.
619 return nullptr;
620
621 // Scan backwards from the return, checking to see if there is a tail call in
622 // this block. If so, set CI to it.
623 CallInst *CI = nullptr;
624 BasicBlock::iterator BBI(TI);
625 while (true) {
626 CI = dyn_cast<CallInst>(BBI);
627 if (CI && CI->getCalledFunction() == &F)
628 break;
629
630 if (BBI == BB->begin())
631 return nullptr; // Didn't find a potential tail call.
632 --BBI;
633 }
634
635 assert((!CI->isTailCall() || !CI->isNoTailCall()) &&
636 "Incompatible call site attributes(Tail,NoTail)");
637 if (!CI->isTailCall() || shouldDisableTailCallsForCold(CI, &F, PSI, BFI))
638 return nullptr;
639
640 // As a special case, detect code like this:
641 // double fabs(double f) { return __builtin_fabs(f); } // a 'fabs' call
642 // and disable this xform in this case, because the code generator will
643 // lower the call to fabs into inline code.
644 if (BB == &F.getEntryBlock() && &BB->front() == CI &&
645 &*std::next(BB->begin()) == TI && CI->getCalledFunction() &&
647 // A single-block function with just a call and a return. Check that
648 // the arguments match.
649 auto I = CI->arg_begin(), E = CI->arg_end();
650 Function::arg_iterator FI = F.arg_begin(), FE = F.arg_end();
651 for (; I != E && FI != FE; ++I, ++FI)
652 if (*I != &*FI) break;
653 if (I == E && FI == FE)
654 return nullptr;
655 }
656
657 return CI;
658}
659
660void TailRecursionEliminator::createTailRecurseLoopHeader(CallInst *CI) {
661 HeaderBB = &F.getEntryBlock();
662 BasicBlock *NewEntry = BasicBlock::Create(F.getContext(), "", &F, HeaderBB);
663 NewEntry->takeName(HeaderBB);
664 HeaderBB->setName("tailrecurse");
665 auto *BI = UncondBrInst::Create(HeaderBB, NewEntry);
666 BI->setDebugLoc(DebugLoc::getCompilerGenerated());
667 // If the new branch preserves the debug location of CI, it could result in
668 // misleading stepping, if CI is located in a conditional branch.
669 // So, here we don't give any debug location to the new branch.
670
671 // Move all fixed sized allocas from HeaderBB to NewEntry.
672 for (BasicBlock::iterator OEBI = HeaderBB->begin(), E = HeaderBB->end(),
673 NEBI = NewEntry->begin();
674 OEBI != E;)
675 if (AllocaInst *AI = dyn_cast<AllocaInst>(OEBI++))
676 if (isa<ConstantInt>(AI->getArraySize()))
677 AI->moveBefore(NEBI);
678
679 // Now that we have created a new block, which jumps to the entry
680 // block, insert a PHI node for each argument of the function.
681 // For now, we initialize each PHI to only have the real arguments
682 // which are passed in.
683 BasicBlock::iterator InsertPos = HeaderBB->begin();
684 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
685 PHINode *PN = PHINode::Create(I->getType(), 2, I->getName() + ".tr");
686 PN->insertBefore(InsertPos);
687 I->replaceAllUsesWith(PN); // Everyone use the PHI node now!
688 PN->addIncoming(&*I, NewEntry);
689 ArgumentPHIs.push_back(PN);
690 }
691
692 // If the function doen't return void, create the RetPN and RetKnownPN PHI
693 // nodes to track our return value. We initialize RetPN with poison and
694 // RetKnownPN with false since we can't know our return value at function
695 // entry.
696 Type *RetType = F.getReturnType();
697 if (!RetType->isVoidTy()) {
698 Type *BoolType = Type::getInt1Ty(F.getContext());
699 RetPN = PHINode::Create(RetType, 2, "ret.tr");
700 RetPN->insertBefore(InsertPos);
701 RetKnownPN = PHINode::Create(BoolType, 2, "ret.known.tr");
702 RetKnownPN->insertBefore(InsertPos);
703
704 RetPN->addIncoming(PoisonValue::get(RetType), NewEntry);
705 RetKnownPN->addIncoming(ConstantInt::getFalse(BoolType), NewEntry);
706 }
707
708 // The entry block was changed from HeaderBB to NewEntry.
709 // The forward DominatorTree needs to be recalculated when the EntryBB is
710 // changed. In this corner-case we recalculate the entire tree.
711 DTU.recalculate(*NewEntry->getParent());
712}
713
714void TailRecursionEliminator::insertAccumulator(Instruction *AccRecInstr) {
715 assert(!AccPN && "Trying to insert multiple accumulators");
716
717 AccumulatorRecursionInstr = AccRecInstr;
718
719 // Start by inserting a new PHI node for the accumulator.
720 pred_iterator PB = pred_begin(HeaderBB), PE = pred_end(HeaderBB);
721 AccPN = PHINode::Create(F.getReturnType(), std::distance(PB, PE) + 1,
722 "accumulator.tr");
723 AccPN->insertBefore(HeaderBB->begin());
724
725 // Loop over all of the predecessors of the tail recursion block. For the
726 // real entry into the function we seed the PHI with the identity constant for
727 // the accumulation operation. For any other existing branches to this block
728 // (due to other tail recursions eliminated) the accumulator is not modified.
729 // Because we haven't added the branch in the current block to HeaderBB yet,
730 // it will not show up as a predecessor.
731 for (pred_iterator PI = PB; PI != PE; ++PI) {
732 BasicBlock *P = *PI;
733 if (P == &F.getEntryBlock()) {
734 AccPN->addIncoming(AccumulatorInitialValue, P);
735 } else {
736 AccPN->addIncoming(AccPN, P);
737 }
738 }
739
740 ++NumAccumAdded;
741}
742
743// Creates a copy of contents of ByValue operand of the specified
744// call instruction into the newly created temporarily variable.
745void TailRecursionEliminator::copyByValueOperandIntoLocalTemp(CallInst *CI,
746 int OpndIdx) {
747 Type *AggTy = CI->getParamByValType(OpndIdx);
748 assert(AggTy);
749 const DataLayout &DL = F.getDataLayout();
750
751 // Get alignment of byVal operand.
752 Align Alignment(CI->getParamAlign(OpndIdx).valueOrOne());
753
754 // Create alloca for temporarily byval operands.
755 // Put alloca into the entry block.
756 Value *NewAlloca = new AllocaInst(
757 AggTy, DL.getAllocaAddrSpace(), nullptr, Alignment,
758 CI->getArgOperand(OpndIdx)->getName(), F.getEntryBlock().begin());
759
760 IRBuilder<> Builder(CI);
761 Value *Size = Builder.getInt64(DL.getTypeAllocSize(AggTy));
762
763 // Copy data from byvalue operand into the temporarily variable.
764 Builder.CreateMemCpy(NewAlloca, /*DstAlign*/ Alignment,
765 CI->getArgOperand(OpndIdx),
766 /*SrcAlign*/ Alignment, Size);
767 CI->setArgOperand(OpndIdx, NewAlloca);
768}
769
770// Creates a copy from temporarily variable(keeping value of ByVal argument)
771// into the corresponding function argument location.
772void TailRecursionEliminator::copyLocalTempOfByValueOperandIntoArguments(
773 CallInst *CI, int OpndIdx) {
774 Type *AggTy = CI->getParamByValType(OpndIdx);
775 assert(AggTy);
776 const DataLayout &DL = F.getDataLayout();
777
778 // Get alignment of byVal operand.
779 Align Alignment(CI->getParamAlign(OpndIdx).valueOrOne());
780
781 IRBuilder<> Builder(CI);
782 Value *Size = Builder.getInt64(DL.getTypeAllocSize(AggTy));
783
784 // Copy data from the temporarily variable into corresponding
785 // function argument location.
786 Builder.CreateMemCpy(F.getArg(OpndIdx), /*DstAlign*/ Alignment,
787 CI->getArgOperand(OpndIdx),
788 /*SrcAlign*/ Alignment, Size);
789}
790
791bool TailRecursionEliminator::eliminateCall(CallInst *CI) {
792 ReturnInst *Ret = cast<ReturnInst>(CI->getParent()->getTerminator());
793
794 // Ok, we found a potential tail call. We can currently only transform the
795 // tail call if all of the instructions between the call and the return are
796 // movable to above the call itself, leaving the call next to the return.
797 // Check that this is the case now.
798 Instruction *AccRecInstr = nullptr;
799 BasicBlock::iterator BBI(CI);
800 for (++BBI; &*BBI != Ret; ++BBI) {
801 if (canMoveAboveCall(&*BBI, CI, AA))
802 continue;
803
804 // If we can't move the instruction above the call, it might be because it
805 // is an (associative and commutative) or unary accumulator recurrence
806 // arithmetic operation that could be transformed using accumulator
807 // recursion elimination. Check to see if this is the case, and if so,
808 // remember which instruction accumulates for later.
809 Constant *AccInitVal = canTransformAccumulatorRecursion(&*BBI, CI);
810
811 if (AccPN || !AccInitVal)
812 return false; // We cannot eliminate the tail recursion!
813
814 // Yes, this is accumulator recursion. Remember which instruction
815 // accumulates.
816 AccRecInstr = &*BBI;
817
818 // Keep track of the base case (i.e., initial value) of the accumulator
819 // return value if any.
820 AccumulatorInitialValue = AccInitVal;
821 }
822
823 BasicBlock *BB = Ret->getParent();
824
825 using namespace ore;
826 ORE->emit([&]() {
827 return OptimizationRemark(DEBUG_TYPE, "tailcall-recursion", CI)
828 << "transforming tail recursion into loop";
829 });
830
831 // OK! We can transform this tail call. If this is the first one found,
832 // create the new entry block, allowing us to branch back to the old entry.
833 if (!HeaderBB)
834 createTailRecurseLoopHeader(CI);
835
836 // Copy values of ByVal operands into local temporarily variables.
837 for (unsigned I = 0, E = CI->arg_size(); I != E; ++I) {
838 if (CI->isByValArgument(I))
839 copyByValueOperandIntoLocalTemp(CI, I);
840 }
841
842 // Ok, now that we know we have a pseudo-entry block WITH all of the
843 // required PHI nodes, add entries into the PHI node for the actual
844 // parameters passed into the tail-recursive call.
845 for (unsigned I = 0, E = CI->arg_size(); I != E; ++I) {
846 if (CI->isByValArgument(I)) {
847 copyLocalTempOfByValueOperandIntoArguments(CI, I);
848 // When eliminating a tail call, we modify the values of the arguments.
849 // Therefore, if the byval parameter has a readonly attribute, we have to
850 // remove it. It is safe because, from the perspective of a caller, the
851 // byval parameter is always treated as "readonly," even if the readonly
852 // attribute is removed.
853 F.removeParamAttr(I, Attribute::ReadOnly);
854 ArgumentPHIs[I]->addIncoming(F.getArg(I), BB);
855 } else
856 ArgumentPHIs[I]->addIncoming(CI->getArgOperand(I), BB);
857 }
858
859 if (AccRecInstr) {
860 insertAccumulator(AccRecInstr);
861
862 // Rewrite the accumulator recursion instruction so that it does not use
863 // the result of the call anymore, instead, use the PHI node we just
864 // inserted.
865 AccRecInstr->setOperand(AccRecInstr->getOperand(0) != CI, AccPN);
866
867 // Reassociating into the loop reorders the operands, so flags from the
868 // original order (nsw/nuw/exact/...) may no longer hold.
869 AccRecInstr->dropPoisonGeneratingFlags();
870 }
871
872 // Update our return value tracking
873 if (RetPN) {
874 if (Ret->getReturnValue() == CI || AccRecInstr) {
875 // Defer selecting a return value
876 RetPN->addIncoming(RetPN, BB);
877 RetKnownPN->addIncoming(RetKnownPN, BB);
878 } else {
879 // We found a return value we want to use, insert a select instruction to
880 // select it if we don't already know what our return value will be and
881 // store the result in our return value PHI node.
882 SelectInst *SI =
883 SelectInst::Create(RetKnownPN, RetPN, Ret->getReturnValue(),
884 "current.ret.tr", Ret->getIterator());
885 SI->setDebugLoc(Ret->getDebugLoc());
886 RetSelects.push_back(SI);
887
888 RetPN->addIncoming(SI, BB);
889 RetKnownPN->addIncoming(ConstantInt::getTrue(RetKnownPN->getType()), BB);
890 }
891
892 if (AccPN)
893 AccPN->addIncoming(AccRecInstr ? AccRecInstr : AccPN, BB);
894 }
895
896 // Now that all of the PHI nodes are in place, remove the call and
897 // ret instructions, replacing them with an unconditional branch.
898 UncondBrInst *NewBI = UncondBrInst::Create(HeaderBB, Ret->getIterator());
899 NewBI->setDebugLoc(CI->getDebugLoc());
900
901 Ret->eraseFromParent(); // Remove return.
902 CI->eraseFromParent(); // Remove call.
903 DTU.applyUpdates({{DominatorTree::Insert, BB, HeaderBB}});
904 ++NumEliminated;
905 if (!DisableEntryCountRecompute && UpdateFunctionEntryCount &&
906 OrigEntryBBFreq) {
907 assert(F.getEntryCount().has_value());
908 // This pass is not expected to remove BBs, only add an entry BB. For that
909 // reason, and because the BB here isn't the new entry BB, the BFI lookup is
910 // expected to succeed.
911 assert(&F.getEntryBlock() != BB);
912 auto RelativeBBFreq =
913 static_cast<double>(BFI->getBlockFreq(BB).getFrequency()) /
914 static_cast<double>(OrigEntryBBFreq);
915 auto ToSubtract =
916 static_cast<uint64_t>(std::round(RelativeBBFreq * OrigEntryCount));
917 auto OldEntryCount = *F.getEntryCount();
918 if (OldEntryCount <= ToSubtract) {
920 errs() << "[TRE] The entrycount attributable to the recursive call, "
921 << ToSubtract
922 << ", should be strictly lower than the function entry count, "
923 << OldEntryCount << "\n");
924 } else {
925 F.setEntryCount(OldEntryCount - ToSubtract);
926 }
927 }
928 return true;
929}
930
931void TailRecursionEliminator::cleanupAndFinalize() {
932 // If we eliminated any tail recursions, it's possible that we inserted some
933 // silly PHI nodes which just merge an initial value (the incoming operand)
934 // with themselves. Check to see if we did and clean up our mess if so. This
935 // occurs when a function passes an argument straight through to its tail
936 // call.
937 for (PHINode *PN : ArgumentPHIs) {
938 // If the PHI Node is a dynamic constant, replace it with the value it is.
939 if (Value *PNV = simplifyInstruction(PN, F.getDataLayout())) {
940 PN->replaceAllUsesWith(PNV);
941 PN->eraseFromParent();
942 }
943 }
944
945 if (RetPN) {
946 Instruction *AccRecInstr = AccumulatorRecursionInstr;
947 auto MaterializeAccumulator = [&](Value *OtherVal,
948 BasicBlock::iterator InsertPt) {
949 Instruction *New = AccRecInstr->clone();
950 New->setName("accumulator.ret.tr");
951 New->setOperand(AccRecInstr->getOperand(0) == AccPN, OtherVal);
952 New->insertBefore(InsertPt);
953 New->dropLocation();
954 return New;
955 };
956
957 if (RetSelects.empty()) {
958 // If we didn't insert any select instructions, then we know we didn't
959 // store a return value and we can remove the PHI nodes we inserted.
960 RetPN->dropAllReferences();
961 RetPN->eraseFromParent();
962
963 RetKnownPN->dropAllReferences();
964 RetKnownPN->eraseFromParent();
965
966 if (AccPN) {
967 // We need to insert a copy of our accumulator instruction before any
968 // return in the function, and return its result instead.
969 for (BasicBlock &BB : F) {
970 ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator());
971 if (!RI)
972 continue;
973
974 if (isUnaryAccumulatorRecurrence(AccRecInstr)) {
975 // Base-case initialization: the accumulator PHI already holds the
976 // final result, so return it directly.
977 RI->setOperand(0, AccPN);
978 } else {
979 // Since the accumulator starts with the identity value, before the
980 // return we need to apply the accumulation instruction one more
981 // time to combine the last value with the result of the recursive
982 // call.
983 RI->setOperand(0, MaterializeAccumulator(RI->getOperand(0),
984 RI->getIterator()));
985 }
986 }
987 }
988 } else {
989 // We need to insert a select instruction before any return left in the
990 // function to select our stored return value if we have one.
991 for (BasicBlock &BB : F) {
992 ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator());
993 if (!RI)
994 continue;
995
996 SelectInst *SI =
997 SelectInst::Create(RetKnownPN, RetPN, RI->getOperand(0),
998 "current.ret.tr", RI->getIterator());
999 SI->setDebugLoc(DebugLoc::getCompilerGenerated());
1000 RetSelects.push_back(SI);
1001 RI->setOperand(0, SI);
1002 }
1003
1004 if (AccPN) {
1005 // We need to insert a copy of our accumulator instruction before any
1006 // of the selects we inserted, and select its result instead.
1007 for (SelectInst *SI : RetSelects) {
1008 if (isUnaryAccumulatorRecurrence(AccRecInstr)) {
1009 SI->setFalseValue(AccPN);
1010 } else {
1011 SI->setFalseValue(
1012 MaterializeAccumulator(SI->getFalseValue(), SI->getIterator()));
1013 }
1014 }
1015 }
1016 }
1017 }
1018}
1019
1020bool TailRecursionEliminator::processBlock(BasicBlock &BB) {
1021 Instruction *TI = BB.getTerminator();
1022
1023 if (UncondBrInst *BI = dyn_cast<UncondBrInst>(TI)) {
1024 BasicBlock *Succ = BI->getSuccessor();
1025 ReturnInst *Ret = dyn_cast<ReturnInst>(Succ->getFirstNonPHIOrDbg(true));
1026
1027 if (!Ret)
1028 return false;
1029
1030 CallInst *CI = findTRECandidate(&BB);
1031
1032 if (!CI)
1033 return false;
1034
1035 LLVM_DEBUG(dbgs() << "FOLDING: " << *Succ
1036 << "INTO UNCOND BRANCH PRED: " << BB);
1037 FoldReturnIntoUncondBranch(Ret, Succ, &BB, &DTU);
1038 ++NumRetDuped;
1039
1040 // If all predecessors of Succ have been eliminated by
1041 // FoldReturnIntoUncondBranch, delete it. It is important to empty it,
1042 // because the ret instruction in there is still using a value which
1043 // eliminateCall will attempt to remove. This block can only contain
1044 // instructions that can't have uses, therefore it is safe to remove.
1045 if (pred_empty(Succ))
1046 DTU.deleteBB(Succ);
1047
1048 eliminateCall(CI);
1049 return true;
1050 }
1051
1052 if (isa<ReturnInst>(TI)) {
1053 CallInst *CI = findTRECandidate(&BB);
1054
1055 if (CI)
1056 return eliminateCall(CI);
1057 }
1058
1059 return false;
1060}
1061
1062bool TailRecursionEliminator::eliminate(
1063 Function &F, const TargetTransformInfo *TTI, AliasAnalysis *AA,
1064 OptimizationRemarkEmitter *ORE, DomTreeUpdater &DTU,
1065 BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
1066 bool UpdateFunctionEntryCount) {
1067 if (F.getFnAttribute("disable-tail-calls").getValueAsBool())
1068 return false;
1069
1070 bool MadeChange = false;
1071 MadeChange |= markTails(F, ORE, PSI, BFI);
1072
1073 // If this function is a varargs function, we won't be able to PHI the args
1074 // right, so don't even try to convert it...
1075 if (F.getFunctionType()->isVarArg())
1076 return MadeChange;
1077
1078 if (!canTRE(F))
1079 return MadeChange;
1080
1081 // Change any tail recursive calls to loops.
1082 TailRecursionEliminator TRE(F, TTI, AA, ORE, DTU, BFI, PSI,
1083 UpdateFunctionEntryCount);
1084
1085 for (BasicBlock &BB : F)
1086 MadeChange |= TRE.processBlock(BB);
1087
1088 TRE.cleanupAndFinalize();
1089
1090 return MadeChange;
1091}
1092
1093namespace {
1094struct TailCallElim : public FunctionPass {
1095 static char ID; // Pass identification, replacement for typeid
1096 TailCallElim() : FunctionPass(ID) {
1098 }
1099
1100 void getAnalysisUsage(AnalysisUsage &AU) const override {
1101 AU.addRequired<TargetTransformInfoWrapperPass>();
1102 AU.addRequired<AAResultsWrapperPass>();
1103 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
1104 AU.addPreserved<GlobalsAAWrapperPass>();
1105 AU.addPreserved<DominatorTreeWrapperPass>();
1106 AU.addPreserved<PostDominatorTreeWrapperPass>();
1107 }
1108
1109 bool runOnFunction(Function &F) override {
1110 if (skipFunction(F))
1111 return false;
1112
1113 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1114 auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
1115 auto *PDTWP = getAnalysisIfAvailable<PostDominatorTreeWrapperPass>();
1116 auto *PDT = PDTWP ? &PDTWP->getPostDomTree() : nullptr;
1117 // There is no noticable performance difference here between Lazy and Eager
1118 // UpdateStrategy based on some test results. It is feasible to switch the
1119 // UpdateStrategy to Lazy if we find it profitable later.
1120 DomTreeUpdater DTU(DT, PDT, DomTreeUpdater::UpdateStrategy::Eager);
1121
1122 return TailRecursionEliminator::eliminate(
1123 F, &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F),
1124 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
1125 &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(), DTU,
1126 /*BFI=*/nullptr, /*PSI=*/nullptr, /*UpdateFunctionEntryCount=*/false);
1127 }
1128};
1129} // namespace
1130
1131char TailCallElim::ID = 0;
1132INITIALIZE_PASS_BEGIN(TailCallElim, "tailcallelim", "Tail Call Elimination",
1133 false, false)
1136INITIALIZE_PASS_END(TailCallElim, "tailcallelim", "Tail Call Elimination",
1138
1139// Public interface to the TailCallElimination pass
1141 return new TailCallElim();
1142}
1143
1146
1149 // This must come first. It needs the 2 analyses, meaning, if it came after
1150 // the lines asking for the cached result, should they be nullptr (which, in
1151 // the case of the PDT, is likely), updates to the trees would be missed.
1152 auto *BFI = F.getEntryCount().has_value()
1154 : nullptr;
1155 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
1156 auto *PSI = MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
1158 auto *DT = AM.getCachedResult<DominatorTreeAnalysis>(F);
1160 // There is no noticable performance difference here between Lazy and Eager
1161 // UpdateStrategy based on some test results. It is feasible to switch the
1162 // UpdateStrategy to Lazy if we find it profitable later.
1163 DomTreeUpdater DTU(DT, PDT, DomTreeUpdater::UpdateStrategy::Eager);
1164 bool Changed = TailRecursionEliminator::eliminate(
1165 F, &TTI, &AA, &ORE, DTU, BFI, PSI, UpdateFunctionEntryCount);
1166
1167 if (!Changed)
1168 return PreservedAnalyses::all();
1172 return PA;
1173}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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 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 Constant * findBaseCaseRetConstant(Function &F, Instruction *AccRecInstr)
static Constant * canTransformAccumulatorRecursion(Instruction *I, CallInst *CI)
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.
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 const Function * getFunction() const
Return the function this instruction belongs to.
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.
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
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
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:81
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:1739
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.
bool isModSet(const ModRefInfo MRI)
Definition ModRef.h:49
LLVM_ABI bool isSafeToLoadUnconditionally(Value *V, Align Alignment, const APInt &Size, const DataLayout &DL, Instruction *ScanFrom, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr)
Return true if we know that executing a load from this value cannot trap.
Definition Loads.cpp:449
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
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
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
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
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
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