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   // ResolvedUndefsIn might mark I as overdefined. Bail out, even if we would
824   // discover a concrete value later.
825   if (ValueState[&I].isOverdefined())
826     return;
827 
828   Function *F = I.getParent()->getParent();
829   Value *ResultOp = I.getOperand(0);
830 
831   // If we are tracking the return value of this function, merge it in.
832   if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
833     MapVector<Function*, LatticeVal>::iterator TFRVI =
834       TrackedRetVals.find(F);
835     if (TFRVI != TrackedRetVals.end()) {
836       mergeInValue(TFRVI->second, F, getValueState(ResultOp));
837       return;
838     }
839   }
840 
841   // Handle functions that return multiple values.
842   if (!TrackedMultipleRetVals.empty()) {
843     if (auto *STy = dyn_cast<StructType>(ResultOp->getType()))
844       if (MRVFunctionsTracked.count(F))
845         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
846           mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
847                        getStructValueState(ResultOp, i));
848   }
849 }
850 
851 void SCCPSolver::visitTerminator(Instruction &TI) {
852   SmallVector<bool, 16> SuccFeasible;
853   getFeasibleSuccessors(TI, SuccFeasible);
854 
855   BasicBlock *BB = TI.getParent();
856 
857   // Mark all feasible successors executable.
858   for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
859     if (SuccFeasible[i])
860       markEdgeExecutable(BB, TI.getSuccessor(i));
861 }
862 
863 void SCCPSolver::visitCastInst(CastInst &I) {
864   // ResolvedUndefsIn might mark I as overdefined. Bail out, even if we would
865   // discover a concrete value later.
866   if (ValueState[&I].isOverdefined())
867     return;
868 
869   LatticeVal OpSt = getValueState(I.getOperand(0));
870   if (OpSt.isOverdefined())          // Inherit overdefinedness of operand
871     markOverdefined(&I);
872   else if (OpSt.isConstant()) {
873     // Fold the constant as we build.
874     Constant *C = ConstantFoldCastOperand(I.getOpcode(), OpSt.getConstant(),
875                                           I.getType(), DL);
876     if (isa<UndefValue>(C))
877       return;
878     // Propagate constant value
879     markConstant(&I, C);
880   }
881 }
882 
883 void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
884   // ResolvedUndefsIn might mark I as overdefined. Bail out, even if we would
885   // discover a concrete value later.
886   if (ValueState[&EVI].isOverdefined())
887     return;
888 
889   // If this returns a struct, mark all elements over defined, we don't track
890   // structs in structs.
891   if (EVI.getType()->isStructTy())
892     return (void)markOverdefined(&EVI);
893 
894   // If this is extracting from more than one level of struct, we don't know.
895   if (EVI.getNumIndices() != 1)
896     return (void)markOverdefined(&EVI);
897 
898   Value *AggVal = EVI.getAggregateOperand();
899   if (AggVal->getType()->isStructTy()) {
900     unsigned i = *EVI.idx_begin();
901     LatticeVal EltVal = getStructValueState(AggVal, i);
902     mergeInValue(getValueState(&EVI), &EVI, EltVal);
903   } else {
904     // Otherwise, must be extracting from an array.
905     return (void)markOverdefined(&EVI);
906   }
907 }
908 
909 void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
910   auto *STy = dyn_cast<StructType>(IVI.getType());
911   if (!STy)
912     return (void)markOverdefined(&IVI);
913 
914   // ResolvedUndefsIn might mark I as overdefined. Bail out, even if we would
915   // discover a concrete value later.
916   if (ValueState[&IVI].isOverdefined())
917     return;
918 
919   // If this has more than one index, we can't handle it, drive all results to
920   // undef.
921   if (IVI.getNumIndices() != 1)
922     return (void)markOverdefined(&IVI);
923 
924   Value *Aggr = IVI.getAggregateOperand();
925   unsigned Idx = *IVI.idx_begin();
926 
927   // Compute the result based on what we're inserting.
928   for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
929     // This passes through all values that aren't the inserted element.
930     if (i != Idx) {
931       LatticeVal EltVal = getStructValueState(Aggr, i);
932       mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
933       continue;
934     }
935 
936     Value *Val = IVI.getInsertedValueOperand();
937     if (Val->getType()->isStructTy())
938       // We don't track structs in structs.
939       markOverdefined(getStructValueState(&IVI, i), &IVI);
940     else {
941       LatticeVal InVal = getValueState(Val);
942       mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
943     }
944   }
945 }
946 
947 void SCCPSolver::visitSelectInst(SelectInst &I) {
948   // If this select returns a struct, just mark the result overdefined.
949   // TODO: We could do a lot better than this if code actually uses this.
950   if (I.getType()->isStructTy())
951     return (void)markOverdefined(&I);
952 
953   // ResolvedUndefsIn might mark I as overdefined. Bail out, even if we would
954   // discover a concrete value later.
955   if (ValueState[&I].isOverdefined())
956     return;
957 
958   LatticeVal CondValue = getValueState(I.getCondition());
959   if (CondValue.isUnknown())
960     return;
961 
962   if (ConstantInt *CondCB = CondValue.getConstantInt()) {
963     Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
964     mergeInValue(&I, getValueState(OpVal));
965     return;
966   }
967 
968   // Otherwise, the condition is overdefined or a constant we can't evaluate.
969   // See if we can produce something better than overdefined based on the T/F
970   // value.
971   LatticeVal TVal = getValueState(I.getTrueValue());
972   LatticeVal FVal = getValueState(I.getFalseValue());
973 
974   // select ?, C, C -> C.
975   if (TVal.isConstant() && FVal.isConstant() &&
976       TVal.getConstant() == FVal.getConstant())
977     return (void)markConstant(&I, FVal.getConstant());
978 
979   if (TVal.isUnknown())   // select ?, undef, X -> X.
980     return (void)mergeInValue(&I, FVal);
981   if (FVal.isUnknown())   // select ?, X, undef -> X.
982     return (void)mergeInValue(&I, TVal);
983   markOverdefined(&I);
984 }
985 
986 // Handle Unary Operators.
987 void SCCPSolver::visitUnaryOperator(Instruction &I) {
988   LatticeVal V0State = getValueState(I.getOperand(0));
989 
990   LatticeVal &IV = ValueState[&I];
991   // ResolvedUndefsIn might mark I as overdefined. Bail out, even if we would
992   // discover a concrete value later.
993   if (IV.isOverdefined()) return;
994 
995   if (V0State.isConstant()) {
996     Constant *C = ConstantExpr::get(I.getOpcode(), V0State.getConstant());
997 
998     // op Y -> undef.
999     if (isa<UndefValue>(C))
1000       return;
1001     return (void)markConstant(IV, &I, C);
1002   }
1003 
1004   // If something is undef, wait for it to resolve.
1005   if (!V0State.isOverdefined())
1006     return;
1007 
1008   markOverdefined(&I);
1009 }
1010 
1011 // Handle Binary Operators.
1012 void SCCPSolver::visitBinaryOperator(Instruction &I) {
1013   LatticeVal V1State = getValueState(I.getOperand(0));
1014   LatticeVal V2State = getValueState(I.getOperand(1));
1015 
1016   LatticeVal &IV = ValueState[&I];
1017   if (IV.isOverdefined()) return;
1018 
1019   if (V1State.isConstant() && V2State.isConstant()) {
1020     Constant *C = ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
1021                                     V2State.getConstant());
1022     // X op Y -> undef.
1023     if (isa<UndefValue>(C))
1024       return;
1025     return (void)markConstant(IV, &I, C);
1026   }
1027 
1028   // If something is undef, wait for it to resolve.
1029   if (!V1State.isOverdefined() && !V2State.isOverdefined()) {
1030 
1031     return;
1032   }
1033 
1034   // Otherwise, one of our operands is overdefined.  Try to produce something
1035   // better than overdefined with some tricks.
1036   // If this is 0 / Y, it doesn't matter that the second operand is
1037   // overdefined, and we can replace it with zero.
1038   if (I.getOpcode() == Instruction::UDiv || I.getOpcode() == Instruction::SDiv)
1039     if (V1State.isConstant() && V1State.getConstant()->isNullValue())
1040       return (void)markConstant(IV, &I, V1State.getConstant());
1041 
1042   // If this is:
1043   // -> AND/MUL with 0
1044   // -> OR with -1
1045   // it doesn't matter that the other operand is overdefined.
1046   if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Mul ||
1047       I.getOpcode() == Instruction::Or) {
1048     LatticeVal *NonOverdefVal = nullptr;
1049     if (!V1State.isOverdefined())
1050       NonOverdefVal = &V1State;
1051     else if (!V2State.isOverdefined())
1052       NonOverdefVal = &V2State;
1053     if (NonOverdefVal) {
1054       if (NonOverdefVal->isUnknown())
1055         return;
1056 
1057       if (I.getOpcode() == Instruction::And ||
1058           I.getOpcode() == Instruction::Mul) {
1059         // X and 0 = 0
1060         // X * 0 = 0
1061         if (NonOverdefVal->getConstant()->isNullValue())
1062           return (void)markConstant(IV, &I, NonOverdefVal->getConstant());
1063       } else {
1064         // X or -1 = -1
1065         if (ConstantInt *CI = NonOverdefVal->getConstantInt())
1066           if (CI->isMinusOne())
1067             return (void)markConstant(IV, &I, NonOverdefVal->getConstant());
1068       }
1069     }
1070   }
1071 
1072   markOverdefined(&I);
1073 }
1074 
1075 // Handle ICmpInst instruction.
1076 void SCCPSolver::visitCmpInst(CmpInst &I) {
1077   // Do not cache this lookup, getValueState calls later in the function might
1078   // invalidate the reference.
1079   if (ValueState[&I].isOverdefined()) return;
1080 
1081   Value *Op1 = I.getOperand(0);
1082   Value *Op2 = I.getOperand(1);
1083 
1084   // For parameters, use ParamState which includes constant range info if
1085   // available.
1086   auto V1Param = ParamState.find(Op1);
1087   ValueLatticeElement V1State = (V1Param != ParamState.end())
1088                                     ? V1Param->second
1089                                     : getValueState(Op1).toValueLattice();
1090 
1091   auto V2Param = ParamState.find(Op2);
1092   ValueLatticeElement V2State = V2Param != ParamState.end()
1093                                     ? V2Param->second
1094                                     : getValueState(Op2).toValueLattice();
1095 
1096   Constant *C = V1State.getCompare(I.getPredicate(), I.getType(), V2State);
1097   if (C) {
1098     if (isa<UndefValue>(C))
1099       return;
1100     LatticeVal CV;
1101     CV.markConstant(C);
1102     mergeInValue(&I, CV);
1103     return;
1104   }
1105 
1106   // If operands are still unknown, wait for it to resolve.
1107   if (!V1State.isOverdefined() && !V2State.isOverdefined() &&
1108       !ValueState[&I].isConstant())
1109     return;
1110 
1111   markOverdefined(&I);
1112 }
1113 
1114 // Handle getelementptr instructions.  If all operands are constants then we
1115 // can turn this into a getelementptr ConstantExpr.
1116 void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
1117   if (ValueState[&I].isOverdefined()) return;
1118 
1119   SmallVector<Constant*, 8> Operands;
1120   Operands.reserve(I.getNumOperands());
1121 
1122   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1123     LatticeVal State = getValueState(I.getOperand(i));
1124     if (State.isUnknown())
1125       return;  // Operands are not resolved yet.
1126 
1127     if (State.isOverdefined())
1128       return (void)markOverdefined(&I);
1129 
1130     assert(State.isConstant() && "Unknown state!");
1131     Operands.push_back(State.getConstant());
1132   }
1133 
1134   Constant *Ptr = Operands[0];
1135   auto Indices = makeArrayRef(Operands.begin() + 1, Operands.end());
1136   Constant *C =
1137       ConstantExpr::getGetElementPtr(I.getSourceElementType(), Ptr, Indices);
1138   if (isa<UndefValue>(C))
1139       return;
1140   markConstant(&I, C);
1141 }
1142 
1143 void SCCPSolver::visitStoreInst(StoreInst &SI) {
1144   // If this store is of a struct, ignore it.
1145   if (SI.getOperand(0)->getType()->isStructTy())
1146     return;
1147 
1148   if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1149     return;
1150 
1151   // ResolvedUndefsIn might mark I as overdefined. Bail out, even if we would
1152   // discover a concrete value later.
1153   if (ValueState[&SI].isOverdefined())
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   // ResolvedUndefsIn might mark I as overdefined. Bail out, even if we would
1174   // discover a concrete value later.
1175   if (ValueState[&I].isOverdefined())
1176     return;
1177 
1178   LatticeVal PtrVal = getValueState(I.getOperand(0));
1179   if (PtrVal.isUnknown()) return;   // The pointer is not resolved yet!
1180 
1181   LatticeVal &IV = ValueState[&I];
1182 
1183   if (!PtrVal.isConstant() || I.isVolatile())
1184     return (void)markOverdefined(IV, &I);
1185 
1186   Constant *Ptr = PtrVal.getConstant();
1187 
1188   // load null is undefined.
1189   if (isa<ConstantPointerNull>(Ptr)) {
1190     if (NullPointerIsDefined(I.getFunction(), I.getPointerAddressSpace()))
1191       return (void)markOverdefined(IV, &I);
1192     else
1193       return;
1194   }
1195 
1196   // Transform load (constant global) into the value loaded.
1197   if (auto *GV = dyn_cast<GlobalVariable>(Ptr)) {
1198     if (!TrackedGlobals.empty()) {
1199       // If we are tracking this global, merge in the known value for it.
1200       DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1201         TrackedGlobals.find(GV);
1202       if (It != TrackedGlobals.end()) {
1203         mergeInValue(IV, &I, It->second);
1204         return;
1205       }
1206     }
1207   }
1208 
1209   // Transform load from a constant into a constant if possible.
1210   if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, I.getType(), DL)) {
1211     if (isa<UndefValue>(C))
1212       return;
1213     return (void)markConstant(IV, &I, C);
1214   }
1215 
1216   // Otherwise we cannot say for certain what value this load will produce.
1217   // Bail out.
1218   markOverdefined(IV, &I);
1219 }
1220 
1221 void SCCPSolver::visitCallSite(CallSite CS) {
1222   Function *F = CS.getCalledFunction();
1223   Instruction *I = CS.getInstruction();
1224 
1225   if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1226     if (II->getIntrinsicID() == Intrinsic::ssa_copy) {
1227       if (ValueState[I].isOverdefined())
1228         return;
1229 
1230       auto *PI = getPredicateInfoFor(I);
1231       if (!PI)
1232         return;
1233 
1234       Value *CopyOf = I->getOperand(0);
1235       auto *PBranch = dyn_cast<PredicateBranch>(PI);
1236       if (!PBranch) {
1237         mergeInValue(ValueState[I], I, getValueState(CopyOf));
1238         return;
1239       }
1240 
1241       Value *Cond = PBranch->Condition;
1242 
1243       // Everything below relies on the condition being a comparison.
1244       auto *Cmp = dyn_cast<CmpInst>(Cond);
1245       if (!Cmp) {
1246         mergeInValue(ValueState[I], I, getValueState(CopyOf));
1247         return;
1248       }
1249 
1250       Value *CmpOp0 = Cmp->getOperand(0);
1251       Value *CmpOp1 = Cmp->getOperand(1);
1252       if (CopyOf != CmpOp0 && CopyOf != CmpOp1) {
1253         mergeInValue(ValueState[I], I, getValueState(CopyOf));
1254         return;
1255       }
1256 
1257       if (CmpOp0 != CopyOf)
1258         std::swap(CmpOp0, CmpOp1);
1259 
1260       LatticeVal OriginalVal = getValueState(CopyOf);
1261       LatticeVal EqVal = getValueState(CmpOp1);
1262       LatticeVal &IV = ValueState[I];
1263       if (PBranch->TrueEdge && Cmp->getPredicate() == CmpInst::ICMP_EQ) {
1264         addAdditionalUser(CmpOp1, I);
1265         if (OriginalVal.isConstant())
1266           mergeInValue(IV, I, OriginalVal);
1267         else
1268           mergeInValue(IV, I, EqVal);
1269         return;
1270       }
1271       if (!PBranch->TrueEdge && Cmp->getPredicate() == CmpInst::ICMP_NE) {
1272         addAdditionalUser(CmpOp1, I);
1273         if (OriginalVal.isConstant())
1274           mergeInValue(IV, I, OriginalVal);
1275         else
1276           mergeInValue(IV, I, EqVal);
1277         return;
1278       }
1279 
1280       return (void)mergeInValue(IV, I, getValueState(CopyOf));
1281     }
1282   }
1283 
1284   // The common case is that we aren't tracking the callee, either because we
1285   // are not doing interprocedural analysis or the callee is indirect, or is
1286   // external.  Handle these cases first.
1287   if (!F || F->isDeclaration()) {
1288 CallOverdefined:
1289     // Void return and not tracking callee, just bail.
1290     if (I->getType()->isVoidTy()) return;
1291 
1292     // Otherwise, if we have a single return value case, and if the function is
1293     // a declaration, maybe we can constant fold it.
1294     if (F && F->isDeclaration() && !I->getType()->isStructTy() &&
1295         canConstantFoldCallTo(cast<CallBase>(CS.getInstruction()), F)) {
1296       SmallVector<Constant*, 8> Operands;
1297       for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1298            AI != E; ++AI) {
1299         if (AI->get()->getType()->isStructTy())
1300           return markOverdefined(I); // Can't handle struct args.
1301         LatticeVal State = getValueState(*AI);
1302 
1303         if (State.isUnknown())
1304           return;  // Operands are not resolved yet.
1305         if (State.isOverdefined())
1306           return (void)markOverdefined(I);
1307         assert(State.isConstant() && "Unknown state!");
1308         Operands.push_back(State.getConstant());
1309       }
1310 
1311       if (getValueState(I).isOverdefined())
1312         return;
1313 
1314       // If we can constant fold this, mark the result of the call as a
1315       // constant.
1316       if (Constant *C = ConstantFoldCall(cast<CallBase>(CS.getInstruction()), F,
1317                                          Operands, &GetTLI(*F))) {
1318         // call -> undef.
1319         if (isa<UndefValue>(C))
1320           return;
1321         return (void)markConstant(I, C);
1322       }
1323     }
1324 
1325     // Otherwise, we don't know anything about this call, mark it overdefined.
1326     return (void)markOverdefined(I);
1327   }
1328 
1329   // If this is a local function that doesn't have its address taken, mark its
1330   // entry block executable and merge in the actual arguments to the call into
1331   // the formal arguments of the function.
1332   if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){
1333     MarkBlockExecutable(&F->front());
1334 
1335     // Propagate information from this call site into the callee.
1336     CallSite::arg_iterator CAI = CS.arg_begin();
1337     for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1338          AI != E; ++AI, ++CAI) {
1339       // If this argument is byval, and if the function is not readonly, there
1340       // will be an implicit copy formed of the input aggregate.
1341       if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
1342         markOverdefined(&*AI);
1343         continue;
1344       }
1345 
1346       if (auto *STy = dyn_cast<StructType>(AI->getType())) {
1347         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1348           LatticeVal CallArg = getStructValueState(*CAI, i);
1349           mergeInValue(getStructValueState(&*AI, i), &*AI, CallArg);
1350         }
1351       } else {
1352         // Most other parts of the Solver still only use the simpler value
1353         // lattice, so we propagate changes for parameters to both lattices.
1354         ValueLatticeElement ConcreteArgument =
1355             isa<Argument>(*CAI) ? getParamState(*CAI)
1356                                 : getValueState(*CAI).toValueLattice();
1357         bool ParamChanged = getParamState(&*AI).mergeIn(ConcreteArgument, DL);
1358         bool ValueChanged =
1359             mergeInValue(&*AI, toLatticeVal(ConcreteArgument, AI->getType()));
1360         // Add argument to work list, if the state of a parameter changes but
1361         // ValueState does not change (because it is already overdefined there),
1362         // We have to take changes in ParamState into account, as it is used
1363         // when evaluating Cmp instructions.
1364         if (!ValueChanged && ParamChanged)
1365           pushToWorkList(ValueState[&*AI], &*AI);
1366       }
1367     }
1368   }
1369 
1370   // If this is a single/zero retval case, see if we're tracking the function.
1371   if (auto *STy = dyn_cast<StructType>(F->getReturnType())) {
1372     if (!MRVFunctionsTracked.count(F))
1373       goto CallOverdefined;  // Not tracking this callee.
1374 
1375     // If we are tracking this callee, propagate the result of the function
1376     // into this call site.
1377     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1378       mergeInValue(getStructValueState(I, i), I,
1379                    TrackedMultipleRetVals[std::make_pair(F, i)]);
1380   } else {
1381     MapVector<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1382     if (TFRVI == TrackedRetVals.end())
1383       goto CallOverdefined;  // Not tracking this callee.
1384 
1385     // If so, propagate the return value of the callee into this call result.
1386     mergeInValue(I, TFRVI->second);
1387   }
1388 }
1389 
1390 void SCCPSolver::Solve() {
1391   // Process the work lists until they are empty!
1392   while (!BBWorkList.empty() || !InstWorkList.empty() ||
1393          !OverdefinedInstWorkList.empty()) {
1394     // Process the overdefined instruction's work list first, which drives other
1395     // things to overdefined more quickly.
1396     while (!OverdefinedInstWorkList.empty()) {
1397       Value *I = OverdefinedInstWorkList.pop_back_val();
1398 
1399       LLVM_DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n');
1400 
1401       // "I" got into the work list because it either made the transition from
1402       // bottom to constant, or to overdefined.
1403       //
1404       // Anything on this worklist that is overdefined need not be visited
1405       // since all of its users will have already been marked as overdefined
1406       // Update all of the users of this instruction's value.
1407       //
1408       markUsersAsChanged(I);
1409     }
1410 
1411     // Process the instruction work list.
1412     while (!InstWorkList.empty()) {
1413       Value *I = InstWorkList.pop_back_val();
1414 
1415       LLVM_DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n');
1416 
1417       // "I" got into the work list because it made the transition from undef to
1418       // constant.
1419       //
1420       // Anything on this worklist that is overdefined need not be visited
1421       // since all of its users will have already been marked as overdefined.
1422       // Update all of the users of this instruction's value.
1423       //
1424       if (I->getType()->isStructTy() || !getValueState(I).isOverdefined())
1425         markUsersAsChanged(I);
1426     }
1427 
1428     // Process the basic block work list.
1429     while (!BBWorkList.empty()) {
1430       BasicBlock *BB = BBWorkList.back();
1431       BBWorkList.pop_back();
1432 
1433       LLVM_DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n');
1434 
1435       // Notify all instructions in this basic block that they are newly
1436       // executable.
1437       visit(BB);
1438     }
1439   }
1440 }
1441 
1442 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
1443 /// that branches on undef values cannot reach any of their successors.
1444 /// However, this is not a safe assumption.  After we solve dataflow, this
1445 /// method should be use to handle this.  If this returns true, the solver
1446 /// should be rerun.
1447 ///
1448 /// This method handles this by finding an unresolved branch and marking it one
1449 /// of the edges from the block as being feasible, even though the condition
1450 /// doesn't say it would otherwise be.  This allows SCCP to find the rest of the
1451 /// CFG and only slightly pessimizes the analysis results (by marking one,
1452 /// potentially infeasible, edge feasible).  This cannot usefully modify the
1453 /// constraints on the condition of the branch, as that would impact other users
1454 /// of the value.
1455 ///
1456 /// This scan also checks for values that use undefs. It conservatively marks
1457 /// them as overdefined.
1458 bool SCCPSolver::ResolvedUndefsIn(Function &F) {
1459   for (BasicBlock &BB : F) {
1460     if (!BBExecutable.count(&BB))
1461       continue;
1462 
1463     for (Instruction &I : BB) {
1464       // Look for instructions which produce undef values.
1465       if (I.getType()->isVoidTy()) continue;
1466 
1467       if (auto *STy = dyn_cast<StructType>(I.getType())) {
1468         // Only a few things that can be structs matter for undef.
1469 
1470         // Tracked calls must never be marked overdefined in ResolvedUndefsIn.
1471         if (CallSite CS = CallSite(&I))
1472           if (Function *F = CS.getCalledFunction())
1473             if (MRVFunctionsTracked.count(F))
1474               continue;
1475 
1476         // extractvalue and insertvalue don't need to be marked; they are
1477         // tracked as precisely as their operands.
1478         if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(I))
1479           continue;
1480         // Send the results of everything else to overdefined.  We could be
1481         // more precise than this but it isn't worth bothering.
1482         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1483           LatticeVal &LV = getStructValueState(&I, i);
1484           if (LV.isUnknown())
1485             markOverdefined(LV, &I);
1486         }
1487         continue;
1488       }
1489 
1490       LatticeVal &LV = getValueState(&I);
1491       if (!LV.isUnknown())
1492         continue;
1493 
1494       // There are two reasons a call can have an undef result
1495       // 1. It could be tracked.
1496       // 2. It could be constant-foldable.
1497       // Because of the way we solve return values, tracked calls must
1498       // never be marked overdefined in ResolvedUndefsIn.
1499       if (CallSite CS = CallSite(&I))
1500         if (Function *F = CS.getCalledFunction())
1501           if (TrackedRetVals.count(F))
1502             continue;
1503 
1504       markOverdefined(&I);
1505       return true;
1506     }
1507 
1508     // Check to see if we have a branch or switch on an undefined value.  If so
1509     // we force the branch to go one way or the other to make the successor
1510     // values live.  It doesn't really matter which way we force it.
1511     Instruction *TI = BB.getTerminator();
1512     if (auto *BI = dyn_cast<BranchInst>(TI)) {
1513       if (!BI->isConditional()) continue;
1514       if (!getValueState(BI->getCondition()).isUnknown())
1515         continue;
1516 
1517       // If the input to SCCP is actually branch on undef, fix the undef to
1518       // false.
1519       if (isa<UndefValue>(BI->getCondition())) {
1520         BI->setCondition(ConstantInt::getFalse(BI->getContext()));
1521         markEdgeExecutable(&BB, TI->getSuccessor(1));
1522         return true;
1523       }
1524 
1525       // Otherwise, it is a branch on a symbolic value which is currently
1526       // considered to be undef.  Make sure some edge is executable, so a
1527       // branch on "undef" always flows somewhere.
1528       // FIXME: Distinguish between dead code and an LLVM "undef" value.
1529       BasicBlock *DefaultSuccessor = TI->getSuccessor(1);
1530       if (markEdgeExecutable(&BB, DefaultSuccessor))
1531         return true;
1532 
1533       continue;
1534     }
1535 
1536    if (auto *IBR = dyn_cast<IndirectBrInst>(TI)) {
1537       // Indirect branch with no successor ?. Its ok to assume it branches
1538       // to no target.
1539       if (IBR->getNumSuccessors() < 1)
1540         continue;
1541 
1542       if (!getValueState(IBR->getAddress()).isUnknown())
1543         continue;
1544 
1545       // If the input to SCCP is actually branch on undef, fix the undef to
1546       // the first successor of the indirect branch.
1547       if (isa<UndefValue>(IBR->getAddress())) {
1548         IBR->setAddress(BlockAddress::get(IBR->getSuccessor(0)));
1549         markEdgeExecutable(&BB, IBR->getSuccessor(0));
1550         return true;
1551       }
1552 
1553       // Otherwise, it is a branch on a symbolic value which is currently
1554       // considered to be undef.  Make sure some edge is executable, so a
1555       // branch on "undef" always flows somewhere.
1556       // FIXME: IndirectBr on "undef" doesn't actually need to go anywhere:
1557       // we can assume the branch has undefined behavior instead.
1558       BasicBlock *DefaultSuccessor = IBR->getSuccessor(0);
1559       if (markEdgeExecutable(&BB, DefaultSuccessor))
1560         return true;
1561 
1562       continue;
1563     }
1564 
1565     if (auto *SI = dyn_cast<SwitchInst>(TI)) {
1566       if (!SI->getNumCases() || !getValueState(SI->getCondition()).isUnknown())
1567         continue;
1568 
1569       // If the input to SCCP is actually switch on undef, fix the undef to
1570       // the first constant.
1571       if (isa<UndefValue>(SI->getCondition())) {
1572         SI->setCondition(SI->case_begin()->getCaseValue());
1573         markEdgeExecutable(&BB, SI->case_begin()->getCaseSuccessor());
1574         return true;
1575       }
1576 
1577       // Otherwise, it is a branch on a symbolic value which is currently
1578       // considered to be undef.  Make sure some edge is executable, so a
1579       // branch on "undef" always flows somewhere.
1580       // FIXME: Distinguish between dead code and an LLVM "undef" value.
1581       BasicBlock *DefaultSuccessor = SI->case_begin()->getCaseSuccessor();
1582       if (markEdgeExecutable(&BB, DefaultSuccessor))
1583         return true;
1584 
1585       continue;
1586     }
1587   }
1588 
1589   return false;
1590 }
1591 
1592 static bool tryToReplaceWithConstant(SCCPSolver &Solver, Value *V) {
1593   Constant *Const = nullptr;
1594   if (V->getType()->isStructTy()) {
1595     std::vector<LatticeVal> IVs = Solver.getStructLatticeValueFor(V);
1596     if (llvm::any_of(IVs,
1597                      [](const LatticeVal &LV) { return LV.isOverdefined(); }))
1598       return false;
1599     std::vector<Constant *> ConstVals;
1600     auto *ST = cast<StructType>(V->getType());
1601     for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1602       LatticeVal V = IVs[i];
1603       ConstVals.push_back(V.isConstant()
1604                               ? V.getConstant()
1605                               : UndefValue::get(ST->getElementType(i)));
1606     }
1607     Const = ConstantStruct::get(ST, ConstVals);
1608   } else {
1609     const LatticeVal &IV = Solver.getLatticeValueFor(V);
1610     if (IV.isOverdefined())
1611       return false;
1612 
1613     Const = IV.isConstant() ? IV.getConstant() : UndefValue::get(V->getType());
1614   }
1615   assert(Const && "Constant is nullptr here!");
1616 
1617   // Replacing `musttail` instructions with constant breaks `musttail` invariant
1618   // unless the call itself can be removed
1619   CallInst *CI = dyn_cast<CallInst>(V);
1620   if (CI && CI->isMustTailCall() && !CI->isSafeToRemove()) {
1621     CallSite CS(CI);
1622     Function *F = CS.getCalledFunction();
1623 
1624     // Don't zap returns of the callee
1625     if (F)
1626       Solver.AddMustTailCallee(F);
1627 
1628     LLVM_DEBUG(dbgs() << "  Can\'t treat the result of musttail call : " << *CI
1629                       << " as a constant\n");
1630     return false;
1631   }
1632 
1633   LLVM_DEBUG(dbgs() << "  Constant: " << *Const << " = " << *V << '\n');
1634 
1635   // Replaces all of the uses of a variable with uses of the constant.
1636   V->replaceAllUsesWith(Const);
1637   return true;
1638 }
1639 
1640 // runSCCP() - Run the Sparse Conditional Constant Propagation algorithm,
1641 // and return true if the function was modified.
1642 static bool runSCCP(Function &F, const DataLayout &DL,
1643                     const TargetLibraryInfo *TLI) {
1644   LLVM_DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n");
1645   SCCPSolver Solver(
1646       DL, [TLI](Function &F) -> const TargetLibraryInfo & { return *TLI; });
1647 
1648   // Mark the first block of the function as being executable.
1649   Solver.MarkBlockExecutable(&F.front());
1650 
1651   // Mark all arguments to the function as being overdefined.
1652   for (Argument &AI : F.args())
1653     Solver.markOverdefined(&AI);
1654 
1655   // Solve for constants.
1656   bool ResolvedUndefs = true;
1657   while (ResolvedUndefs) {
1658     Solver.Solve();
1659     LLVM_DEBUG(dbgs() << "RESOLVING UNDEFs\n");
1660     ResolvedUndefs = Solver.ResolvedUndefsIn(F);
1661   }
1662 
1663   bool MadeChanges = false;
1664 
1665   // If we decided that there are basic blocks that are dead in this function,
1666   // delete their contents now.  Note that we cannot actually delete the blocks,
1667   // as we cannot modify the CFG of the function.
1668 
1669   for (BasicBlock &BB : F) {
1670     if (!Solver.isBlockExecutable(&BB)) {
1671       LLVM_DEBUG(dbgs() << "  BasicBlock Dead:" << BB);
1672 
1673       ++NumDeadBlocks;
1674       NumInstRemoved += removeAllNonTerminatorAndEHPadInstructions(&BB);
1675 
1676       MadeChanges = true;
1677       continue;
1678     }
1679 
1680     // Iterate over all of the instructions in a function, replacing them with
1681     // constants if we have found them to be of constant values.
1682     for (BasicBlock::iterator BI = BB.begin(), E = BB.end(); BI != E;) {
1683       Instruction *Inst = &*BI++;
1684       if (Inst->getType()->isVoidTy() || Inst->isTerminator())
1685         continue;
1686 
1687       if (tryToReplaceWithConstant(Solver, Inst)) {
1688         if (isInstructionTriviallyDead(Inst))
1689           Inst->eraseFromParent();
1690         // Hey, we just changed something!
1691         MadeChanges = true;
1692         ++NumInstRemoved;
1693       }
1694     }
1695   }
1696 
1697   return MadeChanges;
1698 }
1699 
1700 PreservedAnalyses SCCPPass::run(Function &F, FunctionAnalysisManager &AM) {
1701   const DataLayout &DL = F.getParent()->getDataLayout();
1702   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1703   if (!runSCCP(F, DL, &TLI))
1704     return PreservedAnalyses::all();
1705 
1706   auto PA = PreservedAnalyses();
1707   PA.preserve<GlobalsAA>();
1708   PA.preserveSet<CFGAnalyses>();
1709   return PA;
1710 }
1711 
1712 namespace {
1713 
1714 //===--------------------------------------------------------------------===//
1715 //
1716 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
1717 /// Sparse Conditional Constant Propagator.
1718 ///
1719 class SCCPLegacyPass : public FunctionPass {
1720 public:
1721   // Pass identification, replacement for typeid
1722   static char ID;
1723 
1724   SCCPLegacyPass() : FunctionPass(ID) {
1725     initializeSCCPLegacyPassPass(*PassRegistry::getPassRegistry());
1726   }
1727 
1728   void getAnalysisUsage(AnalysisUsage &AU) const override {
1729     AU.addRequired<TargetLibraryInfoWrapperPass>();
1730     AU.addPreserved<GlobalsAAWrapperPass>();
1731     AU.setPreservesCFG();
1732   }
1733 
1734   // runOnFunction - Run the Sparse Conditional Constant Propagation
1735   // algorithm, and return true if the function was modified.
1736   bool runOnFunction(Function &F) override {
1737     if (skipFunction(F))
1738       return false;
1739     const DataLayout &DL = F.getParent()->getDataLayout();
1740     const TargetLibraryInfo *TLI =
1741         &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
1742     return runSCCP(F, DL, TLI);
1743   }
1744 };
1745 
1746 } // end anonymous namespace
1747 
1748 char SCCPLegacyPass::ID = 0;
1749 
1750 INITIALIZE_PASS_BEGIN(SCCPLegacyPass, "sccp",
1751                       "Sparse Conditional Constant Propagation", false, false)
1752 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1753 INITIALIZE_PASS_END(SCCPLegacyPass, "sccp",
1754                     "Sparse Conditional Constant Propagation", false, false)
1755 
1756 // createSCCPPass - This is the public interface to this file.
1757 FunctionPass *llvm::createSCCPPass() { return new SCCPLegacyPass(); }
1758 
1759 static void findReturnsToZap(Function &F,
1760                              SmallVector<ReturnInst *, 8> &ReturnsToZap,
1761                              SCCPSolver &Solver) {
1762   // We can only do this if we know that nothing else can call the function.
1763   if (!Solver.isArgumentTrackedFunction(&F))
1764     return;
1765 
1766   // There is a non-removable musttail call site of this function. Zapping
1767   // returns is not allowed.
1768   if (Solver.isMustTailCallee(&F)) {
1769     LLVM_DEBUG(dbgs() << "Can't zap returns of the function : " << F.getName()
1770                       << " due to present musttail call of it\n");
1771     return;
1772   }
1773 
1774   assert(
1775       all_of(F.users(),
1776              [&Solver](User *U) {
1777                if (isa<Instruction>(U) &&
1778                    !Solver.isBlockExecutable(cast<Instruction>(U)->getParent()))
1779                  return true;
1780                // Non-callsite uses are not impacted by zapping. Also, constant
1781                // uses (like blockaddresses) could stuck around, without being
1782                // used in the underlying IR, meaning we do not have lattice
1783                // values for them.
1784                if (!CallSite(U))
1785                  return true;
1786                if (U->getType()->isStructTy()) {
1787                  return all_of(
1788                      Solver.getStructLatticeValueFor(U),
1789                      [](const LatticeVal &LV) { return !LV.isOverdefined(); });
1790                }
1791                return !Solver.getLatticeValueFor(U).isOverdefined();
1792              }) &&
1793       "We can only zap functions where all live users have a concrete value");
1794 
1795   for (BasicBlock &BB : F) {
1796     if (CallInst *CI = BB.getTerminatingMustTailCall()) {
1797       LLVM_DEBUG(dbgs() << "Can't zap return of the block due to present "
1798                         << "musttail call : " << *CI << "\n");
1799       (void)CI;
1800       return;
1801     }
1802 
1803     if (auto *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
1804       if (!isa<UndefValue>(RI->getOperand(0)))
1805         ReturnsToZap.push_back(RI);
1806   }
1807 }
1808 
1809 // Update the condition for terminators that are branching on indeterminate
1810 // values, forcing them to use a specific edge.
1811 static void forceIndeterminateEdge(Instruction* I, SCCPSolver &Solver) {
1812   BasicBlock *Dest = nullptr;
1813   Constant *C = nullptr;
1814   if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1815     if (!isa<ConstantInt>(SI->getCondition())) {
1816       // Indeterminate switch; use first case value.
1817       Dest = SI->case_begin()->getCaseSuccessor();
1818       C = SI->case_begin()->getCaseValue();
1819     }
1820   } else if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1821     if (!isa<ConstantInt>(BI->getCondition())) {
1822       // Indeterminate branch; use false.
1823       Dest = BI->getSuccessor(1);
1824       C = ConstantInt::getFalse(BI->getContext());
1825     }
1826   } else if (IndirectBrInst *IBR = dyn_cast<IndirectBrInst>(I)) {
1827     if (!isa<BlockAddress>(IBR->getAddress()->stripPointerCasts())) {
1828       // Indeterminate indirectbr; use successor 0.
1829       Dest = IBR->getSuccessor(0);
1830       C = BlockAddress::get(IBR->getSuccessor(0));
1831     }
1832   } else {
1833     llvm_unreachable("Unexpected terminator instruction");
1834   }
1835   if (C) {
1836     assert(Solver.isEdgeFeasible(I->getParent(), Dest) &&
1837            "Didn't find feasible edge?");
1838     (void)Dest;
1839 
1840     I->setOperand(0, C);
1841   }
1842 }
1843 
1844 bool llvm::runIPSCCP(
1845     Module &M, const DataLayout &DL,
1846     std::function<const TargetLibraryInfo &(Function &)> GetTLI,
1847     function_ref<AnalysisResultsForFn(Function &)> getAnalysis) {
1848   SCCPSolver Solver(DL, GetTLI);
1849 
1850   // Loop over all functions, marking arguments to those with their addresses
1851   // taken or that are external as overdefined.
1852   for (Function &F : M) {
1853     if (F.isDeclaration())
1854       continue;
1855 
1856     Solver.addAnalysis(F, getAnalysis(F));
1857 
1858     // Determine if we can track the function's return values. If so, add the
1859     // function to the solver's set of return-tracked functions.
1860     if (canTrackReturnsInterprocedurally(&F))
1861       Solver.AddTrackedFunction(&F);
1862 
1863     // Determine if we can track the function's arguments. If so, add the
1864     // function to the solver's set of argument-tracked functions.
1865     if (canTrackArgumentsInterprocedurally(&F)) {
1866       Solver.AddArgumentTrackedFunction(&F);
1867       continue;
1868     }
1869 
1870     // Assume the function is called.
1871     Solver.MarkBlockExecutable(&F.front());
1872 
1873     // Assume nothing about the incoming arguments.
1874     for (Argument &AI : F.args())
1875       Solver.markOverdefined(&AI);
1876   }
1877 
1878   // Determine if we can track any of the module's global variables. If so, add
1879   // the global variables we can track to the solver's set of tracked global
1880   // variables.
1881   for (GlobalVariable &G : M.globals()) {
1882     G.removeDeadConstantUsers();
1883     if (canTrackGlobalVariableInterprocedurally(&G))
1884       Solver.TrackValueOfGlobalVariable(&G);
1885   }
1886 
1887   // Solve for constants.
1888   bool ResolvedUndefs = true;
1889   Solver.Solve();
1890   while (ResolvedUndefs) {
1891     LLVM_DEBUG(dbgs() << "RESOLVING UNDEFS\n");
1892     ResolvedUndefs = false;
1893     for (Function &F : M)
1894       if (Solver.ResolvedUndefsIn(F)) {
1895         // We run Solve() after we resolved an undef in a function, because
1896         // we might deduce a fact that eliminates an undef in another function.
1897         Solver.Solve();
1898         ResolvedUndefs = true;
1899       }
1900   }
1901 
1902   bool MadeChanges = false;
1903 
1904   // Iterate over all of the instructions in the module, replacing them with
1905   // constants if we have found them to be of constant values.
1906 
1907   for (Function &F : M) {
1908     if (F.isDeclaration())
1909       continue;
1910 
1911     SmallVector<BasicBlock *, 512> BlocksToErase;
1912 
1913     if (Solver.isBlockExecutable(&F.front()))
1914       for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;
1915            ++AI) {
1916         if (!AI->use_empty() && tryToReplaceWithConstant(Solver, &*AI)) {
1917           ++IPNumArgsElimed;
1918           continue;
1919         }
1920       }
1921 
1922     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1923       if (!Solver.isBlockExecutable(&*BB)) {
1924         LLVM_DEBUG(dbgs() << "  BasicBlock Dead:" << *BB);
1925         ++NumDeadBlocks;
1926 
1927         MadeChanges = true;
1928 
1929         if (&*BB != &F.front())
1930           BlocksToErase.push_back(&*BB);
1931         continue;
1932       }
1933 
1934       for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1935         Instruction *Inst = &*BI++;
1936         if (Inst->getType()->isVoidTy())
1937           continue;
1938         if (tryToReplaceWithConstant(Solver, Inst)) {
1939           if (Inst->isSafeToRemove())
1940             Inst->eraseFromParent();
1941           // Hey, we just changed something!
1942           MadeChanges = true;
1943           ++IPNumInstRemoved;
1944         }
1945       }
1946     }
1947 
1948     DomTreeUpdater DTU = Solver.getDTU(F);
1949     // Change dead blocks to unreachable. We do it after replacing constants
1950     // in all executable blocks, because changeToUnreachable may remove PHI
1951     // nodes in executable blocks we found values for. The function's entry
1952     // block is not part of BlocksToErase, so we have to handle it separately.
1953     for (BasicBlock *BB : BlocksToErase) {
1954       NumInstRemoved +=
1955           changeToUnreachable(BB->getFirstNonPHI(), /*UseLLVMTrap=*/false,
1956                               /*PreserveLCSSA=*/false, &DTU);
1957     }
1958     if (!Solver.isBlockExecutable(&F.front()))
1959       NumInstRemoved += changeToUnreachable(F.front().getFirstNonPHI(),
1960                                             /*UseLLVMTrap=*/false,
1961                                             /*PreserveLCSSA=*/false, &DTU);
1962 
1963     // Now that all instructions in the function are constant folded,
1964     // use ConstantFoldTerminator to get rid of in-edges, record DT updates and
1965     // delete dead BBs.
1966     for (BasicBlock *DeadBB : BlocksToErase) {
1967       // If there are any PHI nodes in this successor, drop entries for BB now.
1968       for (Value::user_iterator UI = DeadBB->user_begin(),
1969                                 UE = DeadBB->user_end();
1970            UI != UE;) {
1971         // Grab the user and then increment the iterator early, as the user
1972         // will be deleted. Step past all adjacent uses from the same user.
1973         auto *I = dyn_cast<Instruction>(*UI);
1974         do { ++UI; } while (UI != UE && *UI == I);
1975 
1976         // Ignore blockaddress users; BasicBlock's dtor will handle them.
1977         if (!I) continue;
1978 
1979         // If we have forced an edge for an indeterminate value, then force the
1980         // terminator to fold to that edge.
1981         forceIndeterminateEdge(I, Solver);
1982         BasicBlock *InstBB = I->getParent();
1983         bool Folded = ConstantFoldTerminator(InstBB,
1984                                              /*DeleteDeadConditions=*/false,
1985                                              /*TLI=*/nullptr, &DTU);
1986         assert(Folded &&
1987               "Expect TermInst on constantint or blockaddress to be folded");
1988         (void) Folded;
1989         // If we folded the terminator to an unconditional branch to another
1990         // dead block, replace it with Unreachable, to avoid trying to fold that
1991         // branch again.
1992         BranchInst *BI = cast<BranchInst>(InstBB->getTerminator());
1993         if (BI && BI->isUnconditional() &&
1994             !Solver.isBlockExecutable(BI->getSuccessor(0))) {
1995           InstBB->getTerminator()->eraseFromParent();
1996           new UnreachableInst(InstBB->getContext(), InstBB);
1997         }
1998       }
1999       // Mark dead BB for deletion.
2000       DTU.deleteBB(DeadBB);
2001     }
2002 
2003     for (BasicBlock &BB : F) {
2004       for (BasicBlock::iterator BI = BB.begin(), E = BB.end(); BI != E;) {
2005         Instruction *Inst = &*BI++;
2006         if (Solver.getPredicateInfoFor(Inst)) {
2007           if (auto *II = dyn_cast<IntrinsicInst>(Inst)) {
2008             if (II->getIntrinsicID() == Intrinsic::ssa_copy) {
2009               Value *Op = II->getOperand(0);
2010               Inst->replaceAllUsesWith(Op);
2011               Inst->eraseFromParent();
2012             }
2013           }
2014         }
2015       }
2016     }
2017   }
2018 
2019   // If we inferred constant or undef return values for a function, we replaced
2020   // all call uses with the inferred value.  This means we don't need to bother
2021   // actually returning anything from the function.  Replace all return
2022   // instructions with return undef.
2023   //
2024   // Do this in two stages: first identify the functions we should process, then
2025   // actually zap their returns.  This is important because we can only do this
2026   // if the address of the function isn't taken.  In cases where a return is the
2027   // last use of a function, the order of processing functions would affect
2028   // whether other functions are optimizable.
2029   SmallVector<ReturnInst*, 8> ReturnsToZap;
2030 
2031   const MapVector<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
2032   for (const auto &I : RV) {
2033     Function *F = I.first;
2034     if (I.second.isOverdefined() || F->getReturnType()->isVoidTy())
2035       continue;
2036     findReturnsToZap(*F, ReturnsToZap, Solver);
2037   }
2038 
2039   for (auto F : Solver.getMRVFunctionsTracked()) {
2040     assert(F->getReturnType()->isStructTy() &&
2041            "The return type should be a struct");
2042     StructType *STy = cast<StructType>(F->getReturnType());
2043     if (Solver.isStructLatticeConstant(F, STy))
2044       findReturnsToZap(*F, ReturnsToZap, Solver);
2045   }
2046 
2047   // Zap all returns which we've identified as zap to change.
2048   for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) {
2049     Function *F = ReturnsToZap[i]->getParent()->getParent();
2050     ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType()));
2051   }
2052 
2053   // If we inferred constant or undef values for globals variables, we can
2054   // delete the global and any stores that remain to it.
2055   const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
2056   for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
2057          E = TG.end(); I != E; ++I) {
2058     GlobalVariable *GV = I->first;
2059     assert(!I->second.isOverdefined() &&
2060            "Overdefined values should have been taken out of the map!");
2061     LLVM_DEBUG(dbgs() << "Found that GV '" << GV->getName()
2062                       << "' is constant!\n");
2063     while (!GV->use_empty()) {
2064       StoreInst *SI = cast<StoreInst>(GV->user_back());
2065       SI->eraseFromParent();
2066     }
2067     M.getGlobalList().erase(GV);
2068     ++IPNumGlobalConst;
2069   }
2070 
2071   return MadeChanges;
2072 }
2073