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