1 //===- DeadArgumentElimination.cpp - Eliminate dead arguments -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass deletes dead arguments from internal functions. Dead argument
11 // elimination removes arguments which are directly dead, as well as arguments
12 // only passed into function calls as dead arguments of other functions. This
13 // pass also deletes dead return values in a similar way.
15 // This pass is often useful as a cleanup pass to run after aggressive
16 // interprocedural passes, which add possibly-dead arguments or return values.
18 //===----------------------------------------------------------------------===//
20 #include "llvm/Transforms/IPO/DeadArgumentElimination.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/IR/Argument.h"
24 #include "llvm/IR/Attributes.h"
25 #include "llvm/IR/BasicBlock.h"
26 #include "llvm/IR/CallSite.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/InstrTypes.h"
31 #include "llvm/IR/Instruction.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/Intrinsics.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/PassManager.h"
37 #include "llvm/IR/Type.h"
38 #include "llvm/IR/Use.h"
39 #include "llvm/IR/User.h"
40 #include "llvm/IR/Value.h"
41 #include "llvm/Pass.h"
42 #include "llvm/Support/Casting.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Transforms/IPO.h"
46 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
54 #define DEBUG_TYPE "deadargelim"
56 STATISTIC(NumArgumentsEliminated, "Number of unread args removed");
57 STATISTIC(NumRetValsEliminated , "Number of unused return values removed");
58 STATISTIC(NumArgumentsReplacedWithUndef,
59 "Number of unread args replaced with undef");
63 /// DAE - The dead argument elimination pass.
64 class DAE : public ModulePass {
66 // DAH uses this to specify a different ID.
67 explicit DAE(char &ID) : ModulePass(ID) {}
70 static char ID; // Pass identification, replacement for typeid
72 DAE() : ModulePass(ID) {
73 initializeDAEPass(*PassRegistry::getPassRegistry());
76 bool runOnModule(Module &M) override {
79 DeadArgumentEliminationPass DAEP(ShouldHackArguments());
80 ModuleAnalysisManager DummyMAM;
81 PreservedAnalyses PA = DAEP.run(M, DummyMAM);
82 return !PA.areAllPreserved();
85 virtual bool ShouldHackArguments() const { return false; }
88 } // end anonymous namespace
92 INITIALIZE_PASS(DAE, "deadargelim", "Dead Argument Elimination", false, false)
96 /// DAH - DeadArgumentHacking pass - Same as dead argument elimination, but
97 /// deletes arguments to functions which are external. This is only for use
99 struct DAH : public DAE {
104 bool ShouldHackArguments() const override { return true; }
107 } // end anonymous namespace
111 INITIALIZE_PASS(DAH, "deadarghaX0r",
112 "Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)",
115 /// createDeadArgEliminationPass - This pass removes arguments from functions
116 /// which are not used by the body of the function.
117 ModulePass *llvm::createDeadArgEliminationPass() { return new DAE(); }
119 ModulePass *llvm::createDeadArgHackingPass() { return new DAH(); }
121 /// DeleteDeadVarargs - If this is an function that takes a ... list, and if
122 /// llvm.vastart is never called, the varargs list is dead for the function.
123 bool DeadArgumentEliminationPass::DeleteDeadVarargs(Function &Fn) {
124 assert(Fn.getFunctionType()->isVarArg() && "Function isn't varargs!");
125 if (Fn.isDeclaration() || !Fn.hasLocalLinkage()) return false;
127 // Ensure that the function is only directly called.
128 if (Fn.hasAddressTaken())
131 // Don't touch naked functions. The assembly might be using an argument, or
132 // otherwise rely on the frame layout in a way that this analysis will not
134 if (Fn.hasFnAttribute(Attribute::Naked)) {
138 // Okay, we know we can transform this function if safe. Scan its body
139 // looking for calls marked musttail or calls to llvm.vastart.
140 for (BasicBlock &BB : Fn) {
141 for (Instruction &I : BB) {
142 CallInst *CI = dyn_cast<CallInst>(&I);
145 if (CI->isMustTailCall())
147 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
148 if (II->getIntrinsicID() == Intrinsic::vastart)
154 // If we get here, there are no calls to llvm.vastart in the function body,
155 // remove the "..." and adjust all the calls.
157 // Start by computing a new prototype for the function, which is the same as
158 // the old function, but doesn't have isVarArg set.
159 FunctionType *FTy = Fn.getFunctionType();
161 std::vector<Type *> Params(FTy->param_begin(), FTy->param_end());
162 FunctionType *NFTy = FunctionType::get(FTy->getReturnType(),
164 unsigned NumArgs = Params.size();
166 // Create the new function body and insert it into the module...
167 Function *NF = Function::Create(NFTy, Fn.getLinkage(), Fn.getAddressSpace());
168 NF->copyAttributesFrom(&Fn);
169 NF->setComdat(Fn.getComdat());
170 Fn.getParent()->getFunctionList().insert(Fn.getIterator(), NF);
173 // Loop over all of the callers of the function, transforming the call sites
174 // to pass in a smaller number of arguments into the new function.
176 std::vector<Value *> Args;
177 for (Value::user_iterator I = Fn.user_begin(), E = Fn.user_end(); I != E; ) {
181 Instruction *Call = CS.getInstruction();
183 // Pass all the same arguments.
184 Args.assign(CS.arg_begin(), CS.arg_begin() + NumArgs);
186 // Drop any attributes that were on the vararg arguments.
187 AttributeList PAL = CS.getAttributes();
188 if (!PAL.isEmpty()) {
189 SmallVector<AttributeSet, 8> ArgAttrs;
190 for (unsigned ArgNo = 0; ArgNo < NumArgs; ++ArgNo)
191 ArgAttrs.push_back(PAL.getParamAttributes(ArgNo));
192 PAL = AttributeList::get(Fn.getContext(), PAL.getFnAttributes(),
193 PAL.getRetAttributes(), ArgAttrs);
196 SmallVector<OperandBundleDef, 1> OpBundles;
197 CS.getOperandBundlesAsDefs(OpBundles);
200 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
201 NewCS = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
202 Args, OpBundles, "", Call);
204 NewCS = CallInst::Create(NF, Args, OpBundles, "", Call);
205 cast<CallInst>(NewCS.getInstruction())
206 ->setTailCallKind(cast<CallInst>(Call)->getTailCallKind());
208 NewCS.setCallingConv(CS.getCallingConv());
209 NewCS.setAttributes(PAL);
210 NewCS->setDebugLoc(Call->getDebugLoc());
212 if (Call->extractProfTotalWeight(W))
213 NewCS->setProfWeight(W);
217 if (!Call->use_empty())
218 Call->replaceAllUsesWith(NewCS.getInstruction());
220 NewCS->takeName(Call);
222 // Finally, remove the old call from the program, reducing the use-count of
224 Call->eraseFromParent();
227 // Since we have now created the new function, splice the body of the old
228 // function right into the new function, leaving the old rotting hulk of the
230 NF->getBasicBlockList().splice(NF->begin(), Fn.getBasicBlockList());
232 // Loop over the argument list, transferring uses of the old arguments over to
233 // the new arguments, also transferring over the names as well. While we're at
234 // it, remove the dead arguments from the DeadArguments list.
235 for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(),
236 I2 = NF->arg_begin(); I != E; ++I, ++I2) {
237 // Move the name and users over to the new version.
238 I->replaceAllUsesWith(&*I2);
242 // Clone metadatas from the old function, including debug info descriptor.
243 SmallVector<std::pair<unsigned, MDNode *>, 1> MDs;
244 Fn.getAllMetadata(MDs);
246 NF->addMetadata(MD.first, *MD.second);
248 // Fix up any BlockAddresses that refer to the function.
249 Fn.replaceAllUsesWith(ConstantExpr::getBitCast(NF, Fn.getType()));
250 // Delete the bitcast that we just created, so that NF does not
251 // appear to be address-taken.
252 NF->removeDeadConstantUsers();
253 // Finally, nuke the old function.
254 Fn.eraseFromParent();
258 /// RemoveDeadArgumentsFromCallers - Checks if the given function has any
259 /// arguments that are unused, and changes the caller parameters to be undefined
261 bool DeadArgumentEliminationPass::RemoveDeadArgumentsFromCallers(Function &Fn) {
262 // We cannot change the arguments if this TU does not define the function or
263 // if the linker may choose a function body from another TU, even if the
264 // nominal linkage indicates that other copies of the function have the same
265 // semantics. In the below example, the dead load from %p may not have been
266 // eliminated from the linker-chosen copy of f, so replacing %p with undef
267 // in callers may introduce undefined behavior.
269 // define linkonce_odr void @f(i32* %p) {
273 if (!Fn.hasExactDefinition())
276 // Functions with local linkage should already have been handled, except the
277 // fragile (variadic) ones which we can improve here.
278 if (Fn.hasLocalLinkage() && !Fn.getFunctionType()->isVarArg())
281 // Don't touch naked functions. The assembly might be using an argument, or
282 // otherwise rely on the frame layout in a way that this analysis will not
284 if (Fn.hasFnAttribute(Attribute::Naked))
290 SmallVector<unsigned, 8> UnusedArgs;
291 bool Changed = false;
293 for (Argument &Arg : Fn.args()) {
294 if (!Arg.hasSwiftErrorAttr() && Arg.use_empty() && !Arg.hasByValOrInAllocaAttr()) {
295 if (Arg.isUsedByMetadata()) {
296 Arg.replaceAllUsesWith(UndefValue::get(Arg.getType()));
299 UnusedArgs.push_back(Arg.getArgNo());
303 if (UnusedArgs.empty())
306 for (Use &U : Fn.uses()) {
307 CallSite CS(U.getUser());
308 if (!CS || !CS.isCallee(&U))
311 // Now go through all unused args and replace them with "undef".
312 for (unsigned I = 0, E = UnusedArgs.size(); I != E; ++I) {
313 unsigned ArgNo = UnusedArgs[I];
315 Value *Arg = CS.getArgument(ArgNo);
316 CS.setArgument(ArgNo, UndefValue::get(Arg->getType()));
317 ++NumArgumentsReplacedWithUndef;
325 /// Convenience function that returns the number of return values. It returns 0
326 /// for void functions and 1 for functions not returning a struct. It returns
327 /// the number of struct elements for functions returning a struct.
328 static unsigned NumRetVals(const Function *F) {
329 Type *RetTy = F->getReturnType();
330 if (RetTy->isVoidTy())
332 else if (StructType *STy = dyn_cast<StructType>(RetTy))
333 return STy->getNumElements();
334 else if (ArrayType *ATy = dyn_cast<ArrayType>(RetTy))
335 return ATy->getNumElements();
340 /// Returns the sub-type a function will return at a given Idx. Should
341 /// correspond to the result type of an ExtractValue instruction executed with
342 /// just that one Idx (i.e. only top-level structure is considered).
343 static Type *getRetComponentType(const Function *F, unsigned Idx) {
344 Type *RetTy = F->getReturnType();
345 assert(!RetTy->isVoidTy() && "void type has no subtype");
347 if (StructType *STy = dyn_cast<StructType>(RetTy))
348 return STy->getElementType(Idx);
349 else if (ArrayType *ATy = dyn_cast<ArrayType>(RetTy))
350 return ATy->getElementType();
355 /// MarkIfNotLive - This checks Use for liveness in LiveValues. If Use is not
356 /// live, it adds Use to the MaybeLiveUses argument. Returns the determined
358 DeadArgumentEliminationPass::Liveness
359 DeadArgumentEliminationPass::MarkIfNotLive(RetOrArg Use,
360 UseVector &MaybeLiveUses) {
361 // We're live if our use or its Function is already marked as live.
362 if (LiveFunctions.count(Use.F) || LiveValues.count(Use))
365 // We're maybe live otherwise, but remember that we must become live if
367 MaybeLiveUses.push_back(Use);
371 /// SurveyUse - This looks at a single use of an argument or return value
372 /// and determines if it should be alive or not. Adds this use to MaybeLiveUses
373 /// if it causes the used value to become MaybeLive.
375 /// RetValNum is the return value number to use when this use is used in a
376 /// return instruction. This is used in the recursion, you should always leave
378 DeadArgumentEliminationPass::Liveness
379 DeadArgumentEliminationPass::SurveyUse(const Use *U, UseVector &MaybeLiveUses,
380 unsigned RetValNum) {
381 const User *V = U->getUser();
382 if (const ReturnInst *RI = dyn_cast<ReturnInst>(V)) {
383 // The value is returned from a function. It's only live when the
384 // function's return value is live. We use RetValNum here, for the case
385 // that U is really a use of an insertvalue instruction that uses the
387 const Function *F = RI->getParent()->getParent();
388 if (RetValNum != -1U) {
389 RetOrArg Use = CreateRet(F, RetValNum);
390 // We might be live, depending on the liveness of Use.
391 return MarkIfNotLive(Use, MaybeLiveUses);
393 DeadArgumentEliminationPass::Liveness Result = MaybeLive;
394 for (unsigned i = 0; i < NumRetVals(F); ++i) {
395 RetOrArg Use = CreateRet(F, i);
396 // We might be live, depending on the liveness of Use. If any
397 // sub-value is live, then the entire value is considered live. This
398 // is a conservative choice, and better tracking is possible.
399 DeadArgumentEliminationPass::Liveness SubResult =
400 MarkIfNotLive(Use, MaybeLiveUses);
407 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(V)) {
408 if (U->getOperandNo() != InsertValueInst::getAggregateOperandIndex()
410 // The use we are examining is inserted into an aggregate. Our liveness
411 // depends on all uses of that aggregate, but if it is used as a return
412 // value, only index at which we were inserted counts.
413 RetValNum = *IV->idx_begin();
415 // Note that if we are used as the aggregate operand to the insertvalue,
416 // we don't change RetValNum, but do survey all our uses.
418 Liveness Result = MaybeLive;
419 for (const Use &UU : IV->uses()) {
420 Result = SurveyUse(&UU, MaybeLiveUses, RetValNum);
427 if (auto CS = ImmutableCallSite(V)) {
428 const Function *F = CS.getCalledFunction();
430 // Used in a direct call.
432 // The function argument is live if it is used as a bundle operand.
433 if (CS.isBundleOperand(U))
436 // Find the argument number. We know for sure that this use is an
437 // argument, since if it was the function argument this would be an
438 // indirect call and the we know can't be looking at a value of the
439 // label type (for the invoke instruction).
440 unsigned ArgNo = CS.getArgumentNo(U);
442 if (ArgNo >= F->getFunctionType()->getNumParams())
443 // The value is passed in through a vararg! Must be live.
446 assert(CS.getArgument(ArgNo)
447 == CS->getOperand(U->getOperandNo())
448 && "Argument is not where we expected it");
450 // Value passed to a normal call. It's only live when the corresponding
451 // argument to the called function turns out live.
452 RetOrArg Use = CreateArg(F, ArgNo);
453 return MarkIfNotLive(Use, MaybeLiveUses);
456 // Used in any other way? Value must be live.
460 /// SurveyUses - This looks at all the uses of the given value
461 /// Returns the Liveness deduced from the uses of this value.
463 /// Adds all uses that cause the result to be MaybeLive to MaybeLiveRetUses. If
464 /// the result is Live, MaybeLiveUses might be modified but its content should
465 /// be ignored (since it might not be complete).
466 DeadArgumentEliminationPass::Liveness
467 DeadArgumentEliminationPass::SurveyUses(const Value *V,
468 UseVector &MaybeLiveUses) {
469 // Assume it's dead (which will only hold if there are no uses at all..).
470 Liveness Result = MaybeLive;
472 for (const Use &U : V->uses()) {
473 Result = SurveyUse(&U, MaybeLiveUses);
480 // SurveyFunction - This performs the initial survey of the specified function,
481 // checking out whether or not it uses any of its incoming arguments or whether
482 // any callers use the return value. This fills in the LiveValues set and Uses
485 // We consider arguments of non-internal functions to be intrinsically alive as
486 // well as arguments to functions which have their "address taken".
487 void DeadArgumentEliminationPass::SurveyFunction(const Function &F) {
488 // Functions with inalloca parameters are expecting args in a particular
489 // register and memory layout.
490 if (F.getAttributes().hasAttrSomewhere(Attribute::InAlloca)) {
495 // Don't touch naked functions. The assembly might be using an argument, or
496 // otherwise rely on the frame layout in a way that this analysis will not
498 if (F.hasFnAttribute(Attribute::Naked)) {
503 unsigned RetCount = NumRetVals(&F);
505 // Assume all return values are dead
506 using RetVals = SmallVector<Liveness, 5>;
508 RetVals RetValLiveness(RetCount, MaybeLive);
510 using RetUses = SmallVector<UseVector, 5>;
512 // These vectors map each return value to the uses that make it MaybeLive, so
513 // we can add those to the Uses map if the return value really turns out to be
514 // MaybeLive. Initialized to a list of RetCount empty lists.
515 RetUses MaybeLiveRetUses(RetCount);
517 bool HasMustTailCalls = false;
519 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
520 if (const ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
521 if (RI->getNumOperands() != 0 && RI->getOperand(0)->getType()
522 != F.getFunctionType()->getReturnType()) {
523 // We don't support old style multiple return values.
529 // If we have any returns of `musttail` results - the signature can't
531 if (BB->getTerminatingMustTailCall() != nullptr)
532 HasMustTailCalls = true;
535 if (HasMustTailCalls) {
536 LLVM_DEBUG(dbgs() << "DeadArgumentEliminationPass - " << F.getName()
537 << " has musttail calls\n");
540 if (!F.hasLocalLinkage() && (!ShouldHackArguments || F.isIntrinsic())) {
546 dbgs() << "DeadArgumentEliminationPass - Inspecting callers for fn: "
547 << F.getName() << "\n");
548 // Keep track of the number of live retvals, so we can skip checks once all
549 // of them turn out to be live.
550 unsigned NumLiveRetVals = 0;
552 bool HasMustTailCallers = false;
554 // Loop all uses of the function.
555 for (const Use &U : F.uses()) {
556 // If the function is PASSED IN as an argument, its address has been
558 ImmutableCallSite CS(U.getUser());
559 if (!CS || !CS.isCallee(&U)) {
564 // The number of arguments for `musttail` call must match the number of
565 // arguments of the caller
566 if (CS.isMustTailCall())
567 HasMustTailCallers = true;
569 // If this use is anything other than a call site, the function is alive.
570 const Instruction *TheCall = CS.getInstruction();
571 if (!TheCall) { // Not a direct call site?
576 // If we end up here, we are looking at a direct call to our function.
578 // Now, check how our return value(s) is/are used in this caller. Don't
579 // bother checking return values if all of them are live already.
580 if (NumLiveRetVals == RetCount)
583 // Check all uses of the return value.
584 for (const Use &U : TheCall->uses()) {
585 if (ExtractValueInst *Ext = dyn_cast<ExtractValueInst>(U.getUser())) {
586 // This use uses a part of our return value, survey the uses of
587 // that part and store the results for this index only.
588 unsigned Idx = *Ext->idx_begin();
589 if (RetValLiveness[Idx] != Live) {
590 RetValLiveness[Idx] = SurveyUses(Ext, MaybeLiveRetUses[Idx]);
591 if (RetValLiveness[Idx] == Live)
595 // Used by something else than extractvalue. Survey, but assume that the
596 // result applies to all sub-values.
597 UseVector MaybeLiveAggregateUses;
598 if (SurveyUse(&U, MaybeLiveAggregateUses) == Live) {
599 NumLiveRetVals = RetCount;
600 RetValLiveness.assign(RetCount, Live);
603 for (unsigned i = 0; i != RetCount; ++i) {
604 if (RetValLiveness[i] != Live)
605 MaybeLiveRetUses[i].append(MaybeLiveAggregateUses.begin(),
606 MaybeLiveAggregateUses.end());
613 if (HasMustTailCallers) {
614 LLVM_DEBUG(dbgs() << "DeadArgumentEliminationPass - " << F.getName()
615 << " has musttail callers\n");
618 // Now we've inspected all callers, record the liveness of our return values.
619 for (unsigned i = 0; i != RetCount; ++i)
620 MarkValue(CreateRet(&F, i), RetValLiveness[i], MaybeLiveRetUses[i]);
622 LLVM_DEBUG(dbgs() << "DeadArgumentEliminationPass - Inspecting args for fn: "
623 << F.getName() << "\n");
625 // Now, check all of our arguments.
627 UseVector MaybeLiveArgUses;
628 for (Function::const_arg_iterator AI = F.arg_begin(),
629 E = F.arg_end(); AI != E; ++AI, ++i) {
631 if (F.getFunctionType()->isVarArg() || HasMustTailCallers ||
633 // Variadic functions will already have a va_arg function expanded inside
634 // them, making them potentially very sensitive to ABI changes resulting
635 // from removing arguments entirely, so don't. For example AArch64 handles
636 // register and stack HFAs very differently, and this is reflected in the
637 // IR which has already been generated.
639 // `musttail` calls to this function restrict argument removal attempts.
640 // The signature of the caller must match the signature of the function.
642 // `musttail` calls in this function prevents us from changing its
646 // See what the effect of this use is (recording any uses that cause
647 // MaybeLive in MaybeLiveArgUses).
648 Result = SurveyUses(&*AI, MaybeLiveArgUses);
652 MarkValue(CreateArg(&F, i), Result, MaybeLiveArgUses);
653 // Clear the vector again for the next iteration.
654 MaybeLiveArgUses.clear();
658 /// MarkValue - This function marks the liveness of RA depending on L. If L is
659 /// MaybeLive, it also takes all uses in MaybeLiveUses and records them in Uses,
660 /// such that RA will be marked live if any use in MaybeLiveUses gets marked
662 void DeadArgumentEliminationPass::MarkValue(const RetOrArg &RA, Liveness L,
663 const UseVector &MaybeLiveUses) {
669 // Note any uses of this value, so this return value can be
670 // marked live whenever one of the uses becomes live.
671 for (const auto &MaybeLiveUse : MaybeLiveUses)
672 Uses.insert(std::make_pair(MaybeLiveUse, RA));
677 /// MarkLive - Mark the given Function as alive, meaning that it cannot be
678 /// changed in any way. Additionally,
679 /// mark any values that are used as this function's parameters or by its return
680 /// values (according to Uses) live as well.
681 void DeadArgumentEliminationPass::MarkLive(const Function &F) {
682 LLVM_DEBUG(dbgs() << "DeadArgumentEliminationPass - Intrinsically live fn: "
683 << F.getName() << "\n");
684 // Mark the function as live.
685 LiveFunctions.insert(&F);
686 // Mark all arguments as live.
687 for (unsigned i = 0, e = F.arg_size(); i != e; ++i)
688 PropagateLiveness(CreateArg(&F, i));
689 // Mark all return values as live.
690 for (unsigned i = 0, e = NumRetVals(&F); i != e; ++i)
691 PropagateLiveness(CreateRet(&F, i));
694 /// MarkLive - Mark the given return value or argument as live. Additionally,
695 /// mark any values that are used by this value (according to Uses) live as
697 void DeadArgumentEliminationPass::MarkLive(const RetOrArg &RA) {
698 if (LiveFunctions.count(RA.F))
699 return; // Function was already marked Live.
701 if (!LiveValues.insert(RA).second)
702 return; // We were already marked Live.
704 LLVM_DEBUG(dbgs() << "DeadArgumentEliminationPass - Marking "
705 << RA.getDescription() << " live\n");
706 PropagateLiveness(RA);
709 /// PropagateLiveness - Given that RA is a live value, propagate it's liveness
710 /// to any other values it uses (according to Uses).
711 void DeadArgumentEliminationPass::PropagateLiveness(const RetOrArg &RA) {
712 // We don't use upper_bound (or equal_range) here, because our recursive call
713 // to ourselves is likely to cause the upper_bound (which is the first value
714 // not belonging to RA) to become erased and the iterator invalidated.
715 UseMap::iterator Begin = Uses.lower_bound(RA);
716 UseMap::iterator E = Uses.end();
718 for (I = Begin; I != E && I->first == RA; ++I)
721 // Erase RA from the Uses map (from the lower bound to wherever we ended up
723 Uses.erase(Begin, I);
726 // RemoveDeadStuffFromFunction - Remove any arguments and return values from F
727 // that are not in LiveValues. Transform the function and all of the callees of
728 // the function to not have these arguments and return values.
730 bool DeadArgumentEliminationPass::RemoveDeadStuffFromFunction(Function *F) {
731 // Don't modify fully live functions
732 if (LiveFunctions.count(F))
735 // Start by computing a new prototype for the function, which is the same as
736 // the old function, but has fewer arguments and a different return type.
737 FunctionType *FTy = F->getFunctionType();
738 std::vector<Type*> Params;
740 // Keep track of if we have a live 'returned' argument
741 bool HasLiveReturnedArg = false;
743 // Set up to build a new list of parameter attributes.
744 SmallVector<AttributeSet, 8> ArgAttrVec;
745 const AttributeList &PAL = F->getAttributes();
747 // Remember which arguments are still alive.
748 SmallVector<bool, 10> ArgAlive(FTy->getNumParams(), false);
749 // Construct the new parameter list from non-dead arguments. Also construct
750 // a new set of parameter attributes to correspond. Skip the first parameter
751 // attribute, since that belongs to the return value.
753 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
755 RetOrArg Arg = CreateArg(F, i);
756 if (LiveValues.erase(Arg)) {
757 Params.push_back(I->getType());
759 ArgAttrVec.push_back(PAL.getParamAttributes(i));
760 HasLiveReturnedArg |= PAL.hasParamAttribute(i, Attribute::Returned);
762 ++NumArgumentsEliminated;
763 LLVM_DEBUG(dbgs() << "DeadArgumentEliminationPass - Removing argument "
764 << i << " (" << I->getName() << ") from "
765 << F->getName() << "\n");
769 // Find out the new return value.
770 Type *RetTy = FTy->getReturnType();
771 Type *NRetTy = nullptr;
772 unsigned RetCount = NumRetVals(F);
774 // -1 means unused, other numbers are the new index
775 SmallVector<int, 5> NewRetIdxs(RetCount, -1);
776 std::vector<Type*> RetTypes;
778 // If there is a function with a live 'returned' argument but a dead return
779 // value, then there are two possible actions:
780 // 1) Eliminate the return value and take off the 'returned' attribute on the
782 // 2) Retain the 'returned' attribute and treat the return value (but not the
783 // entire function) as live so that it is not eliminated.
785 // It's not clear in the general case which option is more profitable because,
786 // even in the absence of explicit uses of the return value, code generation
787 // is free to use the 'returned' attribute to do things like eliding
788 // save/restores of registers across calls. Whether or not this happens is
789 // target and ABI-specific as well as depending on the amount of register
790 // pressure, so there's no good way for an IR-level pass to figure this out.
792 // Fortunately, the only places where 'returned' is currently generated by
793 // the FE are places where 'returned' is basically free and almost always a
794 // performance win, so the second option can just be used always for now.
796 // This should be revisited if 'returned' is ever applied more liberally.
797 if (RetTy->isVoidTy() || HasLiveReturnedArg) {
800 // Look at each of the original return values individually.
801 for (unsigned i = 0; i != RetCount; ++i) {
802 RetOrArg Ret = CreateRet(F, i);
803 if (LiveValues.erase(Ret)) {
804 RetTypes.push_back(getRetComponentType(F, i));
805 NewRetIdxs[i] = RetTypes.size() - 1;
807 ++NumRetValsEliminated;
809 dbgs() << "DeadArgumentEliminationPass - Removing return value "
810 << i << " from " << F->getName() << "\n");
813 if (RetTypes.size() > 1) {
814 // More than one return type? Reduce it down to size.
815 if (StructType *STy = dyn_cast<StructType>(RetTy)) {
816 // Make the new struct packed if we used to return a packed struct
818 NRetTy = StructType::get(STy->getContext(), RetTypes, STy->isPacked());
820 assert(isa<ArrayType>(RetTy) && "unexpected multi-value return");
821 NRetTy = ArrayType::get(RetTypes[0], RetTypes.size());
823 } else if (RetTypes.size() == 1)
824 // One return type? Just a simple value then, but only if we didn't use to
825 // return a struct with that simple value before.
826 NRetTy = RetTypes.front();
827 else if (RetTypes.empty())
828 // No return types? Make it void, but only if we didn't use to return {}.
829 NRetTy = Type::getVoidTy(F->getContext());
832 assert(NRetTy && "No new return type found?");
834 // The existing function return attributes.
835 AttrBuilder RAttrs(PAL.getRetAttributes());
837 // Remove any incompatible attributes, but only if we removed all return
838 // values. Otherwise, ensure that we don't have any conflicting attributes
839 // here. Currently, this should not be possible, but special handling might be
840 // required when new return value attributes are added.
841 if (NRetTy->isVoidTy())
842 RAttrs.remove(AttributeFuncs::typeIncompatible(NRetTy));
844 assert(!RAttrs.overlaps(AttributeFuncs::typeIncompatible(NRetTy)) &&
845 "Return attributes no longer compatible?");
847 AttributeSet RetAttrs = AttributeSet::get(F->getContext(), RAttrs);
849 // Strip allocsize attributes. They might refer to the deleted arguments.
850 AttributeSet FnAttrs = PAL.getFnAttributes().removeAttribute(
851 F->getContext(), Attribute::AllocSize);
853 // Reconstruct the AttributesList based on the vector we constructed.
854 assert(ArgAttrVec.size() == Params.size());
855 AttributeList NewPAL =
856 AttributeList::get(F->getContext(), FnAttrs, RetAttrs, ArgAttrVec);
858 // Create the new function type based on the recomputed parameters.
859 FunctionType *NFTy = FunctionType::get(NRetTy, Params, FTy->isVarArg());
865 // Create the new function body and insert it into the module...
866 Function *NF = Function::Create(NFTy, F->getLinkage(), F->getAddressSpace());
867 NF->copyAttributesFrom(F);
868 NF->setComdat(F->getComdat());
869 NF->setAttributes(NewPAL);
870 // Insert the new function before the old function, so we won't be processing
872 F->getParent()->getFunctionList().insert(F->getIterator(), NF);
875 // Loop over all of the callers of the function, transforming the call sites
876 // to pass in a smaller number of arguments into the new function.
877 std::vector<Value*> Args;
878 while (!F->use_empty()) {
879 CallSite CS(F->user_back());
880 Instruction *Call = CS.getInstruction();
883 const AttributeList &CallPAL = CS.getAttributes();
885 // Adjust the call return attributes in case the function was changed to
887 AttrBuilder RAttrs(CallPAL.getRetAttributes());
888 RAttrs.remove(AttributeFuncs::typeIncompatible(NRetTy));
889 AttributeSet RetAttrs = AttributeSet::get(F->getContext(), RAttrs);
891 // Declare these outside of the loops, so we can reuse them for the second
892 // loop, which loops the varargs.
893 CallSite::arg_iterator I = CS.arg_begin();
895 // Loop over those operands, corresponding to the normal arguments to the
896 // original function, and add those that are still alive.
897 for (unsigned e = FTy->getNumParams(); i != e; ++I, ++i)
900 // Get original parameter attributes, but skip return attributes.
901 AttributeSet Attrs = CallPAL.getParamAttributes(i);
902 if (NRetTy != RetTy && Attrs.hasAttribute(Attribute::Returned)) {
903 // If the return type has changed, then get rid of 'returned' on the
904 // call site. The alternative is to make all 'returned' attributes on
905 // call sites keep the return value alive just like 'returned'
906 // attributes on function declaration but it's less clearly a win and
907 // this is not an expected case anyway
908 ArgAttrVec.push_back(AttributeSet::get(
910 AttrBuilder(Attrs).removeAttribute(Attribute::Returned)));
912 // Otherwise, use the original attributes.
913 ArgAttrVec.push_back(Attrs);
917 // Push any varargs arguments on the list. Don't forget their attributes.
918 for (CallSite::arg_iterator E = CS.arg_end(); I != E; ++I, ++i) {
920 ArgAttrVec.push_back(CallPAL.getParamAttributes(i));
923 // Reconstruct the AttributesList based on the vector we constructed.
924 assert(ArgAttrVec.size() == Args.size());
926 // Again, be sure to remove any allocsize attributes, since their indices
927 // may now be incorrect.
928 AttributeSet FnAttrs = CallPAL.getFnAttributes().removeAttribute(
929 F->getContext(), Attribute::AllocSize);
931 AttributeList NewCallPAL = AttributeList::get(
932 F->getContext(), FnAttrs, RetAttrs, ArgAttrVec);
934 SmallVector<OperandBundleDef, 1> OpBundles;
935 CS.getOperandBundlesAsDefs(OpBundles);
938 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
939 NewCS = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
940 Args, OpBundles, "", Call->getParent());
942 NewCS = CallInst::Create(NF, Args, OpBundles, "", Call);
943 cast<CallInst>(NewCS.getInstruction())
944 ->setTailCallKind(cast<CallInst>(Call)->getTailCallKind());
946 NewCS.setCallingConv(CS.getCallingConv());
947 NewCS.setAttributes(NewCallPAL);
948 NewCS->setDebugLoc(Call->getDebugLoc());
950 if (Call->extractProfTotalWeight(W))
951 NewCS->setProfWeight(W);
955 Instruction *New = NewCS.getInstruction();
956 if (!Call->use_empty() || Call->isUsedByMetadata()) {
957 if (New->getType() == Call->getType()) {
958 // Return type not changed? Just replace users then.
959 Call->replaceAllUsesWith(New);
961 } else if (New->getType()->isVoidTy()) {
962 // If the return value is dead, replace any uses of it with undef
963 // (any non-debug value uses will get removed later on).
964 if (!Call->getType()->isX86_MMXTy())
965 Call->replaceAllUsesWith(UndefValue::get(Call->getType()));
967 assert((RetTy->isStructTy() || RetTy->isArrayTy()) &&
968 "Return type changed, but not into a void. The old return type"
969 " must have been a struct or an array!");
970 Instruction *InsertPt = Call;
971 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
972 BasicBlock *NewEdge = SplitEdge(New->getParent(), II->getNormalDest());
973 InsertPt = &*NewEdge->getFirstInsertionPt();
976 // We used to return a struct or array. Instead of doing smart stuff
977 // with all the uses, we will just rebuild it using extract/insertvalue
978 // chaining and let instcombine clean that up.
980 // Start out building up our return value from undef
981 Value *RetVal = UndefValue::get(RetTy);
982 for (unsigned i = 0; i != RetCount; ++i)
983 if (NewRetIdxs[i] != -1) {
985 if (RetTypes.size() > 1)
986 // We are still returning a struct, so extract the value from our
988 V = ExtractValueInst::Create(New, NewRetIdxs[i], "newret",
991 // We are now returning a single element, so just insert that
993 // Insert the value at the old position
994 RetVal = InsertValueInst::Create(RetVal, V, i, "oldret", InsertPt);
996 // Now, replace all uses of the old call instruction with the return
998 Call->replaceAllUsesWith(RetVal);
1003 // Finally, remove the old call from the program, reducing the use-count of
1005 Call->eraseFromParent();
1008 // Since we have now created the new function, splice the body of the old
1009 // function right into the new function, leaving the old rotting hulk of the
1011 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
1013 // Loop over the argument list, transferring uses of the old arguments over to
1014 // the new arguments, also transferring over the names as well.
1016 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
1017 I2 = NF->arg_begin(); I != E; ++I, ++i)
1019 // If this is a live argument, move the name and users over to the new
1021 I->replaceAllUsesWith(&*I2);
1025 // If this argument is dead, replace any uses of it with undef
1026 // (any non-debug value uses will get removed later on).
1027 if (!I->getType()->isX86_MMXTy())
1028 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1031 // If we change the return value of the function we must rewrite any return
1032 // instructions. Check this now.
1033 if (F->getReturnType() != NF->getReturnType())
1034 for (BasicBlock &BB : *NF)
1035 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator())) {
1038 if (NFTy->getReturnType()->isVoidTy()) {
1041 assert(RetTy->isStructTy() || RetTy->isArrayTy());
1042 // The original return value was a struct or array, insert
1043 // extractvalue/insertvalue chains to extract only the values we need
1044 // to return and insert them into our new result.
1045 // This does generate messy code, but we'll let it to instcombine to
1047 Value *OldRet = RI->getOperand(0);
1048 // Start out building up our return value from undef
1049 RetVal = UndefValue::get(NRetTy);
1050 for (unsigned i = 0; i != RetCount; ++i)
1051 if (NewRetIdxs[i] != -1) {
1052 ExtractValueInst *EV = ExtractValueInst::Create(OldRet, i,
1054 if (RetTypes.size() > 1) {
1055 // We're still returning a struct, so reinsert the value into
1056 // our new return value at the new index
1058 RetVal = InsertValueInst::Create(RetVal, EV, NewRetIdxs[i],
1061 // We are now only returning a simple value, so just return the
1067 // Replace the return instruction with one returning the new return
1068 // value (possibly 0 if we became void).
1069 ReturnInst::Create(F->getContext(), RetVal, RI);
1070 BB.getInstList().erase(RI);
1073 // Clone metadatas from the old function, including debug info descriptor.
1074 SmallVector<std::pair<unsigned, MDNode *>, 1> MDs;
1075 F->getAllMetadata(MDs);
1077 NF->addMetadata(MD.first, *MD.second);
1079 // Now that the old function is dead, delete it.
1080 F->eraseFromParent();
1085 PreservedAnalyses DeadArgumentEliminationPass::run(Module &M,
1086 ModuleAnalysisManager &) {
1087 bool Changed = false;
1089 // First pass: Do a simple check to see if any functions can have their "..."
1090 // removed. We can do this if they never call va_start. This loop cannot be
1091 // fused with the next loop, because deleting a function invalidates
1092 // information computed while surveying other functions.
1093 LLVM_DEBUG(dbgs() << "DeadArgumentEliminationPass - Deleting dead varargs\n");
1094 for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
1096 if (F.getFunctionType()->isVarArg())
1097 Changed |= DeleteDeadVarargs(F);
1100 // Second phase:loop through the module, determining which arguments are live.
1101 // We assume all arguments are dead unless proven otherwise (allowing us to
1102 // determine that dead arguments passed into recursive functions are dead).
1104 LLVM_DEBUG(dbgs() << "DeadArgumentEliminationPass - Determining liveness\n");
1108 // Now, remove all dead arguments and return values from each function in
1110 for (Module::iterator I = M.begin(), E = M.end(); I != E; ) {
1111 // Increment now, because the function will probably get removed (ie.
1112 // replaced by a new one).
1113 Function *F = &*I++;
1114 Changed |= RemoveDeadStuffFromFunction(F);
1117 // Finally, look for any unused parameters in functions with non-local
1118 // linkage and replace the passed in parameters with undef.
1120 Changed |= RemoveDeadArgumentsFromCallers(F);
1123 return PreservedAnalyses::all();
1124 return PreservedAnalyses::none();