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/ArrayRef.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/DenseSet.h"
23 #include "llvm/ADT/MapVector.h"
24 #include "llvm/ADT/PointerIntPair.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SetVector.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/Analysis/ConstantFolding.h"
31 #include "llvm/Analysis/DomTreeUpdater.h"
32 #include "llvm/Analysis/GlobalsModRef.h"
33 #include "llvm/Analysis/InstructionSimplify.h"
34 #include "llvm/Analysis/TargetLibraryInfo.h"
35 #include "llvm/Analysis/ValueLattice.h"
36 #include "llvm/Analysis/ValueLatticeUtils.h"
37 #include "llvm/Analysis/ValueTracking.h"
38 #include "llvm/IR/BasicBlock.h"
39 #include "llvm/IR/Constant.h"
40 #include "llvm/IR/Constants.h"
41 #include "llvm/IR/DataLayout.h"
42 #include "llvm/IR/DerivedTypes.h"
43 #include "llvm/IR/Function.h"
44 #include "llvm/IR/GlobalVariable.h"
45 #include "llvm/IR/InstVisitor.h"
46 #include "llvm/IR/InstrTypes.h"
47 #include "llvm/IR/Instruction.h"
48 #include "llvm/IR/Instructions.h"
49 #include "llvm/IR/Module.h"
50 #include "llvm/IR/PassManager.h"
51 #include "llvm/IR/Type.h"
52 #include "llvm/IR/User.h"
53 #include "llvm/IR/Value.h"
54 #include "llvm/InitializePasses.h"
55 #include "llvm/Pass.h"
56 #include "llvm/Support/Casting.h"
57 #include "llvm/Support/Debug.h"
58 #include "llvm/Support/ErrorHandling.h"
59 #include "llvm/Support/raw_ostream.h"
60 #include "llvm/Transforms/Scalar.h"
61 #include "llvm/Transforms/Utils/Local.h"
62 #include "llvm/Transforms/Utils/PredicateInfo.h"
63 #include <cassert>
64 #include <utility>
65 #include <vector>
66 
67 using namespace llvm;
68 
69 #define DEBUG_TYPE "sccp"
70 
71 STATISTIC(NumInstRemoved, "Number of instructions removed");
72 STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
73 STATISTIC(NumInstReplaced,
74           "Number of instructions replaced with (simpler) instruction");
75 
76 STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
77 STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
78 STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
79 STATISTIC(
80     IPNumInstReplaced,
81     "Number of instructions replaced with (simpler) instruction by IPSCCP");
82 
83 // The maximum number of range extensions allowed for operations requiring
84 // widening.
85 static const unsigned MaxNumRangeExtensions = 10;
86 
87 /// Returns MergeOptions with MaxWidenSteps set to MaxNumRangeExtensions.
88 static ValueLatticeElement::MergeOptions getMaxWidenStepsOpts() {
89   return ValueLatticeElement::MergeOptions().setMaxWidenSteps(
90       MaxNumRangeExtensions);
91 }
92 namespace {
93 
94 // Helper to check if \p LV is either a constant or a constant
95 // range with a single element. This should cover exactly the same cases as the
96 // old ValueLatticeElement::isConstant() and is intended to be used in the
97 // transition to ValueLatticeElement.
98 bool isConstant(const ValueLatticeElement &LV) {
99   return LV.isConstant() ||
100          (LV.isConstantRange() && LV.getConstantRange().isSingleElement());
101 }
102 
103 // Helper to check if \p LV is either overdefined or a constant range with more
104 // than a single element. This should cover exactly the same cases as the old
105 // ValueLatticeElement::isOverdefined() and is intended to be used in the
106 // transition to ValueLatticeElement.
107 bool isOverdefined(const ValueLatticeElement &LV) {
108   return !LV.isUnknownOrUndef() && !isConstant(LV);
109 }
110 
111 //===----------------------------------------------------------------------===//
112 //
113 /// SCCPSolver - This class is a general purpose solver for Sparse Conditional
114 /// Constant Propagation.
115 ///
116 class SCCPSolver : public InstVisitor<SCCPSolver> {
117   const DataLayout &DL;
118   std::function<const TargetLibraryInfo &(Function &)> GetTLI;
119   SmallPtrSet<BasicBlock *, 8> BBExecutable; // The BBs that are executable.
120   DenseMap<Value *, ValueLatticeElement>
121       ValueState; // The state each value is in.
122 
123   /// StructValueState - This maintains ValueState for values that have
124   /// StructType, for example for formal arguments, calls, insertelement, etc.
125   DenseMap<std::pair<Value *, unsigned>, ValueLatticeElement> StructValueState;
126 
127   /// GlobalValue - If we are tracking any values for the contents of a global
128   /// variable, we keep a mapping from the constant accessor to the element of
129   /// the global, to the currently known value.  If the value becomes
130   /// overdefined, it's entry is simply removed from this map.
131   DenseMap<GlobalVariable *, ValueLatticeElement> TrackedGlobals;
132 
133   /// TrackedRetVals - If we are tracking arguments into and the return
134   /// value out of a function, it will have an entry in this map, indicating
135   /// what the known return value for the function is.
136   MapVector<Function *, ValueLatticeElement> TrackedRetVals;
137 
138   /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
139   /// that return multiple values.
140   MapVector<std::pair<Function *, unsigned>, ValueLatticeElement>
141       TrackedMultipleRetVals;
142 
143   /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is
144   /// represented here for efficient lookup.
145   SmallPtrSet<Function *, 16> MRVFunctionsTracked;
146 
147   /// A list of functions whose return cannot be modified.
148   SmallPtrSet<Function *, 16> MustPreserveReturnsInFunctions;
149 
150   /// TrackingIncomingArguments - This is the set of functions for whose
151   /// arguments we make optimistic assumptions about and try to prove as
152   /// constants.
153   SmallPtrSet<Function *, 16> TrackingIncomingArguments;
154 
155   /// The reason for two worklists is that overdefined is the lowest state
156   /// on the lattice, and moving things to overdefined as fast as possible
157   /// makes SCCP converge much faster.
158   ///
159   /// By having a separate worklist, we accomplish this because everything
160   /// possibly overdefined will become overdefined at the soonest possible
161   /// point.
162   SmallVector<Value *, 64> OverdefinedInstWorkList;
163   SmallVector<Value *, 64> InstWorkList;
164 
165   // The BasicBlock work list
166   SmallVector<BasicBlock *, 64>  BBWorkList;
167 
168   /// KnownFeasibleEdges - Entries in this set are edges which have already had
169   /// PHI nodes retriggered.
170   using Edge = std::pair<BasicBlock *, BasicBlock *>;
171   DenseSet<Edge> KnownFeasibleEdges;
172 
173   DenseMap<Function *, AnalysisResultsForFn> AnalysisResults;
174   DenseMap<Value *, SmallPtrSet<User *, 2>> AdditionalUsers;
175 
176   LLVMContext &Ctx;
177 
178 public:
179   void addAnalysis(Function &F, AnalysisResultsForFn A) {
180     AnalysisResults.insert({&F, std::move(A)});
181   }
182 
183   const PredicateBase *getPredicateInfoFor(Instruction *I) {
184     auto A = AnalysisResults.find(I->getParent()->getParent());
185     if (A == AnalysisResults.end())
186       return nullptr;
187     return A->second.PredInfo->getPredicateInfoFor(I);
188   }
189 
190   DomTreeUpdater getDTU(Function &F) {
191     auto A = AnalysisResults.find(&F);
192     assert(A != AnalysisResults.end() && "Need analysis results for function.");
193     return {A->second.DT, A->second.PDT, DomTreeUpdater::UpdateStrategy::Lazy};
194   }
195 
196   SCCPSolver(const DataLayout &DL,
197              std::function<const TargetLibraryInfo &(Function &)> GetTLI,
198              LLVMContext &Ctx)
199       : DL(DL), GetTLI(std::move(GetTLI)), Ctx(Ctx) {}
200 
201   /// MarkBlockExecutable - This method can be used by clients to mark all of
202   /// the blocks that are known to be intrinsically live in the processed unit.
203   ///
204   /// This returns true if the block was not considered live before.
205   bool MarkBlockExecutable(BasicBlock *BB) {
206     if (!BBExecutable.insert(BB).second)
207       return false;
208     LLVM_DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << '\n');
209     BBWorkList.push_back(BB);  // Add the block to the work list!
210     return true;
211   }
212 
213   /// TrackValueOfGlobalVariable - Clients can use this method to
214   /// inform the SCCPSolver that it should track loads and stores to the
215   /// specified global variable if it can.  This is only legal to call if
216   /// performing Interprocedural SCCP.
217   void TrackValueOfGlobalVariable(GlobalVariable *GV) {
218     // We only track the contents of scalar globals.
219     if (GV->getValueType()->isSingleValueType()) {
220       ValueLatticeElement &IV = TrackedGlobals[GV];
221       if (!isa<UndefValue>(GV->getInitializer()))
222         IV.markConstant(GV->getInitializer());
223     }
224   }
225 
226   /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
227   /// and out of the specified function (which cannot have its address taken),
228   /// this method must be called.
229   void AddTrackedFunction(Function *F) {
230     // Add an entry, F -> undef.
231     if (auto *STy = dyn_cast<StructType>(F->getReturnType())) {
232       MRVFunctionsTracked.insert(F);
233       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
234         TrackedMultipleRetVals.insert(
235             std::make_pair(std::make_pair(F, i), ValueLatticeElement()));
236     } else if (!F->getReturnType()->isVoidTy())
237       TrackedRetVals.insert(std::make_pair(F, ValueLatticeElement()));
238   }
239 
240   /// Add function to the list of functions whose return cannot be modified.
241   void addToMustPreserveReturnsInFunctions(Function *F) {
242     MustPreserveReturnsInFunctions.insert(F);
243   }
244 
245   /// Returns true if the return of the given function cannot be modified.
246   bool mustPreserveReturn(Function *F) {
247     return MustPreserveReturnsInFunctions.count(F);
248   }
249 
250   void AddArgumentTrackedFunction(Function *F) {
251     TrackingIncomingArguments.insert(F);
252   }
253 
254   /// Returns true if the given function is in the solver's set of
255   /// argument-tracked functions.
256   bool isArgumentTrackedFunction(Function *F) {
257     return TrackingIncomingArguments.count(F);
258   }
259 
260   /// Solve - Solve for constants and executable blocks.
261   void Solve();
262 
263   /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
264   /// that branches on undef values cannot reach any of their successors.
265   /// However, this is not a safe assumption.  After we solve dataflow, this
266   /// method should be use to handle this.  If this returns true, the solver
267   /// should be rerun.
268   bool ResolvedUndefsIn(Function &F);
269 
270   bool isBlockExecutable(BasicBlock *BB) const {
271     return BBExecutable.count(BB);
272   }
273 
274   // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
275   // block to the 'To' basic block is currently feasible.
276   bool isEdgeFeasible(BasicBlock *From, BasicBlock *To) const;
277 
278   std::vector<ValueLatticeElement> getStructLatticeValueFor(Value *V) const {
279     std::vector<ValueLatticeElement> StructValues;
280     auto *STy = dyn_cast<StructType>(V->getType());
281     assert(STy && "getStructLatticeValueFor() can be called only on structs");
282     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
283       auto I = StructValueState.find(std::make_pair(V, i));
284       assert(I != StructValueState.end() && "Value not in valuemap!");
285       StructValues.push_back(I->second);
286     }
287     return StructValues;
288   }
289 
290   void removeLatticeValueFor(Value *V) { ValueState.erase(V); }
291 
292   const ValueLatticeElement &getLatticeValueFor(Value *V) const {
293     assert(!V->getType()->isStructTy() &&
294            "Should use getStructLatticeValueFor");
295     DenseMap<Value *, ValueLatticeElement>::const_iterator I =
296         ValueState.find(V);
297     assert(I != ValueState.end() &&
298            "V not found in ValueState nor Paramstate map!");
299     return I->second;
300   }
301 
302   /// getTrackedRetVals - Get the inferred return value map.
303   const MapVector<Function *, ValueLatticeElement> &getTrackedRetVals() {
304     return TrackedRetVals;
305   }
306 
307   /// getTrackedGlobals - Get and return the set of inferred initializers for
308   /// global variables.
309   const DenseMap<GlobalVariable *, ValueLatticeElement> &getTrackedGlobals() {
310     return TrackedGlobals;
311   }
312 
313   /// getMRVFunctionsTracked - Get the set of functions which return multiple
314   /// values tracked by the pass.
315   const SmallPtrSet<Function *, 16> getMRVFunctionsTracked() {
316     return MRVFunctionsTracked;
317   }
318 
319   /// markOverdefined - Mark the specified value overdefined.  This
320   /// works with both scalars and structs.
321   void markOverdefined(Value *V) {
322     if (auto *STy = dyn_cast<StructType>(V->getType()))
323       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
324         markOverdefined(getStructValueState(V, i), V);
325     else
326       markOverdefined(ValueState[V], V);
327   }
328 
329   // isStructLatticeConstant - Return true if all the lattice values
330   // corresponding to elements of the structure are constants,
331   // false otherwise.
332   bool isStructLatticeConstant(Function *F, StructType *STy) {
333     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
334       const auto &It = TrackedMultipleRetVals.find(std::make_pair(F, i));
335       assert(It != TrackedMultipleRetVals.end());
336       ValueLatticeElement LV = It->second;
337       if (!isConstant(LV))
338         return false;
339     }
340     return true;
341   }
342 
343   /// Helper to return a Constant if \p LV is either a constant or a constant
344   /// range with a single element.
345   Constant *getConstant(const ValueLatticeElement &LV) const {
346     if (LV.isConstant())
347       return LV.getConstant();
348 
349     if (LV.isConstantRange()) {
350       auto &CR = LV.getConstantRange();
351       if (CR.getSingleElement())
352         return ConstantInt::get(Ctx, *CR.getSingleElement());
353     }
354     return nullptr;
355   }
356 
357 private:
358   ConstantInt *getConstantInt(const ValueLatticeElement &IV) const {
359     return dyn_cast_or_null<ConstantInt>(getConstant(IV));
360   }
361 
362   // pushToWorkList - Helper for markConstant/markOverdefined
363   void pushToWorkList(ValueLatticeElement &IV, Value *V) {
364     if (IV.isOverdefined())
365       return OverdefinedInstWorkList.push_back(V);
366     InstWorkList.push_back(V);
367   }
368 
369   // Helper to push \p V to the worklist, after updating it to \p IV. Also
370   // prints a debug message with the updated value.
371   void pushToWorkListMsg(ValueLatticeElement &IV, Value *V) {
372     LLVM_DEBUG(dbgs() << "updated " << IV << ": " << *V << '\n');
373     pushToWorkList(IV, V);
374   }
375 
376   // markConstant - Make a value be marked as "constant".  If the value
377   // is not already a constant, add it to the instruction work list so that
378   // the users of the instruction are updated later.
379   bool markConstant(ValueLatticeElement &IV, Value *V, Constant *C,
380                     bool MayIncludeUndef = false) {
381     if (!IV.markConstant(C, MayIncludeUndef))
382       return false;
383     LLVM_DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n');
384     pushToWorkList(IV, V);
385     return true;
386   }
387 
388   bool markConstant(Value *V, Constant *C) {
389     assert(!V->getType()->isStructTy() && "structs should use mergeInValue");
390     return markConstant(ValueState[V], V, C);
391   }
392 
393   // markOverdefined - Make a value be marked as "overdefined". If the
394   // value is not already overdefined, add it to the overdefined instruction
395   // work list so that the users of the instruction are updated later.
396   bool markOverdefined(ValueLatticeElement &IV, Value *V) {
397     if (!IV.markOverdefined()) return false;
398 
399     LLVM_DEBUG(dbgs() << "markOverdefined: ";
400                if (auto *F = dyn_cast<Function>(V)) dbgs()
401                << "Function '" << F->getName() << "'\n";
402                else dbgs() << *V << '\n');
403     // Only instructions go on the work list
404     pushToWorkList(IV, V);
405     return true;
406   }
407 
408   /// Merge \p MergeWithV into \p IV and push \p V to the worklist, if \p IV
409   /// changes.
410   bool mergeInValue(ValueLatticeElement &IV, Value *V,
411                     ValueLatticeElement MergeWithV,
412                     ValueLatticeElement::MergeOptions Opts = {
413                         /*MayIncludeUndef=*/false, /*CheckWiden=*/false}) {
414     if (IV.mergeIn(MergeWithV, Opts)) {
415       pushToWorkList(IV, V);
416       LLVM_DEBUG(dbgs() << "Merged " << MergeWithV << " into " << *V << " : "
417                         << IV << "\n");
418       return true;
419     }
420     return false;
421   }
422 
423   bool mergeInValue(Value *V, ValueLatticeElement MergeWithV,
424                     ValueLatticeElement::MergeOptions Opts = {
425                         /*MayIncludeUndef=*/false, /*CheckWiden=*/false}) {
426     assert(!V->getType()->isStructTy() &&
427            "non-structs should use markConstant");
428     return mergeInValue(ValueState[V], V, MergeWithV, Opts);
429   }
430 
431   /// getValueState - Return the ValueLatticeElement object that corresponds to
432   /// the value.  This function handles the case when the value hasn't been seen
433   /// yet by properly seeding constants etc.
434   ValueLatticeElement &getValueState(Value *V) {
435     assert(!V->getType()->isStructTy() && "Should use getStructValueState");
436 
437     auto I = ValueState.insert(std::make_pair(V, ValueLatticeElement()));
438     ValueLatticeElement &LV = I.first->second;
439 
440     if (!I.second)
441       return LV;  // Common case, already in the map.
442 
443     if (auto *C = dyn_cast<Constant>(V))
444       LV.markConstant(C);          // Constants are constant
445 
446     // All others are unknown by default.
447     return LV;
448   }
449 
450   /// getStructValueState - Return the ValueLatticeElement object that
451   /// corresponds to the value/field pair.  This function handles the case when
452   /// the value hasn't been seen yet by properly seeding constants etc.
453   ValueLatticeElement &getStructValueState(Value *V, unsigned i) {
454     assert(V->getType()->isStructTy() && "Should use getValueState");
455     assert(i < cast<StructType>(V->getType())->getNumElements() &&
456            "Invalid element #");
457 
458     auto I = StructValueState.insert(
459         std::make_pair(std::make_pair(V, i), ValueLatticeElement()));
460     ValueLatticeElement &LV = I.first->second;
461 
462     if (!I.second)
463       return LV;  // Common case, already in the map.
464 
465     if (auto *C = dyn_cast<Constant>(V)) {
466       Constant *Elt = C->getAggregateElement(i);
467 
468       if (!Elt)
469         LV.markOverdefined();      // Unknown sort of constant.
470       else if (isa<UndefValue>(Elt))
471         ; // Undef values remain unknown.
472       else
473         LV.markConstant(Elt);      // Constants are constant.
474     }
475 
476     // All others are underdefined by default.
477     return LV;
478   }
479 
480   /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
481   /// work list if it is not already executable.
482   bool markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
483     if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
484       return false;  // This edge is already known to be executable!
485 
486     if (!MarkBlockExecutable(Dest)) {
487       // If the destination is already executable, we just made an *edge*
488       // feasible that wasn't before.  Revisit the PHI nodes in the block
489       // because they have potentially new operands.
490       LLVM_DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName()
491                         << " -> " << Dest->getName() << '\n');
492 
493       for (PHINode &PN : Dest->phis())
494         visitPHINode(PN);
495     }
496     return true;
497   }
498 
499   // getFeasibleSuccessors - Return a vector of booleans to indicate which
500   // successors are reachable from a given terminator instruction.
501   void getFeasibleSuccessors(Instruction &TI, SmallVectorImpl<bool> &Succs);
502 
503   // OperandChangedState - This method is invoked on all of the users of an
504   // instruction that was just changed state somehow.  Based on this
505   // information, we need to update the specified user of this instruction.
506   void OperandChangedState(Instruction *I) {
507     if (BBExecutable.count(I->getParent()))   // Inst is executable?
508       visit(*I);
509   }
510 
511   // Add U as additional user of V.
512   void addAdditionalUser(Value *V, User *U) {
513     auto Iter = AdditionalUsers.insert({V, {}});
514     Iter.first->second.insert(U);
515   }
516 
517   // Mark I's users as changed, including AdditionalUsers.
518   void markUsersAsChanged(Value *I) {
519     // Functions include their arguments in the use-list. Changed function
520     // values mean that the result of the function changed. We only need to
521     // update the call sites with the new function result and do not have to
522     // propagate the call arguments.
523     if (isa<Function>(I)) {
524       for (User *U : I->users()) {
525         if (auto *CB = dyn_cast<CallBase>(U))
526           handleCallResult(*CB);
527       }
528     } else {
529       for (User *U : I->users())
530         if (auto *UI = dyn_cast<Instruction>(U))
531           OperandChangedState(UI);
532     }
533 
534     auto Iter = AdditionalUsers.find(I);
535     if (Iter != AdditionalUsers.end()) {
536       for (User *U : Iter->second)
537         if (auto *UI = dyn_cast<Instruction>(U))
538           OperandChangedState(UI);
539     }
540   }
541   void handleCallOverdefined(CallBase &CB);
542   void handleCallResult(CallBase &CB);
543   void handleCallArguments(CallBase &CB);
544 
545 private:
546   friend class InstVisitor<SCCPSolver>;
547 
548   // visit implementations - Something changed in this instruction.  Either an
549   // operand made a transition, or the instruction is newly executable.  Change
550   // the value type of I to reflect these changes if appropriate.
551   void visitPHINode(PHINode &I);
552 
553   // Terminators
554 
555   void visitReturnInst(ReturnInst &I);
556   void visitTerminator(Instruction &TI);
557 
558   void visitCastInst(CastInst &I);
559   void visitSelectInst(SelectInst &I);
560   void visitUnaryOperator(Instruction &I);
561   void visitBinaryOperator(Instruction &I);
562   void visitCmpInst(CmpInst &I);
563   void visitExtractValueInst(ExtractValueInst &EVI);
564   void visitInsertValueInst(InsertValueInst &IVI);
565 
566   void visitCatchSwitchInst(CatchSwitchInst &CPI) {
567     markOverdefined(&CPI);
568     visitTerminator(CPI);
569   }
570 
571   // Instructions that cannot be folded away.
572 
573   void visitStoreInst     (StoreInst &I);
574   void visitLoadInst      (LoadInst &I);
575   void visitGetElementPtrInst(GetElementPtrInst &I);
576 
577   void visitCallInst      (CallInst &I) {
578     visitCallBase(I);
579   }
580 
581   void visitInvokeInst    (InvokeInst &II) {
582     visitCallBase(II);
583     visitTerminator(II);
584   }
585 
586   void visitCallBrInst    (CallBrInst &CBI) {
587     visitCallBase(CBI);
588     visitTerminator(CBI);
589   }
590 
591   void visitCallBase      (CallBase &CB);
592   void visitResumeInst    (ResumeInst &I) { /*returns void*/ }
593   void visitUnreachableInst(UnreachableInst &I) { /*returns void*/ }
594   void visitFenceInst     (FenceInst &I) { /*returns void*/ }
595 
596   void visitInstruction(Instruction &I) {
597     // All the instructions we don't do any special handling for just
598     // go to overdefined.
599     LLVM_DEBUG(dbgs() << "SCCP: Don't know how to handle: " << I << '\n');
600     markOverdefined(&I);
601   }
602 };
603 
604 } // end anonymous namespace
605 
606 // getFeasibleSuccessors - Return a vector of booleans to indicate which
607 // successors are reachable from a given terminator instruction.
608 void SCCPSolver::getFeasibleSuccessors(Instruction &TI,
609                                        SmallVectorImpl<bool> &Succs) {
610   Succs.resize(TI.getNumSuccessors());
611   if (auto *BI = dyn_cast<BranchInst>(&TI)) {
612     if (BI->isUnconditional()) {
613       Succs[0] = true;
614       return;
615     }
616 
617     ValueLatticeElement BCValue = getValueState(BI->getCondition());
618     ConstantInt *CI = getConstantInt(BCValue);
619     if (!CI) {
620       // Overdefined condition variables, and branches on unfoldable constant
621       // conditions, mean the branch could go either way.
622       if (!BCValue.isUnknownOrUndef())
623         Succs[0] = Succs[1] = true;
624       return;
625     }
626 
627     // Constant condition variables mean the branch can only go a single way.
628     Succs[CI->isZero()] = true;
629     return;
630   }
631 
632   // Unwinding instructions successors are always executable.
633   if (TI.isExceptionalTerminator()) {
634     Succs.assign(TI.getNumSuccessors(), true);
635     return;
636   }
637 
638   if (auto *SI = dyn_cast<SwitchInst>(&TI)) {
639     if (!SI->getNumCases()) {
640       Succs[0] = true;
641       return;
642     }
643     const ValueLatticeElement &SCValue = getValueState(SI->getCondition());
644     if (ConstantInt *CI = getConstantInt(SCValue)) {
645       Succs[SI->findCaseValue(CI)->getSuccessorIndex()] = true;
646       return;
647     }
648 
649     // TODO: Switch on undef is UB. Stop passing false once the rest of LLVM
650     // is ready.
651     if (SCValue.isConstantRange(/*UndefAllowed=*/false)) {
652       const ConstantRange &Range = SCValue.getConstantRange();
653       for (const auto &Case : SI->cases()) {
654         const APInt &CaseValue = Case.getCaseValue()->getValue();
655         if (Range.contains(CaseValue))
656           Succs[Case.getSuccessorIndex()] = true;
657       }
658 
659       // TODO: Determine whether default case is reachable.
660       Succs[SI->case_default()->getSuccessorIndex()] = true;
661       return;
662     }
663 
664     // Overdefined or unknown condition? All destinations are executable!
665     if (!SCValue.isUnknownOrUndef())
666       Succs.assign(TI.getNumSuccessors(), true);
667     return;
668   }
669 
670   // In case of indirect branch and its address is a blockaddress, we mark
671   // the target as executable.
672   if (auto *IBR = dyn_cast<IndirectBrInst>(&TI)) {
673     // Casts are folded by visitCastInst.
674     ValueLatticeElement IBRValue = getValueState(IBR->getAddress());
675     BlockAddress *Addr = dyn_cast_or_null<BlockAddress>(getConstant(IBRValue));
676     if (!Addr) {   // Overdefined or unknown condition?
677       // All destinations are executable!
678       if (!IBRValue.isUnknownOrUndef())
679         Succs.assign(TI.getNumSuccessors(), true);
680       return;
681     }
682 
683     BasicBlock* T = Addr->getBasicBlock();
684     assert(Addr->getFunction() == T->getParent() &&
685            "Block address of a different function ?");
686     for (unsigned i = 0; i < IBR->getNumSuccessors(); ++i) {
687       // This is the target.
688       if (IBR->getDestination(i) == T) {
689         Succs[i] = true;
690         return;
691       }
692     }
693 
694     // If we didn't find our destination in the IBR successor list, then we
695     // have undefined behavior. Its ok to assume no successor is executable.
696     return;
697   }
698 
699   // In case of callbr, we pessimistically assume that all successors are
700   // feasible.
701   if (isa<CallBrInst>(&TI)) {
702     Succs.assign(TI.getNumSuccessors(), true);
703     return;
704   }
705 
706   LLVM_DEBUG(dbgs() << "Unknown terminator instruction: " << TI << '\n');
707   llvm_unreachable("SCCP: Don't know how to handle this terminator!");
708 }
709 
710 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
711 // block to the 'To' basic block is currently feasible.
712 bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) const {
713   // Check if we've called markEdgeExecutable on the edge yet. (We could
714   // be more aggressive and try to consider edges which haven't been marked
715   // yet, but there isn't any need.)
716   return KnownFeasibleEdges.count(Edge(From, To));
717 }
718 
719 // visit Implementations - Something changed in this instruction, either an
720 // operand made a transition, or the instruction is newly executable.  Change
721 // the value type of I to reflect these changes if appropriate.  This method
722 // makes sure to do the following actions:
723 //
724 // 1. If a phi node merges two constants in, and has conflicting value coming
725 //    from different branches, or if the PHI node merges in an overdefined
726 //    value, then the PHI node becomes overdefined.
727 // 2. If a phi node merges only constants in, and they all agree on value, the
728 //    PHI node becomes a constant value equal to that.
729 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
730 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
731 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
732 // 6. If a conditional branch has a value that is constant, make the selected
733 //    destination executable
734 // 7. If a conditional branch has a value that is overdefined, make all
735 //    successors executable.
736 void SCCPSolver::visitPHINode(PHINode &PN) {
737   // If this PN returns a struct, just mark the result overdefined.
738   // TODO: We could do a lot better than this if code actually uses this.
739   if (PN.getType()->isStructTy())
740     return (void)markOverdefined(&PN);
741 
742   if (getValueState(&PN).isOverdefined())
743     return; // Quick exit
744 
745   // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
746   // and slow us down a lot.  Just mark them overdefined.
747   if (PN.getNumIncomingValues() > 64)
748     return (void)markOverdefined(&PN);
749 
750   unsigned NumActiveIncoming = 0;
751 
752   // Look at all of the executable operands of the PHI node.  If any of them
753   // are overdefined, the PHI becomes overdefined as well.  If they are all
754   // constant, and they agree with each other, the PHI becomes the identical
755   // constant.  If they are constant and don't agree, the PHI is a constant
756   // range. If there are no executable operands, the PHI remains unknown.
757   ValueLatticeElement PhiState = getValueState(&PN);
758   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
759     if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
760       continue;
761 
762     ValueLatticeElement IV = getValueState(PN.getIncomingValue(i));
763     PhiState.mergeIn(IV);
764     NumActiveIncoming++;
765     if (PhiState.isOverdefined())
766       break;
767   }
768 
769   // We allow up to 1 range extension per active incoming value and one
770   // additional extension. Note that we manually adjust the number of range
771   // extensions to match the number of active incoming values. This helps to
772   // limit multiple extensions caused by the same incoming value, if other
773   // incoming values are equal.
774   mergeInValue(&PN, PhiState,
775                ValueLatticeElement::MergeOptions().setMaxWidenSteps(
776                    NumActiveIncoming + 1));
777   ValueLatticeElement &PhiStateRef = getValueState(&PN);
778   PhiStateRef.setNumRangeExtensions(
779       std::max(NumActiveIncoming, PhiStateRef.getNumRangeExtensions()));
780 }
781 
782 void SCCPSolver::visitReturnInst(ReturnInst &I) {
783   if (I.getNumOperands() == 0) return;  // ret void
784 
785   Function *F = I.getParent()->getParent();
786   Value *ResultOp = I.getOperand(0);
787 
788   // If we are tracking the return value of this function, merge it in.
789   if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
790     auto TFRVI = TrackedRetVals.find(F);
791     if (TFRVI != TrackedRetVals.end()) {
792       mergeInValue(TFRVI->second, F, getValueState(ResultOp));
793       return;
794     }
795   }
796 
797   // Handle functions that return multiple values.
798   if (!TrackedMultipleRetVals.empty()) {
799     if (auto *STy = dyn_cast<StructType>(ResultOp->getType()))
800       if (MRVFunctionsTracked.count(F))
801         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
802           mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
803                        getStructValueState(ResultOp, i));
804   }
805 }
806 
807 void SCCPSolver::visitTerminator(Instruction &TI) {
808   SmallVector<bool, 16> SuccFeasible;
809   getFeasibleSuccessors(TI, SuccFeasible);
810 
811   BasicBlock *BB = TI.getParent();
812 
813   // Mark all feasible successors executable.
814   for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
815     if (SuccFeasible[i])
816       markEdgeExecutable(BB, TI.getSuccessor(i));
817 }
818 
819 void SCCPSolver::visitCastInst(CastInst &I) {
820   // ResolvedUndefsIn might mark I as overdefined. Bail out, even if we would
821   // discover a concrete value later.
822   if (ValueState[&I].isOverdefined())
823     return;
824 
825   ValueLatticeElement OpSt = getValueState(I.getOperand(0));
826   if (Constant *OpC = getConstant(OpSt)) {
827     // Fold the constant as we build.
828     Constant *C = ConstantFoldCastOperand(I.getOpcode(), OpC, I.getType(), DL);
829     if (isa<UndefValue>(C))
830       return;
831     // Propagate constant value
832     markConstant(&I, C);
833   } else if (OpSt.isConstantRange() && I.getDestTy()->isIntegerTy()) {
834     auto &LV = getValueState(&I);
835     ConstantRange OpRange = OpSt.getConstantRange();
836     Type *DestTy = I.getDestTy();
837     // Vectors where all elements have the same known constant range are treated
838     // as a single constant range in the lattice. When bitcasting such vectors,
839     // there is a mis-match between the width of the lattice value (single
840     // constant range) and the original operands (vector). Go to overdefined in
841     // that case.
842     if (I.getOpcode() == Instruction::BitCast &&
843         I.getOperand(0)->getType()->isVectorTy() &&
844         OpRange.getBitWidth() < DL.getTypeSizeInBits(DestTy))
845       return (void)markOverdefined(&I);
846 
847     ConstantRange Res =
848         OpRange.castOp(I.getOpcode(), DL.getTypeSizeInBits(DestTy));
849     mergeInValue(LV, &I, ValueLatticeElement::getRange(Res));
850   } else if (!OpSt.isUnknownOrUndef())
851     markOverdefined(&I);
852 }
853 
854 void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
855   // If this returns a struct, mark all elements over defined, we don't track
856   // structs in structs.
857   if (EVI.getType()->isStructTy())
858     return (void)markOverdefined(&EVI);
859 
860   // ResolvedUndefsIn might mark I as overdefined. Bail out, even if we would
861   // discover a concrete value later.
862   if (ValueState[&EVI].isOverdefined())
863     return (void)markOverdefined(&EVI);
864 
865   // If this is extracting from more than one level of struct, we don't know.
866   if (EVI.getNumIndices() != 1)
867     return (void)markOverdefined(&EVI);
868 
869   Value *AggVal = EVI.getAggregateOperand();
870   if (AggVal->getType()->isStructTy()) {
871     unsigned i = *EVI.idx_begin();
872     ValueLatticeElement EltVal = getStructValueState(AggVal, i);
873     mergeInValue(getValueState(&EVI), &EVI, EltVal);
874   } else {
875     // Otherwise, must be extracting from an array.
876     return (void)markOverdefined(&EVI);
877   }
878 }
879 
880 void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
881   auto *STy = dyn_cast<StructType>(IVI.getType());
882   if (!STy)
883     return (void)markOverdefined(&IVI);
884 
885   // ResolvedUndefsIn might mark I as overdefined. Bail out, even if we would
886   // discover a concrete value later.
887   if (isOverdefined(ValueState[&IVI]))
888     return (void)markOverdefined(&IVI);
889 
890   // If this has more than one index, we can't handle it, drive all results to
891   // undef.
892   if (IVI.getNumIndices() != 1)
893     return (void)markOverdefined(&IVI);
894 
895   Value *Aggr = IVI.getAggregateOperand();
896   unsigned Idx = *IVI.idx_begin();
897 
898   // Compute the result based on what we're inserting.
899   for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
900     // This passes through all values that aren't the inserted element.
901     if (i != Idx) {
902       ValueLatticeElement EltVal = getStructValueState(Aggr, i);
903       mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
904       continue;
905     }
906 
907     Value *Val = IVI.getInsertedValueOperand();
908     if (Val->getType()->isStructTy())
909       // We don't track structs in structs.
910       markOverdefined(getStructValueState(&IVI, i), &IVI);
911     else {
912       ValueLatticeElement InVal = getValueState(Val);
913       mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
914     }
915   }
916 }
917 
918 void SCCPSolver::visitSelectInst(SelectInst &I) {
919   // If this select returns a struct, just mark the result overdefined.
920   // TODO: We could do a lot better than this if code actually uses this.
921   if (I.getType()->isStructTy())
922     return (void)markOverdefined(&I);
923 
924   // ResolvedUndefsIn might mark I as overdefined. Bail out, even if we would
925   // discover a concrete value later.
926   if (ValueState[&I].isOverdefined())
927     return (void)markOverdefined(&I);
928 
929   ValueLatticeElement CondValue = getValueState(I.getCondition());
930   if (CondValue.isUnknownOrUndef())
931     return;
932 
933   if (ConstantInt *CondCB = getConstantInt(CondValue)) {
934     Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
935     mergeInValue(&I, getValueState(OpVal));
936     return;
937   }
938 
939   // Otherwise, the condition is overdefined or a constant we can't evaluate.
940   // See if we can produce something better than overdefined based on the T/F
941   // value.
942   ValueLatticeElement TVal = getValueState(I.getTrueValue());
943   ValueLatticeElement FVal = getValueState(I.getFalseValue());
944 
945   bool Changed = ValueState[&I].mergeIn(TVal);
946   Changed |= ValueState[&I].mergeIn(FVal);
947   if (Changed)
948     pushToWorkListMsg(ValueState[&I], &I);
949 }
950 
951 // Handle Unary Operators.
952 void SCCPSolver::visitUnaryOperator(Instruction &I) {
953   ValueLatticeElement V0State = getValueState(I.getOperand(0));
954 
955   ValueLatticeElement &IV = ValueState[&I];
956   // ResolvedUndefsIn might mark I as overdefined. Bail out, even if we would
957   // discover a concrete value later.
958   if (isOverdefined(IV))
959     return (void)markOverdefined(&I);
960 
961   if (isConstant(V0State)) {
962     Constant *C = ConstantExpr::get(I.getOpcode(), getConstant(V0State));
963 
964     // op Y -> undef.
965     if (isa<UndefValue>(C))
966       return;
967     return (void)markConstant(IV, &I, C);
968   }
969 
970   // If something is undef, wait for it to resolve.
971   if (!isOverdefined(V0State))
972     return;
973 
974   markOverdefined(&I);
975 }
976 
977 // Handle Binary Operators.
978 void SCCPSolver::visitBinaryOperator(Instruction &I) {
979   ValueLatticeElement V1State = getValueState(I.getOperand(0));
980   ValueLatticeElement V2State = getValueState(I.getOperand(1));
981 
982   ValueLatticeElement &IV = ValueState[&I];
983   if (IV.isOverdefined())
984     return;
985 
986   // If something is undef, wait for it to resolve.
987   if (V1State.isUnknownOrUndef() || V2State.isUnknownOrUndef())
988     return;
989 
990   if (V1State.isOverdefined() && V2State.isOverdefined())
991     return (void)markOverdefined(&I);
992 
993   // If either of the operands is a constant, try to fold it to a constant.
994   // TODO: Use information from notconstant better.
995   if ((V1State.isConstant() || V2State.isConstant())) {
996     Value *V1 = isConstant(V1State) ? getConstant(V1State) : I.getOperand(0);
997     Value *V2 = isConstant(V2State) ? getConstant(V2State) : I.getOperand(1);
998     Value *R = SimplifyBinOp(I.getOpcode(), V1, V2, SimplifyQuery(DL));
999     auto *C = dyn_cast_or_null<Constant>(R);
1000     if (C) {
1001       // X op Y -> undef.
1002       if (isa<UndefValue>(C))
1003         return;
1004       // Conservatively assume that the result may be based on operands that may
1005       // be undef. Note that we use mergeInValue to combine the constant with
1006       // the existing lattice value for I, as different constants might be found
1007       // after one of the operands go to overdefined, e.g. due to one operand
1008       // being a special floating value.
1009       ValueLatticeElement NewV;
1010       NewV.markConstant(C, /*MayIncludeUndef=*/true);
1011       return (void)mergeInValue(&I, NewV);
1012     }
1013   }
1014 
1015   // Only use ranges for binary operators on integers.
1016   if (!I.getType()->isIntegerTy())
1017     return markOverdefined(&I);
1018 
1019   // Try to simplify to a constant range.
1020   ConstantRange A = ConstantRange::getFull(I.getType()->getScalarSizeInBits());
1021   ConstantRange B = ConstantRange::getFull(I.getType()->getScalarSizeInBits());
1022   if (V1State.isConstantRange())
1023     A = V1State.getConstantRange();
1024   if (V2State.isConstantRange())
1025     B = V2State.getConstantRange();
1026 
1027   ConstantRange R = A.binaryOp(cast<BinaryOperator>(&I)->getOpcode(), B);
1028   mergeInValue(&I, ValueLatticeElement::getRange(R));
1029 
1030   // TODO: Currently we do not exploit special values that produce something
1031   // better than overdefined with an overdefined operand for vector or floating
1032   // point types, like and <4 x i32> overdefined, zeroinitializer.
1033 }
1034 
1035 // Handle ICmpInst instruction.
1036 void SCCPSolver::visitCmpInst(CmpInst &I) {
1037   // Do not cache this lookup, getValueState calls later in the function might
1038   // invalidate the reference.
1039   if (isOverdefined(ValueState[&I]))
1040     return (void)markOverdefined(&I);
1041 
1042   Value *Op1 = I.getOperand(0);
1043   Value *Op2 = I.getOperand(1);
1044 
1045   // For parameters, use ParamState which includes constant range info if
1046   // available.
1047   auto V1State = getValueState(Op1);
1048   auto V2State = getValueState(Op2);
1049 
1050   Constant *C = V1State.getCompare(I.getPredicate(), I.getType(), V2State);
1051   if (C) {
1052     if (isa<UndefValue>(C))
1053       return;
1054     ValueLatticeElement CV;
1055     CV.markConstant(C);
1056     mergeInValue(&I, CV);
1057     return;
1058   }
1059 
1060   // If operands are still unknown, wait for it to resolve.
1061   if ((V1State.isUnknownOrUndef() || V2State.isUnknownOrUndef()) &&
1062       !isConstant(ValueState[&I]))
1063     return;
1064 
1065   markOverdefined(&I);
1066 }
1067 
1068 // Handle getelementptr instructions.  If all operands are constants then we
1069 // can turn this into a getelementptr ConstantExpr.
1070 void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
1071   if (isOverdefined(ValueState[&I]))
1072     return (void)markOverdefined(&I);
1073 
1074   SmallVector<Constant*, 8> Operands;
1075   Operands.reserve(I.getNumOperands());
1076 
1077   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1078     ValueLatticeElement State = getValueState(I.getOperand(i));
1079     if (State.isUnknownOrUndef())
1080       return;  // Operands are not resolved yet.
1081 
1082     if (isOverdefined(State))
1083       return (void)markOverdefined(&I);
1084 
1085     if (Constant *C = getConstant(State)) {
1086       Operands.push_back(C);
1087       continue;
1088     }
1089 
1090     return (void)markOverdefined(&I);
1091   }
1092 
1093   Constant *Ptr = Operands[0];
1094   auto Indices = makeArrayRef(Operands.begin() + 1, Operands.end());
1095   Constant *C =
1096       ConstantExpr::getGetElementPtr(I.getSourceElementType(), Ptr, Indices);
1097   if (isa<UndefValue>(C))
1098       return;
1099   markConstant(&I, C);
1100 }
1101 
1102 void SCCPSolver::visitStoreInst(StoreInst &SI) {
1103   // If this store is of a struct, ignore it.
1104   if (SI.getOperand(0)->getType()->isStructTy())
1105     return;
1106 
1107   if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1108     return;
1109 
1110   GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
1111   auto I = TrackedGlobals.find(GV);
1112   if (I == TrackedGlobals.end())
1113     return;
1114 
1115   // Get the value we are storing into the global, then merge it.
1116   mergeInValue(I->second, GV, getValueState(SI.getOperand(0)),
1117                ValueLatticeElement::MergeOptions().setCheckWiden(false));
1118   if (I->second.isOverdefined())
1119     TrackedGlobals.erase(I);      // No need to keep tracking this!
1120 }
1121 
1122 static ValueLatticeElement getValueFromMetadata(const Instruction *I) {
1123   if (MDNode *Ranges = I->getMetadata(LLVMContext::MD_range))
1124     if (I->getType()->isIntegerTy())
1125       return ValueLatticeElement::getRange(
1126           getConstantRangeFromMetadata(*Ranges));
1127   if (I->hasMetadata(LLVMContext::MD_nonnull))
1128     return ValueLatticeElement::getNot(
1129         ConstantPointerNull::get(cast<PointerType>(I->getType())));
1130   return ValueLatticeElement::getOverdefined();
1131 }
1132 
1133 // Handle load instructions.  If the operand is a constant pointer to a constant
1134 // global, we can replace the load with the loaded constant value!
1135 void SCCPSolver::visitLoadInst(LoadInst &I) {
1136   // If this load is of a struct or the load is volatile, just mark the result
1137   // as overdefined.
1138   if (I.getType()->isStructTy() || I.isVolatile())
1139     return (void)markOverdefined(&I);
1140 
1141   // ResolvedUndefsIn might mark I as overdefined. Bail out, even if we would
1142   // discover a concrete value later.
1143   if (ValueState[&I].isOverdefined())
1144     return (void)markOverdefined(&I);
1145 
1146   ValueLatticeElement PtrVal = getValueState(I.getOperand(0));
1147   if (PtrVal.isUnknownOrUndef())
1148     return; // The pointer is not resolved yet!
1149 
1150   ValueLatticeElement &IV = ValueState[&I];
1151 
1152   if (isConstant(PtrVal)) {
1153     Constant *Ptr = getConstant(PtrVal);
1154 
1155     // load null is undefined.
1156     if (isa<ConstantPointerNull>(Ptr)) {
1157       if (NullPointerIsDefined(I.getFunction(), I.getPointerAddressSpace()))
1158         return (void)markOverdefined(IV, &I);
1159       else
1160         return;
1161     }
1162 
1163     // Transform load (constant global) into the value loaded.
1164     if (auto *GV = dyn_cast<GlobalVariable>(Ptr)) {
1165       if (!TrackedGlobals.empty()) {
1166         // If we are tracking this global, merge in the known value for it.
1167         auto It = TrackedGlobals.find(GV);
1168         if (It != TrackedGlobals.end()) {
1169           mergeInValue(IV, &I, It->second, getMaxWidenStepsOpts());
1170           return;
1171         }
1172       }
1173     }
1174 
1175     // Transform load from a constant into a constant if possible.
1176     if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, I.getType(), DL)) {
1177       if (isa<UndefValue>(C))
1178         return;
1179       return (void)markConstant(IV, &I, C);
1180     }
1181   }
1182 
1183   // Fall back to metadata.
1184   mergeInValue(&I, getValueFromMetadata(&I));
1185 }
1186 
1187 void SCCPSolver::visitCallBase(CallBase &CB) {
1188   handleCallResult(CB);
1189   handleCallArguments(CB);
1190 }
1191 
1192 void SCCPSolver::handleCallOverdefined(CallBase &CB) {
1193   Function *F = CB.getCalledFunction();
1194 
1195   // Void return and not tracking callee, just bail.
1196   if (CB.getType()->isVoidTy())
1197     return;
1198 
1199   // Always mark struct return as overdefined.
1200   if (CB.getType()->isStructTy())
1201     return (void)markOverdefined(&CB);
1202 
1203   // Otherwise, if we have a single return value case, and if the function is
1204   // a declaration, maybe we can constant fold it.
1205   if (F && F->isDeclaration() && canConstantFoldCallTo(&CB, F)) {
1206     SmallVector<Constant *, 8> Operands;
1207     for (auto AI = CB.arg_begin(), E = CB.arg_end(); AI != E; ++AI) {
1208       if (AI->get()->getType()->isStructTy())
1209         return markOverdefined(&CB); // Can't handle struct args.
1210       ValueLatticeElement State = getValueState(*AI);
1211 
1212       if (State.isUnknownOrUndef())
1213         return; // Operands are not resolved yet.
1214       if (isOverdefined(State))
1215         return (void)markOverdefined(&CB);
1216       assert(isConstant(State) && "Unknown state!");
1217       Operands.push_back(getConstant(State));
1218     }
1219 
1220     if (isOverdefined(getValueState(&CB)))
1221       return (void)markOverdefined(&CB);
1222 
1223     // If we can constant fold this, mark the result of the call as a
1224     // constant.
1225     if (Constant *C = ConstantFoldCall(&CB, F, Operands, &GetTLI(*F))) {
1226       // call -> undef.
1227       if (isa<UndefValue>(C))
1228         return;
1229       return (void)markConstant(&CB, C);
1230     }
1231   }
1232 
1233   // Fall back to metadata.
1234   mergeInValue(&CB, getValueFromMetadata(&CB));
1235 }
1236 
1237 void SCCPSolver::handleCallArguments(CallBase &CB) {
1238   Function *F = CB.getCalledFunction();
1239   // If this is a local function that doesn't have its address taken, mark its
1240   // entry block executable and merge in the actual arguments to the call into
1241   // the formal arguments of the function.
1242   if (!TrackingIncomingArguments.empty() &&
1243       TrackingIncomingArguments.count(F)) {
1244     MarkBlockExecutable(&F->front());
1245 
1246     // Propagate information from this call site into the callee.
1247     auto CAI = CB.arg_begin();
1248     for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
1249          ++AI, ++CAI) {
1250       // If this argument is byval, and if the function is not readonly, there
1251       // will be an implicit copy formed of the input aggregate.
1252       if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
1253         markOverdefined(&*AI);
1254         continue;
1255       }
1256 
1257       if (auto *STy = dyn_cast<StructType>(AI->getType())) {
1258         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1259           ValueLatticeElement CallArg = getStructValueState(*CAI, i);
1260           mergeInValue(getStructValueState(&*AI, i), &*AI, CallArg,
1261                        getMaxWidenStepsOpts());
1262         }
1263       } else
1264         mergeInValue(&*AI, getValueState(*CAI), getMaxWidenStepsOpts());
1265     }
1266   }
1267 }
1268 
1269 void SCCPSolver::handleCallResult(CallBase &CB) {
1270   Function *F = CB.getCalledFunction();
1271 
1272   if (auto *II = dyn_cast<IntrinsicInst>(&CB)) {
1273     if (II->getIntrinsicID() == Intrinsic::ssa_copy) {
1274       if (ValueState[&CB].isOverdefined())
1275         return;
1276 
1277       Value *CopyOf = CB.getOperand(0);
1278       ValueLatticeElement CopyOfVal = getValueState(CopyOf);
1279       auto *PI = getPredicateInfoFor(&CB);
1280       assert(PI && "Missing predicate info for ssa.copy");
1281 
1282       const Optional<PredicateConstraint> &Constraint = PI->getConstraint();
1283       if (!Constraint) {
1284         mergeInValue(ValueState[&CB], &CB, CopyOfVal);
1285         return;
1286       }
1287 
1288       CmpInst::Predicate Pred = Constraint->Predicate;
1289       Value *OtherOp = Constraint->OtherOp;
1290 
1291       // Wait until OtherOp is resolved.
1292       if (getValueState(OtherOp).isUnknown()) {
1293         addAdditionalUser(OtherOp, &CB);
1294         return;
1295       }
1296 
1297       // TODO: Actually filp MayIncludeUndef for the created range to false,
1298       // once most places in the optimizer respect the branches on
1299       // undef/poison are UB rule. The reason why the new range cannot be
1300       // undef is as follows below:
1301       // The new range is based on a branch condition. That guarantees that
1302       // neither of the compare operands can be undef in the branch targets,
1303       // unless we have conditions that are always true/false (e.g. icmp ule
1304       // i32, %a, i32_max). For the latter overdefined/empty range will be
1305       // inferred, but the branch will get folded accordingly anyways.
1306       bool MayIncludeUndef = !isa<PredicateAssume>(PI);
1307 
1308       ValueLatticeElement CondVal = getValueState(OtherOp);
1309       ValueLatticeElement &IV = ValueState[&CB];
1310       if (CondVal.isConstantRange() || CopyOfVal.isConstantRange()) {
1311         auto ImposedCR =
1312             ConstantRange::getFull(DL.getTypeSizeInBits(CopyOf->getType()));
1313 
1314         // Get the range imposed by the condition.
1315         if (CondVal.isConstantRange())
1316           ImposedCR = ConstantRange::makeAllowedICmpRegion(
1317               Pred, CondVal.getConstantRange());
1318 
1319         // Combine range info for the original value with the new range from the
1320         // condition.
1321         auto CopyOfCR = CopyOfVal.isConstantRange()
1322                             ? CopyOfVal.getConstantRange()
1323                             : ConstantRange::getFull(
1324                                   DL.getTypeSizeInBits(CopyOf->getType()));
1325         auto NewCR = ImposedCR.intersectWith(CopyOfCR);
1326         // If the existing information is != x, do not use the information from
1327         // a chained predicate, as the != x information is more likely to be
1328         // helpful in practice.
1329         if (!CopyOfCR.contains(NewCR) && CopyOfCR.getSingleMissingElement())
1330           NewCR = CopyOfCR;
1331 
1332         addAdditionalUser(OtherOp, &CB);
1333         mergeInValue(
1334             IV, &CB,
1335             ValueLatticeElement::getRange(NewCR, MayIncludeUndef));
1336         return;
1337       } else if (Pred == CmpInst::ICMP_EQ && CondVal.isConstant()) {
1338         // For non-integer values or integer constant expressions, only
1339         // propagate equal constants.
1340         addAdditionalUser(OtherOp, &CB);
1341         mergeInValue(IV, &CB, CondVal);
1342         return;
1343       } else if (Pred == CmpInst::ICMP_NE && CondVal.isConstant() &&
1344                  !MayIncludeUndef) {
1345         // Propagate inequalities.
1346         addAdditionalUser(OtherOp, &CB);
1347         mergeInValue(IV, &CB,
1348                      ValueLatticeElement::getNot(CondVal.getConstant()));
1349         return;
1350       }
1351 
1352       return (void)mergeInValue(IV, &CB, CopyOfVal);
1353     }
1354 
1355     if (ConstantRange::isIntrinsicSupported(II->getIntrinsicID())) {
1356       // Compute result range for intrinsics supported by ConstantRange.
1357       // Do this even if we don't know a range for all operands, as we may
1358       // still know something about the result range, e.g. of abs(x).
1359       SmallVector<ConstantRange, 2> OpRanges;
1360       for (Value *Op : II->args()) {
1361         const ValueLatticeElement &State = getValueState(Op);
1362         if (State.isConstantRange())
1363           OpRanges.push_back(State.getConstantRange());
1364         else
1365           OpRanges.push_back(
1366               ConstantRange::getFull(Op->getType()->getScalarSizeInBits()));
1367       }
1368 
1369       ConstantRange Result =
1370           ConstantRange::intrinsic(II->getIntrinsicID(), OpRanges);
1371       return (void)mergeInValue(II, ValueLatticeElement::getRange(Result));
1372     }
1373   }
1374 
1375   // The common case is that we aren't tracking the callee, either because we
1376   // are not doing interprocedural analysis or the callee is indirect, or is
1377   // external.  Handle these cases first.
1378   if (!F || F->isDeclaration())
1379     return handleCallOverdefined(CB);
1380 
1381   // If this is a single/zero retval case, see if we're tracking the function.
1382   if (auto *STy = dyn_cast<StructType>(F->getReturnType())) {
1383     if (!MRVFunctionsTracked.count(F))
1384       return handleCallOverdefined(CB); // Not tracking this callee.
1385 
1386     // If we are tracking this callee, propagate the result of the function
1387     // into this call site.
1388     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1389       mergeInValue(getStructValueState(&CB, i), &CB,
1390                    TrackedMultipleRetVals[std::make_pair(F, i)],
1391                    getMaxWidenStepsOpts());
1392   } else {
1393     auto TFRVI = TrackedRetVals.find(F);
1394     if (TFRVI == TrackedRetVals.end())
1395       return handleCallOverdefined(CB); // Not tracking this callee.
1396 
1397     // If so, propagate the return value of the callee into this call result.
1398     mergeInValue(&CB, TFRVI->second, getMaxWidenStepsOpts());
1399   }
1400 }
1401 
1402 void SCCPSolver::Solve() {
1403   // Process the work lists until they are empty!
1404   while (!BBWorkList.empty() || !InstWorkList.empty() ||
1405          !OverdefinedInstWorkList.empty()) {
1406     // Process the overdefined instruction's work list first, which drives other
1407     // things to overdefined more quickly.
1408     while (!OverdefinedInstWorkList.empty()) {
1409       Value *I = OverdefinedInstWorkList.pop_back_val();
1410 
1411       LLVM_DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n');
1412 
1413       // "I" got into the work list because it either made the transition from
1414       // bottom to constant, or to overdefined.
1415       //
1416       // Anything on this worklist that is overdefined need not be visited
1417       // since all of its users will have already been marked as overdefined
1418       // Update all of the users of this instruction's value.
1419       //
1420       markUsersAsChanged(I);
1421     }
1422 
1423     // Process the instruction work list.
1424     while (!InstWorkList.empty()) {
1425       Value *I = InstWorkList.pop_back_val();
1426 
1427       LLVM_DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n');
1428 
1429       // "I" got into the work list because it made the transition from undef to
1430       // constant.
1431       //
1432       // Anything on this worklist that is overdefined need not be visited
1433       // since all of its users will have already been marked as overdefined.
1434       // Update all of the users of this instruction's value.
1435       //
1436       if (I->getType()->isStructTy() || !getValueState(I).isOverdefined())
1437         markUsersAsChanged(I);
1438     }
1439 
1440     // Process the basic block work list.
1441     while (!BBWorkList.empty()) {
1442       BasicBlock *BB = BBWorkList.pop_back_val();
1443 
1444       LLVM_DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n');
1445 
1446       // Notify all instructions in this basic block that they are newly
1447       // executable.
1448       visit(BB);
1449     }
1450   }
1451 }
1452 
1453 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
1454 /// that branches on undef values cannot reach any of their successors.
1455 /// However, this is not a safe assumption.  After we solve dataflow, this
1456 /// method should be use to handle this.  If this returns true, the solver
1457 /// should be rerun.
1458 ///
1459 /// This method handles this by finding an unresolved branch and marking it one
1460 /// of the edges from the block as being feasible, even though the condition
1461 /// doesn't say it would otherwise be.  This allows SCCP to find the rest of the
1462 /// CFG and only slightly pessimizes the analysis results (by marking one,
1463 /// potentially infeasible, edge feasible).  This cannot usefully modify the
1464 /// constraints on the condition of the branch, as that would impact other users
1465 /// of the value.
1466 ///
1467 /// This scan also checks for values that use undefs. It conservatively marks
1468 /// them as overdefined.
1469 bool SCCPSolver::ResolvedUndefsIn(Function &F) {
1470   bool MadeChange = false;
1471   for (BasicBlock &BB : F) {
1472     if (!BBExecutable.count(&BB))
1473       continue;
1474 
1475     for (Instruction &I : BB) {
1476       // Look for instructions which produce undef values.
1477       if (I.getType()->isVoidTy()) continue;
1478 
1479       if (auto *STy = dyn_cast<StructType>(I.getType())) {
1480         // Only a few things that can be structs matter for undef.
1481 
1482         // Tracked calls must never be marked overdefined in ResolvedUndefsIn.
1483         if (auto *CB = dyn_cast<CallBase>(&I))
1484           if (Function *F = CB->getCalledFunction())
1485             if (MRVFunctionsTracked.count(F))
1486               continue;
1487 
1488         // extractvalue and insertvalue don't need to be marked; they are
1489         // tracked as precisely as their operands.
1490         if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(I))
1491           continue;
1492         // Send the results of everything else to overdefined.  We could be
1493         // more precise than this but it isn't worth bothering.
1494         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1495           ValueLatticeElement &LV = getStructValueState(&I, i);
1496           if (LV.isUnknownOrUndef()) {
1497             markOverdefined(LV, &I);
1498             MadeChange = true;
1499           }
1500         }
1501         continue;
1502       }
1503 
1504       ValueLatticeElement &LV = getValueState(&I);
1505       if (!LV.isUnknownOrUndef())
1506         continue;
1507 
1508       // There are two reasons a call can have an undef result
1509       // 1. It could be tracked.
1510       // 2. It could be constant-foldable.
1511       // Because of the way we solve return values, tracked calls must
1512       // never be marked overdefined in ResolvedUndefsIn.
1513       if (auto *CB = dyn_cast<CallBase>(&I))
1514         if (Function *F = CB->getCalledFunction())
1515           if (TrackedRetVals.count(F))
1516             continue;
1517 
1518       if (isa<LoadInst>(I)) {
1519         // A load here means one of two things: a load of undef from a global,
1520         // a load from an unknown pointer.  Either way, having it return undef
1521         // is okay.
1522         continue;
1523       }
1524 
1525       markOverdefined(&I);
1526       MadeChange = true;
1527     }
1528 
1529     // Check to see if we have a branch or switch on an undefined value.  If so
1530     // we force the branch to go one way or the other to make the successor
1531     // values live.  It doesn't really matter which way we force it.
1532     Instruction *TI = BB.getTerminator();
1533     if (auto *BI = dyn_cast<BranchInst>(TI)) {
1534       if (!BI->isConditional()) continue;
1535       if (!getValueState(BI->getCondition()).isUnknownOrUndef())
1536         continue;
1537 
1538       // If the input to SCCP is actually branch on undef, fix the undef to
1539       // false.
1540       if (isa<UndefValue>(BI->getCondition())) {
1541         BI->setCondition(ConstantInt::getFalse(BI->getContext()));
1542         markEdgeExecutable(&BB, TI->getSuccessor(1));
1543         MadeChange = true;
1544         continue;
1545       }
1546 
1547       // Otherwise, it is a branch on a symbolic value which is currently
1548       // considered to be undef.  Make sure some edge is executable, so a
1549       // branch on "undef" always flows somewhere.
1550       // FIXME: Distinguish between dead code and an LLVM "undef" value.
1551       BasicBlock *DefaultSuccessor = TI->getSuccessor(1);
1552       if (markEdgeExecutable(&BB, DefaultSuccessor))
1553         MadeChange = true;
1554 
1555       continue;
1556     }
1557 
1558    if (auto *IBR = dyn_cast<IndirectBrInst>(TI)) {
1559       // Indirect branch with no successor ?. Its ok to assume it branches
1560       // to no target.
1561       if (IBR->getNumSuccessors() < 1)
1562         continue;
1563 
1564       if (!getValueState(IBR->getAddress()).isUnknownOrUndef())
1565         continue;
1566 
1567       // If the input to SCCP is actually branch on undef, fix the undef to
1568       // the first successor of the indirect branch.
1569       if (isa<UndefValue>(IBR->getAddress())) {
1570         IBR->setAddress(BlockAddress::get(IBR->getSuccessor(0)));
1571         markEdgeExecutable(&BB, IBR->getSuccessor(0));
1572         MadeChange = true;
1573         continue;
1574       }
1575 
1576       // Otherwise, it is a branch on a symbolic value which is currently
1577       // considered to be undef.  Make sure some edge is executable, so a
1578       // branch on "undef" always flows somewhere.
1579       // FIXME: IndirectBr on "undef" doesn't actually need to go anywhere:
1580       // we can assume the branch has undefined behavior instead.
1581       BasicBlock *DefaultSuccessor = IBR->getSuccessor(0);
1582       if (markEdgeExecutable(&BB, DefaultSuccessor))
1583         MadeChange = true;
1584 
1585       continue;
1586     }
1587 
1588     if (auto *SI = dyn_cast<SwitchInst>(TI)) {
1589       if (!SI->getNumCases() ||
1590           !getValueState(SI->getCondition()).isUnknownOrUndef())
1591         continue;
1592 
1593       // If the input to SCCP is actually switch on undef, fix the undef to
1594       // the first constant.
1595       if (isa<UndefValue>(SI->getCondition())) {
1596         SI->setCondition(SI->case_begin()->getCaseValue());
1597         markEdgeExecutable(&BB, SI->case_begin()->getCaseSuccessor());
1598         MadeChange = true;
1599         continue;
1600       }
1601 
1602       // Otherwise, it is a branch on a symbolic value which is currently
1603       // considered to be undef.  Make sure some edge is executable, so a
1604       // branch on "undef" always flows somewhere.
1605       // FIXME: Distinguish between dead code and an LLVM "undef" value.
1606       BasicBlock *DefaultSuccessor = SI->case_begin()->getCaseSuccessor();
1607       if (markEdgeExecutable(&BB, DefaultSuccessor))
1608         MadeChange = true;
1609 
1610       continue;
1611     }
1612   }
1613 
1614   return MadeChange;
1615 }
1616 
1617 static bool tryToReplaceWithConstant(SCCPSolver &Solver, Value *V) {
1618   Constant *Const = nullptr;
1619   if (V->getType()->isStructTy()) {
1620     std::vector<ValueLatticeElement> IVs = Solver.getStructLatticeValueFor(V);
1621     if (any_of(IVs,
1622                [](const ValueLatticeElement &LV) { return isOverdefined(LV); }))
1623       return false;
1624     std::vector<Constant *> ConstVals;
1625     auto *ST = cast<StructType>(V->getType());
1626     for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1627       ValueLatticeElement V = IVs[i];
1628       ConstVals.push_back(isConstant(V)
1629                               ? Solver.getConstant(V)
1630                               : UndefValue::get(ST->getElementType(i)));
1631     }
1632     Const = ConstantStruct::get(ST, ConstVals);
1633   } else {
1634     const ValueLatticeElement &IV = Solver.getLatticeValueFor(V);
1635     if (isOverdefined(IV))
1636       return false;
1637 
1638     Const =
1639         isConstant(IV) ? Solver.getConstant(IV) : UndefValue::get(V->getType());
1640   }
1641   assert(Const && "Constant is nullptr here!");
1642 
1643   // Replacing `musttail` instructions with constant breaks `musttail` invariant
1644   // unless the call itself can be removed.
1645   // Calls with "clang.arc.attachedcall" implicitly use the return value and
1646   // those uses cannot be updated with a constant.
1647   CallBase *CB = dyn_cast<CallBase>(V);
1648   if (CB && ((CB->isMustTailCall() && !CB->isSafeToRemove()) ||
1649              CB->getOperandBundle(LLVMContext::OB_clang_arc_attachedcall))) {
1650     Function *F = CB->getCalledFunction();
1651 
1652     // Don't zap returns of the callee
1653     if (F)
1654       Solver.addToMustPreserveReturnsInFunctions(F);
1655 
1656     LLVM_DEBUG(dbgs() << "  Can\'t treat the result of call " << *CB
1657                       << " as a constant\n");
1658     return false;
1659   }
1660 
1661   LLVM_DEBUG(dbgs() << "  Constant: " << *Const << " = " << *V << '\n');
1662 
1663   // Replaces all of the uses of a variable with uses of the constant.
1664   V->replaceAllUsesWith(Const);
1665   return true;
1666 }
1667 
1668 static bool simplifyInstsInBlock(SCCPSolver &Solver, BasicBlock &BB,
1669                                  SmallPtrSetImpl<Value *> &InsertedValues,
1670                                  Statistic &InstRemovedStat,
1671                                  Statistic &InstReplacedStat) {
1672   bool MadeChanges = false;
1673   for (Instruction &Inst : make_early_inc_range(BB)) {
1674     if (Inst.getType()->isVoidTy())
1675       continue;
1676     if (tryToReplaceWithConstant(Solver, &Inst)) {
1677       if (Inst.isSafeToRemove())
1678         Inst.eraseFromParent();
1679       // Hey, we just changed something!
1680       MadeChanges = true;
1681       ++InstRemovedStat;
1682     } else if (isa<SExtInst>(&Inst)) {
1683       Value *ExtOp = Inst.getOperand(0);
1684       if (isa<Constant>(ExtOp) || InsertedValues.count(ExtOp))
1685         continue;
1686       const ValueLatticeElement &IV = Solver.getLatticeValueFor(ExtOp);
1687       if (!IV.isConstantRange(/*UndefAllowed=*/false))
1688         continue;
1689       if (IV.getConstantRange().isAllNonNegative()) {
1690         auto *ZExt = new ZExtInst(ExtOp, Inst.getType(), "", &Inst);
1691         InsertedValues.insert(ZExt);
1692         Inst.replaceAllUsesWith(ZExt);
1693         Solver.removeLatticeValueFor(&Inst);
1694         Inst.eraseFromParent();
1695         InstReplacedStat++;
1696         MadeChanges = true;
1697       }
1698     }
1699   }
1700   return MadeChanges;
1701 }
1702 
1703 // runSCCP() - Run the Sparse Conditional Constant Propagation algorithm,
1704 // and return true if the function was modified.
1705 static bool runSCCP(Function &F, const DataLayout &DL,
1706                     const TargetLibraryInfo *TLI) {
1707   LLVM_DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n");
1708   SCCPSolver Solver(
1709       DL, [TLI](Function &F) -> const TargetLibraryInfo & { return *TLI; },
1710       F.getContext());
1711 
1712   // Mark the first block of the function as being executable.
1713   Solver.MarkBlockExecutable(&F.front());
1714 
1715   // Mark all arguments to the function as being overdefined.
1716   for (Argument &AI : F.args())
1717     Solver.markOverdefined(&AI);
1718 
1719   // Solve for constants.
1720   bool ResolvedUndefs = true;
1721   while (ResolvedUndefs) {
1722     Solver.Solve();
1723     LLVM_DEBUG(dbgs() << "RESOLVING UNDEFs\n");
1724     ResolvedUndefs = Solver.ResolvedUndefsIn(F);
1725   }
1726 
1727   bool MadeChanges = false;
1728 
1729   // If we decided that there are basic blocks that are dead in this function,
1730   // delete their contents now.  Note that we cannot actually delete the blocks,
1731   // as we cannot modify the CFG of the function.
1732 
1733   SmallPtrSet<Value *, 32> InsertedValues;
1734   for (BasicBlock &BB : F) {
1735     if (!Solver.isBlockExecutable(&BB)) {
1736       LLVM_DEBUG(dbgs() << "  BasicBlock Dead:" << BB);
1737 
1738       ++NumDeadBlocks;
1739       NumInstRemoved += removeAllNonTerminatorAndEHPadInstructions(&BB).first;
1740 
1741       MadeChanges = true;
1742       continue;
1743     }
1744 
1745     MadeChanges |= simplifyInstsInBlock(Solver, BB, InsertedValues,
1746                                         NumInstRemoved, NumInstReplaced);
1747   }
1748 
1749   return MadeChanges;
1750 }
1751 
1752 PreservedAnalyses SCCPPass::run(Function &F, FunctionAnalysisManager &AM) {
1753   const DataLayout &DL = F.getParent()->getDataLayout();
1754   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1755   if (!runSCCP(F, DL, &TLI))
1756     return PreservedAnalyses::all();
1757 
1758   auto PA = PreservedAnalyses();
1759   PA.preserve<GlobalsAA>();
1760   PA.preserveSet<CFGAnalyses>();
1761   return PA;
1762 }
1763 
1764 namespace {
1765 
1766 //===--------------------------------------------------------------------===//
1767 //
1768 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
1769 /// Sparse Conditional Constant Propagator.
1770 ///
1771 class SCCPLegacyPass : public FunctionPass {
1772 public:
1773   // Pass identification, replacement for typeid
1774   static char ID;
1775 
1776   SCCPLegacyPass() : FunctionPass(ID) {
1777     initializeSCCPLegacyPassPass(*PassRegistry::getPassRegistry());
1778   }
1779 
1780   void getAnalysisUsage(AnalysisUsage &AU) const override {
1781     AU.addRequired<TargetLibraryInfoWrapperPass>();
1782     AU.addPreserved<GlobalsAAWrapperPass>();
1783     AU.setPreservesCFG();
1784   }
1785 
1786   // runOnFunction - Run the Sparse Conditional Constant Propagation
1787   // algorithm, and return true if the function was modified.
1788   bool runOnFunction(Function &F) override {
1789     if (skipFunction(F))
1790       return false;
1791     const DataLayout &DL = F.getParent()->getDataLayout();
1792     const TargetLibraryInfo *TLI =
1793         &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
1794     return runSCCP(F, DL, TLI);
1795   }
1796 };
1797 
1798 } // end anonymous namespace
1799 
1800 char SCCPLegacyPass::ID = 0;
1801 
1802 INITIALIZE_PASS_BEGIN(SCCPLegacyPass, "sccp",
1803                       "Sparse Conditional Constant Propagation", false, false)
1804 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1805 INITIALIZE_PASS_END(SCCPLegacyPass, "sccp",
1806                     "Sparse Conditional Constant Propagation", false, false)
1807 
1808 // createSCCPPass - This is the public interface to this file.
1809 FunctionPass *llvm::createSCCPPass() { return new SCCPLegacyPass(); }
1810 
1811 static void findReturnsToZap(Function &F,
1812                              SmallVector<ReturnInst *, 8> &ReturnsToZap,
1813                              SCCPSolver &Solver) {
1814   // We can only do this if we know that nothing else can call the function.
1815   if (!Solver.isArgumentTrackedFunction(&F))
1816     return;
1817 
1818   if (Solver.mustPreserveReturn(&F)) {
1819     LLVM_DEBUG(
1820         dbgs()
1821         << "Can't zap returns of the function : " << F.getName()
1822         << " due to present musttail or \"clang.arc.attachedcall\" call of "
1823            "it\n");
1824     return;
1825   }
1826 
1827   assert(
1828       all_of(F.users(),
1829              [&Solver](User *U) {
1830                if (isa<Instruction>(U) &&
1831                    !Solver.isBlockExecutable(cast<Instruction>(U)->getParent()))
1832                  return true;
1833                // Non-callsite uses are not impacted by zapping. Also, constant
1834                // uses (like blockaddresses) could stuck around, without being
1835                // used in the underlying IR, meaning we do not have lattice
1836                // values for them.
1837                if (!isa<CallBase>(U))
1838                  return true;
1839                if (U->getType()->isStructTy()) {
1840                  return all_of(Solver.getStructLatticeValueFor(U),
1841                                [](const ValueLatticeElement &LV) {
1842                                  return !isOverdefined(LV);
1843                                });
1844                }
1845                return !isOverdefined(Solver.getLatticeValueFor(U));
1846              }) &&
1847       "We can only zap functions where all live users have a concrete value");
1848 
1849   for (BasicBlock &BB : F) {
1850     if (CallInst *CI = BB.getTerminatingMustTailCall()) {
1851       LLVM_DEBUG(dbgs() << "Can't zap return of the block due to present "
1852                         << "musttail call : " << *CI << "\n");
1853       (void)CI;
1854       return;
1855     }
1856 
1857     if (auto *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
1858       if (!isa<UndefValue>(RI->getOperand(0)))
1859         ReturnsToZap.push_back(RI);
1860   }
1861 }
1862 
1863 static bool removeNonFeasibleEdges(const SCCPSolver &Solver, BasicBlock *BB,
1864                                    DomTreeUpdater &DTU) {
1865   SmallPtrSet<BasicBlock *, 8> FeasibleSuccessors;
1866   bool HasNonFeasibleEdges = false;
1867   for (BasicBlock *Succ : successors(BB)) {
1868     if (Solver.isEdgeFeasible(BB, Succ))
1869       FeasibleSuccessors.insert(Succ);
1870     else
1871       HasNonFeasibleEdges = true;
1872   }
1873 
1874   // All edges feasible, nothing to do.
1875   if (!HasNonFeasibleEdges)
1876     return false;
1877 
1878   // SCCP can only determine non-feasible edges for br, switch and indirectbr.
1879   Instruction *TI = BB->getTerminator();
1880   assert((isa<BranchInst>(TI) || isa<SwitchInst>(TI) ||
1881           isa<IndirectBrInst>(TI)) &&
1882          "Terminator must be a br, switch or indirectbr");
1883 
1884   if (FeasibleSuccessors.size() == 1) {
1885     // Replace with an unconditional branch to the only feasible successor.
1886     BasicBlock *OnlyFeasibleSuccessor = *FeasibleSuccessors.begin();
1887     SmallVector<DominatorTree::UpdateType, 8> Updates;
1888     bool HaveSeenOnlyFeasibleSuccessor = false;
1889     for (BasicBlock *Succ : successors(BB)) {
1890       if (Succ == OnlyFeasibleSuccessor && !HaveSeenOnlyFeasibleSuccessor) {
1891         // Don't remove the edge to the only feasible successor the first time
1892         // we see it. We still do need to remove any multi-edges to it though.
1893         HaveSeenOnlyFeasibleSuccessor = true;
1894         continue;
1895       }
1896 
1897       Succ->removePredecessor(BB);
1898       Updates.push_back({DominatorTree::Delete, BB, Succ});
1899     }
1900 
1901     BranchInst::Create(OnlyFeasibleSuccessor, BB);
1902     TI->eraseFromParent();
1903     DTU.applyUpdatesPermissive(Updates);
1904   } else if (FeasibleSuccessors.size() > 1) {
1905     SwitchInstProfUpdateWrapper SI(*cast<SwitchInst>(TI));
1906     SmallVector<DominatorTree::UpdateType, 8> Updates;
1907     for (auto CI = SI->case_begin(); CI != SI->case_end();) {
1908       if (FeasibleSuccessors.contains(CI->getCaseSuccessor())) {
1909         ++CI;
1910         continue;
1911       }
1912 
1913       BasicBlock *Succ = CI->getCaseSuccessor();
1914       Succ->removePredecessor(BB);
1915       Updates.push_back({DominatorTree::Delete, BB, Succ});
1916       SI.removeCase(CI);
1917       // Don't increment CI, as we removed a case.
1918     }
1919 
1920     DTU.applyUpdatesPermissive(Updates);
1921   } else {
1922     llvm_unreachable("Must have at least one feasible successor");
1923   }
1924   return true;
1925 }
1926 
1927 bool llvm::runIPSCCP(
1928     Module &M, const DataLayout &DL,
1929     std::function<const TargetLibraryInfo &(Function &)> GetTLI,
1930     function_ref<AnalysisResultsForFn(Function &)> getAnalysis) {
1931   SCCPSolver Solver(DL, GetTLI, M.getContext());
1932 
1933   // Loop over all functions, marking arguments to those with their addresses
1934   // taken or that are external as overdefined.
1935   for (Function &F : M) {
1936     if (F.isDeclaration())
1937       continue;
1938 
1939     Solver.addAnalysis(F, getAnalysis(F));
1940 
1941     // Determine if we can track the function's return values. If so, add the
1942     // function to the solver's set of return-tracked functions.
1943     if (canTrackReturnsInterprocedurally(&F))
1944       Solver.AddTrackedFunction(&F);
1945 
1946     // Determine if we can track the function's arguments. If so, add the
1947     // function to the solver's set of argument-tracked functions.
1948     if (canTrackArgumentsInterprocedurally(&F)) {
1949       Solver.AddArgumentTrackedFunction(&F);
1950       continue;
1951     }
1952 
1953     // Assume the function is called.
1954     Solver.MarkBlockExecutable(&F.front());
1955 
1956     // Assume nothing about the incoming arguments.
1957     for (Argument &AI : F.args())
1958       Solver.markOverdefined(&AI);
1959   }
1960 
1961   // Determine if we can track any of the module's global variables. If so, add
1962   // the global variables we can track to the solver's set of tracked global
1963   // variables.
1964   for (GlobalVariable &G : M.globals()) {
1965     G.removeDeadConstantUsers();
1966     if (canTrackGlobalVariableInterprocedurally(&G))
1967       Solver.TrackValueOfGlobalVariable(&G);
1968   }
1969 
1970   // Solve for constants.
1971   bool ResolvedUndefs = true;
1972   Solver.Solve();
1973   while (ResolvedUndefs) {
1974     LLVM_DEBUG(dbgs() << "RESOLVING UNDEFS\n");
1975     ResolvedUndefs = false;
1976     for (Function &F : M) {
1977       if (Solver.ResolvedUndefsIn(F))
1978         ResolvedUndefs = true;
1979     }
1980     if (ResolvedUndefs)
1981       Solver.Solve();
1982   }
1983 
1984   bool MadeChanges = false;
1985 
1986   // Iterate over all of the instructions in the module, replacing them with
1987   // constants if we have found them to be of constant values.
1988 
1989   for (Function &F : M) {
1990     if (F.isDeclaration())
1991       continue;
1992 
1993     SmallVector<BasicBlock *, 512> BlocksToErase;
1994 
1995     if (Solver.isBlockExecutable(&F.front())) {
1996       bool ReplacedPointerArg = false;
1997       for (Argument &Arg : F.args()) {
1998         if (!Arg.use_empty() && tryToReplaceWithConstant(Solver, &Arg)) {
1999           ReplacedPointerArg |= Arg.getType()->isPointerTy();
2000           ++IPNumArgsElimed;
2001         }
2002       }
2003 
2004       // If we replaced an argument, the argmemonly and
2005       // inaccessiblemem_or_argmemonly attributes do not hold any longer. Remove
2006       // them from both the function and callsites.
2007       if (ReplacedPointerArg) {
2008         AttrBuilder AttributesToRemove;
2009         AttributesToRemove.addAttribute(Attribute::ArgMemOnly);
2010         AttributesToRemove.addAttribute(Attribute::InaccessibleMemOrArgMemOnly);
2011         F.removeAttributes(AttributeList::FunctionIndex, AttributesToRemove);
2012 
2013         for (User *U : F.users()) {
2014           auto *CB = dyn_cast<CallBase>(U);
2015           if (!CB || CB->getCalledFunction() != &F)
2016             continue;
2017 
2018           CB->removeAttributes(AttributeList::FunctionIndex,
2019                                AttributesToRemove);
2020         }
2021       }
2022     }
2023 
2024     SmallPtrSet<Value *, 32> InsertedValues;
2025     for (BasicBlock &BB : F) {
2026       if (!Solver.isBlockExecutable(&BB)) {
2027         LLVM_DEBUG(dbgs() << "  BasicBlock Dead:" << BB);
2028         ++NumDeadBlocks;
2029 
2030         MadeChanges = true;
2031 
2032         if (&BB != &F.front())
2033           BlocksToErase.push_back(&BB);
2034         continue;
2035       }
2036 
2037       MadeChanges |= simplifyInstsInBlock(Solver, BB, InsertedValues,
2038                                           IPNumInstRemoved, IPNumInstReplaced);
2039     }
2040 
2041     DomTreeUpdater DTU = Solver.getDTU(F);
2042     // Change dead blocks to unreachable. We do it after replacing constants
2043     // in all executable blocks, because changeToUnreachable may remove PHI
2044     // nodes in executable blocks we found values for. The function's entry
2045     // block is not part of BlocksToErase, so we have to handle it separately.
2046     for (BasicBlock *BB : BlocksToErase) {
2047       NumInstRemoved +=
2048           changeToUnreachable(BB->getFirstNonPHI(), /*UseLLVMTrap=*/false,
2049                               /*PreserveLCSSA=*/false, &DTU);
2050     }
2051     if (!Solver.isBlockExecutable(&F.front()))
2052       NumInstRemoved += changeToUnreachable(F.front().getFirstNonPHI(),
2053                                             /*UseLLVMTrap=*/false,
2054                                             /*PreserveLCSSA=*/false, &DTU);
2055 
2056     for (BasicBlock &BB : F)
2057       MadeChanges |= removeNonFeasibleEdges(Solver, &BB, DTU);
2058 
2059     for (BasicBlock *DeadBB : BlocksToErase)
2060       DTU.deleteBB(DeadBB);
2061 
2062     for (BasicBlock &BB : F) {
2063       for (BasicBlock::iterator BI = BB.begin(), E = BB.end(); BI != E;) {
2064         Instruction *Inst = &*BI++;
2065         if (Solver.getPredicateInfoFor(Inst)) {
2066           if (auto *II = dyn_cast<IntrinsicInst>(Inst)) {
2067             if (II->getIntrinsicID() == Intrinsic::ssa_copy) {
2068               Value *Op = II->getOperand(0);
2069               Inst->replaceAllUsesWith(Op);
2070               Inst->eraseFromParent();
2071             }
2072           }
2073         }
2074       }
2075     }
2076   }
2077 
2078   // If we inferred constant or undef return values for a function, we replaced
2079   // all call uses with the inferred value.  This means we don't need to bother
2080   // actually returning anything from the function.  Replace all return
2081   // instructions with return undef.
2082   //
2083   // Do this in two stages: first identify the functions we should process, then
2084   // actually zap their returns.  This is important because we can only do this
2085   // if the address of the function isn't taken.  In cases where a return is the
2086   // last use of a function, the order of processing functions would affect
2087   // whether other functions are optimizable.
2088   SmallVector<ReturnInst*, 8> ReturnsToZap;
2089 
2090   for (const auto &I : Solver.getTrackedRetVals()) {
2091     Function *F = I.first;
2092     const ValueLatticeElement &ReturnValue = I.second;
2093 
2094     // If there is a known constant range for the return value, add !range
2095     // metadata to the function's call sites.
2096     if (ReturnValue.isConstantRange() &&
2097         !ReturnValue.getConstantRange().isSingleElement()) {
2098       // Do not add range metadata if the return value may include undef.
2099       if (ReturnValue.isConstantRangeIncludingUndef())
2100         continue;
2101 
2102       auto &CR = ReturnValue.getConstantRange();
2103       for (User *User : F->users()) {
2104         auto *CB = dyn_cast<CallBase>(User);
2105         if (!CB || CB->getCalledFunction() != F)
2106           continue;
2107 
2108         // Limit to cases where the return value is guaranteed to be neither
2109         // poison nor undef. Poison will be outside any range and currently
2110         // values outside of the specified range cause immediate undefined
2111         // behavior.
2112         if (!isGuaranteedNotToBeUndefOrPoison(CB, nullptr, CB))
2113           continue;
2114 
2115         // Do not touch existing metadata for now.
2116         // TODO: We should be able to take the intersection of the existing
2117         // metadata and the inferred range.
2118         if (CB->getMetadata(LLVMContext::MD_range))
2119           continue;
2120 
2121         LLVMContext &Context = CB->getParent()->getContext();
2122         Metadata *RangeMD[] = {
2123             ConstantAsMetadata::get(ConstantInt::get(Context, CR.getLower())),
2124             ConstantAsMetadata::get(ConstantInt::get(Context, CR.getUpper()))};
2125         CB->setMetadata(LLVMContext::MD_range, MDNode::get(Context, RangeMD));
2126       }
2127       continue;
2128     }
2129     if (F->getReturnType()->isVoidTy())
2130       continue;
2131     if (isConstant(ReturnValue) || ReturnValue.isUnknownOrUndef())
2132       findReturnsToZap(*F, ReturnsToZap, Solver);
2133   }
2134 
2135   for (auto F : Solver.getMRVFunctionsTracked()) {
2136     assert(F->getReturnType()->isStructTy() &&
2137            "The return type should be a struct");
2138     StructType *STy = cast<StructType>(F->getReturnType());
2139     if (Solver.isStructLatticeConstant(F, STy))
2140       findReturnsToZap(*F, ReturnsToZap, Solver);
2141   }
2142 
2143   // Zap all returns which we've identified as zap to change.
2144   SmallSetVector<Function *, 8> FuncZappedReturn;
2145   for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) {
2146     Function *F = ReturnsToZap[i]->getParent()->getParent();
2147     ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType()));
2148     // Record all functions that are zapped.
2149     FuncZappedReturn.insert(F);
2150   }
2151 
2152   // Remove the returned attribute for zapped functions and the
2153   // corresponding call sites.
2154   for (Function *F : FuncZappedReturn) {
2155     for (Argument &A : F->args())
2156       F->removeParamAttr(A.getArgNo(), Attribute::Returned);
2157     for (Use &U : F->uses()) {
2158       // Skip over blockaddr users.
2159       if (isa<BlockAddress>(U.getUser()))
2160         continue;
2161       CallBase *CB = cast<CallBase>(U.getUser());
2162       for (Use &Arg : CB->args())
2163         CB->removeParamAttr(CB->getArgOperandNo(&Arg), Attribute::Returned);
2164     }
2165   }
2166 
2167   // If we inferred constant or undef values for globals variables, we can
2168   // delete the global and any stores that remain to it.
2169   for (auto &I : make_early_inc_range(Solver.getTrackedGlobals())) {
2170     GlobalVariable *GV = I.first;
2171     if (isOverdefined(I.second))
2172       continue;
2173     LLVM_DEBUG(dbgs() << "Found that GV '" << GV->getName()
2174                       << "' is constant!\n");
2175     while (!GV->use_empty()) {
2176       StoreInst *SI = cast<StoreInst>(GV->user_back());
2177       SI->eraseFromParent();
2178       MadeChanges = true;
2179     }
2180     M.getGlobalList().erase(GV);
2181     ++IPNumGlobalConst;
2182   }
2183 
2184   return MadeChanges;
2185 }
2186