42 #define DEBUG_TYPE "mergeicmps" 46 BCEAtom() :
GEP(
nullptr), LoadI(
nullptr),
Offset() {}
48 const Value *
Base()
const {
return GEP ?
GEP->getPointerOperand() :
nullptr; }
52 assert(O.Base() &&
"invalid atom");
58 const int NameCmp =
Base()->getName().compare(O.Base()->getName());
60 if (
Base() == O.Base()) {
61 return Offset.slt(O.Offset);
63 return Base() < O.Base();
76 BCEAtom visitICmpLoadOperand(
Value *
const Val) {
78 if (
auto *
const LoadI = dyn_cast<LoadInst>(Val)) {
80 if (LoadI->isUsedOutsideOfBlock(LoadI->getParent())) {
84 if (LoadI->isVolatile()) {
88 Value *
const Addr = LoadI->getOperand(0);
89 if (
auto *
const GEP = dyn_cast<GetElementPtrInst>(Addr)) {
91 if (LoadI->isUsedOutsideOfBlock(LoadI->getParent())) {
95 const auto &DL =
GEP->getModule()->getDataLayout();
102 Result.Offset =
APInt(DL.getPointerTypeSizeInBits(
GEP->getType()), 0);
103 if (
GEP->accumulateConstantOffset(DL, Result.Offset)) {
105 Result.LoadI = LoadI;
125 BCECmpBlock(BCEAtom L, BCEAtom R,
int SizeBits)
126 : Lhs_(L), Rhs_(R), SizeBits_(SizeBits) {
130 bool IsValid()
const {
131 return Lhs_.Base() !=
nullptr && Rhs_.Base() !=
nullptr;
136 void AssertConsistent()
const {
144 const BCEAtom &Lhs()
const {
return Lhs_; }
145 const BCEAtom &Rhs()
const {
return Rhs_; }
146 int SizeBits()
const {
return SizeBits_; }
149 bool doesOtherWork()
const;
153 bool canSplit()
const;
173 bool RequireSplit =
false;
181 bool BCECmpBlock::canSinkBCECmpInst(
const Instruction *Inst,
190 for (
auto BI : BlockInsts) {
199 {Lhs_.GEP, Rhs_.GEP, Lhs_.LoadI, Rhs_.LoadI, CmpI, BranchI});
202 if (BlockInsts.
count(&Inst))
204 assert(canSinkBCECmpInst(&Inst, BlockInsts) &&
"Split unsplittable block");
207 OtherInsts.push_back(&Inst);
216 bool BCECmpBlock::canSplit()
const {
218 {Lhs_.GEP, Rhs_.GEP, Lhs_.LoadI, Rhs_.LoadI, CmpI, BranchI});
220 if (!BlockInsts.
count(&Inst)) {
221 if (!canSinkBCECmpInst(&Inst, BlockInsts))
228 bool BCECmpBlock::doesOtherWork()
const {
232 {Lhs_.GEP, Rhs_.GEP, Lhs_.LoadI, Rhs_.LoadI, CmpI, BranchI});
238 if (!BlockInsts.
count(&Inst))
246 BCECmpBlock visitICmp(
const ICmpInst *
const CmpI,
261 auto Lhs = visitICmpLoadOperand(CmpI->
getOperand(0));
262 if (!Lhs.Base())
return {};
263 auto Rhs = visitICmpLoadOperand(CmpI->
getOperand(1));
264 if (!Rhs.Base())
return {};
265 return BCECmpBlock(std::move(Lhs), std::move(Rhs),
275 if (Block->
empty())
return {};
277 if (!BranchI)
return {};
279 if (BranchI->isUnconditional()) {
285 if (!CmpI)
return {};
296 if (!Const->isZero())
return {};
299 if (!CmpI)
return {};
301 assert(BranchI->getNumSuccessors() == 2 &&
"expecting a cond branch");
302 BasicBlock *
const FalseBlock = BranchI->getSuccessor(1);
312 static inline void enqueueBlock(std::vector<BCECmpBlock> &Comparisons,
313 BCECmpBlock &Comparison) {
315 <<
"': Found cmp of " << Comparison.SizeBits()
316 <<
" bits between " << Comparison.Lhs().Base() <<
" + " 317 << Comparison.Lhs().Offset <<
" and " 318 << Comparison.Rhs().Base() <<
" + " 319 << Comparison.Rhs().Offset <<
"\n");
321 Comparisons.push_back(Comparison);
327 BCECmpChain(
const std::vector<BasicBlock *> &Blocks,
PHINode &Phi);
329 int size()
const {
return Comparisons_.size(); }
331 #ifdef MERGEICMPS_DOT_ON 333 #endif // MERGEICMPS_DOT_ON 338 static bool IsContiguous(
const BCECmpBlock &First,
339 const BCECmpBlock &Second) {
340 return First.Lhs().Base() == Second.Lhs().Base() &&
341 First.Rhs().Base() == Second.Rhs().Base() &&
342 First.Lhs().Offset + First.SizeBits() / 8 == Second.Lhs().Offset &&
343 First.Rhs().Offset + First.SizeBits() / 8 == Second.Rhs().Offset;
354 std::vector<BCECmpBlock> Comparisons_;
359 BCECmpChain::BCECmpChain(
const std::vector<BasicBlock *> &Blocks,
PHINode &Phi)
361 assert(!Blocks.empty() &&
"a chain should have at least one block");
363 std::vector<BCECmpBlock> Comparisons;
364 for (
size_t BlockIdx = 0; BlockIdx < Blocks.size(); ++BlockIdx) {
366 assert(Block &&
"invalid block");
369 Comparison.BB = Block;
370 if (!Comparison.IsValid()) {
371 LLVM_DEBUG(
dbgs() <<
"chain with invalid BCECmpBlock, no merge.\n");
374 if (Comparison.doesOtherWork()) {
376 <<
"' does extra work besides compare\n");
377 if (Comparisons.empty()) {
391 if (Comparison.canSplit()) {
393 <<
"Split initial block '" << Comparison.BB->getName()
394 <<
"' that does extra work besides compare\n");
395 Comparison.RequireSplit =
true;
396 enqueueBlock(Comparisons, Comparison);
399 <<
"ignoring initial block '" << Comparison.BB->getName()
400 <<
"' that does extra work besides compare\n");
429 enqueueBlock(Comparisons, Comparison);
433 if (Comparisons.empty()) {
434 LLVM_DEBUG(
dbgs() <<
"chain with no BCE basic blocks, no merge\n");
437 EntryBlock_ = Comparisons[0].BB;
438 Comparisons_ = std::move(Comparisons);
439 #ifdef MERGEICMPS_DOT_ON 440 errs() <<
"BEFORE REORDERING:\n\n";
442 #endif // MERGEICMPS_DOT_ON 445 llvm::sort(Comparisons_.begin(), Comparisons_.end(),
446 [](
const BCECmpBlock &a,
const BCECmpBlock &b) {
447 return a.Lhs() < b.Lhs();
449 #ifdef MERGEICMPS_DOT_ON 450 errs() <<
"AFTER REORDERING:\n\n";
452 #endif // MERGEICMPS_DOT_ON 455 #ifdef MERGEICMPS_DOT_ON 457 errs() <<
"digraph dag {\n";
458 errs() <<
" graph [bgcolor=transparent];\n";
459 errs() <<
" node [color=black,style=filled,fillcolor=lightyellow];\n";
460 errs() <<
" edge [color=black];\n";
461 for (
size_t I = 0;
I < Comparisons_.size(); ++
I) {
462 const auto &Comparison = Comparisons_[
I];
463 errs() <<
" \"" <<
I <<
"\" [label=\"%" 464 << Comparison.Lhs().Base()->getName() <<
" + " 465 << Comparison.Lhs().Offset <<
" == %" 466 << Comparison.Rhs().Base()->getName() <<
" + " 467 << Comparison.Rhs().Offset <<
" (" << (Comparison.SizeBits() / 8)
469 const Value *
const Val = Phi_.getIncomingValueForBlock(Comparison.BB);
470 if (
I > 0)
errs() <<
" \"" << (
I - 1) <<
"\" -> \"" <<
I <<
"\";\n";
471 errs() <<
" \"" <<
I <<
"\" -> \"Phi\" [label=\"" << *Val <<
"\"];\n";
473 errs() <<
" \"Phi\" [label=\"Phi\"];\n";
476 #endif // MERGEICMPS_DOT_ON 482 bool AtLeastOneMerged =
false;
483 for (
size_t I = 1;
I < Comparisons_.size(); ++
I) {
484 if (IsContiguous(Comparisons_[
I - 1], Comparisons_[
I])) {
485 AtLeastOneMerged =
true;
489 if (!AtLeastOneMerged)
return false;
494 for (
const auto &Comparison : Comparisons_) {
495 Phi_.removeIncomingValue(Comparison.BB,
false);
501 for (
size_t I = 1;
I < Comparisons_.size(); ++
I) {
502 if (Entry == Comparisons_[
I].BB) {
512 if (EntryBlock_ != Comparisons_[0].BB) {
513 EntryBlock_->replaceAllUsesWith(Comparisons_[0].BB);
514 EntryBlock_ = Comparisons_[0].BB;
519 for (
size_t I = 1;
I < Comparisons_.size(); ++
I) {
520 if (IsContiguous(Comparisons_[
I - 1], Comparisons_[
I])) {
525 makeArrayRef(Comparisons_).slice(I - NumMerged, NumMerged),
526 Comparisons_[I].BB, Phi_, TLI);
531 .slice(Comparisons_.size() - NumMerged, NumMerged),
542 const auto &FirstComparison = *Comparisons.
begin();
546 if (Comparisons.
size() >= 2) {
551 [](
const BCECmpBlock &
B) {
return B.RequireSplit; });
552 if (
C != Comparisons.
end())
553 C->split(EntryBlock_);
556 const auto TotalSize =
557 std::accumulate(Comparisons.
begin(), Comparisons.
end(), 0,
558 [](
int Size,
const BCECmpBlock &
C) {
559 return Size +
C.SizeBits();
568 FirstComparison.BranchI->eraseFromParent();
569 FirstComparison.CmpI->eraseFromParent();
570 FirstComparison.Lhs().LoadI->eraseFromParent();
571 FirstComparison.Rhs().LoadI->eraseFromParent();
576 FirstComparison.Lhs().GEP, FirstComparison.Rhs().GEP,
592 for (
size_t I = 1;
I < Comparisons.
size(); ++
I) {
602 if (FirstComparison.BranchI->isConditional()) {
607 FirstComparison.BranchI->setSuccessor(0, NextBBInChain);
612 FirstComparison.BranchI->eraseFromParent();
614 Builder.
CreateCondBr(FirstComparison.CmpI, NextBBInChain,
619 if (FirstComparison.BranchI->isConditional()) {
622 FirstComparison.BranchI->eraseFromParent();
634 std::vector<BasicBlock *> getOrderedBlocks(
PHINode &Phi,
638 std::vector<BasicBlock *> Blocks(NumBlocks);
639 assert(LastBlock &&
"invalid last block");
641 for (
int BlockIndex = NumBlocks - 1; BlockIndex > 0; --BlockIndex) {
646 <<
" has its address taken\n");
649 Blocks[BlockIndex] = CurBlock;
651 if (!SinglePredecessor) {
654 <<
" has two or more predecessors\n");
660 <<
" does not link back to the phi\n");
663 CurBlock = SinglePredecessor;
665 Blocks[0] = CurBlock;
709 <<
"skip: non-constant value not from cmp or not from last block.\n");
726 if (Blocks.empty())
return false;
727 BCECmpChain CmpChain(Blocks, Phi);
729 if (CmpChain.size() < 2) {
734 return CmpChain.simplify(TLI);
746 if (skipFunction(F))
return false;
747 const auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
748 const auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
749 auto PA =
runImpl(F, &TLI, &TTI);
750 return !PA.areAllPreserved();
772 if (!TLI->
has(LibFunc_memcmp))
775 bool MadeChange =
false;
777 for (
auto BBIt = ++F.
begin(); BBIt != F.
end(); ++BBIt) {
779 if (
auto *
const Phi = dyn_cast<PHINode>(&*BBIt->begin()))
780 MadeChange |= processPhi(*Phi, TLI);
791 "Merge contiguous icmps into a memcmp",
false,
false)
Pass interface - Implemented by all 'passes'.
static ConstantInt * getFalse(LLVMContext &Context)
BranchInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
static bool runImpl(Function &F, TargetLibraryInfo &TLI, DominatorTree &DT)
This is the entry point for all transforms.
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...
Compute iterated dominance frontiers using a linear time algorithm.
Implements a dense probed hash-table based set.
static void dump(StringRef Title, SpillInfo const &Spills)
static std::pair< StringRef, StringRef > split(StringRef Str, char Separator)
Checked version of split, to ensure mandatory subparts.
An instruction for reading from memory.
LLVMContext & getContext() const
Get the context in which this basic block lives.
iterator begin()
Instruction iterator methods.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
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.
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Pass * createMergeICmpsPass()
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)...
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Value * getOperand(unsigned i) const
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
const BasicBlock & getEntryBlock() const
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
static bool runOnFunction(Function &F, bool PostInlining)
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.
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.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
Represent the analysis usage information of a pass.
This instruction compares its operands according to the predicate given to the constructor.
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.
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
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)
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.
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type...
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.
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
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.
bool isDereferenceablePointer(const Value *V, const DataLayout &DL, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr)
Return true if this is always a dereferenceable pointer.
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.
SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
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.
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
BranchInst * CreateBr(BasicBlock *Dest)
Create an unconditional 'br label X' instruction.
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.
INITIALIZE_PASS_BEGIN(MergeICmps, "mergeicmps", "Merge contiguous icmps into a memcmp", false, false) INITIALIZE_PASS_END(MergeICmps
void initializeMergeICmpsPass(PassRegistry &)
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
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.