1 //===- DeadArgumentElimination.cpp - Eliminate dead arguments -------------===// 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 pass deletes dead arguments from internal functions. Dead argument 10 // elimination removes arguments which are directly dead, as well as arguments 11 // only passed into function calls as dead arguments of other functions. This 12 // pass also deletes dead return values in a similar way. 13 // 14 // This pass is often useful as a cleanup pass to run after aggressive 15 // interprocedural passes, which add possibly-dead arguments or return values. 16 // 17 //===----------------------------------------------------------------------===// 18 19 #include "llvm/Transforms/IPO/DeadArgumentElimination.h" 20 #include "llvm/ADT/SmallVector.h" 21 #include "llvm/ADT/Statistic.h" 22 #include "llvm/IR/Argument.h" 23 #include "llvm/IR/Attributes.h" 24 #include "llvm/IR/BasicBlock.h" 25 #include "llvm/IR/Constants.h" 26 #include "llvm/IR/DerivedTypes.h" 27 #include "llvm/IR/Function.h" 28 #include "llvm/IR/InstrTypes.h" 29 #include "llvm/IR/Instruction.h" 30 #include "llvm/IR/Instructions.h" 31 #include "llvm/IR/IntrinsicInst.h" 32 #include "llvm/IR/Intrinsics.h" 33 #include "llvm/IR/Module.h" 34 #include "llvm/IR/PassManager.h" 35 #include "llvm/IR/Type.h" 36 #include "llvm/IR/Use.h" 37 #include "llvm/IR/User.h" 38 #include "llvm/IR/Value.h" 39 #include "llvm/InitializePasses.h" 40 #include "llvm/Pass.h" 41 #include "llvm/Support/Casting.h" 42 #include "llvm/Support/Debug.h" 43 #include "llvm/Support/raw_ostream.h" 44 #include "llvm/Transforms/IPO.h" 45 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 46 #include <cassert> 47 #include <cstdint> 48 #include <utility> 49 #include <vector> 50 51 using namespace llvm; 52 53 #define DEBUG_TYPE "deadargelim" 54 55 STATISTIC(NumArgumentsEliminated, "Number of unread args removed"); 56 STATISTIC(NumRetValsEliminated , "Number of unused return values removed"); 57 STATISTIC(NumArgumentsReplacedWithUndef, 58 "Number of unread args replaced with undef"); 59 60 namespace { 61 62 /// DAE - The dead argument elimination pass. 63 class DAE : public ModulePass { 64 protected: 65 // DAH uses this to specify a different ID. 66 explicit DAE(char &ID) : ModulePass(ID) {} 67 68 public: 69 static char ID; // Pass identification, replacement for typeid 70 71 DAE() : ModulePass(ID) { 72 initializeDAEPass(*PassRegistry::getPassRegistry()); 73 } 74 75 bool runOnModule(Module &M) override { 76 if (skipModule(M)) 77 return false; 78 DeadArgumentEliminationPass DAEP(ShouldHackArguments()); 79 ModuleAnalysisManager DummyMAM; 80 PreservedAnalyses PA = DAEP.run(M, DummyMAM); 81 return !PA.areAllPreserved(); 82 } 83 84 virtual bool ShouldHackArguments() const { return false; } 85 }; 86 87 } // end anonymous namespace 88 89 char DAE::ID = 0; 90 91 INITIALIZE_PASS(DAE, "deadargelim", "Dead Argument Elimination", false, false) 92 93 namespace { 94 95 /// DAH - DeadArgumentHacking pass - Same as dead argument elimination, but 96 /// deletes arguments to functions which are external. This is only for use 97 /// by bugpoint. 98 struct DAH : public DAE { 99 static char ID; 100 101 DAH() : DAE(ID) {} 102 103 bool ShouldHackArguments() const override { return true; } 104 }; 105 106 } // end anonymous namespace 107 108 char DAH::ID = 0; 109 110 INITIALIZE_PASS(DAH, "deadarghaX0r", 111 "Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)", 112 false, false) 113 114 /// createDeadArgEliminationPass - This pass removes arguments from functions 115 /// which are not used by the body of the function. 116 ModulePass *llvm::createDeadArgEliminationPass() { return new DAE(); } 117 118 ModulePass *llvm::createDeadArgHackingPass() { return new DAH(); } 119 120 /// DeleteDeadVarargs - If this is an function that takes a ... list, and if 121 /// llvm.vastart is never called, the varargs list is dead for the function. 122 bool DeadArgumentEliminationPass::DeleteDeadVarargs(Function &Fn) { 123 assert(Fn.getFunctionType()->isVarArg() && "Function isn't varargs!"); 124 if (Fn.isDeclaration() || !Fn.hasLocalLinkage()) return false; 125 126 // Ensure that the function is only directly called. 127 if (Fn.hasAddressTaken()) 128 return false; 129 130 // Don't touch naked functions. The assembly might be using an argument, or 131 // otherwise rely on the frame layout in a way that this analysis will not 132 // see. 133 if (Fn.hasFnAttribute(Attribute::Naked)) { 134 return false; 135 } 136 137 // Okay, we know we can transform this function if safe. Scan its body 138 // looking for calls marked musttail or calls to llvm.vastart. 139 for (BasicBlock &BB : Fn) { 140 for (Instruction &I : BB) { 141 CallInst *CI = dyn_cast<CallInst>(&I); 142 if (!CI) 143 continue; 144 if (CI->isMustTailCall()) 145 return false; 146 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) { 147 if (II->getIntrinsicID() == Intrinsic::vastart) 148 return false; 149 } 150 } 151 } 152 153 // If we get here, there are no calls to llvm.vastart in the function body, 154 // remove the "..." and adjust all the calls. 155 156 // Start by computing a new prototype for the function, which is the same as 157 // the old function, but doesn't have isVarArg set. 158 FunctionType *FTy = Fn.getFunctionType(); 159 160 std::vector<Type *> Params(FTy->param_begin(), FTy->param_end()); 161 FunctionType *NFTy = FunctionType::get(FTy->getReturnType(), 162 Params, false); 163 unsigned NumArgs = Params.size(); 164 165 // Create the new function body and insert it into the module... 166 Function *NF = Function::Create(NFTy, Fn.getLinkage(), Fn.getAddressSpace()); 167 NF->copyAttributesFrom(&Fn); 168 NF->setComdat(Fn.getComdat()); 169 Fn.getParent()->getFunctionList().insert(Fn.getIterator(), NF); 170 NF->takeName(&Fn); 171 172 // Loop over all of the callers of the function, transforming the call sites 173 // to pass in a smaller number of arguments into the new function. 174 // 175 std::vector<Value *> Args; 176 for (Value::user_iterator I = Fn.user_begin(), E = Fn.user_end(); I != E; ) { 177 CallBase *CB = dyn_cast<CallBase>(*I++); 178 if (!CB) 179 continue; 180 181 // Pass all the same arguments. 182 Args.assign(CB->arg_begin(), CB->arg_begin() + NumArgs); 183 184 // Drop any attributes that were on the vararg arguments. 185 AttributeList PAL = CB->getAttributes(); 186 if (!PAL.isEmpty()) { 187 SmallVector<AttributeSet, 8> ArgAttrs; 188 for (unsigned ArgNo = 0; ArgNo < NumArgs; ++ArgNo) 189 ArgAttrs.push_back(PAL.getParamAttributes(ArgNo)); 190 PAL = AttributeList::get(Fn.getContext(), PAL.getFnAttributes(), 191 PAL.getRetAttributes(), ArgAttrs); 192 } 193 194 SmallVector<OperandBundleDef, 1> OpBundles; 195 CB->getOperandBundlesAsDefs(OpBundles); 196 197 CallBase *NewCB = nullptr; 198 if (InvokeInst *II = dyn_cast<InvokeInst>(CB)) { 199 NewCB = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(), 200 Args, OpBundles, "", CB); 201 } else { 202 NewCB = CallInst::Create(NF, Args, OpBundles, "", CB); 203 cast<CallInst>(NewCB)->setTailCallKind( 204 cast<CallInst>(CB)->getTailCallKind()); 205 } 206 NewCB->setCallingConv(CB->getCallingConv()); 207 NewCB->setAttributes(PAL); 208 NewCB->setDebugLoc(CB->getDebugLoc()); 209 uint64_t W; 210 if (CB->extractProfTotalWeight(W)) 211 NewCB->setProfWeight(W); 212 213 Args.clear(); 214 215 if (!CB->use_empty()) 216 CB->replaceAllUsesWith(NewCB); 217 218 NewCB->takeName(CB); 219 220 // Finally, remove the old call from the program, reducing the use-count of 221 // F. 222 CB->eraseFromParent(); 223 } 224 225 // Since we have now created the new function, splice the body of the old 226 // function right into the new function, leaving the old rotting hulk of the 227 // function empty. 228 NF->getBasicBlockList().splice(NF->begin(), Fn.getBasicBlockList()); 229 230 // Loop over the argument list, transferring uses of the old arguments over to 231 // the new arguments, also transferring over the names as well. While we're at 232 // it, remove the dead arguments from the DeadArguments list. 233 for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end(), 234 I2 = NF->arg_begin(); I != E; ++I, ++I2) { 235 // Move the name and users over to the new version. 236 I->replaceAllUsesWith(&*I2); 237 I2->takeName(&*I); 238 } 239 240 // Clone metadatas from the old function, including debug info descriptor. 241 SmallVector<std::pair<unsigned, MDNode *>, 1> MDs; 242 Fn.getAllMetadata(MDs); 243 for (auto MD : MDs) 244 NF->addMetadata(MD.first, *MD.second); 245 246 // Fix up any BlockAddresses that refer to the function. 247 Fn.replaceAllUsesWith(ConstantExpr::getBitCast(NF, Fn.getType())); 248 // Delete the bitcast that we just created, so that NF does not 249 // appear to be address-taken. 250 NF->removeDeadConstantUsers(); 251 // Finally, nuke the old function. 252 Fn.eraseFromParent(); 253 return true; 254 } 255 256 /// RemoveDeadArgumentsFromCallers - Checks if the given function has any 257 /// arguments that are unused, and changes the caller parameters to be undefined 258 /// instead. 259 bool DeadArgumentEliminationPass::RemoveDeadArgumentsFromCallers(Function &Fn) { 260 // We cannot change the arguments if this TU does not define the function or 261 // if the linker may choose a function body from another TU, even if the 262 // nominal linkage indicates that other copies of the function have the same 263 // semantics. In the below example, the dead load from %p may not have been 264 // eliminated from the linker-chosen copy of f, so replacing %p with undef 265 // in callers may introduce undefined behavior. 266 // 267 // define linkonce_odr void @f(i32* %p) { 268 // %v = load i32 %p 269 // ret void 270 // } 271 if (!Fn.hasExactDefinition()) 272 return false; 273 274 // Functions with local linkage should already have been handled, except the 275 // fragile (variadic) ones which we can improve here. 276 if (Fn.hasLocalLinkage() && !Fn.getFunctionType()->isVarArg()) 277 return false; 278 279 // Don't touch naked functions. The assembly might be using an argument, or 280 // otherwise rely on the frame layout in a way that this analysis will not 281 // see. 282 if (Fn.hasFnAttribute(Attribute::Naked)) 283 return false; 284 285 if (Fn.use_empty()) 286 return false; 287 288 SmallVector<unsigned, 8> UnusedArgs; 289 bool Changed = false; 290 291 for (Argument &Arg : Fn.args()) { 292 if (!Arg.hasSwiftErrorAttr() && Arg.use_empty() && 293 !Arg.hasPassPointeeByValueAttr()) { 294 if (Arg.isUsedByMetadata()) { 295 Arg.replaceAllUsesWith(UndefValue::get(Arg.getType())); 296 Changed = true; 297 } 298 UnusedArgs.push_back(Arg.getArgNo()); 299 } 300 } 301 302 if (UnusedArgs.empty()) 303 return false; 304 305 for (Use &U : Fn.uses()) { 306 CallBase *CB = dyn_cast<CallBase>(U.getUser()); 307 if (!CB || !CB->isCallee(&U)) 308 continue; 309 310 // Now go through all unused args and replace them with "undef". 311 for (unsigned I = 0, E = UnusedArgs.size(); I != E; ++I) { 312 unsigned ArgNo = UnusedArgs[I]; 313 314 Value *Arg = CB->getArgOperand(ArgNo); 315 CB->setArgOperand(ArgNo, UndefValue::get(Arg->getType())); 316 ++NumArgumentsReplacedWithUndef; 317 Changed = true; 318 } 319 } 320 321 return Changed; 322 } 323 324 /// Convenience function that returns the number of return values. It returns 0 325 /// for void functions and 1 for functions not returning a struct. It returns 326 /// the number of struct elements for functions returning a struct. 327 static unsigned NumRetVals(const Function *F) { 328 Type *RetTy = F->getReturnType(); 329 if (RetTy->isVoidTy()) 330 return 0; 331 else if (StructType *STy = dyn_cast<StructType>(RetTy)) 332 return STy->getNumElements(); 333 else if (ArrayType *ATy = dyn_cast<ArrayType>(RetTy)) 334 return ATy->getNumElements(); 335 else 336 return 1; 337 } 338 339 /// Returns the sub-type a function will return at a given Idx. Should 340 /// correspond to the result type of an ExtractValue instruction executed with 341 /// just that one Idx (i.e. only top-level structure is considered). 342 static Type *getRetComponentType(const Function *F, unsigned Idx) { 343 Type *RetTy = F->getReturnType(); 344 assert(!RetTy->isVoidTy() && "void type has no subtype"); 345 346 if (StructType *STy = dyn_cast<StructType>(RetTy)) 347 return STy->getElementType(Idx); 348 else if (ArrayType *ATy = dyn_cast<ArrayType>(RetTy)) 349 return ATy->getElementType(); 350 else 351 return RetTy; 352 } 353 354 /// MarkIfNotLive - This checks Use for liveness in LiveValues. If Use is not 355 /// live, it adds Use to the MaybeLiveUses argument. Returns the determined 356 /// liveness of Use. 357 DeadArgumentEliminationPass::Liveness 358 DeadArgumentEliminationPass::MarkIfNotLive(RetOrArg Use, 359 UseVector &MaybeLiveUses) { 360 // We're live if our use or its Function is already marked as live. 361 if (LiveFunctions.count(Use.F) || LiveValues.count(Use)) 362 return Live; 363 364 // We're maybe live otherwise, but remember that we must become live if 365 // Use becomes live. 366 MaybeLiveUses.push_back(Use); 367 return MaybeLive; 368 } 369 370 /// SurveyUse - This looks at a single use of an argument or return value 371 /// and determines if it should be alive or not. Adds this use to MaybeLiveUses 372 /// if it causes the used value to become MaybeLive. 373 /// 374 /// RetValNum is the return value number to use when this use is used in a 375 /// return instruction. This is used in the recursion, you should always leave 376 /// it at 0. 377 DeadArgumentEliminationPass::Liveness 378 DeadArgumentEliminationPass::SurveyUse(const Use *U, UseVector &MaybeLiveUses, 379 unsigned RetValNum) { 380 const User *V = U->getUser(); 381 if (const ReturnInst *RI = dyn_cast<ReturnInst>(V)) { 382 // The value is returned from a function. It's only live when the 383 // function's return value is live. We use RetValNum here, for the case 384 // that U is really a use of an insertvalue instruction that uses the 385 // original Use. 386 const Function *F = RI->getParent()->getParent(); 387 if (RetValNum != -1U) { 388 RetOrArg Use = CreateRet(F, RetValNum); 389 // We might be live, depending on the liveness of Use. 390 return MarkIfNotLive(Use, MaybeLiveUses); 391 } else { 392 DeadArgumentEliminationPass::Liveness Result = MaybeLive; 393 for (unsigned Ri = 0; Ri < NumRetVals(F); ++Ri) { 394 RetOrArg Use = CreateRet(F, Ri); 395 // We might be live, depending on the liveness of Use. If any 396 // sub-value is live, then the entire value is considered live. This 397 // is a conservative choice, and better tracking is possible. 398 DeadArgumentEliminationPass::Liveness SubResult = 399 MarkIfNotLive(Use, MaybeLiveUses); 400 if (Result != Live) 401 Result = SubResult; 402 } 403 return Result; 404 } 405 } 406 if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(V)) { 407 if (U->getOperandNo() != InsertValueInst::getAggregateOperandIndex() 408 && IV->hasIndices()) 409 // The use we are examining is inserted into an aggregate. Our liveness 410 // depends on all uses of that aggregate, but if it is used as a return 411 // value, only index at which we were inserted counts. 412 RetValNum = *IV->idx_begin(); 413 414 // Note that if we are used as the aggregate operand to the insertvalue, 415 // we don't change RetValNum, but do survey all our uses. 416 417 Liveness Result = MaybeLive; 418 for (const Use &UU : IV->uses()) { 419 Result = SurveyUse(&UU, MaybeLiveUses, RetValNum); 420 if (Result == Live) 421 break; 422 } 423 return Result; 424 } 425 426 if (const auto *CB = dyn_cast<CallBase>(V)) { 427 const Function *F = CB->getCalledFunction(); 428 if (F) { 429 // Used in a direct call. 430 431 // The function argument is live if it is used as a bundle operand. 432 if (CB->isBundleOperand(U)) 433 return Live; 434 435 // Find the argument number. We know for sure that this use is an 436 // argument, since if it was the function argument this would be an 437 // indirect call and the we know can't be looking at a value of the 438 // label type (for the invoke instruction). 439 unsigned ArgNo = CB->getArgOperandNo(U); 440 441 if (ArgNo >= F->getFunctionType()->getNumParams()) 442 // The value is passed in through a vararg! Must be live. 443 return Live; 444 445 assert(CB->getArgOperand(ArgNo) == CB->getOperand(U->getOperandNo()) && 446 "Argument is not where we expected it"); 447 448 // Value passed to a normal call. It's only live when the corresponding 449 // argument to the called function turns out live. 450 RetOrArg Use = CreateArg(F, ArgNo); 451 return MarkIfNotLive(Use, MaybeLiveUses); 452 } 453 } 454 // Used in any other way? Value must be live. 455 return Live; 456 } 457 458 /// SurveyUses - This looks at all the uses of the given value 459 /// Returns the Liveness deduced from the uses of this value. 460 /// 461 /// Adds all uses that cause the result to be MaybeLive to MaybeLiveRetUses. If 462 /// the result is Live, MaybeLiveUses might be modified but its content should 463 /// be ignored (since it might not be complete). 464 DeadArgumentEliminationPass::Liveness 465 DeadArgumentEliminationPass::SurveyUses(const Value *V, 466 UseVector &MaybeLiveUses) { 467 // Assume it's dead (which will only hold if there are no uses at all..). 468 Liveness Result = MaybeLive; 469 // Check each use. 470 for (const Use &U : V->uses()) { 471 Result = SurveyUse(&U, MaybeLiveUses); 472 if (Result == Live) 473 break; 474 } 475 return Result; 476 } 477 478 // SurveyFunction - This performs the initial survey of the specified function, 479 // checking out whether or not it uses any of its incoming arguments or whether 480 // any callers use the return value. This fills in the LiveValues set and Uses 481 // map. 482 // 483 // We consider arguments of non-internal functions to be intrinsically alive as 484 // well as arguments to functions which have their "address taken". 485 void DeadArgumentEliminationPass::SurveyFunction(const Function &F) { 486 // Functions with inalloca/preallocated parameters are expecting args in a 487 // particular register and memory layout. 488 if (F.getAttributes().hasAttrSomewhere(Attribute::InAlloca) || 489 F.getAttributes().hasAttrSomewhere(Attribute::Preallocated)) { 490 MarkLive(F); 491 return; 492 } 493 494 // Don't touch naked functions. The assembly might be using an argument, or 495 // otherwise rely on the frame layout in a way that this analysis will not 496 // see. 497 if (F.hasFnAttribute(Attribute::Naked)) { 498 MarkLive(F); 499 return; 500 } 501 502 unsigned RetCount = NumRetVals(&F); 503 504 // Assume all return values are dead 505 using RetVals = SmallVector<Liveness, 5>; 506 507 RetVals RetValLiveness(RetCount, MaybeLive); 508 509 using RetUses = SmallVector<UseVector, 5>; 510 511 // These vectors map each return value to the uses that make it MaybeLive, so 512 // we can add those to the Uses map if the return value really turns out to be 513 // MaybeLive. Initialized to a list of RetCount empty lists. 514 RetUses MaybeLiveRetUses(RetCount); 515 516 bool HasMustTailCalls = false; 517 518 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) { 519 if (const ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) { 520 if (RI->getNumOperands() != 0 && RI->getOperand(0)->getType() 521 != F.getFunctionType()->getReturnType()) { 522 // We don't support old style multiple return values. 523 MarkLive(F); 524 return; 525 } 526 } 527 528 // If we have any returns of `musttail` results - the signature can't 529 // change 530 if (BB->getTerminatingMustTailCall() != nullptr) 531 HasMustTailCalls = true; 532 } 533 534 if (HasMustTailCalls) { 535 LLVM_DEBUG(dbgs() << "DeadArgumentEliminationPass - " << F.getName() 536 << " has musttail calls\n"); 537 } 538 539 if (!F.hasLocalLinkage() && (!ShouldHackArguments || F.isIntrinsic())) { 540 MarkLive(F); 541 return; 542 } 543 544 LLVM_DEBUG( 545 dbgs() << "DeadArgumentEliminationPass - Inspecting callers for fn: " 546 << F.getName() << "\n"); 547 // Keep track of the number of live retvals, so we can skip checks once all 548 // of them turn out to be live. 549 unsigned NumLiveRetVals = 0; 550 551 bool HasMustTailCallers = false; 552 553 // Loop all uses of the function. 554 for (const Use &U : F.uses()) { 555 // If the function is PASSED IN as an argument, its address has been 556 // taken. 557 const auto *CB = dyn_cast<CallBase>(U.getUser()); 558 if (!CB || !CB->isCallee(&U)) { 559 MarkLive(F); 560 return; 561 } 562 563 // The number of arguments for `musttail` call must match the number of 564 // arguments of the caller 565 if (CB->isMustTailCall()) 566 HasMustTailCallers = true; 567 568 // If we end up here, we are looking at a direct call to our function. 569 570 // Now, check how our return value(s) is/are used in this caller. Don't 571 // bother checking return values if all of them are live already. 572 if (NumLiveRetVals == RetCount) 573 continue; 574 575 // Check all uses of the return value. 576 for (const Use &U : CB->uses()) { 577 if (ExtractValueInst *Ext = dyn_cast<ExtractValueInst>(U.getUser())) { 578 // This use uses a part of our return value, survey the uses of 579 // that part and store the results for this index only. 580 unsigned Idx = *Ext->idx_begin(); 581 if (RetValLiveness[Idx] != Live) { 582 RetValLiveness[Idx] = SurveyUses(Ext, MaybeLiveRetUses[Idx]); 583 if (RetValLiveness[Idx] == Live) 584 NumLiveRetVals++; 585 } 586 } else { 587 // Used by something else than extractvalue. Survey, but assume that the 588 // result applies to all sub-values. 589 UseVector MaybeLiveAggregateUses; 590 if (SurveyUse(&U, MaybeLiveAggregateUses) == Live) { 591 NumLiveRetVals = RetCount; 592 RetValLiveness.assign(RetCount, Live); 593 break; 594 } else { 595 for (unsigned Ri = 0; Ri != RetCount; ++Ri) { 596 if (RetValLiveness[Ri] != Live) 597 MaybeLiveRetUses[Ri].append(MaybeLiveAggregateUses.begin(), 598 MaybeLiveAggregateUses.end()); 599 } 600 } 601 } 602 } 603 } 604 605 if (HasMustTailCallers) { 606 LLVM_DEBUG(dbgs() << "DeadArgumentEliminationPass - " << F.getName() 607 << " has musttail callers\n"); 608 } 609 610 // Now we've inspected all callers, record the liveness of our return values. 611 for (unsigned Ri = 0; Ri != RetCount; ++Ri) 612 MarkValue(CreateRet(&F, Ri), RetValLiveness[Ri], MaybeLiveRetUses[Ri]); 613 614 LLVM_DEBUG(dbgs() << "DeadArgumentEliminationPass - Inspecting args for fn: " 615 << F.getName() << "\n"); 616 617 // Now, check all of our arguments. 618 unsigned ArgI = 0; 619 UseVector MaybeLiveArgUses; 620 for (Function::const_arg_iterator AI = F.arg_begin(), E = F.arg_end(); 621 AI != E; ++AI, ++ArgI) { 622 Liveness Result; 623 if (F.getFunctionType()->isVarArg() || HasMustTailCallers || 624 HasMustTailCalls) { 625 // Variadic functions will already have a va_arg function expanded inside 626 // them, making them potentially very sensitive to ABI changes resulting 627 // from removing arguments entirely, so don't. For example AArch64 handles 628 // register and stack HFAs very differently, and this is reflected in the 629 // IR which has already been generated. 630 // 631 // `musttail` calls to this function restrict argument removal attempts. 632 // The signature of the caller must match the signature of the function. 633 // 634 // `musttail` calls in this function prevents us from changing its 635 // signature 636 Result = Live; 637 } else { 638 // See what the effect of this use is (recording any uses that cause 639 // MaybeLive in MaybeLiveArgUses). 640 Result = SurveyUses(&*AI, MaybeLiveArgUses); 641 } 642 643 // Mark the result. 644 MarkValue(CreateArg(&F, ArgI), Result, MaybeLiveArgUses); 645 // Clear the vector again for the next iteration. 646 MaybeLiveArgUses.clear(); 647 } 648 } 649 650 /// MarkValue - This function marks the liveness of RA depending on L. If L is 651 /// MaybeLive, it also takes all uses in MaybeLiveUses and records them in Uses, 652 /// such that RA will be marked live if any use in MaybeLiveUses gets marked 653 /// live later on. 654 void DeadArgumentEliminationPass::MarkValue(const RetOrArg &RA, Liveness L, 655 const UseVector &MaybeLiveUses) { 656 switch (L) { 657 case Live: 658 MarkLive(RA); 659 break; 660 case MaybeLive: 661 // Note any uses of this value, so this return value can be 662 // marked live whenever one of the uses becomes live. 663 for (const auto &MaybeLiveUse : MaybeLiveUses) 664 Uses.insert(std::make_pair(MaybeLiveUse, RA)); 665 break; 666 } 667 } 668 669 /// MarkLive - Mark the given Function as alive, meaning that it cannot be 670 /// changed in any way. Additionally, 671 /// mark any values that are used as this function's parameters or by its return 672 /// values (according to Uses) live as well. 673 void DeadArgumentEliminationPass::MarkLive(const Function &F) { 674 LLVM_DEBUG(dbgs() << "DeadArgumentEliminationPass - Intrinsically live fn: " 675 << F.getName() << "\n"); 676 // Mark the function as live. 677 LiveFunctions.insert(&F); 678 // Mark all arguments as live. 679 for (unsigned ArgI = 0, E = F.arg_size(); ArgI != E; ++ArgI) 680 PropagateLiveness(CreateArg(&F, ArgI)); 681 // Mark all return values as live. 682 for (unsigned Ri = 0, E = NumRetVals(&F); Ri != E; ++Ri) 683 PropagateLiveness(CreateRet(&F, Ri)); 684 } 685 686 /// MarkLive - Mark the given return value or argument as live. Additionally, 687 /// mark any values that are used by this value (according to Uses) live as 688 /// well. 689 void DeadArgumentEliminationPass::MarkLive(const RetOrArg &RA) { 690 if (LiveFunctions.count(RA.F)) 691 return; // Function was already marked Live. 692 693 if (!LiveValues.insert(RA).second) 694 return; // We were already marked Live. 695 696 LLVM_DEBUG(dbgs() << "DeadArgumentEliminationPass - Marking " 697 << RA.getDescription() << " live\n"); 698 PropagateLiveness(RA); 699 } 700 701 /// PropagateLiveness - Given that RA is a live value, propagate it's liveness 702 /// to any other values it uses (according to Uses). 703 void DeadArgumentEliminationPass::PropagateLiveness(const RetOrArg &RA) { 704 // We don't use upper_bound (or equal_range) here, because our recursive call 705 // to ourselves is likely to cause the upper_bound (which is the first value 706 // not belonging to RA) to become erased and the iterator invalidated. 707 UseMap::iterator Begin = Uses.lower_bound(RA); 708 UseMap::iterator E = Uses.end(); 709 UseMap::iterator I; 710 for (I = Begin; I != E && I->first == RA; ++I) 711 MarkLive(I->second); 712 713 // Erase RA from the Uses map (from the lower bound to wherever we ended up 714 // after the loop). 715 Uses.erase(Begin, I); 716 } 717 718 // RemoveDeadStuffFromFunction - Remove any arguments and return values from F 719 // that are not in LiveValues. Transform the function and all of the callees of 720 // the function to not have these arguments and return values. 721 // 722 bool DeadArgumentEliminationPass::RemoveDeadStuffFromFunction(Function *F) { 723 // Don't modify fully live functions 724 if (LiveFunctions.count(F)) 725 return false; 726 727 // Start by computing a new prototype for the function, which is the same as 728 // the old function, but has fewer arguments and a different return type. 729 FunctionType *FTy = F->getFunctionType(); 730 std::vector<Type*> Params; 731 732 // Keep track of if we have a live 'returned' argument 733 bool HasLiveReturnedArg = false; 734 735 // Set up to build a new list of parameter attributes. 736 SmallVector<AttributeSet, 8> ArgAttrVec; 737 const AttributeList &PAL = F->getAttributes(); 738 739 // Remember which arguments are still alive. 740 SmallVector<bool, 10> ArgAlive(FTy->getNumParams(), false); 741 // Construct the new parameter list from non-dead arguments. Also construct 742 // a new set of parameter attributes to correspond. Skip the first parameter 743 // attribute, since that belongs to the return value. 744 unsigned ArgI = 0; 745 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; 746 ++I, ++ArgI) { 747 RetOrArg Arg = CreateArg(F, ArgI); 748 if (LiveValues.erase(Arg)) { 749 Params.push_back(I->getType()); 750 ArgAlive[ArgI] = true; 751 ArgAttrVec.push_back(PAL.getParamAttributes(ArgI)); 752 HasLiveReturnedArg |= PAL.hasParamAttribute(ArgI, Attribute::Returned); 753 } else { 754 ++NumArgumentsEliminated; 755 LLVM_DEBUG(dbgs() << "DeadArgumentEliminationPass - Removing argument " 756 << ArgI << " (" << I->getName() << ") from " 757 << F->getName() << "\n"); 758 } 759 } 760 761 // Find out the new return value. 762 Type *RetTy = FTy->getReturnType(); 763 Type *NRetTy = nullptr; 764 unsigned RetCount = NumRetVals(F); 765 766 // -1 means unused, other numbers are the new index 767 SmallVector<int, 5> NewRetIdxs(RetCount, -1); 768 std::vector<Type*> RetTypes; 769 770 // If there is a function with a live 'returned' argument but a dead return 771 // value, then there are two possible actions: 772 // 1) Eliminate the return value and take off the 'returned' attribute on the 773 // argument. 774 // 2) Retain the 'returned' attribute and treat the return value (but not the 775 // entire function) as live so that it is not eliminated. 776 // 777 // It's not clear in the general case which option is more profitable because, 778 // even in the absence of explicit uses of the return value, code generation 779 // is free to use the 'returned' attribute to do things like eliding 780 // save/restores of registers across calls. Whether or not this happens is 781 // target and ABI-specific as well as depending on the amount of register 782 // pressure, so there's no good way for an IR-level pass to figure this out. 783 // 784 // Fortunately, the only places where 'returned' is currently generated by 785 // the FE are places where 'returned' is basically free and almost always a 786 // performance win, so the second option can just be used always for now. 787 // 788 // This should be revisited if 'returned' is ever applied more liberally. 789 if (RetTy->isVoidTy() || HasLiveReturnedArg) { 790 NRetTy = RetTy; 791 } else { 792 // Look at each of the original return values individually. 793 for (unsigned Ri = 0; Ri != RetCount; ++Ri) { 794 RetOrArg Ret = CreateRet(F, Ri); 795 if (LiveValues.erase(Ret)) { 796 RetTypes.push_back(getRetComponentType(F, Ri)); 797 NewRetIdxs[Ri] = RetTypes.size() - 1; 798 } else { 799 ++NumRetValsEliminated; 800 LLVM_DEBUG( 801 dbgs() << "DeadArgumentEliminationPass - Removing return value " 802 << Ri << " from " << F->getName() << "\n"); 803 } 804 } 805 if (RetTypes.size() > 1) { 806 // More than one return type? Reduce it down to size. 807 if (StructType *STy = dyn_cast<StructType>(RetTy)) { 808 // Make the new struct packed if we used to return a packed struct 809 // already. 810 NRetTy = StructType::get(STy->getContext(), RetTypes, STy->isPacked()); 811 } else { 812 assert(isa<ArrayType>(RetTy) && "unexpected multi-value return"); 813 NRetTy = ArrayType::get(RetTypes[0], RetTypes.size()); 814 } 815 } else if (RetTypes.size() == 1) 816 // One return type? Just a simple value then, but only if we didn't use to 817 // return a struct with that simple value before. 818 NRetTy = RetTypes.front(); 819 else if (RetTypes.empty()) 820 // No return types? Make it void, but only if we didn't use to return {}. 821 NRetTy = Type::getVoidTy(F->getContext()); 822 } 823 824 assert(NRetTy && "No new return type found?"); 825 826 // The existing function return attributes. 827 AttrBuilder RAttrs(PAL.getRetAttributes()); 828 829 // Remove any incompatible attributes, but only if we removed all return 830 // values. Otherwise, ensure that we don't have any conflicting attributes 831 // here. Currently, this should not be possible, but special handling might be 832 // required when new return value attributes are added. 833 if (NRetTy->isVoidTy()) 834 RAttrs.remove(AttributeFuncs::typeIncompatible(NRetTy)); 835 else 836 assert(!RAttrs.overlaps(AttributeFuncs::typeIncompatible(NRetTy)) && 837 "Return attributes no longer compatible?"); 838 839 AttributeSet RetAttrs = AttributeSet::get(F->getContext(), RAttrs); 840 841 // Strip allocsize attributes. They might refer to the deleted arguments. 842 AttributeSet FnAttrs = PAL.getFnAttributes().removeAttribute( 843 F->getContext(), Attribute::AllocSize); 844 845 // Reconstruct the AttributesList based on the vector we constructed. 846 assert(ArgAttrVec.size() == Params.size()); 847 AttributeList NewPAL = 848 AttributeList::get(F->getContext(), FnAttrs, RetAttrs, ArgAttrVec); 849 850 // Create the new function type based on the recomputed parameters. 851 FunctionType *NFTy = FunctionType::get(NRetTy, Params, FTy->isVarArg()); 852 853 // No change? 854 if (NFTy == FTy) 855 return false; 856 857 // Create the new function body and insert it into the module... 858 Function *NF = Function::Create(NFTy, F->getLinkage(), F->getAddressSpace()); 859 NF->copyAttributesFrom(F); 860 NF->setComdat(F->getComdat()); 861 NF->setAttributes(NewPAL); 862 // Insert the new function before the old function, so we won't be processing 863 // it again. 864 F->getParent()->getFunctionList().insert(F->getIterator(), NF); 865 NF->takeName(F); 866 867 // Loop over all of the callers of the function, transforming the call sites 868 // to pass in a smaller number of arguments into the new function. 869 std::vector<Value*> Args; 870 while (!F->use_empty()) { 871 CallBase &CB = cast<CallBase>(*F->user_back()); 872 873 ArgAttrVec.clear(); 874 const AttributeList &CallPAL = CB.getAttributes(); 875 876 // Adjust the call return attributes in case the function was changed to 877 // return void. 878 AttrBuilder RAttrs(CallPAL.getRetAttributes()); 879 RAttrs.remove(AttributeFuncs::typeIncompatible(NRetTy)); 880 AttributeSet RetAttrs = AttributeSet::get(F->getContext(), RAttrs); 881 882 // Declare these outside of the loops, so we can reuse them for the second 883 // loop, which loops the varargs. 884 auto I = CB.arg_begin(); 885 unsigned Pi = 0; 886 // Loop over those operands, corresponding to the normal arguments to the 887 // original function, and add those that are still alive. 888 for (unsigned E = FTy->getNumParams(); Pi != E; ++I, ++Pi) 889 if (ArgAlive[Pi]) { 890 Args.push_back(*I); 891 // Get original parameter attributes, but skip return attributes. 892 AttributeSet Attrs = CallPAL.getParamAttributes(Pi); 893 if (NRetTy != RetTy && Attrs.hasAttribute(Attribute::Returned)) { 894 // If the return type has changed, then get rid of 'returned' on the 895 // call site. The alternative is to make all 'returned' attributes on 896 // call sites keep the return value alive just like 'returned' 897 // attributes on function declaration but it's less clearly a win and 898 // this is not an expected case anyway 899 ArgAttrVec.push_back(AttributeSet::get( 900 F->getContext(), 901 AttrBuilder(Attrs).removeAttribute(Attribute::Returned))); 902 } else { 903 // Otherwise, use the original attributes. 904 ArgAttrVec.push_back(Attrs); 905 } 906 } 907 908 // Push any varargs arguments on the list. Don't forget their attributes. 909 for (auto E = CB.arg_end(); I != E; ++I, ++Pi) { 910 Args.push_back(*I); 911 ArgAttrVec.push_back(CallPAL.getParamAttributes(Pi)); 912 } 913 914 // Reconstruct the AttributesList based on the vector we constructed. 915 assert(ArgAttrVec.size() == Args.size()); 916 917 // Again, be sure to remove any allocsize attributes, since their indices 918 // may now be incorrect. 919 AttributeSet FnAttrs = CallPAL.getFnAttributes().removeAttribute( 920 F->getContext(), Attribute::AllocSize); 921 922 AttributeList NewCallPAL = AttributeList::get( 923 F->getContext(), FnAttrs, RetAttrs, ArgAttrVec); 924 925 SmallVector<OperandBundleDef, 1> OpBundles; 926 CB.getOperandBundlesAsDefs(OpBundles); 927 928 CallBase *NewCB = nullptr; 929 if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) { 930 NewCB = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(), 931 Args, OpBundles, "", CB.getParent()); 932 } else { 933 NewCB = CallInst::Create(NFTy, NF, Args, OpBundles, "", &CB); 934 cast<CallInst>(NewCB)->setTailCallKind( 935 cast<CallInst>(&CB)->getTailCallKind()); 936 } 937 NewCB->setCallingConv(CB.getCallingConv()); 938 NewCB->setAttributes(NewCallPAL); 939 NewCB->setDebugLoc(CB.getDebugLoc()); 940 uint64_t W; 941 if (CB.extractProfTotalWeight(W)) 942 NewCB->setProfWeight(W); 943 Args.clear(); 944 ArgAttrVec.clear(); 945 946 if (!CB.use_empty() || CB.isUsedByMetadata()) { 947 if (NewCB->getType() == CB.getType()) { 948 // Return type not changed? Just replace users then. 949 CB.replaceAllUsesWith(NewCB); 950 NewCB->takeName(&CB); 951 } else if (NewCB->getType()->isVoidTy()) { 952 // If the return value is dead, replace any uses of it with undef 953 // (any non-debug value uses will get removed later on). 954 if (!CB.getType()->isX86_MMXTy()) 955 CB.replaceAllUsesWith(UndefValue::get(CB.getType())); 956 } else { 957 assert((RetTy->isStructTy() || RetTy->isArrayTy()) && 958 "Return type changed, but not into a void. The old return type" 959 " must have been a struct or an array!"); 960 Instruction *InsertPt = &CB; 961 if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) { 962 BasicBlock *NewEdge = 963 SplitEdge(NewCB->getParent(), II->getNormalDest()); 964 InsertPt = &*NewEdge->getFirstInsertionPt(); 965 } 966 967 // We used to return a struct or array. Instead of doing smart stuff 968 // with all the uses, we will just rebuild it using extract/insertvalue 969 // chaining and let instcombine clean that up. 970 // 971 // Start out building up our return value from undef 972 Value *RetVal = UndefValue::get(RetTy); 973 for (unsigned Ri = 0; Ri != RetCount; ++Ri) 974 if (NewRetIdxs[Ri] != -1) { 975 Value *V; 976 if (RetTypes.size() > 1) 977 // We are still returning a struct, so extract the value from our 978 // return value 979 V = ExtractValueInst::Create(NewCB, NewRetIdxs[Ri], "newret", 980 InsertPt); 981 else 982 // We are now returning a single element, so just insert that 983 V = NewCB; 984 // Insert the value at the old position 985 RetVal = InsertValueInst::Create(RetVal, V, Ri, "oldret", InsertPt); 986 } 987 // Now, replace all uses of the old call instruction with the return 988 // struct we built 989 CB.replaceAllUsesWith(RetVal); 990 NewCB->takeName(&CB); 991 } 992 } 993 994 // Finally, remove the old call from the program, reducing the use-count of 995 // F. 996 CB.eraseFromParent(); 997 } 998 999 // Since we have now created the new function, splice the body of the old 1000 // function right into the new function, leaving the old rotting hulk of the 1001 // function empty. 1002 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList()); 1003 1004 // Loop over the argument list, transferring uses of the old arguments over to 1005 // the new arguments, also transferring over the names as well. 1006 ArgI = 0; 1007 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(), 1008 I2 = NF->arg_begin(); 1009 I != E; ++I, ++ArgI) 1010 if (ArgAlive[ArgI]) { 1011 // If this is a live argument, move the name and users over to the new 1012 // version. 1013 I->replaceAllUsesWith(&*I2); 1014 I2->takeName(&*I); 1015 ++I2; 1016 } else { 1017 // If this argument is dead, replace any uses of it with undef 1018 // (any non-debug value uses will get removed later on). 1019 if (!I->getType()->isX86_MMXTy()) 1020 I->replaceAllUsesWith(UndefValue::get(I->getType())); 1021 } 1022 1023 // If we change the return value of the function we must rewrite any return 1024 // instructions. Check this now. 1025 if (F->getReturnType() != NF->getReturnType()) 1026 for (BasicBlock &BB : *NF) 1027 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator())) { 1028 Value *RetVal = nullptr; 1029 1030 if (!NFTy->getReturnType()->isVoidTy()) { 1031 assert(RetTy->isStructTy() || RetTy->isArrayTy()); 1032 // The original return value was a struct or array, insert 1033 // extractvalue/insertvalue chains to extract only the values we need 1034 // to return and insert them into our new result. 1035 // This does generate messy code, but we'll let it to instcombine to 1036 // clean that up. 1037 Value *OldRet = RI->getOperand(0); 1038 // Start out building up our return value from undef 1039 RetVal = UndefValue::get(NRetTy); 1040 for (unsigned RetI = 0; RetI != RetCount; ++RetI) 1041 if (NewRetIdxs[RetI] != -1) { 1042 ExtractValueInst *EV = 1043 ExtractValueInst::Create(OldRet, RetI, "oldret", RI); 1044 if (RetTypes.size() > 1) { 1045 // We're still returning a struct, so reinsert the value into 1046 // our new return value at the new index 1047 1048 RetVal = InsertValueInst::Create(RetVal, EV, NewRetIdxs[RetI], 1049 "newret", RI); 1050 } else { 1051 // We are now only returning a simple value, so just return the 1052 // extracted value. 1053 RetVal = EV; 1054 } 1055 } 1056 } 1057 // Replace the return instruction with one returning the new return 1058 // value (possibly 0 if we became void). 1059 auto *NewRet = ReturnInst::Create(F->getContext(), RetVal, RI); 1060 NewRet->setDebugLoc(RI->getDebugLoc()); 1061 BB.getInstList().erase(RI); 1062 } 1063 1064 // Clone metadatas from the old function, including debug info descriptor. 1065 SmallVector<std::pair<unsigned, MDNode *>, 1> MDs; 1066 F->getAllMetadata(MDs); 1067 for (auto MD : MDs) 1068 NF->addMetadata(MD.first, *MD.second); 1069 1070 // Now that the old function is dead, delete it. 1071 F->eraseFromParent(); 1072 1073 return true; 1074 } 1075 1076 PreservedAnalyses DeadArgumentEliminationPass::run(Module &M, 1077 ModuleAnalysisManager &) { 1078 bool Changed = false; 1079 1080 // First pass: Do a simple check to see if any functions can have their "..." 1081 // removed. We can do this if they never call va_start. This loop cannot be 1082 // fused with the next loop, because deleting a function invalidates 1083 // information computed while surveying other functions. 1084 LLVM_DEBUG(dbgs() << "DeadArgumentEliminationPass - Deleting dead varargs\n"); 1085 for (Module::iterator I = M.begin(), E = M.end(); I != E; ) { 1086 Function &F = *I++; 1087 if (F.getFunctionType()->isVarArg()) 1088 Changed |= DeleteDeadVarargs(F); 1089 } 1090 1091 // Second phase:loop through the module, determining which arguments are live. 1092 // We assume all arguments are dead unless proven otherwise (allowing us to 1093 // determine that dead arguments passed into recursive functions are dead). 1094 // 1095 LLVM_DEBUG(dbgs() << "DeadArgumentEliminationPass - Determining liveness\n"); 1096 for (auto &F : M) 1097 SurveyFunction(F); 1098 1099 // Now, remove all dead arguments and return values from each function in 1100 // turn. 1101 for (Module::iterator I = M.begin(), E = M.end(); I != E; ) { 1102 // Increment now, because the function will probably get removed (ie. 1103 // replaced by a new one). 1104 Function *F = &*I++; 1105 Changed |= RemoveDeadStuffFromFunction(F); 1106 } 1107 1108 // Finally, look for any unused parameters in functions with non-local 1109 // linkage and replace the passed in parameters with undef. 1110 for (auto &F : M) 1111 Changed |= RemoveDeadArgumentsFromCallers(F); 1112 1113 if (!Changed) 1114 return PreservedAnalyses::all(); 1115 return PreservedAnalyses::none(); 1116 } 1117