10 #define DEBUG_TYPE "hexagon-lir"
39 cl::desc(
"Disable generation of memcpy in loop idiom recognition"));
43 cl::desc(
"Disable generation of memmove in loop idiom recognition"));
47 "check guarding the memmove."));
51 cl::desc(
"Threshold (in bytes) to perform the transformation, if the "
52 "runtime loop count (mem transfer size) is known at compile-time."));
56 cl::desc(
"Only enable generating memmove in non-nested loops"));
60 cl::desc(
"Enable Hexagon-specific memcpy for volatile destination."));
66 =
"hexagon_memcpy_forward_vp4cp4n2";
75 class HexagonLoopIdiomRecognize :
public LoopPass {
78 explicit HexagonLoopIdiomRecognize() :
LoopPass(
ID) {
82 return "Recognize Hexagon-specific loop idioms";
109 bool runOnCountableLoop(
Loop *
L);
117 bool HasMemcpy, HasMemmove;
124 "Recognize Hexagon-specific loop idioms",
false,
false)
133 "Recognize Hexagon-specific loop
idioms",
false, false)
138 typedef std::function<Value* (Instruction*, LLVMContext&)>
Rule;
143 struct WorkListType {
144 WorkListType() =
default;
146 void push_back(
Value* V) {
148 if (!S.count(V)) { Q.push_back(V); S.insert(V); }
150 Value *pop_front_val() {
151 Value *V = Q.front(); Q.pop_front(); S.erase(V);
154 bool empty()
const {
return Q.empty(); }
157 std::deque<Value*> Q;
161 typedef std::set<Value*> ValueSetType;
162 std::vector<Rule> Rules;
186 template <
typename FuncT>
void traverse(
Value *V, FuncT
F);
187 void record(
Value *V);
189 void unuse(
Value *V);
217 template <
typename FuncT>
218 void Simplifier::Context::traverse(
Value *V, FuncT
F) {
237 OS << V <<
'(' << *V <<
')';
241 if (U->getParent()) {
243 U->printAsOperand(OS,
true);
248 unsigned N = U->getNumOperands();
251 OS << U->getOpcodeName();
252 for (
const Value *
Op : U->operands()) {
271 Value *V = Q.pop_front_val();
272 if (M.find(V) != M.end())
275 if (isa<PHINode>(U) || U->getParent() != Block)
277 for (
Value *
Op : U->operands())
279 M.insert({U, U->clone()});
283 for (std::pair<Value*,Value*>
P : M) {
292 auto R = M.find(Exp);
301 void Simplifier::Context::record(
Value *V) {
319 void Simplifier::Context::unuse(
Value *V) {
320 if (!isa<Instruction>(V) || cast<Instruction>(V)->
getParent() !=
nullptr)
376 Value *V = Q.pop_front_val();
382 NewV = subst(NewV, V, DupV);
390 Root = subst(Root, OldV, NewV);
396 for (
Value *V : Clones) {
402 for (
Value *V : Clones) {
426 if (!
equal(InI, InJ))
428 }
else if (InI != InJ || !InI)
441 Value *V = Q.pop_front_val();
447 if (SubI &&
equal(SubI, U))
473 if (
Instruction *RootI = dyn_cast<Instruction>(Root))
486 if (Count++ >= Limit)
491 bool Changed =
false;
492 for (
Rule &R : Rules) {
507 return Count < Limit ? C.
Root :
nullptr;
518 class PolynomialMultiplyRecognize {
520 explicit PolynomialMultiplyRecognize(
Loop *loop,
const DataLayout &dl,
523 : CurLoop(loop),
DL(dl), DT(dt), TLI(tli), SE(se) {}
530 LLVMContext &Ctx = CurLoop->getHeader()->getParent()->getContext();
539 void classifyCycle(
Instruction *DivI, ValueSeq &Cycle, ValueSeq &Early,
541 bool classifyInst(
Instruction *UseI, ValueSeq &Early, ValueSeq &Late);
543 bool highBitsAreZero(
Value *V,
unsigned IterCount);
544 bool keepsHighBitsZero(
Value *V,
unsigned IterCount);
550 struct ParsedValues {
551 ParsedValues() : M(nullptr),
P(nullptr), Q(nullptr), R(nullptr),
552 X(nullptr), Res(nullptr), IterCount(0),
Left(false), Inv(false) {}
560 bool matchRightShift(
SelectInst *SelI, ParsedValues &PV);
562 Value *CIV, ParsedValues &PV,
bool PreScan);
563 unsigned getInverseMxN(
unsigned QP);
566 void setupSimplifier();
580 if (std::distance(PI, PE) != 2)
582 BasicBlock *PB = (*PI == BB) ? *std::next(PI) : *PI;
584 for (
auto I = BB->
begin(),
E = BB->
end(); I !=
E && isa<PHINode>(
I); ++
I) {
585 auto *PN = cast<PHINode>(
I);
586 Value *InitV = PN->getIncomingValueForBlock(PB);
587 if (!isa<ConstantInt>(InitV) || !cast<ConstantInt>(InitV)->
isZero())
589 Value *IterV = PN->getIncomingValueForBlock(BB);
590 if (!isa<BinaryOperator>(IterV))
595 Value *IncV =
nullptr;
596 if (BO->getOperand(0) == PN)
597 IncV = BO->getOperand(1);
598 else if (BO->getOperand(1) == PN)
599 IncV = BO->getOperand(0);
603 if (
auto *
T = dyn_cast<ConstantInt>(IncV))
604 if (
T->getZExtValue() == 1)
613 Use &TheUse = UI.getUse();
615 if (
auto *II = dyn_cast<Instruction>(TheUse.
getUser()))
617 II->replaceUsesOfWith(I, J);
622 bool PolynomialMultiplyRecognize::matchLeftShift(
SelectInst *SelI,
623 Value *CIV, ParsedValues &PV) {
635 using namespace PatternMatch;
638 Value *
A =
nullptr, *B =
nullptr, *
C =
nullptr;
648 Value *
X =
nullptr, *Sh1 =
nullptr;
676 Value *ShouldSameV =
nullptr, *ShouldXoredV =
nullptr;
679 ShouldXoredV = FalseV;
681 ShouldSameV = FalseV;
682 ShouldXoredV = TrueV;
685 Value *Q =
nullptr, *R =
nullptr, *
Y =
nullptr, *
Z =
nullptr;
691 if (ShouldSameV ==
Y)
693 else if (ShouldSameV == Z)
738 bool PolynomialMultiplyRecognize::matchRightShift(
SelectInst *SelI,
751 using namespace PatternMatch;
781 Value *R =
nullptr, *Q =
nullptr;
814 bool PolynomialMultiplyRecognize::scanSelect(
SelectInst *SelI,
817 using namespace PatternMatch;
855 if (matchLeftShift(SelI, CIV, PV)) {
864 if (SelI != RPhi->getIncomingValueForBlock(LoopB))
870 if (CurLoop->isLoopInvariant(PV.X)) {
880 Value *Var =
nullptr, *Inv =
nullptr, *X1 =
nullptr, *X2 =
nullptr;
885 if (!I1 || I1->getParent() != LoopB) {
888 }
else if (!I2 || I2->getParent() != LoopB) {
899 Value *EntryP = RPhi->getIncomingValueForBlock(PrehB);
906 if (matchRightShift(SelI, PV)) {
909 if (PV.Inv && !isa<ConstantInt>(PV.Q))
921 bool PolynomialMultiplyRecognize::isPromotableTo(
Value *Val,
940 case Instruction::PHI:
941 case Instruction::ZExt:
942 case Instruction::And:
943 case Instruction::Or:
944 case Instruction::Xor:
945 case Instruction::LShr:
948 case Instruction::ICmp:
949 if (
CmpInst *CI = cast<CmpInst>(In))
950 return CI->isEquality() || CI->isUnsigned();
959 void PolynomialMultiplyRecognize::promoteTo(
Instruction *In,
967 if (
PHINode *
P = dyn_cast<PHINode>(In)) {
968 unsigned N =
P->getNumIncomingValues();
969 for (
unsigned i = 0; i !=
N; ++i) {
973 Value *InV =
P->getIncomingValue(i);
976 if (Ty !=
P->getType()) {
981 P->setIncomingValue(i, InV);
984 }
else if (
ZExtInst *Z = dyn_cast<ZExtInst>(In)) {
985 Value *Op =
Z->getOperand(0);
987 Z->replaceAllUsesWith(Op);
988 Z->eraseFromParent();
995 if (CI->getType()->getBitWidth() < DestBW)
1001 bool PolynomialMultiplyRecognize::promoteTypes(
BasicBlock *LoopB,
1022 if (!T || T->getBitWidth() > DestBW)
1028 if (!In.
isTerminator() && !isPromotableTo(&In, DestTy))
1032 std::vector<Instruction*> LoopIns;
1033 std::transform(LoopB->begin(), LoopB->end(), std::back_inserter(LoopIns),
1036 promoteTo(In, DestTy, LoopB);
1041 for (
auto I = ExitB->begin(); I !=
End; ++
I) {
1057 cast<Instruction>(
T)->setOperand(0, P);
1065 bool PolynomialMultiplyRecognize::findCycle(
Value *Out,
Value *In,
1071 auto *BB = cast<Instruction>(Out)->
getParent();
1072 bool HadPhi =
false;
1074 for (
auto U : Out->
users()) {
1076 if (I ==
nullptr || I->
getParent() != BB)
1083 bool IsPhi = isa<PHINode>(
I);
1084 if (IsPhi && HadPhi)
1090 if (findCycle(I, In, Cycle))
1094 return !Cycle.empty();
1098 void PolynomialMultiplyRecognize::classifyCycle(
Instruction *DivI,
1099 ValueSeq &Cycle, ValueSeq &Early, ValueSeq &Late) {
1105 unsigned I, N = Cycle.size();
1106 for (I = 0; I <
N; ++
I) {
1110 else if (!isa<PHINode>(V))
1117 ValueSeq &First = !IsE ? Early : Late;
1118 for (
unsigned J = 0; J <
I; ++J)
1119 First.insert(Cycle[J]);
1121 ValueSeq &Second = IsE ? Early : Late;
1122 Second.insert(Cycle[I]);
1123 for (++I; I <
N; ++
I) {
1125 if (DivI == V || isa<PHINode>(V))
1131 First.insert(Cycle[I]);
1135 bool PolynomialMultiplyRecognize::classifyInst(
Instruction *UseI,
1136 ValueSeq &Early, ValueSeq &Late) {
1142 if (Early.count(TV) || Early.count(FV)) {
1143 if (Late.count(TV) || Late.count(FV))
1146 }
else if (Late.count(TV) || Late.count(FV)) {
1147 if (Early.count(TV) || Early.count(FV))
1159 bool AE =
true,
AL =
true;
1161 if (Early.count(&*I))
1163 else if (Late.count(&*I))
1188 bool PolynomialMultiplyRecognize::commutesWithShift(
Instruction *I) {
1190 case Instruction::And:
1191 case Instruction::Or:
1192 case Instruction::Xor:
1193 case Instruction::LShr:
1194 case Instruction::Shl:
1196 case Instruction::ICmp:
1197 case Instruction::PHI:
1206 bool PolynomialMultiplyRecognize::highBitsAreZero(
Value *V,
1207 unsigned IterCount) {
1214 return Known.countMinLeadingZeros() >= IterCount;
1218 bool PolynomialMultiplyRecognize::keepsHighBitsZero(
Value *V,
1219 unsigned IterCount) {
1222 if (
auto *
C = dyn_cast<ConstantInt>(V))
1223 return C->getValue().countLeadingZeros() >= IterCount;
1225 if (
auto *I = dyn_cast<Instruction>(V)) {
1227 case Instruction::And:
1228 case Instruction::Or:
1229 case Instruction::Xor:
1230 case Instruction::LShr:
1232 case Instruction::ICmp:
1233 case Instruction::PHI:
1234 case Instruction::ZExt:
1243 bool PolynomialMultiplyRecognize::isOperandShifted(
Instruction *I,
Value *Op) {
1245 if (Opc == Instruction::Shl || Opc == Instruction::LShr)
1251 bool PolynomialMultiplyRecognize::convertShiftsToLeft(
BasicBlock *LoopB,
1253 Value *CIV = getCountIV(LoopB);
1257 if (CIVTy ==
nullptr)
1261 ValueSeq Early, Late, Cycled;
1265 using namespace PatternMatch;
1270 if (!findCycle(&I, V,
C))
1275 classifyCycle(&I,
C, Early, Late);
1276 Cycled.insert(
C.begin(),
C.end());
1282 ValueSeq
Users(Cycled.begin(), Cycled.end());
1283 for (
unsigned i = 0; i <
Users.size(); ++i) {
1285 if (!isa<IntegerType>(V->
getType()))
1287 auto *R = cast<Instruction>(V);
1290 if (!commutesWithShift(R))
1292 for (
auto I = R->
user_begin(),
E = R->user_end(); I !=
E; ++
I) {
1293 auto *T = cast<Instruction>(*I);
1297 if (T->getParent() != LoopB || RShifts.count(T) || isa<PHINode>(
T))
1301 if (!classifyInst(T, Early, Late))
1306 if (
Users.size() == 0)
1310 ValueSeq Internal(
Users.begin(),
Users.end());
1312 for (
unsigned i = 0; i < Internal.size(); ++i) {
1316 for (
Value *Op : R->operands()) {
1318 if (T && T->getParent() != LoopB)
1321 Internal.insert(Op);
1324 for (
Value *V : Inputs)
1325 if (!highBitsAreZero(V, IterCount))
1327 for (
Value *V : Internal)
1328 if (!keepsHighBitsZero(V, IterCount))
1333 std::map<Value*,Value*> ShiftMap;
1334 typedef std::map<std::pair<Value*,Type*>,
Value*> CastMapType;
1335 CastMapType CastMap;
1339 auto H = CM.find(std::make_pair(V, Ty));
1342 Value *CV = IRB.CreateIntCast(V, Ty,
false);
1343 CM.insert(std::make_pair(std::make_pair(V, Ty), CV));
1347 for (
auto I = LoopB->begin(),
E = LoopB->end(); I !=
E; ++
I) {
1348 if (isa<PHINode>(I) || !
Users.count(&*I))
1350 using namespace PatternMatch;
1359 for (
auto &J : I->operands()) {
1360 Value *Op = J.get();
1361 if (!isOperandShifted(&*I, Op))
1363 if (
Users.count(Op))
1366 if (isa<ConstantInt>(Op) && cast<ConstantInt>(
Op)->
isZero())
1369 auto F = ShiftMap.find(Op);
1370 Value *W = (
F != ShiftMap.end()) ?
F->second :
nullptr;
1372 IRB.SetInsertPoint(&*I);
1376 Value *ShAmt = CIV, *ShVal =
Op;
1377 auto *VTy = cast<IntegerType>(ShVal->getType());
1378 auto *ATy = cast<IntegerType>(ShAmt->
getType());
1379 if (Late.count(&*I))
1384 if (VTy->getBitWidth() < ATy->getBitWidth())
1385 ShVal = upcast(CastMap, IRB, ShVal, ATy);
1387 ShAmt = upcast(CastMap, IRB, ShAmt, VTy);
1390 W = IRB.CreateShl(ShVal, ShAmt);
1391 ShiftMap.insert(std::make_pair(Op, W));
1393 I->replaceUsesOfWith(Op, W);
1403 for (
auto P = ExitB->
begin(), Q = ExitB->
end(); P != Q; ++
P) {
1404 if (!isa<PHINode>(P))
1406 auto *PN = cast<PHINode>(
P);
1407 Value *U = PN->getIncomingValueForBlock(LoopB);
1408 if (!
Users.count(U))
1416 cast<User>(S)->replaceUsesOfWith(S, PN);
1423 void PolynomialMultiplyRecognize::cleanupLoopBody(
BasicBlock *LoopB) {
1424 for (
auto &I : *LoopB)
1426 I.replaceAllUsesWith(SV);
1428 for (
auto I = LoopB->begin(), N =
I; I != LoopB->end(); I =
N) {
1435 unsigned PolynomialMultiplyRecognize::getInverseMxN(
unsigned QP) {
1438 std::array<char,32> Q,
C;
1440 for (
unsigned i = 0; i < 32; ++i) {
1457 for (
unsigned i = 1; i < 32; ++i) {
1465 for (
unsigned j = 0; j < i; ++j)
1466 T = T ^ (C[j] & Q[i-j]);
1471 for (
unsigned i = 0; i < 32; ++i)
1482 Module *M = At->getParent()->getParent()->getParent();
1485 Value *P = PV.P, *Q = PV.Q, *P0 =
P;
1486 unsigned IC = PV.IterCount;
1488 if (PV.M !=
nullptr)
1489 P0 = P = B.CreateXor(P, PV.M);
1494 if (PV.IterCount != 32)
1495 P = B.CreateAnd(P, BMI);
1499 assert(QI && QI->getBitWidth() <= 32);
1502 unsigned M = (1 << PV.IterCount) - 1;
1503 unsigned Tmp = (QI->getZExtValue() | 1) & M;
1504 unsigned QV = getInverseMxN(Tmp) & M;
1506 P = B.CreateCall(PMF, {
P, QVI});
1507 P = B.CreateTrunc(P, QI->getType());
1509 P = B.CreateAnd(P, BMI);
1512 Value *R = B.CreateCall(PMF, {
P, Q});
1514 if (PV.M !=
nullptr)
1515 R = B.CreateXor(R, B.CreateIntCast(P0, R->
getType(),
false));
1521 void PolynomialMultiplyRecognize::setupSimplifier() {
1525 if (I->
getOpcode() != Instruction::ZExt)
1531 case Instruction::And:
1532 case Instruction::Or:
1533 case Instruction::Xor:
1539 return B.CreateBinOp(cast<BinaryOperator>(T)->getOpcode(),
1552 if (And0->
getOpcode() != Instruction::And ||
1553 And1->getOpcode() != Instruction::And)
1555 if (And0->
getOperand(1) != And1->getOperand(1))
1558 return B.CreateAnd(B.CreateXor(And0->
getOperand(0), And1->getOperand(0)),
1571 Value *
X = Sel->getTrueValue(), *
Y = Sel->getFalseValue();
1573 return B.CreateSelect(Sel->getCondition(),
1574 B.CreateBinOp(Op, X, Z),
1575 B.CreateBinOp(Op,
Y, Z));
1580 Value *
Y = Sel->getTrueValue(), *Z = Sel->getFalseValue();
1581 return B.CreateSelect(Sel->getCondition(),
1582 B.CreateBinOp(Op, X, Y),
1583 B.CreateBinOp(Op, X, Z));
1597 if (Sel0->getCondition() ==
C)
1598 return B.CreateSelect(C, Sel0->getTrueValue(), Sel->
getFalseValue());
1601 if (Sel1->getCondition() ==
C)
1602 return B.CreateSelect(C, Sel->
getTrueValue(), Sel1->getFalseValue());
1612 if (!LShr || LShr->
getOpcode() != Instruction::LShr)
1625 if (I->
getOpcode() != Instruction::LShr)
1631 case Instruction::And:
1632 case Instruction::Or:
1633 case Instruction::Xor:
1640 return B.CreateBinOp(BitOp->
getOpcode(),
1647 auto IsBitOp = [](
unsigned Op) ->
bool {
1649 case Instruction::And:
1650 case Instruction::Or:
1651 case Instruction::Xor:
1657 if (!BitOp1 || !IsBitOp(BitOp1->
getOpcode()))
1660 if (!BitOp2 || !IsBitOp(BitOp2->
getOpcode()))
1669 B.CreateBinOp(BitOp1->
getOpcode(), CA, CB));
1674 bool PolynomialMultiplyRecognize::recognize() {
1675 DEBUG(
dbgs() <<
"Starting PolynomialMultiplyRecognize on loop\n"
1676 << *CurLoop <<
'\n');
1683 DEBUG(
dbgs() <<
"Loop header:\n" << *LoopB);
1685 if (LoopB != CurLoop->getLoopLatch())
1688 if (ExitB ==
nullptr)
1690 BasicBlock *EntryB = CurLoop->getLoopPreheader();
1691 if (EntryB ==
nullptr)
1694 unsigned IterCount = 0;
1695 const SCEV *CT = SE.getBackedgeTakenCount(CurLoop);
1696 if (isa<SCEVCouldNotCompute>(CT))
1698 if (
auto *CV = dyn_cast<SCEVConstant>(CT))
1699 IterCount = CV->getValue()->getZExtValue() + 1;
1701 Value *CIV = getCountIV(LoopB);
1703 PV.IterCount = IterCount;
1704 DEBUG(
dbgs() <<
"Loop IV: " << *CIV <<
"\nIterCount: " << IterCount <<
'\n');
1714 bool FoundPreScan =
false;
1721 Value *T = Simp.simplify(C);
1722 SelectInst *SelI = (T && isa<SelectInst>(
T)) ? cast<SelectInst>(
T) : SI;
1723 DEBUG(
dbgs() <<
"scanSelect(pre-scan): " << PE(C, SelI) <<
'\n');
1724 if (scanSelect(SelI, LoopB, EntryB, CIV, PV,
true)) {
1725 FoundPreScan =
true;
1735 if (!FoundPreScan) {
1736 DEBUG(
dbgs() <<
"Have not found candidates for pmpy\n");
1745 if (!promoteTypes(LoopB, ExitB))
1747 if (!convertShiftsToLeft(LoopB, ExitB, IterCount))
1749 cleanupLoopBody(LoopB);
1753 bool FoundScan =
false;
1758 DEBUG(
dbgs() <<
"scanSelect: " << *SelI <<
'\n');
1759 FoundScan = scanSelect(SelI, LoopB, EntryB, CIV, PV,
false);
1768 dbgs() <<
"Found pmpy idiom: R = " << PP <<
".Q\n";
1770 dbgs() <<
"Found inverse pmpy idiom: R = (" << PP <<
"/Q).Q) + "
1772 dbgs() <<
" Res:" << *PV.Res <<
"\n P:" << *PV.P <<
"\n";
1774 dbgs() <<
" M:" << *PV.M <<
"\n";
1775 dbgs() <<
" Q:" << *PV.Q <<
"\n";
1776 dbgs() <<
" Iteration count:" << PV.IterCount <<
"\n";
1780 Value *PM = generate(At, PV);
1784 if (PM->getType() != PV.Res->getType())
1787 PV.Res->replaceAllUsesWith(PM);
1788 PV.Res->eraseFromParent();
1795 assert(((SizeInBits & 7) || (SizeInBits >> 32) == 0) &&
1796 "Don't overflow unsigned.");
1797 return (
unsigned)SizeInBits >> 3;
1801 int HexagonLoopIdiomRecognize::getSCEVStride(
const SCEVAddRecExpr *S) {
1803 return SC->getAPInt().getSExtValue();
1808 bool HexagonLoopIdiomRecognize::isLegalStore(
Loop *CurLoop,
StoreInst *SI) {
1818 if ((SizeInBits & 7) || (SizeInBits >> 32) != 0)
1825 if (!StoreEv || StoreEv->getLoop() != CurLoop || !StoreEv->isAffine())
1830 int Stride = getSCEVStride(StoreEv);
1834 if (StoreSize !=
unsigned(
std::abs(Stride)))
1847 if (!LoadEv || LoadEv->getLoop() != CurLoop || !LoadEv->isAffine())
1851 if (StoreEv->getOperand(1) != LoadEv->getOperand(1))
1864 const SCEV *BECount,
unsigned StoreSize,
1874 if (
const SCEVConstant *BECst = dyn_cast<SCEVConstant>(BECount))
1875 AccessSize = (BECst->getValue()->getZExtValue() + 1) * StoreSize;
1883 for (
auto *B : L->
blocks())
1892 void HexagonLoopIdiomRecognize::collectStores(
Loop *CurLoop,
BasicBlock *BB,
1896 if (
StoreInst *SI = dyn_cast<StoreInst>(&I))
1897 if (isLegalStore(CurLoop, SI))
1902 bool HexagonLoopIdiomRecognize::processCopyingStore(
Loop *CurLoop,
1905 "Expected only non-volatile stores, or Hexagon-specific memcpy"
1906 "to volatile destination.");
1909 auto *StoreEv = cast<SCEVAddRecExpr>(SE->getSCEV(StorePtr));
1910 unsigned Stride = getSCEVStride(StoreEv);
1912 if (Stride != StoreSize)
1937 Value *StoreBasePtr = Expander.expandCodeFor(StoreEv->getStart(),
1939 Value *LoadBasePtr =
nullptr;
1941 bool Overlap =
false;
1952 if (StoreBasePtr && (LoadBasePtr != StoreBasePtr)) {
1954 StoreBasePtr =
nullptr;
1958 LoadBasePtr =
nullptr;
1967 StoreSize, *AA, Ignore1)) {
1971 StoreSize, *AA, Ignore1)) {
1973 goto CleanupAndExit;
1981 goto CleanupAndExit;
1987 goto CleanupAndExit;
1996 if (!coverLoop(CurLoop, Insts))
1997 goto CleanupAndExit;
2000 goto CleanupAndExit;
2003 goto CleanupAndExit;
2008 LoadBasePtr = Expander.expandCodeFor(LoadEv->getStart(),
2015 goto CleanupAndExit;
2018 bool StridePos = getSCEVStride(LoadEv) >= 0;
2021 if (!StridePos && DestVolatile)
2022 goto CleanupAndExit;
2024 bool RuntimeCheck = (Overlap || DestVolatile);
2031 if (ExitBlocks.
size() != 1)
2032 goto CleanupAndExit;
2033 ExitB = ExitBlocks[0];
2039 BECount = SE->getTruncateOrZeroExtend(BECount, IntPtrTy);
2043 const SCEV *NumBytesS =
2044 SE->getAddExpr(BECount, SE->getOne(IntPtrTy),
SCEV::FlagNUW);
2046 NumBytesS = SE->getMulExpr(NumBytesS, SE->getConstant(IntPtrTy, StoreSize),
2048 Value *NumBytes = Expander.expandCodeFor(NumBytesS, IntPtrTy, ExpPt);
2049 if (
Instruction *In = dyn_cast<Instruction>(NumBytes))
2057 if (
ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes)) {
2058 uint64_t C = CI->getZExtValue();
2059 if (Threshold != 0 && C < Threshold)
2060 goto CleanupAndExit;
2062 goto CleanupAndExit;
2067 Loop *ParentL = LF->getLoopFor(Preheader);
2077 for (
auto &In : *Header) {
2085 DT->addNewBlock(NewPreheader, Preheader);
2086 DT->changeImmediateDominator(Header, NewPreheader);
2094 Value *LA = Builder.CreatePtrToInt(LoadBasePtr, IntPtrTy);
2095 Value *SA = Builder.CreatePtrToInt(StoreBasePtr, IntPtrTy);
2096 Value *LowA = StridePos ? SA : LA;
2097 Value *HighA = StridePos ? LA : SA;
2098 Value *CmpA = Builder.CreateICmpULT(LowA, HighA);
2102 Value *Dist = Builder.CreateSub(HighA, LowA);
2103 Value *CmpD = Builder.CreateICmpSLT(NumBytes, Dist);
2104 Value *CmpEither = Builder.CreateOr(Cond, CmpD);
2107 if (Threshold != 0) {
2110 Value *CmpB = Builder.CreateICmpULT(Thr, NumBytes);
2111 Value *CmpBoth = Builder.CreateAnd(Cond, CmpB);
2115 Func, NewPreheader);
2119 Builder.CreateCondBr(Cond, MemmoveB, NewPreheader);
2122 DT->addNewBlock(MemmoveB, Preheader);
2127 ExitD = DT->findNearestCommonDominator(ExitD, PB);
2135 if (ExitD && DT->dominates(Preheader, ExitD)) {
2143 CondBuilder.CreateBr(ExitB);
2152 Int32PtrTy, Int32PtrTy, Int32Ty);
2156 const SCEV *OneS = SE->getConstant(Int32Ty, 1);
2157 const SCEV *BECount32 = SE->getTruncateOrZeroExtend(BECount, Int32Ty);
2159 Value *NumWords = Expander.expandCodeFor(NumWordsS, Int32Ty,
2161 if (
Instruction *In = dyn_cast<Instruction>(NumWords))
2167 : CondBuilder.CreateBitCast(StoreBasePtr, Int32PtrTy);
2170 : CondBuilder.CreateBitCast(LoadBasePtr, Int32PtrTy);
2171 NewCall = CondBuilder.CreateCall(Fn, {Op0, Op1, NumWords});
2173 NewCall = CondBuilder.CreateMemMove(StoreBasePtr, LoadBasePtr,
2174 NumBytes, Alignment);
2177 NewCall = Builder.CreateMemCpy(StoreBasePtr, LoadBasePtr,
2178 NumBytes, Alignment);
2186 DEBUG(
dbgs() <<
" Formed " << (Overlap ?
"memmove: " :
"memcpy: ")
2188 <<
" from load ptr=" << *LoadEv <<
" at: " << *LI <<
"\n"
2189 <<
" from store ptr=" << *StoreEv <<
" at: " << *SI <<
"\n");
2198 bool HexagonLoopIdiomRecognize::coverLoop(
Loop *
L,
2201 for (
auto *B : L->
blocks())
2210 for (
unsigned i = 0; i < Worklist.size(); ++i) {
2217 if (!LoopBlocks.
count(PB))
2219 Worklist.insert(OpI);
2227 for (
auto *B : L->
blocks()) {
2228 for (
auto &In : *B) {
2229 if (isa<BranchInst>(In) || isa<DbgInfoIntrinsic>(
In))
2233 for (
const auto &K : In.
users()) {
2238 if (LF->getLoopFor(UseB) !=
L)
2250 bool HexagonLoopIdiomRecognize::runOnLoopBlock(
Loop *CurLoop,
BasicBlock *BB,
2255 auto DominatedByBB = [
this,BB] (
BasicBlock *EB) ->
bool {
2256 return DT->dominates(BB, EB);
2261 bool MadeChange =
false;
2264 collectStores(CurLoop, BB, Stores);
2267 for (
auto &SI : Stores)
2268 MadeChange |= processCopyingStore(CurLoop, SI, BECount);
2274 bool HexagonLoopIdiomRecognize::runOnCountableLoop(
Loop *L) {
2275 PolynomialMultiplyRecognize PMR(L, *
DL, *DT, *TLI, *SE);
2276 if (PMR.recognize())
2279 if (!HasMemcpy && !HasMemmove)
2282 const SCEV *BECount = SE->getBackedgeTakenCount(L);
2283 assert(!isa<SCEVCouldNotCompute>(BECount) &&
2284 "runOnCountableLoop() called on a loop without a predictable"
2285 "backedge-taken count");
2290 bool Changed =
false;
2295 if (LF->getLoopFor(BB) !=
L)
2297 Changed |= runOnLoopBlock(L, BB, BECount, ExitBlocks);
2319 if (Name ==
"memset" || Name ==
"memcpy" || Name ==
"memmove")
2322 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2323 DL = &L->
getHeader()->getModule()->getDataLayout();
2324 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2325 LF = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2326 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
2327 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2329 HasMemcpy = TLI->has(LibFunc_memcpy);
2330 HasMemmove = TLI->has(LibFunc_memmove);
2332 if (SE->hasLoopInvariantBackedgeTakenCount(L))
2333 return runOnCountableLoop(L);
2339 return new HexagonLoopIdiomRecognize();
Pass interface - Implemented by all 'passes'.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
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. ...
IntegerType * getType() const
getType - Specialize the getType() method to always return an IntegerType, which reduces the amount o...
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
This class is the base class for the comparison instructions.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
DenseMap< Value *, Value * > ValueMapType
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
void dropAllReferences()
Drop all references to operands.
bool isVolatile() const
Return true if this is a store to a volatile memory location.
Constant * getOrInsertFunction(StringRef Name, FunctionType *T, AttributeList AttributeList)
Look up the specified function in the module symbol table.
A Module instance is used to store all the information related to an LLVM module. ...
match_zero m_Zero()
Match an arbitrary zero/null constant.
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
This class represents zero extension of integer types.
unsigned getNumOperands() const
static cl::opt< bool > DisableMemmoveIdiom("disable-memmove-idiom", cl::Hidden, cl::init(false), cl::desc("Disable generation of memmove in loop idiom recognition"))
Context(Instruction *Exp)
The main scalar evolution driver.
This class represents a function call, abstracting a target machine's calling convention.
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Get a value with low bits set.
static PointerType * getInt32PtrTy(LLVMContext &C, unsigned AS=0)
static cl::opt< unsigned > CompileTimeMemSizeThreshold("compile-time-mem-idiom-threshold", cl::Hidden, cl::init(64), cl::desc("Threshold (in bytes) to perform the transformation, if the ""runtime loop count (mem transfer size) is known at compile-time."))
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
Externally visible function.
void deleteValue()
Delete a pointer to a generic Value.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
LoopT * getParentLoop() const
const Function * getParent() const
Return the enclosing method, or null if none.
static void cleanup(BlockFrequencyInfoImplBase &BFI)
Clear all memory not needed downstream.
An instruction for reading from memory.
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
iv Induction Variable Users
const std::vector< BlockT * > & getBlocks() const
Get a list of the basic blocks which make up this loop.
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
The access modifies the value stored in memory.
BlockT * getHeader() const
StringRef getName() const
Return a constant reference to the value's name.
iterator begin()
Instruction iterator methods.
bool match(Val *V, const Pattern &P)
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
INITIALIZE_PASS_BEGIN(HexagonLoopIdiomRecognize,"hexagon-loop-idiom","Recognize Hexagon-specific loop idioms", false, false) INITIALIZE_PASS_END(HexagonLoopIdiomRecognize
This class represents the LLVM 'select' instruction.
static const char * HexagonVolatileMemcpyName
bool isIdenticalTo(const Instruction *I) const
Return true if the specified instruction is exactly identical to the current one. ...
A Use represents the edge between a Value definition and its users.
PE(const Simplifier::Context &c, Value *v=nullptr)
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
static cl::opt< unsigned > RuntimeMemSizeThreshold("runtime-mem-idiom-threshold", cl::Hidden, cl::init(0), cl::desc("Threshold (in bytes) for the runtime ""check guarding the memmove."))
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
uint64_t getSignBit() const
Return a uint64_t with just the most significant bit set (the sign bit, if the value is treated as a ...
void setName(const Twine &Name)
Change the name of the value.
zlib-gnu style compression
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
User * getUser() const LLVM_READONLY
Returns the User that contains this Use.
void addRule(const Rule &R)
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
This node represents a polynomial recurrence on the trip count of the specified loop.
CastClass_match< OpTy, Instruction::ZExt > m_ZExt(const OpTy &Op)
Matches ZExt.
Base class for the actual dominator tree node.
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
An instruction for storing to memory.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
unsigned getNumIncomingValues() const
Return the number of incoming edges.
iterator_range< block_iterator > blocks() const
initializer< Ty > init(const Ty &Val)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
void initializeHexagonLoopIdiomRecognizePass(PassRegistry &)
unsigned getAlignment() const
Return the alignment of the access that is being performed.
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
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...
This is an important class for using LLVM in a threaded context.
Type * getType() const
Return the LLVM type of this SCEV expression.
This is an important base class in LLVM.
const Value * getCondition() const
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
const SCEV * getOperand(unsigned i) const
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
bool hasNoSignedWrap() const
Determine whether the no signed wrap flag is set.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
const Simplifier::Context & C
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...
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Represent the analysis usage information of a pass.
static Type * getVoidTy(LLVMContext &C)
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
const InstListType & getInstList() const
Return the underlying instruction list container.
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang","erlang-compatible garbage collector")
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
static const unsigned End
static bool mayLoopAccessLocation(Value *Ptr, ModRefInfo Access, Loop *L, const SCEV *BECount, unsigned StoreSize, AliasAnalysis &AA, SmallPtrSetImpl< Instruction * > &Ignored)
mayLoopAccessLocation - Return true if the specified loop might access the specified pointer location...
Value * getOperand(unsigned i) const
Interval::pred_iterator pred_end(Interval *I)
Value * getPointerOperand()
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
self_iterator getIterator()
Class to represent integer types.
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
static cl::opt< bool > OnlyNonNestedMemmove("only-nonnested-memmove-idiom", cl::Hidden, cl::init(true), cl::desc("Only enable generating memmove in non-nested loops"))
bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr)
If the specified value is a trivially dead instruction, delete it.
void getUniqueExitBlocks(SmallVectorImpl< BasicBlock * > &ExitBlocks) const
Return all unique successor blocks of this loop.
LLVMContext & getContext() const
All values hold a context through their type.
static void replaceAllUsesOfWithIn(Value *I, Value *J, BasicBlock *BB)
const Value * getTrueValue() const
Triple - Helper class for working with autoconf configuration names.
hexagon loop Recognize Hexagon specific loop idioms
static cl::opt< unsigned > SimplifyLimit("hlir-simplify-limit", cl::init(10000), cl::Hidden, cl::desc("Maximum number of simplification steps in HLIR"))
bool isTerminator() const
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Representation for a specific memory location.
BinaryOps getOpcode() const
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
This is the shared class of boolean and integer constants.
auto find(R &&Range, const T &Val) -> decltype(std::begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
void setIncomingBlock(unsigned i, BasicBlock *BB)
bool hasNoUnsignedWrap() const
Determine whether the no unsigned wrap flag is set.
void print(raw_ostream &OS, const Value *V) const
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
AnalysisUsage & addRequiredID(const void *ID)
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
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.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
CHAIN = SC CHAIN, Imm128 - System call.
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.
std::function< Value *(Instruction *, LLVMContext &)> Rule
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
void setLinkage(LinkageTypes LT)
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
void setOperand(unsigned i, Value *Val)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
static void initialize(TargetLibraryInfoImpl &TLI, const Triple &T, ArrayRef< StringRef > StandardNames)
initialize - Initialize the set of available library functions based on the specified target triple...
ModRefInfo getModRefInfo(ImmutableCallSite CS, const MemoryLocation &Loc)
getModRefInfo (for call sites) - Return information about whether a particular call site modifies or ...
bool isIntegerTy() const
True if this is an instance of IntegerType.
iterator_range< user_iterator > users()
static cl::opt< bool > DisableMemcpyIdiom("disable-memcpy-idiom", cl::Hidden, cl::init(false), cl::desc("Disable generation of memcpy in loop idiom recognition"))
This class uses information about analyze scalars to rewrite expressions in canonical form...
llvm_unreachable("Unknown RegBank!")
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
iterator insert(iterator where, pointer New)
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
This class represents an analyzed expression in the program.
static IntegerType * getInt32Ty(LLVMContext &C)
Represents a single loop in the control flow graph.
match_one m_One()
Match an integer 1 or a vector with all elements equal to 1.
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
bool hasOneUse() const
Return true if there is exactly one user of this value.
APFloat abs(APFloat X)
Returns the absolute value of the argument.
Pass * createHexagonLoopIdiomPass()
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
raw_ostream & operator<<(raw_ostream &OS, const APInt &I)
void mutateType(Type *Ty)
Mutate the type of this Value to be of the specified type.
OutputIt transform(R &&Range, OutputIt d_first, UnaryPredicate P)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere...
static int const Threshold
TODO: Write a new FunctionPass AliasAnalysis so that it can keep a cache.
cl::opt< bool > HexagonVolatileMemcpy("disable-hexagon-volatile-memcpy", cl::Hidden, cl::init(false), cl::desc("Enable Hexagon-specific memcpy for volatile destination."))
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
static const Function * getParent(const Value *V)
uint64_t getTypeSizeInBits(Type *Ty) const
Size examples:
This class implements an extremely fast bulk output stream that can only output to a stream...
static unsigned getStoreSizeInBytes(StoreInst *SI, const DataLayout *DL)
The legacy pass manager's analysis pass to compute loop information.
const Value * getFalseValue() const
StringRef - Represent a constant reference to a string, i.e.
static Expected< std::string > replace(StringRef S, StringRef From, StringRef To)
PassRegistry - This class manages the registration and intitialization of the pass subsystem as appli...
Legacy analysis pass which computes a DominatorTree.
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml","ocaml 3.10-compatible collector")
bool isSameOperationAs(const Instruction *I, unsigned flags=0) const
This function determines if the specified instruction executes the same operation as the current one...
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
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...
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
Value * getPointerOperand()
void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, OptimizationRemarkEmitter *ORE=nullptr)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
const BasicBlock * getParent() const
This class represents a constant integer value.
CmpClass_match< LHS, RHS, ICmpInst, ICmpInst::Predicate > m_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R)
hexagon loop Recognize Hexagon specific loop false
void setIDom(DomTreeNodeBase *NewIDom)
#define LLVM_ATTRIBUTE_USED