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