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   SmallPtrSet<BasicBlock *, 8> FeasibleSuccessors;
341   bool HasNonFeasibleEdges = false;
342   for (BasicBlock *Succ : successors(BB)) {
343     if (Solver.isEdgeFeasible(BB, Succ))
344       FeasibleSuccessors.insert(Succ);
345     else
346       HasNonFeasibleEdges = true;
347   }
348 
349   // All edges feasible, nothing to do.
350   if (!HasNonFeasibleEdges)
351     return false;
352 
353   // SCCP can only determine non-feasible edges for br, switch and indirectbr.
354   Instruction *TI = BB->getTerminator();
355   assert((isa<BranchInst>(TI) || isa<SwitchInst>(TI) ||
356           isa<IndirectBrInst>(TI)) &&
357          "Terminator must be a br, switch or indirectbr");
358 
359   if (FeasibleSuccessors.size() == 1) {
360     // Replace with an unconditional branch to the only feasible successor.
361     BasicBlock *OnlyFeasibleSuccessor = *FeasibleSuccessors.begin();
362     SmallVector<DominatorTree::UpdateType, 8> Updates;
363     bool HaveSeenOnlyFeasibleSuccessor = false;
364     for (BasicBlock *Succ : successors(BB)) {
365       if (Succ == OnlyFeasibleSuccessor && !HaveSeenOnlyFeasibleSuccessor) {
366         // Don't remove the edge to the only feasible successor the first time
367         // we see it. We still do need to remove any multi-edges to it though.
368         HaveSeenOnlyFeasibleSuccessor = true;
369         continue;
370       }
371 
372       Succ->removePredecessor(BB);
373       Updates.push_back({DominatorTree::Delete, BB, Succ});
374     }
375 
376     BranchInst::Create(OnlyFeasibleSuccessor, BB);
377     TI->eraseFromParent();
378     DTU.applyUpdatesPermissive(Updates);
379   } else if (FeasibleSuccessors.size() > 1) {
380     SwitchInstProfUpdateWrapper SI(*cast<SwitchInst>(TI));
381     SmallVector<DominatorTree::UpdateType, 8> Updates;
382     for (auto CI = SI->case_begin(); CI != SI->case_end();) {
383       if (FeasibleSuccessors.contains(CI->getCaseSuccessor())) {
384         ++CI;
385         continue;
386       }
387 
388       BasicBlock *Succ = CI->getCaseSuccessor();
389       Succ->removePredecessor(BB);
390       Updates.push_back({DominatorTree::Delete, BB, Succ});
391       SI.removeCase(CI);
392       // Don't increment CI, as we removed a case.
393     }
394 
395     DTU.applyUpdatesPermissive(Updates);
396   } else {
397     llvm_unreachable("Must have at least one feasible successor");
398   }
399   return true;
400 }
401 
402 bool llvm::runIPSCCP(
403     Module &M, const DataLayout &DL,
404     std::function<const TargetLibraryInfo &(Function &)> GetTLI,
405     function_ref<AnalysisResultsForFn(Function &)> getAnalysis) {
406   SCCPSolver Solver(DL, GetTLI, M.getContext());
407 
408   // Loop over all functions, marking arguments to those with their addresses
409   // taken or that are external as overdefined.
410   for (Function &F : M) {
411     if (F.isDeclaration())
412       continue;
413 
414     Solver.addAnalysis(F, getAnalysis(F));
415 
416     // Determine if we can track the function's return values. If so, add the
417     // function to the solver's set of return-tracked functions.
418     if (canTrackReturnsInterprocedurally(&F))
419       Solver.addTrackedFunction(&F);
420 
421     // Determine if we can track the function's arguments. If so, add the
422     // function to the solver's set of argument-tracked functions.
423     if (canTrackArgumentsInterprocedurally(&F)) {
424       Solver.addArgumentTrackedFunction(&F);
425       continue;
426     }
427 
428     // Assume the function is called.
429     Solver.markBlockExecutable(&F.front());
430 
431     // Assume nothing about the incoming arguments.
432     for (Argument &AI : F.args())
433       Solver.markOverdefined(&AI);
434   }
435 
436   // Determine if we can track any of the module's global variables. If so, add
437   // the global variables we can track to the solver's set of tracked global
438   // variables.
439   for (GlobalVariable &G : M.globals()) {
440     G.removeDeadConstantUsers();
441     if (canTrackGlobalVariableInterprocedurally(&G))
442       Solver.trackValueOfGlobalVariable(&G);
443   }
444 
445   // Solve for constants.
446   bool ResolvedUndefs = true;
447   Solver.solve();
448   while (ResolvedUndefs) {
449     LLVM_DEBUG(dbgs() << "RESOLVING UNDEFS\n");
450     ResolvedUndefs = false;
451     for (Function &F : M) {
452       if (Solver.resolvedUndefsIn(F))
453         ResolvedUndefs = true;
454     }
455     if (ResolvedUndefs)
456       Solver.solve();
457   }
458 
459   bool MadeChanges = false;
460 
461   // Iterate over all of the instructions in the module, replacing them with
462   // constants if we have found them to be of constant values.
463 
464   for (Function &F : M) {
465     if (F.isDeclaration())
466       continue;
467 
468     SmallVector<BasicBlock *, 512> BlocksToErase;
469 
470     if (Solver.isBlockExecutable(&F.front())) {
471       bool ReplacedPointerArg = false;
472       for (Argument &Arg : F.args()) {
473         if (!Arg.use_empty() && tryToReplaceWithConstant(Solver, &Arg)) {
474           ReplacedPointerArg |= Arg.getType()->isPointerTy();
475           ++IPNumArgsElimed;
476         }
477       }
478 
479       // If we replaced an argument, the argmemonly and
480       // inaccessiblemem_or_argmemonly attributes do not hold any longer. Remove
481       // them from both the function and callsites.
482       if (ReplacedPointerArg) {
483         AttributeMask AttributesToRemove;
484         AttributesToRemove.addAttribute(Attribute::ArgMemOnly);
485         AttributesToRemove.addAttribute(Attribute::InaccessibleMemOrArgMemOnly);
486         F.removeFnAttrs(AttributesToRemove);
487 
488         for (User *U : F.users()) {
489           auto *CB = dyn_cast<CallBase>(U);
490           if (!CB || CB->getCalledFunction() != &F)
491             continue;
492 
493           CB->removeFnAttrs(AttributesToRemove);
494         }
495       }
496       MadeChanges |= ReplacedPointerArg;
497     }
498 
499     SmallPtrSet<Value *, 32> InsertedValues;
500     for (BasicBlock &BB : F) {
501       if (!Solver.isBlockExecutable(&BB)) {
502         LLVM_DEBUG(dbgs() << "  BasicBlock Dead:" << BB);
503         ++NumDeadBlocks;
504 
505         MadeChanges = true;
506 
507         if (&BB != &F.front())
508           BlocksToErase.push_back(&BB);
509         continue;
510       }
511 
512       MadeChanges |= simplifyInstsInBlock(Solver, BB, InsertedValues,
513                                           IPNumInstRemoved, IPNumInstReplaced);
514     }
515 
516     DomTreeUpdater DTU = Solver.getDTU(F);
517     // Change dead blocks to unreachable. We do it after replacing constants
518     // in all executable blocks, because changeToUnreachable may remove PHI
519     // nodes in executable blocks we found values for. The function's entry
520     // block is not part of BlocksToErase, so we have to handle it separately.
521     for (BasicBlock *BB : BlocksToErase) {
522       NumInstRemoved += changeToUnreachable(BB->getFirstNonPHI(),
523                                             /*PreserveLCSSA=*/false, &DTU);
524     }
525     if (!Solver.isBlockExecutable(&F.front()))
526       NumInstRemoved += changeToUnreachable(F.front().getFirstNonPHI(),
527                                             /*PreserveLCSSA=*/false, &DTU);
528 
529     for (BasicBlock &BB : F)
530       MadeChanges |= removeNonFeasibleEdges(Solver, &BB, DTU);
531 
532     for (BasicBlock *DeadBB : BlocksToErase)
533       DTU.deleteBB(DeadBB);
534 
535     for (BasicBlock &BB : F) {
536       for (Instruction &Inst : llvm::make_early_inc_range(BB)) {
537         if (Solver.getPredicateInfoFor(&Inst)) {
538           if (auto *II = dyn_cast<IntrinsicInst>(&Inst)) {
539             if (II->getIntrinsicID() == Intrinsic::ssa_copy) {
540               Value *Op = II->getOperand(0);
541               Inst.replaceAllUsesWith(Op);
542               Inst.eraseFromParent();
543             }
544           }
545         }
546       }
547     }
548   }
549 
550   // If we inferred constant or undef return values for a function, we replaced
551   // all call uses with the inferred value.  This means we don't need to bother
552   // actually returning anything from the function.  Replace all return
553   // instructions with return undef.
554   //
555   // Do this in two stages: first identify the functions we should process, then
556   // actually zap their returns.  This is important because we can only do this
557   // if the address of the function isn't taken.  In cases where a return is the
558   // last use of a function, the order of processing functions would affect
559   // whether other functions are optimizable.
560   SmallVector<ReturnInst*, 8> ReturnsToZap;
561 
562   for (const auto &I : Solver.getTrackedRetVals()) {
563     Function *F = I.first;
564     const ValueLatticeElement &ReturnValue = I.second;
565 
566     // If there is a known constant range for the return value, add !range
567     // metadata to the function's call sites.
568     if (ReturnValue.isConstantRange() &&
569         !ReturnValue.getConstantRange().isSingleElement()) {
570       // Do not add range metadata if the return value may include undef.
571       if (ReturnValue.isConstantRangeIncludingUndef())
572         continue;
573 
574       auto &CR = ReturnValue.getConstantRange();
575       for (User *User : F->users()) {
576         auto *CB = dyn_cast<CallBase>(User);
577         if (!CB || CB->getCalledFunction() != F)
578           continue;
579 
580         // Limit to cases where the return value is guaranteed to be neither
581         // poison nor undef. Poison will be outside any range and currently
582         // values outside of the specified range cause immediate undefined
583         // behavior.
584         if (!isGuaranteedNotToBeUndefOrPoison(CB, nullptr, CB))
585           continue;
586 
587         // Do not touch existing metadata for now.
588         // TODO: We should be able to take the intersection of the existing
589         // metadata and the inferred range.
590         if (CB->getMetadata(LLVMContext::MD_range))
591           continue;
592 
593         LLVMContext &Context = CB->getParent()->getContext();
594         Metadata *RangeMD[] = {
595             ConstantAsMetadata::get(ConstantInt::get(Context, CR.getLower())),
596             ConstantAsMetadata::get(ConstantInt::get(Context, CR.getUpper()))};
597         CB->setMetadata(LLVMContext::MD_range, MDNode::get(Context, RangeMD));
598       }
599       continue;
600     }
601     if (F->getReturnType()->isVoidTy())
602       continue;
603     if (isConstant(ReturnValue) || ReturnValue.isUnknownOrUndef())
604       findReturnsToZap(*F, ReturnsToZap, Solver);
605   }
606 
607   for (auto F : Solver.getMRVFunctionsTracked()) {
608     assert(F->getReturnType()->isStructTy() &&
609            "The return type should be a struct");
610     StructType *STy = cast<StructType>(F->getReturnType());
611     if (Solver.isStructLatticeConstant(F, STy))
612       findReturnsToZap(*F, ReturnsToZap, Solver);
613   }
614 
615   // Zap all returns which we've identified as zap to change.
616   SmallSetVector<Function *, 8> FuncZappedReturn;
617   for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) {
618     Function *F = ReturnsToZap[i]->getParent()->getParent();
619     ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType()));
620     // Record all functions that are zapped.
621     FuncZappedReturn.insert(F);
622   }
623 
624   // Remove the returned attribute for zapped functions and the
625   // corresponding call sites.
626   for (Function *F : FuncZappedReturn) {
627     for (Argument &A : F->args())
628       F->removeParamAttr(A.getArgNo(), Attribute::Returned);
629     for (Use &U : F->uses()) {
630       // Skip over blockaddr users.
631       if (isa<BlockAddress>(U.getUser()))
632         continue;
633       CallBase *CB = cast<CallBase>(U.getUser());
634       for (Use &Arg : CB->args())
635         CB->removeParamAttr(CB->getArgOperandNo(&Arg), Attribute::Returned);
636     }
637   }
638 
639   // If we inferred constant or undef values for globals variables, we can
640   // delete the global and any stores that remain to it.
641   for (auto &I : make_early_inc_range(Solver.getTrackedGlobals())) {
642     GlobalVariable *GV = I.first;
643     if (isOverdefined(I.second))
644       continue;
645     LLVM_DEBUG(dbgs() << "Found that GV '" << GV->getName()
646                       << "' is constant!\n");
647     while (!GV->use_empty()) {
648       StoreInst *SI = cast<StoreInst>(GV->user_back());
649       SI->eraseFromParent();
650       MadeChanges = true;
651     }
652     M.getGlobalList().erase(GV);
653     ++IPNumGlobalConst;
654   }
655 
656   return MadeChanges;
657 }
658