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