101 #define DEBUG_TYPE "loop-idiom" 103 STATISTIC(NumMemSet,
"Number of memset's formed from loop stores");
104 STATISTIC(NumMemCpy,
"Number of memcpy's formed from loop load+stores");
107 "use-lir-code-size-heurs",
108 cl::desc(
"Use loop idiom recognition code size heuristics when compiling" 114 class LoopIdiomRecognize {
115 Loop *CurLoop =
nullptr;
123 bool ApplyCodeSizeHeuristics;
131 : AA(AA), DT(DT), LI(LI), SE(SE), TLI(TLI), TTI(TTI), DL(DL) {}
133 bool runOnLoop(
Loop *L);
139 StoreListMap StoreRefsForMemset;
140 StoreListMap StoreRefsForMemsetPattern;
141 StoreList StoreRefsForMemcpy;
143 bool HasMemsetPattern;
147 enum LegalStoreKind {
152 UnorderedAtomicMemcpy,
160 bool runOnCountableLoop();
170 bool processLoopStridedStore(
Value *DestPtr,
unsigned StoreSize,
171 unsigned StoreAlignment,
Value *StoredVal,
175 bool NegStride,
bool IsLoopMemset =
false);
177 bool avoidLIRForMultiBlockLoop(
bool IsMemset =
false,
178 bool IsLoopMemset =
false);
184 bool runOnNoncountableLoop();
186 bool recognizePopcount();
189 bool recognizeAndInsertCTLZ();
193 bool IsCntPhiUsedOutsideLoop);
198 class LoopIdiomRecognizeLegacyPass :
public LoopPass {
202 explicit LoopIdiomRecognizeLegacyPass() :
LoopPass(ID) {
211 AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
212 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
213 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
214 ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
216 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
218 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
222 LoopIdiomRecognize LIR(AA, DT, LI, SE, TLI, TTI, DL);
223 return LIR.runOnLoop(L);
244 LoopIdiomRecognize LIR(&AR.
AA, &AR.
DT, &AR.
LI, &AR.
SE, &AR.
TLI, &AR.
TTI, DL);
245 if (!LIR.runOnLoop(&L))
252 "Recognize loop idioms",
false,
false)
272 bool LoopIdiomRecognize::runOnLoop(
Loop *L) {
281 if (Name ==
"memset" || Name ==
"memcpy")
285 ApplyCodeSizeHeuristics =
288 HasMemset = TLI->
has(LibFunc_memset);
289 HasMemsetPattern = TLI->
has(LibFunc_memset_pattern16);
290 HasMemcpy = TLI->
has(LibFunc_memcpy);
292 if (HasMemset || HasMemsetPattern || HasMemcpy)
294 return runOnCountableLoop();
296 return runOnNoncountableLoop();
299 bool LoopIdiomRecognize::runOnCountableLoop() {
301 assert(!isa<SCEVCouldNotCompute>(BECount) &&
302 "runOnCountableLoop() called on a loop without a predictable" 303 "backedge-taken count");
307 if (
const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
308 if (BECst->getAPInt() == 0)
312 CurLoop->getUniqueExitBlocks(ExitBlocks);
315 << CurLoop->getHeader()->getParent()->getName()
316 <<
"] Loop %" << CurLoop->getHeader()->getName() <<
"\n");
318 bool MadeChange =
false;
328 for (
auto *BB : CurLoop->getBlocks()) {
333 MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks);
359 if (Size == 0 || (Size & 7) || (Size & (Size - 1)))
379 unsigned ArraySize = 16 /
Size;
384 LoopIdiomRecognize::LegalStoreKind
406 uint64_t SizeInBits = DL->getTypeSizeInBits(StoredVal->
getType());
407 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
419 if (!isa<SCEVConstant>(StoreEv->
getOperand(1)))
436 if (!UnorderedAtomic && HasMemset && SplatValue &&
439 CurLoop->isLoopInvariant(SplatValue)) {
441 return LegalStoreKind::Memset;
442 }
else if (!UnorderedAtomic && HasMemsetPattern &&
447 return LegalStoreKind::MemsetPattern;
456 if (StoreSize != Stride && StoreSize != -Stride)
482 UnorderedAtomic = UnorderedAtomic || LI->
isAtomic();
483 return UnorderedAtomic ? LegalStoreKind::UnorderedAtomicMemcpy
484 : LegalStoreKind::Memcpy;
490 void LoopIdiomRecognize::collectStores(
BasicBlock *BB) {
491 StoreRefsForMemset.clear();
492 StoreRefsForMemsetPattern.clear();
493 StoreRefsForMemcpy.clear();
500 switch (isLegalStore(SI)) {
504 case LegalStoreKind::Memset: {
507 StoreRefsForMemset[Ptr].push_back(SI);
509 case LegalStoreKind::MemsetPattern: {
512 StoreRefsForMemsetPattern[Ptr].push_back(SI);
514 case LegalStoreKind::Memcpy:
515 case LegalStoreKind::UnorderedAtomicMemcpy:
516 StoreRefsForMemcpy.push_back(SI);
519 assert(
false &&
"unhandled return value");
528 bool LoopIdiomRecognize::runOnLoopBlock(
534 for (
unsigned i = 0, e = ExitBlocks.
size(); i != e; ++i)
538 bool MadeChange =
false;
545 for (
auto &SL : StoreRefsForMemset)
546 MadeChange |= processLoopStores(SL.second, BECount,
true);
548 for (
auto &SL : StoreRefsForMemsetPattern)
549 MadeChange |= processLoopStores(SL.second, BECount,
false);
552 for (
auto &SI : StoreRefsForMemcpy)
553 MadeChange |= processLoopStoreOfLoopLoad(SI, BECount);
558 if (
MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) {
560 if (!processLoopMemSet(MSI, BECount))
586 for (
unsigned i = 0, e = SL.
size(); i < e; ++i) {
587 assert(SL[i]->
isSimple() &&
"Expected only non-volatile stores.");
589 Value *FirstStoredVal = SL[i]->getValueOperand();
590 Value *FirstStorePtr = SL[i]->getPointerOperand();
592 cast<SCEVAddRecExpr>(SE->
getSCEV(FirstStorePtr));
594 unsigned FirstStoreSize = DL->getTypeStoreSize(SL[i]->getValueOperand()->
getType());
597 if (FirstStride == FirstStoreSize || -FirstStride == FirstStoreSize) {
602 Value *FirstSplatValue =
nullptr;
603 Constant *FirstPatternValue =
nullptr;
610 assert((FirstSplatValue || FirstPatternValue) &&
611 "Expected either splat value or pattern value.");
619 for (j = i + 1; j < e; ++j)
621 for (j = i; j > 0; --j)
624 for (
auto &k : IndexQueue) {
625 assert(SL[k]->
isSimple() &&
"Expected only non-volatile stores.");
626 Value *SecondStorePtr = SL[k]->getPointerOperand();
628 cast<SCEVAddRecExpr>(SE->
getSCEV(SecondStorePtr));
631 if (FirstStride != SecondStride)
634 Value *SecondStoredVal = SL[k]->getValueOperand();
635 Value *SecondSplatValue =
nullptr;
636 Constant *SecondPatternValue =
nullptr;
643 assert((SecondSplatValue || SecondPatternValue) &&
644 "Expected either splat value or pattern value.");
648 if (FirstSplatValue != SecondSplatValue)
651 if (FirstPatternValue != SecondPatternValue)
656 ConsecutiveChain[SL[i]] = SL[k];
665 bool Changed =
false;
670 if (Tails.
count(*it))
679 unsigned StoreSize = 0;
683 if (TransformedStores.
count(I))
689 I = ConsecutiveChain[
I];
699 if (StoreSize != Stride && StoreSize != -Stride)
702 bool NegStride = StoreSize == -Stride;
704 if (processLoopStridedStore(StorePtr, StoreSize, HeadStore->
getAlignment(),
705 StoredVal, HeadStore, AdjacentStores, StoreEv,
706 BECount, NegStride)) {
707 TransformedStores.
insert(AdjacentStores.begin(), AdjacentStores.end());
716 bool LoopIdiomRecognize::processLoopMemSet(
MemSetInst *MSI,
717 const SCEV *BECount) {
736 uint64_t SizeInBytes = cast<ConstantInt>(MSI->
getLength())->getZExtValue();
737 if ((SizeInBytes >> 32) != 0)
747 if (SizeInBytes != Stride && SizeInBytes != -Stride)
753 if (!SplatValue || !CurLoop->isLoopInvariant(SplatValue))
758 bool NegStride = SizeInBytes == -Stride;
759 return processLoopStridedStore(Pointer, (
unsigned)SizeInBytes,
761 Ev, BECount, NegStride,
true);
769 const SCEV *BECount,
unsigned StoreSize,
779 if (
const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
780 AccessSize = (BECst->getValue()->getZExtValue() + 1) * StoreSize;
791 if (IgnoredStores.
count(&
I) == 0 &&
803 Type *IntPtr,
unsigned StoreSize,
817 unsigned StoreSize,
Loop *CurLoop,
819 const SCEV *NumBytesS;
840 if (StoreSize != 1) {
849 bool LoopIdiomRecognize::processLoopStridedStore(
850 Value *DestPtr,
unsigned StoreSize,
unsigned StoreAlignment,
853 const SCEV *BECount,
bool NegStride,
bool IsLoopMemset) {
860 assert((SplatValue || PatternValue) &&
861 "Expected either splat value or pattern value.");
867 BasicBlock *Preheader = CurLoop->getLoopPreheader();
872 Type *IntPtr = Builder.getIntPtrTy(*DL, DestAS);
890 Expander.expandCodeFor(Start, DestInt8PtrTy, Preheader->
getTerminator());
892 StoreSize, *AA, Stores)) {
899 if (avoidLIRForMultiBlockLoop(
true, IsLoopMemset))
904 const SCEV *NumBytesS =
905 getNumBytes(BECount, IntPtr, StoreSize, CurLoop, DL, SE);
913 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->
getTerminator());
918 Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, StoreAlignment);
921 Type *Int8PtrTy = DestInt8PtrTy;
926 Int8PtrTy, Int8PtrTy, IntPtr);
933 PatternValue,
".memset_pattern");
935 GV->setAlignment(16);
937 NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes});
941 <<
" from store to: " << *Ev <<
" at: " << *TheStore
947 for (
auto *
I : Stores)
956 bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(
StoreInst *SI,
957 const SCEV *BECount) {
964 bool NegStride = StoreSize == -Stride;
979 BasicBlock *Preheader = CurLoop->getLoopPreheader();
985 Type *IntPtrTy = Builder.getIntPtrTy(*DL, StrAS);
997 Value *StoreBasePtr = Expander.expandCodeFor(
998 StrStart, Builder.getInt8PtrTy(StrAS), Preheader->
getTerminator());
1003 StoreSize, *AA, Stores)) {
1010 const SCEV *LdStart = LoadEv->getStart();
1019 Value *LoadBasePtr = Expander.expandCodeFor(
1020 LdStart, Builder.getInt8PtrTy(LdAS), Preheader->
getTerminator());
1023 StoreSize, *AA, Stores)) {
1031 if (avoidLIRForMultiBlockLoop())
1036 const SCEV *NumBytesS =
1037 getNumBytes(BECount, IntPtrTy, StoreSize, CurLoop, DL, SE);
1040 Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->
getTerminator());
1047 NewCall = Builder.CreateMemCpy(StoreBasePtr, SI->
getAlignment(),
1053 if (Align < StoreSize)
1066 NewCall = Builder.CreateElementUnorderedAtomicMemCpy(
1068 NumBytes, StoreSize);
1073 <<
" from load ptr=" << *LoadEv <<
" at: " << *LI <<
"\n" 1074 <<
" from store ptr=" << *StoreEv <<
" at: " << *SI
1087 bool LoopIdiomRecognize::avoidLIRForMultiBlockLoop(
bool IsMemset,
1088 bool IsLoopMemset) {
1089 if (ApplyCodeSizeHeuristics && CurLoop->getNumBlocks() > 1) {
1090 if (!CurLoop->getParentLoop() && (!IsMemset || !IsLoopMemset)) {
1091 LLVM_DEBUG(
dbgs() <<
" " << CurLoop->getHeader()->getParent()->getName()
1092 <<
" : LIR " << (IsMemset ?
"Memset" :
"Memcpy")
1093 <<
" avoided: multi-block top-level loop\n");
1101 bool LoopIdiomRecognize::runOnNoncountableLoop() {
1102 return recognizePopcount() || recognizeAndInsertCTLZ();
1119 if (!CmpZero || !CmpZero->
isZero())
1135 if (PhiX && PhiX->getParent() == LoopEntry &&
1136 (PhiX->getOperand(0) == DefX || PhiX->
getOperand(1) == DefX))
1172 Value *VarX1, *VarX0;
1175 DefX2 = CountInst =
nullptr;
1176 VarX1 = VarX0 =
nullptr;
1177 PhiX = CountPhi =
nullptr;
1183 dyn_cast<BranchInst>(LoopEntry->
getTerminator()), LoopEntry))
1184 DefX2 = dyn_cast<Instruction>(
T);
1191 if (!DefX2 || DefX2->
getOpcode() != Instruction::And)
1196 if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->
getOperand(0))))
1202 if (!SubOneOp || SubOneOp->
getOperand(0) != VarX1)
1221 CountInst =
nullptr;
1223 IterE = LoopEntry->
end();
1224 Iter != IterE; Iter++) {
1230 if (!Inc || !Inc->
isOne())
1238 bool LiveOutLoop =
false;
1240 if ((cast<Instruction>(U))->getParent() != LoopEntry) {
1265 CntInst = CountInst;
1304 Value *VarX =
nullptr;
1314 dyn_cast<BranchInst>(LoopEntry->
getTerminator()), LoopEntry))
1315 DefX = dyn_cast<Instruction>(
T);
1320 if (!DefX || (DefX->
getOpcode() != Instruction::AShr &&
1321 DefX->
getOpcode() != Instruction::LShr))
1324 if (!Shft || !Shft->
isOne())
1340 IterE = LoopEntry->
end();
1341 Iter != IterE; Iter++) {
1347 if (!Inc || !Inc->
isOne())
1367 bool LoopIdiomRecognize::recognizeAndInsertCTLZ() {
1369 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
1377 bool IsCntPhiUsedOutsideLoop =
false;
1379 if (!CurLoop->contains(cast<Instruction>(U))) {
1380 IsCntPhiUsedOutsideLoop =
true;
1383 bool IsCntInstUsedOutsideLoop =
false;
1385 if (!CurLoop->contains(cast<Instruction>(U))) {
1386 IsCntInstUsedOutsideLoop =
true;
1391 if (IsCntInstUsedOutsideLoop && IsCntPhiUsedOutsideLoop)
1397 bool ZeroCheck =
false;
1400 BasicBlock *PH = CurLoop->getLoopPreheader();
1412 if (!IsCntPhiUsedOutsideLoop) {
1436 if (CurLoop->getHeader()->size() != 6 &&
1441 transformLoopToCountable(PH, CntInst, CntPhi, InitX, DefX,
1443 IsCntPhiUsedOutsideLoop);
1451 bool LoopIdiomRecognize::recognizePopcount() {
1461 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
1464 BasicBlock *LoopBody = *(CurLoop->block_begin());
1465 if (LoopBody->
size() >= 20) {
1471 BasicBlock *PH = CurLoop->getLoopPreheader();
1475 if (!EntryBI || EntryBI->isConditional())
1484 if (!PreCondBI || PreCondBI->isUnconditional())
1493 transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val);
1499 Value *Ops[] = {Val};
1511 const DebugLoc &DL,
bool ZeroCheck) {
1554 void LoopIdiomRecognize::transformLoopToCountable(
1557 bool IsCntPhiUsedOutsideLoop) {
1565 Builder.SetCurrentDebugLocation(DL);
1566 Value *
CTLZ, *Count, *CountPrev, *NewCount, *InitXNext;
1568 if (IsCntPhiUsedOutsideLoop) {
1569 if (DefX->
getOpcode() == Instruction::AShr)
1572 else if (DefX->
getOpcode() == Instruction::LShr)
1580 Count = Builder.CreateSub(
1584 if (IsCntPhiUsedOutsideLoop) {
1586 Count = Builder.CreateAdd(
1590 if (IsCntPhiUsedOutsideLoop)
1591 NewCount = Builder.CreateZExtOrTrunc(CountPrev,
1592 cast<IntegerType>(CntInst->
getType()));
1594 NewCount = Builder.CreateZExtOrTrunc(Count,
1595 cast<IntegerType>(CntInst->
getType()));
1600 if (!InitConst || !InitConst->
isZero())
1601 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
1611 BasicBlock *Body = *(CurLoop->block_begin());
1613 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
1618 Builder.SetInsertPoint(LbCond);
1621 "tcdec",
false,
true));
1628 LbCond->setPredicate(Pred);
1629 LbCond->setOperand(0, TcDec);
1635 if (IsCntPhiUsedOutsideLoop)
1645 void LoopIdiomRecognize::transformLoopToPopcount(
BasicBlock *PreCondBB,
1648 BasicBlock *PreHead = CurLoop->getLoopPreheader();
1649 auto *PreCondBr = cast<BranchInst>(PreCondBB->
getTerminator());
1658 Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
1661 NewCount = PopCntZext =
1664 if (NewCount != PopCnt)
1665 (cast<Instruction>(NewCount))->setDebugLoc(DL);
1673 if (!InitConst || !InitConst->
isZero()) {
1674 NewCount = Builder.
CreateAdd(NewCount, CntInitVal);
1675 (cast<Instruction>(NewCount))->setDebugLoc(DL);
1684 ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
1686 Value *Opnd0 = PopCntZext;
1691 ICmpInst *NewPreCond = cast<ICmpInst>(
1693 PreCondBr->setCondition(NewPreCond);
1718 BasicBlock *Body = *(CurLoop->block_begin());
1721 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
1729 "tcdec",
false,
true));
1736 LbCond->setPredicate(Pred);
1737 LbCond->setOperand(0, TcDec);
The access may reference and may modify the value stored in memory.
Pass interface - Implemented by all 'passes'.
Value * getValueOperand()
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void push_back(const T &Elt)
A parsed version of the target data layout string in and methods for querying it. ...
static ConstantInt * getFalse(LLVMContext &Context)
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
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...
static CallInst * createPopcntIntrinsic(IRBuilder<> &IRBuilder, Value *Val, const DebugLoc &DL)
PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
const SCEV * getConstant(ConstantInt *V)
Compute iterated dominance frontiers using a linear time algorithm.
BinaryOps getOpcode() const
Value * isBytewiseValue(Value *V)
If the specified value can be set by repeating the same byte in memory, return the i8 value that it i...
bool isAtomic() const
Return true if this instruction has an AtomicOrdering of unordered or higher.
Constant * getOrInsertFunction(StringRef Name, FunctionType *T, AttributeList AttributeList)
Look up the specified function in the module symbol table.
ArrayRef< BasicBlock *>::const_iterator block_iterator
A Module instance is used to store all the information related to an LLVM module. ...
The main scalar evolution driver.
static bool detectCTLZIdiom(Loop *CurLoop, PHINode *&PhiX, Instruction *&CntInst, PHINode *&CntPhi, Instruction *&DefX)
Return true if the idiom is detected in the loop.
This class represents a function call, abstracting a target machine's calling convention.
static PHINode * getRecurrenceVar(Value *VarX, Instruction *DefX, BasicBlock *LoopEntry)
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
Like Internal, but omit from symbol table.
LLVMContext & getContext() const
All values hold a context through their type.
This class wraps the llvm.memset intrinsic.
BasicBlock * getSuccessor(unsigned i) const
STATISTIC(NumFunctions, "Total number of functions")
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
An instruction for reading from memory.
Value * getCondition() const
Value * getLength() const
iterator end()
Get an iterator to the end of the SetVector.
static Constant * get(ArrayType *T, ArrayRef< Constant *> V)
Value * getDest() const
This is just like getRawDest, but it strips off any cast instructions (including addrspacecast) that ...
iterator begin()
Instruction iterator methods.
AnalysisUsage & addRequired()
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
#define INITIALIZE_PASS_DEPENDENCY(depName)
bool isVolatile() const
Return true if this is a load from a volatile memory location.
const Loop * getLoop() const
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
static CallInst * createCTLZIntrinsic(IRBuilder<> &IRBuilder, Value *Val, const DebugLoc &DL, bool ZeroCheck)
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
This file contains the simple types necessary to represent the attributes associated with functions a...
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
unsigned getDestAlignment() const
This file implements a class to represent arbitrary precision integral constant values and operations...
const APInt & getAPInt() const
BlockT * getHeader() const
void computeLoopSafetyInfo(LoopSafetyInfo *, Loop *)
Computes safety information for a loop checks loop body & header for the possibility of may throw exc...
static bool isSimple(Instruction *I)
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
Type * getType() const
All values are typed, get the type of this value.
Value handle that is nullable, but tries to track the Value.
bool insert(const value_type &X)
Insert a new element into the SetVector.
This node represents a polynomial recurrence on the trip count of the specified loop.
static APInt getStoreStride(const SCEVAddRecExpr *StoreEv)
BasicBlock * GetInsertBlock() const
Class to represent array types.
static cl::opt< bool > UseLIRCodeSizeHeurs("use-lir-code-size-heurs", cl::desc("Use loop idiom recognition code size heuristics when compiling" "with -Os/-Oz"), cl::init(true), cl::Hidden)
bool has(LibFunc F) const
Tests whether a library function is available.
iterator begin()
Get an iterator to the beginning of the SetVector.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
void initializeLoopIdiomRecognizeLegacyPassPass(PassRegistry &)
An instruction for storing to memory.
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
static void deleteDeadInstruction(Instruction *I)
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
Value * getOperand(unsigned i) const
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
bool isLoopEntryGuardedByCond(const Loop *L, ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS)
Test whether entry to the loop is protected by a conditional between LHS and RHS. ...
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
bool isConsecutiveAccess(Value *A, Value *B, const DataLayout &DL, ScalarEvolution &SE, bool CheckType=true)
Returns true if the memory operations A and B are consecutive.
bool inferLibFuncAttributes(Function &F, const TargetLibraryInfo &TLI)
Analyze the name and prototype of the given function and set any applicable attributes.
initializer< Ty > init(const Ty &Val)
const SCEV * getOperand(unsigned i) const
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
A set of analyses that are preserved following a run of a transformation pass.
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
ConstantInt * getTrue()
Get the constant value for i1 true.
Conditional or Unconditional Branch instruction.
bool isKnownNonNegative(const Value *V, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr)
Returns true if the give value is known to be non-negative.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
This file contains the declarations for the subclasses of Constant, which represent the different fla...
const Instruction & front() const
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
const SCEV * getAddExpr(SmallVectorImpl< const SCEV *> &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
Represent the analysis usage information of a pass.
bool optForSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
static Value * matchCondition(BranchInst *BI, BasicBlock *LoopEntry)
Check if the given conditional branch is based on the comparison between a variable and zero...
This instruction compares its operands according to the predicate given to the constructor.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values...
Value * getPointerOperand()
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
self_iterator getIterator()
const SCEV * getStart() const
const SCEV * getMinusSCEV(const SCEV *LHS, const SCEV *RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr)
If the specified value is a trivially dead instruction, delete it.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
static wasm::ValType getType(const TargetRegisterClass *RC)
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
const SCEV * getMulExpr(SmallVectorImpl< const SCEV *> &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
Value * GetUnderlyingObject(Value *V, const DataLayout &DL, unsigned MaxLookup=6)
This method strips off any GEP address adjustments and pointer casts from the specified value...
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
TargetTransformInfo & TTI
Representation for a specific memory location.
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
typename vector_type::const_iterator iterator
Iterator for intrusive lists based on ilist_node.
This is the shared class of boolean and integer constants.
Type * getType() const
Return the LLVM type of this SCEV expression.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Module.h This file contains the declarations for the Module class.
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.
bool isConditional() const
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static Constant * getMemSetPatternValue(Value *V, const DataLayout *DL)
getMemSetPatternValue - If a strided store of the specified value is safe to turn into a memset_patte...
static const SCEV * getNumBytes(const SCEV *BECount, Type *IntPtr, unsigned StoreSize, Loop *CurLoop, const DataLayout *DL, ScalarEvolution *SE)
Compute the number of bytes as a SCEV from the backedge taken count.
static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB, Instruction *&CntInst, PHINode *&CntPhi, Value *&Var)
Return true iff the idiom is detected in the loop.
static ConstantInt * getTrue(LLVMContext &Context)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
The access may modify the value stored in memory.
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
loop Recognize loop idioms
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.
ModRefInfo getModRefInfo(ImmutableCallSite CS, const MemoryLocation &Loc)
getModRefInfo (for call sites) - Return information about whether a particular call site modifies or ...
iterator_range< user_iterator > users()
This class uses information about analyze scalars to rewrite expressions in canonical form...
Pass * createLoopIdiomPass()
ConstantInt * getFalse()
Get the constant value for i1 false.
uint64_t getTypeSizeInBits(Type *Ty) const
Size examples:
Predicate getPredicate() const
Return the predicate for this instruction.
bool isVolatile() const
Return true if this is a store to a volatile memory location.
Captures loop safety information.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
INITIALIZE_PASS_BEGIN(LoopIdiomRecognizeLegacyPass, "loop-idiom", "Recognize loop idioms", false, false) INITIALIZE_PASS_END(LoopIdiomRecognizeLegacyPass
void forgetLoop(const Loop *L)
This method should be called by the client when it has changed a loop in a way that may effect Scalar...
void setUnnamedAddr(UnnamedAddr Val)
unsigned getAlignment() const
Return the alignment of the access that is being performed.
This class represents an analyzed expression in the program.
unsigned getIntegerBitWidth() const
Represents a single loop in the control flow graph.
This file provides utility analysis objects describing memory locations.
StringRef getName() const
Return a constant reference to the value's name.
const Function * getParent() const
Return the enclosing method, or null if none.
LLVM_NODISCARD ModRefInfo intersectModRef(const ModRefInfo MRI1, const ModRefInfo MRI2)
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
void getLoopAnalysisUsage(AnalysisUsage &AU)
Helper to consistently add the set of standard passes to a loop pass's AnalysisUsage.
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
block_iterator block_end() const
unsigned getAlignment() const
Return the alignment of the access that is being performed.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
static const SCEV * getStartForNegStride(const SCEV *Start, const SCEV *BECount, Type *IntPtr, unsigned StoreSize, ScalarEvolution *SE)
const SCEV * getBackedgeTakenCount(const Loop *L)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
const SCEV * getNegativeSCEV(const SCEV *V, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap)
Return the SCEV object corresponding to -V.
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
A vector that has set insertion semantics.
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
static bool mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L, const SCEV *BECount, unsigned StoreSize, AliasAnalysis &AA, SmallPtrSetImpl< Instruction *> &IgnoredStores)
mayLoopAccessLocation - Return true if the specified loop might access the specified pointer location...
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
StringRef - Represent a constant reference to a string, i.e.
A container for analyses that lazily runs them and caches their results.
void replaceUsesOutsideBlock(Value *V, BasicBlock *BB)
replaceUsesOutsideBlock - Go through the uses list for this definition and make each use point to "V"...
const SCEV * getTruncateOrZeroExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
LLVM_NODISCARD bool isModOrRefSet(const ModRefInfo MRI)
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...
This header defines various interfaces for pass management in LLVM.
bool isSafeToExpand(const SCEV *S, ScalarEvolution &SE)
Return true if the given expression is safe to expand in the sense that all materialized values are s...
block_iterator block_begin() const
bool hasLoopInvariantBackedgeTakenCount(const Loop *L)
Return true if the specified loop has an analyzable loop-invariant backedge-taken count...
Value * getPointerOperand()
const SCEV * getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
This class represents a constant integer value.
CallInst * CreateCall(Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)