Path: blob/main/contrib/llvm-project/llvm/lib/Transforms/IPO/CalledValuePropagation.cpp
35269 views
//===- CalledValuePropagation.cpp - Propagate called values -----*- C++ -*-===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements a transformation that attaches !callees metadata to9// indirect call sites. For a given call site, the metadata, if present,10// indicates the set of functions the call site could possibly target at11// run-time. This metadata is added to indirect call sites when the set of12// possible targets can be determined by analysis and is known to be small. The13// analysis driving the transformation is similar to constant propagation and14// makes uses of the generic sparse propagation solver.15//16//===----------------------------------------------------------------------===//1718#include "llvm/Transforms/IPO/CalledValuePropagation.h"19#include "llvm/Analysis/SparsePropagation.h"20#include "llvm/Analysis/ValueLatticeUtils.h"21#include "llvm/IR/Constants.h"22#include "llvm/IR/MDBuilder.h"23#include "llvm/IR/Module.h"24#include "llvm/Support/CommandLine.h"25#include "llvm/Transforms/IPO.h"2627using namespace llvm;2829#define DEBUG_TYPE "called-value-propagation"3031/// The maximum number of functions to track per lattice value. Once the number32/// of functions a call site can possibly target exceeds this threshold, it's33/// lattice value becomes overdefined. The number of possible lattice values is34/// bounded by Ch(F, M), where F is the number of functions in the module and M35/// is MaxFunctionsPerValue. As such, this value should be kept very small. We36/// likely can't do anything useful for call sites with a large number of37/// possible targets, anyway.38static cl::opt<unsigned> MaxFunctionsPerValue(39"cvp-max-functions-per-value", cl::Hidden, cl::init(4),40cl::desc("The maximum number of functions to track per lattice value"));4142namespace {43/// To enable interprocedural analysis, we assign LLVM values to the following44/// groups. The register group represents SSA registers, the return group45/// represents the return values of functions, and the memory group represents46/// in-memory values. An LLVM Value can technically be in more than one group.47/// It's necessary to distinguish these groups so we can, for example, track a48/// global variable separately from the value stored at its location.49enum class IPOGrouping { Register, Return, Memory };5051/// Our LatticeKeys are PointerIntPairs composed of LLVM values and groupings.52using CVPLatticeKey = PointerIntPair<Value *, 2, IPOGrouping>;5354/// The lattice value type used by our custom lattice function. It holds the55/// lattice state, and a set of functions.56class CVPLatticeVal {57public:58/// The states of the lattice values. Only the FunctionSet state is59/// interesting. It indicates the set of functions to which an LLVM value may60/// refer.61enum CVPLatticeStateTy { Undefined, FunctionSet, Overdefined, Untracked };6263/// Comparator for sorting the functions set. We want to keep the order64/// deterministic for testing, etc.65struct Compare {66bool operator()(const Function *LHS, const Function *RHS) const {67return LHS->getName() < RHS->getName();68}69};7071CVPLatticeVal() = default;72CVPLatticeVal(CVPLatticeStateTy LatticeState) : LatticeState(LatticeState) {}73CVPLatticeVal(std::vector<Function *> &&Functions)74: LatticeState(FunctionSet), Functions(std::move(Functions)) {75assert(llvm::is_sorted(this->Functions, Compare()));76}7778/// Get a reference to the functions held by this lattice value. The number79/// of functions will be zero for states other than FunctionSet.80const std::vector<Function *> &getFunctions() const {81return Functions;82}8384/// Returns true if the lattice value is in the FunctionSet state.85bool isFunctionSet() const { return LatticeState == FunctionSet; }8687bool operator==(const CVPLatticeVal &RHS) const {88return LatticeState == RHS.LatticeState && Functions == RHS.Functions;89}9091bool operator!=(const CVPLatticeVal &RHS) const {92return LatticeState != RHS.LatticeState || Functions != RHS.Functions;93}9495private:96/// Holds the state this lattice value is in.97CVPLatticeStateTy LatticeState = Undefined;9899/// Holds functions indicating the possible targets of call sites. This set100/// is empty for lattice values in the undefined, overdefined, and untracked101/// states. The maximum size of the set is controlled by102/// MaxFunctionsPerValue. Since most LLVM values are expected to be in103/// uninteresting states (i.e., overdefined), CVPLatticeVal objects should be104/// small and efficiently copyable.105// FIXME: This could be a TinyPtrVector and/or merge with LatticeState.106std::vector<Function *> Functions;107};108109/// The custom lattice function used by the generic sparse propagation solver.110/// It handles merging lattice values and computing new lattice values for111/// constants, arguments, values returned from trackable functions, and values112/// located in trackable global variables. It also computes the lattice values113/// that change as a result of executing instructions.114class CVPLatticeFunc115: public AbstractLatticeFunction<CVPLatticeKey, CVPLatticeVal> {116public:117CVPLatticeFunc()118: AbstractLatticeFunction(CVPLatticeVal(CVPLatticeVal::Undefined),119CVPLatticeVal(CVPLatticeVal::Overdefined),120CVPLatticeVal(CVPLatticeVal::Untracked)) {}121122/// Compute and return a CVPLatticeVal for the given CVPLatticeKey.123CVPLatticeVal ComputeLatticeVal(CVPLatticeKey Key) override {124switch (Key.getInt()) {125case IPOGrouping::Register:126if (isa<Instruction>(Key.getPointer())) {127return getUndefVal();128} else if (auto *A = dyn_cast<Argument>(Key.getPointer())) {129if (canTrackArgumentsInterprocedurally(A->getParent()))130return getUndefVal();131} else if (auto *C = dyn_cast<Constant>(Key.getPointer())) {132return computeConstant(C);133}134return getOverdefinedVal();135case IPOGrouping::Memory:136case IPOGrouping::Return:137if (auto *GV = dyn_cast<GlobalVariable>(Key.getPointer())) {138if (canTrackGlobalVariableInterprocedurally(GV))139return computeConstant(GV->getInitializer());140} else if (auto *F = cast<Function>(Key.getPointer()))141if (canTrackReturnsInterprocedurally(F))142return getUndefVal();143}144return getOverdefinedVal();145}146147/// Merge the two given lattice values. The interesting cases are merging two148/// FunctionSet values and a FunctionSet value with an Undefined value. For149/// these cases, we simply union the function sets. If the size of the union150/// is greater than the maximum functions we track, the merged value is151/// overdefined.152CVPLatticeVal MergeValues(CVPLatticeVal X, CVPLatticeVal Y) override {153if (X == getOverdefinedVal() || Y == getOverdefinedVal())154return getOverdefinedVal();155if (X == getUndefVal() && Y == getUndefVal())156return getUndefVal();157std::vector<Function *> Union;158std::set_union(X.getFunctions().begin(), X.getFunctions().end(),159Y.getFunctions().begin(), Y.getFunctions().end(),160std::back_inserter(Union), CVPLatticeVal::Compare{});161if (Union.size() > MaxFunctionsPerValue)162return getOverdefinedVal();163return CVPLatticeVal(std::move(Union));164}165166/// Compute the lattice values that change as a result of executing the given167/// instruction. The changed values are stored in \p ChangedValues. We handle168/// just a few kinds of instructions since we're only propagating values that169/// can be called.170void ComputeInstructionState(171Instruction &I, DenseMap<CVPLatticeKey, CVPLatticeVal> &ChangedValues,172SparseSolver<CVPLatticeKey, CVPLatticeVal> &SS) override {173switch (I.getOpcode()) {174case Instruction::Call:175case Instruction::Invoke:176return visitCallBase(cast<CallBase>(I), ChangedValues, SS);177case Instruction::Load:178return visitLoad(*cast<LoadInst>(&I), ChangedValues, SS);179case Instruction::Ret:180return visitReturn(*cast<ReturnInst>(&I), ChangedValues, SS);181case Instruction::Select:182return visitSelect(*cast<SelectInst>(&I), ChangedValues, SS);183case Instruction::Store:184return visitStore(*cast<StoreInst>(&I), ChangedValues, SS);185default:186return visitInst(I, ChangedValues, SS);187}188}189190/// Print the given CVPLatticeVal to the specified stream.191void PrintLatticeVal(CVPLatticeVal LV, raw_ostream &OS) override {192if (LV == getUndefVal())193OS << "Undefined ";194else if (LV == getOverdefinedVal())195OS << "Overdefined";196else if (LV == getUntrackedVal())197OS << "Untracked ";198else199OS << "FunctionSet";200}201202/// Print the given CVPLatticeKey to the specified stream.203void PrintLatticeKey(CVPLatticeKey Key, raw_ostream &OS) override {204if (Key.getInt() == IPOGrouping::Register)205OS << "<reg> ";206else if (Key.getInt() == IPOGrouping::Memory)207OS << "<mem> ";208else if (Key.getInt() == IPOGrouping::Return)209OS << "<ret> ";210if (isa<Function>(Key.getPointer()))211OS << Key.getPointer()->getName();212else213OS << *Key.getPointer();214}215216/// We collect a set of indirect calls when visiting call sites. This method217/// returns a reference to that set.218SmallPtrSetImpl<CallBase *> &getIndirectCalls() { return IndirectCalls; }219220private:221/// Holds the indirect calls we encounter during the analysis. We will attach222/// metadata to these calls after the analysis indicating the functions the223/// calls can possibly target.224SmallPtrSet<CallBase *, 32> IndirectCalls;225226/// Compute a new lattice value for the given constant. The constant, after227/// stripping any pointer casts, should be a Function. We ignore null228/// pointers as an optimization, since calling these values is undefined229/// behavior.230CVPLatticeVal computeConstant(Constant *C) {231if (isa<ConstantPointerNull>(C))232return CVPLatticeVal(CVPLatticeVal::FunctionSet);233if (auto *F = dyn_cast<Function>(C->stripPointerCasts()))234return CVPLatticeVal({F});235return getOverdefinedVal();236}237238/// Handle return instructions. The function's return state is the merge of239/// the returned value state and the function's return state.240void visitReturn(ReturnInst &I,241DenseMap<CVPLatticeKey, CVPLatticeVal> &ChangedValues,242SparseSolver<CVPLatticeKey, CVPLatticeVal> &SS) {243Function *F = I.getParent()->getParent();244if (F->getReturnType()->isVoidTy())245return;246auto RegI = CVPLatticeKey(I.getReturnValue(), IPOGrouping::Register);247auto RetF = CVPLatticeKey(F, IPOGrouping::Return);248ChangedValues[RetF] =249MergeValues(SS.getValueState(RegI), SS.getValueState(RetF));250}251252/// Handle call sites. The state of a called function's formal arguments is253/// the merge of the argument state with the call sites corresponding actual254/// argument state. The call site state is the merge of the call site state255/// with the returned value state of the called function.256void visitCallBase(CallBase &CB,257DenseMap<CVPLatticeKey, CVPLatticeVal> &ChangedValues,258SparseSolver<CVPLatticeKey, CVPLatticeVal> &SS) {259Function *F = CB.getCalledFunction();260auto RegI = CVPLatticeKey(&CB, IPOGrouping::Register);261262// If this is an indirect call, save it so we can quickly revisit it when263// attaching metadata.264if (!F)265IndirectCalls.insert(&CB);266267// If we can't track the function's return values, there's nothing to do.268if (!F || !canTrackReturnsInterprocedurally(F)) {269// Void return, No need to create and update CVPLattice state as no one270// can use it.271if (CB.getType()->isVoidTy())272return;273ChangedValues[RegI] = getOverdefinedVal();274return;275}276277// Inform the solver that the called function is executable, and perform278// the merges for the arguments and return value.279SS.MarkBlockExecutable(&F->front());280auto RetF = CVPLatticeKey(F, IPOGrouping::Return);281for (Argument &A : F->args()) {282auto RegFormal = CVPLatticeKey(&A, IPOGrouping::Register);283auto RegActual =284CVPLatticeKey(CB.getArgOperand(A.getArgNo()), IPOGrouping::Register);285ChangedValues[RegFormal] =286MergeValues(SS.getValueState(RegFormal), SS.getValueState(RegActual));287}288289// Void return, No need to create and update CVPLattice state as no one can290// use it.291if (CB.getType()->isVoidTy())292return;293294ChangedValues[RegI] =295MergeValues(SS.getValueState(RegI), SS.getValueState(RetF));296}297298/// Handle select instructions. The select instruction state is the merge the299/// true and false value states.300void visitSelect(SelectInst &I,301DenseMap<CVPLatticeKey, CVPLatticeVal> &ChangedValues,302SparseSolver<CVPLatticeKey, CVPLatticeVal> &SS) {303auto RegI = CVPLatticeKey(&I, IPOGrouping::Register);304auto RegT = CVPLatticeKey(I.getTrueValue(), IPOGrouping::Register);305auto RegF = CVPLatticeKey(I.getFalseValue(), IPOGrouping::Register);306ChangedValues[RegI] =307MergeValues(SS.getValueState(RegT), SS.getValueState(RegF));308}309310/// Handle load instructions. If the pointer operand of the load is a global311/// variable, we attempt to track the value. The loaded value state is the312/// merge of the loaded value state with the global variable state.313void visitLoad(LoadInst &I,314DenseMap<CVPLatticeKey, CVPLatticeVal> &ChangedValues,315SparseSolver<CVPLatticeKey, CVPLatticeVal> &SS) {316auto RegI = CVPLatticeKey(&I, IPOGrouping::Register);317if (auto *GV = dyn_cast<GlobalVariable>(I.getPointerOperand())) {318auto MemGV = CVPLatticeKey(GV, IPOGrouping::Memory);319ChangedValues[RegI] =320MergeValues(SS.getValueState(RegI), SS.getValueState(MemGV));321} else {322ChangedValues[RegI] = getOverdefinedVal();323}324}325326/// Handle store instructions. If the pointer operand of the store is a327/// global variable, we attempt to track the value. The global variable state328/// is the merge of the stored value state with the global variable state.329void visitStore(StoreInst &I,330DenseMap<CVPLatticeKey, CVPLatticeVal> &ChangedValues,331SparseSolver<CVPLatticeKey, CVPLatticeVal> &SS) {332auto *GV = dyn_cast<GlobalVariable>(I.getPointerOperand());333if (!GV)334return;335auto RegI = CVPLatticeKey(I.getValueOperand(), IPOGrouping::Register);336auto MemGV = CVPLatticeKey(GV, IPOGrouping::Memory);337ChangedValues[MemGV] =338MergeValues(SS.getValueState(RegI), SS.getValueState(MemGV));339}340341/// Handle all other instructions. All other instructions are marked342/// overdefined.343void visitInst(Instruction &I,344DenseMap<CVPLatticeKey, CVPLatticeVal> &ChangedValues,345SparseSolver<CVPLatticeKey, CVPLatticeVal> &SS) {346// Simply bail if this instruction has no user.347if (I.use_empty())348return;349auto RegI = CVPLatticeKey(&I, IPOGrouping::Register);350ChangedValues[RegI] = getOverdefinedVal();351}352};353} // namespace354355namespace llvm {356/// A specialization of LatticeKeyInfo for CVPLatticeKeys. The generic solver357/// must translate between LatticeKeys and LLVM Values when adding Values to358/// its work list and inspecting the state of control-flow related values.359template <> struct LatticeKeyInfo<CVPLatticeKey> {360static inline Value *getValueFromLatticeKey(CVPLatticeKey Key) {361return Key.getPointer();362}363static inline CVPLatticeKey getLatticeKeyFromValue(Value *V) {364return CVPLatticeKey(V, IPOGrouping::Register);365}366};367} // namespace llvm368369static bool runCVP(Module &M) {370// Our custom lattice function and generic sparse propagation solver.371CVPLatticeFunc Lattice;372SparseSolver<CVPLatticeKey, CVPLatticeVal> Solver(&Lattice);373374// For each function in the module, if we can't track its arguments, let the375// generic solver assume it is executable.376for (Function &F : M)377if (!F.isDeclaration() && !canTrackArgumentsInterprocedurally(&F))378Solver.MarkBlockExecutable(&F.front());379380// Solver our custom lattice. In doing so, we will also build a set of381// indirect call sites.382Solver.Solve();383384// Attach metadata to the indirect call sites that were collected indicating385// the set of functions they can possibly target.386bool Changed = false;387MDBuilder MDB(M.getContext());388for (CallBase *C : Lattice.getIndirectCalls()) {389auto RegI = CVPLatticeKey(C->getCalledOperand(), IPOGrouping::Register);390CVPLatticeVal LV = Solver.getExistingValueState(RegI);391if (!LV.isFunctionSet() || LV.getFunctions().empty())392continue;393MDNode *Callees = MDB.createCallees(LV.getFunctions());394C->setMetadata(LLVMContext::MD_callees, Callees);395Changed = true;396}397398return Changed;399}400401PreservedAnalyses CalledValuePropagationPass::run(Module &M,402ModuleAnalysisManager &) {403runCVP(M);404return PreservedAnalyses::all();405}406407408