67 #define DEBUG_TYPE "mergeicmps" 71 if (
const LoadInst *LI = dyn_cast<LoadInst>(I))
72 return LI->isSimple();
74 return SI->isSimple();
84 :
GEP(GEP), LoadI(LoadI), BaseId(BaseId),
Offset(Offset) {}
86 BCEAtom(
const BCEAtom &) =
delete;
87 BCEAtom &operator=(
const BCEAtom &) =
delete;
89 BCEAtom(BCEAtom &&that) =
default;
90 BCEAtom &operator=(BCEAtom &&that) {
96 Offset = std::move(that.Offset);
111 return BaseId != O.BaseId ? BaseId < O.BaseId : Offset.
slt(O.Offset);
122 class BaseIdentifier {
127 assert(Base &&
"invalid base");
128 const auto Insertion = BaseToIndex.try_emplace(Base, Order);
129 if (Insertion.second)
131 return Insertion.first->second;
142 BCEAtom visitICmpLoadOperand(
Value *
const Val, BaseIdentifier &BaseId) {
147 if (LoadI->isUsedOutsideOfBlock(LoadI->getParent())) {
152 if (!LoadI->isSimple()) {
156 Value *
const Addr = LoadI->getOperand(0);
161 if (
GEP->isUsedOutsideOfBlock(LoadI->getParent())) {
165 const auto &DL =
GEP->getModule()->getDataLayout();
173 if (!
GEP->accumulateConstantOffset(DL, Offset))
175 return BCEAtom(
GEP, LoadI, BaseId.getBaseId(
GEP->getPointerOperand()),
193 BCECmpBlock(BCEAtom L, BCEAtom R,
int SizeBits)
194 : Lhs_(std::move(L)), Rhs_(std::move(R)), SizeBits_(SizeBits) {
198 bool IsValid()
const {
return Lhs_.BaseId != 0 && Rhs_.BaseId != 0; }
202 void AssertConsistent()
const {
210 const BCEAtom &Lhs()
const {
return Lhs_; }
211 const BCEAtom &Rhs()
const {
return Rhs_; }
212 int SizeBits()
const {
return SizeBits_; }
215 bool doesOtherWork()
const;
240 bool RequireSplit =
false;
248 bool BCECmpBlock::canSinkBCECmpInst(
const Instruction *Inst,
255 if (!isSimpleLoadOrStore(Inst))
266 for (
auto BI : BlockInsts) {
275 {Lhs_.GEP, Rhs_.GEP, Lhs_.LoadI, Rhs_.LoadI, CmpI, BranchI});
278 if (BlockInsts.
count(&Inst))
280 assert(canSinkBCECmpInst(&Inst, BlockInsts, AA) &&
281 "Split unsplittable block");
284 OtherInsts.push_back(&Inst);
295 {Lhs_.GEP, Rhs_.GEP, Lhs_.LoadI, Rhs_.LoadI, CmpI, BranchI});
297 if (!BlockInsts.
count(&Inst)) {
298 if (!canSinkBCECmpInst(&Inst, BlockInsts, AA))
305 bool BCECmpBlock::doesOtherWork()
const {
309 {Lhs_.GEP, Rhs_.GEP, Lhs_.LoadI, Rhs_.LoadI, CmpI, BranchI});
315 if (!BlockInsts.
count(&Inst))
323 BCECmpBlock visitICmp(
const ICmpInst *
const CmpI,
325 BaseIdentifier &BaseId) {
340 auto Lhs = visitICmpLoadOperand(CmpI->
getOperand(0), BaseId);
343 auto Rhs = visitICmpLoadOperand(CmpI->
getOperand(1), BaseId);
347 return BCECmpBlock(std::move(Lhs), std::move(Rhs),
355 BaseIdentifier &BaseId) {
356 if (Block->
empty())
return {};
358 if (!BranchI)
return {};
360 if (BranchI->isUnconditional()) {
366 if (!CmpI)
return {};
370 Result.BranchI = BranchI;
377 if (!Const->isZero())
return {};
380 if (!CmpI)
return {};
382 assert(BranchI->getNumSuccessors() == 2 &&
"expecting a cond branch");
383 BasicBlock *
const FalseBlock = BranchI->getSuccessor(1);
384 auto Result = visitICmp(
388 Result.BranchI = BranchI;
394 static inline void enqueueBlock(std::vector<BCECmpBlock> &Comparisons,
395 BCECmpBlock &&Comparison) {
397 <<
"': Found cmp of " << Comparison.SizeBits()
398 <<
" bits between " << Comparison.Lhs().BaseId <<
" + " 399 << Comparison.Lhs().Offset <<
" and " 400 << Comparison.Rhs().BaseId <<
" + " 401 << Comparison.Rhs().Offset <<
"\n");
403 Comparisons.push_back(std::move(Comparison));
409 BCECmpChain(
const std::vector<BasicBlock *> &Blocks,
PHINode &Phi,
412 int size()
const {
return Comparisons_.size(); }
414 #ifdef MERGEICMPS_DOT_ON 416 #endif // MERGEICMPS_DOT_ON 422 static bool IsContiguous(
const BCECmpBlock &First,
423 const BCECmpBlock &Second) {
424 return First.Lhs().BaseId == Second.Lhs().BaseId &&
425 First.Rhs().BaseId == Second.Rhs().BaseId &&
426 First.Lhs().Offset + First.SizeBits() / 8 == Second.Lhs().Offset &&
427 First.Rhs().Offset + First.SizeBits() / 8 == Second.Rhs().Offset;
431 std::vector<BCECmpBlock> Comparisons_;
436 BCECmpChain::BCECmpChain(
const std::vector<BasicBlock *> &Blocks,
PHINode &Phi,
439 assert(!Blocks.empty() &&
"a chain should have at least one block");
441 std::vector<BCECmpBlock> Comparisons;
442 BaseIdentifier BaseId;
443 for (
size_t BlockIdx = 0; BlockIdx < Blocks.size(); ++BlockIdx) {
445 assert(Block &&
"invalid block");
448 Comparison.BB = Block;
449 if (!Comparison.IsValid()) {
450 LLVM_DEBUG(
dbgs() <<
"chain with invalid BCECmpBlock, no merge.\n");
453 if (Comparison.doesOtherWork()) {
455 <<
"' does extra work besides compare\n");
456 if (Comparisons.empty()) {
470 if (Comparison.canSplit(AA)) {
472 <<
"Split initial block '" << Comparison.BB->getName()
473 <<
"' that does extra work besides compare\n");
474 Comparison.RequireSplit =
true;
475 enqueueBlock(Comparisons, std::move(Comparison));
478 <<
"ignoring initial block '" << Comparison.BB->getName()
479 <<
"' that does extra work besides compare\n");
508 enqueueBlock(Comparisons, std::move(Comparison));
512 if (Comparisons.empty()) {
513 LLVM_DEBUG(
dbgs() <<
"chain with no BCE basic blocks, no merge\n");
516 EntryBlock_ = Comparisons[0].BB;
517 Comparisons_ = std::move(Comparisons);
518 #ifdef MERGEICMPS_DOT_ON 519 errs() <<
"BEFORE REORDERING:\n\n";
521 #endif // MERGEICMPS_DOT_ON 525 [](
const BCECmpBlock &LhsBlock,
const BCECmpBlock &RhsBlock) {
526 return std::tie(LhsBlock.Lhs(), LhsBlock.Rhs()) <
527 std::tie(RhsBlock.Lhs(), RhsBlock.Rhs());
529 #ifdef MERGEICMPS_DOT_ON 530 errs() <<
"AFTER REORDERING:\n\n";
532 #endif // MERGEICMPS_DOT_ON 535 #ifdef MERGEICMPS_DOT_ON 537 errs() <<
"digraph dag {\n";
538 errs() <<
" graph [bgcolor=transparent];\n";
539 errs() <<
" node [color=black,style=filled,fillcolor=lightyellow];\n";
540 errs() <<
" edge [color=black];\n";
541 for (
size_t I = 0;
I < Comparisons_.size(); ++
I) {
542 const auto &Comparison = Comparisons_[
I];
543 errs() <<
" \"" <<
I <<
"\" [label=\"%" 544 << Comparison.Lhs().Base()->getName() <<
" + " 545 << Comparison.Lhs().Offset <<
" == %" 546 << Comparison.Rhs().Base()->getName() <<
" + " 547 << Comparison.Rhs().Offset <<
" (" << (Comparison.SizeBits() / 8)
549 const Value *
const Val = Phi_.getIncomingValueForBlock(Comparison.BB);
550 if (
I > 0)
errs() <<
" \"" << (
I - 1) <<
"\" -> \"" <<
I <<
"\";\n";
551 errs() <<
" \"" <<
I <<
"\" -> \"Phi\" [label=\"" << *Val <<
"\"];\n";
553 errs() <<
" \"Phi\" [label=\"Phi\"];\n";
556 #endif // MERGEICMPS_DOT_ON 562 class MergedBlockName {
568 :
Name(makeName(Comparisons)) {}
575 if (Comparisons.
size() == 1)
576 return Comparisons[0].BB->getName();
577 const int size = std::accumulate(Comparisons.
begin(), Comparisons.
end(), 0,
578 [](
int i,
const BCECmpBlock &Cmp) {
579 return i + Cmp.BB->getName().size();
590 Scratch.
append(str.begin(), str.end());
592 append(Comparisons[0].BB->getName());
593 for (
int I = 1,
E = Comparisons.
size();
I <
E; ++
I) {
611 assert(!Comparisons.
empty() &&
"merging zero comparisons");
613 const BCECmpBlock &FirstCmp = Comparisons[0];
618 NextCmpBlock->
getParent(), InsertBefore);
621 Value *
const Lhs = Builder.Insert(FirstCmp.Lhs().GEP->clone());
622 Value *
const Rhs = Builder.Insert(FirstCmp.Rhs().GEP->clone());
624 Value *IsEqual =
nullptr;
627 if (Comparisons.
size() == 1) {
629 Value *
const LhsLoad =
630 Builder.CreateLoad(FirstCmp.Lhs().LoadI->getType(), Lhs);
631 Value *
const RhsLoad =
632 Builder.CreateLoad(FirstCmp.Rhs().LoadI->getType(), Rhs);
634 IsEqual = Builder.CreateICmpEQ(LhsLoad, RhsLoad);
641 [](
const BCECmpBlock &
B) {
return B.RequireSplit; });
642 if (ToSplit != Comparisons.
end()) {
644 ToSplit->split(BB, AA);
647 const unsigned TotalSizeBits = std::accumulate(
648 Comparisons.
begin(), Comparisons.
end(), 0u,
649 [](
int Size,
const BCECmpBlock &
C) {
return Size +
C.SizeBits(); });
657 IsEqual = Builder.CreateICmpEQ(
663 if (NextCmpBlock == PhiBB) {
665 Builder.CreateBr(PhiBB);
670 Builder.CreateCondBr(IsEqual, NextCmpBlock, PhiBB);
680 assert(Comparisons_.size() >= 2 &&
"simplifying trivial BCECmpChain");
683 const auto AtLeastOneMerged = [
this]() {
684 for (
size_t I = 1;
I < Comparisons_.size(); ++
I) {
685 if (IsContiguous(Comparisons_[
I - 1], Comparisons_[
I]))
690 if (!AtLeastOneMerged())
693 LLVM_DEBUG(
dbgs() <<
"Simplifying comparison chain starting at block " 694 << EntryBlock_->getName() <<
"\n");
698 const auto mergeRange = [
this, &TLI, &AA, &DTU](
int I,
int Num,
701 return mergeComparisons(
makeArrayRef(Comparisons_).slice(I, Num),
702 InsertBefore, Next, Phi_, TLI, AA, DTU);
706 for (
int I = static_cast<int>(Comparisons_.size()) - 2; I >= 0; --
I) {
707 if (IsContiguous(Comparisons_[I], Comparisons_[I + 1])) {
708 LLVM_DEBUG(
dbgs() <<
"Merging block " << Comparisons_[I].BB->getName()
709 <<
" into " << Comparisons_[I + 1].BB->getName()
713 NextCmpBlock = mergeRange(I + 1, NumMerged, NextCmpBlock, NextCmpBlock);
720 NextCmpBlock = mergeRange(0, NumMerged, EntryBlock_, NextCmpBlock);
736 const bool ChainEntryIsFnEntry =
737 (EntryBlock_ == &EntryBlock_->getParent()->getEntryBlock());
738 if (ChainEntryIsFnEntry && DTU.
hasDomTree()) {
740 << EntryBlock_->getName() <<
" to " 741 << NextCmpBlock->
getName() <<
"\n");
745 EntryBlock_ =
nullptr;
749 for (
auto &Cmp : Comparisons_) {
750 LLVM_DEBUG(
dbgs() <<
"Deleting merged block " << Cmp.BB->getName() <<
"\n");
755 Comparisons_.clear();
759 std::vector<BasicBlock *> getOrderedBlocks(
PHINode &Phi,
763 std::vector<BasicBlock *> Blocks(NumBlocks);
764 assert(LastBlock &&
"invalid last block");
766 for (
int BlockIndex = NumBlocks - 1; BlockIndex > 0; --BlockIndex) {
771 <<
" has its address taken\n");
774 Blocks[BlockIndex] = CurBlock;
776 if (!SinglePredecessor) {
779 <<
" has two or more predecessors\n");
785 <<
" does not link back to the phi\n");
788 CurBlock = SinglePredecessor;
790 Blocks[0] = CurBlock;
835 <<
"skip: non-constant value not from cmp or not from last block.\n");
852 if (Blocks.empty())
return false;
853 BCECmpChain CmpChain(Blocks, Phi, AA);
855 if (CmpChain.size() < 2) {
860 return CmpChain.simplify(TLI, AA, DTU);
874 if (!TLI.
has(LibFunc_memcmp))
880 bool MadeChange =
false;
882 for (
auto BBIt = ++F.
begin(); BBIt != F.
end(); ++BBIt) {
884 if (
auto *
const Phi = dyn_cast<PHINode>(&*BBIt->begin()))
885 MadeChange |= processPhi(*Phi, TLI, AA, DTU);
900 if (skipFunction(F))
return false;
901 const auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
902 const auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
905 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
906 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
907 return runImpl(F, TLI, TTI, AA, DTWP ? &DTWP->getDomTree() :
nullptr);
924 "Merge contiguous icmps into a memcmp",
false,
false)
939 const bool MadeChanges =
runImpl(F, TLI, TTI, AA, DT);
Legacy wrapper pass to provide the GlobalsAAResult object.
Pass interface - Implemented by all 'passes'.
void DeleteDeadBlocks(ArrayRef< BasicBlock *> BBs, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified blocks from BB.
static ConstantInt * getFalse(LLVMContext &Context)
static bool runImpl(Function &F, TargetLibraryInfo &TLI, DominatorTree &DT)
This is the entry point for all transforms.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
This class represents lattice values for constants.
This is the interface for a simple mod/ref and alias analysis over globals.
bool hasOptSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
Implements a dense probed hash-table based set.
void push_back(const T &Elt)
bool slt(const APInt &RHS) const
Signed less than comparison.
DominatorTree & getDomTree()
Flush DomTree updates and return DomTree.
Analysis pass providing the TargetTransformInfo.
static void dump(StringRef Title, SpillInfo const &Spills)
Analysis pass which computes a DominatorTree.
An instruction for reading from memory.
void initializeMergeICmpsLegacyPassPass(PassRegistry &)
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
void reserve(size_type N)
LLVMContext & getContext() const
Get the context in which this basic block lives.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
iterator begin()
Instruction iterator methods.
Pass * createMergeICmpsLegacyPass()
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
static constexpr UpdateKind Delete
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
Type * getType() const
All values are typed, get the type of this value.
bool has(LibFunc F) const
Tests whether a library function is available.
const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
An instruction for storing to memory.
DomTreeNodeBase< NodeT > * setNewRoot(NodeT *BB)
Add a new node to the forward dominator tree and make it a new root.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Value * getOperand(unsigned i) const
void replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
void append(in_iter S, in_iter E)
Append from an iterator pair.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
static bool runOnFunction(Function &F, bool PostInlining)
static MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
A set of analyses that are preserved following a run of a transformation pass.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
static constexpr UpdateKind Insert
LLVM Basic Block Representation.
This is an important class for using LLVM in a threaded context.
Conditional or Unconditional Branch instruction.
size_t size() const
size - Get the array size.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Value * getIncomingValueForBlock(const BasicBlock *BB) const
A manager for alias analyses.
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Represent the analysis usage information of a pass.
This instruction compares its operands according to the predicate given to the constructor.
Analysis pass providing a never-invalidated alias analysis result.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
FunctionPass class - This class is used to implement most global optimizations.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
bool pred_empty(const BasicBlock *BB)
auto find_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly...
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
void sort(IteratorTy Start, IteratorTy End)
Representation for a specific memory location.
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc.
This is the shared class of boolean and integer constants.
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
void applyUpdates(ArrayRef< DominatorTree::UpdateType > Updates)
Submit updates to all available trees.
bool isDereferenceablePointer(const Value *V, Type *Ty, const DataLayout &DL, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr)
Return true if this is always a dereferenceable pointer.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Provides information about what library functions are available for the current target.
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Class for arbitrary precision integers.
LLVM_NODISCARD bool isModSet(const ModRefInfo MRI)
Predicate getPredicate() const
Return the predicate for this instruction.
Merge contiguous icmps into a memcmp
static IntegerType * getInt32Ty(LLVMContext &C)
StringRef getName() const
Return a constant reference to the value's name.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
const Function * getParent() const
Return the enclosing method, or null if none.
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
void preserve()
Mark an analysis as preserved.
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
INITIALIZE_PASS_BEGIN(MergeICmpsLegacyPass, "mergeicmps", "Merge contiguous icmps into a memcmp", false, false) INITIALIZE_PASS_END(MergeICmpsLegacyPass
Analysis pass providing the TargetLibraryInfo.
Value * emitMemCmp(Value *Ptr1, Value *Ptr2, Value *Len, IRBuilder<> &B, const DataLayout &DL, const TargetLibraryInfo *TLI)
Emit a call to the memcmp function.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool operator<(int64_t V1, const APSInt &V2)
LLVM Value Representation.
static const Function * getParent(const Value *V)
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
bool hasOneUse() const
Return true if there is exactly one user of this value.
StringRef - Represent a constant reference to a string, i.e.
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
bool hasDomTree() const
Returns true if it holds a DominatorTree.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc)
getModRefInfo (for call sites) - Return information about whether a particular call site modifies or ...
bool empty() const
empty - Check if the array is empty.
const BasicBlock * getParent() const
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.