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