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