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