1 //===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements sparse conditional constant propagation and merging: 10 // 11 // Specifically, this: 12 // * Assumes values are constant unless proven otherwise 13 // * Assumes BasicBlocks are dead unless proven otherwise 14 // * Proves values to be constant, and replaces them with constants 15 // * Proves conditional branches to be unconditional 16 // 17 //===----------------------------------------------------------------------===// 18 19 #include "llvm/Transforms/Scalar/SCCP.h" 20 #include "llvm/ADT/DenseMap.h" 21 #include "llvm/ADT/MapVector.h" 22 #include "llvm/ADT/STLExtras.h" 23 #include "llvm/ADT/SetVector.h" 24 #include "llvm/ADT/SmallPtrSet.h" 25 #include "llvm/ADT/SmallVector.h" 26 #include "llvm/ADT/Statistic.h" 27 #include "llvm/Analysis/DomTreeUpdater.h" 28 #include "llvm/Analysis/GlobalsModRef.h" 29 #include "llvm/Analysis/TargetLibraryInfo.h" 30 #include "llvm/Analysis/ValueLattice.h" 31 #include "llvm/Analysis/ValueLatticeUtils.h" 32 #include "llvm/Analysis/ValueTracking.h" 33 #include "llvm/IR/BasicBlock.h" 34 #include "llvm/IR/Constant.h" 35 #include "llvm/IR/Constants.h" 36 #include "llvm/IR/DerivedTypes.h" 37 #include "llvm/IR/Function.h" 38 #include "llvm/IR/GlobalVariable.h" 39 #include "llvm/IR/InstrTypes.h" 40 #include "llvm/IR/Instruction.h" 41 #include "llvm/IR/Instructions.h" 42 #include "llvm/IR/IntrinsicInst.h" 43 #include "llvm/IR/Module.h" 44 #include "llvm/IR/PassManager.h" 45 #include "llvm/IR/Type.h" 46 #include "llvm/IR/User.h" 47 #include "llvm/IR/Value.h" 48 #include "llvm/InitializePasses.h" 49 #include "llvm/Pass.h" 50 #include "llvm/Support/Casting.h" 51 #include "llvm/Support/Debug.h" 52 #include "llvm/Support/ErrorHandling.h" 53 #include "llvm/Support/raw_ostream.h" 54 #include "llvm/Transforms/Scalar.h" 55 #include "llvm/Transforms/Utils/Local.h" 56 #include "llvm/Transforms/Utils/SCCPSolver.h" 57 #include <cassert> 58 #include <utility> 59 #include <vector> 60 61 using namespace llvm; 62 63 #define DEBUG_TYPE "sccp" 64 65 STATISTIC(NumInstRemoved, "Number of instructions removed"); 66 STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable"); 67 STATISTIC(NumInstReplaced, 68 "Number of instructions replaced with (simpler) instruction"); 69 70 STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP"); 71 STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP"); 72 STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP"); 73 STATISTIC( 74 IPNumInstReplaced, 75 "Number of instructions replaced with (simpler) instruction by IPSCCP"); 76 77 // Helper to check if \p LV is either a constant or a constant 78 // range with a single element. This should cover exactly the same cases as the 79 // old ValueLatticeElement::isConstant() and is intended to be used in the 80 // transition to ValueLatticeElement. 81 static bool isConstant(const ValueLatticeElement &LV) { 82 return LV.isConstant() || 83 (LV.isConstantRange() && LV.getConstantRange().isSingleElement()); 84 } 85 86 // Helper to check if \p LV is either overdefined or a constant range with more 87 // than a single element. This should cover exactly the same cases as the old 88 // ValueLatticeElement::isOverdefined() and is intended to be used in the 89 // transition to ValueLatticeElement. 90 static bool isOverdefined(const ValueLatticeElement &LV) { 91 return !LV.isUnknownOrUndef() && !isConstant(LV); 92 } 93 94 static bool tryToReplaceWithConstant(SCCPSolver &Solver, Value *V) { 95 Constant *Const = nullptr; 96 if (V->getType()->isStructTy()) { 97 std::vector<ValueLatticeElement> IVs = Solver.getStructLatticeValueFor(V); 98 if (llvm::any_of(IVs, isOverdefined)) 99 return false; 100 std::vector<Constant *> ConstVals; 101 auto *ST = cast<StructType>(V->getType()); 102 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) { 103 ValueLatticeElement V = IVs[i]; 104 ConstVals.push_back(isConstant(V) 105 ? Solver.getConstant(V) 106 : UndefValue::get(ST->getElementType(i))); 107 } 108 Const = ConstantStruct::get(ST, ConstVals); 109 } else { 110 const ValueLatticeElement &IV = Solver.getLatticeValueFor(V); 111 if (isOverdefined(IV)) 112 return false; 113 114 Const = 115 isConstant(IV) ? Solver.getConstant(IV) : UndefValue::get(V->getType()); 116 } 117 assert(Const && "Constant is nullptr here!"); 118 119 // Replacing `musttail` instructions with constant breaks `musttail` invariant 120 // unless the call itself can be removed. 121 // Calls with "clang.arc.attachedcall" implicitly use the return value and 122 // those uses cannot be updated with a constant. 123 CallBase *CB = dyn_cast<CallBase>(V); 124 if (CB && ((CB->isMustTailCall() && !CB->isSafeToRemove()) || 125 CB->getOperandBundle(LLVMContext::OB_clang_arc_attachedcall))) { 126 Function *F = CB->getCalledFunction(); 127 128 // Don't zap returns of the callee 129 if (F) 130 Solver.addToMustPreserveReturnsInFunctions(F); 131 132 LLVM_DEBUG(dbgs() << " Can\'t treat the result of call " << *CB 133 << " as a constant\n"); 134 return false; 135 } 136 137 LLVM_DEBUG(dbgs() << " Constant: " << *Const << " = " << *V << '\n'); 138 139 // Replaces all of the uses of a variable with uses of the constant. 140 V->replaceAllUsesWith(Const); 141 return true; 142 } 143 144 static bool simplifyInstsInBlock(SCCPSolver &Solver, BasicBlock &BB, 145 SmallPtrSetImpl<Value *> &InsertedValues, 146 Statistic &InstRemovedStat, 147 Statistic &InstReplacedStat) { 148 bool MadeChanges = false; 149 for (Instruction &Inst : make_early_inc_range(BB)) { 150 if (Inst.getType()->isVoidTy()) 151 continue; 152 if (tryToReplaceWithConstant(Solver, &Inst)) { 153 if (Inst.isSafeToRemove()) 154 Inst.eraseFromParent(); 155 156 MadeChanges = true; 157 ++InstRemovedStat; 158 } else if (isa<SExtInst>(&Inst)) { 159 Value *ExtOp = Inst.getOperand(0); 160 if (isa<Constant>(ExtOp) || InsertedValues.count(ExtOp)) 161 continue; 162 const ValueLatticeElement &IV = Solver.getLatticeValueFor(ExtOp); 163 if (!IV.isConstantRange(/*UndefAllowed=*/false)) 164 continue; 165 if (IV.getConstantRange().isAllNonNegative()) { 166 auto *ZExt = new ZExtInst(ExtOp, Inst.getType(), "", &Inst); 167 InsertedValues.insert(ZExt); 168 Inst.replaceAllUsesWith(ZExt); 169 Solver.removeLatticeValueFor(&Inst); 170 Inst.eraseFromParent(); 171 InstReplacedStat++; 172 MadeChanges = true; 173 } 174 } 175 } 176 return MadeChanges; 177 } 178 179 // runSCCP() - Run the Sparse Conditional Constant Propagation algorithm, 180 // and return true if the function was modified. 181 static bool runSCCP(Function &F, const DataLayout &DL, 182 const TargetLibraryInfo *TLI) { 183 LLVM_DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n"); 184 SCCPSolver Solver( 185 DL, [TLI](Function &F) -> const TargetLibraryInfo & { return *TLI; }, 186 F.getContext()); 187 188 // Mark the first block of the function as being executable. 189 Solver.markBlockExecutable(&F.front()); 190 191 // Mark all arguments to the function as being overdefined. 192 for (Argument &AI : F.args()) 193 Solver.markOverdefined(&AI); 194 195 // Solve for constants. 196 bool ResolvedUndefs = true; 197 while (ResolvedUndefs) { 198 Solver.solve(); 199 LLVM_DEBUG(dbgs() << "RESOLVING UNDEFs\n"); 200 ResolvedUndefs = Solver.resolvedUndefsIn(F); 201 } 202 203 bool MadeChanges = false; 204 205 // If we decided that there are basic blocks that are dead in this function, 206 // delete their contents now. Note that we cannot actually delete the blocks, 207 // as we cannot modify the CFG of the function. 208 209 SmallPtrSet<Value *, 32> InsertedValues; 210 for (BasicBlock &BB : F) { 211 if (!Solver.isBlockExecutable(&BB)) { 212 LLVM_DEBUG(dbgs() << " BasicBlock Dead:" << BB); 213 214 ++NumDeadBlocks; 215 NumInstRemoved += removeAllNonTerminatorAndEHPadInstructions(&BB).first; 216 217 MadeChanges = true; 218 continue; 219 } 220 221 MadeChanges |= simplifyInstsInBlock(Solver, BB, InsertedValues, 222 NumInstRemoved, NumInstReplaced); 223 } 224 225 return MadeChanges; 226 } 227 228 PreservedAnalyses SCCPPass::run(Function &F, FunctionAnalysisManager &AM) { 229 const DataLayout &DL = F.getParent()->getDataLayout(); 230 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); 231 if (!runSCCP(F, DL, &TLI)) 232 return PreservedAnalyses::all(); 233 234 auto PA = PreservedAnalyses(); 235 PA.preserveSet<CFGAnalyses>(); 236 return PA; 237 } 238 239 namespace { 240 241 //===--------------------------------------------------------------------===// 242 // 243 /// SCCP Class - This class uses the SCCPSolver to implement a per-function 244 /// Sparse Conditional Constant Propagator. 245 /// 246 class SCCPLegacyPass : public FunctionPass { 247 public: 248 // Pass identification, replacement for typeid 249 static char ID; 250 251 SCCPLegacyPass() : FunctionPass(ID) { 252 initializeSCCPLegacyPassPass(*PassRegistry::getPassRegistry()); 253 } 254 255 void getAnalysisUsage(AnalysisUsage &AU) const override { 256 AU.addRequired<TargetLibraryInfoWrapperPass>(); 257 AU.addPreserved<GlobalsAAWrapperPass>(); 258 AU.setPreservesCFG(); 259 } 260 261 // runOnFunction - Run the Sparse Conditional Constant Propagation 262 // algorithm, and return true if the function was modified. 263 bool runOnFunction(Function &F) override { 264 if (skipFunction(F)) 265 return false; 266 const DataLayout &DL = F.getParent()->getDataLayout(); 267 const TargetLibraryInfo *TLI = 268 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F); 269 return runSCCP(F, DL, TLI); 270 } 271 }; 272 273 } // end anonymous namespace 274 275 char SCCPLegacyPass::ID = 0; 276 277 INITIALIZE_PASS_BEGIN(SCCPLegacyPass, "sccp", 278 "Sparse Conditional Constant Propagation", false, false) 279 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 280 INITIALIZE_PASS_END(SCCPLegacyPass, "sccp", 281 "Sparse Conditional Constant Propagation", false, false) 282 283 // createSCCPPass - This is the public interface to this file. 284 FunctionPass *llvm::createSCCPPass() { return new SCCPLegacyPass(); } 285 286 static void findReturnsToZap(Function &F, 287 SmallVector<ReturnInst *, 8> &ReturnsToZap, 288 SCCPSolver &Solver) { 289 // We can only do this if we know that nothing else can call the function. 290 if (!Solver.isArgumentTrackedFunction(&F)) 291 return; 292 293 if (Solver.mustPreserveReturn(&F)) { 294 LLVM_DEBUG( 295 dbgs() 296 << "Can't zap returns of the function : " << F.getName() 297 << " due to present musttail or \"clang.arc.attachedcall\" call of " 298 "it\n"); 299 return; 300 } 301 302 assert( 303 all_of(F.users(), 304 [&Solver](User *U) { 305 if (isa<Instruction>(U) && 306 !Solver.isBlockExecutable(cast<Instruction>(U)->getParent())) 307 return true; 308 // Non-callsite uses are not impacted by zapping. Also, constant 309 // uses (like blockaddresses) could stuck around, without being 310 // used in the underlying IR, meaning we do not have lattice 311 // values for them. 312 if (!isa<CallBase>(U)) 313 return true; 314 if (U->getType()->isStructTy()) { 315 return all_of(Solver.getStructLatticeValueFor(U), 316 [](const ValueLatticeElement &LV) { 317 return !isOverdefined(LV); 318 }); 319 } 320 return !isOverdefined(Solver.getLatticeValueFor(U)); 321 }) && 322 "We can only zap functions where all live users have a concrete value"); 323 324 for (BasicBlock &BB : F) { 325 if (CallInst *CI = BB.getTerminatingMustTailCall()) { 326 LLVM_DEBUG(dbgs() << "Can't zap return of the block due to present " 327 << "musttail call : " << *CI << "\n"); 328 (void)CI; 329 return; 330 } 331 332 if (auto *RI = dyn_cast<ReturnInst>(BB.getTerminator())) 333 if (!isa<UndefValue>(RI->getOperand(0))) 334 ReturnsToZap.push_back(RI); 335 } 336 } 337 338 static bool removeNonFeasibleEdges(const SCCPSolver &Solver, BasicBlock *BB, 339 DomTreeUpdater &DTU, 340 BasicBlock *&NewUnreachableBB) { 341 SmallPtrSet<BasicBlock *, 8> FeasibleSuccessors; 342 bool HasNonFeasibleEdges = false; 343 for (BasicBlock *Succ : successors(BB)) { 344 if (Solver.isEdgeFeasible(BB, Succ)) 345 FeasibleSuccessors.insert(Succ); 346 else 347 HasNonFeasibleEdges = true; 348 } 349 350 // All edges feasible, nothing to do. 351 if (!HasNonFeasibleEdges) 352 return false; 353 354 // SCCP can only determine non-feasible edges for br, switch and indirectbr. 355 Instruction *TI = BB->getTerminator(); 356 assert((isa<BranchInst>(TI) || isa<SwitchInst>(TI) || 357 isa<IndirectBrInst>(TI)) && 358 "Terminator must be a br, switch or indirectbr"); 359 360 if (FeasibleSuccessors.size() == 1) { 361 // Replace with an unconditional branch to the only feasible successor. 362 BasicBlock *OnlyFeasibleSuccessor = *FeasibleSuccessors.begin(); 363 SmallVector<DominatorTree::UpdateType, 8> Updates; 364 bool HaveSeenOnlyFeasibleSuccessor = false; 365 for (BasicBlock *Succ : successors(BB)) { 366 if (Succ == OnlyFeasibleSuccessor && !HaveSeenOnlyFeasibleSuccessor) { 367 // Don't remove the edge to the only feasible successor the first time 368 // we see it. We still do need to remove any multi-edges to it though. 369 HaveSeenOnlyFeasibleSuccessor = true; 370 continue; 371 } 372 373 Succ->removePredecessor(BB); 374 Updates.push_back({DominatorTree::Delete, BB, Succ}); 375 } 376 377 BranchInst::Create(OnlyFeasibleSuccessor, BB); 378 TI->eraseFromParent(); 379 DTU.applyUpdatesPermissive(Updates); 380 } else if (FeasibleSuccessors.size() > 1) { 381 SwitchInstProfUpdateWrapper SI(*cast<SwitchInst>(TI)); 382 SmallVector<DominatorTree::UpdateType, 8> Updates; 383 384 // If the default destination is unfeasible it will never be taken. Replace 385 // it with a new block with a single Unreachable instruction. 386 BasicBlock *DefaultDest = SI->getDefaultDest(); 387 if (!FeasibleSuccessors.contains(DefaultDest)) { 388 if (!NewUnreachableBB) { 389 NewUnreachableBB = 390 BasicBlock::Create(DefaultDest->getContext(), "default.unreachable", 391 DefaultDest->getParent(), DefaultDest); 392 new UnreachableInst(DefaultDest->getContext(), NewUnreachableBB); 393 } 394 395 SI->setDefaultDest(NewUnreachableBB); 396 Updates.push_back({DominatorTree::Delete, BB, DefaultDest}); 397 Updates.push_back({DominatorTree::Insert, BB, NewUnreachableBB}); 398 } 399 400 for (auto CI = SI->case_begin(); CI != SI->case_end();) { 401 if (FeasibleSuccessors.contains(CI->getCaseSuccessor())) { 402 ++CI; 403 continue; 404 } 405 406 BasicBlock *Succ = CI->getCaseSuccessor(); 407 Succ->removePredecessor(BB); 408 Updates.push_back({DominatorTree::Delete, BB, Succ}); 409 SI.removeCase(CI); 410 // Don't increment CI, as we removed a case. 411 } 412 413 DTU.applyUpdatesPermissive(Updates); 414 } else { 415 llvm_unreachable("Must have at least one feasible successor"); 416 } 417 return true; 418 } 419 420 bool llvm::runIPSCCP( 421 Module &M, const DataLayout &DL, 422 std::function<const TargetLibraryInfo &(Function &)> GetTLI, 423 function_ref<AnalysisResultsForFn(Function &)> getAnalysis) { 424 SCCPSolver Solver(DL, GetTLI, M.getContext()); 425 426 // Loop over all functions, marking arguments to those with their addresses 427 // taken or that are external as overdefined. 428 for (Function &F : M) { 429 if (F.isDeclaration()) 430 continue; 431 432 Solver.addAnalysis(F, getAnalysis(F)); 433 434 // Determine if we can track the function's return values. If so, add the 435 // function to the solver's set of return-tracked functions. 436 if (canTrackReturnsInterprocedurally(&F)) 437 Solver.addTrackedFunction(&F); 438 439 // Determine if we can track the function's arguments. If so, add the 440 // function to the solver's set of argument-tracked functions. 441 if (canTrackArgumentsInterprocedurally(&F)) { 442 Solver.addArgumentTrackedFunction(&F); 443 continue; 444 } 445 446 // Assume the function is called. 447 Solver.markBlockExecutable(&F.front()); 448 449 // Assume nothing about the incoming arguments. 450 for (Argument &AI : F.args()) 451 Solver.markOverdefined(&AI); 452 } 453 454 // Determine if we can track any of the module's global variables. If so, add 455 // the global variables we can track to the solver's set of tracked global 456 // variables. 457 for (GlobalVariable &G : M.globals()) { 458 G.removeDeadConstantUsers(); 459 if (canTrackGlobalVariableInterprocedurally(&G)) 460 Solver.trackValueOfGlobalVariable(&G); 461 } 462 463 // Solve for constants. 464 bool ResolvedUndefs = true; 465 Solver.solve(); 466 while (ResolvedUndefs) { 467 LLVM_DEBUG(dbgs() << "RESOLVING UNDEFS\n"); 468 ResolvedUndefs = false; 469 for (Function &F : M) { 470 if (Solver.resolvedUndefsIn(F)) 471 ResolvedUndefs = true; 472 } 473 if (ResolvedUndefs) 474 Solver.solve(); 475 } 476 477 bool MadeChanges = false; 478 479 // Iterate over all of the instructions in the module, replacing them with 480 // constants if we have found them to be of constant values. 481 482 for (Function &F : M) { 483 if (F.isDeclaration()) 484 continue; 485 486 SmallVector<BasicBlock *, 512> BlocksToErase; 487 488 if (Solver.isBlockExecutable(&F.front())) { 489 bool ReplacedPointerArg = false; 490 for (Argument &Arg : F.args()) { 491 if (!Arg.use_empty() && tryToReplaceWithConstant(Solver, &Arg)) { 492 ReplacedPointerArg |= Arg.getType()->isPointerTy(); 493 ++IPNumArgsElimed; 494 } 495 } 496 497 // If we replaced an argument, the argmemonly and 498 // inaccessiblemem_or_argmemonly attributes do not hold any longer. Remove 499 // them from both the function and callsites. 500 if (ReplacedPointerArg) { 501 AttributeMask AttributesToRemove; 502 AttributesToRemove.addAttribute(Attribute::ArgMemOnly); 503 AttributesToRemove.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); 504 F.removeFnAttrs(AttributesToRemove); 505 506 for (User *U : F.users()) { 507 auto *CB = dyn_cast<CallBase>(U); 508 if (!CB || CB->getCalledFunction() != &F) 509 continue; 510 511 CB->removeFnAttrs(AttributesToRemove); 512 } 513 } 514 MadeChanges |= ReplacedPointerArg; 515 } 516 517 SmallPtrSet<Value *, 32> InsertedValues; 518 for (BasicBlock &BB : F) { 519 if (!Solver.isBlockExecutable(&BB)) { 520 LLVM_DEBUG(dbgs() << " BasicBlock Dead:" << BB); 521 ++NumDeadBlocks; 522 523 MadeChanges = true; 524 525 if (&BB != &F.front()) 526 BlocksToErase.push_back(&BB); 527 continue; 528 } 529 530 MadeChanges |= simplifyInstsInBlock(Solver, BB, InsertedValues, 531 IPNumInstRemoved, IPNumInstReplaced); 532 } 533 534 DomTreeUpdater DTU = Solver.getDTU(F); 535 // Change dead blocks to unreachable. We do it after replacing constants 536 // in all executable blocks, because changeToUnreachable may remove PHI 537 // nodes in executable blocks we found values for. The function's entry 538 // block is not part of BlocksToErase, so we have to handle it separately. 539 for (BasicBlock *BB : BlocksToErase) { 540 NumInstRemoved += changeToUnreachable(BB->getFirstNonPHI(), 541 /*PreserveLCSSA=*/false, &DTU); 542 } 543 if (!Solver.isBlockExecutable(&F.front())) 544 NumInstRemoved += changeToUnreachable(F.front().getFirstNonPHI(), 545 /*PreserveLCSSA=*/false, &DTU); 546 547 BasicBlock *NewUnreachableBB = nullptr; 548 for (BasicBlock &BB : F) 549 MadeChanges |= removeNonFeasibleEdges(Solver, &BB, DTU, NewUnreachableBB); 550 551 for (BasicBlock *DeadBB : BlocksToErase) 552 if (!DeadBB->hasAddressTaken()) 553 DTU.deleteBB(DeadBB); 554 555 for (BasicBlock &BB : F) { 556 for (Instruction &Inst : llvm::make_early_inc_range(BB)) { 557 if (Solver.getPredicateInfoFor(&Inst)) { 558 if (auto *II = dyn_cast<IntrinsicInst>(&Inst)) { 559 if (II->getIntrinsicID() == Intrinsic::ssa_copy) { 560 Value *Op = II->getOperand(0); 561 Inst.replaceAllUsesWith(Op); 562 Inst.eraseFromParent(); 563 } 564 } 565 } 566 } 567 } 568 } 569 570 // If we inferred constant or undef return values for a function, we replaced 571 // all call uses with the inferred value. This means we don't need to bother 572 // actually returning anything from the function. Replace all return 573 // instructions with return undef. 574 // 575 // Do this in two stages: first identify the functions we should process, then 576 // actually zap their returns. This is important because we can only do this 577 // if the address of the function isn't taken. In cases where a return is the 578 // last use of a function, the order of processing functions would affect 579 // whether other functions are optimizable. 580 SmallVector<ReturnInst*, 8> ReturnsToZap; 581 582 for (const auto &I : Solver.getTrackedRetVals()) { 583 Function *F = I.first; 584 const ValueLatticeElement &ReturnValue = I.second; 585 586 // If there is a known constant range for the return value, add !range 587 // metadata to the function's call sites. 588 if (ReturnValue.isConstantRange() && 589 !ReturnValue.getConstantRange().isSingleElement()) { 590 // Do not add range metadata if the return value may include undef. 591 if (ReturnValue.isConstantRangeIncludingUndef()) 592 continue; 593 594 auto &CR = ReturnValue.getConstantRange(); 595 for (User *User : F->users()) { 596 auto *CB = dyn_cast<CallBase>(User); 597 if (!CB || CB->getCalledFunction() != F) 598 continue; 599 600 // Limit to cases where the return value is guaranteed to be neither 601 // poison nor undef. Poison will be outside any range and currently 602 // values outside of the specified range cause immediate undefined 603 // behavior. 604 if (!isGuaranteedNotToBeUndefOrPoison(CB, nullptr, CB)) 605 continue; 606 607 // Do not touch existing metadata for now. 608 // TODO: We should be able to take the intersection of the existing 609 // metadata and the inferred range. 610 if (CB->getMetadata(LLVMContext::MD_range)) 611 continue; 612 613 LLVMContext &Context = CB->getParent()->getContext(); 614 Metadata *RangeMD[] = { 615 ConstantAsMetadata::get(ConstantInt::get(Context, CR.getLower())), 616 ConstantAsMetadata::get(ConstantInt::get(Context, CR.getUpper()))}; 617 CB->setMetadata(LLVMContext::MD_range, MDNode::get(Context, RangeMD)); 618 } 619 continue; 620 } 621 if (F->getReturnType()->isVoidTy()) 622 continue; 623 if (isConstant(ReturnValue) || ReturnValue.isUnknownOrUndef()) 624 findReturnsToZap(*F, ReturnsToZap, Solver); 625 } 626 627 for (auto F : Solver.getMRVFunctionsTracked()) { 628 assert(F->getReturnType()->isStructTy() && 629 "The return type should be a struct"); 630 StructType *STy = cast<StructType>(F->getReturnType()); 631 if (Solver.isStructLatticeConstant(F, STy)) 632 findReturnsToZap(*F, ReturnsToZap, Solver); 633 } 634 635 // Zap all returns which we've identified as zap to change. 636 SmallSetVector<Function *, 8> FuncZappedReturn; 637 for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) { 638 Function *F = ReturnsToZap[i]->getParent()->getParent(); 639 ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType())); 640 // Record all functions that are zapped. 641 FuncZappedReturn.insert(F); 642 } 643 644 // Remove the returned attribute for zapped functions and the 645 // corresponding call sites. 646 for (Function *F : FuncZappedReturn) { 647 for (Argument &A : F->args()) 648 F->removeParamAttr(A.getArgNo(), Attribute::Returned); 649 for (Use &U : F->uses()) { 650 // Skip over blockaddr users. 651 if (isa<BlockAddress>(U.getUser())) 652 continue; 653 CallBase *CB = cast<CallBase>(U.getUser()); 654 for (Use &Arg : CB->args()) 655 CB->removeParamAttr(CB->getArgOperandNo(&Arg), Attribute::Returned); 656 } 657 } 658 659 // If we inferred constant or undef values for globals variables, we can 660 // delete the global and any stores that remain to it. 661 for (auto &I : make_early_inc_range(Solver.getTrackedGlobals())) { 662 GlobalVariable *GV = I.first; 663 if (isOverdefined(I.second)) 664 continue; 665 LLVM_DEBUG(dbgs() << "Found that GV '" << GV->getName() 666 << "' is constant!\n"); 667 while (!GV->use_empty()) { 668 StoreInst *SI = cast<StoreInst>(GV->user_back()); 669 SI->eraseFromParent(); 670 MadeChanges = true; 671 } 672 M.getGlobalList().erase(GV); 673 ++IPNumGlobalConst; 674 } 675 676 return MadeChanges; 677 } 678