1 //===- SCCPSolver.cpp - SCCP Utility --------------------------- *- C++ -*-===//
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 // \file
10 // This file implements the Sparse Conditional Constant Propagation (SCCP)
11 // utility.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Transforms/Utils/SCCPSolver.h"
16 #include "llvm/Analysis/ConstantFolding.h"
17 #include "llvm/Analysis/InstructionSimplify.h"
18 #include "llvm/Analysis/ValueTracking.h"
19 #include "llvm/InitializePasses.h"
20 #include "llvm/Pass.h"
21 #include "llvm/Support/Casting.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include "llvm/Transforms/Utils/Local.h"
26 #include <cassert>
27 #include <utility>
28 #include <vector>
29 
30 using namespace llvm;
31 
32 #define DEBUG_TYPE "sccp"
33 
34 // The maximum number of range extensions allowed for operations requiring
35 // widening.
36 static const unsigned MaxNumRangeExtensions = 10;
37 
38 /// Returns MergeOptions with MaxWidenSteps set to MaxNumRangeExtensions.
39 static ValueLatticeElement::MergeOptions getMaxWidenStepsOpts() {
40   return ValueLatticeElement::MergeOptions().setMaxWidenSteps(
41       MaxNumRangeExtensions);
42 }
43 
44 namespace {
45 
46 // Helper to check if \p LV is either a constant or a constant
47 // range with a single element. This should cover exactly the same cases as the
48 // old ValueLatticeElement::isConstant() and is intended to be used in the
49 // transition to ValueLatticeElement.
50 bool isConstant(const ValueLatticeElement &LV) {
51   return LV.isConstant() ||
52          (LV.isConstantRange() && LV.getConstantRange().isSingleElement());
53 }
54 
55 // Helper to check if \p LV is either overdefined or a constant range with more
56 // than a single element. This should cover exactly the same cases as the old
57 // ValueLatticeElement::isOverdefined() and is intended to be used in the
58 // transition to ValueLatticeElement.
59 bool isOverdefined(const ValueLatticeElement &LV) {
60   return !LV.isUnknownOrUndef() && !isConstant(LV);
61 }
62 
63 } // namespace
64 
65 namespace llvm {
66 
67 /// Helper class for SCCPSolver. This implements the instruction visitor and
68 /// holds all the state.
69 class SCCPInstVisitor : public InstVisitor<SCCPInstVisitor> {
70   const DataLayout &DL;
71   std::function<const TargetLibraryInfo &(Function &)> GetTLI;
72   SmallPtrSet<BasicBlock *, 8> BBExecutable; // The BBs that are executable.
73   DenseMap<Value *, ValueLatticeElement>
74       ValueState; // The state each value is in.
75 
76   /// StructValueState - This maintains ValueState for values that have
77   /// StructType, for example for formal arguments, calls, insertelement, etc.
78   DenseMap<std::pair<Value *, unsigned>, ValueLatticeElement> StructValueState;
79 
80   /// GlobalValue - If we are tracking any values for the contents of a global
81   /// variable, we keep a mapping from the constant accessor to the element of
82   /// the global, to the currently known value.  If the value becomes
83   /// overdefined, it's entry is simply removed from this map.
84   DenseMap<GlobalVariable *, ValueLatticeElement> TrackedGlobals;
85 
86   /// TrackedRetVals - If we are tracking arguments into and the return
87   /// value out of a function, it will have an entry in this map, indicating
88   /// what the known return value for the function is.
89   MapVector<Function *, ValueLatticeElement> TrackedRetVals;
90 
91   /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
92   /// that return multiple values.
93   MapVector<std::pair<Function *, unsigned>, ValueLatticeElement>
94       TrackedMultipleRetVals;
95 
96   /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is
97   /// represented here for efficient lookup.
98   SmallPtrSet<Function *, 16> MRVFunctionsTracked;
99 
100   /// A list of functions whose return cannot be modified.
101   SmallPtrSet<Function *, 16> MustPreserveReturnsInFunctions;
102 
103   /// TrackingIncomingArguments - This is the set of functions for whose
104   /// arguments we make optimistic assumptions about and try to prove as
105   /// constants.
106   SmallPtrSet<Function *, 16> TrackingIncomingArguments;
107 
108   /// The reason for two worklists is that overdefined is the lowest state
109   /// on the lattice, and moving things to overdefined as fast as possible
110   /// makes SCCP converge much faster.
111   ///
112   /// By having a separate worklist, we accomplish this because everything
113   /// possibly overdefined will become overdefined at the soonest possible
114   /// point.
115   SmallVector<Value *, 64> OverdefinedInstWorkList;
116   SmallVector<Value *, 64> InstWorkList;
117 
118   // The BasicBlock work list
119   SmallVector<BasicBlock *, 64> BBWorkList;
120 
121   /// KnownFeasibleEdges - Entries in this set are edges which have already had
122   /// PHI nodes retriggered.
123   using Edge = std::pair<BasicBlock *, BasicBlock *>;
124   DenseSet<Edge> KnownFeasibleEdges;
125 
126   DenseMap<Function *, AnalysisResultsForFn> AnalysisResults;
127   DenseMap<Value *, SmallPtrSet<User *, 2>> AdditionalUsers;
128 
129   LLVMContext &Ctx;
130 
131 private:
132   ConstantInt *getConstantInt(const ValueLatticeElement &IV) const {
133     return dyn_cast_or_null<ConstantInt>(getConstant(IV));
134   }
135 
136   // pushToWorkList - Helper for markConstant/markOverdefined
137   void pushToWorkList(ValueLatticeElement &IV, Value *V);
138 
139   // Helper to push \p V to the worklist, after updating it to \p IV. Also
140   // prints a debug message with the updated value.
141   void pushToWorkListMsg(ValueLatticeElement &IV, Value *V);
142 
143   // markConstant - Make a value be marked as "constant".  If the value
144   // is not already a constant, add it to the instruction work list so that
145   // the users of the instruction are updated later.
146   bool markConstant(ValueLatticeElement &IV, Value *V, Constant *C,
147                     bool MayIncludeUndef = false);
148 
149   bool markConstant(Value *V, Constant *C) {
150     assert(!V->getType()->isStructTy() && "structs should use mergeInValue");
151     return markConstant(ValueState[V], V, C);
152   }
153 
154   // markOverdefined - Make a value be marked as "overdefined". If the
155   // value is not already overdefined, add it to the overdefined instruction
156   // work list so that the users of the instruction are updated later.
157   bool markOverdefined(ValueLatticeElement &IV, Value *V);
158 
159   /// Merge \p MergeWithV into \p IV and push \p V to the worklist, if \p IV
160   /// changes.
161   bool mergeInValue(ValueLatticeElement &IV, Value *V,
162                     ValueLatticeElement MergeWithV,
163                     ValueLatticeElement::MergeOptions Opts = {
164                         /*MayIncludeUndef=*/false, /*CheckWiden=*/false});
165 
166   bool mergeInValue(Value *V, ValueLatticeElement MergeWithV,
167                     ValueLatticeElement::MergeOptions Opts = {
168                         /*MayIncludeUndef=*/false, /*CheckWiden=*/false}) {
169     assert(!V->getType()->isStructTy() &&
170            "non-structs should use markConstant");
171     return mergeInValue(ValueState[V], V, MergeWithV, Opts);
172   }
173 
174   /// getValueState - Return the ValueLatticeElement object that corresponds to
175   /// the value.  This function handles the case when the value hasn't been seen
176   /// yet by properly seeding constants etc.
177   ValueLatticeElement &getValueState(Value *V) {
178     assert(!V->getType()->isStructTy() && "Should use getStructValueState");
179 
180     auto I = ValueState.insert(std::make_pair(V, ValueLatticeElement()));
181     ValueLatticeElement &LV = I.first->second;
182 
183     if (!I.second)
184       return LV; // Common case, already in the map.
185 
186     if (auto *C = dyn_cast<Constant>(V))
187       LV.markConstant(C); // Constants are constant
188 
189     // All others are unknown by default.
190     return LV;
191   }
192 
193   /// getStructValueState - Return the ValueLatticeElement object that
194   /// corresponds to the value/field pair.  This function handles the case when
195   /// the value hasn't been seen yet by properly seeding constants etc.
196   ValueLatticeElement &getStructValueState(Value *V, unsigned i) {
197     assert(V->getType()->isStructTy() && "Should use getValueState");
198     assert(i < cast<StructType>(V->getType())->getNumElements() &&
199            "Invalid element #");
200 
201     auto I = StructValueState.insert(
202         std::make_pair(std::make_pair(V, i), ValueLatticeElement()));
203     ValueLatticeElement &LV = I.first->second;
204 
205     if (!I.second)
206       return LV; // Common case, already in the map.
207 
208     if (auto *C = dyn_cast<Constant>(V)) {
209       Constant *Elt = C->getAggregateElement(i);
210 
211       if (!Elt)
212         LV.markOverdefined(); // Unknown sort of constant.
213       else if (isa<UndefValue>(Elt))
214         ; // Undef values remain unknown.
215       else
216         LV.markConstant(Elt); // Constants are constant.
217     }
218 
219     // All others are underdefined by default.
220     return LV;
221   }
222 
223   /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
224   /// work list if it is not already executable.
225   bool markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest);
226 
227   // getFeasibleSuccessors - Return a vector of booleans to indicate which
228   // successors are reachable from a given terminator instruction.
229   void getFeasibleSuccessors(Instruction &TI, SmallVectorImpl<bool> &Succs);
230 
231   // OperandChangedState - This method is invoked on all of the users of an
232   // instruction that was just changed state somehow.  Based on this
233   // information, we need to update the specified user of this instruction.
234   void operandChangedState(Instruction *I) {
235     if (BBExecutable.count(I->getParent())) // Inst is executable?
236       visit(*I);
237   }
238 
239   // Add U as additional user of V.
240   void addAdditionalUser(Value *V, User *U) {
241     auto Iter = AdditionalUsers.insert({V, {}});
242     Iter.first->second.insert(U);
243   }
244 
245   // Mark I's users as changed, including AdditionalUsers.
246   void markUsersAsChanged(Value *I) {
247     // Functions include their arguments in the use-list. Changed function
248     // values mean that the result of the function changed. We only need to
249     // update the call sites with the new function result and do not have to
250     // propagate the call arguments.
251     if (isa<Function>(I)) {
252       for (User *U : I->users()) {
253         if (auto *CB = dyn_cast<CallBase>(U))
254           handleCallResult(*CB);
255       }
256     } else {
257       for (User *U : I->users())
258         if (auto *UI = dyn_cast<Instruction>(U))
259           operandChangedState(UI);
260     }
261 
262     auto Iter = AdditionalUsers.find(I);
263     if (Iter != AdditionalUsers.end()) {
264       // Copy additional users before notifying them of changes, because new
265       // users may be added, potentially invalidating the iterator.
266       SmallVector<Instruction *, 2> ToNotify;
267       for (User *U : Iter->second)
268         if (auto *UI = dyn_cast<Instruction>(U))
269           ToNotify.push_back(UI);
270       for (Instruction *UI : ToNotify)
271         operandChangedState(UI);
272     }
273   }
274   void handleCallOverdefined(CallBase &CB);
275   void handleCallResult(CallBase &CB);
276   void handleCallArguments(CallBase &CB);
277 
278 private:
279   friend class InstVisitor<SCCPInstVisitor>;
280 
281   // visit implementations - Something changed in this instruction.  Either an
282   // operand made a transition, or the instruction is newly executable.  Change
283   // the value type of I to reflect these changes if appropriate.
284   void visitPHINode(PHINode &I);
285 
286   // Terminators
287 
288   void visitReturnInst(ReturnInst &I);
289   void visitTerminator(Instruction &TI);
290 
291   void visitCastInst(CastInst &I);
292   void visitSelectInst(SelectInst &I);
293   void visitUnaryOperator(Instruction &I);
294   void visitBinaryOperator(Instruction &I);
295   void visitCmpInst(CmpInst &I);
296   void visitExtractValueInst(ExtractValueInst &EVI);
297   void visitInsertValueInst(InsertValueInst &IVI);
298 
299   void visitCatchSwitchInst(CatchSwitchInst &CPI) {
300     markOverdefined(&CPI);
301     visitTerminator(CPI);
302   }
303 
304   // Instructions that cannot be folded away.
305 
306   void visitStoreInst(StoreInst &I);
307   void visitLoadInst(LoadInst &I);
308   void visitGetElementPtrInst(GetElementPtrInst &I);
309 
310   void visitInvokeInst(InvokeInst &II) {
311     visitCallBase(II);
312     visitTerminator(II);
313   }
314 
315   void visitCallBrInst(CallBrInst &CBI) {
316     visitCallBase(CBI);
317     visitTerminator(CBI);
318   }
319 
320   void visitCallBase(CallBase &CB);
321   void visitResumeInst(ResumeInst &I) { /*returns void*/
322   }
323   void visitUnreachableInst(UnreachableInst &I) { /*returns void*/
324   }
325   void visitFenceInst(FenceInst &I) { /*returns void*/
326   }
327 
328   void visitInstruction(Instruction &I);
329 
330 public:
331   void addAnalysis(Function &F, AnalysisResultsForFn A) {
332     AnalysisResults.insert({&F, std::move(A)});
333   }
334 
335   void visitCallInst(CallInst &I) { visitCallBase(I); }
336 
337   bool markBlockExecutable(BasicBlock *BB);
338 
339   const PredicateBase *getPredicateInfoFor(Instruction *I) {
340     auto A = AnalysisResults.find(I->getParent()->getParent());
341     if (A == AnalysisResults.end())
342       return nullptr;
343     return A->second.PredInfo->getPredicateInfoFor(I);
344   }
345 
346   DomTreeUpdater getDTU(Function &F) {
347     auto A = AnalysisResults.find(&F);
348     assert(A != AnalysisResults.end() && "Need analysis results for function.");
349     return {A->second.DT, A->second.PDT, DomTreeUpdater::UpdateStrategy::Lazy};
350   }
351 
352   SCCPInstVisitor(const DataLayout &DL,
353                   std::function<const TargetLibraryInfo &(Function &)> GetTLI,
354                   LLVMContext &Ctx)
355       : DL(DL), GetTLI(GetTLI), Ctx(Ctx) {}
356 
357   void trackValueOfGlobalVariable(GlobalVariable *GV) {
358     // We only track the contents of scalar globals.
359     if (GV->getValueType()->isSingleValueType()) {
360       ValueLatticeElement &IV = TrackedGlobals[GV];
361       if (!isa<UndefValue>(GV->getInitializer()))
362         IV.markConstant(GV->getInitializer());
363     }
364   }
365 
366   void addTrackedFunction(Function *F) {
367     // Add an entry, F -> undef.
368     if (auto *STy = dyn_cast<StructType>(F->getReturnType())) {
369       MRVFunctionsTracked.insert(F);
370       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
371         TrackedMultipleRetVals.insert(
372             std::make_pair(std::make_pair(F, i), ValueLatticeElement()));
373     } else if (!F->getReturnType()->isVoidTy())
374       TrackedRetVals.insert(std::make_pair(F, ValueLatticeElement()));
375   }
376 
377   void addToMustPreserveReturnsInFunctions(Function *F) {
378     MustPreserveReturnsInFunctions.insert(F);
379   }
380 
381   bool mustPreserveReturn(Function *F) {
382     return MustPreserveReturnsInFunctions.count(F);
383   }
384 
385   void addArgumentTrackedFunction(Function *F) {
386     TrackingIncomingArguments.insert(F);
387   }
388 
389   bool isArgumentTrackedFunction(Function *F) {
390     return TrackingIncomingArguments.count(F);
391   }
392 
393   void solve();
394 
395   bool resolvedUndefsIn(Function &F);
396 
397   bool isBlockExecutable(BasicBlock *BB) const {
398     return BBExecutable.count(BB);
399   }
400 
401   bool isEdgeFeasible(BasicBlock *From, BasicBlock *To) const;
402 
403   std::vector<ValueLatticeElement> getStructLatticeValueFor(Value *V) const {
404     std::vector<ValueLatticeElement> StructValues;
405     auto *STy = dyn_cast<StructType>(V->getType());
406     assert(STy && "getStructLatticeValueFor() can be called only on structs");
407     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
408       auto I = StructValueState.find(std::make_pair(V, i));
409       assert(I != StructValueState.end() && "Value not in valuemap!");
410       StructValues.push_back(I->second);
411     }
412     return StructValues;
413   }
414 
415   void removeLatticeValueFor(Value *V) { ValueState.erase(V); }
416 
417   const ValueLatticeElement &getLatticeValueFor(Value *V) const {
418     assert(!V->getType()->isStructTy() &&
419            "Should use getStructLatticeValueFor");
420     DenseMap<Value *, ValueLatticeElement>::const_iterator I =
421         ValueState.find(V);
422     assert(I != ValueState.end() &&
423            "V not found in ValueState nor Paramstate map!");
424     return I->second;
425   }
426 
427   const MapVector<Function *, ValueLatticeElement> &getTrackedRetVals() {
428     return TrackedRetVals;
429   }
430 
431   const DenseMap<GlobalVariable *, ValueLatticeElement> &getTrackedGlobals() {
432     return TrackedGlobals;
433   }
434 
435   const SmallPtrSet<Function *, 16> getMRVFunctionsTracked() {
436     return MRVFunctionsTracked;
437   }
438 
439   void markOverdefined(Value *V) {
440     if (auto *STy = dyn_cast<StructType>(V->getType()))
441       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
442         markOverdefined(getStructValueState(V, i), V);
443     else
444       markOverdefined(ValueState[V], V);
445   }
446 
447   bool isStructLatticeConstant(Function *F, StructType *STy);
448 
449   Constant *getConstant(const ValueLatticeElement &LV) const;
450 
451   SmallPtrSetImpl<Function *> &getArgumentTrackedFunctions() {
452     return TrackingIncomingArguments;
453   }
454 
455   void markArgInFuncSpecialization(Function *F, Argument *A, Constant *C);
456 
457   void markFunctionUnreachable(Function *F) {
458     for (auto &BB : *F)
459       BBExecutable.erase(&BB);
460   }
461 };
462 
463 } // namespace llvm
464 
465 bool SCCPInstVisitor::markBlockExecutable(BasicBlock *BB) {
466   if (!BBExecutable.insert(BB).second)
467     return false;
468   LLVM_DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << '\n');
469   BBWorkList.push_back(BB); // Add the block to the work list!
470   return true;
471 }
472 
473 void SCCPInstVisitor::pushToWorkList(ValueLatticeElement &IV, Value *V) {
474   if (IV.isOverdefined())
475     return OverdefinedInstWorkList.push_back(V);
476   InstWorkList.push_back(V);
477 }
478 
479 void SCCPInstVisitor::pushToWorkListMsg(ValueLatticeElement &IV, Value *V) {
480   LLVM_DEBUG(dbgs() << "updated " << IV << ": " << *V << '\n');
481   pushToWorkList(IV, V);
482 }
483 
484 bool SCCPInstVisitor::markConstant(ValueLatticeElement &IV, Value *V,
485                                    Constant *C, bool MayIncludeUndef) {
486   if (!IV.markConstant(C, MayIncludeUndef))
487     return false;
488   LLVM_DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n');
489   pushToWorkList(IV, V);
490   return true;
491 }
492 
493 bool SCCPInstVisitor::markOverdefined(ValueLatticeElement &IV, Value *V) {
494   if (!IV.markOverdefined())
495     return false;
496 
497   LLVM_DEBUG(dbgs() << "markOverdefined: ";
498              if (auto *F = dyn_cast<Function>(V)) dbgs()
499              << "Function '" << F->getName() << "'\n";
500              else dbgs() << *V << '\n');
501   // Only instructions go on the work list
502   pushToWorkList(IV, V);
503   return true;
504 }
505 
506 bool SCCPInstVisitor::isStructLatticeConstant(Function *F, StructType *STy) {
507   for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
508     const auto &It = TrackedMultipleRetVals.find(std::make_pair(F, i));
509     assert(It != TrackedMultipleRetVals.end());
510     ValueLatticeElement LV = It->second;
511     if (!isConstant(LV))
512       return false;
513   }
514   return true;
515 }
516 
517 Constant *SCCPInstVisitor::getConstant(const ValueLatticeElement &LV) const {
518   if (LV.isConstant())
519     return LV.getConstant();
520 
521   if (LV.isConstantRange()) {
522     const auto &CR = LV.getConstantRange();
523     if (CR.getSingleElement())
524       return ConstantInt::get(Ctx, *CR.getSingleElement());
525   }
526   return nullptr;
527 }
528 
529 void SCCPInstVisitor::markArgInFuncSpecialization(Function *F, Argument *A,
530                                                   Constant *C) {
531   assert(F->arg_size() == A->getParent()->arg_size() &&
532          "Functions should have the same number of arguments");
533 
534   // Mark the argument constant in the new function.
535   markConstant(A, C);
536 
537   // For the remaining arguments in the new function, copy the lattice state
538   // over from the old function.
539   for (Argument *OldArg = F->arg_begin(), *NewArg = A->getParent()->arg_begin(),
540                 *End = F->arg_end();
541        OldArg != End; ++OldArg, ++NewArg) {
542 
543     LLVM_DEBUG(dbgs() << "SCCP: Marking argument "
544                       << NewArg->getNameOrAsOperand() << "\n");
545 
546     if (NewArg != A && ValueState.count(OldArg)) {
547       // Note: This previously looked like this:
548       // ValueState[NewArg] = ValueState[OldArg];
549       // This is incorrect because the DenseMap class may resize the underlying
550       // memory when inserting `NewArg`, which will invalidate the reference to
551       // `OldArg`. Instead, we make sure `NewArg` exists before setting it.
552       auto &NewValue = ValueState[NewArg];
553       NewValue = ValueState[OldArg];
554       pushToWorkList(NewValue, NewArg);
555     }
556   }
557 }
558 
559 void SCCPInstVisitor::visitInstruction(Instruction &I) {
560   // All the instructions we don't do any special handling for just
561   // go to overdefined.
562   LLVM_DEBUG(dbgs() << "SCCP: Don't know how to handle: " << I << '\n');
563   markOverdefined(&I);
564 }
565 
566 bool SCCPInstVisitor::mergeInValue(ValueLatticeElement &IV, Value *V,
567                                    ValueLatticeElement MergeWithV,
568                                    ValueLatticeElement::MergeOptions Opts) {
569   if (IV.mergeIn(MergeWithV, Opts)) {
570     pushToWorkList(IV, V);
571     LLVM_DEBUG(dbgs() << "Merged " << MergeWithV << " into " << *V << " : "
572                       << IV << "\n");
573     return true;
574   }
575   return false;
576 }
577 
578 bool SCCPInstVisitor::markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
579   if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
580     return false; // This edge is already known to be executable!
581 
582   if (!markBlockExecutable(Dest)) {
583     // If the destination is already executable, we just made an *edge*
584     // feasible that wasn't before.  Revisit the PHI nodes in the block
585     // because they have potentially new operands.
586     LLVM_DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName()
587                       << " -> " << Dest->getName() << '\n');
588 
589     for (PHINode &PN : Dest->phis())
590       visitPHINode(PN);
591   }
592   return true;
593 }
594 
595 // getFeasibleSuccessors - Return a vector of booleans to indicate which
596 // successors are reachable from a given terminator instruction.
597 void SCCPInstVisitor::getFeasibleSuccessors(Instruction &TI,
598                                             SmallVectorImpl<bool> &Succs) {
599   Succs.resize(TI.getNumSuccessors());
600   if (auto *BI = dyn_cast<BranchInst>(&TI)) {
601     if (BI->isUnconditional()) {
602       Succs[0] = true;
603       return;
604     }
605 
606     ValueLatticeElement BCValue = getValueState(BI->getCondition());
607     ConstantInt *CI = getConstantInt(BCValue);
608     if (!CI) {
609       // Overdefined condition variables, and branches on unfoldable constant
610       // conditions, mean the branch could go either way.
611       if (!BCValue.isUnknownOrUndef())
612         Succs[0] = Succs[1] = true;
613       return;
614     }
615 
616     // Constant condition variables mean the branch can only go a single way.
617     Succs[CI->isZero()] = true;
618     return;
619   }
620 
621   // Unwinding instructions successors are always executable.
622   if (TI.isExceptionalTerminator()) {
623     Succs.assign(TI.getNumSuccessors(), true);
624     return;
625   }
626 
627   if (auto *SI = dyn_cast<SwitchInst>(&TI)) {
628     if (!SI->getNumCases()) {
629       Succs[0] = true;
630       return;
631     }
632     const ValueLatticeElement &SCValue = getValueState(SI->getCondition());
633     if (ConstantInt *CI = getConstantInt(SCValue)) {
634       Succs[SI->findCaseValue(CI)->getSuccessorIndex()] = true;
635       return;
636     }
637 
638     // TODO: Switch on undef is UB. Stop passing false once the rest of LLVM
639     // is ready.
640     if (SCValue.isConstantRange(/*UndefAllowed=*/false)) {
641       const ConstantRange &Range = SCValue.getConstantRange();
642       for (const auto &Case : SI->cases()) {
643         const APInt &CaseValue = Case.getCaseValue()->getValue();
644         if (Range.contains(CaseValue))
645           Succs[Case.getSuccessorIndex()] = true;
646       }
647 
648       // TODO: Determine whether default case is reachable.
649       Succs[SI->case_default()->getSuccessorIndex()] = true;
650       return;
651     }
652 
653     // Overdefined or unknown condition? All destinations are executable!
654     if (!SCValue.isUnknownOrUndef())
655       Succs.assign(TI.getNumSuccessors(), true);
656     return;
657   }
658 
659   // In case of indirect branch and its address is a blockaddress, we mark
660   // the target as executable.
661   if (auto *IBR = dyn_cast<IndirectBrInst>(&TI)) {
662     // Casts are folded by visitCastInst.
663     ValueLatticeElement IBRValue = getValueState(IBR->getAddress());
664     BlockAddress *Addr = dyn_cast_or_null<BlockAddress>(getConstant(IBRValue));
665     if (!Addr) { // Overdefined or unknown condition?
666       // All destinations are executable!
667       if (!IBRValue.isUnknownOrUndef())
668         Succs.assign(TI.getNumSuccessors(), true);
669       return;
670     }
671 
672     BasicBlock *T = Addr->getBasicBlock();
673     assert(Addr->getFunction() == T->getParent() &&
674            "Block address of a different function ?");
675     for (unsigned i = 0; i < IBR->getNumSuccessors(); ++i) {
676       // This is the target.
677       if (IBR->getDestination(i) == T) {
678         Succs[i] = true;
679         return;
680       }
681     }
682 
683     // If we didn't find our destination in the IBR successor list, then we
684     // have undefined behavior. Its ok to assume no successor is executable.
685     return;
686   }
687 
688   // In case of callbr, we pessimistically assume that all successors are
689   // feasible.
690   if (isa<CallBrInst>(&TI)) {
691     Succs.assign(TI.getNumSuccessors(), true);
692     return;
693   }
694 
695   LLVM_DEBUG(dbgs() << "Unknown terminator instruction: " << TI << '\n');
696   llvm_unreachable("SCCP: Don't know how to handle this terminator!");
697 }
698 
699 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
700 // block to the 'To' basic block is currently feasible.
701 bool SCCPInstVisitor::isEdgeFeasible(BasicBlock *From, BasicBlock *To) const {
702   // Check if we've called markEdgeExecutable on the edge yet. (We could
703   // be more aggressive and try to consider edges which haven't been marked
704   // yet, but there isn't any need.)
705   return KnownFeasibleEdges.count(Edge(From, To));
706 }
707 
708 // visit Implementations - Something changed in this instruction, either an
709 // operand made a transition, or the instruction is newly executable.  Change
710 // the value type of I to reflect these changes if appropriate.  This method
711 // makes sure to do the following actions:
712 //
713 // 1. If a phi node merges two constants in, and has conflicting value coming
714 //    from different branches, or if the PHI node merges in an overdefined
715 //    value, then the PHI node becomes overdefined.
716 // 2. If a phi node merges only constants in, and they all agree on value, the
717 //    PHI node becomes a constant value equal to that.
718 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
719 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
720 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
721 // 6. If a conditional branch has a value that is constant, make the selected
722 //    destination executable
723 // 7. If a conditional branch has a value that is overdefined, make all
724 //    successors executable.
725 void SCCPInstVisitor::visitPHINode(PHINode &PN) {
726   // If this PN returns a struct, just mark the result overdefined.
727   // TODO: We could do a lot better than this if code actually uses this.
728   if (PN.getType()->isStructTy())
729     return (void)markOverdefined(&PN);
730 
731   if (getValueState(&PN).isOverdefined())
732     return; // Quick exit
733 
734   // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
735   // and slow us down a lot.  Just mark them overdefined.
736   if (PN.getNumIncomingValues() > 64)
737     return (void)markOverdefined(&PN);
738 
739   unsigned NumActiveIncoming = 0;
740 
741   // Look at all of the executable operands of the PHI node.  If any of them
742   // are overdefined, the PHI becomes overdefined as well.  If they are all
743   // constant, and they agree with each other, the PHI becomes the identical
744   // constant.  If they are constant and don't agree, the PHI is a constant
745   // range. If there are no executable operands, the PHI remains unknown.
746   ValueLatticeElement PhiState = getValueState(&PN);
747   for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
748     if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
749       continue;
750 
751     ValueLatticeElement IV = getValueState(PN.getIncomingValue(i));
752     PhiState.mergeIn(IV);
753     NumActiveIncoming++;
754     if (PhiState.isOverdefined())
755       break;
756   }
757 
758   // We allow up to 1 range extension per active incoming value and one
759   // additional extension. Note that we manually adjust the number of range
760   // extensions to match the number of active incoming values. This helps to
761   // limit multiple extensions caused by the same incoming value, if other
762   // incoming values are equal.
763   mergeInValue(&PN, PhiState,
764                ValueLatticeElement::MergeOptions().setMaxWidenSteps(
765                    NumActiveIncoming + 1));
766   ValueLatticeElement &PhiStateRef = getValueState(&PN);
767   PhiStateRef.setNumRangeExtensions(
768       std::max(NumActiveIncoming, PhiStateRef.getNumRangeExtensions()));
769 }
770 
771 void SCCPInstVisitor::visitReturnInst(ReturnInst &I) {
772   if (I.getNumOperands() == 0)
773     return; // ret void
774 
775   Function *F = I.getParent()->getParent();
776   Value *ResultOp = I.getOperand(0);
777 
778   // If we are tracking the return value of this function, merge it in.
779   if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
780     auto TFRVI = TrackedRetVals.find(F);
781     if (TFRVI != TrackedRetVals.end()) {
782       mergeInValue(TFRVI->second, F, getValueState(ResultOp));
783       return;
784     }
785   }
786 
787   // Handle functions that return multiple values.
788   if (!TrackedMultipleRetVals.empty()) {
789     if (auto *STy = dyn_cast<StructType>(ResultOp->getType()))
790       if (MRVFunctionsTracked.count(F))
791         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
792           mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
793                        getStructValueState(ResultOp, i));
794   }
795 }
796 
797 void SCCPInstVisitor::visitTerminator(Instruction &TI) {
798   SmallVector<bool, 16> SuccFeasible;
799   getFeasibleSuccessors(TI, SuccFeasible);
800 
801   BasicBlock *BB = TI.getParent();
802 
803   // Mark all feasible successors executable.
804   for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
805     if (SuccFeasible[i])
806       markEdgeExecutable(BB, TI.getSuccessor(i));
807 }
808 
809 void SCCPInstVisitor::visitCastInst(CastInst &I) {
810   // ResolvedUndefsIn might mark I as overdefined. Bail out, even if we would
811   // discover a concrete value later.
812   if (ValueState[&I].isOverdefined())
813     return;
814 
815   ValueLatticeElement OpSt = getValueState(I.getOperand(0));
816   if (OpSt.isUnknownOrUndef())
817     return;
818 
819   if (Constant *OpC = getConstant(OpSt)) {
820     // Fold the constant as we build.
821     Constant *C = ConstantFoldCastOperand(I.getOpcode(), OpC, I.getType(), DL);
822     if (isa<UndefValue>(C))
823       return;
824     // Propagate constant value
825     markConstant(&I, C);
826   } else if (I.getDestTy()->isIntegerTy()) {
827     auto &LV = getValueState(&I);
828     ConstantRange OpRange =
829         OpSt.isConstantRange()
830             ? OpSt.getConstantRange()
831             : ConstantRange::getFull(
832                   I.getOperand(0)->getType()->getScalarSizeInBits());
833 
834     Type *DestTy = I.getDestTy();
835     // Vectors where all elements have the same known constant range are treated
836     // as a single constant range in the lattice. When bitcasting such vectors,
837     // there is a mis-match between the width of the lattice value (single
838     // constant range) and the original operands (vector). Go to overdefined in
839     // that case.
840     if (I.getOpcode() == Instruction::BitCast &&
841         I.getOperand(0)->getType()->isVectorTy() &&
842         OpRange.getBitWidth() < DL.getTypeSizeInBits(DestTy))
843       return (void)markOverdefined(&I);
844 
845     ConstantRange Res =
846         OpRange.castOp(I.getOpcode(), DL.getTypeSizeInBits(DestTy));
847     mergeInValue(LV, &I, ValueLatticeElement::getRange(Res));
848   } else
849     markOverdefined(&I);
850 }
851 
852 void SCCPInstVisitor::visitExtractValueInst(ExtractValueInst &EVI) {
853   // If this returns a struct, mark all elements over defined, we don't track
854   // structs in structs.
855   if (EVI.getType()->isStructTy())
856     return (void)markOverdefined(&EVI);
857 
858   // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would
859   // discover a concrete value later.
860   if (ValueState[&EVI].isOverdefined())
861     return (void)markOverdefined(&EVI);
862 
863   // If this is extracting from more than one level of struct, we don't know.
864   if (EVI.getNumIndices() != 1)
865     return (void)markOverdefined(&EVI);
866 
867   Value *AggVal = EVI.getAggregateOperand();
868   if (AggVal->getType()->isStructTy()) {
869     unsigned i = *EVI.idx_begin();
870     ValueLatticeElement EltVal = getStructValueState(AggVal, i);
871     mergeInValue(getValueState(&EVI), &EVI, EltVal);
872   } else {
873     // Otherwise, must be extracting from an array.
874     return (void)markOverdefined(&EVI);
875   }
876 }
877 
878 void SCCPInstVisitor::visitInsertValueInst(InsertValueInst &IVI) {
879   auto *STy = dyn_cast<StructType>(IVI.getType());
880   if (!STy)
881     return (void)markOverdefined(&IVI);
882 
883   // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would
884   // discover a concrete value later.
885   if (isOverdefined(ValueState[&IVI]))
886     return (void)markOverdefined(&IVI);
887 
888   // If this has more than one index, we can't handle it, drive all results to
889   // undef.
890   if (IVI.getNumIndices() != 1)
891     return (void)markOverdefined(&IVI);
892 
893   Value *Aggr = IVI.getAggregateOperand();
894   unsigned Idx = *IVI.idx_begin();
895 
896   // Compute the result based on what we're inserting.
897   for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
898     // This passes through all values that aren't the inserted element.
899     if (i != Idx) {
900       ValueLatticeElement EltVal = getStructValueState(Aggr, i);
901       mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
902       continue;
903     }
904 
905     Value *Val = IVI.getInsertedValueOperand();
906     if (Val->getType()->isStructTy())
907       // We don't track structs in structs.
908       markOverdefined(getStructValueState(&IVI, i), &IVI);
909     else {
910       ValueLatticeElement InVal = getValueState(Val);
911       mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
912     }
913   }
914 }
915 
916 void SCCPInstVisitor::visitSelectInst(SelectInst &I) {
917   // If this select returns a struct, just mark the result overdefined.
918   // TODO: We could do a lot better than this if code actually uses this.
919   if (I.getType()->isStructTy())
920     return (void)markOverdefined(&I);
921 
922   // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would
923   // discover a concrete value later.
924   if (ValueState[&I].isOverdefined())
925     return (void)markOverdefined(&I);
926 
927   ValueLatticeElement CondValue = getValueState(I.getCondition());
928   if (CondValue.isUnknownOrUndef())
929     return;
930 
931   if (ConstantInt *CondCB = getConstantInt(CondValue)) {
932     Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
933     mergeInValue(&I, getValueState(OpVal));
934     return;
935   }
936 
937   // Otherwise, the condition is overdefined or a constant we can't evaluate.
938   // See if we can produce something better than overdefined based on the T/F
939   // value.
940   ValueLatticeElement TVal = getValueState(I.getTrueValue());
941   ValueLatticeElement FVal = getValueState(I.getFalseValue());
942 
943   bool Changed = ValueState[&I].mergeIn(TVal);
944   Changed |= ValueState[&I].mergeIn(FVal);
945   if (Changed)
946     pushToWorkListMsg(ValueState[&I], &I);
947 }
948 
949 // Handle Unary Operators.
950 void SCCPInstVisitor::visitUnaryOperator(Instruction &I) {
951   ValueLatticeElement V0State = getValueState(I.getOperand(0));
952 
953   ValueLatticeElement &IV = ValueState[&I];
954   // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would
955   // discover a concrete value later.
956   if (isOverdefined(IV))
957     return (void)markOverdefined(&I);
958 
959   if (isConstant(V0State)) {
960     Constant *C = ConstantExpr::get(I.getOpcode(), getConstant(V0State));
961 
962     // op Y -> undef.
963     if (isa<UndefValue>(C))
964       return;
965     return (void)markConstant(IV, &I, C);
966   }
967 
968   // If something is undef, wait for it to resolve.
969   if (!isOverdefined(V0State))
970     return;
971 
972   markOverdefined(&I);
973 }
974 
975 // Handle Binary Operators.
976 void SCCPInstVisitor::visitBinaryOperator(Instruction &I) {
977   ValueLatticeElement V1State = getValueState(I.getOperand(0));
978   ValueLatticeElement V2State = getValueState(I.getOperand(1));
979 
980   ValueLatticeElement &IV = ValueState[&I];
981   if (IV.isOverdefined())
982     return;
983 
984   // If something is undef, wait for it to resolve.
985   if (V1State.isUnknownOrUndef() || V2State.isUnknownOrUndef())
986     return;
987 
988   if (V1State.isOverdefined() && V2State.isOverdefined())
989     return (void)markOverdefined(&I);
990 
991   // If either of the operands is a constant, try to fold it to a constant.
992   // TODO: Use information from notconstant better.
993   if ((V1State.isConstant() || V2State.isConstant())) {
994     Value *V1 = isConstant(V1State) ? getConstant(V1State) : I.getOperand(0);
995     Value *V2 = isConstant(V2State) ? getConstant(V2State) : I.getOperand(1);
996     Value *R = SimplifyBinOp(I.getOpcode(), V1, V2, SimplifyQuery(DL));
997     auto *C = dyn_cast_or_null<Constant>(R);
998     if (C) {
999       // X op Y -> undef.
1000       if (isa<UndefValue>(C))
1001         return;
1002       // Conservatively assume that the result may be based on operands that may
1003       // be undef. Note that we use mergeInValue to combine the constant with
1004       // the existing lattice value for I, as different constants might be found
1005       // after one of the operands go to overdefined, e.g. due to one operand
1006       // being a special floating value.
1007       ValueLatticeElement NewV;
1008       NewV.markConstant(C, /*MayIncludeUndef=*/true);
1009       return (void)mergeInValue(&I, NewV);
1010     }
1011   }
1012 
1013   // Only use ranges for binary operators on integers.
1014   if (!I.getType()->isIntegerTy())
1015     return markOverdefined(&I);
1016 
1017   // Try to simplify to a constant range.
1018   ConstantRange A = ConstantRange::getFull(I.getType()->getScalarSizeInBits());
1019   ConstantRange B = ConstantRange::getFull(I.getType()->getScalarSizeInBits());
1020   if (V1State.isConstantRange())
1021     A = V1State.getConstantRange();
1022   if (V2State.isConstantRange())
1023     B = V2State.getConstantRange();
1024 
1025   ConstantRange R = A.binaryOp(cast<BinaryOperator>(&I)->getOpcode(), B);
1026   mergeInValue(&I, ValueLatticeElement::getRange(R));
1027 
1028   // TODO: Currently we do not exploit special values that produce something
1029   // better than overdefined with an overdefined operand for vector or floating
1030   // point types, like and <4 x i32> overdefined, zeroinitializer.
1031 }
1032 
1033 // Handle ICmpInst instruction.
1034 void SCCPInstVisitor::visitCmpInst(CmpInst &I) {
1035   // Do not cache this lookup, getValueState calls later in the function might
1036   // invalidate the reference.
1037   if (isOverdefined(ValueState[&I]))
1038     return (void)markOverdefined(&I);
1039 
1040   Value *Op1 = I.getOperand(0);
1041   Value *Op2 = I.getOperand(1);
1042 
1043   // For parameters, use ParamState which includes constant range info if
1044   // available.
1045   auto V1State = getValueState(Op1);
1046   auto V2State = getValueState(Op2);
1047 
1048   Constant *C = V1State.getCompare(I.getPredicate(), I.getType(), V2State);
1049   if (C) {
1050     if (isa<UndefValue>(C))
1051       return;
1052     ValueLatticeElement CV;
1053     CV.markConstant(C);
1054     mergeInValue(&I, CV);
1055     return;
1056   }
1057 
1058   // If operands are still unknown, wait for it to resolve.
1059   if ((V1State.isUnknownOrUndef() || V2State.isUnknownOrUndef()) &&
1060       !isConstant(ValueState[&I]))
1061     return;
1062 
1063   markOverdefined(&I);
1064 }
1065 
1066 // Handle getelementptr instructions.  If all operands are constants then we
1067 // can turn this into a getelementptr ConstantExpr.
1068 void SCCPInstVisitor::visitGetElementPtrInst(GetElementPtrInst &I) {
1069   if (isOverdefined(ValueState[&I]))
1070     return (void)markOverdefined(&I);
1071 
1072   SmallVector<Constant *, 8> Operands;
1073   Operands.reserve(I.getNumOperands());
1074 
1075   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1076     ValueLatticeElement State = getValueState(I.getOperand(i));
1077     if (State.isUnknownOrUndef())
1078       return; // Operands are not resolved yet.
1079 
1080     if (isOverdefined(State))
1081       return (void)markOverdefined(&I);
1082 
1083     if (Constant *C = getConstant(State)) {
1084       Operands.push_back(C);
1085       continue;
1086     }
1087 
1088     return (void)markOverdefined(&I);
1089   }
1090 
1091   Constant *Ptr = Operands[0];
1092   auto Indices = makeArrayRef(Operands.begin() + 1, Operands.end());
1093   Constant *C =
1094       ConstantExpr::getGetElementPtr(I.getSourceElementType(), Ptr, Indices);
1095   if (isa<UndefValue>(C))
1096     return;
1097   markConstant(&I, C);
1098 }
1099 
1100 void SCCPInstVisitor::visitStoreInst(StoreInst &SI) {
1101   // If this store is of a struct, ignore it.
1102   if (SI.getOperand(0)->getType()->isStructTy())
1103     return;
1104 
1105   if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1106     return;
1107 
1108   GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
1109   auto I = TrackedGlobals.find(GV);
1110   if (I == TrackedGlobals.end())
1111     return;
1112 
1113   // Get the value we are storing into the global, then merge it.
1114   mergeInValue(I->second, GV, getValueState(SI.getOperand(0)),
1115                ValueLatticeElement::MergeOptions().setCheckWiden(false));
1116   if (I->second.isOverdefined())
1117     TrackedGlobals.erase(I); // No need to keep tracking this!
1118 }
1119 
1120 static ValueLatticeElement getValueFromMetadata(const Instruction *I) {
1121   if (MDNode *Ranges = I->getMetadata(LLVMContext::MD_range))
1122     if (I->getType()->isIntegerTy())
1123       return ValueLatticeElement::getRange(
1124           getConstantRangeFromMetadata(*Ranges));
1125   if (I->hasMetadata(LLVMContext::MD_nonnull))
1126     return ValueLatticeElement::getNot(
1127         ConstantPointerNull::get(cast<PointerType>(I->getType())));
1128   return ValueLatticeElement::getOverdefined();
1129 }
1130 
1131 // Handle load instructions.  If the operand is a constant pointer to a constant
1132 // global, we can replace the load with the loaded constant value!
1133 void SCCPInstVisitor::visitLoadInst(LoadInst &I) {
1134   // If this load is of a struct or the load is volatile, just mark the result
1135   // as overdefined.
1136   if (I.getType()->isStructTy() || I.isVolatile())
1137     return (void)markOverdefined(&I);
1138 
1139   // resolvedUndefsIn might mark I as overdefined. Bail out, even if we would
1140   // discover a concrete value later.
1141   if (ValueState[&I].isOverdefined())
1142     return (void)markOverdefined(&I);
1143 
1144   ValueLatticeElement PtrVal = getValueState(I.getOperand(0));
1145   if (PtrVal.isUnknownOrUndef())
1146     return; // The pointer is not resolved yet!
1147 
1148   ValueLatticeElement &IV = ValueState[&I];
1149 
1150   if (isConstant(PtrVal)) {
1151     Constant *Ptr = getConstant(PtrVal);
1152 
1153     // load null is undefined.
1154     if (isa<ConstantPointerNull>(Ptr)) {
1155       if (NullPointerIsDefined(I.getFunction(), I.getPointerAddressSpace()))
1156         return (void)markOverdefined(IV, &I);
1157       else
1158         return;
1159     }
1160 
1161     // Transform load (constant global) into the value loaded.
1162     if (auto *GV = dyn_cast<GlobalVariable>(Ptr)) {
1163       if (!TrackedGlobals.empty()) {
1164         // If we are tracking this global, merge in the known value for it.
1165         auto It = TrackedGlobals.find(GV);
1166         if (It != TrackedGlobals.end()) {
1167           mergeInValue(IV, &I, It->second, getMaxWidenStepsOpts());
1168           return;
1169         }
1170       }
1171     }
1172 
1173     // Transform load from a constant into a constant if possible.
1174     if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, I.getType(), DL)) {
1175       if (isa<UndefValue>(C))
1176         return;
1177       return (void)markConstant(IV, &I, C);
1178     }
1179   }
1180 
1181   // Fall back to metadata.
1182   mergeInValue(&I, getValueFromMetadata(&I));
1183 }
1184 
1185 void SCCPInstVisitor::visitCallBase(CallBase &CB) {
1186   handleCallResult(CB);
1187   handleCallArguments(CB);
1188 }
1189 
1190 void SCCPInstVisitor::handleCallOverdefined(CallBase &CB) {
1191   Function *F = CB.getCalledFunction();
1192 
1193   // Void return and not tracking callee, just bail.
1194   if (CB.getType()->isVoidTy())
1195     return;
1196 
1197   // Always mark struct return as overdefined.
1198   if (CB.getType()->isStructTy())
1199     return (void)markOverdefined(&CB);
1200 
1201   // Otherwise, if we have a single return value case, and if the function is
1202   // a declaration, maybe we can constant fold it.
1203   if (F && F->isDeclaration() && canConstantFoldCallTo(&CB, F)) {
1204     SmallVector<Constant *, 8> Operands;
1205     for (const Use &A : CB.args()) {
1206       if (A.get()->getType()->isStructTy())
1207         return markOverdefined(&CB); // Can't handle struct args.
1208       ValueLatticeElement State = getValueState(A);
1209 
1210       if (State.isUnknownOrUndef())
1211         return; // Operands are not resolved yet.
1212       if (isOverdefined(State))
1213         return (void)markOverdefined(&CB);
1214       assert(isConstant(State) && "Unknown state!");
1215       Operands.push_back(getConstant(State));
1216     }
1217 
1218     if (isOverdefined(getValueState(&CB)))
1219       return (void)markOverdefined(&CB);
1220 
1221     // If we can constant fold this, mark the result of the call as a
1222     // constant.
1223     if (Constant *C = ConstantFoldCall(&CB, F, Operands, &GetTLI(*F))) {
1224       // call -> undef.
1225       if (isa<UndefValue>(C))
1226         return;
1227       return (void)markConstant(&CB, C);
1228     }
1229   }
1230 
1231   // Fall back to metadata.
1232   mergeInValue(&CB, getValueFromMetadata(&CB));
1233 }
1234 
1235 void SCCPInstVisitor::handleCallArguments(CallBase &CB) {
1236   Function *F = CB.getCalledFunction();
1237   // If this is a local function that doesn't have its address taken, mark its
1238   // entry block executable and merge in the actual arguments to the call into
1239   // the formal arguments of the function.
1240   if (!TrackingIncomingArguments.empty() &&
1241       TrackingIncomingArguments.count(F)) {
1242     markBlockExecutable(&F->front());
1243 
1244     // Propagate information from this call site into the callee.
1245     auto CAI = CB.arg_begin();
1246     for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
1247          ++AI, ++CAI) {
1248       // If this argument is byval, and if the function is not readonly, there
1249       // will be an implicit copy formed of the input aggregate.
1250       if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
1251         markOverdefined(&*AI);
1252         continue;
1253       }
1254 
1255       if (auto *STy = dyn_cast<StructType>(AI->getType())) {
1256         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1257           ValueLatticeElement CallArg = getStructValueState(*CAI, i);
1258           mergeInValue(getStructValueState(&*AI, i), &*AI, CallArg,
1259                        getMaxWidenStepsOpts());
1260         }
1261       } else
1262         mergeInValue(&*AI, getValueState(*CAI), getMaxWidenStepsOpts());
1263     }
1264   }
1265 }
1266 
1267 void SCCPInstVisitor::handleCallResult(CallBase &CB) {
1268   Function *F = CB.getCalledFunction();
1269 
1270   if (auto *II = dyn_cast<IntrinsicInst>(&CB)) {
1271     if (II->getIntrinsicID() == Intrinsic::ssa_copy) {
1272       if (ValueState[&CB].isOverdefined())
1273         return;
1274 
1275       Value *CopyOf = CB.getOperand(0);
1276       ValueLatticeElement CopyOfVal = getValueState(CopyOf);
1277       const auto *PI = getPredicateInfoFor(&CB);
1278       assert(PI && "Missing predicate info for ssa.copy");
1279 
1280       const Optional<PredicateConstraint> &Constraint = PI->getConstraint();
1281       if (!Constraint) {
1282         mergeInValue(ValueState[&CB], &CB, CopyOfVal);
1283         return;
1284       }
1285 
1286       CmpInst::Predicate Pred = Constraint->Predicate;
1287       Value *OtherOp = Constraint->OtherOp;
1288 
1289       // Wait until OtherOp is resolved.
1290       if (getValueState(OtherOp).isUnknown()) {
1291         addAdditionalUser(OtherOp, &CB);
1292         return;
1293       }
1294 
1295       // TODO: Actually filp MayIncludeUndef for the created range to false,
1296       // once most places in the optimizer respect the branches on
1297       // undef/poison are UB rule. The reason why the new range cannot be
1298       // undef is as follows below:
1299       // The new range is based on a branch condition. That guarantees that
1300       // neither of the compare operands can be undef in the branch targets,
1301       // unless we have conditions that are always true/false (e.g. icmp ule
1302       // i32, %a, i32_max). For the latter overdefined/empty range will be
1303       // inferred, but the branch will get folded accordingly anyways.
1304       bool MayIncludeUndef = !isa<PredicateAssume>(PI);
1305 
1306       ValueLatticeElement CondVal = getValueState(OtherOp);
1307       ValueLatticeElement &IV = ValueState[&CB];
1308       if (CondVal.isConstantRange() || CopyOfVal.isConstantRange()) {
1309         auto ImposedCR =
1310             ConstantRange::getFull(DL.getTypeSizeInBits(CopyOf->getType()));
1311 
1312         // Get the range imposed by the condition.
1313         if (CondVal.isConstantRange())
1314           ImposedCR = ConstantRange::makeAllowedICmpRegion(
1315               Pred, CondVal.getConstantRange());
1316 
1317         // Combine range info for the original value with the new range from the
1318         // condition.
1319         auto CopyOfCR = CopyOfVal.isConstantRange()
1320                             ? CopyOfVal.getConstantRange()
1321                             : ConstantRange::getFull(
1322                                   DL.getTypeSizeInBits(CopyOf->getType()));
1323         auto NewCR = ImposedCR.intersectWith(CopyOfCR);
1324         // If the existing information is != x, do not use the information from
1325         // a chained predicate, as the != x information is more likely to be
1326         // helpful in practice.
1327         if (!CopyOfCR.contains(NewCR) && CopyOfCR.getSingleMissingElement())
1328           NewCR = CopyOfCR;
1329 
1330         addAdditionalUser(OtherOp, &CB);
1331         mergeInValue(IV, &CB,
1332                      ValueLatticeElement::getRange(NewCR, MayIncludeUndef));
1333         return;
1334       } else if (Pred == CmpInst::ICMP_EQ && CondVal.isConstant()) {
1335         // For non-integer values or integer constant expressions, only
1336         // propagate equal constants.
1337         addAdditionalUser(OtherOp, &CB);
1338         mergeInValue(IV, &CB, CondVal);
1339         return;
1340       } else if (Pred == CmpInst::ICMP_NE && CondVal.isConstant() &&
1341                  !MayIncludeUndef) {
1342         // Propagate inequalities.
1343         addAdditionalUser(OtherOp, &CB);
1344         mergeInValue(IV, &CB,
1345                      ValueLatticeElement::getNot(CondVal.getConstant()));
1346         return;
1347       }
1348 
1349       return (void)mergeInValue(IV, &CB, CopyOfVal);
1350     }
1351 
1352     if (ConstantRange::isIntrinsicSupported(II->getIntrinsicID())) {
1353       // Compute result range for intrinsics supported by ConstantRange.
1354       // Do this even if we don't know a range for all operands, as we may
1355       // still know something about the result range, e.g. of abs(x).
1356       SmallVector<ConstantRange, 2> OpRanges;
1357       for (Value *Op : II->args()) {
1358         const ValueLatticeElement &State = getValueState(Op);
1359         if (State.isConstantRange())
1360           OpRanges.push_back(State.getConstantRange());
1361         else
1362           OpRanges.push_back(
1363               ConstantRange::getFull(Op->getType()->getScalarSizeInBits()));
1364       }
1365 
1366       ConstantRange Result =
1367           ConstantRange::intrinsic(II->getIntrinsicID(), OpRanges);
1368       return (void)mergeInValue(II, ValueLatticeElement::getRange(Result));
1369     }
1370   }
1371 
1372   // The common case is that we aren't tracking the callee, either because we
1373   // are not doing interprocedural analysis or the callee is indirect, or is
1374   // external.  Handle these cases first.
1375   if (!F || F->isDeclaration())
1376     return handleCallOverdefined(CB);
1377 
1378   // If this is a single/zero retval case, see if we're tracking the function.
1379   if (auto *STy = dyn_cast<StructType>(F->getReturnType())) {
1380     if (!MRVFunctionsTracked.count(F))
1381       return handleCallOverdefined(CB); // Not tracking this callee.
1382 
1383     // If we are tracking this callee, propagate the result of the function
1384     // into this call site.
1385     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1386       mergeInValue(getStructValueState(&CB, i), &CB,
1387                    TrackedMultipleRetVals[std::make_pair(F, i)],
1388                    getMaxWidenStepsOpts());
1389   } else {
1390     auto TFRVI = TrackedRetVals.find(F);
1391     if (TFRVI == TrackedRetVals.end())
1392       return handleCallOverdefined(CB); // Not tracking this callee.
1393 
1394     // If so, propagate the return value of the callee into this call result.
1395     mergeInValue(&CB, TFRVI->second, getMaxWidenStepsOpts());
1396   }
1397 }
1398 
1399 void SCCPInstVisitor::solve() {
1400   // Process the work lists until they are empty!
1401   while (!BBWorkList.empty() || !InstWorkList.empty() ||
1402          !OverdefinedInstWorkList.empty()) {
1403     // Process the overdefined instruction's work list first, which drives other
1404     // things to overdefined more quickly.
1405     while (!OverdefinedInstWorkList.empty()) {
1406       Value *I = OverdefinedInstWorkList.pop_back_val();
1407 
1408       LLVM_DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n');
1409 
1410       // "I" got into the work list because it either made the transition from
1411       // bottom to constant, or to overdefined.
1412       //
1413       // Anything on this worklist that is overdefined need not be visited
1414       // since all of its users will have already been marked as overdefined
1415       // Update all of the users of this instruction's value.
1416       //
1417       markUsersAsChanged(I);
1418     }
1419 
1420     // Process the instruction work list.
1421     while (!InstWorkList.empty()) {
1422       Value *I = InstWorkList.pop_back_val();
1423 
1424       LLVM_DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n');
1425 
1426       // "I" got into the work list because it made the transition from undef to
1427       // constant.
1428       //
1429       // Anything on this worklist that is overdefined need not be visited
1430       // since all of its users will have already been marked as overdefined.
1431       // Update all of the users of this instruction's value.
1432       //
1433       if (I->getType()->isStructTy() || !getValueState(I).isOverdefined())
1434         markUsersAsChanged(I);
1435     }
1436 
1437     // Process the basic block work list.
1438     while (!BBWorkList.empty()) {
1439       BasicBlock *BB = BBWorkList.pop_back_val();
1440 
1441       LLVM_DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n');
1442 
1443       // Notify all instructions in this basic block that they are newly
1444       // executable.
1445       visit(BB);
1446     }
1447   }
1448 }
1449 
1450 /// resolvedUndefsIn - While solving the dataflow for a function, we assume
1451 /// that branches on undef values cannot reach any of their successors.
1452 /// However, this is not a safe assumption.  After we solve dataflow, this
1453 /// method should be use to handle this.  If this returns true, the solver
1454 /// should be rerun.
1455 ///
1456 /// This method handles this by finding an unresolved branch and marking it one
1457 /// of the edges from the block as being feasible, even though the condition
1458 /// doesn't say it would otherwise be.  This allows SCCP to find the rest of the
1459 /// CFG and only slightly pessimizes the analysis results (by marking one,
1460 /// potentially infeasible, edge feasible).  This cannot usefully modify the
1461 /// constraints on the condition of the branch, as that would impact other users
1462 /// of the value.
1463 ///
1464 /// This scan also checks for values that use undefs. It conservatively marks
1465 /// them as overdefined.
1466 bool SCCPInstVisitor::resolvedUndefsIn(Function &F) {
1467   bool MadeChange = false;
1468   for (BasicBlock &BB : F) {
1469     if (!BBExecutable.count(&BB))
1470       continue;
1471 
1472     for (Instruction &I : BB) {
1473       // Look for instructions which produce undef values.
1474       if (I.getType()->isVoidTy())
1475         continue;
1476 
1477       if (auto *STy = dyn_cast<StructType>(I.getType())) {
1478         // Only a few things that can be structs matter for undef.
1479 
1480         // Tracked calls must never be marked overdefined in resolvedUndefsIn.
1481         if (auto *CB = dyn_cast<CallBase>(&I))
1482           if (Function *F = CB->getCalledFunction())
1483             if (MRVFunctionsTracked.count(F))
1484               continue;
1485 
1486         // extractvalue and insertvalue don't need to be marked; they are
1487         // tracked as precisely as their operands.
1488         if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(I))
1489           continue;
1490         // Send the results of everything else to overdefined.  We could be
1491         // more precise than this but it isn't worth bothering.
1492         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1493           ValueLatticeElement &LV = getStructValueState(&I, i);
1494           if (LV.isUnknownOrUndef()) {
1495             markOverdefined(LV, &I);
1496             MadeChange = true;
1497           }
1498         }
1499         continue;
1500       }
1501 
1502       ValueLatticeElement &LV = getValueState(&I);
1503       if (!LV.isUnknownOrUndef())
1504         continue;
1505 
1506       // There are two reasons a call can have an undef result
1507       // 1. It could be tracked.
1508       // 2. It could be constant-foldable.
1509       // Because of the way we solve return values, tracked calls must
1510       // never be marked overdefined in resolvedUndefsIn.
1511       if (auto *CB = dyn_cast<CallBase>(&I))
1512         if (Function *F = CB->getCalledFunction())
1513           if (TrackedRetVals.count(F))
1514             continue;
1515 
1516       if (isa<LoadInst>(I)) {
1517         // A load here means one of two things: a load of undef from a global,
1518         // a load from an unknown pointer.  Either way, having it return undef
1519         // is okay.
1520         continue;
1521       }
1522 
1523       markOverdefined(&I);
1524       MadeChange = true;
1525     }
1526 
1527     // Check to see if we have a branch or switch on an undefined value.  If so
1528     // we force the branch to go one way or the other to make the successor
1529     // values live.  It doesn't really matter which way we force it.
1530     Instruction *TI = BB.getTerminator();
1531     if (auto *BI = dyn_cast<BranchInst>(TI)) {
1532       if (!BI->isConditional())
1533         continue;
1534       if (!getValueState(BI->getCondition()).isUnknownOrUndef())
1535         continue;
1536 
1537       // If the input to SCCP is actually branch on undef, fix the undef to
1538       // false.
1539       if (isa<UndefValue>(BI->getCondition())) {
1540         BI->setCondition(ConstantInt::getFalse(BI->getContext()));
1541         markEdgeExecutable(&BB, TI->getSuccessor(1));
1542         MadeChange = true;
1543         continue;
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 = TI->getSuccessor(1);
1551       if (markEdgeExecutable(&BB, DefaultSuccessor))
1552         MadeChange = true;
1553 
1554       continue;
1555     }
1556 
1557     if (auto *IBR = dyn_cast<IndirectBrInst>(TI)) {
1558       // Indirect branch with no successor ?. Its ok to assume it branches
1559       // to no target.
1560       if (IBR->getNumSuccessors() < 1)
1561         continue;
1562 
1563       if (!getValueState(IBR->getAddress()).isUnknownOrUndef())
1564         continue;
1565 
1566       // If the input to SCCP is actually branch on undef, fix the undef to
1567       // the first successor of the indirect branch.
1568       if (isa<UndefValue>(IBR->getAddress())) {
1569         IBR->setAddress(BlockAddress::get(IBR->getSuccessor(0)));
1570         markEdgeExecutable(&BB, IBR->getSuccessor(0));
1571         MadeChange = true;
1572         continue;
1573       }
1574 
1575       // Otherwise, it is a branch on a symbolic value which is currently
1576       // considered to be undef.  Make sure some edge is executable, so a
1577       // branch on "undef" always flows somewhere.
1578       // FIXME: IndirectBr on "undef" doesn't actually need to go anywhere:
1579       // we can assume the branch has undefined behavior instead.
1580       BasicBlock *DefaultSuccessor = IBR->getSuccessor(0);
1581       if (markEdgeExecutable(&BB, DefaultSuccessor))
1582         MadeChange = true;
1583 
1584       continue;
1585     }
1586 
1587     if (auto *SI = dyn_cast<SwitchInst>(TI)) {
1588       if (!SI->getNumCases() ||
1589           !getValueState(SI->getCondition()).isUnknownOrUndef())
1590         continue;
1591 
1592       // If the input to SCCP is actually switch on undef, fix the undef to
1593       // the first constant.
1594       if (isa<UndefValue>(SI->getCondition())) {
1595         SI->setCondition(SI->case_begin()->getCaseValue());
1596         markEdgeExecutable(&BB, SI->case_begin()->getCaseSuccessor());
1597         MadeChange = true;
1598         continue;
1599       }
1600 
1601       // Otherwise, it is a branch on a symbolic value which is currently
1602       // considered to be undef.  Make sure some edge is executable, so a
1603       // branch on "undef" always flows somewhere.
1604       // FIXME: Distinguish between dead code and an LLVM "undef" value.
1605       BasicBlock *DefaultSuccessor = SI->case_begin()->getCaseSuccessor();
1606       if (markEdgeExecutable(&BB, DefaultSuccessor))
1607         MadeChange = true;
1608 
1609       continue;
1610     }
1611   }
1612 
1613   return MadeChange;
1614 }
1615 
1616 //===----------------------------------------------------------------------===//
1617 //
1618 // SCCPSolver implementations
1619 //
1620 SCCPSolver::SCCPSolver(
1621     const DataLayout &DL,
1622     std::function<const TargetLibraryInfo &(Function &)> GetTLI,
1623     LLVMContext &Ctx)
1624     : Visitor(new SCCPInstVisitor(DL, std::move(GetTLI), Ctx)) {}
1625 
1626 SCCPSolver::~SCCPSolver() = default;
1627 
1628 void SCCPSolver::addAnalysis(Function &F, AnalysisResultsForFn A) {
1629   return Visitor->addAnalysis(F, std::move(A));
1630 }
1631 
1632 bool SCCPSolver::markBlockExecutable(BasicBlock *BB) {
1633   return Visitor->markBlockExecutable(BB);
1634 }
1635 
1636 const PredicateBase *SCCPSolver::getPredicateInfoFor(Instruction *I) {
1637   return Visitor->getPredicateInfoFor(I);
1638 }
1639 
1640 DomTreeUpdater SCCPSolver::getDTU(Function &F) { return Visitor->getDTU(F); }
1641 
1642 void SCCPSolver::trackValueOfGlobalVariable(GlobalVariable *GV) {
1643   Visitor->trackValueOfGlobalVariable(GV);
1644 }
1645 
1646 void SCCPSolver::addTrackedFunction(Function *F) {
1647   Visitor->addTrackedFunction(F);
1648 }
1649 
1650 void SCCPSolver::addToMustPreserveReturnsInFunctions(Function *F) {
1651   Visitor->addToMustPreserveReturnsInFunctions(F);
1652 }
1653 
1654 bool SCCPSolver::mustPreserveReturn(Function *F) {
1655   return Visitor->mustPreserveReturn(F);
1656 }
1657 
1658 void SCCPSolver::addArgumentTrackedFunction(Function *F) {
1659   Visitor->addArgumentTrackedFunction(F);
1660 }
1661 
1662 bool SCCPSolver::isArgumentTrackedFunction(Function *F) {
1663   return Visitor->isArgumentTrackedFunction(F);
1664 }
1665 
1666 void SCCPSolver::solve() { Visitor->solve(); }
1667 
1668 bool SCCPSolver::resolvedUndefsIn(Function &F) {
1669   return Visitor->resolvedUndefsIn(F);
1670 }
1671 
1672 bool SCCPSolver::isBlockExecutable(BasicBlock *BB) const {
1673   return Visitor->isBlockExecutable(BB);
1674 }
1675 
1676 bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) const {
1677   return Visitor->isEdgeFeasible(From, To);
1678 }
1679 
1680 std::vector<ValueLatticeElement>
1681 SCCPSolver::getStructLatticeValueFor(Value *V) const {
1682   return Visitor->getStructLatticeValueFor(V);
1683 }
1684 
1685 void SCCPSolver::removeLatticeValueFor(Value *V) {
1686   return Visitor->removeLatticeValueFor(V);
1687 }
1688 
1689 const ValueLatticeElement &SCCPSolver::getLatticeValueFor(Value *V) const {
1690   return Visitor->getLatticeValueFor(V);
1691 }
1692 
1693 const MapVector<Function *, ValueLatticeElement> &
1694 SCCPSolver::getTrackedRetVals() {
1695   return Visitor->getTrackedRetVals();
1696 }
1697 
1698 const DenseMap<GlobalVariable *, ValueLatticeElement> &
1699 SCCPSolver::getTrackedGlobals() {
1700   return Visitor->getTrackedGlobals();
1701 }
1702 
1703 const SmallPtrSet<Function *, 16> SCCPSolver::getMRVFunctionsTracked() {
1704   return Visitor->getMRVFunctionsTracked();
1705 }
1706 
1707 void SCCPSolver::markOverdefined(Value *V) { Visitor->markOverdefined(V); }
1708 
1709 bool SCCPSolver::isStructLatticeConstant(Function *F, StructType *STy) {
1710   return Visitor->isStructLatticeConstant(F, STy);
1711 }
1712 
1713 Constant *SCCPSolver::getConstant(const ValueLatticeElement &LV) const {
1714   return Visitor->getConstant(LV);
1715 }
1716 
1717 SmallPtrSetImpl<Function *> &SCCPSolver::getArgumentTrackedFunctions() {
1718   return Visitor->getArgumentTrackedFunctions();
1719 }
1720 
1721 void SCCPSolver::markArgInFuncSpecialization(Function *F, Argument *A,
1722                                              Constant *C) {
1723   Visitor->markArgInFuncSpecialization(F, A, C);
1724 }
1725 
1726 void SCCPSolver::markFunctionUnreachable(Function *F) {
1727   Visitor->markFunctionUnreachable(F);
1728 }
1729 
1730 void SCCPSolver::visit(Instruction *I) { Visitor->visit(I); }
1731 
1732 void SCCPSolver::visitCall(CallInst &I) { Visitor->visitCall(I); }
1733