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