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