42 #include "llvm/Config/llvm-config.h" 63 #include "llvm/IR/IntrinsicsAArch64.h" 64 #include "llvm/IR/IntrinsicsX86.h" 105 using namespace llvm;
108 #define DEBUG_TYPE "codegenprepare" 110 STATISTIC(NumBlocksElim,
"Number of blocks eliminated");
111 STATISTIC(NumPHIsElim,
"Number of trivial PHIs eliminated");
112 STATISTIC(NumGEPsElim,
"Number of GEPs converted to casts");
113 STATISTIC(NumCmpUses,
"Number of uses of Cmp expressions replaced with uses of " 115 STATISTIC(NumCastUses,
"Number of uses of Cast expressions replaced with uses " 117 STATISTIC(NumMemoryInsts,
"Number of memory instructions whose address " 118 "computations were sunk");
120 "Number of phis created when address " 121 "computations were sunk to memory instructions");
123 "Number of select created when address " 124 "computations were sunk to memory instructions");
125 STATISTIC(NumExtsMoved,
"Number of [s|z]ext instructions combined with loads");
126 STATISTIC(NumExtUses,
"Number of uses of [s|z]ext instructions optimized");
128 "Number of and mask instructions added to form ext loads");
129 STATISTIC(NumAndUses,
"Number of uses of and mask instructions optimized");
130 STATISTIC(NumRetsDup,
"Number of return instructions duplicated");
131 STATISTIC(NumDbgValueMoved,
"Number of debug value instructions moved");
132 STATISTIC(NumSelectsExpanded,
"Number of selects turned into branches");
133 STATISTIC(NumStoreExtractExposed,
"Number of store(extractelement) exposed");
137 cl::desc(
"Disable branch optimizations in CodeGenPrepare"));
141 cl::desc(
"Disable GC optimizations in CodeGenPrepare"));
145 cl::desc(
"Disable select to branch conversion."));
149 cl::desc(
"Address sinking in CGP using GEPs."));
153 cl::desc(
"Enable sinkinig and/cmp into branches."));
157 cl::desc(
"Disable store(extract) optimizations in CodeGenPrepare"));
161 cl::desc(
"Stress test store(extract) optimizations in CodeGenPrepare"));
165 cl::desc(
"Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in " 170 cl::desc(
"Stress test ext(promotable(ld)) -> promoted(ext(ld)) " 171 "optimization in CodeGenPrepare"));
175 cl::desc(
"Disable protection against removing loop preheaders"));
179 cl::desc(
"Use profile info to add section prefix for hot/cold functions"));
183 cl::desc(
"Skip merging empty blocks if (frequency of empty block) / " 184 "(frequency of destination block) is greater than this ratio"));
188 cl::desc(
"Force store splitting no matter what the target query says."));
192 cl::desc(
"Enable merging of redundant sexts when one is dominating" 197 cl::desc(
"Disables combining addressing modes with different parts " 198 "in optimizeMemoryInst."));
202 cl::desc(
"Allow creation of Phis in Address sinking."));
206 cl::desc(
"Allow creation of selects in Address sinking."));
210 cl::desc(
"Allow combining of BaseReg field in Address sinking."));
214 cl::desc(
"Allow combining of BaseGV field in Address sinking."));
218 cl::desc(
"Allow combining of BaseOffs field in Address sinking."));
222 cl::desc(
"Allow combining of ScaledReg field in Address sinking."));
227 cl::desc(
"Enable splitting large offset of GEP."));
231 cl::desc(
"Enable ICMP_EQ to ICMP_S(L|G)T conversion."));
250 class TypePromotionTransaction;
260 std::unique_ptr<BlockFrequencyInfo>
BFI;
261 std::unique_ptr<BranchProbabilityInfo> BPI;
276 SetOfInstrs InsertedInsts;
280 InstrToOrigTy PromotedInsts;
283 SetOfInstrs RemovedInsts;
303 ValueToSExts ValToSExtendedUses;
313 std::unique_ptr<DominatorTree> DT;
324 StringRef getPassName()
const override {
return "CodeGen Prepare"; }
335 template <
typename F>
336 void resetIteratorIfInvalidatedWhileCalling(
BasicBlock *BB, F f) {
340 Value *CurValue = &*CurInstIterator;
347 if (IterHandle != CurValue) {
348 CurInstIterator = BB->
begin();
356 DT = std::make_unique<DominatorTree>(
F);
360 bool eliminateFallThrough(
Function &F);
361 bool eliminateMostlyEmptyBlocks(
Function &F);
364 void eliminateMostlyEmptyBlock(
BasicBlock *BB);
367 bool optimizeBlock(
BasicBlock &BB,
bool &ModifiedDT);
370 Type *AccessTy,
unsigned AddrSpace);
371 bool optimizeInlineAsmInst(
CallInst *CS);
372 bool optimizeCallInst(
CallInst *CI,
bool &ModifiedDT);
380 bool optimizeExtractElementInst(
Instruction *Inst);
381 bool dupRetToEnableTailCallOpts(
BasicBlock *BB,
bool &ModifiedDT);
386 bool tryToPromoteExts(TypePromotionTransaction &TPT,
389 unsigned CreatedInstsCost = 0);
391 bool splitLargeGEPOffsets();
392 bool performAddressTypePromotion(
394 bool AllowPromotionWithoutCommonHeader,
395 bool HasPromoted, TypePromotionTransaction &TPT,
397 bool splitBranchCondition(
Function &F,
bool &ModifiedDT);
403 bool optimizeCmp(
CmpInst *Cmp,
bool &ModifiedDT);
404 bool combineToUSubWithOverflow(
CmpInst *Cmp,
bool &ModifiedDT);
405 bool combineToUAddWithOverflow(
CmpInst *Cmp,
bool &ModifiedDT);
413 "Optimize for code generation",
false,
false)
426 bool EverMadeChange =
false;
428 InsertedInsts.clear();
429 PromotedInsts.clear();
431 if (
auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
433 SubtargetInfo =
TM->getSubtargetImpl(F);
434 TLI = SubtargetInfo->getTargetLowering();
435 TRI = SubtargetInfo->getRegisterInfo();
437 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
438 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
439 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
442 PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
445 if (PSI->isFunctionHotInCallGraph(&F, *
BFI))
447 else if (PSI->isFunctionColdInCallGraph(&F, *
BFI))
453 if (!OptSize && !PSI->hasHugeWorkingSetSize() && TLI &&
454 TLI->isSlowDivBypassed()) {
456 TLI->getBypassSlowDivWidths();
458 while (BB !=
nullptr) {
471 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
473 bool ModifiedDT =
false;
475 EverMadeChange |= splitBranchCondition(F, ModifiedDT);
481 bool MadeChange =
true;
487 bool ModifiedDTOnIteration =
false;
488 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
491 if (ModifiedDTOnIteration)
495 MadeChange |= mergeSExts(F);
496 if (!LargeOffsetGEPMap.empty())
497 MadeChange |= splitLargeGEPOffsets();
503 EverMadeChange |= MadeChange;
504 SeenChainsForSExt.clear();
505 ValToSExtendedUses.clear();
506 RemovedInsts.clear();
507 LargeOffsetGEPMap.clear();
508 LargeOffsetGEPID.clear();
522 if (!MadeChange)
continue;
525 II = Successors.
begin(),
IE = Successors.
end(); II !=
IE; ++II)
531 MadeChange |= !WorkList.
empty();
532 while (!WorkList.
empty()) {
539 II = Successors.
begin(),
IE = Successors.
end(); II !=
IE; ++II)
546 if (EverMadeChange || MadeChange)
547 MadeChange |= eliminateFallThrough(F);
549 EverMadeChange |= MadeChange;
558 for (
auto &
I : Statepoints)
559 EverMadeChange |= simplifyOffsetableRelocate(*
I);
564 EverMadeChange |= placeDbgValues(F);
566 return EverMadeChange;
572 bool CodeGenPrepare::eliminateFallThrough(
Function &F) {
573 bool Changed =
false;
581 for (
auto &Block : Blocks) {
582 auto *BB = cast_or_null<BasicBlock>(Block);
590 if (!SinglePred || SinglePred == BB || BB->
hasAddressTaken())
continue;
614 if (BBI != BB->
begin()) {
616 while (isa<DbgInfoIntrinsic>(BBI)) {
617 if (BBI == BB->
begin())
621 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
630 if (!canMergeBlocks(BB, DestBB))
640 bool CodeGenPrepare::eliminateMostlyEmptyBlocks(
Function &F) {
643 while (!LoopList.empty()) {
644 Loop *L = LoopList.pop_back_val();
645 LoopList.insert(LoopList.end(), L->
begin(), L->
end());
647 Preheaders.
insert(Preheader);
650 bool MadeChange =
false;
658 for (
auto &Block : Blocks) {
659 BasicBlock *BB = cast_or_null<BasicBlock>(Block);
662 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
664 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.
count(BB)))
667 eliminateMostlyEmptyBlock(BB);
673 bool CodeGenPrepare::isMergingEmptyBlockProfitable(
BasicBlock *BB,
689 if (
auto *CBI = dyn_cast<CallBrInst>((*PI)->getTerminator()))
690 for (
unsigned i = 0,
e = CBI->getNumSuccessors(); i !=
e; ++i)
691 if (DestBB == CBI->getSuccessor(i))
723 if (!isa<PHINode>(DestBB->
begin()))
733 if (DestBBPred == BB)
737 return DestPN.getIncomingValueForBlock(BB) ==
738 DestPN.getIncomingValueForBlock(DestBBPred);
740 SameIncomingValueBBs.
insert(DestBBPred);
746 if (SameIncomingValueBBs.
count(Pred))
752 for (
auto SameValueBB : SameIncomingValueBBs)
753 if (SameValueBB->getUniquePredecessor() == Pred &&
754 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
755 BBFreq +=
BFI->getBlockFreq(SameValueBB);
764 bool CodeGenPrepare::canMergeBlocks(
const BasicBlock *BB,
772 if (UI->
getParent() != DestBB || !isa<PHINode>(UI))
778 if (
const PHINode *UPN = dyn_cast<PHINode>(UI))
779 for (
unsigned I = 0,
E = UPN->getNumIncomingValues();
I !=
E; ++
I) {
782 Insn->
getParent() != UPN->getIncomingBlock(
I))
793 if (!DestBBPN)
return true;
797 if (
const PHINode *BBPN = dyn_cast<PHINode>(BB->
begin())) {
799 for (
unsigned i = 0,
e = BBPN->getNumIncomingValues(); i !=
e; ++i)
800 BBPreds.
insert(BBPN->getIncomingBlock(i));
808 if (BBPreds.
count(Pred)) {
810 const Value *V1 = PN.getIncomingValueForBlock(Pred);
811 const Value *
V2 = PN.getIncomingValueForBlock(BB);
814 if (
const PHINode *V2PN = dyn_cast<PHINode>(V2))
815 if (V2PN->getParent() == BB)
816 V2 = V2PN->getIncomingValueForBlock(Pred);
819 if (V1 != V2)
return false;
829 void CodeGenPrepare::eliminateMostlyEmptyBlock(
BasicBlock *BB) {
839 if (SinglePred != DestBB) {
840 assert(SinglePred == BB &&
841 "Single predecessor not the same as predecessor");
853 for (
PHINode &PN : DestBB->phis()) {
855 Value *InVal = PN.removeIncomingValue(BB,
false);
860 if (InValPhi && InValPhi->
getParent() == BB) {
869 for (
unsigned i = 0,
e = BBPN->getNumIncomingValues(); i !=
e; ++i)
870 PN.addIncoming(InVal, BBPN->getIncomingBlock(i));
873 PN.addIncoming(InVal, *PI);
897 for (
auto *ThisRelocate : AllRelocateCalls) {
898 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
899 ThisRelocate->getDerivedPtrIndex());
900 RelocateIdxMap.
insert(std::make_pair(K, ThisRelocate));
902 for (
auto &Item : RelocateIdxMap) {
903 std::pair<unsigned, unsigned>
Key = Item.first;
904 if (Key.first == Key.second)
909 auto BaseKey = std::make_pair(Key.first, Key.first);
912 auto MaybeBase = RelocateIdxMap.find(BaseKey);
913 if (MaybeBase == RelocateIdxMap.end())
918 RelocateInstMap[MaybeBase->second].push_back(I);
929 if (!
Op ||
Op->getZExtValue() > 20)
943 bool MadeChange =
false;
951 &*R != RelocatedBase; ++R)
952 if (
auto RI = dyn_cast<GCRelocateInst>(R))
961 "Not relocating a derived object of the original base object");
962 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
977 if (!Derived || Derived->getPointerOperand() != Base)
986 "Should always have one since it's not a terminator");
1013 Value *ActualRelocatedBase = RelocatedBase;
1015 ActualRelocatedBase =
1016 Builder.CreateBitCast(RelocatedBase, Base->
getType());
1018 Value *Replacement = Builder.CreateGEP(
1019 Derived->getSourceElementType(), ActualRelocatedBase,
makeArrayRef(OffsetV));
1023 Value *ActualReplacement = Replacement;
1024 if (Replacement->
getType() != ToReplace->getType()) {
1026 Builder.CreateBitCast(Replacement, ToReplace->
getType());
1029 ToReplace->eraseFromParent();
1053 bool CodeGenPrepare::simplifyOffsetableRelocate(
Instruction &
I) {
1054 bool MadeChange =
false;
1057 for (
auto *U : I.
users())
1064 if (AllRelocateCalls.
size() < 2)
1071 if (RelocateInstMap.
empty())
1074 for (
auto &Item : RelocateInstMap)
1088 bool MadeChange =
false;
1091 Use &TheUse = UI.getUse();
1097 if (
PHINode *PN = dyn_cast<PHINode>(User)) {
1098 UserBB = PN->getIncomingBlock(TheUse);
1116 if (UserBB == DefBB)
continue;
1119 CastInst *&InsertedCast = InsertedCasts[UserBB];
1121 if (!InsertedCast) {
1125 CI->
getType(),
"", &*InsertPt);
1130 TheUse = InsertedCast;
1154 if (
auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
1156 ASC->getDestAddressSpace()))
1170 if (SrcVT.
bitsLT(DstVT))
return false;
1189 bool CodeGenPrepare::replaceMathCmpWithIntrinsic(
BinaryOperator *BO,
1210 IID == Intrinsic::usub_with_overflow) {
1211 assert(isa<Constant>(Arg1) &&
"Unexpected input for usubo");
1218 if (&Iter == BO || &Iter == Cmp) {
1223 assert(InsertPt !=
nullptr &&
"Parent block did not contain cmp or binop");
1244 if (isa<Constant>(A))
1259 Add = cast<BinaryOperator>(U);
1268 bool CodeGenPrepare::combineToUAddWithOverflow(
CmpInst *Cmp,
1277 TLI->getValueType(*DL, Add->
getType())))
1286 if (!replaceMathCmpWithIntrinsic(Add, Cmp, Intrinsic::uadd_with_overflow))
1294 bool CodeGenPrepare::combineToUSubWithOverflow(
CmpInst *Cmp,
1298 if (isa<Constant>(A) && isa<Constant>(
B))
1323 Value *CmpVariableOperand = isa<Constant>(A) ?
B : A;
1325 for (
User *U : CmpVariableOperand->
users()) {
1328 Sub = cast<BinaryOperator>(U);
1333 const APInt *CmpC, *AddC;
1336 Sub = cast<BinaryOperator>(U);
1344 TLI->getValueType(*DL, Sub->getType())))
1347 if (!replaceMathCmpWithIntrinsic(Sub, Cmp, Intrinsic::usub_with_overflow))
1372 bool MadeChange =
false;
1375 Use &TheUse = UI.getUse();
1382 if (isa<PHINode>(User))
1390 if (UserBB == DefBB)
continue;
1393 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1407 TheUse = InsertedCmp;
1452 if (isa<BranchInst>(U))
1454 if (isa<SelectInst>(U) && cast<SelectInst>(U)->getCondition() == Cmp)
1473 if (CmpBB != FalseBB)
1491 if (
auto *BI = dyn_cast<BranchInst>(U)) {
1492 assert(BI->isConditional() &&
"Must be conditional");
1493 BI->swapSuccessors();
1496 if (
auto *
SI = dyn_cast<SelectInst>(U)) {
1499 SI->swapProfMetadata();
1508 bool CodeGenPrepare::optimizeCmp(
CmpInst *Cmp,
bool &ModifiedDT) {
1512 if (combineToUAddWithOverflow(Cmp, ModifiedDT))
1515 if (combineToUSubWithOverflow(Cmp, ModifiedDT))
1531 SetOfInstrs &InsertedInsts) {
1534 assert(!InsertedInsts.count(AndI) &&
1535 "Attempting to optimize already optimized and instruction");
1536 (void) InsertedInsts;
1545 if (!isa<ConstantInt>(AndI->
getOperand(0)) &&
1550 for (
auto *U : AndI->
users()) {
1554 if (!isa<ICmpInst>(User))
1558 if (!CmpC || !CmpC->isZero())
1573 Use &TheUse = UI.getUse();
1591 TheUse = InsertedAnd;
1607 if (!isa<TruncInst>(User)) {
1608 if (User->
getOpcode() != Instruction::And ||
1612 const APInt &Cimm = cast<ConstantInt>(User->
getOperand(1))->getValue();
1614 if ((Cimm & (Cimm + 1)).getBoolValue())
1627 auto *TruncI = cast<TruncInst>(User);
1628 bool MadeChange =
false;
1631 TruncE = TruncI->user_end();
1632 TruncUI != TruncE;) {
1634 Use &TruncTheUse = TruncUI.getUse();
1635 Instruction *TruncUser = cast<Instruction>(*TruncUI);
1654 if (isa<PHINode>(TruncUser))
1659 if (UserBB == TruncUserBB)
1663 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1665 if (!InsertedShift && !InsertedTrunc) {
1669 if (ShiftI->
getOpcode() == Instruction::AShr)
1670 InsertedShift = BinaryOperator::CreateAShr(ShiftI->
getOperand(0), CI,
1673 InsertedShift = BinaryOperator::CreateLShr(ShiftI->
getOperand(0), CI,
1680 assert(TruncInsertPt != TruncUserBB->
end());
1683 TruncI->
getType(),
"", &*TruncInsertPt);
1684 InsertedTrunc->
setDebugLoc(TruncI->getDebugLoc());
1688 TruncTheUse = InsertedTrunc;
1721 bool MadeChange =
false;
1724 Use &TheUse = UI.getUse();
1730 if (isa<PHINode>(User))
1738 if (UserBB == DefBB) {
1753 if (isa<TruncInst>(User) && shiftIsLegal
1766 if (!InsertedShift) {
1770 if (ShiftI->
getOpcode() == Instruction::AShr)
1771 InsertedShift = BinaryOperator::CreateAShr(ShiftI->
getOperand(0), CI,
1774 InsertedShift = BinaryOperator::CreateLShr(ShiftI->
getOperand(0), CI,
1782 TheUse = InsertedShift;
1848 Builder.SetCurrentDebugLocation(CountZeros->
getDebugLoc());
1853 Value *Cmp = Builder.CreateICmpEQ(CountZeros->
getOperand(0), Zero,
"cmpz");
1854 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
1859 Builder.SetInsertPoint(&EndBlock->
front());
1860 PHINode *PN = Builder.CreatePHI(Ty, 2,
"ctz");
1862 Value *BitWidth = Builder.getInt(
APInt(SizeInBits, SizeInBits));
1874 bool CodeGenPrepare::optimizeCallInst(
CallInst *CI,
bool &ModifiedDT) {
1881 if (TLI->ExpandInlineAsm(CI)) {
1883 CurInstIterator = BB->
begin();
1890 if (optimizeInlineAsmInst(CI))
1896 unsigned MinSize, PrefAlign;
1897 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
1903 if (!
Arg->getType()->isPointerTy())
1906 cast<PointerType>(
Arg->getType())->getAddressSpace()),
1908 Value *Val =
Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
1910 if ((Offset2 & (PrefAlign-1)) != 0)
1913 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->
getAlignment() < PrefAlign &&
1931 if (DestAlign >
MI->getDestAlignment())
1932 MI->setDestAlignment(DestAlign);
1935 if (SrcAlign > MTI->getSourceAlignment())
1936 MTI->setSourceAlignment(SrcAlign);
1948 if (!
Arg->getType()->isPointerTy())
1950 unsigned AS =
Arg->getType()->getPointerAddressSpace();
1951 return optimizeMemoryInst(CI,
Arg,
Arg->getType(), AS);
1956 switch (II->getIntrinsicID()) {
1958 case Intrinsic::experimental_widenable_condition: {
1962 if (II->use_empty()) {
1967 resetIteratorIfInvalidatedWhileCalling(BB, [&]() {
1972 case Intrinsic::objectsize:
1974 case Intrinsic::is_constant:
1976 case Intrinsic::aarch64_stlxr:
1977 case Intrinsic::aarch64_stxr: {
1986 InsertedInsts.insert(ExtVal);
1990 case Intrinsic::launder_invariant_group:
1991 case Intrinsic::strip_invariant_group: {
1992 Value *ArgVal = II->getArgOperand(0);
1993 auto it = LargeOffsetGEPMap.find(II);
1994 if (it != LargeOffsetGEPMap.end()) {
1998 auto GEPs = std::move(it->second);
1999 LargeOffsetGEPMap[ArgVal].append(GEPs.begin(), GEPs.end());
2000 LargeOffsetGEPMap.erase(II);
2003 II->replaceAllUsesWith(ArgVal);
2004 II->eraseFromParent();
2007 case Intrinsic::cttz:
2008 case Intrinsic::ctlz:
2011 case Intrinsic::dbg_value:
2012 return fixupDbgValue(II);
2018 if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
2019 while (!PtrOps.
empty()) {
2022 if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
2075 bool CodeGenPrepare::dupRetToEnableTailCallOpts(
BasicBlock *BB,
bool &ModifiedDT) {
2104 do { ++BI; }
while (isa<DbgInfoIntrinsic>(BI) || &*BI == BCI);
2109 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
2126 TLI->mayBeEmittedAsTailCall(CI) &&
2133 if (!VisitedBBs.
insert(*PI).second)
2139 do { ++RI; }
while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
2144 if (CI && CI->
use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
2150 bool Changed =
false;
2151 for (
auto const &TailCallBB : TailCallBBs) {
2160 ModifiedDT = Changed =
true;
2180 Value *BaseReg =
nullptr;
2181 Value *ScaledReg =
nullptr;
2182 Value *OriginalValue =
nullptr;
2183 bool InBounds =
true;
2187 BaseRegField = 0x01,
2189 BaseOffsField = 0x04,
2190 ScaledRegField = 0x08,
2192 MultipleFields = 0xff
2196 ExtAddrMode() =
default;
2201 FieldName
compare(
const ExtAddrMode &other) {
2204 if (BaseReg && other.BaseReg &&
2205 BaseReg->
getType() != other.BaseReg->getType())
2206 return MultipleFields;
2207 if (BaseGV && other.BaseGV &&
2208 BaseGV->getType() != other.BaseGV->getType())
2209 return MultipleFields;
2210 if (ScaledReg && other.ScaledReg &&
2211 ScaledReg->
getType() != other.ScaledReg->getType())
2212 return MultipleFields;
2215 if (InBounds != other.InBounds)
2216 return MultipleFields;
2219 unsigned Result = NoField;
2220 if (BaseReg != other.BaseReg)
2221 Result |= BaseRegField;
2222 if (BaseGV != other.BaseGV)
2223 Result |= BaseGVField;
2224 if (BaseOffs != other.BaseOffs)
2225 Result |= BaseOffsField;
2226 if (ScaledReg != other.ScaledReg)
2227 Result |= ScaledRegField;
2230 if (Scale && other.Scale && Scale != other.Scale)
2231 Result |= ScaleField;
2234 return MultipleFields;
2236 return static_cast<FieldName
>(Result);
2246 return !BaseOffs && !Scale && !(BaseGV && BaseReg);
2257 case ScaledRegField:
2264 void SetCombinedField(FieldName Field,
Value *V,
2270 case ExtAddrMode::BaseRegField:
2273 case ExtAddrMode::BaseGVField:
2276 assert(BaseReg ==
nullptr);
2280 case ExtAddrMode::ScaledRegField:
2285 for (
const ExtAddrMode &AM : AddrModes)
2291 case ExtAddrMode::BaseOffsField:
2294 assert(ScaledReg ==
nullptr);
2312 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 2314 bool NeedPlus =
false;
2319 OS << (NeedPlus ?
" + " :
"")
2321 BaseGV->printAsOperand(OS,
false);
2326 OS << (NeedPlus ?
" + " :
"")
2332 OS << (NeedPlus ?
" + " :
"")
2334 BaseReg->printAsOperand(OS,
false);
2338 OS << (NeedPlus ?
" + " :
"")
2340 ScaledReg->printAsOperand(OS,
false);
2357 class TypePromotionTransaction {
2361 class TypePromotionAction {
2369 TypePromotionAction(
Instruction *Inst) : Inst(Inst) {}
2371 virtual ~TypePromotionAction() =
default;
2378 virtual void undo() = 0;
2383 virtual void commit() {
2389 class InsertionHandler {
2400 bool HasPrevInstruction;
2407 if (HasPrevInstruction)
2408 Point.PrevInst = &*--It;
2415 if (HasPrevInstruction) {
2430 class InstructionMoveBefore :
public TypePromotionAction {
2437 : TypePromotionAction(Inst),
Position(Inst) {
2438 LLVM_DEBUG(
dbgs() <<
"Do: move: " << *Inst <<
"\nbefore: " << *Before
2444 void undo()
override {
2446 Position.insert(Inst);
2451 class OperandSetter :
public TypePromotionAction {
2461 : TypePromotionAction(Inst), Idx(Idx) {
2463 <<
"for:" << *Inst <<
"\n" 2464 <<
"with:" << *NewVal <<
"\n");
2470 void undo()
override {
2472 <<
"for: " << *Inst <<
"\n" 2473 <<
"with: " << *Origin <<
"\n");
2480 class OperandsHider :
public TypePromotionAction {
2486 OperandsHider(
Instruction *Inst) : TypePromotionAction(Inst) {
2489 OriginalValues.
reserve(NumOpnds);
2490 for (
unsigned It = 0; It < NumOpnds; ++It) {
2502 void undo()
override {
2504 for (
unsigned It = 0, EndIt = OriginalValues.
size(); It != EndIt; ++It)
2510 class TruncBuilder :
public TypePromotionAction {
2517 TruncBuilder(
Instruction *Opnd,
Type *Ty) : TypePromotionAction(Opnd) {
2524 Value *getBuiltValue() {
return Val; }
2527 void undo()
override {
2529 if (
Instruction *IVal = dyn_cast<Instruction>(Val))
2530 IVal->eraseFromParent();
2535 class SExtBuilder :
public TypePromotionAction {
2543 : TypePromotionAction(InsertPt) {
2545 Val = Builder.
CreateSExt(Opnd, Ty,
"promoted");
2550 Value *getBuiltValue() {
return Val; }
2553 void undo()
override {
2555 if (
Instruction *IVal = dyn_cast<Instruction>(Val))
2556 IVal->eraseFromParent();
2561 class ZExtBuilder :
public TypePromotionAction {
2569 : TypePromotionAction(InsertPt) {
2571 Val = Builder.
CreateZExt(Opnd, Ty,
"promoted");
2576 Value *getBuiltValue() {
return Val; }
2579 void undo()
override {
2581 if (
Instruction *IVal = dyn_cast<Instruction>(Val))
2582 IVal->eraseFromParent();
2587 class TypeMutator :
public TypePromotionAction {
2594 : TypePromotionAction(Inst), OrigTy(Inst->
getType()) {
2595 LLVM_DEBUG(
dbgs() <<
"Do: MutateType: " << *Inst <<
" with " << *NewTy
2601 void undo()
override {
2602 LLVM_DEBUG(
dbgs() <<
"Undo: MutateType: " << *Inst <<
" with " << *OrigTy
2609 class UsesReplacer :
public TypePromotionAction {
2611 struct InstructionAndIdx {
2618 InstructionAndIdx(
Instruction *Inst,
unsigned Idx)
2619 : Inst(Inst), Idx(Idx) {}
2632 LLVM_DEBUG(
dbgs() <<
"Do: UsersReplacer: " << *Inst <<
" with " << *New
2636 Instruction *UserI = cast<Instruction>(U.getUser());
2637 OriginalUses.
push_back(InstructionAndIdx(UserI, U.getOperandNo()));
2648 void undo()
override {
2650 for (use_iterator UseIt = OriginalUses.
begin(),
2651 EndIt = OriginalUses.
end();
2652 UseIt != EndIt; ++UseIt) {
2653 UseIt->Inst->setOperand(UseIt->Idx, Inst);
2659 for (
auto *DVI: DbgValues) {
2662 DVI->setOperand(0, MV);
2668 class InstructionRemover :
public TypePromotionAction {
2674 OperandsHider Hider;
2677 UsesReplacer *Replacer =
nullptr;
2680 SetOfInstrs &RemovedInsts;
2687 InstructionRemover(
Instruction *Inst, SetOfInstrs &RemovedInsts,
2688 Value *New =
nullptr)
2689 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
2690 RemovedInsts(RemovedInsts) {
2692 Replacer =
new UsesReplacer(Inst, New);
2693 LLVM_DEBUG(
dbgs() <<
"Do: InstructionRemover: " << *Inst <<
"\n");
2694 RemovedInsts.insert(Inst);
2701 ~InstructionRemover()
override {
delete Replacer; }
2705 void undo()
override {
2706 LLVM_DEBUG(
dbgs() <<
"Undo: InstructionRemover: " << *Inst <<
"\n");
2707 Inserter.insert(Inst);
2711 RemovedInsts.erase(Inst);
2719 using ConstRestorationPt =
const TypePromotionAction *;
2721 TypePromotionTransaction(SetOfInstrs &RemovedInsts)
2722 : RemovedInsts(RemovedInsts) {}
2728 void rollback(ConstRestorationPt Point);
2731 ConstRestorationPt getRestorationPoint()
const;
2766 SetOfInstrs &RemovedInsts;
2771 void TypePromotionTransaction::setOperand(
Instruction *Inst,
unsigned Idx,
2773 Actions.
push_back(std::make_unique<TypePromotionTransaction::OperandSetter>(
2774 Inst, Idx, NewVal));
2780 std::make_unique<TypePromotionTransaction::InstructionRemover>(
2781 Inst, RemovedInsts, NewVal));
2784 void TypePromotionTransaction::replaceAllUsesWith(
Instruction *Inst,
2787 std::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
2790 void TypePromotionTransaction::mutateType(
Instruction *Inst,
Type *NewTy) {
2792 std::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
2797 std::unique_ptr<TruncBuilder> Ptr(
new TruncBuilder(Opnd, Ty));
2798 Value *Val = Ptr->getBuiltValue();
2799 Actions.push_back(std::move(Ptr));
2805 std::unique_ptr<SExtBuilder> Ptr(
new SExtBuilder(Inst, Opnd, Ty));
2806 Value *Val = Ptr->getBuiltValue();
2807 Actions.push_back(std::move(Ptr));
2813 std::unique_ptr<ZExtBuilder> Ptr(
new ZExtBuilder(Inst, Opnd, Ty));
2814 Value *Val = Ptr->getBuiltValue();
2815 Actions.push_back(std::move(Ptr));
2819 void TypePromotionTransaction::moveBefore(
Instruction *Inst,
2822 std::make_unique<TypePromotionTransaction::InstructionMoveBefore>(
2826 TypePromotionTransaction::ConstRestorationPt
2827 TypePromotionTransaction::getRestorationPoint()
const {
2828 return !Actions.empty() ? Actions.back().get() :
nullptr;
2831 void TypePromotionTransaction::commit() {
2832 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
2838 void TypePromotionTransaction::rollback(
2839 TypePromotionTransaction::ConstRestorationPt Point) {
2840 while (!Actions.empty() && Point != Actions.back().get()) {
2841 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
2851 class AddressingModeMatcher {
2868 const SetOfInstrs &InsertedInsts;
2871 InstrToOrigTy &PromotedInsts;
2874 TypePromotionTransaction &TPT;
2877 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP;
2881 bool IgnoreProfitability;
2889 AddressingModeMatcher(
2892 ExtAddrMode &AM,
const SetOfInstrs &InsertedInsts,
2893 InstrToOrigTy &PromotedInsts, TypePromotionTransaction &TPT,
2896 : AddrModeInsts(AMI), TLI(TLI),
TRI(TRI),
2898 MemoryInst(MI),
AddrMode(AM), InsertedInsts(InsertedInsts),
2899 PromotedInsts(PromotedInsts), TPT(TPT), LargeOffsetGEP(LargeOffsetGEP),
2900 OptSize(OptSize), PSI(PSI),
BFI(BFI) {
2901 IgnoreProfitability =
false;
2916 const SetOfInstrs &InsertedInsts, InstrToOrigTy &PromotedInsts,
2917 TypePromotionTransaction &TPT,
2922 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI, AccessTy, AS,
2923 MemoryInst, Result, InsertedInsts,
2924 PromotedInsts, TPT, LargeOffsetGEP,
2927 (void)Success;
assert(Success &&
"Couldn't select *anything*?");
2932 bool matchScaledValue(
Value *ScaleReg, int64_t Scale,
unsigned Depth);
2933 bool matchAddr(
Value *Addr,
unsigned Depth);
2934 bool matchOperationAddr(
User *AddrInst,
unsigned Opcode,
unsigned Depth,
2935 bool *MovedAway =
nullptr);
2936 bool isProfitableToFoldIntoAddressingMode(
Instruction *I,
2937 ExtAddrMode &AMBefore,
2938 ExtAddrMode &AMAfter);
2939 bool valueAlreadyLiveAtInst(
Value *Val,
Value *KnownLive1,
Value *KnownLive2);
2940 bool isPromotionProfitable(
unsigned NewCost,
unsigned OldCost,
2941 Value *PromotedOperand)
const;
2947 class PhiNodeSetIterator {
2948 PhiNodeSet *
const Set;
2949 size_t CurrentIndex = 0;
2954 PhiNodeSetIterator(PhiNodeSet *
const Set,
size_t Start);
2956 PhiNodeSetIterator& operator++();
2957 bool operator==(
const PhiNodeSetIterator &RHS)
const;
2958 bool operator!=(
const PhiNodeSetIterator &RHS)
const;
2972 friend class PhiNodeSetIterator;
2975 using iterator = PhiNodeSetIterator;
2990 size_t FirstValidElement = 0;
2997 if (NodeMap.insert(std::make_pair(Ptr, NodeList.
size())).second) {
3008 auto it = NodeMap.find(Ptr);
3009 if (it != NodeMap.end()) {
3011 SkipRemovedElements(FirstValidElement);
3021 FirstValidElement = 0;
3027 if (FirstValidElement == 0)
3028 SkipRemovedElements(FirstValidElement);
3029 return PhiNodeSetIterator(
this, FirstValidElement);
3033 iterator
end() {
return PhiNodeSetIterator(
this, NodeList.
size()); }
3036 size_t size()
const {
3037 return NodeMap.size();
3042 return NodeMap.count(Ptr);
3051 void SkipRemovedElements(
size_t &CurrentIndex) {
3052 while (CurrentIndex < NodeList.
size()) {
3053 auto it = NodeMap.find(NodeList[CurrentIndex]);
3056 if (it != NodeMap.end() && it->second == CurrentIndex)
3063 PhiNodeSetIterator::PhiNodeSetIterator(PhiNodeSet *
const Set,
size_t Start)
3064 : Set(Set), CurrentIndex(Start) {}
3068 "PhiNodeSet access out of range");
3069 return Set->NodeList[CurrentIndex];
3072 PhiNodeSetIterator& PhiNodeSetIterator::operator++() {
3074 "PhiNodeSet access out of range");
3076 Set->SkipRemovedElements(CurrentIndex);
3081 return CurrentIndex == RHS.CurrentIndex;
3085 return !((*this) == RHS);
3091 class SimplificationTracker {
3096 PhiNodeSet AllPhiNodes;
3106 auto SV = Storage.
find(V);
3107 if (SV == Storage.
end())
3117 while (!WorkList.
empty()) {
3119 if (!Visited.
insert(
P).second)
3121 if (
auto *PI = dyn_cast<Instruction>(
P))
3123 for (
auto *U : PI->users())
3126 PI->replaceAllUsesWith(V);
3127 if (
auto *PHI = dyn_cast<PHINode>(PI))
3128 AllPhiNodes.erase(PHI);
3129 if (
auto *
Select = dyn_cast<SelectInst>(PI))
3131 PI->eraseFromParent();
3142 Value* OldReplacement = Get(From);
3143 while (OldReplacement != From) {
3146 OldReplacement = Get(From);
3148 assert(To && Get(To) == To &&
"Replacement PHI node is already replaced.");
3151 AllPhiNodes.erase(From);
3155 PhiNodeSet& newPhiNodes() {
return AllPhiNodes; }
3157 void insertNewPhi(
PHINode *PN) { AllPhiNodes.insert(PN); }
3161 unsigned countNewPhiNodes()
const {
return AllPhiNodes.size(); }
3163 unsigned countNewSelectNodes()
const {
return AllSelectNodes.
size(); }
3165 void destroyNewNodes(
Type *CommonType) {
3168 for (
auto I : AllPhiNodes) {
3172 AllPhiNodes.
clear();
3173 for (
auto I : AllSelectNodes) {
3177 AllSelectNodes.
clear();
3182 class AddressingModeCombiner {
3184 typedef std::pair<PHINode *, PHINode *> PHIPair;
3191 ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField;
3194 bool AllAddrModesTrivial =
true;
3207 : CommonType(
nullptr), SQ(_SQ), Original(OriginalValue) {}
3211 return AddrModes[0];
3217 bool addNewAddrMode(ExtAddrMode &NewAddrMode) {
3221 AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial();
3224 if (AddrModes.
empty()) {
3232 ExtAddrMode::FieldName ThisDifferentField =
3233 AddrModes[0].compare(NewAddrMode);
3234 if (DifferentField == ExtAddrMode::NoField)
3235 DifferentField = ThisDifferentField;
3236 else if (DifferentField != ThisDifferentField)
3237 DifferentField = ExtAddrMode::MultipleFields;
3240 bool CanHandle = DifferentField != ExtAddrMode::MultipleFields;
3243 CanHandle = CanHandle && DifferentField != ExtAddrMode::ScaleField;
3248 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseOffsField ||
3249 !NewAddrMode.ScaledReg);
3253 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseGVField ||
3254 !NewAddrMode.HasBaseReg);
3271 bool combineAddrModes() {
3273 if (AddrModes.
size() == 0)
3277 if (AddrModes.
size() == 1 || DifferentField == ExtAddrMode::NoField)
3282 if (AllAddrModesTrivial)
3285 if (!addrModeCombiningAllowed())
3291 FoldAddrToValueMapping Map;
3292 if (!initializeMap(Map))
3295 Value *CommonValue = findCommon(Map);
3297 AddrModes[0].SetCombinedField(DifferentField, CommonValue, AddrModes);
3298 return CommonValue !=
nullptr;
3307 bool initializeMap(FoldAddrToValueMapping &Map) {
3312 for (
auto &AM : AddrModes) {
3313 Value *DV = AM.GetFieldAsValue(DifferentField, IntPtrTy);
3316 if (CommonType && CommonType !=
Type)
3319 Map[AM.OriginalValue] = DV;
3324 assert(CommonType &&
"At least one non-null value must be!");
3325 for (
auto *V : NullValue)
3353 Value *findCommon(FoldAddrToValueMapping &Map) {
3361 SimplificationTracker
ST(SQ);
3366 InsertPlaceholders(Map, TraverseOrder, ST);
3369 FillPlaceholders(Map, TraverseOrder, ST);
3372 ST.destroyNewNodes(CommonType);
3377 unsigned PhiNotMatchedCount = 0;
3379 ST.destroyNewNodes(CommonType);
3383 auto *Result = ST.Get(Map.find(Original)->second);
3385 NumMemoryInstsPhiCreated += ST.countNewPhiNodes() + PhiNotMatchedCount;
3386 NumMemoryInstsSelectCreated += ST.countNewSelectNodes();
3395 PhiNodeSet &PhiNodesToMatch) {
3397 Matcher.
insert({ PHI, Candidate });
3402 while (!WorkList.
empty()) {
3404 if (!Visited.
insert(Item).second)
3411 for (
auto B : Item.first->blocks()) {
3412 Value *FirstValue = Item.first->getIncomingValueForBlock(
B);
3413 Value *SecondValue = Item.second->getIncomingValueForBlock(
B);
3414 if (FirstValue == SecondValue)
3424 if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) ||
3429 if (Matcher.
count({ FirstPhi, SecondPhi }))
3434 if (MatchedPHIs.
insert(FirstPhi).second)
3435 Matcher.
insert({ FirstPhi, SecondPhi });
3437 WorkList.
push_back({ FirstPhi, SecondPhi });
3446 bool MatchPhiSet(SimplificationTracker &
ST,
bool AllowNewPhiNodes,
3447 unsigned &PhiNotMatchedCount) {
3453 PhiNodeSet &PhiNodesToMatch = ST.newPhiNodes();
3454 while (PhiNodesToMatch.size()) {
3455 PHINode *PHI = *PhiNodesToMatch.begin();
3458 WillNotMatch.
clear();
3459 WillNotMatch.
insert(PHI);
3462 bool IsMatched =
false;
3466 if ((IsMatched = MatchPhiNode(PHI, &
P, Matched, PhiNodesToMatch)))
3471 for (
auto M : Matched)
3472 WillNotMatch.
insert(M.first);
3477 for (
auto MV : Matched)
3478 ST.ReplacePhi(MV.first, MV.second);
3483 if (!AllowNewPhiNodes)
3486 PhiNotMatchedCount += WillNotMatch.
size();
3487 for (
auto *
P : WillNotMatch)
3488 PhiNodesToMatch.erase(
P);
3493 void FillPlaceholders(FoldAddrToValueMapping &Map,
3495 SimplificationTracker &ST) {
3496 while (!TraverseOrder.
empty()) {
3498 assert(Map.find(Current) != Map.end() &&
"No node to fill!!!");
3499 Value *V = Map[Current];
3503 auto *CurrentSelect = cast<SelectInst>(Current);
3504 auto *TrueValue = CurrentSelect->getTrueValue();
3505 assert(Map.find(TrueValue) != Map.end() &&
"No True Value!");
3506 Select->setTrueValue(ST.Get(Map[TrueValue]));
3507 auto *FalseValue = CurrentSelect->getFalseValue();
3508 assert(Map.find(FalseValue) != Map.end() &&
"No False Value!");
3509 Select->setFalseValue(ST.Get(Map[FalseValue]));
3512 auto *PHI = cast<PHINode>(V);
3515 Value *PV = cast<PHINode>(Current)->getIncomingValueForBlock(
B);
3516 assert(Map.find(PV) != Map.end() &&
"No predecessor Value!");
3520 Map[Current] = ST.Simplify(V);
3529 void InsertPlaceholders(FoldAddrToValueMapping &Map,
3531 SimplificationTracker &ST) {
3533 assert((isa<PHINode>(Original) || isa<SelectInst>(Original)) &&
3534 "Address must be a Phi or Select node");
3537 while (!Worklist.
empty()) {
3540 if (Map.find(Current) != Map.end())
3546 if (
SelectInst *CurrentSelect = dyn_cast<SelectInst>(Current)) {
3551 CurrentSelect->getName(), CurrentSelect, CurrentSelect);
3553 ST.insertNewSelect(Select);
3555 Worklist.
push_back(CurrentSelect->getTrueValue());
3556 Worklist.
push_back(CurrentSelect->getFalseValue());
3559 PHINode *CurrentPhi = cast<PHINode>(Current);
3564 ST.insertNewPhi(PHI);
3571 bool addrModeCombiningAllowed() {
3574 switch (DifferentField) {
3577 case ExtAddrMode::BaseRegField:
3579 case ExtAddrMode::BaseGVField:
3581 case ExtAddrMode::BaseOffsField:
3583 case ExtAddrMode::ScaledRegField:
3593 bool AddressingModeMatcher::matchScaledValue(
Value *ScaleReg, int64_t Scale,
3598 return matchAddr(ScaleReg, Depth);
3609 ExtAddrMode TestAddrMode =
AddrMode;
3613 TestAddrMode.Scale += Scale;
3614 TestAddrMode.ScaledReg = ScaleReg;
3617 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
3627 if (isa<Instruction>(ScaleReg) &&
3629 TestAddrMode.InBounds =
false;
3630 TestAddrMode.ScaledReg = AddLHS;
3631 TestAddrMode.BaseOffs += CI->
getSExtValue()*TestAddrMode.Scale;
3635 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
3636 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
3652 case Instruction::BitCast:
3653 case Instruction::AddrSpaceCast:
3658 case Instruction::PtrToInt:
3661 case Instruction::IntToPtr:
3666 case Instruction::Mul:
3667 case Instruction::Shl:
3670 case Instruction::GetElementPtr:
3698 class TypePromotionHelper {
3701 static void addPromotedInst(InstrToOrigTy &PromotedInsts,
3704 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
3705 InstrToOrigTy::iterator It = PromotedInsts.find(ExtOpnd);
3706 if (It != PromotedInsts.end()) {
3709 if (It->second.getInt() == ExtTy)
3715 ExtTy = BothExtension;
3717 PromotedInsts[ExtOpnd] = TypeIsSExt(ExtOpnd->
getType(), ExtTy);
3724 static const Type *getOrigType(
const InstrToOrigTy &PromotedInsts,
3727 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
3728 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
3729 if (It != PromotedInsts.end() && It->second.getInt() == ExtTy)
3730 return It->second.getPointer();
3745 static bool canGetThrough(
const Instruction *Inst,
Type *ConsideredExtType,
3746 const InstrToOrigTy &PromotedInsts,
bool IsSExt);
3750 static bool shouldExtOperand(
const Instruction *Inst,
int OpIdx) {
3751 return !(isa<SelectInst>(Inst) && OpIdx == 0);
3763 static Value *promoteOperandForTruncAndAnyExt(
3765 InstrToOrigTy &PromotedInsts,
unsigned &CreatedInstsCost,
3779 TypePromotionTransaction &TPT,
3780 InstrToOrigTy &PromotedInsts,
3781 unsigned &CreatedInstsCost,
3787 static Value *signExtendOperandForOther(
3789 InstrToOrigTy &PromotedInsts,
unsigned &CreatedInstsCost,
3792 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3793 Exts, Truncs, TLI,
true);
3797 static Value *zeroExtendOperandForOther(
3799 InstrToOrigTy &PromotedInsts,
unsigned &CreatedInstsCost,
3802 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3803 Exts, Truncs, TLI,
false);
3809 InstrToOrigTy &PromotedInsts,
3810 unsigned &CreatedInstsCost,
3824 static Action getAction(
Instruction *Ext,
const SetOfInstrs &InsertedInsts,
3826 const InstrToOrigTy &PromotedInsts);
3831 bool TypePromotionHelper::canGetThrough(
const Instruction *Inst,
3832 Type *ConsideredExtType,
3833 const InstrToOrigTy &PromotedInsts,
3842 if (isa<ZExtInst>(Inst))
3846 if (IsSExt && isa<SExtInst>(Inst))
3852 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
3858 if ((Inst->
getOpcode() == Instruction::And ||
3863 if (Inst->
getOpcode() == Instruction::Xor) {
3875 if (Inst->
getOpcode() == Instruction::LShr && !IsSExt)
3884 const auto *ExtInst = cast<const Instruction>(*Inst->
user_begin());
3885 if (ExtInst->hasOneUse()) {
3887 if (AndInst && AndInst->getOpcode() == Instruction::And) {
3898 if (!isa<TruncInst>(Inst))
3920 const Type *OpndType = getOrigType(PromotedInsts, Opnd, IsSExt);
3923 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
3933 TypePromotionHelper::Action TypePromotionHelper::getAction(
3936 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3937 "Unexpected instruction type");
3940 bool IsSExt = isa<SExtInst>(
Ext);
3944 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
3950 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
3955 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
3956 isa<ZExtInst>(ExtOpnd))
3957 return promoteOperandForTruncAndAnyExt;
3963 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
3966 Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
3968 InstrToOrigTy &PromotedInsts,
unsigned &CreatedInstsCost,
3974 Value *ExtVal = SExt;
3975 bool HasMergedNonFreeExt =
false;
3976 if (isa<ZExtInst>(SExtOpnd)) {
3979 HasMergedNonFreeExt = !TLI.
isExtFree(SExtOpnd);
3982 TPT.replaceAllUsesWith(SExt, ZExt);
3983 TPT.eraseInstruction(SExt);
3988 TPT.setOperand(SExt, 0, SExtOpnd->
getOperand(0));
3990 CreatedInstsCost = 0;
3994 TPT.eraseInstruction(SExtOpnd);
4002 CreatedInstsCost = !TLI.
isExtFree(ExtInst) && !HasMergedNonFreeExt;
4010 TPT.eraseInstruction(ExtInst, NextVal);
4014 Value *TypePromotionHelper::promoteOperandForOther(
4016 InstrToOrigTy &PromotedInsts,
unsigned &CreatedInstsCost,
4023 CreatedInstsCost = 0;
4029 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->
getType());
4030 if (
Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
4032 ITrunc->moveAfter(ExtOpnd);
4037 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
4040 TPT.setOperand(Ext, 0, ExtOpnd);
4050 addPromotedInst(PromotedInsts, ExtOpnd, IsSExt);
4052 TPT.mutateType(ExtOpnd, Ext->
getType());
4054 TPT.replaceAllUsesWith(Ext, ExtOpnd);
4059 for (
int OpIdx = 0, EndOpIdx = ExtOpnd->
getNumOperands(); OpIdx != EndOpIdx;
4063 !shouldExtOperand(ExtOpnd, OpIdx)) {
4069 if (
const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
4072 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
4073 : Cst->getValue().zext(BitWidth);
4078 if (isa<UndefValue>(Opnd)) {
4089 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->
getType())
4090 : TPT.createZExt(Ext, Opnd, Ext->
getType());
4091 if (!isa<Instruction>(ValForExtOpnd)) {
4092 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
4095 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
4099 TPT.setOperand(ExtForOpnd, 0, Opnd);
4102 TPT.moveBefore(ExtForOpnd, ExtOpnd);
4103 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
4104 CreatedInstsCost += !TLI.
isExtFree(ExtForOpnd);
4106 ExtForOpnd =
nullptr;
4108 if (ExtForOpnd == Ext) {
4110 TPT.eraseInstruction(Ext);
4123 bool AddressingModeMatcher::isPromotionProfitable(
4124 unsigned NewCost,
unsigned OldCost,
Value *PromotedOperand)
const {
4125 LLVM_DEBUG(
dbgs() <<
"OldCost: " << OldCost <<
"\tNewCost: " << NewCost
4130 if (NewCost > OldCost)
4132 if (NewCost < OldCost)
4151 bool AddressingModeMatcher::matchOperationAddr(
User *AddrInst,
unsigned Opcode,
4155 if (Depth >= 5)
return false;
4162 case Instruction::PtrToInt:
4165 case Instruction::IntToPtr: {
4173 case Instruction::BitCast:
4183 case Instruction::AddrSpaceCast: {
4193 ExtAddrMode BackupAddrMode =
AddrMode;
4194 unsigned OldSize = AddrModeInsts.size();
4199 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4200 TPT.getRestorationPoint();
4203 if (matchAddr(AddrInst->
getOperand(1), Depth+1) &&
4209 AddrModeInsts.resize(OldSize);
4210 TPT.rollback(LastKnownGood);
4213 if (matchAddr(AddrInst->
getOperand(0), Depth+1) &&
4219 AddrModeInsts.resize(OldSize);
4220 TPT.rollback(LastKnownGood);
4226 case Instruction::Mul:
4227 case Instruction::Shl: {
4234 if (Opcode == Instruction::Shl)
4235 Scale = 1LL << Scale;
4239 case Instruction::GetElementPtr: {
4242 int VariableOperand = -1;
4243 unsigned VariableScale = 0;
4245 int64_t ConstantOffset = 0;
4251 cast<ConstantInt>(AddrInst->
getOperand(i))->getZExtValue();
4256 const APInt &CVal = CI->getValue();
4264 if (VariableOperand != -1)
4268 VariableOperand = i;
4269 VariableScale = TypeSize;
4276 if (VariableOperand == -1) {
4277 AddrMode.BaseOffs += ConstantOffset;
4278 if (ConstantOffset == 0 ||
4281 if (matchAddr(AddrInst->
getOperand(0), Depth+1)) {
4282 if (!cast<GEPOperator>(AddrInst)->isInBounds())
4288 ConstantOffset > 0) {
4295 auto *
GEP = cast<GetElementPtrInst>(AddrInst);
4296 if (isa<Argument>(Base) || isa<GlobalValue>(Base) ||
4297 (BaseI && !isa<CastInst>(BaseI) &&
4298 !isa<GetElementPtrInst>(BaseI))) {
4304 LargeOffsetGEP = std::make_pair(GEP, ConstantOffset);
4307 AddrMode.BaseOffs -= ConstantOffset;
4312 ExtAddrMode BackupAddrMode =
AddrMode;
4313 unsigned OldSize = AddrModeInsts.size();
4316 AddrMode.BaseOffs += ConstantOffset;
4317 if (!cast<GEPOperator>(AddrInst)->isInBounds())
4321 if (!matchAddr(AddrInst->
getOperand(0), Depth+1)) {
4325 AddrModeInsts.resize(OldSize);
4333 if (!matchScaledValue(AddrInst->
getOperand(VariableOperand), VariableScale,
4338 AddrModeInsts.resize(OldSize);
4343 AddrMode.BaseOffs += ConstantOffset;
4344 if (!matchScaledValue(AddrInst->
getOperand(VariableOperand),
4345 VariableScale,
Depth)) {
4348 AddrModeInsts.resize(OldSize);
4355 case Instruction::SExt:
4356 case Instruction::ZExt: {
4363 TypePromotionHelper::Action TPH =
4364 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
4368 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4369 TPT.getRestorationPoint();
4370 unsigned CreatedInstsCost = 0;
4372 Value *PromotedOperand =
4373 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost,
nullptr,
nullptr, TLI);
4388 assert(PromotedOperand &&
4389 "TypePromotionHelper should have filtered out those cases");
4391 ExtAddrMode BackupAddrMode =
AddrMode;
4392 unsigned OldSize = AddrModeInsts.size();
4394 if (!matchAddr(PromotedOperand, Depth) ||
4399 !isPromotionProfitable(CreatedInstsCost,
4400 ExtCost + (AddrModeInsts.size() - OldSize),
4403 AddrModeInsts.resize(OldSize);
4404 LLVM_DEBUG(
dbgs() <<
"Sign extension does not pay off: rollback\n");
4405 TPT.rollback(LastKnownGood);
4419 bool AddressingModeMatcher::matchAddr(
Value *Addr,
unsigned Depth) {
4422 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4423 TPT.getRestorationPoint();
4424 if (
ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
4426 AddrMode.BaseOffs += CI->getSExtValue();
4429 AddrMode.BaseOffs -= CI->getSExtValue();
4430 }
else if (
GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
4438 }
else if (
Instruction *I = dyn_cast<Instruction>(Addr)) {
4439 ExtAddrMode BackupAddrMode =
AddrMode;
4440 unsigned OldSize = AddrModeInsts.size();
4443 bool MovedAway =
false;
4453 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode,
AddrMode)) {
4454 AddrModeInsts.push_back(I);
4461 AddrModeInsts.resize(OldSize);
4462 TPT.rollback(LastKnownGood);
4464 }
else if (
ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
4465 if (matchOperationAddr(CE, CE->getOpcode(),
Depth))
4467 TPT.rollback(LastKnownGood);
4468 }
else if (isa<ConstantPointerNull>(Addr)) {
4494 TPT.rollback(LastKnownGood);
4508 for (
unsigned i = 0,
e = TargetConstraints.size(); i !=
e; ++i) {
4539 if (!ConsideredInsts.
insert(I).second)
4550 if (SeenInsts++ >= MaxMemoryUsesToScan)
4553 Instruction *UserI = cast<Instruction>(U.getUser());
4554 if (
LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
4555 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
4560 unsigned opNo = U.getOperandNo();
4563 MemoryUses.push_back(std::make_pair(
SI, opNo));
4568 unsigned opNo = U.getOperandNo();
4571 MemoryUses.push_back(std::make_pair(RMW, opNo));
4576 unsigned opNo = U.getOperandNo();
4579 MemoryUses.push_back(std::make_pair(CmpX, opNo));
4583 if (
CallInst *CI = dyn_cast<CallInst>(UserI)) {
4586 bool OptForSize = OptSize ||
4592 if (!IA)
return true;
4601 PSI, BFI, SeenInsts))
4612 bool AddressingModeMatcher::valueAlreadyLiveAtInst(
Value *Val,
Value *KnownLive1,
4613 Value *KnownLive2) {
4615 if (Val ==
nullptr || Val == KnownLive1 || Val == KnownLive2)
4619 if (!isa<Instruction>(Val) && !isa<Argument>(Val))
return true;
4624 if (
AllocaInst *AI = dyn_cast<AllocaInst>(Val))
4625 if (AI->isStaticAlloca())
4655 bool AddressingModeMatcher::
4656 isProfitableToFoldIntoAddressingMode(
Instruction *I, ExtAddrMode &AMBefore,
4657 ExtAddrMode &AMAfter) {
4658 if (IgnoreProfitability)
return true;
4669 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
4673 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
4675 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
4676 ScaledReg =
nullptr;
4680 if (!BaseReg && !ScaledReg)
4703 for (
unsigned i = 0,
e = MemoryUses.
size(); i !=
e; ++i) {
4705 unsigned OpNo = MemoryUses[i].second;
4720 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(
nullptr,
4722 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4723 TPT.getRestorationPoint();
4724 AddressingModeMatcher Matcher(
4725 MatchedAddrModeInsts, TLI,
TRI, AddressAccessTy, AS, MemoryInst, Result,
4726 InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP, OptSize, PSI,
BFI);
4727 Matcher.IgnoreProfitability =
true;
4728 bool Success = Matcher.matchAddr(Address, 0);
4729 (void)Success;
assert(Success &&
"Couldn't select *anything*?");
4734 TPT.rollback(LastKnownGood);
4740 MatchedAddrModeInsts.
clear();
4773 bool CodeGenPrepare::optimizeMemoryInst(
Instruction *MemoryInst,
Value *Addr,
4774 Type *AccessTy,
unsigned AddrSpace) {
4786 bool PhiOrSelectSeen =
false;
4789 AddressingModeCombiner AddrModes(SQ, Addr);
4790 TypePromotionTransaction TPT(RemovedInsts);
4791 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4792 TPT.getRestorationPoint();
4793 while (!worklist.
empty()) {
4806 if (!Visited.
insert(V).second)
4810 if (
PHINode *
P = dyn_cast<PHINode>(V)) {
4811 for (
Value *IncValue :
P->incoming_values())
4813 PhiOrSelectSeen =
true;
4820 PhiOrSelectSeen =
true;
4827 AddrModeInsts.
clear();
4828 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(
nullptr,
4831 V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *
TRI,
4832 InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP, OptSize, PSI,
4836 if (GEP && !NewGEPBases.count(GEP)) {
4840 LargeOffsetGEPMap[GEP->getPointerOperand()].push_back(LargeOffsetGEP);
4841 if (LargeOffsetGEPID.find(GEP) == LargeOffsetGEPID.end())
4842 LargeOffsetGEPID[GEP] = LargeOffsetGEPID.size();
4845 NewAddrMode.OriginalValue = V;
4846 if (!AddrModes.addNewAddrMode(NewAddrMode))
4853 if (!AddrModes.combineAddrModes()) {
4854 TPT.rollback(LastKnownGood);
4860 ExtAddrMode
AddrMode = AddrModes.getAddrMode();
4866 if (!PhiOrSelectSeen &&
none_of(AddrModeInsts, [&](
Value *V) {
4889 LLVM_DEBUG(
dbgs() <<
"CGP: Reusing nonlocal addrmode: " << AddrMode
4890 <<
" for " << *MemoryInst <<
"\n");
4894 TM && SubtargetInfo->addrSinkUsingGEPs())) {
4897 LLVM_DEBUG(
dbgs() <<
"CGP: SINKING nonlocal addrmode: " << AddrMode
4898 <<
" for " << *MemoryInst <<
"\n");
4899 Type *IntPtrTy = DL->getIntPtrType(Addr->
getType());
4900 Value *ResultPtr =
nullptr, *ResultIndex =
nullptr;
4903 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
4904 ResultPtr = AddrMode.BaseReg;
4905 AddrMode.BaseReg =
nullptr;
4908 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
4911 if (ResultPtr || AddrMode.Scale != 1)
4914 ResultPtr = AddrMode.ScaledReg;
4925 if (AddrMode.Scale) {
4926 Type *ScaledRegTy = AddrMode.ScaledReg->getType();
4932 if (AddrMode.BaseGV) {
4936 ResultPtr = AddrMode.BaseGV;
4942 if (!DL->isNonIntegralPointerType(Addr->
getType())) {
4943 if (!ResultPtr && AddrMode.BaseReg) {
4946 AddrMode.BaseReg =
nullptr;
4947 }
else if (!ResultPtr && AddrMode.Scale == 1) {
4955 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
4957 }
else if (!ResultPtr) {
4969 if (AddrMode.BaseReg) {
4970 Value *V = AddrMode.BaseReg;
4978 if (AddrMode.Scale) {
4979 Value *V = AddrMode.ScaledReg;
4980 if (V->
getType() == IntPtrTy) {
4985 "We can't transform if ScaledReg is too narrow");
4989 if (AddrMode.Scale != 1)
4993 ResultIndex = Builder.
CreateAdd(ResultIndex, V,
"sunkaddr");
4999 if (AddrMode.BaseOffs) {
5004 if (ResultPtr->
getType() != I8PtrTy)
5010 : Builder.
CreateGEP(I8Ty, ResultPtr, ResultIndex,
"sunkaddr");
5017 SunkAddr = ResultPtr;
5019 if (ResultPtr->
getType() != I8PtrTy)
5025 : Builder.
CreateGEP(I8Ty, ResultPtr, ResultIndex,
"sunkaddr");
5034 Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() :
nullptr;
5035 Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() :
nullptr;
5036 PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy);
5037 PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy);
5038 if (DL->isNonIntegralPointerType(Addr->
getType()) ||
5039 (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) ||
5040 (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) ||
5042 DL->isNonIntegralPointerType(AddrMode.BaseGV->getType())))
5045 LLVM_DEBUG(
dbgs() <<
"CGP: SINKING nonlocal addrmode: " << AddrMode
5046 <<
" for " << *MemoryInst <<
"\n");
5047 Type *IntPtrTy = DL->getIntPtrType(Addr->
getType());
5048 Value *Result =
nullptr;
5055 if (AddrMode.BaseReg) {
5056 Value *V = AddrMode.BaseReg;
5065 if (AddrMode.Scale) {
5066 Value *V = AddrMode.ScaledReg;
5067 if (V->
getType() == IntPtrTy) {
5071 }
else if (cast<IntegerType>(IntPtrTy)->
getBitWidth() <
5080 Instruction *I = dyn_cast_or_null<Instruction>(Result);
5081 if (I && (Result != AddrMode.BaseReg))
5085 if (AddrMode.Scale != 1)
5089 Result = Builder.
CreateAdd(Result, V,
"sunkaddr");
5095 if (AddrMode.BaseGV) {
5098 Result = Builder.
CreateAdd(Result, V,
"sunkaddr");
5104 if (AddrMode.BaseOffs) {
5107 Result = Builder.
CreateAdd(Result, V,
"sunkaddr");
5128 Value *CurValue = &*CurInstIterator;
5134 if (IterHandle != CurValue) {
5137 CurInstIterator = BB->
begin();
5147 bool CodeGenPrepare::optimizeInlineAsmInst(
CallInst *CS) {
5148 bool MadeChange =
false;
5151 TM->getSubtargetImpl(*CS->
getFunction())->getRegisterInfo();
5155 for (
unsigned i = 0,
e = TargetConstraints.size(); i !=
e; ++i) {
5164 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->
getType(), ~0u);
5177 bool IsSExt = isa<SExtInst>(FirstUser);
5178 Type *ExtTy = FirstUser->getType();
5181 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
5204 if (ExtTy->getScalarType()->getIntegerBitWidth() >
5227 bool CodeGenPrepare::tryToPromoteExts(
5230 unsigned CreatedInstsCost) {
5231 bool Promoted =
false;
5234 for (
auto I : Exts) {
5249 TypePromotionHelper::Action TPH =
5250 TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
5259 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5260 TPT.getRestorationPoint();
5262 unsigned NewCreatedInstsCost = 0;
5265 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
5266 &NewExts,
nullptr, *TLI);
5268 "TypePromotionHelper should have filtered out those cases");
5276 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
5279 TotalCreatedInstsCost =
5280 std::max((
long long)0, (TotalCreatedInstsCost - ExtCost));
5282 (TotalCreatedInstsCost > 1 ||
5287 TPT.rollback(LastKnownGood);
5293 (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
5294 bool NewPromoted =
false;
5295 for (
auto ExtInst : NewlyMovedExts) {
5296 Instruction *MovedExt = cast<Instruction>(ExtInst);
5300 if (isa<LoadInst>(ExtOperand) &&
5302 (ExtOperand->hasOneUse() ||
hasSameExtUse(ExtOperand, *TLI))))
5305 ProfitablyMovedExts.
push_back(MovedExt);
5312 TPT.rollback(LastKnownGood);
5323 bool CodeGenPrepare::mergeSExts(
Function &F) {
5324 bool Changed =
false;
5325 for (
auto &
Entry : ValToSExtendedUses) {
5326 SExts &Insts =
Entry.second;
5329 if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) ||
5332 bool inserted =
false;
5333 for (
auto &Pt : CurPts) {
5334 if (getDT(F).dominates(Inst, Pt)) {
5335 Pt->replaceAllUsesWith(Inst);
5336 RemovedInsts.insert(Pt);
5337 Pt->removeFromParent();
5343 if (!getDT(F).dominates(Pt, Inst))
5348 RemovedInsts.insert(Inst);
5355 CurPts.push_back(Inst);
5397 bool CodeGenPrepare::splitLargeGEPOffsets() {
5398 bool Changed =
false;
5399 for (
auto &
Entry : LargeOffsetGEPMap) {
5402 &LargeOffsetGEPs =
Entry.second;
5403 auto compareGEPOffset =
5404 [&](
const std::pair<GetElementPtrInst *, int64_t> &LHS,
5405 const std::pair<GetElementPtrInst *, int64_t> &RHS) {
5406 if (LHS.first == RHS.first)
5408 if (LHS.second != RHS.second)
5409 return LHS.second < RHS.second;
5410 return LargeOffsetGEPID[LHS.first] < LargeOffsetGEPID[RHS.first];
5413 llvm::sort(LargeOffsetGEPs, compareGEPOffset);
5414 LargeOffsetGEPs.
erase(
5415 std::unique(LargeOffsetGEPs.
begin(), LargeOffsetGEPs.
end()),
5416 LargeOffsetGEPs.
end());
5418 if (LargeOffsetGEPs.
front().second == LargeOffsetGEPs.
back().second)
5421 int64_t BaseOffset = LargeOffsetGEPs.
begin()->second;
5422 Value *NewBaseGEP =
nullptr;
5424 auto LargeOffsetGEP = LargeOffsetGEPs.
begin();
5425 while (LargeOffsetGEP != LargeOffsetGEPs.
end()) {
5427 int64_t
Offset = LargeOffsetGEP->second;
5428 if (Offset != BaseOffset) {
5430 AddrMode.BaseOffs = Offset - BaseOffset;
5441 NewBaseGEP =
nullptr;
5447 Type *IntPtrTy = DL->getIntPtrType(GEP->
getType());
5457 if (
auto *BaseI = dyn_cast<Instruction>(OldBase)) {
5461 if (isa<PHINode>(BaseI))
5463 else if (
InvokeInst *Invoke = dyn_cast<InvokeInst>(BaseI)) {
5465 SplitEdge(NewBaseInsertBB, Invoke->getNormalDest());
5468 NewBaseInsertPt = std::next(BaseI->getIterator());
5475 IRBuilder<> NewBaseBuilder(NewBaseInsertBB, NewBaseInsertPt);
5478 NewBaseGEP = OldBase;
5479 if (NewBaseGEP->
getType() != I8PtrTy)
5482 NewBaseBuilder.
CreateGEP(I8Ty, NewBaseGEP, BaseIndex,
"splitgep");
5483 NewGEPBases.insert(NewBaseGEP);
5487 Value *NewGEP = NewBaseGEP;
5488 if (Offset == BaseOffset) {
5489 if (GEP->
getType() != I8PtrTy)
5494 NewGEP = Builder.
CreateGEP(I8Ty, NewBaseGEP, Index);
5496 if (GEP->
getType() != I8PtrTy)
5500 LargeOffsetGEPID.erase(GEP);
5501 LargeOffsetGEP = LargeOffsetGEPs.
erase(LargeOffsetGEP);
5511 bool CodeGenPrepare::canFormExtLd(
5514 for (
auto *MovedExtInst : MovedExts) {
5515 if (isa<LoadInst>(MovedExtInst->getOperand(0))) {
5516 LI = cast<LoadInst>(MovedExtInst->getOperand(0));
5517 Inst = MovedExtInst;
5569 bool CodeGenPrepare::optimizeExt(
Instruction *&Inst) {
5575 bool AllowPromotionWithoutCommonHeader =
false;
5579 bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
5580 *Inst, AllowPromotionWithoutCommonHeader);
5581 TypePromotionTransaction TPT(RemovedInsts);
5582 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5583 TPT.getRestorationPoint();
5588 bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts);
5596 if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) {
5597 assert(LI && ExtFedByLoad &&
"Expect a valid load and extension");
5610 Inst = ExtFedByLoad;
5615 if (ATPConsiderable &&
5616 performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
5617 HasPromoted, TPT, SpeculativelyMovedExts))
5620 TPT.rollback(LastKnownGood);
5629 bool CodeGenPrepare::performAddressTypePromotion(
5630 Instruction *&Inst,
bool AllowPromotionWithoutCommonHeader,
5631 bool HasPromoted, TypePromotionTransaction &TPT,
5633 bool Promoted =
false;
5635 bool AllSeenFirst =
true;
5636 for (
auto I : SpeculativelyMovedExts) {
5639 SeenChainsForSExt.
find(HeadOfChain);
5642 if (AlreadySeen != SeenChainsForSExt.
end()) {
5643 if (AlreadySeen->second !=
nullptr)
5644 UnhandledExts.
insert(AlreadySeen->second);
5645 AllSeenFirst =
false;
5649 if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
5650 SpeculativelyMovedExts.size() == 1)) {
5654 for (
auto I : SpeculativelyMovedExts) {
5656 SeenChainsForSExt[HeadOfChain] =
nullptr;
5657 ValToSExtendedUses[HeadOfChain].push_back(I);
5660 Inst = SpeculativelyMovedExts.pop_back_val();
5665 for (
auto I : SpeculativelyMovedExts) {
5667 SeenChainsForSExt[HeadOfChain] = Inst;
5672 if (!AllSeenFirst && !UnhandledExts.
empty())
5673 for (
auto VisitedSExt : UnhandledExts) {
5674 if (RemovedInsts.count(VisitedSExt))
5676 TypePromotionTransaction TPT(RemovedInsts);
5680 bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains);
5684 for (
auto I : Chains) {
5687 SeenChainsForSExt[HeadOfChain] =
nullptr;
5688 ValToSExtendedUses[HeadOfChain].push_back(I);
5694 bool CodeGenPrepare::optimizeExtUses(
Instruction *I) {
5709 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->
getParent())
5712 bool DefIsLiveOut =
false;
5718 if (UserBB == DefBB)
continue;
5719 DefIsLiveOut =
true;
5729 if (UserBB == DefBB)
continue;
5732 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
5739 bool MadeChange =
false;
5745 if (UserBB == DefBB)
continue;
5748 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
5750 if (!InsertedTrunc) {
5752 assert(InsertPt != UserBB->end());
5754 InsertedInsts.insert(InsertedTrunc);
5823 InsertedInsts.count(cast<Instruction>(*Load->
user_begin())))
5831 for (
auto *U : Load->
users())
5832 WorkList.
push_back(cast<Instruction>(U));
5836 APInt DemandBits(BitWidth, 0);
5837 APInt WidestAndBits(BitWidth, 0);
5839 while (!WorkList.
empty()) {
5844 if (!Visited.
insert(I).second)
5848 if (
auto *Phi = dyn_cast<PHINode>(I)) {
5849 for (
auto *U : Phi->users())
5850 WorkList.
push_back(cast<Instruction>(U));
5855 case Instruction::And: {
5859 APInt AndBits = AndC->getValue();
5860 DemandBits |= AndBits;
5862 if (AndBits.
ugt(WidestAndBits))
5863 WidestAndBits = AndBits;
5869 case Instruction::Shl: {
5878 case Instruction::Trunc: {
5902 if (ActiveBits <= 1 || !DemandBits.
isMask(ActiveBits) ||
5903 WidestAndBits != DemandBits)
5916 auto *NewAnd = cast<Instruction>(
5920 InsertedInsts.insert(NewAnd);
5925 NewAnd->setOperand(0, Load);
5928 for (
auto *And : AndsToMaybeRemove)
5931 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
5932 And->replaceAllUsesWith(NewAnd);
5933 if (&*CurInstIterator == And)
5934 CurInstIterator = std::next(And->getIterator());
5935 And->eraseFromParent();
5966 uint64_t TrueWeight, FalseWeight;
5968 uint64_t Max =
std::max(TrueWeight, FalseWeight);
5969 uint64_t Sum = TrueWeight + FalseWeight;
6003 for (
SelectInst *DefSI = SI; DefSI !=
nullptr && Selects.
count(DefSI);
6006 "The condition of DefSI does not match with SI");
6007 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
6010 assert(V &&
"Failed to get select true/false value");
6030 Value *Cond, *TVal, *FVal;
6049 bool CodeGenPrepare::optimizeSelectInst(
SelectInst *
SI) {
6072 CurInstIterator = std::next(LastSI->
getIterator());
6077 if (VectorCond || SI->
getMetadata(LLVMContext::MD_unpredictable))
6125 BFI->setBlockFreq(EndBlock,
BFI->getBlockFreq(StartBlock).getFrequency());
6141 if (TrueBlock ==
nullptr) {
6147 auto *TrueInst = cast<Instruction>(SI->
getTrueValue());
6148 TrueInst->moveBefore(TrueBranch);
6151 if (FalseBlock ==
nullptr) {
6158 FalseInst->moveBefore(FalseBranch);
6164 if (TrueBlock == FalseBlock) {
6165 assert(TrueBlock ==
nullptr &&
6166 "Unexpected basic block transform while optimizing select");
6180 if (TrueBlock ==
nullptr) {
6183 TrueBlock = StartBlock;
6184 }
else if (FalseBlock ==
nullptr) {
6187 FalseBlock = StartBlock;
6195 INS.insert(ASI.begin(), ASI.end());
6199 for (
auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
6211 ++NumSelectsExpanded;
6215 CurInstIterator = StartBlock->
end();
6222 for (
unsigned i = 0; i <
Mask.size(); ++i) {
6223 if (SplatElem != -1 &&
Mask[i] != -1 &&
Mask[i] != SplatElem)
6225 SplatElem =
Mask[i];
6250 bool MadeChange =
false;
6256 if (UserBB == DefBB)
continue;
6263 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
6265 if (!InsertedShuffle) {
6267 assert(InsertPt != UserBB->end());
6287 bool CodeGenPrepare::tryToSinkFreeOperands(
Instruction *I) {
6299 bool Changed =
false;
6302 auto *UI = cast<Instruction>(U->get());
6303 if (UI->getParent() == TargetBB || isa<PHINode>(UI))
6311 for (
Use *U : ToReplace) {
6312 auto *UI = cast<Instruction>(U->get());
6314 NewInstructions[UI] = NI;
6316 LLVM_DEBUG(
dbgs() <<
"Sinking " << *UI <<
" to user " << *I <<
"\n");
6317 NI->insertBefore(InsertPoint);
6319 InsertedInsts.insert(NI);
6324 Instruction *OldI = cast<Instruction>(U->getUser());
6325 if (NewInstructions.
count(OldI))
6326 NewInstructions[OldI]->setOperand(U->getOperandNo(), NI);
6333 for (
auto *I : MaybeDead) {
6335 LLVM_DEBUG(
dbgs() <<
"Removing dead instruction: " << *I <<
"\n");
6343 bool CodeGenPrepare::optimizeSwitchInst(
SwitchInst *SI) {
6353 if (RegWidth <= cast<IntegerType>(OldType)->
getBitWidth())
6369 if (
auto *
Arg = dyn_cast<Argument>(Cond))
6370 if (
Arg->hasSExtAttr())
6371 ExtType = Instruction::SExt;
6374 ExtInst->insertBefore(SI);
6377 for (
auto Case : SI->
cases()) {
6378 APInt NarrowConst = Case.getCaseValue()->getValue();
6379 APInt WideConst = (ExtType == Instruction::ZExt) ?
6380 NarrowConst.
zext(RegWidth) : NarrowConst.
sext(RegWidth);
6405 class VectorPromoteHelper {
6422 unsigned StoreExtractCombineCost;
6431 if (InstsToBePromoted.
empty())
6433 return InstsToBePromoted.
back();
6439 unsigned getTransitionOriginalValueIdx()
const {
6440 assert(isa<ExtractElementInst>(Transition) &&
6441 "Other kind of transitions are not supported yet");
6448 unsigned getTransitionIdx()
const {
6449 assert(isa<ExtractElementInst>(Transition) &&
6450 "Other kind of transitions are not supported yet");
6458 Type *getTransitionType()
const {
6473 bool isProfitableToPromote() {
6474 Value *ValIdx = Transition->
getOperand(getTransitionOriginalValueIdx());
6475 unsigned Index = isa<ConstantInt>(ValIdx)
6476 ? cast<ConstantInt>(ValIdx)->getZExtValue()
6478 Type *PromotedType = getTransitionType();
6495 uint64_t ScalarCost =
6497 uint64_t VectorCost = StoreExtractCombineCost;
6498 for (
const auto &Inst : InstsToBePromoted) {
6504 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
6505 isa<ConstantFP>(Arg0);
6518 dbgs() <<
"Estimated cost of computation to be promoted:\nScalar: " 6519 << ScalarCost <<
"\nVector: " << VectorCost <<
'\n');
6520 return ScalarCost > VectorCost;
6537 if (
ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
6538 ExtractIdx = CstVal->getSExtValue();
6543 unsigned End = getTransitionType()->getVectorNumElements();
6549 for (
unsigned Idx = 0; Idx != End; ++Idx) {
6550 if (Idx == ExtractIdx)
6561 unsigned OperandIdx) {
6564 if (OperandIdx != 1)
6569 case Instruction::SDiv:
6570 case Instruction::UDiv:
6571 case Instruction::SRem:
6572 case Instruction::URem:
6574 case Instruction::FDiv:
6575 case Instruction::FRem:
6584 unsigned CombineCost)
6585 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
6586 StoreExtractCombineCost(CombineCost) {
6587 assert(Transition &&
"Do not know how to promote null");
6591 bool canPromote(
const Instruction *ToBePromoted)
const {
6593 return isa<BinaryOperator>(ToBePromoted);
6598 bool shouldPromote(
const Instruction *ToBePromoted)
const {
6601 for (
const Use &U : ToBePromoted->
operands()) {
6602 const Value *Val = U.get();
6603 if (Val == getEndOfTransition()) {
6607 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
6611 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
6612 !isa<ConstantFP>(Val))
6621 ISDOpcode, TLI.
getValueType(DL, getTransitionType(),
true));
6630 void enqueueForPromotion(
Instruction *ToBePromoted) {
6631 InstsToBePromoted.
push_back(ToBePromoted);
6635 void recordCombineInstruction(
Instruction *ToBeCombined) {
6637 CombineInst = ToBeCombined;
6647 if (InstsToBePromoted.
empty() || !CombineInst)
6655 for (
auto &ToBePromoted : InstsToBePromoted)
6656 promoteImpl(ToBePromoted);
6657 InstsToBePromoted.clear();
6664 void VectorPromoteHelper::promoteImpl(
Instruction *ToBePromoted) {
6674 "The type of the result of the transition does not match " 6679 Type *TransitionTy = getTransitionType();
6685 Value *Val = U.get();
6686 Value *NewVal =
nullptr;
6687 if (Val == Transition)
6688 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
6689 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
6690 isa<ConstantFP>(Val)) {
6693 cast<Constant>(Val),
6694 isa<UndefValue>(Val) ||
6695 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
6699 ToBePromoted->
setOperand(U.getOperandNo(), NewVal);
6701 Transition->moveAfter(ToBePromoted);
6702 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
6708 bool CodeGenPrepare::optimizeExtractElementInst(
Instruction *Inst) {
6724 LLVM_DEBUG(
dbgs() <<
"Found an interesting transition: " << *Inst <<
'\n');
6725 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
6732 if (ToBePromoted->
getParent() != Parent) {
6733 LLVM_DEBUG(
dbgs() <<
"Instruction to promote is in a different block (" 6735 <<
") than the transition (" << Parent->
getName()
6740 if (VPH.canCombine(ToBePromoted)) {
6742 <<
"will be combined with: " << *ToBePromoted <<
'\n');
6743 VPH.recordCombineInstruction(ToBePromoted);
6744 bool Changed = VPH.promote();
6745 NumStoreExtractExposed += Changed;
6750 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
6753 LLVM_DEBUG(
dbgs() <<
"Promoting is possible... Enqueue for promotion!\n");
6755 VPH.enqueueForPromotion(ToBePromoted);
6756 Inst = ToBePromoted;
6849 if (LBC && LBC->getParent() != SI.
getParent())
6850 LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
6851 if (HBC && HBC->getParent() != SI.
getParent())
6852 HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
6855 auto CreateSplitStore = [&](
Value *V,
bool Upper) {
6856 V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
6857 Value *Addr = Builder.CreateBitCast(
6860 const bool IsOffsetStore = (IsLE &&
Upper) || (!IsLE && !
Upper);
6862 Addr = Builder.CreateGEP(
6863 SplitStoreType, Addr,
6866 if (IsOffsetStore && Alignment) {
6872 Builder.CreateAlignedStore(
6873 V, Addr, Alignment.hasValue() ? Alignment.getValue().value() : 0);
6876 CreateSplitStore(LValue,
false);
6877 CreateSplitStore(HValue,
true);
6967 if (!isa<Instruction>(GEPIOp))
6969 auto *GEPIOpI = cast<Instruction>(GEPIOp);
6970 if (GEPIOpI->getParent() != SrcBlock)
6975 if (
auto *I = dyn_cast<Instruction>(Usr)) {
6981 }) == GEPI->
users().end())
6984 std::vector<GetElementPtrInst *> UGEPIs;
6988 if (Usr == GEPI)
continue;
6990 if (!isa<Instruction>(Usr))
6992 auto *UI = cast<Instruction>(Usr);
6994 if (UI->getParent() == SrcBlock)
6997 if (!isa<GetElementPtrInst>(Usr))
6999 auto *UGEPI = cast<GetElementPtrInst>(Usr);
7005 if (UGEPI->getOperand(0) != GEPIOp)
7008 cast<ConstantInt>(UGEPI->getOperand(1))->
getType())
7010 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
7014 UGEPIs.push_back(UGEPI);
7016 if (UGEPIs.size() == 0)
7020 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
7028 UGEPI->setOperand(0, GEPI);
7029 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
7037 UGEPI->setIsInBounds(
false);
7043 return cast<Instruction>(Usr)->
getParent() != SrcBlock;
7044 }) == GEPIOp->
users().end() &&
"GEPIOp is used outside SrcBlock");
7048 bool CodeGenPrepare::optimizeInst(
Instruction *I,
bool &ModifiedDT) {
7051 if (InsertedInsts.count(I))
7055 if (
PHINode *
P = dyn_cast<PHINode>(I)) {
7060 LargeOffsetGEPMap.erase(
P);
7061 P->replaceAllUsesWith(V);
7062 P->eraseFromParent();
7069 if (
CastInst *CI = dyn_cast<CastInst>(I)) {
7082 if (isa<ZExtInst>(I) || isa<SExtInst>(
I)) {
7091 bool MadeChange = optimizeExt(I);
7092 return MadeChange | optimizeExtUses(I);
7098 if (
auto *Cmp = dyn_cast<CmpInst>(I))
7099 if (TLI && optimizeCmp(Cmp, ModifiedDT))
7102 if (
LoadInst *LI = dyn_cast<LoadInst>(I)) {
7103 LI->
setMetadata(LLVMContext::MD_invariant_group,
nullptr);
7105 bool Modified = optimizeLoadExt(LI);
7113 if (
StoreInst *SI = dyn_cast<StoreInst>(I)) {
7116 SI->
setMetadata(LLVMContext::MD_invariant_group,
nullptr);
7118 unsigned AS = SI->getPointerAddressSpace();
7119 return optimizeMemoryInst(I, SI->
getOperand(1),
7126 unsigned AS = RMW->getPointerAddressSpace();
7127 return optimizeMemoryInst(I, RMW->getPointerOperand(),
7132 unsigned AS = CmpX->getPointerAddressSpace();
7133 return optimizeMemoryInst(I, CmpX->getPointerOperand(),
7134 CmpX->getCompareOperand()->
getType(), AS);
7139 if (BinOp && (BinOp->getOpcode() == Instruction::And) &&
7144 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
7145 BinOp->getOpcode() == Instruction::LShr)) {
7153 if (GEPI->hasAllZeroIndices()) {
7156 GEPI->getName(), GEPI);
7158 GEPI->replaceAllUsesWith(NC);
7159 GEPI->eraseFromParent();
7161 optimizeInst(NC, ModifiedDT);
7170 if (tryToSinkFreeOperands(I))
7174 case Instruction::Shl:
7175 case Instruction::LShr:
7176 case Instruction::AShr:
7177 return optimizeShiftInst(cast<BinaryOperator>(I));
7179 return optimizeCallInst(cast<CallInst>(I), ModifiedDT);
7181 return optimizeSelectInst(cast<SelectInst>(I));
7182 case Instruction::ShuffleVector:
7183 return optimizeShuffleVectorInst(cast<ShuffleVectorInst>(I));
7184 case Instruction::Switch:
7185 return optimizeSwitchInst(cast<SwitchInst>(I));
7186 case Instruction::ExtractElement:
7187 return optimizeExtractElementInst(cast<ExtractElementInst>(I));
7214 bool CodeGenPrepare::optimizeBlock(
BasicBlock &BB,
bool &ModifiedDT) {
7216 bool MadeChange =
false;
7218 CurInstIterator = BB.
begin();
7219 while (CurInstIterator != BB.
end()) {
7220 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
7225 bool MadeBitReverse =
true;
7226 while (TLI && MadeBitReverse) {
7227 MadeBitReverse =
false;
7230 MadeBitReverse = MadeChange =
true;
7235 MadeChange |= dupRetToEnableTailCallOpts(&BB, ModifiedDT);
7242 bool CodeGenPrepare::fixupDbgValue(
Instruction *I) {
7243 assert(isa<DbgValueInst>(I));
7267 bool CodeGenPrepare::placeDbgValues(
Function &F) {
7268 bool MadeChange =
false;
7294 << *DVI <<
' ' << *VI);
7296 if (isa<PHINode>(VI))
7309 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
7311 NewTrue = NewTrue / Scale;
7312 NewFalse = NewFalse / Scale;
7337 bool CodeGenPrepare::splitBranchCondition(
Function &F,
bool &ModifiedDT) {
7341 bool MadeChange =
false;
7342 for (
auto &BB : F) {
7354 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
7362 Value *Cond1, *Cond2;
7365 Opc = Instruction::And;
7368 Opc = Instruction::Or;
7385 Br1->setCondition(Cond1);
7390 if (Opc == Instruction::And)
7391 Br1->setSuccessor(0, TmpBB);
7393 Br1->setSuccessor(1, TmpBB);
7396 auto *Br2 =
IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
7397 if (
auto *I = dyn_cast<Instruction>(Cond2)) {
7411 if (Opc == Instruction::Or)
7419 auto *Val = PN.getIncomingValueForBlock(&BB);
7420 PN.addIncoming(Val, TmpBB);
7425 if (Opc == Instruction::Or) {
7445 uint64_t TrueWeight, FalseWeight;
7446 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
7447 uint64_t NewTrueWeight = TrueWeight;
7448 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
7450 Br1->setMetadata(LLVMContext::MD_prof,
MDBuilder(Br1->getContext())
7451 .createBranchWeights(TrueWeight, FalseWeight));
7453 NewTrueWeight = TrueWeight;
7454 NewFalseWeight = 2 * FalseWeight;
7456 Br2->setMetadata(LLVMContext::MD_prof,
MDBuilder(Br2->getContext())
7457 .createBranchWeights(TrueWeight, FalseWeight));
7478 uint64_t TrueWeight, FalseWeight;
7479 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
7480 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
7481 uint64_t NewFalseWeight = FalseWeight;
7483 Br1->setMetadata(LLVMContext::MD_prof,
MDBuilder(Br1->getContext())
7484 .createBranchWeights(TrueWeight, FalseWeight));
7486 NewTrueWeight = 2 * TrueWeight;
7487 NewFalseWeight = FalseWeight;
7489 Br2->setMetadata(LLVMContext::MD_prof,
MDBuilder(Br2->getContext())
7490 .createBranchWeights(TrueWeight, FalseWeight));
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
const Function & getFunction() const
Value * CreateInBoundsGEP(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &Name="")
static void eraseInstruction(Instruction &I, ICFLoopSafetyInfo &SafetyInfo, AliasSetTracker *AST, MemorySSAUpdater *MSSAU)
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
static bool GEPSequentialConstIndexed(GetElementPtrInst *GEP)
Return a value (possibly void), from a function.
Value * getValueOperand()
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
static MVT getIntegerVT(unsigned BitWidth)
IntegerType * getType() const
getType - Specialize the getType() method to always return an IntegerType, which reduces the amount o...
A parsed version of the target data layout string in and methods for querying it. ...
const_iterator end(StringRef path)
Get end iterator over path.
reference emplace_back(ArgTypes &&... Args)
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
This class is the base class for the comparison instructions.
unsigned getAddrMode(MCInstrInfo const &MCII, MCInst const &MCI)
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.
void DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified block, which must have no predecessors.
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...
APInt sext(unsigned width) const
Sign extend to a new width.
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
static bool isPromotedInstructionLegal(const TargetLowering &TLI, const DataLayout &DL, Value *Val)
Check whether or not Val is a legal instruction for TLI.
iterator_range< CaseIt > cases()
Iteration adapter for range-for loops.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
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."))
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.
LLVM_NODISCARD T pop_back_val()
brc_match< Cond_t, bind_ty< BasicBlock >, bind_ty< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
This class represents lattice values for constants.
BinaryOps getOpcode() const
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
static bool MightBeFoldableInst(Instruction *I)
This is a little filter, which returns true if an addressing computation involving I might be folded ...
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...
static cl::opt< bool > EnableICMP_EQToICMP_ST("cgp-icmp-eq2icmp-st", cl::Hidden, cl::init(false), cl::desc("Enable ICMP_EQ to ICMP_S(L|G)T conversion."))
bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=nullptr, DomTreeUpdater *DTU=nullptr)
If a terminator instruction is predicated on a constant value, convert it into an unconditional branc...
Value * optimizeCall(CallInst *CI)
Take the given call instruction and return a more optimal value to replace the instruction with or 0 ...
virtual bool isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const
Return if the target supports combining a chain like:
bool hasOptSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
An instruction that atomically checks whether a specified value is in a memory location, and, if it is, stores a new value there.
This class represents zero extension of integer types.
void push_back(const T &Elt)
TypeSize getSizeInBits() const
Returns the size of the specified MVT in bits.
static cl::opt< bool > EnableGEPOffsetSplit("cgp-split-large-offset-gep", cl::Hidden, cl::init(true), cl::desc("Enable splitting large offset of GEP."))
Analysis providing profile information.
APInt zext(unsigned width) const
Zero extend to a new width.
This class represents a function call, abstracting a target machine's calling convention.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
Value * getCondition() const
const Value * getTrueValue() const
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))
virtual bool isSelectSupported(SelectSupportKind) const
bool salvageDebugInfo(Instruction &I)
Assuming the instruction I is going to be deleted, attempt to salvage debug users of I by writing the...
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
static cl::opt< bool > AddrSinkCombineBaseOffs("addr-sink-combine-base-offs", cl::Hidden, cl::init(true), cl::desc("Allow combining of BaseOffs field in Address sinking."))
This instruction constructs a fixed permutation of two input vectors.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", Instruction *InsertBefore=nullptr, Instruction *MDFrom=nullptr)
LLVMContext & getContext() const
All values hold a context through their type.
bool isTerminator() const
void setSectionPrefix(StringRef Prefix)
Set the section prefix for this function.
This class implements a map that also provides access to all stored values in a deterministic order...
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
static void dump(StringRef Title, SpillInfo const &Spills)
BasicBlock * getSuccessor(unsigned i) const
Value * CreateSExt(Value *V, Type *DestTy, const Twine &Name="")
STATISTIC(NumFunctions, "Total number of functions")
unsigned const TargetRegisterInfo * TRI
void setArgOperand(unsigned i, Value *v)
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...
bool isInteger() const
Return true if this is an integer or a vector integer type.
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"))
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool hasMultipleConditionRegisters() const
Return true if multiple condition registers are available.
An instruction for reading from memory.
bool hasExtractBitsInsn() const
Return true if the target has BitExtract instructions.
an instruction that atomically reads a memory location, combines it with another value, and then stores the result back.
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
bool isVectorTy() const
True if this is an instance of VectorType.
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...
This defines the Use class.
void reserve(size_type N)
Value * CallOperandVal
If this is the result output operand or a clobber, this is null, otherwise it is the incoming 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...
bool typeSizeEqualsStoreSize(Type *Ty) const
Returns true if no extra padding bits are needed when storing the specified type. ...
bool hasNoSignedWrap() const
Determine whether the no signed wrap flag is set.
LLVMContext & getContext() const
Get the context in which this basic block lives.
cst_pred_ty< is_zero_int > m_ZeroInt()
Match an integer 0 or a vector with all elements equal to 0.
unsigned getBitWidth() const
getBitWidth - Return the bitwidth of this constant.
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...
const CallBase * getStatepoint() const
The statepoint with which this gc.relocate is associated.
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
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"))
virtual bool isFreeAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const
Returns true if a cast from SrcAS to DestAS is "cheap", such that e.g.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
iterator begin()
Instruction iterator methods.
bool MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, MemoryDependenceResults *MemDep=nullptr, bool PredecessorWithTwoSuccessors=false)
Attempts to merge a block into its predecessor, if possible.
BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Split the edge connecting specified block.
MVT getRegisterType(MVT VT) const
Return the type of registers that this ValueType will eventually require.
Value * getArgOperand(unsigned i) const
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
void dump() const
Support for debugging, callable in GDB: V->dump()
bool match(Val *V, const Pattern &P)
AnalysisUsage & addRequired()
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
#define INITIALIZE_PASS_DEPENDENCY(depName)
bool replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI=nullptr, const DominatorTree *DT=nullptr, AssumptionCache *AC=nullptr, SmallSetVector< Instruction *, 8 > *UnsimplifiedUsers=nullptr)
Replace all uses of 'I' with 'SimpleV' and simplify the uses recursively.
This class represents the LLVM 'select' instruction.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
unsigned getAlignment() const
Return the alignment of the memory that is being allocated by the instruction.
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
This is the base class for all instructions that perform data casts.
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.
void replacePhiUsesWith(BasicBlock *Old, BasicBlock *New)
Update all phi nodes in this basic block to refer to basic block New instead of basic block Old...
A Use represents the edge between a Value definition and its users.
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
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...
bool isIntegerTy() const
True if this is an instance of IntegerType.
static cl::opt< bool > DisableBranchOpts("disable-cgp-branch-opts", cl::Hidden, cl::init(false), cl::desc("Disable branch optimizations in CodeGenPrepare"))
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly...
This file contains the simple types necessary to represent the attributes associated with functions a...
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...
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
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...
Position
Position to insert a new instruction relative to an existing instruction.
Align commonAlignment(Align A, Align B)
Returns the alignment that satisfies both alignments.
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
APInt operator*(APInt a, uint64_t RHS)
This file implements a class to represent arbitrary precision integral constant values and operations...
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)
virtual bool isTruncateFree(Type *FromTy, Type *ToTy) const
Return true if it's free to truncate a value of type FromTy to type ToTy.
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...
ReturnInst * FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB, BasicBlock *Pred, DomTreeUpdater *DTU=nullptr)
This method duplicates the specified return instruction into a predecessor which ends in an unconditi...
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
Value * CreateIntToPtr(Value *V, Type *DestTy, const Twine &Name="")
unsigned getActiveBits() const
Compute the number of active bits in the value.
static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI, const DataLayout &DL)
If the specified cast instruction is a noop copy (e.g.
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following: ...
OtherOps getOpcode() const
Get the opcode casted to the right type.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
A constant value that is initialized with an expression using other constant values.
void findDbgValues(SmallVectorImpl< DbgValueInst *> &DbgValues, Value *V)
Finds the llvm.dbg.value intrinsics describing a value.
int64_t getSExtValue() const
Get sign extended value.
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
Type * getType() const
All values are typed, get the type of this value.
Value handle that is nullable, but tries to track the Value.
bool insert(const value_type &X)
Insert a new element into the SetVector.
match_combine_or< LTy, RTy > m_CombineOr(const LTy &L, const RTy &R)
Combine two pattern matchers matching L || R.
bool isInBounds() const
Determine whether the GEP has the inbounds flag.
virtual bool shouldSinkOperands(Instruction *I, SmallVectorImpl< Use *> &Ops) const
Return true if sinking I's operands to the same basic block as I is profitable, e.g.
bool isStatepoint(const CallBase *Call)
static cl::opt< bool > AddrSinkCombineBaseReg("addr-sink-combine-base-reg", cl::Hidden, cl::init(true), cl::desc("Allow combining of BaseReg field in Address sinking."))
CastClass_match< OpTy, Instruction::ZExt > m_ZExt(const OpTy &Op)
Matches ZExt.
static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP, SmallVectorImpl< Value *> &OffsetV)
const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
This contains information for each constraint that we are lowering.
const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
bool isSplatValue(const Value *V, unsigned Depth=0)
Return true if the input value is known to be a vector with all identical elements (potentially inclu...
virtual bool isCheapToSpeculateCtlz() const
Return true if it is cheap to speculate a call to intrinsic ctlz.
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
This class represents a no-op cast from one type to another.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
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.
class_match< ConstantInt > m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
const APInt & getValue() const
Return the constant as an APInt value reference.
bool isLittleEndian() const
Layout endianness...
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
static bool hasSameExtUse(Value *Val, const TargetLowering &TLI)
Check if all the uses of Val are equivalent (or free) zero or sign extensions.
iterator_range< User::op_iterator > arg_operands()
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.
virtual bool isEqualityCmpFoldedWithSignedCmp() const
Return true if instruction generated for equality comparison is folded with instruction generated for...
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
virtual bool isCheapToSpeculateCttz() const
Return true if it is cheap to speculate a call to intrinsic cttz.
virtual bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM, Type *Ty, unsigned AddrSpace, Instruction *I=nullptr) const
Return true if the addressing mode represented by AM is legal for this target, for a load/store of th...
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="")
ConstraintPrefix Type
Type - The basic type of the constraint: input/output/clobber.
bool pointsToAliveValue() 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.
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
static cl::opt< bool > AddrSinkNewPhis("addr-sink-new-phis", cl::Hidden, cl::init(false), cl::desc("Allow creation of Phis in Address sinking."))
static cl::opt< bool > AddrSinkNewSelects("addr-sink-new-select", cl::Hidden, cl::init(true), cl::desc("Allow creation of selects in Address sinking."))
Value * getOperand(unsigned i) const
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
Class to represent pointers.
auto count(R &&Range, const E &Element) -> typename std::iterator_traits< decltype(adl_begin(Range))>::difference_type
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Interval::succ_iterator succ_end(Interval *I)
void replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
bool isJumpExpensive() const
Return true if Flow Control is an expensive operation that should be avoided.
unsigned getAddressSpace() const
Returns the address space of this instruction's pointer type.
static cl::opt< bool > StressStoreExtract("stress-cgp-store-extract", cl::Hidden, cl::init(false), cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"))
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
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: ...
bool bitsGT(EVT VT) const
Return true if this has more bits than VT.
static bool simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase, const SmallVectorImpl< GCRelocateInst *> &Targets)
virtual bool canCombineStoreAndExtract(Type *VectorTy, Value *Idx, unsigned &Cost) const
Return true if the target can combine store(extractelement VectorTy, Idx).
const BasicBlock & getEntryBlock() const
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
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...
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
OneUse_match< T > m_OneUse(const T &SubPattern)
static bool runOnFunction(Function &F, bool PostInlining)
static unsigned getPointerOperandIndex()
initializer< Ty > init(const Ty &Val)
bool hasNUsesOrMore(unsigned N) const
Return true if this value has N users or more.
std::vector< AsmOperandInfo > AsmOperandInfoVector
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"))
bool isAllOnesValue() const
Determine if all bits are set.
bool canIncreaseAlignment() const
static bool isBroadcastShuffle(ShuffleVectorInst *SVI)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt...
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction...
Value * getCalledValue() const
LLVM Basic Block Representation.
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
PointerIntPair - This class implements a pair of a pointer and small integer.
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)
static unsigned getPointerOperandIndex()
This is an important class for using LLVM in a threaded context.
Conditional or Unconditional Branch instruction.
bool isIndirect
isIndirect - True if this operand is an indirect operand.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
LLVM_NODISCARD bool empty() const
bool isRound() const
Return true if the size is a power-of-two number of bytes.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
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)
bool isPointerTy() const
True if this is an instance of PointerType.
virtual bool allowsMisalignedMemoryAccesses(EVT, unsigned AddrSpace=0, unsigned Align=1, MachineMemOperand::Flags Flags=MachineMemOperand::MONone, bool *=nullptr) const
Determine if the target supports unaligned memory accesses.
const Instruction & front() const
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
MaybeAlign getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
bool isMask(unsigned numBits) const
static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI, const TargetLowering *TLI, SelectInst *SI)
Returns true if a SelectInst should be turned into an explicit branch.
specific_intval m_SpecificInt(APInt V)
Match a specific integer value or vector with all elements equal to the value.
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...
cst_pred_ty< is_all_ones > m_AllOnes()
Match an integer or vector with all bits set.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
bool isUsedInBasicBlock(const BasicBlock *BB) const
Check if this value is used in the specified basic block.
Represent the analysis usage information of a pass.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
unsigned getLargestLegalIntTypeSizeInBits() const
Returns the size of largest legal integer type size, or 0 if none are set.
static bool SinkCast(CastInst *CI)
Sink the specified cast instruction into its user blocks.
static cl::opt< bool > AddrSinkCombineScaledReg("addr-sink-combine-scaled-reg", cl::Hidden, cl::init(true), cl::desc("Allow combining of ScaledReg field in Address sinking."))
FunctionPass class - This class is used to implement most global optimizations.
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
Interval::pred_iterator pred_end(Interval *I)
unsigned getAddressSpace() const
Return the address space of the Pointer type.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
self_iterator getIterator()
class_match< BinaryOperator > m_BinOp()
Match an arbitrary binary operation and ignore it.
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
auto find_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly...
const Function * getFunction() const
Return the function this instruction belongs to.
const Value * getCondition() const
static cl::opt< bool > DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false), cl::desc("Disable GC optimizations in CodeGenPrepare"))
unsigned getBasePtrIndex() const
The index into the associate statepoint's argument list which contains the base pointer of the pointe...
bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr)
If the specified value is a trivially dead instruction, delete it.
Type * getIndexedType() const
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
iterator erase(const_iterator CI)
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
static wasm::ValType getType(const TargetRegisterClass *RC)
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
bool hasFnAttr(Attribute::AttrKind Kind) const
Determine whether this call has the given attribute.
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
PointerType * getInt8PtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer to an 8-bit integer value.
bool isExtFree(const Instruction *I) const
Return true if the extension represented by I is free.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Value * CreateMul(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
EVT getValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
Return the EVT corresponding to this LLVM type.
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="")
This struct is a compact representation of a valid (non-zero power of two) alignment.
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
void sort(IteratorTy Start, IteratorTy End)
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
Value * CreateGEP(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &Name="")
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
static Constant * getSplat(unsigned NumElts, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
INITIALIZE_PASS_BEGIN(CodeGenPrepare, DEBUG_TYPE, "Optimize for code generation", false, false) INITIALIZE_PASS_END(CodeGenPrepare
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.
StructType * getStructTypeOrNull() const
unsigned getNumOperands() const
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.
uint64_t getLimitedValue(uint64_t Limit=~0ULL) const
getLimitedValue - If the value is smaller than the specified limit, return it, otherwise return the l...
static bool FindAllMemoryUses(Instruction *I, SmallVectorImpl< std::pair< Instruction *, unsigned >> &MemoryUses, SmallPtrSetImpl< Instruction *> &ConsideredInsts, const TargetLowering &TLI, const TargetRegisterInfo &TRI, bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI, int SeenInsts=0)
Recursively walk all the uses of I until we find a memory use.
This is the shared class of boolean and integer constants.
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
static bool sinkCmpExpression(CmpInst *Cmp, const TargetLowering &TLI)
Sink the given CmpInst into user blocks to reduce the number of virtual registers that must be create...
BlockVerifier::State From
Align max(MaybeAlign Lhs, Align Rhs)
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false...
This struct is a compact representation of a valid (power of two) or undefined (0) alignment...
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Module.h This file contains the declarations for the Module class.
static void getShuffleMask(const Constant *Mask, SmallVectorImpl< int > &Result)
Convert the input shuffle mask operand to a vector of integers.
Provides information about what library functions are available for the current target.
virtual bool shouldConsiderGEPOffsetSplit() const
static BranchProbability getBranchProbability(uint64_t Numerator, uint64_t Denominator)
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()
static IntegerType * getIntNTy(LLVMContext &C, unsigned N)
static bool tryUnmergingGEPsAcrossIndirectBr(GetElementPtrInst *GEPI, const TargetTransformInfo *TTI)
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
bool isConditional() const
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
pred_range predecessors(BasicBlock *BB)
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static ConstantInt * getTrue(LLVMContext &Context)
Value handle that asserts if the Value is deleted.
void setAlignment(MaybeAlign Align)
void setPredicate(Predicate P)
Set the predicate for this instruction to the specified value.
void setOperand(unsigned i, Value *Val)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool enableExtLdPromotion() const
Return true if the target wants to use the optimization that turns ext(promotableInst1(...(promotableInstN(load)))) into promotedInst1(...(promotedInstN(ext(load)))).
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
bool isTypeLegal(EVT VT) const
Return true if the target has native support for the specified value type.
Class for arbitrary precision integers.
static cl::opt< bool > AddrSinkCombineBaseGV("addr-sink-combine-base-gv", cl::Hidden, cl::init(true), cl::desc("Allow combining of BaseGV field in Address sinking."))
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.
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
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.
bool shouldOptimizeForSize(const MachineFunction *MF, ProfileSummaryInfo *PSI, const MachineBlockFrequencyInfo *BFI, PGSOQueryType QueryType=PGSOQueryType::Other)
Returns true if machine function MF is suggested to be size-optimized based on the profile...
typename SuperClass::iterator iterator
iterator_range< user_iterator > users()
InstListType::iterator iterator
Instruction iterators...
static bool foldICmpWithDominatingICmp(CmpInst *Cmp, const TargetLowering &TLI)
For pattern like:
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
static void clear(coro::Shape &Shape)
const Value * getFalseValue() const
int InstructionOpcodeToISD(unsigned Opcode) const
Get the ISD node that corresponds to the Instruction class opcode.
Value * CreatePointerCast(Value *V, Type *DestTy, const Twine &Name="")
SmallVector< NodeAddr< NodeBase * >, 4 > NodeList
FunctionPass * createCodeGenPreparePass()
createCodeGenPreparePass - Transform the code to expose more pattern matching during instruction sele...
void removeFromParent()
This method unlinks 'this' from the containing basic block, but does not delete it.
bool isSequential() const
TargetSubtargetInfo - Generic base class for all target subtargets.
virtual bool useSoftFloat() const
bool operator==(const StringView &LHS, const StringView &RHS)
static Constant * getNeg(Constant *C, bool HasNUW=false, bool HasNSW=false)
bool operator!=(uint64_t V1, const APInt &V2)
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 ...
Value * getVariableLocation(bool AllowNullOp=true) const
Get the location corresponding to the variable referenced by the debug info intrinsic.
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Predicate getPredicate() const
Return the predicate for this instruction.
This class wraps the llvm.memcpy/memmove intrinsics.
bool isVolatile() const
Return true if this is a store to a volatile memory location.
Analysis providing branch probability information.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
void setAlignment(MaybeAlign Align)
uint64_t getElementOffset(unsigned Idx) const
SelectSupportKind
Enum that describes what type of support for selects the target has.
static IntegerType * getInt32Ty(LLVMContext &C)
void setCondition(Value *V)
unsigned getIntegerBitWidth() const
LLVM_NODISCARD bool empty() const
bool SplitIndirectBrCriticalEdges(Function &F, BranchProbabilityInfo *BPI=nullptr, BlockFrequencyInfo *BFI=nullptr)
This represents the llvm.dbg.value instruction.
Represents a single loop in the control flow graph.
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value...
StringRef getName() const
Return a constant reference to the value's name.
Establish a view to a call site for examination.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
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 ...
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation.
const Function * getParent() const
Return the enclosing method, or null if none.
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.
bool empty() const
Determine if the SetVector is empty or not.
user_iterator_impl< User > user_iterator
Type * getResultElementType() const
static bool matchUAddWithOverflowConstantEdgeCases(CmpInst *Cmp, BinaryOperator *&Add)
Match special-case patterns that check for unsigned add overflow.
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...
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.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Type * getValueType() const
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...
static unsigned getPointerOperandIndex()
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
bool isUnconditional() const
bool hasNoUnsignedWrap() const
Determine whether the no unsigned wrap flag is set.
static EVT getEVT(Type *Ty, bool HandleUnknown=false)
Return the value type corresponding to the specified type.
raw_ostream & operator<<(raw_ostream &OS, const APInt &I)
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
unsigned getAlignment() const
Return the alignment of the access that is being performed FIXME: Remove this function once transitio...
LLVM_NODISCARD bool empty() const
void mutateType(Type *Ty)
Mutate the type of this Value to be of the specified type.
CallInst * CreateBinaryIntrinsic(Intrinsic::ID ID, Value *LHS, Value *RHS, Instruction *FMFSource=nullptr, const Twine &Name="")
Create a call to intrinsic ID with 2 operands which is mangled on the first type. ...
Value * CreatePtrToInt(Value *V, Type *DestTy, const Twine &Name="")
int compare(DigitsT LDigits, int16_t LScale, DigitsT RDigits, int16_t RScale)
Compare two scaled numbers.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
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.
void moveAfter(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
unsigned getMinSignedBits() const
Get the minimum bit size for this signed APInt.
user_iterator user_begin()
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 ...
Represents calls to the gc.relocate intrinsic.
Module * getParent()
Get the module that this global value is contained inside of...
static cl::opt< bool > DisableComplexAddrModes("disable-complex-addr-modes", cl::Hidden, cl::init(false), cl::desc("Disables combining addressing modes with different parts " "in optimizeMemoryInst."))
LLVM Value Representation.
A vector that has set insertion semantics.
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
static cl::opt< bool > EnableAndCmpSinking("enable-andcmp-sinking", cl::Hidden, cl::init(true), cl::desc("Enable sinkinig and/cmp into branches."))
static constexpr int MaxMemoryUsesToScan
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 ...
This class implements an extremely fast bulk output stream that can only output to a stream...
bool isLoadExtLegal(unsigned ExtType, EVT ValVT, EVT MemVT) const
Return true if the specified load with extension is legal on this target.
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"))
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
The legacy pass manager's analysis pass to compute loop information.
bool hasNoNaNs() const
Determine whether the no-NaNs flag is set.
bool hasOneUse() const
Return true if there is exactly one user of this value.
StringRef - Represent a constant reference to a string, i.e.
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
const Instruction * getFirstNonPHIOrDbg() const
Returns a pointer to the first instruction in this block that is not a PHINode or a debug intrinsic...
bool recognizeBSwapOrBitReverseIdiom(Instruction *I, bool MatchBSwaps, bool MatchBitReversals, SmallVectorImpl< Instruction *> &InsertedInsts)
Try to match a bswap or bitreverse idiom.
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)
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
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.
bool extractProfMetadata(uint64_t &TrueVal, uint64_t &FalseVal) const
Retrieve the raw weight values of a conditional branch or select.
op_range incoming_values()
for(unsigned i=Desc.getNumOperands(), e=OldMI.getNumOperands();i !=e;++i)
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...
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation...
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
VectorType * getType() const
Overload to return most specific vector type.
EVT getTypeToTransformTo(LLVMContext &Context, EVT VT) const
For types supported by the target, this is an identity function.
virtual bool isNoopAddrSpaceCast(unsigned SrcAS, unsigned DestAS) const
Returns true if a cast between SrcAS and DestAS is a noop.
base_list_type::reverse_iterator reverse_iterator
static IntegerType * getInt8Ty(LLVMContext &C)
static Constant * get(ArrayRef< Constant *> V)
void setLowBits(unsigned loBits)
Set the bottom loBits bits.
Type * getElementType() const
static void computeBaseDerivedRelocateMap(const SmallVectorImpl< GCRelocateInst *> &AllRelocateCalls, DenseMap< GCRelocateInst *, SmallVector< GCRelocateInst *, 2 >> &RelocateInstMap)
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.
const BasicBlock * getParent() const
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...
CmpClass_match< LHS, RHS, ICmpInst, ICmpInst::Predicate > m_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R)
gep_type_iterator gep_type_begin(const User *GEP)
static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal, const TargetLowering &TLI, const TargetRegisterInfo &TRI)
Check to see if all uses of OpVal by the specified inline asm call are due to memory operands...
bool isPredictableSelectExpensive() const
Return true if selects are only cheaper than branches if the branch is unlikely to be predicted right...
bool isExtLoad(const LoadInst *Load, const Instruction *Ext, const DataLayout &DL) const
Return true if Load and Ext can form an ExtLoad.
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.
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.