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         ZExt->takeName(&Inst);
168         InsertedValues.insert(ZExt);
169         Inst.replaceAllUsesWith(ZExt);
170         Solver.removeLatticeValueFor(&Inst);
171         Inst.eraseFromParent();
172         InstReplacedStat++;
173         MadeChanges = true;
174       }
175     }
176   }
177   return MadeChanges;
178 }
179 
180 // runSCCP() - Run the Sparse Conditional Constant Propagation algorithm,
181 // and return true if the function was modified.
182 static bool runSCCP(Function &F, const DataLayout &DL,
183                     const TargetLibraryInfo *TLI) {
184   LLVM_DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n");
185   SCCPSolver Solver(
186       DL, [TLI](Function &F) -> const TargetLibraryInfo & { return *TLI; },
187       F.getContext());
188 
189   // Mark the first block of the function as being executable.
190   Solver.markBlockExecutable(&F.front());
191 
192   // Mark all arguments to the function as being overdefined.
193   for (Argument &AI : F.args())
194     Solver.markOverdefined(&AI);
195 
196   // Solve for constants.
197   bool ResolvedUndefs = true;
198   while (ResolvedUndefs) {
199     Solver.solve();
200     LLVM_DEBUG(dbgs() << "RESOLVING UNDEFs\n");
201     ResolvedUndefs = Solver.resolvedUndefsIn(F);
202   }
203 
204   bool MadeChanges = false;
205 
206   // If we decided that there are basic blocks that are dead in this function,
207   // delete their contents now.  Note that we cannot actually delete the blocks,
208   // as we cannot modify the CFG of the function.
209 
210   SmallPtrSet<Value *, 32> InsertedValues;
211   for (BasicBlock &BB : F) {
212     if (!Solver.isBlockExecutable(&BB)) {
213       LLVM_DEBUG(dbgs() << "  BasicBlock Dead:" << BB);
214 
215       ++NumDeadBlocks;
216       NumInstRemoved += removeAllNonTerminatorAndEHPadInstructions(&BB).first;
217 
218       MadeChanges = true;
219       continue;
220     }
221 
222     MadeChanges |= simplifyInstsInBlock(Solver, BB, InsertedValues,
223                                         NumInstRemoved, NumInstReplaced);
224   }
225 
226   return MadeChanges;
227 }
228 
229 PreservedAnalyses SCCPPass::run(Function &F, FunctionAnalysisManager &AM) {
230   const DataLayout &DL = F.getParent()->getDataLayout();
231   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
232   if (!runSCCP(F, DL, &TLI))
233     return PreservedAnalyses::all();
234 
235   auto PA = PreservedAnalyses();
236   PA.preserveSet<CFGAnalyses>();
237   return PA;
238 }
239 
240 namespace {
241 
242 //===--------------------------------------------------------------------===//
243 //
244 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
245 /// Sparse Conditional Constant Propagator.
246 ///
247 class SCCPLegacyPass : public FunctionPass {
248 public:
249   // Pass identification, replacement for typeid
250   static char ID;
251 
252   SCCPLegacyPass() : FunctionPass(ID) {
253     initializeSCCPLegacyPassPass(*PassRegistry::getPassRegistry());
254   }
255 
256   void getAnalysisUsage(AnalysisUsage &AU) const override {
257     AU.addRequired<TargetLibraryInfoWrapperPass>();
258     AU.addPreserved<GlobalsAAWrapperPass>();
259     AU.setPreservesCFG();
260   }
261 
262   // runOnFunction - Run the Sparse Conditional Constant Propagation
263   // algorithm, and return true if the function was modified.
264   bool runOnFunction(Function &F) override {
265     if (skipFunction(F))
266       return false;
267     const DataLayout &DL = F.getParent()->getDataLayout();
268     const TargetLibraryInfo *TLI =
269         &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
270     return runSCCP(F, DL, TLI);
271   }
272 };
273 
274 } // end anonymous namespace
275 
276 char SCCPLegacyPass::ID = 0;
277 
278 INITIALIZE_PASS_BEGIN(SCCPLegacyPass, "sccp",
279                       "Sparse Conditional Constant Propagation", false, false)
280 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
281 INITIALIZE_PASS_END(SCCPLegacyPass, "sccp",
282                     "Sparse Conditional Constant Propagation", false, false)
283 
284 // createSCCPPass - This is the public interface to this file.
285 FunctionPass *llvm::createSCCPPass() { return new SCCPLegacyPass(); }
286 
287 static void findReturnsToZap(Function &F,
288                              SmallVector<ReturnInst *, 8> &ReturnsToZap,
289                              SCCPSolver &Solver) {
290   // We can only do this if we know that nothing else can call the function.
291   if (!Solver.isArgumentTrackedFunction(&F))
292     return;
293 
294   if (Solver.mustPreserveReturn(&F)) {
295     LLVM_DEBUG(
296         dbgs()
297         << "Can't zap returns of the function : " << F.getName()
298         << " due to present musttail or \"clang.arc.attachedcall\" call of "
299            "it\n");
300     return;
301   }
302 
303   assert(
304       all_of(F.users(),
305              [&Solver](User *U) {
306                if (isa<Instruction>(U) &&
307                    !Solver.isBlockExecutable(cast<Instruction>(U)->getParent()))
308                  return true;
309                // Non-callsite uses are not impacted by zapping. Also, constant
310                // uses (like blockaddresses) could stuck around, without being
311                // used in the underlying IR, meaning we do not have lattice
312                // values for them.
313                if (!isa<CallBase>(U))
314                  return true;
315                if (U->getType()->isStructTy()) {
316                  return all_of(Solver.getStructLatticeValueFor(U),
317                                [](const ValueLatticeElement &LV) {
318                                  return !isOverdefined(LV);
319                                });
320                }
321                return !isOverdefined(Solver.getLatticeValueFor(U));
322              }) &&
323       "We can only zap functions where all live users have a concrete value");
324 
325   for (BasicBlock &BB : F) {
326     if (CallInst *CI = BB.getTerminatingMustTailCall()) {
327       LLVM_DEBUG(dbgs() << "Can't zap return of the block due to present "
328                         << "musttail call : " << *CI << "\n");
329       (void)CI;
330       return;
331     }
332 
333     if (auto *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
334       if (!isa<UndefValue>(RI->getOperand(0)))
335         ReturnsToZap.push_back(RI);
336   }
337 }
338 
339 static bool removeNonFeasibleEdges(const SCCPSolver &Solver, BasicBlock *BB,
340                                    DomTreeUpdater &DTU,
341                                    BasicBlock *&NewUnreachableBB) {
342   SmallPtrSet<BasicBlock *, 8> FeasibleSuccessors;
343   bool HasNonFeasibleEdges = false;
344   for (BasicBlock *Succ : successors(BB)) {
345     if (Solver.isEdgeFeasible(BB, Succ))
346       FeasibleSuccessors.insert(Succ);
347     else
348       HasNonFeasibleEdges = true;
349   }
350 
351   // All edges feasible, nothing to do.
352   if (!HasNonFeasibleEdges)
353     return false;
354 
355   // SCCP can only determine non-feasible edges for br, switch and indirectbr.
356   Instruction *TI = BB->getTerminator();
357   assert((isa<BranchInst>(TI) || isa<SwitchInst>(TI) ||
358           isa<IndirectBrInst>(TI)) &&
359          "Terminator must be a br, switch or indirectbr");
360 
361   if (FeasibleSuccessors.size() == 1) {
362     // Replace with an unconditional branch to the only feasible successor.
363     BasicBlock *OnlyFeasibleSuccessor = *FeasibleSuccessors.begin();
364     SmallVector<DominatorTree::UpdateType, 8> Updates;
365     bool HaveSeenOnlyFeasibleSuccessor = false;
366     for (BasicBlock *Succ : successors(BB)) {
367       if (Succ == OnlyFeasibleSuccessor && !HaveSeenOnlyFeasibleSuccessor) {
368         // Don't remove the edge to the only feasible successor the first time
369         // we see it. We still do need to remove any multi-edges to it though.
370         HaveSeenOnlyFeasibleSuccessor = true;
371         continue;
372       }
373 
374       Succ->removePredecessor(BB);
375       Updates.push_back({DominatorTree::Delete, BB, Succ});
376     }
377 
378     BranchInst::Create(OnlyFeasibleSuccessor, BB);
379     TI->eraseFromParent();
380     DTU.applyUpdatesPermissive(Updates);
381   } else if (FeasibleSuccessors.size() > 1) {
382     SwitchInstProfUpdateWrapper SI(*cast<SwitchInst>(TI));
383     SmallVector<DominatorTree::UpdateType, 8> Updates;
384 
385     // If the default destination is unfeasible it will never be taken. Replace
386     // it with a new block with a single Unreachable instruction.
387     BasicBlock *DefaultDest = SI->getDefaultDest();
388     if (!FeasibleSuccessors.contains(DefaultDest)) {
389       if (!NewUnreachableBB) {
390         NewUnreachableBB =
391             BasicBlock::Create(DefaultDest->getContext(), "default.unreachable",
392                                DefaultDest->getParent(), DefaultDest);
393         new UnreachableInst(DefaultDest->getContext(), NewUnreachableBB);
394       }
395 
396       SI->setDefaultDest(NewUnreachableBB);
397       Updates.push_back({DominatorTree::Delete, BB, DefaultDest});
398       Updates.push_back({DominatorTree::Insert, BB, NewUnreachableBB});
399     }
400 
401     for (auto CI = SI->case_begin(); CI != SI->case_end();) {
402       if (FeasibleSuccessors.contains(CI->getCaseSuccessor())) {
403         ++CI;
404         continue;
405       }
406 
407       BasicBlock *Succ = CI->getCaseSuccessor();
408       Succ->removePredecessor(BB);
409       Updates.push_back({DominatorTree::Delete, BB, Succ});
410       SI.removeCase(CI);
411       // Don't increment CI, as we removed a case.
412     }
413 
414     DTU.applyUpdatesPermissive(Updates);
415   } else {
416     llvm_unreachable("Must have at least one feasible successor");
417   }
418   return true;
419 }
420 
421 bool llvm::runIPSCCP(
422     Module &M, const DataLayout &DL,
423     std::function<const TargetLibraryInfo &(Function &)> GetTLI,
424     function_ref<AnalysisResultsForFn(Function &)> getAnalysis) {
425   SCCPSolver Solver(DL, GetTLI, M.getContext());
426 
427   // Loop over all functions, marking arguments to those with their addresses
428   // taken or that are external as overdefined.
429   for (Function &F : M) {
430     if (F.isDeclaration())
431       continue;
432 
433     Solver.addAnalysis(F, getAnalysis(F));
434 
435     // Determine if we can track the function's return values. If so, add the
436     // function to the solver's set of return-tracked functions.
437     if (canTrackReturnsInterprocedurally(&F))
438       Solver.addTrackedFunction(&F);
439 
440     // Determine if we can track the function's arguments. If so, add the
441     // function to the solver's set of argument-tracked functions.
442     if (canTrackArgumentsInterprocedurally(&F)) {
443       Solver.addArgumentTrackedFunction(&F);
444       continue;
445     }
446 
447     // Assume the function is called.
448     Solver.markBlockExecutable(&F.front());
449 
450     // Assume nothing about the incoming arguments.
451     for (Argument &AI : F.args())
452       Solver.markOverdefined(&AI);
453   }
454 
455   // Determine if we can track any of the module's global variables. If so, add
456   // the global variables we can track to the solver's set of tracked global
457   // variables.
458   for (GlobalVariable &G : M.globals()) {
459     G.removeDeadConstantUsers();
460     if (canTrackGlobalVariableInterprocedurally(&G))
461       Solver.trackValueOfGlobalVariable(&G);
462   }
463 
464   // Solve for constants.
465   bool ResolvedUndefs = true;
466   Solver.solve();
467   while (ResolvedUndefs) {
468     LLVM_DEBUG(dbgs() << "RESOLVING UNDEFS\n");
469     ResolvedUndefs = false;
470     for (Function &F : M) {
471       if (Solver.resolvedUndefsIn(F))
472         ResolvedUndefs = true;
473     }
474     if (ResolvedUndefs)
475       Solver.solve();
476   }
477 
478   bool MadeChanges = false;
479 
480   // Iterate over all of the instructions in the module, replacing them with
481   // constants if we have found them to be of constant values.
482 
483   for (Function &F : M) {
484     if (F.isDeclaration())
485       continue;
486 
487     SmallVector<BasicBlock *, 512> BlocksToErase;
488 
489     if (Solver.isBlockExecutable(&F.front())) {
490       bool ReplacedPointerArg = false;
491       for (Argument &Arg : F.args()) {
492         if (!Arg.use_empty() && tryToReplaceWithConstant(Solver, &Arg)) {
493           ReplacedPointerArg |= Arg.getType()->isPointerTy();
494           ++IPNumArgsElimed;
495         }
496       }
497 
498       // If we replaced an argument, the argmemonly and
499       // inaccessiblemem_or_argmemonly attributes do not hold any longer. Remove
500       // them from both the function and callsites.
501       if (ReplacedPointerArg) {
502         AttributeMask AttributesToRemove;
503         AttributesToRemove.addAttribute(Attribute::ArgMemOnly);
504         AttributesToRemove.addAttribute(Attribute::InaccessibleMemOrArgMemOnly);
505         F.removeFnAttrs(AttributesToRemove);
506 
507         for (User *U : F.users()) {
508           auto *CB = dyn_cast<CallBase>(U);
509           if (!CB || CB->getCalledFunction() != &F)
510             continue;
511 
512           CB->removeFnAttrs(AttributesToRemove);
513         }
514       }
515       MadeChanges |= ReplacedPointerArg;
516     }
517 
518     SmallPtrSet<Value *, 32> InsertedValues;
519     for (BasicBlock &BB : F) {
520       if (!Solver.isBlockExecutable(&BB)) {
521         LLVM_DEBUG(dbgs() << "  BasicBlock Dead:" << BB);
522         ++NumDeadBlocks;
523 
524         MadeChanges = true;
525 
526         if (&BB != &F.front())
527           BlocksToErase.push_back(&BB);
528         continue;
529       }
530 
531       MadeChanges |= simplifyInstsInBlock(Solver, BB, InsertedValues,
532                                           IPNumInstRemoved, IPNumInstReplaced);
533     }
534 
535     DomTreeUpdater DTU = Solver.getDTU(F);
536     // Change dead blocks to unreachable. We do it after replacing constants
537     // in all executable blocks, because changeToUnreachable may remove PHI
538     // nodes in executable blocks we found values for. The function's entry
539     // block is not part of BlocksToErase, so we have to handle it separately.
540     for (BasicBlock *BB : BlocksToErase) {
541       NumInstRemoved += changeToUnreachable(BB->getFirstNonPHI(),
542                                             /*PreserveLCSSA=*/false, &DTU);
543     }
544     if (!Solver.isBlockExecutable(&F.front()))
545       NumInstRemoved += changeToUnreachable(F.front().getFirstNonPHI(),
546                                             /*PreserveLCSSA=*/false, &DTU);
547 
548     BasicBlock *NewUnreachableBB = nullptr;
549     for (BasicBlock &BB : F)
550       MadeChanges |= removeNonFeasibleEdges(Solver, &BB, DTU, NewUnreachableBB);
551 
552     for (BasicBlock *DeadBB : BlocksToErase)
553       if (!DeadBB->hasAddressTaken())
554         DTU.deleteBB(DeadBB);
555 
556     for (BasicBlock &BB : F) {
557       for (Instruction &Inst : llvm::make_early_inc_range(BB)) {
558         if (Solver.getPredicateInfoFor(&Inst)) {
559           if (auto *II = dyn_cast<IntrinsicInst>(&Inst)) {
560             if (II->getIntrinsicID() == Intrinsic::ssa_copy) {
561               Value *Op = II->getOperand(0);
562               Inst.replaceAllUsesWith(Op);
563               Inst.eraseFromParent();
564             }
565           }
566         }
567       }
568     }
569   }
570 
571   // If we inferred constant or undef return values for a function, we replaced
572   // all call uses with the inferred value.  This means we don't need to bother
573   // actually returning anything from the function.  Replace all return
574   // instructions with return undef.
575   //
576   // Do this in two stages: first identify the functions we should process, then
577   // actually zap their returns.  This is important because we can only do this
578   // if the address of the function isn't taken.  In cases where a return is the
579   // last use of a function, the order of processing functions would affect
580   // whether other functions are optimizable.
581   SmallVector<ReturnInst*, 8> ReturnsToZap;
582 
583   for (const auto &I : Solver.getTrackedRetVals()) {
584     Function *F = I.first;
585     const ValueLatticeElement &ReturnValue = I.second;
586 
587     // If there is a known constant range for the return value, add !range
588     // metadata to the function's call sites.
589     if (ReturnValue.isConstantRange() &&
590         !ReturnValue.getConstantRange().isSingleElement()) {
591       // Do not add range metadata if the return value may include undef.
592       if (ReturnValue.isConstantRangeIncludingUndef())
593         continue;
594 
595       auto &CR = ReturnValue.getConstantRange();
596       for (User *User : F->users()) {
597         auto *CB = dyn_cast<CallBase>(User);
598         if (!CB || CB->getCalledFunction() != F)
599           continue;
600 
601         // Limit to cases where the return value is guaranteed to be neither
602         // poison nor undef. Poison will be outside any range and currently
603         // values outside of the specified range cause immediate undefined
604         // behavior.
605         if (!isGuaranteedNotToBeUndefOrPoison(CB, nullptr, CB))
606           continue;
607 
608         // Do not touch existing metadata for now.
609         // TODO: We should be able to take the intersection of the existing
610         // metadata and the inferred range.
611         if (CB->getMetadata(LLVMContext::MD_range))
612           continue;
613 
614         LLVMContext &Context = CB->getParent()->getContext();
615         Metadata *RangeMD[] = {
616             ConstantAsMetadata::get(ConstantInt::get(Context, CR.getLower())),
617             ConstantAsMetadata::get(ConstantInt::get(Context, CR.getUpper()))};
618         CB->setMetadata(LLVMContext::MD_range, MDNode::get(Context, RangeMD));
619       }
620       continue;
621     }
622     if (F->getReturnType()->isVoidTy())
623       continue;
624     if (isConstant(ReturnValue) || ReturnValue.isUnknownOrUndef())
625       findReturnsToZap(*F, ReturnsToZap, Solver);
626   }
627 
628   for (auto F : Solver.getMRVFunctionsTracked()) {
629     assert(F->getReturnType()->isStructTy() &&
630            "The return type should be a struct");
631     StructType *STy = cast<StructType>(F->getReturnType());
632     if (Solver.isStructLatticeConstant(F, STy))
633       findReturnsToZap(*F, ReturnsToZap, Solver);
634   }
635 
636   // Zap all returns which we've identified as zap to change.
637   SmallSetVector<Function *, 8> FuncZappedReturn;
638   for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) {
639     Function *F = ReturnsToZap[i]->getParent()->getParent();
640     ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType()));
641     // Record all functions that are zapped.
642     FuncZappedReturn.insert(F);
643   }
644 
645   // Remove the returned attribute for zapped functions and the
646   // corresponding call sites.
647   for (Function *F : FuncZappedReturn) {
648     for (Argument &A : F->args())
649       F->removeParamAttr(A.getArgNo(), Attribute::Returned);
650     for (Use &U : F->uses()) {
651       // Skip over blockaddr users.
652       if (isa<BlockAddress>(U.getUser()))
653         continue;
654       CallBase *CB = cast<CallBase>(U.getUser());
655       for (Use &Arg : CB->args())
656         CB->removeParamAttr(CB->getArgOperandNo(&Arg), Attribute::Returned);
657     }
658   }
659 
660   // If we inferred constant or undef values for globals variables, we can
661   // delete the global and any stores that remain to it.
662   for (auto &I : make_early_inc_range(Solver.getTrackedGlobals())) {
663     GlobalVariable *GV = I.first;
664     if (isOverdefined(I.second))
665       continue;
666     LLVM_DEBUG(dbgs() << "Found that GV '" << GV->getName()
667                       << "' is constant!\n");
668     while (!GV->use_empty()) {
669       StoreInst *SI = cast<StoreInst>(GV->user_back());
670       SI->eraseFromParent();
671       MadeChanges = true;
672     }
673     M.getGlobalList().erase(GV);
674     ++IPNumGlobalConst;
675   }
676 
677   return MadeChanges;
678 }
679