28#define DEBUG_TYPE "jump-table-to-switch"
30STATISTIC(NumEligibleJumpTables,
"The number of jump tables seen by the pass "
31 "that can be converted if deemed profitable.");
33 "The number of jump tables converted into switches.");
45 if (!Func || Func->isDeclaration() || Func->getFunctionType() != CallFTy ||
46 Func->getInstructionCount() >
47 Opts.jump_table_to_switch_function_size_threshold)
60 ++NumEligibleJumpTables;
62 uint64_t N = GlobalLoad->getElementCount();
63 if (
N > Opts.jump_table_to_switch_size_threshold)
71 for (
uint64_t Index = 0; Index <
N; ++Index) {
72 Constant *
C = GlobalLoad->getElementAt(Index);
88 return JumpTable{GlobalLoad->buildCanonicalIndex(Builder), std::move(Funcs)};
96 ++NumJumpTablesConverted;
108 F.getContext(),
"default.switch.case.unreachable", &
F, Tail);
113 SwitchInst *Switch = Builder.CreateSwitch(JT.Index, BBUnreachable);
119 const auto *ProfMD = CB->
getMetadata(LLVMContext::MD_prof);
128 return F.second && !F.second->isDeclaration();
130 BranchWeights.
reserve(JT.Funcs.size() + 1);
136 *CB, InstrProfValueKind::IPVK_IndirectCallTarget,
137 std::numeric_limits<uint32_t>::max(), TotalCount);
139 for (
const auto &[
G,
C] : Targets) {
140 [[maybe_unused]]
auto It = GuidToCounter.
insert({
G,
C});
146 for (
auto [Index, Func] : JT.Funcs) {
148 "call." +
Twine(Index), &
F, Tail);
156 Call->setMetadata(LLVMContext::MD_prof,
nullptr);
157 Call->setCalledFunction(Func);
158 Call->insertInto(
B,
B->end());
173 <<
"expanded indirect call into switch";
205 DomTreeUpdater DTU(DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy);
208 auto FuncToGuid = [&](
const Function &Fct) {
209 if (
const auto MaybeGUID = Fct.getGUIDIfAssigned(); MaybeGUID)
222 if (!
Call ||
Call->getCalledFunction() ||
Call->isMustTailCall())
224 std::optional<JumpTable> JT;
227 Call->getFunctionType());
231 Call->getFunctionType());
235 JT->Index = S->getCondition();
236 JT->Funcs.push_back({0, F0});
237 JT->Funcs.push_back({1, F1});
242 assert(PtrTy &&
"call operand must be a pointer");
252 CurrentBB = SplittedOutTail ? SplittedOutTail :
nullptr;
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU Register Bank Select
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static Function * getExpandableCallee(const ScalarOptions &Opts, Value *V, FunctionType *CallFTy)
static std::optional< JumpTable > parseJumpTable(const ScalarOptions &Opts, LoadInst *LI, PointerType *PtrTy, FunctionType *CallFTy, IRBuilderBase &Builder)
static BasicBlock * expandToSwitch(CallBase *CB, const JumpTable &JT, DomTreeUpdater &DTU, OptimizationRemarkEmitter &ORE, llvm::function_ref< GlobalValue::GUID(const Function &)> GetGuidForFunction)
This file contains the declarations for profiling metadata utility functions.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
LLVM Basic Block Representation.
const Function * getParent() const
Return the enclosing method, or null if none.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Value * getCalledOperand() const
static LLVM_ABI std::optional< ConstGlobalLoad > fromLoadInst(LoadInst *LI)
Analyze a load instruction to a linear expression that loads from a constant global.
This is an important base class in LLVM.
ValueT lookup_or(const_arg_type_t< KeyT > Val, U &&Default) const
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Analysis pass which computes a DominatorTree.
static constexpr UpdateKind Delete
static constexpr UpdateKind Insert
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
Common base class shared among various IRBuilders.
UnreachableInst * CreateUnreachable()
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Run the pass over the function.
An instruction for reading from memory.
Analysis pass which computes a PostDominatorTree.
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalyses & preserve()
Mark an analysis as preserved.
void reserve(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVMContext & getContext() const
All values hold a context through their type.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
This is an optimization pass for GlobalISel generic memory operations.
constexpr auto not_equal_to(T &&Arg)
Functor variant of std::not_equal_to that can be used as a UnaryPredicate in functional algorithms li...
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
LLVM_ABI std::string getIRPGOObjectName(const GlobalObject &GO, bool InLTO=false)
const ScalarOptions & getScalarOptions(const LLVMContext &C)
LLVM_ABI void setExplicitlyUnknownBranchWeights(Instruction &I, StringRef PassName)
Specify that the branch weights for this terminator cannot be known at compile time.
LLVM_ABI void setBranchWeights(Instruction &I, ArrayRef< uint32_t > Weights, bool IsExpected, bool ElideAllZero=false)
Create a new branch_weights metadata node and add or overwrite a prof metadata reference to instructi...
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI SmallVector< InstrProfValueData, 4 > getValueProfDataFromInst(const Instruction &Inst, InstrProfValueKind ValueKind, uint32_t MaxNumValueData, uint64_t &TotalC, bool GetNoICPValue=false)
Extract the value profile data from Inst and returns them if Inst is annotated with value profile dat...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
LLVM_ABI bool isValueProfileMD(const MDNode *ProfileData)
Checks if an MDNode contains value profiling Metadata.
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI SmallVector< uint32_t > downscaleWeights(ArrayRef< uint64_t > Weights, std::optional< uint64_t > KnownMaxCount=std::nullopt)
downscale the given weights preserving the ratio.