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