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