69 #define DEBUG_TYPE "loop-idiom"
71 STATISTIC(NumMemSet,
"Number of memset's formed from loop stores");
72 STATISTIC(NumMemCpy,
"Number of memcpy's formed from loop load+stores");
75 "use-lir-code-size-heurs",
76 cl::desc(
"Use loop idiom recognition code size heuristics when compiling"
82 class LoopIdiomRecognize {
91 bool ApplyCodeSizeHeuristics;
99 : CurLoop(nullptr), AA(AA), DT(DT), LI(LI), SE(SE), TLI(TLI), TTI(TTI),
102 bool runOnLoop(
Loop *
L);
107 StoreListMap StoreRefsForMemset;
108 StoreListMap StoreRefsForMemsetPattern;
109 StoreList StoreRefsForMemcpy;
111 bool HasMemsetPattern;
114 enum LegalStoreKind {
119 UnorderedAtomicMemcpy,
127 bool runOnCountableLoop();
132 LegalStoreKind isLegalStore(
StoreInst *SI);
137 bool processLoopStridedStore(
Value *DestPtr,
unsigned StoreSize,
138 unsigned StoreAlignment,
Value *StoredVal,
142 bool NegStride,
bool IsLoopMemset =
false);
143 bool processLoopStoreOfLoopLoad(
StoreInst *SI,
const SCEV *BECount);
144 bool avoidLIRForMultiBlockLoop(
bool IsMemset =
false,
145 bool IsLoopMemset =
false);
151 bool runOnNoncountableLoop();
153 bool recognizePopcount();
156 bool recognizeAndInsertCTLZ();
159 bool ZeroCheck,
bool IsCntPhiUsedOutsideLoop);
164 class LoopIdiomRecognizeLegacyPass :
public LoopPass {
167 explicit LoopIdiomRecognizeLegacyPass() :
LoopPass(
ID) {
176 AliasAnalysis *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
177 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
178 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
179 ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
181 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
183 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
187 LoopIdiomRecognize LIR(AA, DT, LI, SE, TLI, TTI, DL);
188 return LIR.runOnLoop(L);
205 const auto *DL = &L.
getHeader()->getModule()->getDataLayout();
207 LoopIdiomRecognize LIR(&AR.
AA, &AR.
DT, &AR.
LI, &AR.
SE, &AR.
TLI, &AR.
TTI, DL);
208 if (!LIR.runOnLoop(&L))
216 "Recognize loop idioms",
false,
false)
236 bool LoopIdiomRecognize::runOnLoop(
Loop *L) {
245 if (Name ==
"memset" || Name ==
"memcpy")
249 ApplyCodeSizeHeuristics =
252 HasMemset = TLI->
has(LibFunc_memset);
253 HasMemsetPattern = TLI->
has(LibFunc_memset_pattern16);
254 HasMemcpy = TLI->
has(LibFunc_memcpy);
256 if (HasMemset || HasMemsetPattern || HasMemcpy)
258 return runOnCountableLoop();
260 return runOnNoncountableLoop();
263 bool LoopIdiomRecognize::runOnCountableLoop() {
265 assert(!isa<SCEVCouldNotCompute>(BECount) &&
266 "runOnCountableLoop() called on a loop without a predictable"
267 "backedge-taken count");
271 if (
const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
272 if (BECst->getAPInt() == 0)
276 CurLoop->getUniqueExitBlocks(ExitBlocks);
278 DEBUG(
dbgs() <<
"loop-idiom Scanning: F["
279 << CurLoop->getHeader()->getParent()->getName() <<
"] Loop %"
280 << CurLoop->getHeader()->getName() <<
"\n");
282 bool MadeChange =
false;
292 for (
auto *BB : CurLoop->getBlocks()) {
297 MadeChange |= runOnLoopBlock(BB, BECount, ExitBlocks);
304 assert(((SizeInBits & 7) || (SizeInBits >> 32) == 0) &&
305 "Don't overflow unsigned.");
306 return (
unsigned)SizeInBits >> 3;
330 if (Size == 0 || (Size & 7) || (Size & (Size - 1)))
350 unsigned ArraySize = 16 /
Size;
355 LoopIdiomRecognize::LegalStoreKind
356 LoopIdiomRecognize::isLegalStore(
StoreInst *SI) {
378 uint64_t SizeInBits = DL->getTypeSizeInBits(StoredVal->
getType());
379 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
391 if (!isa<SCEVConstant>(StoreEv->
getOperand(1)))
408 if (!UnorderedAtomic && HasMemset && SplatValue &&
411 CurLoop->isLoopInvariant(SplatValue)) {
413 return LegalStoreKind::Memset;
414 }
else if (!UnorderedAtomic && HasMemsetPattern &&
419 return LegalStoreKind::MemsetPattern;
428 if (StoreSize != Stride && StoreSize != -Stride)
454 UnorderedAtomic = UnorderedAtomic || LI->
isAtomic();
455 return UnorderedAtomic ? LegalStoreKind::UnorderedAtomicMemcpy
456 : LegalStoreKind::Memcpy;
462 void LoopIdiomRecognize::collectStores(
BasicBlock *BB) {
463 StoreRefsForMemset.clear();
464 StoreRefsForMemsetPattern.clear();
465 StoreRefsForMemcpy.clear();
472 switch (isLegalStore(SI)) {
476 case LegalStoreKind::Memset: {
479 StoreRefsForMemset[
Ptr].push_back(SI);
481 case LegalStoreKind::MemsetPattern: {
484 StoreRefsForMemsetPattern[
Ptr].push_back(SI);
486 case LegalStoreKind::Memcpy:
487 case LegalStoreKind::UnorderedAtomicMemcpy:
488 StoreRefsForMemcpy.push_back(SI);
491 assert(
false &&
"unhandled return value");
500 bool LoopIdiomRecognize::runOnLoopBlock(
506 for (
unsigned i = 0, e = ExitBlocks.
size(); i != e; ++i)
510 bool MadeChange =
false;
517 for (
auto &SL : StoreRefsForMemset)
518 MadeChange |= processLoopStores(SL.second, BECount,
true);
520 for (
auto &SL : StoreRefsForMemsetPattern)
521 MadeChange |= processLoopStores(SL.second, BECount,
false);
524 for (
auto &SI : StoreRefsForMemcpy)
525 MadeChange |= processLoopStoreOfLoopLoad(SI, BECount);
530 if (
MemSetInst *MSI = dyn_cast<MemSetInst>(Inst)) {
532 if (!processLoopMemSet(MSI, BECount))
558 for (
unsigned i = 0, e = SL.
size(); i < e; ++i) {
559 assert(SL[i]->
isSimple() &&
"Expected only non-volatile stores.");
561 Value *FirstStoredVal = SL[i]->getValueOperand();
562 Value *FirstStorePtr = SL[i]->getPointerOperand();
564 cast<SCEVAddRecExpr>(SE->
getSCEV(FirstStorePtr));
569 if (FirstStride == FirstStoreSize || -FirstStride == FirstStoreSize) {
574 Value *FirstSplatValue =
nullptr;
575 Constant *FirstPatternValue =
nullptr;
582 assert((FirstSplatValue || FirstPatternValue) &&
583 "Expected either splat value or pattern value.");
591 for (j = i + 1; j < e; ++j)
593 for (j = i; j > 0; --j)
596 for (
auto &k : IndexQueue) {
597 assert(SL[k]->
isSimple() &&
"Expected only non-volatile stores.");
598 Value *SecondStorePtr = SL[k]->getPointerOperand();
600 cast<SCEVAddRecExpr>(SE->
getSCEV(SecondStorePtr));
603 if (FirstStride != SecondStride)
606 Value *SecondStoredVal = SL[k]->getValueOperand();
607 Value *SecondSplatValue =
nullptr;
608 Constant *SecondPatternValue =
nullptr;
615 assert((SecondSplatValue || SecondPatternValue) &&
616 "Expected either splat value or pattern value.");
620 if (FirstSplatValue != SecondSplatValue)
623 if (FirstPatternValue != SecondPatternValue)
628 ConsecutiveChain[SL[i]] = SL[k];
637 bool Changed =
false;
642 if (Tails.
count(*it))
651 unsigned StoreSize = 0;
655 if (TransformedStores.
count(I))
661 I = ConsecutiveChain[
I];
671 if (StoreSize != Stride && StoreSize != -Stride)
674 bool NegStride = StoreSize == -Stride;
676 if (processLoopStridedStore(StorePtr, StoreSize, HeadStore->
getAlignment(),
677 StoredVal, HeadStore, AdjacentStores, StoreEv,
678 BECount, NegStride)) {
679 TransformedStores.
insert(AdjacentStores.begin(), AdjacentStores.end());
688 bool LoopIdiomRecognize::processLoopMemSet(
MemSetInst *MSI,
689 const SCEV *BECount) {
708 uint64_t SizeInBytes = cast<ConstantInt>(MSI->
getLength())->getZExtValue();
709 if ((SizeInBytes >> 32) != 0)
719 if (SizeInBytes != Stride && SizeInBytes != -Stride)
725 if (!SplatValue || !CurLoop->isLoopInvariant(SplatValue))
730 bool NegStride = SizeInBytes == -Stride;
731 return processLoopStridedStore(Pointer, (
unsigned)SizeInBytes,
733 BECount, NegStride,
true);
741 const SCEV *BECount,
unsigned StoreSize,
751 if (
const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
752 AccessSize = (BECst->getValue()->getZExtValue() + 1) * StoreSize;
763 if (IgnoredStores.
count(&I) == 0 &&
774 Type *IntPtr,
unsigned StoreSize,
785 bool LoopIdiomRecognize::processLoopStridedStore(
786 Value *DestPtr,
unsigned StoreSize,
unsigned StoreAlignment,
789 const SCEV *BECount,
bool NegStride,
bool IsLoopMemset) {
796 assert((SplatValue || PatternValue) &&
797 "Expected either splat value or pattern value.");
803 BasicBlock *Preheader = CurLoop->getLoopPreheader();
808 Type *IntPtr = Builder.getIntPtrTy(*DL, DestAS);
826 Expander.expandCodeFor(Start, DestInt8PtrTy, Preheader->
getTerminator());
835 if (avoidLIRForMultiBlockLoop(
true, IsLoopMemset))
844 const SCEV *NumBytesS =
846 if (StoreSize != 1) {
857 Expander.expandCodeFor(NumBytesS, IntPtr, Preheader->
getTerminator());
862 Builder.CreateMemSet(BasePtr, SplatValue, NumBytes, StoreAlignment);
865 Type *Int8PtrTy = DestInt8PtrTy;
870 Int8PtrTy, Int8PtrTy, IntPtr);
877 PatternValue,
".memset_pattern");
879 GV->setAlignment(16);
881 NewCall = Builder.CreateCall(MSP, {BasePtr, PatternPtr, NumBytes});
884 DEBUG(
dbgs() <<
" Formed memset: " << *NewCall <<
"\n"
885 <<
" from store to: " << *Ev <<
" at: " << *TheStore <<
"\n");
890 for (
auto *I : Stores)
899 bool LoopIdiomRecognize::processLoopStoreOfLoopLoad(
StoreInst *SI,
900 const SCEV *BECount) {
907 bool NegStride = StoreSize == -Stride;
922 BasicBlock *Preheader = CurLoop->getLoopPreheader();
928 Type *IntPtrTy = Builder.getIntPtrTy(*DL, StrAS);
940 Value *StoreBasePtr = Expander.expandCodeFor(
941 StrStart, Builder.getInt8PtrTy(StrAS), Preheader->
getTerminator());
946 StoreSize, *AA, Stores)) {
953 const SCEV *LdStart = LoadEv->getStart();
962 Value *LoadBasePtr = Expander.expandCodeFor(
963 LdStart, Builder.getInt8PtrTy(LdAS), Preheader->
getTerminator());
974 if (avoidLIRForMultiBlockLoop())
983 const SCEV *NumBytesS =
991 Expander.expandCodeFor(NumBytesS, IntPtrTy, Preheader->
getTerminator());
999 NewCall = Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr, NumBytes, Align);
1003 if (Align < StoreSize)
1013 NewCall = Builder.CreateElementUnorderedAtomicMemCpy(
1014 StoreBasePtr, LoadBasePtr, NumBytes, StoreSize);
1026 DEBUG(
dbgs() <<
" Formed memcpy: " << *NewCall <<
"\n"
1027 <<
" from load ptr=" << *LoadEv <<
" at: " << *LI <<
"\n"
1028 <<
" from store ptr=" << *StoreEv <<
" at: " << *SI <<
"\n");
1040 bool LoopIdiomRecognize::avoidLIRForMultiBlockLoop(
bool IsMemset,
1041 bool IsLoopMemset) {
1042 if (ApplyCodeSizeHeuristics && CurLoop->getNumBlocks() > 1) {
1043 if (!CurLoop->getParentLoop() && (!IsMemset || !IsLoopMemset)) {
1044 DEBUG(
dbgs() <<
" " << CurLoop->getHeader()->getParent()->getName()
1045 <<
" : LIR " << (IsMemset ?
"Memset" :
"Memcpy")
1046 <<
" avoided: multi-block top-level loop\n");
1054 bool LoopIdiomRecognize::runOnNoncountableLoop() {
1055 return recognizePopcount() || recognizeAndInsertCTLZ();
1072 if (!CmpZero || !CmpZero->
isZero())
1088 if (PhiX && PhiX->getParent() == LoopEntry &&
1089 (PhiX->getOperand(0) == DefX || PhiX->
getOperand(1) == DefX))
1125 Value *VarX1, *VarX0;
1128 DefX2 = CountInst =
nullptr;
1129 VarX1 = VarX0 =
nullptr;
1130 PhiX = CountPhi =
nullptr;
1136 dyn_cast<BranchInst>(LoopEntry->
getTerminator()), LoopEntry))
1137 DefX2 = dyn_cast<Instruction>(
T);
1144 if (!DefX2 || DefX2->
getOpcode() != Instruction::And)
1149 if ((SubOneOp = dyn_cast<BinaryOperator>(DefX2->
getOperand(0))))
1158 Instruction *SubInst = cast<Instruction>(SubOneOp);
1161 !((SubInst->
getOpcode() == Instruction::Sub && Dec->isOne()) ||
1163 Dec->isMinusOne()))) {
1175 CountInst =
nullptr;
1177 IterE = LoopEntry->
end();
1178 Iter != IterE; Iter++) {
1184 if (!Inc || !Inc->
isOne())
1192 bool LiveOutLoop =
false;
1194 if ((cast<Instruction>(U))->getParent() != LoopEntry) {
1219 CntInst = CountInst;
1258 Value *VarX =
nullptr;
1268 dyn_cast<BranchInst>(LoopEntry->
getTerminator()), LoopEntry))
1269 DefX = dyn_cast<Instruction>(
T);
1274 if (!DefX || DefX->
getOpcode() != Instruction::AShr)
1277 if (!Shft || !Shft->isOne())
1293 IterE = LoopEntry->
end();
1294 Iter != IterE; Iter++) {
1300 if (!Inc || !Inc->
isOne())
1320 bool LoopIdiomRecognize::recognizeAndInsertCTLZ() {
1322 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
1330 bool IsCntPhiUsedOutsideLoop =
false;
1332 if (!CurLoop->contains(dyn_cast<Instruction>(U))) {
1333 IsCntPhiUsedOutsideLoop =
true;
1336 bool IsCntInstUsedOutsideLoop =
false;
1338 if (!CurLoop->contains(dyn_cast<Instruction>(U))) {
1339 IsCntInstUsedOutsideLoop =
true;
1344 if (IsCntInstUsedOutsideLoop && IsCntPhiUsedOutsideLoop)
1350 bool ZeroCheck =
false;
1353 BasicBlock *PH = CurLoop->getLoopPreheader();
1358 if (!IsCntPhiUsedOutsideLoop)
1361 dyn_cast<BranchInst>(PreCondBB->getTerminator())) {
1377 {InitX, ZeroCheck ? Builder.getTrue() : Builder.getFalse()};
1379 if (CurLoop->getHeader()->size() != 6 &&
1385 transformLoopToCountable(PH, CntInst, CntPhi, InitX, DL, ZeroCheck,
1386 IsCntPhiUsedOutsideLoop);
1394 bool LoopIdiomRecognize::recognizePopcount() {
1404 if (CurLoop->getNumBackEdges() != 1 || CurLoop->getNumBlocks() != 1)
1407 BasicBlock *LoopBody = *(CurLoop->block_begin());
1408 if (LoopBody->
size() >= 20) {
1414 BasicBlock *PH = CurLoop->getLoopPreheader();
1418 if (!EntryBI || EntryBI->isConditional())
1427 if (!PreCondBI || PreCondBI->isUnconditional())
1436 transformLoopToPopcount(PreCondBB, CntInst, CntPhi, Val);
1442 Value *Ops[] = {Val};
1454 const DebugLoc &DL,
bool ZeroCheck) {
1497 void LoopIdiomRecognize::transformLoopToCountable(
1499 const DebugLoc DL,
bool ZeroCheck,
bool IsCntPhiUsedOutsideLoop) {
1507 Builder.SetCurrentDebugLocation(DL);
1508 Value *
CTLZ, *Count, *CountPrev, *NewCount, *InitXNext;
1510 if (IsCntPhiUsedOutsideLoop)
1511 InitXNext = Builder.CreateAShr(InitX,
1516 Count = Builder.CreateSub(
1520 if (IsCntPhiUsedOutsideLoop) {
1522 Count = Builder.CreateAdd(
1526 if (IsCntPhiUsedOutsideLoop)
1527 NewCount = Builder.CreateZExtOrTrunc(CountPrev,
1528 cast<IntegerType>(CntInst->
getType()));
1530 NewCount = Builder.CreateZExtOrTrunc(Count,
1531 cast<IntegerType>(CntInst->
getType()));
1536 if (!InitConst || !InitConst->
isZero())
1537 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
1547 BasicBlock *Body = *(CurLoop->block_begin());
1549 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
1554 Builder.SetInsertPoint(LbCond);
1557 "tcdec",
false,
true));
1564 LbCond->setPredicate(Pred);
1565 LbCond->setOperand(0, TcDec);
1571 if (IsCntPhiUsedOutsideLoop)
1581 void LoopIdiomRecognize::transformLoopToPopcount(
BasicBlock *PreCondBB,
1584 BasicBlock *PreHead = CurLoop->getLoopPreheader();
1594 Value *PopCnt, *PopCntZext, *NewCount, *TripCnt;
1597 NewCount = PopCntZext =
1598 Builder.CreateZExtOrTrunc(PopCnt, cast<IntegerType>(CntPhi->
getType()));
1600 if (NewCount != PopCnt)
1601 (cast<Instruction>(NewCount))->setDebugLoc(DL);
1609 if (!InitConst || !InitConst->
isZero()) {
1610 NewCount = Builder.CreateAdd(NewCount, CntInitVal);
1611 (cast<Instruction>(NewCount))->setDebugLoc(DL);
1620 ICmpInst *PreCond = cast<ICmpInst>(PreCondBr->getCondition());
1622 Value *Opnd0 = PopCntZext;
1627 ICmpInst *NewPreCond = cast<ICmpInst>(
1628 Builder.CreateICmp(PreCond->
getPredicate(), Opnd0, Opnd1));
1629 PreCondBr->setCondition(NewPreCond);
1654 BasicBlock *Body = *(CurLoop->block_begin());
1657 ICmpInst *LbCond = cast<ICmpInst>(LbBr->getCondition());
1662 Builder.SetInsertPoint(LbCond);
1665 "tcdec",
false,
true));
1672 LbCond->setPredicate(Pred);
1673 LbCond->setOperand(0, TcDec);
unsigned getAlignment() const
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. ...
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.
const SCEV * getConstant(ConstantInt *V)
STATISTIC(NumFunctions,"Total number of functions")
bool isVolatile() const
Return true if this is a store to a volatile memory location.
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...
This header provides classes for managing a pipeline of passes over loops in LLVM IR...
This is the interface for a simple mod/ref and alias analysis over globals.
Constant * getOrInsertFunction(StringRef Name, FunctionType *T, AttributeList AttributeList)
Look up the specified function in the module symbol table.
static Attribute getWithAlignment(LLVMContext &Context, uint64_t Align)
Return a uniquified Attribute object that has the specific alignment set.
A Module instance is used to store all the information related to an LLVM module. ...
Maximum length of the test input libFuzzer tries to guess a good value based on the corpus and reports it always prefer smaller inputs during the corpus shuffle When libFuzzer itself reports a bug this exit code will be used If indicates the maximal total time in seconds to run the fuzzer minimizes the provided crash input Use with tries to cleanse the provided crash input to make it contain fewer original bytes Use with exact_artifact_path to specify the output Experimental Use value profile to guide fuzzing Number of jobs to run If min(jobs, NumberOfCpuCores()/2)\" is used.") FUZZER_FLAG_INT(reload
Value * getValue() const
Return the arguments to the instruction.
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)
Like Internal, but omit from symbol table.
This class wraps the llvm.memset intrinsic.
const Function * getParent() const
Return the enclosing method, or null if none.
const Instruction & front() const
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
An instruction for reading from memory.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
iterator end()
Get an iterator to the end of the SetVector.
The access modifies the value stored in memory.
BlockT * getHeader() const
const SCEV * getStart() const
iterator begin()
Instruction iterator methods.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
This is the interface for a SCEV-based alias analysis.
static CallInst * createCTLZIntrinsic(IRBuilder<> &IRBuilder, Value *Val, const DebugLoc &DL, bool ZeroCheck)
INITIALIZE_PASS_BEGIN(LoopIdiomRecognizeLegacyPass,"loop-idiom","Recognize loop idioms", false, false) INITIALIZE_PASS_END(LoopIdiomRecognizeLegacyPass
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
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)
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)
Class to represent array types.
BasicBlock * getSuccessor(unsigned i) const
iterator begin()
Get an iterator to the beginning of the SetVector.
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.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
void initializeLoopIdiomRecognizeLegacyPassPass(PassRegistry &)
An instruction for storing to memory.
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...
bool isAtomic() const
Return true if this instruction has an AtomicOrdering of unordered or higher.
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
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)
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)
unsigned getAlignment() const
Return the alignment of the access that is being performed.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values...
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.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
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.
This is an important base class in LLVM.
const SCEV * getOperand(unsigned i) const
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Represent the analysis usage information of a pass.
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.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
Value * getOperand(unsigned i) const
Value * getPointerOperand()
self_iterator getIterator()
unsigned getIntegerBitWidth() const
Predicate getPredicate() const
Return the predicate for this instruction.
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.
const APInt & getAPInt() const
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 PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
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...
TargetTransformInfo & TTI
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...
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
bool isConditional() const
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.
loop Recognize loop false
This is the shared class of boolean and integer constants.
Value * getDest() const
This is just like getRawDest, but it strips off any cast instructions that feed it, giving the original input.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
Provides information about what library functions are available for the current target.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
bool isVolatile() const
Return true if this is a load from a volatile memory location.
Value * getLength() const
BasicBlock * GetInsertBlock() const
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 isZero() const
This is just a convenience method to make client code smaller for a common code.
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...
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
static bool detectPopcountIdiom(Loop *CurLoop, BasicBlock *PreCondBB, Instruction *&CntInst, PHINode *&CntPhi, Value *&Var)
Return true iff the idiom is detected in the loop.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
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.
loop Recognize loop idioms
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 ...
Value * getIncomingValueForBlock(const BasicBlock *BB) const
iterator_range< user_iterator > users()
This class uses information about analyze scalars to rewrite expressions in canonical form...
std::vector< BlockT * >::const_iterator block_iterator
Pass * createLoopIdiomPass()
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
ConstantInt * getFalse()
Get the constant value for i1 false.
block_iterator block_end() const
Value * getCondition() const
Captures loop safety information.
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...
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
void setUnnamedAddr(UnnamedAddr Val)
This class represents an analyzed expression in the program.
Represents a single loop in the control flow graph.
unsigned getAlignment() const
Return the alignment of the access that is being performed.
The access both references and modifies the value stored in memory.
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
CallInst * CreateCall(Value *Callee, ArrayRef< Value * > Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
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)
const Loop * getLoop() const
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())
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.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
A vector that has set insertion semantics.
uint64_t getTypeSizeInBits(Type *Ty) const
Size examples:
static unsigned getStoreSizeInBytes(StoreInst *SI, const DataLayout *DL)
block_iterator block_begin() const
StringRef - Represent a constant reference to a string, i.e.
This is the interface for LLVM's primary stateless and local alias analysis.
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.
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.
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...
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
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...
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool hasLoopInvariantBackedgeTakenCount(const Loop *L)
Return true if the specified loop has an analyzable loop-invariant backedge-taken count...
Value * getPointerOperand()
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
bool has(LibFunc F) const
Tests whether a library function is available.
PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
This class represents a constant integer value.
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Adds the attribute to the indicated argument.