OSDN Git Service

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