65 using namespace llvm::PatternMatch;
67 #define DEBUG_TYPE "codegenprepare"
69 STATISTIC(NumBlocksElim,
"Number of blocks eliminated");
70 STATISTIC(NumPHIsElim,
"Number of trivial PHIs eliminated");
71 STATISTIC(NumGEPsElim,
"Number of GEPs converted to casts");
72 STATISTIC(NumCmpUses,
"Number of uses of Cmp expressions replaced with uses of "
74 STATISTIC(NumCastUses,
"Number of uses of Cast expressions replaced with uses "
76 STATISTIC(NumMemoryInsts,
"Number of memory instructions whose address "
77 "computations were sunk");
78 STATISTIC(NumExtsMoved,
"Number of [s|z]ext instructions combined with loads");
79 STATISTIC(NumExtUses,
"Number of uses of [s|z]ext instructions optimized");
81 "Number of and mask instructions added to form ext loads");
82 STATISTIC(NumAndUses,
"Number of uses of and mask instructions optimized");
83 STATISTIC(NumRetsDup,
"Number of return instructions duplicated");
84 STATISTIC(NumDbgValueMoved,
"Number of debug value instructions moved");
85 STATISTIC(NumSelectsExpanded,
"Number of selects turned into branches");
86 STATISTIC(NumStoreExtractExposed,
"Number of store(extractelement) exposed");
88 STATISTIC(NumMemCmpCalls,
"Number of memcmp calls");
89 STATISTIC(NumMemCmpNotConstant,
"Number of memcmp calls without constant size");
91 "Number of memcmp calls with size greater than max size");
92 STATISTIC(NumMemCmpInlined,
"Number of inlined memcmp calls");
96 cl::desc(
"Disable branch optimizations in CodeGenPrepare"));
100 cl::desc(
"Disable GC optimizations in CodeGenPrepare"));
104 cl::desc(
"Disable select to branch conversion."));
108 cl::desc(
"Address sinking in CGP using GEPs."));
112 cl::desc(
"Enable sinkinig and/cmp into branches."));
116 cl::desc(
"Disable store(extract) optimizations in CodeGenPrepare"));
120 cl::desc(
"Stress test store(extract) optimizations in CodeGenPrepare"));
124 cl::desc(
"Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
129 cl::desc(
"Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
130 "optimization in CodeGenPrepare"));
134 cl::desc(
"Disable protection against removing loop preheaders"));
138 cl::desc(
"Use profile info to add section prefix for hot/cold functions"));
142 cl::desc(
"Skip merging empty blocks if (frequency of empty block) / "
143 "(frequency of destination block) is greater than this ratio"));
147 cl::desc(
"Force store splitting no matter what the target query says."));
151 cl::desc(
"Enable merging of redundant sexts when one is dominating"
156 cl::desc(
"The number of loads per basic block for inline expansion of "
157 "memcmp that is only being compared against zero."));
165 class TypePromotionTransaction;
175 std::unique_ptr<BlockFrequencyInfo>
BFI;
176 std::unique_ptr<BranchProbabilityInfo> BPI;
188 SetOfInstrs InsertedInsts;
191 InstrToOrigTy PromotedInsts;
194 SetOfInstrs RemovedInsts;
200 ValueToSExts ValToSExtendedUses;
218 bool runOnFunction(
Function &
F)
override;
220 StringRef getPassName()
const override {
return "CodeGen Prepare"; }
232 bool eliminateMostlyEmptyBlocks(
Function &
F);
235 void eliminateMostlyEmptyBlock(
BasicBlock *BB);
238 bool optimizeBlock(
BasicBlock &BB,
bool &ModifiedDT);
241 Type *AccessTy,
unsigned AS);
242 bool optimizeInlineAsmInst(
CallInst *CS);
243 bool optimizeCallInst(
CallInst *CI,
bool &ModifiedDT);
250 bool optimizeExtractElementInst(
Instruction *Inst);
251 bool dupRetToEnableTailCallOpts(
BasicBlock *BB);
255 bool tryToPromoteExts(TypePromotionTransaction &TPT,
258 unsigned CreatedInstsCost = 0);
260 bool performAddressTypePromotion(
262 bool AllowPromotionWithoutCommonHeader,
263 bool HasPromoted, TypePromotionTransaction &TPT,
267 bool splitIndirectCriticalEdges(
Function &
F);
273 "Optimize for code generation",
false,
false)
280 bool CodeGenPrepare::runOnFunction(
Function &
F) {
286 bool EverMadeChange =
false;
288 InsertedInsts.clear();
289 PromotedInsts.clear();
294 if (
auto *
TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
296 SubtargetInfo =
TM->getSubtargetImpl(F);
297 TLI = SubtargetInfo->getTargetLowering();
298 TRI = SubtargetInfo->getRegisterInfo();
300 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
301 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
302 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
307 getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
316 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
318 TLI->getBypassSlowDivWidths();
320 while (BB !=
nullptr) {
331 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
336 EverMadeChange |= placeDbgValues(F);
339 EverMadeChange |= splitBranchCondition(F);
343 EverMadeChange |= splitIndirectCriticalEdges(F);
345 bool MadeChange =
true;
348 SeenChainsForSExt.clear();
349 ValToSExtendedUses.clear();
350 RemovedInsts.clear();
353 bool ModifiedDTOnIteration =
false;
354 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
357 if (ModifiedDTOnIteration)
361 MadeChange |= mergeSExts(F);
367 EverMadeChange |= MadeChange;
378 if (!MadeChange)
continue;
381 II = Successors.begin(),
IE = Successors.end(); II !=
IE; ++II)
387 MadeChange |= !WorkList.
empty();
388 while (!WorkList.
empty()) {
396 II = Successors.begin(),
IE = Successors.end(); II !=
IE; ++II)
403 if (EverMadeChange || MadeChange)
404 MadeChange |= eliminateFallThrough(F);
406 EverMadeChange |= MadeChange;
415 for (
auto &
I : Statepoints)
416 EverMadeChange |= simplifyOffsetableRelocate(*
I);
419 return EverMadeChange;
425 bool CodeGenPrepare::eliminateFallThrough(
Function &F) {
426 bool Changed =
false;
435 if (!SinglePred || SinglePred == BB || BB->
hasAddressTaken())
continue;
440 DEBUG(
dbgs() <<
"To merge:\n"<< *SinglePred <<
"\n\n\n");
466 if (BBI != BB->
begin()) {
468 while (isa<DbgInfoIntrinsic>(BBI)) {
469 if (BBI == BB->
begin())
473 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
482 if (!canMergeBlocks(BB, DestBB))
508 case Instruction::IndirectBr:
513 case Instruction::Br:
543 bool CodeGenPrepare::splitIndirectCriticalEdges(
Function &F) {
553 for (
unsigned Succ = 0,
E = IBI->getNumSuccessors(); Succ !=
E; ++Succ)
554 Targets.
insert(IBI->getSuccessor(Succ));
560 bool Changed =
false;
566 if (!IBRPred || OtherPreds.
empty())
592 Pred->getTerminator()->replaceUsesOfWith(
Target, DirectSucc);
601 End =
Target->getFirstNonPHI()->getIterator();
606 "Block was expected to only contain PHIs");
608 while (Indirect !=
End) {
609 PHINode *DirPHI = cast<PHINode>(Direct);
610 PHINode *IndPHI = cast<PHINode>(Indirect);
622 NewIndPHI->
addIncoming(IndPHI->getIncomingValueForBlock(IBRPred),
632 IndPHI->replaceAllUsesWith(MergePHI);
633 IndPHI->eraseFromParent();
646 bool CodeGenPrepare::eliminateMostlyEmptyBlocks(
Function &F) {
649 while (!LoopList.empty()) {
650 Loop *
L = LoopList.pop_back_val();
651 LoopList.insert(LoopList.end(), L->
begin(), L->
end());
653 Preheaders.
insert(Preheader);
656 bool MadeChange =
false;
660 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
662 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.
count(BB)))
665 eliminateMostlyEmptyBlock(BB);
671 bool CodeGenPrepare::isMergingEmptyBlockProfitable(
BasicBlock *BB,
711 if (!isa<PHINode>(DestBB->
begin()))
721 if (DestBBPred == BB)
724 bool HasAllSameValue =
true;
726 while (
const PHINode *DestPN = dyn_cast<PHINode>(DestBBI++)) {
727 if (DestPN->getIncomingValueForBlock(BB) !=
728 DestPN->getIncomingValueForBlock(DestBBPred)) {
729 HasAllSameValue =
false;
734 SameIncomingValueBBs.
insert(DestBBPred);
740 if (SameIncomingValueBBs.
count(Pred))
753 for (
auto SameValueBB : SameIncomingValueBBs)
754 if (SameValueBB->getUniquePredecessor() == Pred &&
755 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
756 BBFreq +=
BFI->getBlockFreq(SameValueBB);
765 bool CodeGenPrepare::canMergeBlocks(
const BasicBlock *BB,
771 while (
const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
774 if (UI->
getParent() != DestBB || !isa<PHINode>(UI))
780 if (
const PHINode *UPN = dyn_cast<PHINode>(UI))
781 for (
unsigned I = 0,
E = UPN->getNumIncomingValues();
I !=
E; ++
I) {
784 Insn->
getParent() != UPN->getIncomingBlock(
I))
795 if (!DestBBPN)
return true;
799 if (
const PHINode *BBPN = dyn_cast<PHINode>(BB->
begin())) {
801 for (
unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
802 BBPreds.
insert(BBPN->getIncomingBlock(i));
810 if (BBPreds.
count(Pred)) {
811 BBI = DestBB->
begin();
812 while (
const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
813 const Value *V1 = PN->getIncomingValueForBlock(Pred);
814 const Value *
V2 = PN->getIncomingValueForBlock(BB);
817 if (
const PHINode *V2PN = dyn_cast<PHINode>(V2))
818 if (V2PN->getParent() == BB)
819 V2 = V2PN->getIncomingValueForBlock(Pred);
822 if (V1 != V2)
return false;
833 void CodeGenPrepare::eliminateMostlyEmptyBlock(
BasicBlock *BB) {
837 DEBUG(
dbgs() <<
"MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
842 if (SinglePred != DestBB) {
851 DEBUG(
dbgs() <<
"AFTER:\n" << *DestBB <<
"\n\n\n");
867 if (InValPhi && InValPhi->
getParent() == BB) {
876 for (
unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
891 DEBUG(
dbgs() <<
"AFTER:\n" << *DestBB <<
"\n\n\n");
904 for (
auto *ThisRelocate : AllRelocateCalls) {
905 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
906 ThisRelocate->getDerivedPtrIndex());
907 RelocateIdxMap.
insert(std::make_pair(K, ThisRelocate));
909 for (
auto &Item : RelocateIdxMap) {
910 std::pair<unsigned, unsigned> Key = Item.first;
911 if (Key.first == Key.second)
916 auto BaseKey = std::make_pair(Key.first, Key.first);
919 auto MaybeBase = RelocateIdxMap.find(BaseKey);
920 if (MaybeBase == RelocateIdxMap.end())
925 RelocateInstMap[MaybeBase->second].push_back(I);
936 if (!
Op ||
Op->getZExtValue() > 20)
950 bool MadeChange =
false;
953 "Not relocating a derived object of the original base object");
954 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
969 if (!Derived || Derived->getPointerOperand() != Base)
978 "Should always have one since it's not a terminator");
1005 Value *ActualRelocatedBase = RelocatedBase;
1007 ActualRelocatedBase =
1008 Builder.CreateBitCast(RelocatedBase, Base->
getType());
1010 Value *Replacement = Builder.CreateGEP(
1011 Derived->getSourceElementType(), ActualRelocatedBase,
makeArrayRef(OffsetV));
1015 Value *ActualReplacement = Replacement;
1016 if (Replacement->
getType() != ToReplace->getType()) {
1018 Builder.CreateBitCast(Replacement, ToReplace->
getType());
1021 ToReplace->eraseFromParent();
1045 bool CodeGenPrepare::simplifyOffsetableRelocate(
Instruction &
I) {
1046 bool MadeChange =
false;
1049 for (
auto *U : I.
users())
1056 if (AllRelocateCalls.
size() < 2)
1063 if (RelocateInstMap.
empty())
1066 for (
auto &Item : RelocateInstMap)
1080 bool MadeChange =
false;
1083 Use &TheUse = UI.getUse();
1089 if (
PHINode *PN = dyn_cast<PHINode>(User)) {
1108 if (UserBB == DefBB)
continue;
1111 CastInst *&InsertedCast = InsertedCasts[UserBB];
1113 if (!InsertedCast) {
1117 CI->
getType(),
"", &*InsertPt);
1121 TheUse = InsertedCast;
1145 if (
auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
1147 ASC->getDestAddressSpace()))
1161 if (SrcVT.
bitsLT(DstVT))
return false;
1192 if (!isa<IntegerType>(Ty))
1212 auto *InsertPt = AddI->
hasOneUse() ? CI : AddI;
1214 auto *UAddWithOverflow =
1243 bool MadeChange =
false;
1246 Use &TheUse = UI.getUse();
1253 if (isa<PHINode>(User))
1260 if (UserBB == DefBB)
continue;
1263 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1276 TheUse = InsertedCmp;
1307 SetOfInstrs &InsertedInsts) {
1310 assert(!InsertedInsts.count(AndI) &&
1311 "Attempting to optimize already optimized and instruction");
1312 (void) InsertedInsts;
1321 if (!isa<ConstantInt>(AndI->
getOperand(0)) &&
1326 for (
auto *U : AndI->
users()) {
1330 if (!isa<ICmpInst>(User))
1334 if (!CmpC || !CmpC->isZero())
1341 DEBUG(
dbgs() <<
"found 'and' feeding only icmp 0;\n");
1349 Use &TheUse = UI.getUse();
1355 DEBUG(
dbgs() <<
"sinking 'and' use: " << *User <<
"\n");
1367 TheUse = InsertedAnd;
1383 if (!isa<TruncInst>(User)) {
1384 if (User->
getOpcode() != Instruction::And ||
1388 const APInt &Cimm = cast<ConstantInt>(User->
getOperand(1))->getValue();
1390 if ((Cimm & (Cimm + 1)).getBoolValue())
1404 bool MadeChange =
false;
1408 TruncUI != TruncE;) {
1410 Use &TruncTheUse = TruncUI.getUse();
1411 Instruction *TruncUser = cast<Instruction>(*TruncUI);
1430 if (isa<PHINode>(TruncUser))
1435 if (UserBB == TruncUserBB)
1439 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1441 if (!InsertedShift && !InsertedTrunc) {
1445 if (ShiftI->
getOpcode() == Instruction::AShr)
1446 InsertedShift = BinaryOperator::CreateAShr(ShiftI->
getOperand(0), CI,
1449 InsertedShift = BinaryOperator::CreateLShr(ShiftI->
getOperand(0), CI,
1455 assert(TruncInsertPt != TruncUserBB->
end());
1458 TruncI->
getType(),
"", &*TruncInsertPt);
1462 TruncTheUse = InsertedTrunc;
1495 bool MadeChange =
false;
1498 Use &TheUse = UI.getUse();
1504 if (isa<PHINode>(User))
1512 if (UserBB == DefBB) {
1527 if (isa<TruncInst>(User) && shiftIsLegal
1540 if (!InsertedShift) {
1544 if (ShiftI->
getOpcode() == Instruction::AShr)
1545 InsertedShift = BinaryOperator::CreateAShr(ShiftI->
getOperand(0), CI,
1548 InsertedShift = BinaryOperator::CreateLShr(ShiftI->
getOperand(0), CI,
1555 TheUse = InsertedShift;
1618 Builder.SetCurrentDebugLocation(CountZeros->
getDebugLoc());
1624 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
1629 Builder.SetInsertPoint(&EndBlock->
front());
1630 PHINode *PN = Builder.CreatePHI(Ty, 2,
"ctz");
1632 Value *BitWidth = Builder.getInt(
APInt(SizeInBits, SizeInBits));
1647 struct ResultBlock {
1655 ResultBlock ResBlock;
1656 unsigned MaxLoadSize;
1658 unsigned NumBlocksNonOneByte;
1659 unsigned NumLoadsPerBlock;
1660 std::vector<BasicBlock *> LoadCmpBlocks;
1663 bool IsUsedForZeroCmp;
1667 unsigned calculateNumBlocks(
unsigned Size);
1668 void createLoadCmpBlocks();
1669 void createResultBlock();
1670 void setupResultBlockPHINodes();
1671 void setupEndBlockPHINodes();
1672 void emitLoadCompareBlock(
unsigned Index,
unsigned LoadSize,
1674 Value *getCompareLoadPairs(
unsigned Index,
unsigned Size,
1675 unsigned &NumBytesProcessed);
1676 void emitLoadCompareBlockMultipleLoads(
unsigned Index,
unsigned Size,
1677 unsigned &NumBytesProcessed);
1678 void emitLoadCompareByteBlock(
unsigned Index,
unsigned GEPIndex);
1679 void emitMemCmpResultBlock();
1680 Value *getMemCmpExpansionZeroCase(
unsigned Size);
1681 Value *getMemCmpEqZeroOneBlock(
unsigned Size);
1682 Value *getMemCmpOneBlock(
unsigned Size);
1683 unsigned getLoadSize(
unsigned Size);
1684 unsigned getNumLoads(
unsigned Size);
1689 Value *getMemCmpExpansion(uint64_t Size);
1692 MemCmpExpansion::ResultBlock::ResultBlock()
1693 : BB(nullptr), PhiSrc1(nullptr), PhiSrc2(nullptr) {}
1704 unsigned MaxLoadSize,
unsigned LoadsPerBlock,
1706 : CI(CI), MaxLoadSize(MaxLoadSize), NumLoadsPerBlock(LoadsPerBlock),
1707 DL(TheDataLayout), Builder(CI) {
1714 NumBlocks = calculateNumBlocks(Size);
1715 if ((!IsUsedForZeroCmp && NumLoadsPerBlock != 1) || NumBlocks != 1) {
1718 setupEndBlockPHINodes();
1719 createResultBlock();
1725 if (!IsUsedForZeroCmp)
1726 setupResultBlockPHINodes();
1729 createLoadCmpBlocks();
1739 void MemCmpExpansion::createLoadCmpBlocks() {
1740 for (
unsigned i = 0; i < NumBlocks; i++) {
1743 LoadCmpBlocks.push_back(BB);
1747 void MemCmpExpansion::createResultBlock() {
1748 ResBlock.BB = BasicBlock::Create(CI->
getContext(),
"res_block",
1756 void MemCmpExpansion::emitLoadCompareByteBlock(
unsigned Index,
1757 unsigned GEPIndex) {
1764 if (Source1->
getType() != LoadSizeType)
1766 if (Source2->
getType() != LoadSizeType)
1770 if (GEPIndex != 0) {
1771 Source1 = Builder.
CreateGEP(LoadSizeType, Source1,
1772 ConstantInt::get(LoadSizeType, GEPIndex));
1773 Source2 = Builder.
CreateGEP(LoadSizeType, Source2,
1774 ConstantInt::get(LoadSizeType, GEPIndex));
1786 if (Index < (LoadCmpBlocks.size() - 1)) {
1790 ConstantInt::get(Diff->
getType(), 0));
1792 BranchInst::Create(EndBlock, LoadCmpBlocks[Index + 1], Cmp);
1796 BranchInst *CmpBr = BranchInst::Create(EndBlock);
1801 unsigned MemCmpExpansion::getNumLoads(
unsigned Size) {
1805 unsigned MemCmpExpansion::getLoadSize(
unsigned Size) {
1812 Value *MemCmpExpansion::getCompareLoadPairs(
unsigned Index,
unsigned Size,
1813 unsigned &NumBytesProcessed) {
1814 std::vector<Value *> XorList, OrList;
1817 unsigned RemainingBytes = Size - NumBytesProcessed;
1818 unsigned NumLoadsRemaining = getNumLoads(RemainingBytes);
1819 unsigned NumLoads =
std::min(NumLoadsRemaining, NumLoadsPerBlock);
1822 if (LoadCmpBlocks.empty())
1827 Value *Cmp =
nullptr;
1828 for (
unsigned i = 0; i < NumLoads; ++i) {
1829 unsigned LoadSize = getLoadSize(RemainingBytes);
1830 unsigned GEPIndex = NumBytesProcessed / LoadSize;
1831 NumBytesProcessed += LoadSize;
1832 RemainingBytes -= LoadSize;
1834 Type *LoadSizeType = IntegerType::get(CI->
getContext(), LoadSize * 8);
1835 Type *MaxLoadType = IntegerType::get(CI->
getContext(), MaxLoadSize * 8);
1836 assert(LoadSize <= MaxLoadSize &&
"Unexpected load type");
1842 if (Source1->
getType() != LoadSizeType)
1844 if (Source2->
getType() != LoadSizeType)
1848 if (GEPIndex != 0) {
1849 Source1 = Builder.
CreateGEP(LoadSizeType, Source1,
1850 ConstantInt::get(LoadSizeType, GEPIndex));
1851 Source2 = Builder.
CreateGEP(LoadSizeType, Source2,
1852 ConstantInt::get(LoadSizeType, GEPIndex));
1856 Value *LoadSrc1 =
nullptr;
1857 if (
auto *Source1C = dyn_cast<Constant>(Source1))
1860 LoadSrc1 = Builder.
CreateLoad(LoadSizeType, Source1);
1862 Value *LoadSrc2 =
nullptr;
1863 if (
auto *Source2C = dyn_cast<Constant>(Source2))
1866 LoadSrc2 = Builder.
CreateLoad(LoadSizeType, Source2);
1868 if (NumLoads != 1) {
1869 if (LoadSizeType != MaxLoadType) {
1870 LoadSrc1 = Builder.
CreateZExt(LoadSrc1, MaxLoadType);
1871 LoadSrc2 = Builder.
CreateZExt(LoadSrc2, MaxLoadType);
1875 Diff = Builder.
CreateXor(LoadSrc1, LoadSrc2);
1876 Diff = Builder.
CreateZExt(Diff, MaxLoadType);
1877 XorList.push_back(Diff);
1884 auto pairWiseOr = [&](std::vector<Value *> &InList) -> std::vector<Value *> {
1885 std::vector<Value *> OutList;
1886 for (
unsigned i = 0; i < InList.size() - 1; i = i + 2) {
1888 OutList.push_back(Or);
1890 if (InList.size() % 2 != 0)
1891 OutList.push_back(InList.back());
1897 OrList = pairWiseOr(XorList);
1900 while (OrList.size() != 1) {
1901 OrList = pairWiseOr(OrList);
1909 void MemCmpExpansion::emitLoadCompareBlockMultipleLoads(
1910 unsigned Index,
unsigned Size,
unsigned &NumBytesProcessed) {
1911 Value *Cmp = getCompareLoadPairs(Index, Size, NumBytesProcessed);
1913 BasicBlock *NextBB = (Index == (LoadCmpBlocks.size() - 1))
1915 : LoadCmpBlocks[Index + 1];
1918 BranchInst *CmpBr = BranchInst::Create(ResBlock.BB, NextBB, Cmp);
1924 if (Index == LoadCmpBlocks.size() - 1) {
1939 void MemCmpExpansion::emitLoadCompareBlock(
unsigned Index,
unsigned LoadSize,
1940 unsigned GEPIndex) {
1941 if (LoadSize == 1) {
1942 MemCmpExpansion::emitLoadCompareByteBlock(Index, GEPIndex);
1946 Type *LoadSizeType = IntegerType::get(CI->
getContext(), LoadSize * 8);
1947 Type *MaxLoadType = IntegerType::get(CI->
getContext(), MaxLoadSize * 8);
1948 assert(LoadSize <= MaxLoadSize &&
"Unexpected load type");
1955 if (Source1->
getType() != LoadSizeType)
1957 if (Source2->
getType() != LoadSizeType)
1961 if (GEPIndex != 0) {
1962 Source1 = Builder.
CreateGEP(LoadSizeType, Source1,
1963 ConstantInt::get(LoadSizeType, GEPIndex));
1964 Source2 = Builder.
CreateGEP(LoadSizeType, Source2,
1965 ConstantInt::get(LoadSizeType, GEPIndex));
1974 Intrinsic::bswap, LoadSizeType);
1975 LoadSrc1 = Builder.
CreateCall(Bswap, LoadSrc1);
1976 LoadSrc2 = Builder.
CreateCall(Bswap, LoadSrc2);
1979 if (LoadSizeType != MaxLoadType) {
1980 LoadSrc1 = Builder.
CreateZExt(LoadSrc1, MaxLoadType);
1981 LoadSrc2 = Builder.
CreateZExt(LoadSrc2, MaxLoadType);
1986 if (!IsUsedForZeroCmp) {
1987 ResBlock.PhiSrc1->addIncoming(LoadSrc1, LoadCmpBlocks[Index]);
1988 ResBlock.PhiSrc2->addIncoming(LoadSrc2, LoadCmpBlocks[Index]);
1991 Value *Cmp = Builder.
CreateICmp(ICmpInst::ICMP_EQ, LoadSrc1, LoadSrc2);
1992 BasicBlock *NextBB = (Index == (LoadCmpBlocks.size() - 1))
1994 : LoadCmpBlocks[Index + 1];
1997 BranchInst *CmpBr = BranchInst::Create(NextBB, ResBlock.BB, Cmp);
2003 if (Index == LoadCmpBlocks.size() - 1) {
2004 Value *Zero = ConstantInt::get(Type::getInt32Ty(CI->
getContext()), 0);
2012 void MemCmpExpansion::emitMemCmpResultBlock() {
2015 if (IsUsedForZeroCmp) {
2020 BranchInst *NewBr = BranchInst::Create(EndBlock);
2034 BranchInst *NewBr = BranchInst::Create(EndBlock);
2039 unsigned MemCmpExpansion::calculateNumBlocks(
unsigned Size) {
2040 unsigned NumBlocks = 0;
2041 bool HaveOneByteLoad =
false;
2042 unsigned RemainingSize =
Size;
2043 unsigned LoadSize = MaxLoadSize;
2044 while (RemainingSize) {
2046 HaveOneByteLoad =
true;
2047 NumBlocks += RemainingSize / LoadSize;
2048 RemainingSize = RemainingSize % LoadSize;
2049 LoadSize = LoadSize / 2;
2051 NumBlocksNonOneByte = HaveOneByteLoad ? (NumBlocks - 1) : NumBlocks;
2053 if (IsUsedForZeroCmp)
2054 NumBlocks = NumBlocks / NumLoadsPerBlock +
2055 (NumBlocks % NumLoadsPerBlock != 0 ? 1 : 0);
2060 void MemCmpExpansion::setupResultBlockPHINodes() {
2061 Type *MaxLoadType = IntegerType::get(CI->
getContext(), MaxLoadSize * 8);
2064 Builder.
CreatePHI(MaxLoadType, NumBlocksNonOneByte,
"phi.src1");
2066 Builder.
CreatePHI(MaxLoadType, NumBlocksNonOneByte,
"phi.src2");
2069 void MemCmpExpansion::setupEndBlockPHINodes() {
2074 Value *MemCmpExpansion::getMemCmpExpansionZeroCase(
unsigned Size) {
2075 unsigned NumBytesProcessed = 0;
2078 for (
unsigned i = 0; i < NumBlocks; ++i)
2079 emitLoadCompareBlockMultipleLoads(i, Size, NumBytesProcessed);
2081 emitMemCmpResultBlock();
2088 Value *MemCmpExpansion::getMemCmpEqZeroOneBlock(
unsigned Size) {
2089 unsigned NumBytesProcessed = 0;
2090 Value *Cmp = getCompareLoadPairs(0, Size, NumBytesProcessed);
2096 Value *MemCmpExpansion::getMemCmpOneBlock(
unsigned Size) {
2097 assert(NumLoadsPerBlock == 1 &&
"Only handles one load pair per block");
2099 Type *LoadSizeType = IntegerType::get(CI->
getContext(), Size * 8);
2104 if (Source1->getType() != LoadSizeType)
2106 if (Source2->
getType() != LoadSizeType)
2115 Intrinsic::bswap, LoadSizeType);
2116 LoadSrc1 = Builder.
CreateCall(Bswap, LoadSrc1);
2117 LoadSrc2 = Builder.
CreateCall(Bswap, LoadSrc2);
2125 ConstantInt::get(I32, 1));
2126 return Builder.
CreateSelect(CmpNE, Sel1, ConstantInt::get(I32, 0));
2132 if (IsUsedForZeroCmp)
2133 return NumBlocks == 1 ? getMemCmpEqZeroOneBlock(Size) :
2134 getMemCmpExpansionZeroCase(Size);
2137 if (NumBlocks == 1 && NumLoadsPerBlock == 1)
2138 return getMemCmpOneBlock(Size);
2144 unsigned LoadSize = MaxLoadSize;
2145 unsigned NumBytesToBeProcessed =
Size;
2147 while (NumBytesToBeProcessed) {
2149 unsigned NumBlocks = NumBytesToBeProcessed / LoadSize;
2150 unsigned GEPIndex = (Size - NumBytesToBeProcessed) / LoadSize;
2151 NumBytesToBeProcessed = NumBytesToBeProcessed % LoadSize;
2155 while (NumBlocks--) {
2156 emitLoadCompareBlock(Index, LoadSize, GEPIndex);
2161 LoadSize = LoadSize / 2;
2164 emitMemCmpResultBlock();
2247 unsigned MaxLoadSize;
2258 NumMemCmpNotConstant++;
2264 unsigned NumLoads = 0;
2265 unsigned RemainingSize = SizeVal;
2266 unsigned LoadSize = MaxLoadSize;
2267 while (RemainingSize) {
2268 NumLoads += RemainingSize / LoadSize;
2269 RemainingSize = RemainingSize % LoadSize;
2270 LoadSize = LoadSize / 2;
2274 NumMemCmpGreaterThanMax++;
2283 MemCmpExpansion MemCmpHelper(CI, SizeVal, MaxLoadSize, NumLoadsPerBlock, *DL);
2294 bool CodeGenPrepare::optimizeCallInst(
CallInst *CI,
bool &ModifiedDT) {
2301 if (TLI->ExpandInlineAsm(CI)) {
2303 CurInstIterator = BB->
begin();
2310 if (optimizeInlineAsmInst(CI))
2316 unsigned MinSize, PrefAlign;
2317 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
2323 if (!Arg->getType()->isPointerTy())
2326 cast<PointerType>(Arg->getType())->getAddressSpace()),
2329 uint64_t Offset2 =
Offset.getLimitedValue();
2330 if ((Offset2 & (PrefAlign-1)) != 0)
2333 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->
getAlignment() < PrefAlign &&
2353 if (Align >
MI->getAlignment())
2354 MI->setAlignment(ConstantInt::get(
MI->getAlignmentType(),
Align));
2364 if (!Arg->getType()->isPointerTy())
2366 unsigned AS = Arg->getType()->getPointerAddressSpace();
2367 return optimizeMemoryInst(CI, Arg, Arg->
getType(), AS);
2374 case Intrinsic::objectsize: {
2382 Value *CurValue = &*CurInstIterator;
2389 if (IterHandle != CurValue) {
2390 CurInstIterator = BB->
begin();
2395 case Intrinsic::aarch64_stlxr:
2396 case Intrinsic::aarch64_stxr: {
2405 InsertedInsts.insert(ExtVal);
2408 case Intrinsic::invariant_group_barrier:
2413 case Intrinsic::cttz:
2414 case Intrinsic::ctlz:
2422 if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
2423 while (!PtrOps.
empty()) {
2426 if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
2440 if (
Value *V = Simplifier.optimizeCall(CI)) {
2485 bool CodeGenPrepare::dupRetToEnableTailCallOpts(
BasicBlock *BB) {
2513 do { ++BI; }
while (isa<DbgInfoIntrinsic>(BI));
2521 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
2535 TLI->mayBeEmittedAsTailCall(CI) &&
2542 if (!VisitedBBs.
insert(*PI).second)
2546 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
2547 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
2548 do { ++RI; }
while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
2553 if (CI && CI->
use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
2559 bool Changed =
false;
2560 for (
unsigned i = 0, e = TailCalls.
size(); i != e; ++i) {
2567 if (
AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
2569 AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
2582 ModifiedDT = Changed =
true;
2604 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
2608 bool operator==(
const ExtAddrMode& O)
const {
2609 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
2610 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
2611 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
2623 bool NeedPlus =
false;
2626 OS << (NeedPlus ?
" + " :
"")
2628 BaseGV->printAsOperand(OS,
false);
2633 OS << (NeedPlus ?
" + " :
"")
2639 OS << (NeedPlus ?
" + " :
"")
2641 BaseReg->printAsOperand(OS,
false);
2645 OS << (NeedPlus ?
" + " :
"")
2647 ScaledReg->printAsOperand(OS,
false);
2653 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2663 class TypePromotionTransaction {
2668 class TypePromotionAction {
2676 TypePromotionAction(
Instruction *Inst) : Inst(Inst) {}
2678 virtual ~TypePromotionAction() {}
2685 virtual void undo() = 0;
2690 virtual void commit() {
2696 class InsertionHandler {
2706 bool HasPrevInstruction;
2713 if (HasPrevInstruction)
2714 Point.PrevInst = &*--It;
2721 if (HasPrevInstruction) {
2726 Instruction *Position = &*Point.BB->getFirstInsertionPt();
2736 class InstructionMoveBefore :
public TypePromotionAction {
2738 InsertionHandler Position;
2743 : TypePromotionAction(Inst), Position(Inst) {
2744 DEBUG(
dbgs() <<
"Do: move: " << *Inst <<
"\nbefore: " << *Before <<
"\n");
2749 void undo()
override {
2750 DEBUG(
dbgs() <<
"Undo: moveBefore: " << *Inst <<
"\n");
2751 Position.insert(Inst);
2756 class OperandSetter :
public TypePromotionAction {
2765 : TypePromotionAction(Inst), Idx(Idx) {
2766 DEBUG(
dbgs() <<
"Do: setOperand: " << Idx <<
"\n"
2767 <<
"for:" << *Inst <<
"\n"
2768 <<
"with:" << *NewVal <<
"\n");
2774 void undo()
override {
2775 DEBUG(
dbgs() <<
"Undo: setOperand:" << Idx <<
"\n"
2776 <<
"for: " << *Inst <<
"\n"
2777 <<
"with: " << *Origin <<
"\n");
2784 class OperandsHider :
public TypePromotionAction {
2790 OperandsHider(
Instruction *Inst) : TypePromotionAction(Inst) {
2791 DEBUG(
dbgs() <<
"Do: OperandsHider: " << *Inst <<
"\n");
2793 OriginalValues.reserve(NumOpnds);
2794 for (
unsigned It = 0; It < NumOpnds; ++It) {
2797 OriginalValues.push_back(Val);
2806 void undo()
override {
2807 DEBUG(
dbgs() <<
"Undo: OperandsHider: " << *Inst <<
"\n");
2808 for (
unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2814 class TruncBuilder :
public TypePromotionAction {
2820 TruncBuilder(
Instruction *Opnd,
Type *Ty) : TypePromotionAction(Opnd) {
2822 Val = Builder.CreateTrunc(Opnd, Ty,
"promoted");
2823 DEBUG(
dbgs() <<
"Do: TruncBuilder: " << *Val <<
"\n");
2827 Value *getBuiltValue() {
return Val; }
2830 void undo()
override {
2831 DEBUG(
dbgs() <<
"Undo: TruncBuilder: " << *Val <<
"\n");
2832 if (
Instruction *IVal = dyn_cast<Instruction>(Val))
2833 IVal->eraseFromParent();
2838 class SExtBuilder :
public TypePromotionAction {
2845 : TypePromotionAction(InsertPt) {
2847 Val = Builder.CreateSExt(Opnd, Ty,
"promoted");
2848 DEBUG(
dbgs() <<
"Do: SExtBuilder: " << *Val <<
"\n");
2852 Value *getBuiltValue() {
return Val; }
2855 void undo()
override {
2856 DEBUG(
dbgs() <<
"Undo: SExtBuilder: " << *Val <<
"\n");
2857 if (
Instruction *IVal = dyn_cast<Instruction>(Val))
2858 IVal->eraseFromParent();
2863 class ZExtBuilder :
public TypePromotionAction {
2870 : TypePromotionAction(InsertPt) {
2872 Val = Builder.CreateZExt(Opnd, Ty,
"promoted");
2873 DEBUG(
dbgs() <<
"Do: ZExtBuilder: " << *Val <<
"\n");
2877 Value *getBuiltValue() {
return Val; }
2880 void undo()
override {
2881 DEBUG(
dbgs() <<
"Undo: ZExtBuilder: " << *Val <<
"\n");
2882 if (
Instruction *IVal = dyn_cast<Instruction>(Val))
2883 IVal->eraseFromParent();
2888 class TypeMutator :
public TypePromotionAction {
2895 : TypePromotionAction(Inst), OrigTy(Inst->
getType()) {
2896 DEBUG(
dbgs() <<
"Do: MutateType: " << *Inst <<
" with " << *NewTy
2902 void undo()
override {
2903 DEBUG(
dbgs() <<
"Undo: MutateType: " << *Inst <<
" with " << *OrigTy
2910 class UsesReplacer :
public TypePromotionAction {
2912 struct InstructionAndIdx {
2917 InstructionAndIdx(
Instruction *Inst,
unsigned Idx)
2918 : Inst(Inst), Idx(Idx) {}
2928 DEBUG(
dbgs() <<
"Do: UsersReplacer: " << *Inst <<
" with " << *New
2932 Instruction *UserI = cast<Instruction>(U.getUser());
2933 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
2940 void undo()
override {
2941 DEBUG(
dbgs() <<
"Undo: UsersReplacer: " << *Inst <<
"\n");
2942 for (use_iterator UseIt = OriginalUses.begin(),
2943 EndIt = OriginalUses.end();
2944 UseIt != EndIt; ++UseIt) {
2945 UseIt->Inst->setOperand(UseIt->Idx, Inst);
2951 class InstructionRemover :
public TypePromotionAction {
2956 OperandsHider Hider;
2958 UsesReplacer *Replacer;
2960 SetOfInstrs &RemovedInsts;
2967 InstructionRemover(
Instruction *Inst, SetOfInstrs &RemovedInsts,
2968 Value *New =
nullptr)
2969 : TypePromotionAction(Inst),
Inserter(Inst), Hider(Inst),
2970 Replacer(nullptr), RemovedInsts(RemovedInsts) {
2972 Replacer =
new UsesReplacer(Inst, New);
2973 DEBUG(
dbgs() <<
"Do: InstructionRemover: " << *Inst <<
"\n");
2974 RemovedInsts.insert(Inst);
2981 ~InstructionRemover()
override {
delete Replacer; }
2985 void undo()
override {
2986 DEBUG(
dbgs() <<
"Undo: InstructionRemover: " << *Inst <<
"\n");
2991 RemovedInsts.erase(Inst);
2999 typedef const TypePromotionAction *ConstRestorationPt;
3001 TypePromotionTransaction(SetOfInstrs &RemovedInsts)
3002 : RemovedInsts(RemovedInsts) {}
3007 void rollback(ConstRestorationPt Point);
3009 ConstRestorationPt getRestorationPoint()
const;
3035 SetOfInstrs &RemovedInsts;
3038 void TypePromotionTransaction::setOperand(
Instruction *Inst,
unsigned Idx,
3041 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
3044 void TypePromotionTransaction::eraseInstruction(
Instruction *Inst,
3047 make_unique<TypePromotionTransaction::InstructionRemover>(Inst,
3048 RemovedInsts, NewVal));
3051 void TypePromotionTransaction::replaceAllUsesWith(
Instruction *Inst,
3053 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
3056 void TypePromotionTransaction::mutateType(
Instruction *Inst,
Type *NewTy) {
3057 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
3062 std::unique_ptr<TruncBuilder>
Ptr(
new TruncBuilder(Opnd, Ty));
3064 Actions.push_back(std::move(
Ptr));
3070 std::unique_ptr<SExtBuilder>
Ptr(
new SExtBuilder(Inst, Opnd, Ty));
3072 Actions.push_back(std::move(
Ptr));
3078 std::unique_ptr<ZExtBuilder>
Ptr(
new ZExtBuilder(Inst, Opnd, Ty));
3080 Actions.push_back(std::move(
Ptr));
3084 void TypePromotionTransaction::moveBefore(
Instruction *Inst,
3087 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
3090 TypePromotionTransaction::ConstRestorationPt
3091 TypePromotionTransaction::getRestorationPoint()
const {
3092 return !Actions.empty() ? Actions.back().get() :
nullptr;
3095 void TypePromotionTransaction::commit() {
3096 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
3102 void TypePromotionTransaction::rollback(
3103 TypePromotionTransaction::ConstRestorationPt Point) {
3104 while (!Actions.empty() && Point != Actions.back().get()) {
3105 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
3113 class AddressingModeMatcher {
3130 const SetOfInstrs &InsertedInsts;
3132 InstrToOrigTy &PromotedInsts;
3134 TypePromotionTransaction &TPT;
3138 bool IgnoreProfitability;
3143 Type *AT,
unsigned AS,
3145 const SetOfInstrs &InsertedInsts,
3146 InstrToOrigTy &PromotedInsts,
3147 TypePromotionTransaction &TPT)
3148 : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
3149 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
3150 MemoryInst(MI),
AddrMode(AM), InsertedInsts(InsertedInsts),
3151 PromotedInsts(PromotedInsts), TPT(TPT) {
3152 IgnoreProfitability =
false;
3163 static ExtAddrMode Match(
Value *V,
Type *AccessTy,
unsigned AS,
3168 const SetOfInstrs &InsertedInsts,
3169 InstrToOrigTy &PromotedInsts,
3170 TypePromotionTransaction &TPT) {
3173 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI,
3175 MemoryInst, Result, InsertedInsts,
3176 PromotedInsts, TPT).matchAddr(V, 0);
3177 (void)Success;
assert(Success &&
"Couldn't select *anything*?");
3181 bool matchScaledValue(
Value *ScaleReg, int64_t Scale,
unsigned Depth);
3183 bool matchOperationAddr(
User *Operation,
unsigned Opcode,
unsigned Depth,
3184 bool *MovedAway =
nullptr);
3185 bool isProfitableToFoldIntoAddressingMode(
Instruction *I,
3186 ExtAddrMode &AMBefore,
3187 ExtAddrMode &AMAfter);
3188 bool valueAlreadyLiveAtInst(
Value *Val,
Value *KnownLive1,
Value *KnownLive2);
3189 bool isPromotionProfitable(
unsigned NewCost,
unsigned OldCost,
3190 Value *PromotedOperand)
const;
3196 bool AddressingModeMatcher::matchScaledValue(
Value *ScaleReg, int64_t Scale,
3201 return matchAddr(ScaleReg, Depth);
3212 ExtAddrMode TestAddrMode =
AddrMode;
3216 TestAddrMode.Scale += Scale;
3217 TestAddrMode.ScaledReg = ScaleReg;
3220 if (!TLI.isLegalAddressingMode(
DL, TestAddrMode, AccessTy, AddrSpace))
3230 if (isa<Instruction>(ScaleReg) &&
3232 TestAddrMode.ScaledReg = AddLHS;
3233 TestAddrMode.BaseOffs += CI->
getSExtValue()*TestAddrMode.Scale;
3237 if (TLI.isLegalAddressingMode(
DL, TestAddrMode, AccessTy, AddrSpace)) {
3238 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
3254 case Instruction::BitCast:
3255 case Instruction::AddrSpaceCast:
3260 case Instruction::PtrToInt:
3263 case Instruction::IntToPtr:
3268 case Instruction::Mul:
3269 case Instruction::Shl:
3272 case Instruction::GetElementPtr:
3283 static bool isPromotedInstructionLegal(
const TargetLowering &TLI,
3298 class TypePromotionHelper {
3310 static bool canGetThrough(
const Instruction *Inst,
Type *ConsideredExtType,
3311 const InstrToOrigTy &PromotedInsts,
bool IsSExt);
3315 static bool shouldExtOperand(
const Instruction *Inst,
int OpIdx) {
3316 return !(isa<SelectInst>(Inst) && OpIdx == 0);
3328 static Value *promoteOperandForTruncAndAnyExt(
3330 InstrToOrigTy &PromotedInsts,
unsigned &CreatedInstsCost,
3344 TypePromotionTransaction &TPT,
3345 InstrToOrigTy &PromotedInsts,
3346 unsigned &CreatedInstsCost,
3352 static Value *signExtendOperandForOther(
3354 InstrToOrigTy &PromotedInsts,
unsigned &CreatedInstsCost,
3357 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3358 Exts, Truncs, TLI,
true);
3362 static Value *zeroExtendOperandForOther(
3364 InstrToOrigTy &PromotedInsts,
unsigned &CreatedInstsCost,
3367 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3368 Exts, Truncs, TLI,
false);
3374 InstrToOrigTy &PromotedInsts,
3375 unsigned &CreatedInstsCost,
3388 static Action getAction(
Instruction *
Ext,
const SetOfInstrs &InsertedInsts,
3390 const InstrToOrigTy &PromotedInsts);
3393 bool TypePromotionHelper::canGetThrough(
const Instruction *Inst,
3394 Type *ConsideredExtType,
3395 const InstrToOrigTy &PromotedInsts,
3404 if (isa<ZExtInst>(Inst))
3408 if (IsSExt && isa<SExtInst>(Inst))
3414 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
3421 if (!isa<TruncInst>(Inst))
3443 const Type *OpndType;
3444 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
3445 if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
3446 OpndType = It->second.getPointer();
3447 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
3457 TypePromotionHelper::Action TypePromotionHelper::getAction(
3460 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3461 "Unexpected instruction type");
3464 bool IsSExt = isa<SExtInst>(
Ext);
3468 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
3474 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
3479 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
3480 isa<ZExtInst>(ExtOpnd))
3481 return promoteOperandForTruncAndAnyExt;
3487 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
3490 Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
3492 InstrToOrigTy &PromotedInsts,
unsigned &CreatedInstsCost,
3498 Value *ExtVal = SExt;
3499 bool HasMergedNonFreeExt =
false;
3500 if (isa<ZExtInst>(SExtOpnd)) {
3503 HasMergedNonFreeExt = !TLI.
isExtFree(SExtOpnd);
3506 TPT.replaceAllUsesWith(SExt, ZExt);
3507 TPT.eraseInstruction(SExt);
3512 TPT.setOperand(SExt, 0, SExtOpnd->
getOperand(0));
3514 CreatedInstsCost = 0;
3518 TPT.eraseInstruction(SExtOpnd);
3526 CreatedInstsCost = !TLI.
isExtFree(ExtInst) && !HasMergedNonFreeExt;
3534 TPT.eraseInstruction(ExtInst, NextVal);
3538 Value *TypePromotionHelper::promoteOperandForOther(
3540 InstrToOrigTy &PromotedInsts,
unsigned &CreatedInstsCost,
3547 CreatedInstsCost = 0;
3553 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->
getType());
3554 if (
Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
3555 ITrunc->removeFromParent();
3557 ITrunc->insertAfter(ExtOpnd);
3562 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
3565 TPT.setOperand(Ext, 0, ExtOpnd);
3575 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
3576 ExtOpnd, TypeIsSExt(ExtOpnd->
getType(), IsSExt)));
3578 TPT.mutateType(ExtOpnd, Ext->
getType());
3580 TPT.replaceAllUsesWith(Ext, ExtOpnd);
3584 DEBUG(
dbgs() <<
"Propagate Ext to operands\n");
3585 for (
int OpIdx = 0, EndOpIdx = ExtOpnd->
getNumOperands(); OpIdx != EndOpIdx;
3589 !shouldExtOperand(ExtOpnd, OpIdx)) {
3590 DEBUG(
dbgs() <<
"No need to propagate\n");
3595 if (
const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
3598 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3599 : Cst->getValue().zext(BitWidth);
3600 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->
getType(), CstVal));
3604 if (isa<UndefValue>(Opnd)) {
3606 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->
getType()));
3614 DEBUG(
dbgs() <<
"More operands to ext\n");
3615 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->
getType())
3616 : TPT.createZExt(Ext, Opnd, Ext->
getType());
3617 if (!isa<Instruction>(ValForExtOpnd)) {
3618 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3621 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
3625 TPT.setOperand(ExtForOpnd, 0, Opnd);
3628 TPT.moveBefore(ExtForOpnd, ExtOpnd);
3629 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
3630 CreatedInstsCost += !TLI.
isExtFree(ExtForOpnd);
3632 ExtForOpnd =
nullptr;
3634 if (ExtForOpnd == Ext) {
3635 DEBUG(
dbgs() <<
"Extension is useless now\n");
3636 TPT.eraseInstruction(Ext);
3649 bool AddressingModeMatcher::isPromotionProfitable(
3650 unsigned NewCost,
unsigned OldCost,
Value *PromotedOperand)
const {
3651 DEBUG(
dbgs() <<
"OldCost: " << OldCost <<
"\tNewCost: " << NewCost <<
'\n');
3655 if (NewCost > OldCost)
3657 if (NewCost < OldCost)
3662 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
3676 bool AddressingModeMatcher::matchOperationAddr(
User *AddrInst,
unsigned Opcode,
3680 if (Depth >= 5)
return false;
3687 case Instruction::PtrToInt:
3690 case Instruction::IntToPtr: {
3698 case Instruction::BitCast:
3709 case Instruction::AddrSpaceCast: {
3719 ExtAddrMode BackupAddrMode =
AddrMode;
3720 unsigned OldSize = AddrModeInsts.size();
3725 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3726 TPT.getRestorationPoint();
3728 if (matchAddr(AddrInst->
getOperand(1), Depth+1) &&
3734 AddrModeInsts.resize(OldSize);
3735 TPT.rollback(LastKnownGood);
3738 if (matchAddr(AddrInst->
getOperand(0), Depth+1) &&
3744 AddrModeInsts.resize(OldSize);
3745 TPT.rollback(LastKnownGood);
3751 case Instruction::Mul:
3752 case Instruction::Shl: {
3758 if (Opcode == Instruction::Shl)
3759 Scale = 1LL << Scale;
3763 case Instruction::GetElementPtr: {
3766 int VariableOperand = -1;
3767 unsigned VariableScale = 0;
3769 int64_t ConstantOffset = 0;
3771 for (
unsigned i = 1, e = AddrInst->
getNumOperands(); i != e; ++i, ++GTI) {
3775 cast<ConstantInt>(AddrInst->
getOperand(i))->getZExtValue();
3781 }
else if (TypeSize) {
3783 if (VariableOperand != -1)
3787 VariableOperand = i;
3788 VariableScale = TypeSize;
3795 if (VariableOperand == -1) {
3796 AddrMode.BaseOffs += ConstantOffset;
3797 if (ConstantOffset == 0 ||
3800 if (matchAddr(AddrInst->
getOperand(0), Depth+1))
3803 AddrMode.BaseOffs -= ConstantOffset;
3808 ExtAddrMode BackupAddrMode =
AddrMode;
3809 unsigned OldSize = AddrModeInsts.size();
3812 AddrMode.BaseOffs += ConstantOffset;
3815 if (!matchAddr(AddrInst->
getOperand(0), Depth+1)) {
3819 AddrModeInsts.resize(OldSize);
3827 if (!matchScaledValue(AddrInst->
getOperand(VariableOperand), VariableScale,
3832 AddrModeInsts.resize(OldSize);
3837 AddrMode.BaseOffs += ConstantOffset;
3838 if (!matchScaledValue(AddrInst->
getOperand(VariableOperand),
3839 VariableScale,
Depth)) {
3842 AddrModeInsts.resize(OldSize);
3849 case Instruction::SExt:
3850 case Instruction::ZExt: {
3857 TypePromotionHelper::Action TPH =
3858 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
3862 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3863 TPT.getRestorationPoint();
3864 unsigned CreatedInstsCost = 0;
3866 Value *PromotedOperand =
3867 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost,
nullptr,
nullptr, TLI);
3882 assert(PromotedOperand &&
3883 "TypePromotionHelper should have filtered out those cases");
3885 ExtAddrMode BackupAddrMode =
AddrMode;
3886 unsigned OldSize = AddrModeInsts.size();
3888 if (!matchAddr(PromotedOperand, Depth) ||
3893 !isPromotionProfitable(CreatedInstsCost,
3894 ExtCost + (AddrModeInsts.size() - OldSize),
3897 AddrModeInsts.resize(OldSize);
3898 DEBUG(
dbgs() <<
"Sign extension does not pay off: rollback\n");
3899 TPT.rollback(LastKnownGood);
3913 bool AddressingModeMatcher::matchAddr(
Value *Addr,
unsigned Depth) {
3916 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3917 TPT.getRestorationPoint();
3918 if (
ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
3924 }
else if (
GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
3932 }
else if (
Instruction *I = dyn_cast<Instruction>(Addr)) {
3933 ExtAddrMode BackupAddrMode =
AddrMode;
3934 unsigned OldSize = AddrModeInsts.size();
3937 bool MovedAway =
false;
3947 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode,
AddrMode)) {
3948 AddrModeInsts.push_back(I);
3955 AddrModeInsts.resize(OldSize);
3956 TPT.rollback(LastKnownGood);
3958 }
else if (
ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
3959 if (matchOperationAddr(CE,
CE->getOpcode(),
Depth))
3961 TPT.rollback(LastKnownGood);
3962 }
else if (isa<ConstantPointerNull>(Addr)) {
3988 TPT.rollback(LastKnownGood);
4002 for (
unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4021 static constexpr
int MaxMemoryUsesToScan = 20;
4026 static bool FindAllMemoryUses(
4032 if (!ConsideredInsts.
insert(I).second)
4036 if (!MightBeFoldableInst(I))
4045 if (SeenInsts++ >= MaxMemoryUsesToScan)
4048 Instruction *UserI = cast<Instruction>(U.getUser());
4049 if (
LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
4050 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
4055 unsigned opNo = U.getOperandNo();
4056 if (opNo != StoreInst::getPointerOperandIndex())
4058 MemoryUses.push_back(std::make_pair(
SI, opNo));
4063 unsigned opNo = U.getOperandNo();
4064 if (opNo != AtomicRMWInst::getPointerOperandIndex())
4066 MemoryUses.push_back(std::make_pair(RMW, opNo));
4071 unsigned opNo = U.getOperandNo();
4072 if (opNo != AtomicCmpXchgInst::getPointerOperandIndex())
4074 MemoryUses.push_back(std::make_pair(CmpX, opNo));
4078 if (
CallInst *CI = dyn_cast<CallInst>(UserI)) {
4085 if (!IA)
return true;
4088 if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
4093 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI,
4105 bool AddressingModeMatcher::valueAlreadyLiveAtInst(
Value *Val,
Value *KnownLive1,
4106 Value *KnownLive2) {
4108 if (Val ==
nullptr || Val == KnownLive1 || Val == KnownLive2)
4112 if (!isa<Instruction>(Val) && !isa<Argument>(Val))
return true;
4117 if (
AllocaInst *AI = dyn_cast<AllocaInst>(Val))
4148 bool AddressingModeMatcher::
4149 isProfitableToFoldIntoAddressingMode(
Instruction *I, ExtAddrMode &AMBefore,
4150 ExtAddrMode &AMAfter) {
4151 if (IgnoreProfitability)
return true;
4162 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
4166 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
4168 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
4169 ScaledReg =
nullptr;
4173 if (!BaseReg && !ScaledReg)
4182 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI))
4195 for (
unsigned i = 0, e = MemoryUses.
size(); i != e; ++i) {
4197 unsigned OpNo = MemoryUses[i].second;
4212 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4213 TPT.getRestorationPoint();
4214 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, TRI,
4215 AddressAccessTy, AS,
4216 MemoryInst, Result, InsertedInsts,
4217 PromotedInsts, TPT);
4218 Matcher.IgnoreProfitability =
true;
4219 bool Success = Matcher.matchAddr(Address, 0);
4220 (void)Success;
assert(Success &&
"Couldn't select *anything*?");
4225 TPT.rollback(LastKnownGood);
4231 MatchedAddrModeInsts.
clear();
4266 bool CodeGenPrepare::optimizeMemoryInst(
Instruction *MemoryInst,
Value *Addr,
4267 Type *AccessTy,
unsigned AddrSpace) {
4279 bool AddrModeFound =
false;
4280 bool PhiSeen =
false;
4283 TypePromotionTransaction TPT(RemovedInsts);
4284 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4285 TPT.getRestorationPoint();
4286 while (!worklist.
empty()) {
4299 if (!Visited.
insert(V).second)
4303 if (
PHINode *
P = dyn_cast<PHINode>(V)) {
4304 for (
Value *IncValue :
P->incoming_values())
4313 AddrModeInsts.
clear();
4314 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
4315 V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *TRI,
4316 InsertedInsts, PromotedInsts, TPT);
4318 if (!AddrModeFound) {
4319 AddrModeFound =
true;
4320 AddrMode = NewAddrMode;
4323 if (NewAddrMode == AddrMode)
4326 AddrModeFound =
false;
4332 if (!AddrModeFound) {
4333 TPT.rollback(LastKnownGood);
4343 DEBUG(
dbgs() <<
"CGP: Found local addrmode: " << AddrMode <<
"\n");
4356 Value *&SunkAddr = SunkAddrs[Addr];
4358 DEBUG(
dbgs() <<
"CGP: Reusing nonlocal addrmode: " << AddrMode <<
" for "
4359 << *MemoryInst <<
"\n");
4361 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->
getType());
4364 SubtargetInfo->useAA())) {
4367 DEBUG(
dbgs() <<
"CGP: SINKING nonlocal addrmode: " << AddrMode <<
" for "
4368 << *MemoryInst <<
"\n");
4370 Value *ResultPtr =
nullptr, *ResultIndex =
nullptr;
4373 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
4374 ResultPtr = AddrMode.BaseReg;
4375 AddrMode.BaseReg =
nullptr;
4378 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
4381 if (ResultPtr || AddrMode.Scale != 1)
4384 ResultPtr = AddrMode.ScaledReg;
4395 if (AddrMode.Scale) {
4396 Type *ScaledRegTy = AddrMode.ScaledReg->getType();
4402 if (AddrMode.BaseGV) {
4406 ResultPtr = AddrMode.BaseGV;
4413 if (!ResultPtr && AddrMode.BaseReg) {
4414 ResultPtr = Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->
getType(),
4416 AddrMode.BaseReg =
nullptr;
4417 }
else if (!ResultPtr && AddrMode.Scale == 1) {
4418 ResultPtr = Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->
getType(),
4425 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
4426 SunkAddr = Constant::getNullValue(Addr->
getType());
4427 }
else if (!ResultPtr) {
4439 if (AddrMode.BaseReg) {
4440 Value *V = AddrMode.BaseReg;
4442 V = Builder.CreateIntCast(V, IntPtrTy,
true,
"sunkaddr");
4448 if (AddrMode.Scale) {
4449 Value *V = AddrMode.ScaledReg;
4450 if (V->
getType() == IntPtrTy) {
4455 "We can't transform if ScaledReg is too narrow");
4456 V = Builder.CreateTrunc(V, IntPtrTy,
"sunkaddr");
4459 if (AddrMode.Scale != 1)
4460 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4463 ResultIndex = Builder.CreateAdd(ResultIndex, V,
"sunkaddr");
4469 if (AddrMode.BaseOffs) {
4470 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4474 if (ResultPtr->
getType() != I8PtrTy)
4475 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
4476 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex,
"sunkaddr");
4483 SunkAddr = ResultPtr;
4485 if (ResultPtr->
getType() != I8PtrTy)
4486 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
4487 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex,
"sunkaddr");
4491 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->
getType());
4496 Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() :
nullptr;
4497 Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() :
nullptr;
4498 PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy);
4499 PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy);
4507 DEBUG(
dbgs() <<
"CGP: SINKING nonlocal addrmode: " << AddrMode <<
" for "
4508 << *MemoryInst <<
"\n");
4510 Value *Result =
nullptr;
4517 if (AddrMode.BaseReg) {
4518 Value *V = AddrMode.BaseReg;
4520 V = Builder.CreatePtrToInt(V, IntPtrTy,
"sunkaddr");
4522 V = Builder.CreateIntCast(V, IntPtrTy,
true,
"sunkaddr");
4527 if (AddrMode.Scale) {
4528 Value *V = AddrMode.ScaledReg;
4529 if (V->
getType() == IntPtrTy) {
4532 V = Builder.CreatePtrToInt(V, IntPtrTy,
"sunkaddr");
4533 }
else if (cast<IntegerType>(IntPtrTy)->
getBitWidth() <
4535 V = Builder.CreateTrunc(V, IntPtrTy,
"sunkaddr");
4542 Instruction *I = dyn_cast_or_null<Instruction>(Result);
4543 if (I && (Result != AddrMode.BaseReg))
4547 if (AddrMode.Scale != 1)
4548 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4551 Result = Builder.CreateAdd(Result, V,
"sunkaddr");
4557 if (AddrMode.BaseGV) {
4558 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy,
"sunkaddr");
4560 Result = Builder.CreateAdd(Result, V,
"sunkaddr");
4566 if (AddrMode.BaseOffs) {
4567 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4569 Result = Builder.CreateAdd(Result, V,
"sunkaddr");
4575 SunkAddr = Constant::getNullValue(Addr->
getType());
4577 SunkAddr = Builder.CreateIntToPtr(Result, Addr->
getType(),
"sunkaddr");
4587 Value *CurValue = &*CurInstIterator;
4593 if (IterHandle != CurValue) {
4596 CurInstIterator = BB->
begin();
4606 bool CodeGenPrepare::optimizeInlineAsmInst(
CallInst *CS) {
4607 bool MadeChange =
false;
4610 TM->getSubtargetImpl(*CS->
getFunction())->getRegisterInfo();
4614 for (
unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4623 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->
getType(), ~0u);
4636 bool IsSExt = isa<SExtInst>(FirstUser);
4637 Type *ExtTy = FirstUser->getType();
4638 for (
const User *U : Val->
users()) {
4640 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
4663 if (ExtTy->getScalarType()->getIntegerBitWidth() >
4686 bool CodeGenPrepare::tryToPromoteExts(
4689 unsigned CreatedInstsCost) {
4690 bool Promoted =
false;
4693 for (
auto I : Exts) {
4708 TypePromotionHelper::Action TPH =
4709 TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
4718 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4719 TPT.getRestorationPoint();
4721 unsigned NewCreatedInstsCost = 0;
4724 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4725 &NewExts,
nullptr, *TLI);
4727 "TypePromotionHelper should have filtered out those cases");
4735 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
4738 TotalCreatedInstsCost =
4739 std::max((
long long)0, (TotalCreatedInstsCost - ExtCost));
4741 (TotalCreatedInstsCost > 1 ||
4742 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
4746 TPT.rollback(LastKnownGood);
4752 (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
4753 bool NewPromoted =
false;
4754 for (
auto ExtInst : NewlyMovedExts) {
4755 Instruction *MovedExt = cast<Instruction>(ExtInst);
4759 if (isa<LoadInst>(ExtOperand) &&
4761 (ExtOperand->hasOneUse() ||
hasSameExtUse(ExtOperand, *TLI))))
4764 ProfitablyMovedExts.
push_back(MovedExt);
4771 TPT.rollback(LastKnownGood);
4782 bool CodeGenPrepare::mergeSExts(
Function &F) {
4784 bool Changed =
false;
4785 for (
auto &Entry : ValToSExtendedUses) {
4786 SExts &Insts = Entry.second;
4789 if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) ||
4792 bool inserted =
false;
4793 for (
auto &Pt : CurPts) {
4794 if (DT.dominates(Inst, Pt)) {
4795 Pt->replaceAllUsesWith(Inst);
4796 RemovedInsts.insert(Pt);
4797 Pt->removeFromParent();
4803 if (!DT.dominates(Pt, Inst))
4808 RemovedInsts.insert(Inst);
4815 CurPts.push_back(Inst);
4823 bool CodeGenPrepare::canFormExtLd(
4826 for (
auto *MovedExtInst : MovedExts) {
4827 if (isa<LoadInst>(MovedExtInst->getOperand(0))) {
4828 LI = cast<LoadInst>(MovedExtInst->getOperand(0));
4829 Inst = MovedExtInst;
4881 bool CodeGenPrepare::optimizeExt(
Instruction *&Inst) {
4887 bool AllowPromotionWithoutCommonHeader =
false;
4891 bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
4892 *Inst, AllowPromotionWithoutCommonHeader);
4893 TypePromotionTransaction TPT(RemovedInsts);
4894 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4895 TPT.getRestorationPoint();
4900 bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts);
4908 if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) {
4909 assert(LI && ExtFedByLoad &&
"Expect a valid load and extension");
4923 Inst = ExtFedByLoad;
4928 if (ATPConsiderable &&
4929 performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
4930 HasPromoted, TPT, SpeculativelyMovedExts))
4933 TPT.rollback(LastKnownGood);
4942 bool CodeGenPrepare::performAddressTypePromotion(
4943 Instruction *&Inst,
bool AllowPromotionWithoutCommonHeader,
4944 bool HasPromoted, TypePromotionTransaction &TPT,
4946 bool Promoted =
false;
4948 bool AllSeenFirst =
true;
4949 for (
auto I : SpeculativelyMovedExts) {
4952 SeenChainsForSExt.
find(HeadOfChain);
4955 if (AlreadySeen != SeenChainsForSExt.
end()) {
4956 if (AlreadySeen->second !=
nullptr)
4957 UnhandledExts.
insert(AlreadySeen->second);
4958 AllSeenFirst =
false;
4962 if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
4963 SpeculativelyMovedExts.size() == 1)) {
4967 for (
auto I : SpeculativelyMovedExts) {
4969 SeenChainsForSExt[HeadOfChain] =
nullptr;
4970 ValToSExtendedUses[HeadOfChain].push_back(I);
4973 Inst = SpeculativelyMovedExts.pop_back_val();
4978 for (
auto I : SpeculativelyMovedExts) {
4980 SeenChainsForSExt[HeadOfChain] = Inst;
4985 if (!AllSeenFirst && !UnhandledExts.
empty())
4986 for (
auto VisitedSExt : UnhandledExts) {
4987 if (RemovedInsts.count(VisitedSExt))
4989 TypePromotionTransaction TPT(RemovedInsts);
4993 bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains);
4997 for (
auto I : Chains) {
5000 SeenChainsForSExt[HeadOfChain] =
nullptr;
5001 ValToSExtendedUses[HeadOfChain].push_back(I);
5007 bool CodeGenPrepare::optimizeExtUses(
Instruction *I) {
5022 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->
getParent())
5025 bool DefIsLiveOut =
false;
5026 for (User *U : I->
users()) {
5031 if (UserBB == DefBB)
continue;
5032 DefIsLiveOut =
true;
5039 for (User *U : Src->
users()) {
5042 if (UserBB == DefBB)
continue;
5045 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
5052 bool MadeChange =
false;
5054 Instruction *User = cast<Instruction>(U.getUser());
5058 if (UserBB == DefBB)
continue;
5061 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
5063 if (!InsertedTrunc) {
5065 assert(InsertPt != UserBB->end());
5067 InsertedInsts.insert(InsertedTrunc);
5140 InsertedInsts.count(cast<Instruction>(*Load->
user_begin())))
5148 for (
auto *U : Load->
users())
5149 WorkList.
push_back(cast<Instruction>(U));
5153 APInt DemandBits(BitWidth, 0);
5154 APInt WidestAndBits(BitWidth, 0);
5156 while (!WorkList.
empty()) {
5161 if (!Visited.
insert(I).second)
5165 if (
auto *Phi = dyn_cast<PHINode>(I)) {
5166 for (
auto *U : Phi->users())
5167 WorkList.
push_back(cast<Instruction>(U));
5172 case llvm::Instruction::And: {
5176 APInt AndBits = AndC->getValue();
5177 DemandBits |= AndBits;
5179 if (AndBits.
ugt(WidestAndBits))
5180 WidestAndBits = AndBits;
5186 case llvm::Instruction::Shl: {
5191 DemandBits.setLowBits(BitWidth - ShiftAmt);
5195 case llvm::Instruction::Trunc: {
5198 DemandBits.setLowBits(TruncBitWidth);
5207 uint32_t ActiveBits = DemandBits.getActiveBits();
5219 if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) ||
5220 WidestAndBits != DemandBits)
5224 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
5234 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
5237 InsertedInsts.insert(NewAnd);
5242 NewAnd->setOperand(0, Load);
5245 for (
auto *And : AndsToMaybeRemove)
5248 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
5249 And->replaceAllUsesWith(NewAnd);
5250 if (&*CurInstIterator == And)
5251 CurInstIterator = std::next(And->getIterator());
5252 And->eraseFromParent();
5267 TTI->
getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
5283 uint64_t TrueWeight, FalseWeight;
5286 uint64_t Sum = TrueWeight + FalseWeight;
5288 auto Probability = BranchProbability::getBranchProbability(Max, Sum);
5320 for (
SelectInst *DefSI = SI; DefSI !=
nullptr && Selects.
count(DefSI);
5323 "The condition of DefSI does not match with SI");
5324 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
5331 bool CodeGenPrepare::optimizeSelectInst(
SelectInst *
SI) {
5348 CurInstIterator = std::next(LastSI->
getIterator());
5357 TargetLowering::SelectSupportKind SelectKind;
5359 SelectKind = TargetLowering::VectorMaskSelect;
5361 SelectKind = TargetLowering::ScalarCondVectorVal;
5363 SelectKind = TargetLowering::ScalarValSelect;
5413 if (TrueBlock ==
nullptr) {
5414 TrueBlock = BasicBlock::Create(SI->
getContext(),
"select.true.sink",
5416 TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
5418 auto *TrueInst = cast<Instruction>(SI->
getTrueValue());
5419 TrueInst->moveBefore(TrueBranch);
5422 if (FalseBlock ==
nullptr) {
5423 FalseBlock = BasicBlock::Create(SI->
getContext(),
"select.false.sink",
5425 FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
5428 FalseInst->moveBefore(FalseBranch);
5434 if (TrueBlock == FalseBlock) {
5435 assert(TrueBlock ==
nullptr &&
5436 "Unexpected basic block transform while optimizing select");
5438 FalseBlock = BasicBlock::Create(SI->
getContext(),
"select.false",
5440 BranchInst::Create(EndBlock, FalseBlock);
5449 if (TrueBlock ==
nullptr) {
5452 TrueBlock = StartBlock;
5453 }
else if (FalseBlock ==
nullptr) {
5456 FalseBlock = StartBlock;
5464 INS.insert(ASI.begin(), ASI.end());
5468 for (
auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
5479 ++NumSelectsExpanded;
5483 CurInstIterator = StartBlock->
end();
5490 for (
unsigned i = 0; i <
Mask.size(); ++i) {
5491 if (SplatElem != -1 &&
Mask[i] != -1 &&
Mask[i] != SplatElem)
5493 SplatElem =
Mask[i];
5518 bool MadeChange =
false;
5519 for (User *U : SVI->
users()) {
5524 if (UserBB == DefBB)
continue;
5531 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
5533 if (!InsertedShuffle) {
5535 assert(InsertPt != UserBB->end());
5554 bool CodeGenPrepare::optimizeSwitchInst(
SwitchInst *SI) {
5564 if (RegWidth <= cast<IntegerType>(OldType)->
getBitWidth())
5573 auto *NewType = Type::getIntNTy(Context, RegWidth);
5580 if (
auto *Arg = dyn_cast<Argument>(Cond))
5581 if (Arg->hasSExtAttr())
5582 ExtType = Instruction::SExt;
5584 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
5587 for (
auto Case : SI->
cases()) {
5588 APInt NarrowConst = Case.getCaseValue()->getValue();
5589 APInt WideConst = (ExtType == Instruction::ZExt) ?
5590 NarrowConst.
zext(RegWidth) : NarrowConst.
sext(RegWidth);
5591 Case.setValue(ConstantInt::get(Context, WideConst));
5614 class VectorPromoteHelper {
5629 unsigned StoreExtractCombineCost;
5637 if (InstsToBePromoted.empty())
5639 return InstsToBePromoted.back();
5645 unsigned getTransitionOriginalValueIdx()
const {
5646 assert(isa<ExtractElementInst>(Transition) &&
5647 "Other kind of transitions are not supported yet");
5654 unsigned getTransitionIdx()
const {
5655 assert(isa<ExtractElementInst>(Transition) &&
5656 "Other kind of transitions are not supported yet");
5664 Type *getTransitionType()
const {
5665 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
5679 bool isProfitableToPromote() {
5680 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
5681 unsigned Index = isa<ConstantInt>(ValIdx)
5682 ? cast<ConstantInt>(ValIdx)->getZExtValue()
5684 Type *PromotedType = getTransitionType();
5701 uint64_t ScalarCost =
5702 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
5703 uint64_t VectorCost = StoreExtractCombineCost;
5704 for (
const auto &Inst : InstsToBePromoted) {
5710 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
5711 isa<ConstantFP>(Arg0);
5713 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5714 : TargetTransformInfo::OK_AnyValue;
5716 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5717 : TargetTransformInfo::OK_AnyValue;
5718 ScalarCost += TTI.getArithmeticInstrCost(
5720 VectorCost += TTI.getArithmeticInstrCost(Inst->
getOpcode(), PromotedType,
5723 DEBUG(
dbgs() <<
"Estimated cost of computation to be promoted:\nScalar: "
5724 << ScalarCost <<
"\nVector: " << VectorCost <<
'\n');
5725 return ScalarCost > VectorCost;
5737 unsigned ExtractIdx = UINT_MAX;
5741 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
5742 if (
ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
5748 unsigned End = getTransitionType()->getVectorNumElements();
5750 return ConstantVector::getSplat(End, Val);
5754 for (
unsigned Idx = 0; Idx !=
End; ++Idx) {
5755 if (Idx == ExtractIdx)
5760 return ConstantVector::get(ConstVec);
5766 unsigned OperandIdx) {
5769 if (OperandIdx != 1)
5774 case Instruction::SDiv:
5775 case Instruction::UDiv:
5776 case Instruction::SRem:
5777 case Instruction::URem:
5779 case Instruction::FDiv:
5780 case Instruction::FRem:
5789 unsigned CombineCost)
5790 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
5791 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
5792 assert(Transition &&
"Do not know how to promote null");
5796 bool canPromote(
const Instruction *ToBePromoted)
const {
5798 return isa<BinaryOperator>(ToBePromoted);
5803 bool shouldPromote(
const Instruction *ToBePromoted)
const {
5806 for (
const Use &U : ToBePromoted->
operands()) {
5807 const Value *Val = U.get();
5808 if (Val == getEndOfTransition()) {
5812 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
5816 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
5817 !isa<ConstantFP>(Val))
5826 ISDOpcode, TLI.
getValueType(DL, getTransitionType(),
true));
5835 void enqueueForPromotion(
Instruction *ToBePromoted) {
5836 InstsToBePromoted.push_back(ToBePromoted);
5840 void recordCombineInstruction(
Instruction *ToBeCombined) {
5842 CombineInst = ToBeCombined;
5852 if (InstsToBePromoted.empty() || !CombineInst)
5860 for (
auto &ToBePromoted : InstsToBePromoted)
5861 promoteImpl(ToBePromoted);
5862 InstsToBePromoted.clear();
5868 void VectorPromoteHelper::promoteImpl(
Instruction *ToBePromoted) {
5878 "The type of the result of the transition does not match "
5883 Type *TransitionTy = getTransitionType();
5888 for (Use &U : ToBePromoted->
operands()) {
5889 Value *Val = U.get();
5890 Value *NewVal =
nullptr;
5891 if (Val == Transition)
5892 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
5893 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
5894 isa<ConstantFP>(Val)) {
5897 cast<Constant>(Val),
5898 isa<UndefValue>(Val) ||
5899 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
5903 ToBePromoted->
setOperand(U.getOperandNo(), NewVal);
5905 Transition->removeFromParent();
5906 Transition->insertAfter(ToBePromoted);
5907 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
5913 bool CodeGenPrepare::optimizeExtractElementInst(
Instruction *Inst) {
5914 unsigned CombineCost = UINT_MAX;
5929 DEBUG(
dbgs() <<
"Found an interesting transition: " << *Inst <<
'\n');
5930 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
5935 DEBUG(
dbgs() <<
"Use: " << *ToBePromoted <<
'\n');
5937 if (ToBePromoted->
getParent() != Parent) {
5938 DEBUG(
dbgs() <<
"Instruction to promote is in a different block ("
5940 <<
") than the transition (" << Parent->
getName() <<
").\n");
5944 if (VPH.canCombine(ToBePromoted)) {
5945 DEBUG(
dbgs() <<
"Assume " << *Inst <<
'\n'
5946 <<
"will be combined with: " << *ToBePromoted <<
'\n');
5947 VPH.recordCombineInstruction(ToBePromoted);
5948 bool Changed = VPH.promote();
5949 NumStoreExtractExposed += Changed;
5954 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
5957 DEBUG(
dbgs() <<
"Promoting is possible... Enqueue for promotion!\n");
5959 VPH.enqueueForPromotion(ToBePromoted);
5960 Inst = ToBePromoted;
6006 Type *SplitStoreType = Type::getIntNTy(SI.
getContext(), HalfValBitSize);
6019 Value *LValue, *HValue;
6037 EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
6038 : EVT::getEVT(LValue->
getType());
6039 EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
6040 : EVT::getEVT(HValue->
getType());
6050 if (LBC && LBC->getParent() != SI.
getParent())
6051 LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
6052 if (HBC && HBC->getParent() != SI.
getParent())
6053 HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
6055 auto CreateSplitStore = [&](
Value *V,
bool Upper) {
6056 V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
6057 Value *Addr = Builder.CreateBitCast(
6061 Addr = Builder.CreateGEP(
6062 SplitStoreType, Addr,
6063 ConstantInt::get(Type::getInt32Ty(SI.
getContext()), 1));
6064 Builder.CreateAlignedStore(
6068 CreateSplitStore(LValue,
false);
6069 CreateSplitStore(HValue,
true);
6076 bool CodeGenPrepare::optimizeInst(
Instruction *I,
bool &ModifiedDT) {
6079 if (InsertedInsts.count(I))
6082 if (
PHINode *
P = dyn_cast<PHINode>(I)) {
6087 P->replaceAllUsesWith(V);
6088 P->eraseFromParent();
6095 if (
CastInst *CI = dyn_cast<CastInst>(I)) {
6108 if (isa<ZExtInst>(I) || isa<SExtInst>(
I)) {
6114 TargetLowering::TypeExpandInteger) {
6117 bool MadeChange = optimizeExt(I);
6118 return MadeChange | optimizeExtUses(I);
6124 if (
CmpInst *CI = dyn_cast<CmpInst>(I))
6128 if (
LoadInst *LI = dyn_cast<LoadInst>(I)) {
6129 LI->
setMetadata(LLVMContext::MD_invariant_group,
nullptr);
6131 bool Modified = optimizeLoadExt(LI);
6139 if (
StoreInst *SI = dyn_cast<StoreInst>(I)) {
6142 SI->
setMetadata(LLVMContext::MD_invariant_group,
nullptr);
6144 unsigned AS = SI->getPointerAddressSpace();
6145 return optimizeMemoryInst(I, SI->
getOperand(1),
6152 unsigned AS = RMW->getPointerAddressSpace();
6153 return optimizeMemoryInst(I, RMW->getPointerOperand(),
6158 unsigned AS = CmpX->getPointerAddressSpace();
6159 return optimizeMemoryInst(I, CmpX->getPointerOperand(),
6160 CmpX->getCompareOperand()->
getType(), AS);
6165 if (BinOp && (BinOp->
getOpcode() == Instruction::And) &&
6169 if (BinOp && (BinOp->
getOpcode() == Instruction::AShr ||
6170 BinOp->
getOpcode() == Instruction::LShr)) {
6179 if (GEPI->hasAllZeroIndices()) {
6182 GEPI->getName(), GEPI);
6184 GEPI->eraseFromParent();
6186 optimizeInst(NC, ModifiedDT);
6192 if (
CallInst *CI = dyn_cast<CallInst>(I))
6193 return optimizeCallInst(CI, ModifiedDT);
6195 if (
SelectInst *SI = dyn_cast<SelectInst>(I))
6196 return optimizeSelectInst(SI);
6199 return optimizeShuffleVectorInst(SVI);
6201 if (
auto *
Switch = dyn_cast<SwitchInst>(I))
6202 return optimizeSwitchInst(
Switch);
6204 if (isa<ExtractElementInst>(I))
6205 return optimizeExtractElementInst(I);
6231 bool CodeGenPrepare::optimizeBlock(
BasicBlock &BB,
bool &ModifiedDT) {
6233 bool MadeChange =
false;
6235 CurInstIterator = BB.
begin();
6236 while (CurInstIterator != BB.
end()) {
6237 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
6242 bool MadeBitReverse =
true;
6243 while (TLI && MadeBitReverse) {
6244 MadeBitReverse =
false;
6247 MadeBitReverse = MadeChange =
true;
6253 MadeChange |= dupRetToEnableTailCallOpts(&BB);
6261 bool CodeGenPrepare::placeDbgValues(
Function &F) {
6262 bool MadeChange =
false;
6274 PrevNonDbgInst = Insn;
6279 if (VI && VI != PrevNonDbgInst && !VI->
isTerminator()) {
6284 DEBUG(
dbgs() <<
"Moving Debug Value before :\n" << *DVI <<
' ' << *VI);
6286 if (isa<PHINode>(VI))
6300 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
6301 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
6302 NewTrue = NewTrue / Scale;
6303 NewFalse = NewFalse / Scale;
6328 bool CodeGenPrepare::splitBranchCondition(
Function &F) {
6332 bool MadeChange =
false;
6333 for (
auto &BB : F) {
6345 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
6349 Value *Cond1, *Cond2;
6352 Opc = Instruction::And;
6355 Opc = Instruction::Or;
6363 DEBUG(
dbgs() <<
"Before branch condition splitting\n"; BB.
dump());
6372 Br1->setCondition(Cond1);
6377 if (Opc == Instruction::And)
6378 Br1->setSuccessor(0, TmpBB);
6380 Br1->setSuccessor(1, TmpBB);
6383 auto *Br2 =
IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
6384 if (
auto *I = dyn_cast<Instruction>(Cond2)) {
6398 if (Opc == Instruction::Or)
6402 for (
auto &I : *TBB) {
6412 for (
auto &I : *FBB) {
6422 if (Opc == Instruction::Or) {
6442 uint64_t TrueWeight, FalseWeight;
6443 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
6444 uint64_t NewTrueWeight = TrueWeight;
6445 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
6447 Br1->setMetadata(LLVMContext::MD_prof,
MDBuilder(Br1->getContext())
6448 .createBranchWeights(TrueWeight, FalseWeight));
6450 NewTrueWeight = TrueWeight;
6451 NewFalseWeight = 2 * FalseWeight;
6453 Br2->setMetadata(LLVMContext::MD_prof,
MDBuilder(Br2->getContext())
6454 .createBranchWeights(TrueWeight, FalseWeight));
6475 uint64_t TrueWeight, FalseWeight;
6476 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
6477 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
6478 uint64_t NewFalseWeight = FalseWeight;
6480 Br1->setMetadata(LLVMContext::MD_prof,
MDBuilder(Br1->getContext())
6481 .createBranchWeights(TrueWeight, FalseWeight));
6483 NewTrueWeight = 2 * TrueWeight;
6484 NewFalseWeight = FalseWeight;
6486 Br2->setMetadata(LLVMContext::MD_prof,
MDBuilder(Br2->getContext())
6487 .createBranchWeights(TrueWeight, FalseWeight));
6497 DEBUG(
dbgs() <<
"After branch condition splitting\n"; BB.
dump();
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
bool hasFnAttr(Attribute::AttrKind Kind) const
Determine whether this call has the given attribute.
Return a value (possibly void), from a function.
Value * getValueOperand()
const Value * getCalledValue() const
Get a pointer to the function that is invoked by this instruction.
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. ...
Type * getIndexedType() const
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
This class is the base class for the comparison instructions.
static Constant * getConstantVector(MVT VT, const APInt &SplatValue, unsigned SplatBitSize, LLVMContext &C)
iterator_range< use_iterator > uses()
class_match< CmpInst > m_Cmp()
Matches any compare instruction and ignore it.
virtual bool isZExtFree(Type *FromTy, Type *ToTy) const
Return true if any actual instruction that defines a value of type FromTy implicitly zero-extends the...
static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI)
Sink the given CmpInst into user blocks to reduce the number of virtual registers that must be create...
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...
bool isOnlyUsedInZeroEqualityComparison(const Instruction *CxtI)
iterator_range< CaseIt > cases()
Iteration adapter for range-for loops.
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
bool isNonIntegralPointerType(PointerType *PT) const
static cl::opt< bool > ForceSplitStore("force-split-store", cl::Hidden, cl::init(false), cl::desc("Force store splitting no matter what the target query says."))
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
static Value * getTrueOrFalseValue(SelectInst *SI, bool isTrue, const SmallPtrSet< const Instruction *, 2 > &Selects)
If isTrue is true, return the true value of SI, otherwise return false value of SI.
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
STATISTIC(NumFunctions,"Total number of functions")
LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const
Return how we should legalize values of this type, either it is already legal (return 'Legal') or we ...
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V)
Check if V (an operand of a select instruction) is an expensive instruction that is only used once...
Value * CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name="")
Value * CreateXor(Value *LHS, Value *RHS, const Twine &Name="")
A Module instance is used to store all the information related to an LLVM module. ...
void setAlignment(unsigned Align)
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
an instruction that atomically checks whether a specified value is in a memory location, and, if it is, stores a new value there.
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
virtual bool isCheapToSpeculateCttz() const
Return true if it is cheap to speculate a call to intrinsic cttz.
This class represents zero extension of integer types.
bool isFunctionHotInCallGraph(const Function *F)
Returns true if F has hot function entry or hot call edge.
unsigned getNumOperands() const
void DeleteDeadBlock(BasicBlock *BB)
Delete the specified block, which must have no predecessors.
virtual bool isMultiStoresCheaperThanBitsMerge(EVT LTy, EVT HTy) const
Return true if it is cheaper to split the store of a merged int val from a pair of smaller values int...
Analysis providing profile information.
Type * getValueType() const
This class represents a function call, abstracting a target machine's calling convention.
void MergeBasicBlockIntoOnlyPred(BasicBlock *BB, DominatorTree *DT=nullptr)
BB is a block with one predecessor and its predecessor is known to have one successor (BB!)...
static BasicBlock * findIBRPredecessor(BasicBlock *BB, SmallVectorImpl< BasicBlock * > &OtherPreds)
unsigned getSizeInBits() const
This instruction constructs a fixed permutation of two input vectors.
void setSectionPrefix(StringRef Prefix)
Set the section prefix for this function.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
static void dump(StringRef Title, SpillInfo const &Spills)
const Function * getParent() const
Return the enclosing method, or null if none.
const Instruction & front() const
The two locations do not alias at all.
virtual bool allowsMisalignedMemoryAccesses(EVT, unsigned AddrSpace=0, unsigned Align=1, bool *=nullptr) const
Determine if the target supports unaligned memory accesses.
unsigned getAddressSpace() const
Return the address space of the Pointer type.
An instruction for reading from memory.
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
an instruction that atomically reads a memory location, combines it with another value, and then stores the result back.
Type * getElementType() const
Value * CallOperandVal
If this is the result output operand or a clobber, this is null, otherwise it is the incoming operand...
void setAlignment(unsigned Align)
bool canIncreaseAlignment() const
bool optForSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
bool optForMinSize() const
Optimize this function for minimum size (-Oz).
static bool despeculateCountZeros(IntrinsicInst *CountZeros, const TargetLowering *TLI, const DataLayout *DL, bool &ModifiedDT)
If counting leading or trailing zeros is an expensive operation and a zero input is defined...
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
StringRef getName() const
Return a constant reference to the value's name.
iterator begin()
Instruction iterator methods.
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
bool enableExtLdPromotion() const
Return true if the target wants to use the optimization that turns ext(promotableInst1(...(promotableInstN(load)))) into promotedInst1(...(promotedInstN(ext(load)))).
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
bool match(Val *V, const Pattern &P)
AnalysisUsage & addRequired()
StructType * getStructTypeOrNull() const
INITIALIZE_PASS_BEGIN(CodeGenPrepare, DEBUG_TYPE,"Optimize for code generation", false, false) INITIALIZE_PASS_END(CodeGenPrepare
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
#define INITIALIZE_PASS_DEPENDENCY(depName)
bool hasNoNaNs() const
Determine whether the no-NaNs flag is set.
bool isUnconditional() const
Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
Remove an incoming value.
bool isRound() const
Return true if the size is a power-of-two number of bytes.
This class represents the LLVM 'select' instruction.
bool hasMultipleConditionRegisters() const
Return true if multiple condition registers are available.
unsigned getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
This is the base class for all instructions that perform data casts.
static cl::opt< bool > DisableExtLdPromotion("disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false), cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in ""CodeGenPrepare"))
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
'undef' values are things that do not have specified contents.
bool bypassSlowDivision(BasicBlock *BB, const DenseMap< unsigned int, unsigned int > &BypassWidth)
This optimization identifies DIV instructions in a BB that can be profitably bypassed and carried out...
static cl::opt< bool > AddrSinkUsingGEPs("addr-sink-using-gep", cl::Hidden, cl::init(true), cl::desc("Address sinking in CGP using GEPs."))
Class to represent struct types.
A Use represents the edge between a Value definition and its users.
bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=nullptr)
If a terminator instruction is predicated on a constant value, convert it into an unconditional branc...
TargetLowering::ConstraintType ConstraintType
Information about the constraint code, e.g.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
virtual bool isNoopAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const
Returns true if a cast between SrcAS and DestAS is a noop.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
static cl::opt< bool > DisableBranchOpts("disable-cgp-branch-opts", cl::Hidden, cl::init(false), cl::desc("Disable branch optimizations in CodeGenPrepare"))
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly...
static bool expandMemCmp(CallInst *CI, const TargetTransformInfo *TTI, const TargetLowering *TLI, const DataLayout *DL)
We want to transform: call = call signext i32 (i8* %0, i8* %1, i64 15) To: loadbb: %0 = bitcast i32* ...
Windows NT (Windows on ARM)
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
bool isInteger() const
Return true if this is an integer or a vector integer type.
int InstructionOpcodeToISD(unsigned Opcode) const
Get the ISD node that corresponds to the Instruction class opcode.
static cl::opt< bool > DisableStoreExtract("disable-cgp-store-extract", cl::Hidden, cl::init(false), cl::desc("Disable store(extract) optimizations in CodeGenPrepare"))
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
bool isExtFree(const Instruction *I) const
Return true if the extension represented by I is free.
LLVM_NODISCARD bool empty() const
static cl::opt< bool > DisablePreheaderProtect("disable-preheader-prot", cl::Hidden, cl::init(false), cl::desc("Disable protection against removing loop preheaders"))
Interval::succ_iterator succ_begin(Interval *I)
succ_begin/succ_end - define methods so that Intervals may be used just like BasicBlocks can with the...
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.
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI, const DataLayout &DL)
If the specified cast instruction is a noop copy (e.g.
const AMDGPUAS &AS return SrcAS
A constant value that is initialized with an expression using other constant values.
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Value handle that is nullable, but tries to track the Value.
bool insert(const value_type &X)
Insert a new element into the SetVector.
static bool simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase, const SmallVectorImpl< GCRelocateInst * > &Targets)
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
match_combine_or< LTy, RTy > m_CombineOr(const LTy &L, const RTy &R)
Combine two pattern matchers matching L || R.
MemCmpExpansion(CallInst *CI, uint64_t Size, unsigned MaxLoadSize, unsigned NumLoadsPerBlock, const DataLayout &DL)
CastClass_match< OpTy, Instruction::ZExt > m_ZExt(const OpTy &Op)
Matches ZExt.
This contains information for each constraint that we are lowering.
uint64_t getLimitedValue(uint64_t Limit=~0ULL) const
getLimitedValue - If the value is smaller than the specified limit, return it, otherwise return the l...
BasicBlock * getSuccessor(unsigned i) const
This class represents a no-op cast from one type to another.
bool empty() const
Determine if the SetVector is empty or not.
static CmpInst * Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2, const Twine &Name="", Instruction *InsertBefore=nullptr)
Construct a compare instruction, given the opcode, the predicate and the two operands.
InstTy * Insert(InstTy *I, const Twine &Name="") const
Insert and return the specified instruction.
class_match< ConstantInt > m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
bool isLittleEndian() const
Layout endianness...
static bool hasSameExtUse(Value *Val, const TargetLowering &TLI)
Check if all the uses of Val are equivalent (or free) zero or sign extensions.
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
const Function * getFunction() const
Return the function this instruction belongs to.
An instruction for storing to memory.
static bool canCombine(MachineBasicBlock &MBB, MachineOperand &MO, unsigned CombineOpc, unsigned ZeroReg=0, bool CheckZeroReg=false)
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
EVT getValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
Return the EVT corresponding to this LLVM type.
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="")
ConstraintPrefix Type
Type - The basic type of the constraint: input/output/clobber.
virtual bool isSelectSupported(SelectSupportKind) const
Optimize for code generation
void takeName(Value *V)
Transfer the name from V to this value.
This class implements simplifications for calls to fortified library functions (__st*cpy_chk, __memcpy_chk, __memmove_chk, __memset_chk), to, when possible, replace them with their non-checking counterparts.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
This class represents a truncation of integer types.
static unsigned getKnownAlignment(Value *V, const DataLayout &DL, const Instruction *CxtI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr)
Try to infer an alignment for the specified pointer.
const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
Class to represent pointers.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
Interval::succ_iterator succ_end(Interval *I)
void replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
static cl::opt< bool > StressStoreExtract("stress-cgp-store-extract", cl::Hidden, cl::init(false), cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"))
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="")
iterator find(const_arg_type_t< KeyT > Val)
static bool isExtractBitsCandidateUse(Instruction *User)
Check if the candidates could be combined with a shift instruction, which includes: ...
uint64_t getElementOffset(unsigned Idx) const
static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI)
constexpr uint64_t MinAlign(uint64_t A, uint64_t B)
A and B are either alignments or offsets.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
LoadInst * CreateLoad(Value *Ptr, const char *Name)
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
OneUse_match< T > m_OneUse(const T &SubPattern)
bool isTypeLegal(EVT VT) const
Return true if the target has native support for the specified value type.
initializer< Ty > init(const Ty &Val)
std::vector< AsmOperandInfo > AsmOperandInfoVector
static cl::opt< unsigned > MemCmpNumLoadsPerBlock("memcmp-num-loads-per-block", cl::Hidden, cl::init(1), cl::desc("The number of loads per basic block for inline expansion of ""memcmp that is only being compared against zero."))
static bool isBroadcastShuffle(ShuffleVectorInst *SVI)
static bool CombineUAddWithOverflow(CmpInst *CI)
Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if possible.
unsigned getAlignment() const
Return the alignment of the access that is being performed.
Subclasses of this class are all able to terminate a basic block.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
void setSuccessor(unsigned idx, BasicBlock *B)
Update the specified successor to point at the provided block.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction...
ConstantInt * lowerObjectSizeCall(IntrinsicInst *ObjectSize, const DataLayout &DL, const TargetLibraryInfo *TLI, bool MustSucceed)
Try to turn a call to .objectsize into an integer value of the given Type.
LLVM Basic Block Representation.
PointerIntPair - This class implements a pair of a pointer and small integer.
bool isFunctionColdInCallGraph(const Function *F)
Returns true if F has cold function entry or cold call edge.
The instances of the Type class are immutable: once they are created, they are never changed...
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
This is an important class for using LLVM in a threaded context.
uint64_t getTypeStoreSizeInBits(Type *Ty) const
Returns the maximum number of bits that may be overwritten by storing the specified type; always a mu...
virtual bool isCheapAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const
Returns true if a cast from SrcAS to DestAS is "cheap", such that e.g.
Conditional or Unconditional Branch instruction.
bool isVectorTy() const
True if this is an instance of VectorType.
bool isIndirect
isIndirect - True if this operand is an indirect operand.
bool isOperationLegalOrCustom(unsigned Op, EVT VT) const
Return true if the specified operation is legal on this target or can be made legal with custom lower...
This is an important base class in LLVM.
const Value * getCondition() const
int64_t getSExtValue() const
Get sign extended value.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Indirect Branch Instruction.
bool hasNoSignedWrap() const
Determine whether the no signed wrap flag is set.
unsigned getAlignment() const
Return the alignment of the memory that is being allocated by the instruction.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI, const TargetLowering *TLI, SelectInst *SI)
Returns true if a SelectInst should be turned into an explicit branch.
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...
static void computeBaseDerivedRelocateMap(const SmallVectorImpl< GCRelocateInst * > &AllRelocateCalls, DenseMap< GCRelocateInst *, SmallVector< GCRelocateInst *, 2 >> &RelocateInstMap)
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
APInt sext(unsigned width) const
Sign extend to a new width.
bool extractProfMetadata(uint64_t &TrueVal, uint64_t &FalseVal) const
Retrieve the raw weight values of a conditional branch or select.
brc_match< Cond_t > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
Represent the analysis usage information of a pass.
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)
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
static const unsigned End
static bool SinkCast(CastInst *CI)
SinkCast - Sink the specified cast instruction into its user blocks.
virtual bool useSoftFloat() const
for(unsigned i=0, e=MI->getNumOperands();i!=e;++i)
FunctionPass class - This class is used to implement most global optimizations.
Value * getOperand(unsigned i) const
MVT getRegisterType(MVT VT) const
Return the type of registers that this ValueType will eventually require.
Interval::pred_iterator pred_end(Interval *I)
bool isPredictableSelectExpensive() const
Return true if selects are only cheaper than branches if the branch is unlikely to be predicted right...
self_iterator getIterator()
class_match< BinaryOperator > m_BinOp()
Match an arbitrary binary operation and ignore it.
unsigned getIntegerBitWidth() const
Predicate getPredicate() const
Return the predicate for this instruction.
Constant * ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty, const DataLayout &DL)
ConstantFoldLoadFromConstPtr - Return the value that a load from C would produce if it is constant an...
static cl::opt< bool > DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false), cl::desc("Disable GC optimizations in CodeGenPrepare"))
LLVM_NODISCARD bool empty() const
bool isPointerTy() const
True if this is an instance of PointerType.
bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr)
If the specified value is a trivially dead instruction, delete it.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
LLVMContext & getContext() const
All values hold a context through their type.
static wasm::ValType getType(const TargetRegisterClass *RC)
bool isLoadExtLegal(unsigned ExtType, EVT ValVT, EVT MemVT) const
Return true if the specified load with extension is legal on this target.
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
bool isUsedInBasicBlock(const BasicBlock *BB) const
Check if this value is used in the specified basic block.
unsigned getMaxExpandSizeMemcmp(bool OptSize) const
Get maximum # of load operations permitted for memcmp.
const Value * getTrueValue() const
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo, SDValue Op, SelectionDAG *DAG=nullptr) const
Determines the constraint code and constraint type to use for the specific AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
void dump() const
Support for debugging, callable in GDB: V->dump()
bool isTerminator() const
bool isConditional() const
bool bitsGT(EVT VT) const
Return true if this has more bits than VT.
bool ugt(const APInt &RHS) const
Unsigned greather than comparison.
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space...
BinaryOps getOpcode() const
unsigned getBasePtrIndex() const
The index into the associate statepoint's argument list which contains the base pointer of the pointe...
void initializeCodeGenPreparePass(PassRegistry &)
A SetVector that performs no allocations if smaller than a certain size.
This is the common base class for memset/memcpy/memmove.
Iterator for intrusive lists based on ilist_node.
static bool IsNonLocalValue(Value *V, BasicBlock *BB)
Return true if the specified values are defined in a different basic block than BB.
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
unsigned countPopulation(T Value)
Count the number of set bits in a value.
This is the shared class of boolean and integer constants.
void setIncomingBlock(unsigned i, BasicBlock *BB)
bool hasNoUnsignedWrap() const
Determine whether the no unsigned wrap flag is set.
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false...
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
static bool SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI, DenseMap< BasicBlock *, BinaryOperator * > &InsertedShifts, const TargetLowering &TLI, const DataLayout &DL)
Sink both shift and truncate instruction to the use of truncate's BB.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
static CallInst * Create(Value *Func, ArrayRef< Value * > Args, ArrayRef< OperandBundleDef > Bundles=None, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size...
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.
static cl::opt< bool > DisableSelectToBranch("disable-cgp-select2branch", cl::Hidden, cl::init(false), cl::desc("Disable select to branch conversion."))
LLVM_NODISCARD T pop_back_val()
Function * getCalledFunction() const
Return the function called, or null if this is an indirect function invocation.
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...
const BasicBlock & getEntryBlock() const
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
bool hasExtractBitsInsn() const
Return true if the target has BitExtract instructions.
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.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
Value * CreateGEP(Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="")
Target - Wrapper for Target specific information.
Class for arbitrary precision integers.
BasicBlock * CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix="", Function *F=nullptr, ClonedCodeInfo *CodeInfo=nullptr, DebugInfoFinder *DIFinder=nullptr)
CloneBasicBlock - Return a copy of the specified basic block, but without embedding the block into a ...
Value * getIncomingValueForBlock(const BasicBlock *BB) const
bool isIntegerTy() const
True if this is an instance of IntegerType.
static BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), Instruction *InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
typename SuperClass::iterator iterator
iterator_range< user_iterator > users()
InstListType::iterator iterator
Instruction iterators...
AddrMode
ARM Addressing Modes.
static cl::opt< bool > StressExtLdPromotion("stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false), cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) ""optimization in CodeGenPrepare"))
Value * getCondition() const
static cl::opt< unsigned > FreqRatioToSkipMerge("cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2), cl::desc("Skip merging empty blocks if (frequency of empty block) / ""(frequency of destination block) is greater than this ratio"))
FunctionPass * createCodeGenPreparePass()
createCodeGenPreparePass - Transform the code to expose more pattern matching during instruction sele...
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
void removeFromParent()
This method unlinks 'this' from the containing basic block, but does not delete it.
llvm_unreachable("Unknown RegBank!")
TargetSubtargetInfo - Generic base class for all target subtargets.
static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP, SmallVectorImpl< Value * > &OffsetV)
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
static CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
This class wraps the llvm.memcpy/memmove intrinsics.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Analysis providing branch probability information.
virtual bool isVectorShiftByScalarCheap(Type *Ty) const
Return true if it's significantly cheaper to shift a vector by a uniform scalar than by an amount whi...
void setCondition(Value *V)
This represents the llvm.dbg.value instruction.
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.
virtual bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM, Type *Ty, unsigned AddrSpace) const
Return true if the addressing mode represented by AM is legal for this target, for a load/store of th...
Establish a view to a call site for examination.
unsigned getSizeInBits() const
Return the size of the specified value type in bits.
void insertAfter(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately after the specified instruction...
SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
bool hasOneUse() const
Return true if there is exactly one user of this value.
user_iterator_impl< User > user_iterator
void setArgOperand(unsigned i, Value *v)
unsigned getPointerSizeInBits(unsigned AS=0) const
Layout pointer size, in bits FIXME: The defaults need to be removed once all of the backends/clients ...
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
CallInst * CreateCall(Value *Callee, ArrayRef< Value * > Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
bool recognizeBSwapOrBitReverseIdiom(Instruction *I, bool MatchBSwaps, bool MatchBitReversals, SmallVectorImpl< Instruction * > &InsertedInsts)
Try and match a bswap or bitreverse idiom.
static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI, const TargetLowering &TLI, const DataLayout &DL)
Sink the shift right instruction into user blocks if the uses could potentially be combined with this...
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
ReturnInst * FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB, BasicBlock *Pred)
This method duplicates the specified return instruction into a predecessor which ends in an unconditi...
VectorType * getType() const
Overload to return most specific vector type.
static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL, const TargetLowering &TLI)
For the instruction sequence of store below, F and I values are bundled together as an i64 value befo...
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
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.
LLVM_NODISCARD bool empty() const
OtherOps getOpcode() const
Get the opcode casted to the right type.
bool isStatepoint(ImmutableCallSite CS)
virtual bool isTruncateFree(Type *FromTy, Type *ToTy) const
Return true if it's free to truncate a value of type FromTy to type ToTy.
iterator_range< op_iterator > arg_operands()
Iteration adapter for range-for loops.
static cl::opt< bool > EnableTypePromotionMerge("cgp-type-promotion-merge", cl::Hidden, cl::desc("Enable merging of redundant sexts when one is dominating"" the other."), cl::init(true))
const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse)
Scale down both weights to fit into uint32_t.
virtual BranchProbability getPredictableBranchThreshold() const
If a branch or a select condition is skewed in one direction by more than this factor, it is very likely to be predicted correctly.
user_iterator user_begin()
LLVMContext & getContext() const
Get the context in which this basic block lives.
bool isSafeToSpeculativelyExecute(const Value *V, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr)
Return true if the instruction does not have any effects besides calculating the result and does not ...
static bool isInput(const StringSet<> &Prefixes, StringRef Arg)
Represents calls to the gc.relocate intrinsic.
unsigned getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
uint64_t PowerOf2Floor(uint64_t A)
Returns the power of two which is less than or equal to the given value.
EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const
For types supported by the target, this is an identity function.
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 cl::opt< bool > EnableAndCmpSinking("enable-andcmp-sinking", cl::Hidden, cl::init(true), cl::desc("Enable sinkinig and/cmp into branches."))
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
static const Function * getParent(const Value *V)
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
uint64_t getTypeSizeInBits(Type *Ty) const
Size examples:
This class implements an extremely fast bulk output stream that can only output to a stream...
virtual bool canCombineStoreAndExtract(Type *VectorTy, Value *Idx, unsigned &Cost) const
Return true if the target can combine store(extractelement VectorTy, Idx).
Primary interface to the complete machine description for the target machine.
static cl::opt< bool > ProfileGuidedSectionPrefix("profile-guided-section-prefix", cl::Hidden, cl::init(true), cl::ZeroOrMore, cl::desc("Use profile info to add section prefix for hot/cold functions"))
The legacy pass manager's analysis pass to compute loop information.
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
const Value * getFalseValue() const
StringRef - Represent a constant reference to a string, i.e.
APInt zext(unsigned width) const
Zero extend to a new width.
unsigned getLargestLegalIntTypeSizeInBits() const
Returns the size of largest legal integer type size, or 0 if none are set.
virtual bool isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const
Return if the target supports combining a chain like:
static bool makeBitReverse(Instruction &I, const DataLayout &DL, const TargetLowering &TLI)
Given an OR instruction, check to see if this is a bitreverse idiom.
bool operator==(uint64_t V1, const APInt &V2)
specific_intval m_SpecificInt(uint64_t V)
Match a specific integer value or vector with all elements equal to the value.
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.
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
bool replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI=nullptr, const DominatorTree *DT=nullptr, AssumptionCache *AC=nullptr)
Replace all uses of 'I' with 'SimpleV' and simplify the uses recursively.
bool attributesPermitTailCall(const Function *F, const Instruction *I, const ReturnInst *Ret, const TargetLoweringBase &TLI, bool *AllowDifferingSizes=nullptr)
Test if given that the input instruction is in the tail call position, if there is an attribute misma...
static void getShuffleMask(Constant *Mask, SmallVectorImpl< int > &Result)
Convert the input shuffle mask operand to a vector of integers.
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation...
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
bool isJumpExpensive() const
Return true if Flow Control is an expensive operation that should be avoided.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
Value * getMemCmpExpansion(uint64_t Size)
static IntegerType * getInt8Ty(LLVMContext &C)
void moveBefore(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it into the function that MovePos lives ...
bool isExtLoad(const LoadInst *Load, const Instruction *Ext, const DataLayout &DL) const
Return true if Load and Ext can form an ExtLoad.
const BasicBlock * getParent() const
const Value * stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL, APInt &Offset) const
Accumulate offsets from stripInBoundsConstantOffsets().
virtual AsmOperandInfoVector ParseConstraints(const DataLayout &DL, const TargetRegisterInfo *TRI, ImmutableCallSite CS) const
Split up the constraint string from the inline assembly value into the specific constraints and their...
bind_ty< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
UAddWithOverflow_match< LHS_t, RHS_t, Sum_t > m_UAddWithOverflow(const LHS_t &L, const RHS_t &R, const Sum_t &S)
Match an icmp instruction checking for unsigned overflow on addition.
A wrapper class for inspecting calls to intrinsic functions.
This file describes how to lower LLVM code to machine code.
an instruction to allocate memory on the stack
static bool sinkAndCmp0Expression(Instruction *AndI, const TargetLowering &TLI, SetOfInstrs &InsertedInsts)
Duplicate and sink the given 'and' instruction into user blocks where it is used in a compare to allo...
virtual bool isCheapToSpeculateCtlz() const
Return true if it is cheap to speculate a call to intrinsic ctlz.
gep_type_iterator gep_type_begin(const User *GEP)
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.