diff --git a/llvm/include/llvm/Transforms/Scalar/SCCP.h b/include/llvm/Transforms/Scalar/SCCP.h --- a/llvm/include/llvm/Transforms/Scalar/SCCP.h +++ b/include/llvm/Transforms/Scalar/SCCP.h @@ -20,15 +20,346 @@ #ifndef LLVM_TRANSFORMS_SCALAR_SCCP_H #define LLVM_TRANSFORMS_SCALAR_SCCP_H +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/DenseMap.h" +#include "llvm/ADT/DenseSet.h" +#include "llvm/ADT/MapVector.h" +#include "llvm/ADT/PointerIntPair.h" #include "llvm/ADT/STLExtras.h" +#include "llvm/ADT/SetVector.h" +#include "llvm/ADT/SmallPtrSet.h" +#include "llvm/ADT/SmallVector.h" +#include "llvm/Analysis/DomTreeUpdater.h" #include "llvm/Analysis/TargetLibraryInfo.h" +#include "llvm/Analysis/ValueLattice.h" +#include "llvm/Analysis/ValueLatticeUtils.h" +#include "llvm/Analysis/ValueTracking.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/Function.h" +#include "llvm/IR/InstVisitor.h" #include "llvm/IR/Module.h" #include "llvm/IR/PassManager.h" #include "llvm/Transforms/Utils/PredicateInfo.h" namespace llvm { +/// Helper struct for bundling up the analysis results per function for IPSCCP. +struct AnalysisResultsForFn { + std::unique_ptr PredInfo; + DominatorTree *DT; + PostDominatorTree *PDT; +}; + +//===----------------------------------------------------------------------===// +// +/// SCCPSolver - This class is a general purpose solver for Sparse Conditional +/// Constant Propagation. +/// +class SCCPSolver : public InstVisitor { + const DataLayout &DL; + std::function GetTLI; + SmallPtrSet BBExecutable; // The BBs that are executable. + DenseMap + ValueState; // The state each value is in. + + /// StructValueState - This maintains ValueState for values that have + /// StructType, for example for formal arguments, calls, insertelement, etc. + DenseMap, ValueLatticeElement> StructValueState; + + /// GlobalValue - If we are tracking any values for the contents of a global + /// variable, we keep a mapping from the constant accessor to the element of + /// the global, to the currently known value. If the value becomes + /// overdefined, it's entry is simply removed from this map. + DenseMap TrackedGlobals; + + /// TrackedRetVals - If we are tracking arguments into and the return + /// value out of a function, it will have an entry in this map, indicating + /// what the known return value for the function is. + MapVector TrackedRetVals; + + /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions + /// that return multiple values. + MapVector, ValueLatticeElement> + TrackedMultipleRetVals; + + /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is + /// represented here for efficient lookup. + SmallPtrSet MRVFunctionsTracked; + + /// MustTailFunctions - Each function here is a callee of non-removable + /// musttail call site. + SmallPtrSet MustTailCallees; + + /// TrackingIncomingArguments - This is the set of functions for whose + /// arguments we make optimistic assumptions about and try to prove as + /// constants. + SmallPtrSet TrackingIncomingArguments; + + /// The reason for two worklists is that overdefined is the lowest state + /// on the lattice, and moving things to overdefined as fast as possible + /// makes SCCP converge much faster. + /// + /// By having a separate worklist, we accomplish this because everything + /// possibly overdefined will become overdefined at the soonest possible + /// point. + SmallVector OverdefinedInstWorkList; + SmallVector InstWorkList; + + // The BasicBlock work list + SmallVector BBWorkList; + + /// KnownFeasibleEdges - Entries in this set are edges which have already had + /// PHI nodes retriggered. + using Edge = std::pair; + DenseSet KnownFeasibleEdges; + + DenseMap AnalysisResults; + DenseMap> AdditionalUsers; + + LLVMContext &Ctx; + +public: + void addAnalysis(Function &F, AnalysisResultsForFn A); + + const PredicateBase *getPredicateInfoFor(Instruction *I); + + DomTreeUpdater getDTU(Function &F); + + SCCPSolver(const DataLayout &DL, + std::function GetTLI, + LLVMContext &Ctx); + + /// MarkBlockExecutable - This method can be used by clients to mark all of + /// the blocks that are known to be intrinsically live in the processed unit. + /// + /// This returns true if the block was not considered live before. + bool MarkBlockExecutable(BasicBlock *BB); + + /// TrackValueOfGlobalVariable - Clients can use this method to + /// inform the SCCPSolver that it should track loads and stores to the + /// specified global variable if it can. This is only legal to call if + /// performing Interprocedural SCCP. + void TrackValueOfGlobalVariable(GlobalVariable *GV); + + /// AddTrackedFunction - If the SCCP solver is supposed to track calls into + /// and out of the specified function (which cannot have its address taken), + /// this method must be called. + void AddTrackedFunction(Function *F); + + /// AddMustTailCallee - If the SCCP solver finds that this function is called + /// from non-removable musttail call site. + void AddMustTailCallee(Function *F) { MustTailCallees.insert(F); } + + /// Returns true if the given function is called from non-removable musttail + /// call site. + bool isMustTailCallee(Function *F) { return MustTailCallees.count(F); } + + void AddArgumentTrackedFunction(Function *F) { + TrackingIncomingArguments.insert(F); + } + + /// Returns true if the given function is in the solver's set of + /// argument-tracked functions. + bool isArgumentTrackedFunction(Function *F) { + return TrackingIncomingArguments.count(F); + } + + /// Solve - Solve for constants and executable blocks. + void Solve(); + + /// ResolvedUndefsIn - While solving the dataflow for a function, we assume + /// that branches on undef values cannot reach any of their successors. + /// However, this is not a safe assumption. After we solve dataflow, this + /// method should be use to handle this. If this returns true, the solver + /// should be rerun. + bool ResolvedUndefsIn(Function &F); + + bool isBlockExecutable(BasicBlock *BB) const { + return BBExecutable.count(BB); + } + + // isEdgeFeasible - Return true if the control flow edge from the 'From' basic + // block to the 'To' basic block is currently feasible. + bool isEdgeFeasible(BasicBlock *From, BasicBlock *To) const; + + std::vector getStructLatticeValueFor(Value *V) const; + + void removeLatticeValueFor(Value *V) { ValueState.erase(V); } + + const ValueLatticeElement &getLatticeValueFor(Value *V) const; + + /// getTrackedRetVals - Get the inferred return value map. + const MapVector &getTrackedRetVals() { + return TrackedRetVals; + } + + /// getTrackedGlobals - Get and return the set of inferred initializers for + /// global variables. + const DenseMap &getTrackedGlobals() { + return TrackedGlobals; + } + + /// getMRVFunctionsTracked - Get the set of functions which return multiple + /// values tracked by the pass. + const SmallPtrSet getMRVFunctionsTracked() { + return MRVFunctionsTracked; + } + + /// getMustTailCallees - Get the set of functions which are called + /// from non-removable musttail call sites. + const SmallPtrSet getMustTailCallees() { + return MustTailCallees; + } + + /// markOverdefined - Mark the specified value overdefined. This + /// works with both scalars and structs. + void markOverdefined(Value *V); + + // isStructLatticeConstant - Return true if all the lattice values + // corresponding to elements of the structure are constants, + // false otherwise. + bool isStructLatticeConstant(Function *F, StructType *STy); + + /// Helper to return a Constant if \p LV is either a constant or a constant + /// range with a single element. + Constant *getConstant(const ValueLatticeElement &LV) const; + +private: + ConstantInt *getConstantInt(const ValueLatticeElement &IV) const { + return dyn_cast_or_null(getConstant(IV)); + } + + // pushToWorkList - Helper for markConstant/markOverdefined + void pushToWorkList(ValueLatticeElement &IV, Value *V) { + if (IV.isOverdefined()) + return OverdefinedInstWorkList.push_back(V); + InstWorkList.push_back(V); + } + + // Helper to push \p V to the worklist, after updating it to \p IV. Also + // prints a debug message with the updated value. + void pushToWorkListMsg(ValueLatticeElement &IV, Value *V); + + // markConstant - Make a value be marked as "constant". If the value + // is not already a constant, add it to the instruction work list so that + // the users of the instruction are updated later. + bool markConstant(ValueLatticeElement &IV, Value *V, Constant *C, + bool MayIncludeUndef = false); + + bool markConstant(Value *V, Constant *C) { + assert(!V->getType()->isStructTy() && "structs should use mergeInValue"); + return markConstant(ValueState[V], V, C); + } + + // markOverdefined - Make a value be marked as "overdefined". If the + // value is not already overdefined, add it to the overdefined instruction + // work list so that the users of the instruction are updated later. + bool markOverdefined(ValueLatticeElement &IV, Value *V); + + /// Merge \p MergeWithV into \p IV and push \p V to the worklist, if \p IV + /// changes. + bool mergeInValue(ValueLatticeElement &IV, Value *V, + ValueLatticeElement MergeWithV, + ValueLatticeElement::MergeOptions Opts = { + /*MayIncludeUndef=*/false, /*CheckWiden=*/false}); + + bool mergeInValue(Value *V, ValueLatticeElement MergeWithV, + ValueLatticeElement::MergeOptions Opts = { + /*MayIncludeUndef=*/false, /*CheckWiden=*/false}); + + /// getValueState - Return the ValueLatticeElement object that corresponds to + /// the value. This function handles the case when the value hasn't been seen + /// yet by properly seeding constants etc. + ValueLatticeElement &getValueState(Value *V); + + /// getStructValueState - Return the ValueLatticeElement object that + /// corresponds to the value/field pair. This function handles the case when + /// the value hasn't been seen yet by properly seeding constants etc. + ValueLatticeElement &getStructValueState(Value *V, unsigned i); + + /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB + /// work list if it is not already executable. + bool markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest); + + // getFeasibleSuccessors - Return a vector of booleans to indicate which + // successors are reachable from a given terminator instruction. + void getFeasibleSuccessors(Instruction &TI, SmallVectorImpl &Succs); + + // OperandChangedState - This method is invoked on all of the users of an + // instruction that was just changed state somehow. Based on this + // information, we need to update the specified user of this instruction. + void OperandChangedState(Instruction *I) { + if (BBExecutable.count(I->getParent())) // Inst is executable? + visit(*I); + } + + // Add U as additional user of V. + void addAdditionalUser(Value *V, User *U) { + auto Iter = AdditionalUsers.insert({V, {}}); + Iter.first->second.insert(U); + } + + // Mark I's users as changed, including AdditionalUsers. + void markUsersAsChanged(Value *I); + void handleCallOverdefined(CallBase &CB); + void handleCallResult(CallBase &CB); + void handleCallArguments(CallBase &CB); + +private: + friend class InstVisitor; + + // visit implementations - Something changed in this instruction. Either an + // operand made a transition, or the instruction is newly executable. Change + // the value type of I to reflect these changes if appropriate. + void visitPHINode(PHINode &I); + + // Terminators + + void visitReturnInst(ReturnInst &I); + void visitTerminator(Instruction &TI); + + void visitCastInst(CastInst &I); + void visitSelectInst(SelectInst &I); + void visitUnaryOperator(Instruction &I); + void visitBinaryOperator(Instruction &I); + void visitCmpInst(CmpInst &I); + void visitExtractValueInst(ExtractValueInst &EVI); + void visitInsertValueInst(InsertValueInst &IVI); + + void visitCatchSwitchInst(CatchSwitchInst &CPI) { + markOverdefined(&CPI); + visitTerminator(CPI); + } + + // Instructions that cannot be folded away. + + void visitStoreInst(StoreInst &I); + void visitLoadInst(LoadInst &I); + void visitGetElementPtrInst(GetElementPtrInst &I); + + void visitCallInst(CallInst &I) { visitCallBase(I); } + + void visitInvokeInst(InvokeInst &II) { + visitCallBase(II); + visitTerminator(II); + } + + void visitCallBrInst(CallBrInst &CBI) { + visitCallBase(CBI); + visitTerminator(CBI); + } + + void visitCallBase(CallBase &CB); + void visitResumeInst(ResumeInst &I) { /*returns void*/ + } + void visitUnreachableInst(UnreachableInst &I) { /*returns void*/ + } + void visitFenceInst(FenceInst &I) { /*returns void*/ + } + + void visitInstruction(Instruction &I); +}; + +bool tryToReplaceWithConstant(llvm::SCCPSolver &Solver, Value *V); class PostDominatorTree; @@ -38,12 +369,6 @@ PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM); }; -/// Helper struct for bundling up the analysis results per function for IPSCCP. -struct AnalysisResultsForFn { - std::unique_ptr PredInfo; - DominatorTree *DT; - PostDominatorTree *PDT; -}; bool runIPSCCP(Module &M, const DataLayout &DL, std::function GetTLI, diff --git a/llvm/lib/Transforms/Scalar/SCCP.cpp b/lib/Transforms/Scalar/SCCP.cpp --- a/llvm/lib/Transforms/Scalar/SCCP.cpp +++ b/lib/Transforms/Scalar/SCCP.cpp @@ -17,24 +17,11 @@ //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar/SCCP.h" -#include "llvm/ADT/ArrayRef.h" -#include "llvm/ADT/DenseMap.h" -#include "llvm/ADT/DenseSet.h" -#include "llvm/ADT/MapVector.h" -#include "llvm/ADT/PointerIntPair.h" -#include "llvm/ADT/STLExtras.h" -#include "llvm/ADT/SetVector.h" -#include "llvm/ADT/SmallPtrSet.h" -#include "llvm/ADT/SmallVector.h" #include "llvm/ADT/Statistic.h" #include "llvm/Analysis/ConstantFolding.h" -#include "llvm/Analysis/DomTreeUpdater.h" #include "llvm/Analysis/GlobalsModRef.h" #include "llvm/Analysis/InstructionSimplify.h" #include "llvm/Analysis/TargetLibraryInfo.h" -#include "llvm/Analysis/ValueLattice.h" -#include "llvm/Analysis/ValueLatticeUtils.h" -#include "llvm/Analysis/ValueTracking.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/Constant.h" #include "llvm/IR/Constants.h" @@ -107,510 +94,239 @@ bool isOverdefined(const ValueLatticeElement &LV) { return !LV.isUnknownOrUndef() && !isConstant(LV); } +} // namespace -//===----------------------------------------------------------------------===// -// -/// SCCPSolver - This class is a general purpose solver for Sparse Conditional -/// Constant Propagation. -/// -class SCCPSolver : public InstVisitor { - const DataLayout &DL; - std::function GetTLI; - SmallPtrSet BBExecutable; // The BBs that are executable. - DenseMap - ValueState; // The state each value is in. - - /// StructValueState - This maintains ValueState for values that have - /// StructType, for example for formal arguments, calls, insertelement, etc. - DenseMap, ValueLatticeElement> StructValueState; - - /// GlobalValue - If we are tracking any values for the contents of a global - /// variable, we keep a mapping from the constant accessor to the element of - /// the global, to the currently known value. If the value becomes - /// overdefined, it's entry is simply removed from this map. - DenseMap TrackedGlobals; - - /// TrackedRetVals - If we are tracking arguments into and the return - /// value out of a function, it will have an entry in this map, indicating - /// what the known return value for the function is. - MapVector TrackedRetVals; - - /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions - /// that return multiple values. - MapVector, ValueLatticeElement> - TrackedMultipleRetVals; - - /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is - /// represented here for efficient lookup. - SmallPtrSet MRVFunctionsTracked; - - /// MustTailFunctions - Each function here is a callee of non-removable - /// musttail call site. - SmallPtrSet MustTailCallees; - - /// TrackingIncomingArguments - This is the set of functions for whose - /// arguments we make optimistic assumptions about and try to prove as - /// constants. - SmallPtrSet TrackingIncomingArguments; - - /// The reason for two worklists is that overdefined is the lowest state - /// on the lattice, and moving things to overdefined as fast as possible - /// makes SCCP converge much faster. - /// - /// By having a separate worklist, we accomplish this because everything - /// possibly overdefined will become overdefined at the soonest possible - /// point. - SmallVector OverdefinedInstWorkList; - SmallVector InstWorkList; - - // The BasicBlock work list - SmallVector BBWorkList; - - /// KnownFeasibleEdges - Entries in this set are edges which have already had - /// PHI nodes retriggered. - using Edge = std::pair; - DenseSet KnownFeasibleEdges; - - DenseMap AnalysisResults; - DenseMap> AdditionalUsers; - - LLVMContext &Ctx; - -public: - void addAnalysis(Function &F, AnalysisResultsForFn A) { - AnalysisResults.insert({&F, std::move(A)}); - } - - const PredicateBase *getPredicateInfoFor(Instruction *I) { - auto A = AnalysisResults.find(I->getParent()->getParent()); - if (A == AnalysisResults.end()) - return nullptr; - return A->second.PredInfo->getPredicateInfoFor(I); - } - - DomTreeUpdater getDTU(Function &F) { - auto A = AnalysisResults.find(&F); - assert(A != AnalysisResults.end() && "Need analysis results for function."); - return {A->second.DT, A->second.PDT, DomTreeUpdater::UpdateStrategy::Lazy}; - } - - SCCPSolver(const DataLayout &DL, - std::function GetTLI, - LLVMContext &Ctx) - : DL(DL), GetTLI(std::move(GetTLI)), Ctx(Ctx) {} - - /// MarkBlockExecutable - This method can be used by clients to mark all of - /// the blocks that are known to be intrinsically live in the processed unit. - /// - /// This returns true if the block was not considered live before. - bool MarkBlockExecutable(BasicBlock *BB) { - if (!BBExecutable.insert(BB).second) - return false; - LLVM_DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << '\n'); - BBWorkList.push_back(BB); // Add the block to the work list! - return true; - } - - /// TrackValueOfGlobalVariable - Clients can use this method to - /// inform the SCCPSolver that it should track loads and stores to the - /// specified global variable if it can. This is only legal to call if - /// performing Interprocedural SCCP. - void TrackValueOfGlobalVariable(GlobalVariable *GV) { - // We only track the contents of scalar globals. - if (GV->getValueType()->isSingleValueType()) { - ValueLatticeElement &IV = TrackedGlobals[GV]; - if (!isa(GV->getInitializer())) - IV.markConstant(GV->getInitializer()); - } - } - - /// AddTrackedFunction - If the SCCP solver is supposed to track calls into - /// and out of the specified function (which cannot have its address taken), - /// this method must be called. - void AddTrackedFunction(Function *F) { - // Add an entry, F -> undef. - if (auto *STy = dyn_cast(F->getReturnType())) { - MRVFunctionsTracked.insert(F); - for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) - TrackedMultipleRetVals.insert( - std::make_pair(std::make_pair(F, i), ValueLatticeElement())); - } else if (!F->getReturnType()->isVoidTy()) - TrackedRetVals.insert(std::make_pair(F, ValueLatticeElement())); - } - - /// AddMustTailCallee - If the SCCP solver finds that this function is called - /// from non-removable musttail call site. - void AddMustTailCallee(Function *F) { - MustTailCallees.insert(F); - } - - /// Returns true if the given function is called from non-removable musttail - /// call site. - bool isMustTailCallee(Function *F) { - return MustTailCallees.count(F); - } - - void AddArgumentTrackedFunction(Function *F) { - TrackingIncomingArguments.insert(F); - } - - /// Returns true if the given function is in the solver's set of - /// argument-tracked functions. - bool isArgumentTrackedFunction(Function *F) { - return TrackingIncomingArguments.count(F); - } - - /// Solve - Solve for constants and executable blocks. - void Solve(); - - /// ResolvedUndefsIn - While solving the dataflow for a function, we assume - /// that branches on undef values cannot reach any of their successors. - /// However, this is not a safe assumption. After we solve dataflow, this - /// method should be use to handle this. If this returns true, the solver - /// should be rerun. - bool ResolvedUndefsIn(Function &F); - - bool isBlockExecutable(BasicBlock *BB) const { - return BBExecutable.count(BB); - } - - // isEdgeFeasible - Return true if the control flow edge from the 'From' basic - // block to the 'To' basic block is currently feasible. - bool isEdgeFeasible(BasicBlock *From, BasicBlock *To) const; - - std::vector getStructLatticeValueFor(Value *V) const { - std::vector StructValues; - auto *STy = dyn_cast(V->getType()); - assert(STy && "getStructLatticeValueFor() can be called only on structs"); - for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { - auto I = StructValueState.find(std::make_pair(V, i)); - assert(I != StructValueState.end() && "Value not in valuemap!"); - StructValues.push_back(I->second); - } - return StructValues; - } +void SCCPSolver::addAnalysis(Function &F, AnalysisResultsForFn A) { + AnalysisResults.insert({&F, std::move(A)}); +} - void removeLatticeValueFor(Value *V) { ValueState.erase(V); } +const PredicateBase *SCCPSolver::getPredicateInfoFor(Instruction *I) { + auto A = AnalysisResults.find(I->getParent()->getParent()); + if (A == AnalysisResults.end()) + return nullptr; + return A->second.PredInfo->getPredicateInfoFor(I); +} - const ValueLatticeElement &getLatticeValueFor(Value *V) const { - assert(!V->getType()->isStructTy() && - "Should use getStructLatticeValueFor"); - DenseMap::const_iterator I = - ValueState.find(V); - assert(I != ValueState.end() && - "V not found in ValueState nor Paramstate map!"); - return I->second; - } +DomTreeUpdater SCCPSolver::getDTU(Function &F) { + auto A = AnalysisResults.find(&F); + assert(A != AnalysisResults.end() && "Need analysis results for function."); + return {A->second.DT, A->second.PDT, DomTreeUpdater::UpdateStrategy::Lazy}; +} - /// getTrackedRetVals - Get the inferred return value map. - const MapVector &getTrackedRetVals() { - return TrackedRetVals; - } +SCCPSolver::SCCPSolver( + const DataLayout &DL, + std::function GetTLI, + LLVMContext &Ctx) + : DL(DL), GetTLI(std::move(GetTLI)), Ctx(Ctx) {} - /// getTrackedGlobals - Get and return the set of inferred initializers for - /// global variables. - const DenseMap &getTrackedGlobals() { - return TrackedGlobals; - } +bool SCCPSolver::MarkBlockExecutable(BasicBlock *BB) { + if (!BBExecutable.insert(BB).second) + return false; + LLVM_DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << '\n'); + BBWorkList.push_back(BB); // Add the block to the work list! + return true; +} - /// getMRVFunctionsTracked - Get the set of functions which return multiple - /// values tracked by the pass. - const SmallPtrSet getMRVFunctionsTracked() { - return MRVFunctionsTracked; +void SCCPSolver::TrackValueOfGlobalVariable(GlobalVariable *GV) { + // We only track the contents of scalar globals. + if (GV->getValueType()->isSingleValueType()) { + ValueLatticeElement &IV = TrackedGlobals[GV]; + if (!isa(GV->getInitializer())) + IV.markConstant(GV->getInitializer()); } +} - /// getMustTailCallees - Get the set of functions which are called - /// from non-removable musttail call sites. - const SmallPtrSet getMustTailCallees() { - return MustTailCallees; - } +void SCCPSolver::AddTrackedFunction(Function *F) { + // Add an entry, F -> undef. + if (auto *STy = dyn_cast(F->getReturnType())) { + MRVFunctionsTracked.insert(F); + for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) + TrackedMultipleRetVals.insert( + std::make_pair(std::make_pair(F, i), ValueLatticeElement())); + } else if (!F->getReturnType()->isVoidTy()) + TrackedRetVals.insert(std::make_pair(F, ValueLatticeElement())); +} - /// markOverdefined - Mark the specified value overdefined. This - /// works with both scalars and structs. - void markOverdefined(Value *V) { - if (auto *STy = dyn_cast(V->getType())) - for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) - markOverdefined(getStructValueState(V, i), V); - else - markOverdefined(ValueState[V], V); +std::vector +SCCPSolver::getStructLatticeValueFor(Value *V) const { + std::vector StructValues; + auto *STy = dyn_cast(V->getType()); + assert(STy && "getStructLatticeValueFor() can be called only on structs"); + for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { + auto I = StructValueState.find(std::make_pair(V, i)); + assert(I != StructValueState.end() && "Value not in valuemap!"); + StructValues.push_back(I->second); } + return StructValues; +} - // isStructLatticeConstant - Return true if all the lattice values - // corresponding to elements of the structure are constants, - // false otherwise. - bool isStructLatticeConstant(Function *F, StructType *STy) { - for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { - const auto &It = TrackedMultipleRetVals.find(std::make_pair(F, i)); - assert(It != TrackedMultipleRetVals.end()); - ValueLatticeElement LV = It->second; - if (!isConstant(LV)) - return false; - } - return true; - } +const ValueLatticeElement &SCCPSolver::getLatticeValueFor(Value *V) const { + assert(!V->getType()->isStructTy() && "Should use getStructLatticeValueFor"); + DenseMap::const_iterator I = ValueState.find(V); + assert(I != ValueState.end() && + "V not found in ValueState nor Paramstate map!"); + return I->second; +} - /// Helper to return a Constant if \p LV is either a constant or a constant - /// range with a single element. - Constant *getConstant(const ValueLatticeElement &LV) const { - if (LV.isConstant()) - return LV.getConstant(); +void SCCPSolver::markOverdefined(Value *V) { + if (auto *STy = dyn_cast(V->getType())) + for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) + markOverdefined(getStructValueState(V, i), V); + else + markOverdefined(ValueState[V], V); +} - if (LV.isConstantRange()) { - auto &CR = LV.getConstantRange(); - if (CR.getSingleElement()) - return ConstantInt::get(Ctx, *CR.getSingleElement()); - } - return nullptr; +bool SCCPSolver::isStructLatticeConstant(Function *F, StructType *STy) { + for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { + const auto &It = TrackedMultipleRetVals.find(std::make_pair(F, i)); + assert(It != TrackedMultipleRetVals.end()); + ValueLatticeElement LV = It->second; + if (!isConstant(LV)) + return false; } + return true; +} -private: - ConstantInt *getConstantInt(const ValueLatticeElement &IV) const { - return dyn_cast_or_null(getConstant(IV)); - } +Constant *SCCPSolver::getConstant(const ValueLatticeElement &LV) const { + if (LV.isConstant()) + return LV.getConstant(); - // pushToWorkList - Helper for markConstant/markOverdefined - void pushToWorkList(ValueLatticeElement &IV, Value *V) { - if (IV.isOverdefined()) - return OverdefinedInstWorkList.push_back(V); - InstWorkList.push_back(V); + if (LV.isConstantRange()) { + auto &CR = LV.getConstantRange(); + if (CR.getSingleElement()) + return ConstantInt::get(Ctx, *CR.getSingleElement()); } + return nullptr; +} - // Helper to push \p V to the worklist, after updating it to \p IV. Also - // prints a debug message with the updated value. - void pushToWorkListMsg(ValueLatticeElement &IV, Value *V) { - LLVM_DEBUG(dbgs() << "updated " << IV << ": " << *V << '\n'); - pushToWorkList(IV, V); - } +void SCCPSolver::pushToWorkListMsg(ValueLatticeElement &IV, Value *V) { + LLVM_DEBUG(dbgs() << "updated " << IV << ": " << *V << '\n'); + pushToWorkList(IV, V); +} +bool SCCPSolver::markConstant(ValueLatticeElement &IV, Value *V, Constant *C, + bool MayIncludeUndef) { + if (!IV.markConstant(C, MayIncludeUndef)) + return false; + LLVM_DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n'); + pushToWorkList(IV, V); + return true; +} - // markConstant - Make a value be marked as "constant". If the value - // is not already a constant, add it to the instruction work list so that - // the users of the instruction are updated later. - bool markConstant(ValueLatticeElement &IV, Value *V, Constant *C, - bool MayIncludeUndef = false) { - if (!IV.markConstant(C, MayIncludeUndef)) - return false; - LLVM_DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n'); - pushToWorkList(IV, V); - return true; - } +bool SCCPSolver::markOverdefined(ValueLatticeElement &IV, Value *V) { + if (!IV.markOverdefined()) + return false; - bool markConstant(Value *V, Constant *C) { - assert(!V->getType()->isStructTy() && "structs should use mergeInValue"); - return markConstant(ValueState[V], V, C); - } + LLVM_DEBUG(dbgs() << "markOverdefined: "; + if (auto *F = dyn_cast(V)) dbgs() + << "Function '" << F->getName() << "'\n"; + else dbgs() << *V << '\n'); + // Only instructions go on the work list + pushToWorkList(IV, V); + return true; +} - // markOverdefined - Make a value be marked as "overdefined". If the - // value is not already overdefined, add it to the overdefined instruction - // work list so that the users of the instruction are updated later. - bool markOverdefined(ValueLatticeElement &IV, Value *V) { - if (!IV.markOverdefined()) return false; - - LLVM_DEBUG(dbgs() << "markOverdefined: "; - if (auto *F = dyn_cast(V)) dbgs() - << "Function '" << F->getName() << "'\n"; - else dbgs() << *V << '\n'); - // Only instructions go on the work list +bool SCCPSolver::mergeInValue(ValueLatticeElement &IV, Value *V, + ValueLatticeElement MergeWithV, + ValueLatticeElement::MergeOptions Opts) { + if (IV.mergeIn(MergeWithV, Opts)) { pushToWorkList(IV, V); + LLVM_DEBUG(dbgs() << "Merged " << MergeWithV << " into " << *V << " : " + << IV << "\n"); return true; } + return false; +} - /// Merge \p MergeWithV into \p IV and push \p V to the worklist, if \p IV - /// changes. - bool mergeInValue(ValueLatticeElement &IV, Value *V, - ValueLatticeElement MergeWithV, - ValueLatticeElement::MergeOptions Opts = { - /*MayIncludeUndef=*/false, /*CheckWiden=*/false}) { - if (IV.mergeIn(MergeWithV, Opts)) { - pushToWorkList(IV, V); - LLVM_DEBUG(dbgs() << "Merged " << MergeWithV << " into " << *V << " : " - << IV << "\n"); - return true; - } - return false; - } - - bool mergeInValue(Value *V, ValueLatticeElement MergeWithV, - ValueLatticeElement::MergeOptions Opts = { - /*MayIncludeUndef=*/false, /*CheckWiden=*/false}) { - assert(!V->getType()->isStructTy() && - "non-structs should use markConstant"); - return mergeInValue(ValueState[V], V, MergeWithV, Opts); - } - - /// getValueState - Return the ValueLatticeElement object that corresponds to - /// the value. This function handles the case when the value hasn't been seen - /// yet by properly seeding constants etc. - ValueLatticeElement &getValueState(Value *V) { - assert(!V->getType()->isStructTy() && "Should use getStructValueState"); +bool SCCPSolver::mergeInValue(Value *V, ValueLatticeElement MergeWithV, + ValueLatticeElement::MergeOptions Opts) { + assert(!V->getType()->isStructTy() && "non-structs should use markConstant"); + return mergeInValue(ValueState[V], V, MergeWithV, Opts); +} - auto I = ValueState.insert(std::make_pair(V, ValueLatticeElement())); - ValueLatticeElement &LV = I.first->second; +ValueLatticeElement &SCCPSolver::getValueState(Value *V) { + assert(!V->getType()->isStructTy() && "Should use getStructValueState"); - if (!I.second) - return LV; // Common case, already in the map. + auto I = ValueState.insert(std::make_pair(V, ValueLatticeElement())); + ValueLatticeElement &LV = I.first->second; - if (auto *C = dyn_cast(V)) - LV.markConstant(C); // Constants are constant + if (!I.second) + return LV; // Common case, already in the map. - // All others are unknown by default. - return LV; - } + if (auto *C = dyn_cast(V)) + LV.markConstant(C); // Constants are constant - /// getStructValueState - Return the ValueLatticeElement object that - /// corresponds to the value/field pair. This function handles the case when - /// the value hasn't been seen yet by properly seeding constants etc. - ValueLatticeElement &getStructValueState(Value *V, unsigned i) { - assert(V->getType()->isStructTy() && "Should use getValueState"); - assert(i < cast(V->getType())->getNumElements() && - "Invalid element #"); + // All others are unknown by default. + return LV; +} - auto I = StructValueState.insert( - std::make_pair(std::make_pair(V, i), ValueLatticeElement())); - ValueLatticeElement &LV = I.first->second; +ValueLatticeElement &SCCPSolver::getStructValueState(Value *V, unsigned i) { + assert(V->getType()->isStructTy() && "Should use getValueState"); + assert(i < cast(V->getType())->getNumElements() && + "Invalid element #"); - if (!I.second) - return LV; // Common case, already in the map. + auto I = StructValueState.insert( + std::make_pair(std::make_pair(V, i), ValueLatticeElement())); + ValueLatticeElement &LV = I.first->second; - if (auto *C = dyn_cast(V)) { - Constant *Elt = C->getAggregateElement(i); + if (!I.second) + return LV; // Common case, already in the map. - if (!Elt) - LV.markOverdefined(); // Unknown sort of constant. - else if (isa(Elt)) - ; // Undef values remain unknown. - else - LV.markConstant(Elt); // Constants are constant. - } + if (auto *C = dyn_cast(V)) { + Constant *Elt = C->getAggregateElement(i); - // All others are underdefined by default. - return LV; + if (!Elt) + LV.markOverdefined(); // Unknown sort of constant. + else if (isa(Elt)) + ; // Undef values remain unknown. + else + LV.markConstant(Elt); // Constants are constant. } - /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB - /// work list if it is not already executable. - bool markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) { - if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second) - return false; // This edge is already known to be executable! - - if (!MarkBlockExecutable(Dest)) { - // If the destination is already executable, we just made an *edge* - // feasible that wasn't before. Revisit the PHI nodes in the block - // because they have potentially new operands. - LLVM_DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName() - << " -> " << Dest->getName() << '\n'); - - for (PHINode &PN : Dest->phis()) - visitPHINode(PN); - } - return true; - } + // All others are underdefined by default. + return LV; +} - // getFeasibleSuccessors - Return a vector of booleans to indicate which - // successors are reachable from a given terminator instruction. - void getFeasibleSuccessors(Instruction &TI, SmallVectorImpl &Succs); +bool SCCPSolver::markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) { + if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second) + return false; // This edge is already known to be executable! - // OperandChangedState - This method is invoked on all of the users of an - // instruction that was just changed state somehow. Based on this - // information, we need to update the specified user of this instruction. - void OperandChangedState(Instruction *I) { - if (BBExecutable.count(I->getParent())) // Inst is executable? - visit(*I); - } + if (!MarkBlockExecutable(Dest)) { + // If the destination is already executable, we just made an *edge* + // feasible that wasn't before. Revisit the PHI nodes in the block + // because they have potentially new operands. + LLVM_DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName() + << " -> " << Dest->getName() << '\n'); - // Add U as additional user of V. - void addAdditionalUser(Value *V, User *U) { - auto Iter = AdditionalUsers.insert({V, {}}); - Iter.first->second.insert(U); + for (PHINode &PN : Dest->phis()) + visitPHINode(PN); } + return true; +} // Mark I's users as changed, including AdditionalUsers. - void markUsersAsChanged(Value *I) { - // Functions include their arguments in the use-list. Changed function - // values mean that the result of the function changed. We only need to - // update the call sites with the new function result and do not have to - // propagate the call arguments. - if (isa(I)) { - for (User *U : I->users()) { - if (auto *CB = dyn_cast(U)) - handleCallResult(*CB); - } - } else { - for (User *U : I->users()) - if (auto *UI = dyn_cast(U)) - OperandChangedState(UI); - } - - auto Iter = AdditionalUsers.find(I); - if (Iter != AdditionalUsers.end()) { - for (User *U : Iter->second) - if (auto *UI = dyn_cast(U)) - OperandChangedState(UI); +void SCCPSolver::markUsersAsChanged(Value *I) { + // Functions include their arguments in the use-list. Changed function + // values mean that the result of the function changed. We only need to + // update the call sites with the new function result and do not have to + // propagate the call arguments. + if (isa(I)) { + for (User *U : I->users()) { + if (auto *CB = dyn_cast(U)) + handleCallResult(*CB); } - } - void handleCallOverdefined(CallBase &CB); - void handleCallResult(CallBase &CB); - void handleCallArguments(CallBase &CB); - -private: - friend class InstVisitor; - - // visit implementations - Something changed in this instruction. Either an - // operand made a transition, or the instruction is newly executable. Change - // the value type of I to reflect these changes if appropriate. - void visitPHINode(PHINode &I); - - // Terminators - - void visitReturnInst(ReturnInst &I); - void visitTerminator(Instruction &TI); - - void visitCastInst(CastInst &I); - void visitSelectInst(SelectInst &I); - void visitUnaryOperator(Instruction &I); - void visitBinaryOperator(Instruction &I); - void visitCmpInst(CmpInst &I); - void visitExtractValueInst(ExtractValueInst &EVI); - void visitInsertValueInst(InsertValueInst &IVI); - - void visitCatchSwitchInst(CatchSwitchInst &CPI) { - markOverdefined(&CPI); - visitTerminator(CPI); - } - - // Instructions that cannot be folded away. - - void visitStoreInst (StoreInst &I); - void visitLoadInst (LoadInst &I); - void visitGetElementPtrInst(GetElementPtrInst &I); - - void visitCallInst (CallInst &I) { - visitCallBase(I); - } - - void visitInvokeInst (InvokeInst &II) { - visitCallBase(II); - visitTerminator(II); - } - - void visitCallBrInst (CallBrInst &CBI) { - visitCallBase(CBI); - visitTerminator(CBI); + } else { + for (User *U : I->users()) + if (auto *UI = dyn_cast(U)) + OperandChangedState(UI); } - void visitCallBase (CallBase &CB); - void visitResumeInst (ResumeInst &I) { /*returns void*/ } - void visitUnreachableInst(UnreachableInst &I) { /*returns void*/ } - void visitFenceInst (FenceInst &I) { /*returns void*/ } - - void visitInstruction(Instruction &I) { - // All the instructions we don't do any special handling for just - // go to overdefined. - LLVM_DEBUG(dbgs() << "SCCP: Don't know how to handle: " << I << '\n'); - markOverdefined(&I); + auto Iter = AdditionalUsers.find(I); + if (Iter != AdditionalUsers.end()) { + for (User *U : Iter->second) + if (auto *UI = dyn_cast(U)) + OperandChangedState(UI); } -}; - -} // end anonymous namespace +} // getFeasibleSuccessors - Return a vector of booleans to indicate which // successors are reachable from a given terminator instruction. @@ -1198,6 +914,13 @@ handleCallArguments(CB); } +void SCCPSolver::visitInstruction(Instruction &I) { + // All the instructions we don't do any special handling for just + // go to overdefined. + LLVM_DEBUG(dbgs() << "SCCP: Don't know how to handle: " << I << '\n'); + markOverdefined(&I); +} + void SCCPSolver::handleCallOverdefined(CallBase &CB) { Function *F = CB.getCalledFunction(); @@ -1624,7 +1347,7 @@ return MadeChange; } -static bool tryToReplaceWithConstant(SCCPSolver &Solver, Value *V) { +bool llvm::tryToReplaceWithConstant(SCCPSolver &Solver, Value *V) { Constant *Const = nullptr; if (V->getType()->isStructTy()) { std::vector IVs = Solver.getStructLatticeValueFor(V);