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