76 #define DEBUG_TYPE "objc-arc-opts" 80 cl::desc(
"Maximum number of ptr states the optimizer keeps track of"),
91 if (isa<ConstantData>(Arg))
95 if (
const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
98 if (
GEP->hasAllZeroIndices())
102 cast<CallInst>(Arg)->getArgOperand(0));
164 STATISTIC(NumNoops,
"Number of no-op objc calls eliminated");
165 STATISTIC(NumPartialNoops,
"Number of partially no-op objc calls eliminated");
166 STATISTIC(NumAutoreleases,
"Number of autoreleases converted to releases");
167 STATISTIC(NumRets,
"Number of return value forwarding " 168 "retain+autoreleases eliminated");
169 STATISTIC(NumRRs,
"Number of retain+release paths eliminated");
170 STATISTIC(NumPeeps,
"Number of calls peephole-optimized");
173 "Number of retains before optimization");
175 "Number of releases before optimization");
177 "Number of retains after optimization");
179 "Number of releases after optimization");
188 unsigned TopDownPathCount = 0;
191 unsigned BottomUpPathCount = 0;
214 using top_down_ptr_iterator = decltype(PerPtrTopDown)::iterator;
215 using const_top_down_ptr_iterator = decltype(PerPtrTopDown)::const_iterator;
217 top_down_ptr_iterator top_down_ptr_begin() {
return PerPtrTopDown.
begin(); }
218 top_down_ptr_iterator top_down_ptr_end() {
return PerPtrTopDown.
end(); }
219 const_top_down_ptr_iterator top_down_ptr_begin()
const {
220 return PerPtrTopDown.
begin();
222 const_top_down_ptr_iterator top_down_ptr_end()
const {
223 return PerPtrTopDown.
end();
225 bool hasTopDownPtrs()
const {
226 return !PerPtrTopDown.
empty();
229 unsigned top_down_ptr_list_size()
const {
230 return std::distance(top_down_ptr_begin(), top_down_ptr_end());
233 using bottom_up_ptr_iterator = decltype(PerPtrBottomUp)::iterator;
234 using const_bottom_up_ptr_iterator =
235 decltype(PerPtrBottomUp)::const_iterator;
237 bottom_up_ptr_iterator bottom_up_ptr_begin() {
238 return PerPtrBottomUp.
begin();
240 bottom_up_ptr_iterator bottom_up_ptr_end() {
return PerPtrBottomUp.
end(); }
241 const_bottom_up_ptr_iterator bottom_up_ptr_begin()
const {
242 return PerPtrBottomUp.
begin();
244 const_bottom_up_ptr_iterator bottom_up_ptr_end()
const {
245 return PerPtrBottomUp.
end();
247 bool hasBottomUpPtrs()
const {
248 return !PerPtrBottomUp.
empty();
251 unsigned bottom_up_ptr_list_size()
const {
252 return std::distance(bottom_up_ptr_begin(), bottom_up_ptr_end());
257 void SetAsEntry() { TopDownPathCount = 1; }
261 void SetAsExit() { BottomUpPathCount = 1; }
267 return PerPtrTopDown[
Arg];
274 return PerPtrBottomUp[
Arg];
279 bottom_up_ptr_iterator findPtrBottomUpState(
const Value *Arg) {
280 return PerPtrBottomUp.
find(Arg);
283 void clearBottomUpPointers() {
284 PerPtrBottomUp.
clear();
287 void clearTopDownPointers() {
288 PerPtrTopDown.
clear();
291 void InitFromPred(
const BBState &
Other);
292 void InitFromSucc(
const BBState &Other);
293 void MergePred(
const BBState &Other);
294 void MergeSucc(
const BBState &Other);
302 bool GetAllPathCountWithOverflow(
unsigned &PathCount)
const {
303 if (TopDownPathCount == OverflowOccurredValue ||
304 BottomUpPathCount == OverflowOccurredValue)
306 unsigned long long Product =
307 (
unsigned long long)TopDownPathCount*BottomUpPathCount;
310 return (Product >> 32) ||
311 ((PathCount = Product) == OverflowOccurredValue);
318 edge_iterator
pred_end()
const {
return Preds.
end(); }
320 edge_iterator
succ_end()
const {
return Succs.
end(); }
325 bool isExit()
const {
return Succs.
empty(); }
330 const unsigned BBState::OverflowOccurredValue = 0xffffffff;
339 void BBState::InitFromPred(
const BBState &
Other) {
340 PerPtrTopDown = Other.PerPtrTopDown;
341 TopDownPathCount = Other.TopDownPathCount;
344 void BBState::InitFromSucc(
const BBState &Other) {
345 PerPtrBottomUp = Other.PerPtrBottomUp;
346 BottomUpPathCount = Other.BottomUpPathCount;
351 void BBState::MergePred(
const BBState &Other) {
352 if (TopDownPathCount == OverflowOccurredValue)
357 TopDownPathCount += Other.TopDownPathCount;
362 if (TopDownPathCount == OverflowOccurredValue) {
363 clearTopDownPointers();
369 if (TopDownPathCount < Other.TopDownPathCount) {
370 TopDownPathCount = OverflowOccurredValue;
371 clearTopDownPointers();
378 for (
auto MI = Other.top_down_ptr_begin(), ME = Other.top_down_ptr_end();
380 auto Pair = PerPtrTopDown.
insert(*
MI);
387 for (
auto MI = top_down_ptr_begin(), ME = top_down_ptr_end();
MI != ME; ++
MI)
388 if (Other.PerPtrTopDown.find(
MI->first) == Other.PerPtrTopDown.end())
394 void BBState::MergeSucc(
const BBState &Other) {
395 if (BottomUpPathCount == OverflowOccurredValue)
400 BottomUpPathCount += Other.BottomUpPathCount;
405 if (BottomUpPathCount == OverflowOccurredValue) {
406 clearBottomUpPointers();
412 if (BottomUpPathCount < Other.BottomUpPathCount) {
413 BottomUpPathCount = OverflowOccurredValue;
414 clearBottomUpPointers();
421 for (
auto MI = Other.bottom_up_ptr_begin(), ME = Other.bottom_up_ptr_end();
423 auto Pair = PerPtrBottomUp.
insert(*
MI);
430 for (
auto MI = bottom_up_ptr_begin(), ME = bottom_up_ptr_end();
MI != ME;
432 if (Other.PerPtrBottomUp.find(
MI->first) == Other.PerPtrBottomUp.end())
438 OS <<
" TopDown State:\n";
439 if (!BBInfo.hasTopDownPtrs()) {
442 for (
auto I = BBInfo.top_down_ptr_begin(),
E = BBInfo.top_down_ptr_end();
445 OS <<
" Ptr: " << *
I->first
446 <<
"\n KnownSafe: " << (P.
IsKnownSafe()?
"true":
"false")
447 <<
"\n ImpreciseRelease: " 449 <<
" HasCFGHazards: " 451 <<
" KnownPositive: " 458 OS <<
" BottomUp State:\n";
459 if (!BBInfo.hasBottomUpPtrs()) {
462 for (
auto I = BBInfo.bottom_up_ptr_begin(),
E = BBInfo.bottom_up_ptr_end();
465 OS <<
" Ptr: " << *
I->first
466 <<
"\n KnownSafe: " << (P.
IsKnownSafe()?
"true":
"false")
467 <<
"\n ImpreciseRelease: " 469 <<
" HasCFGHazards: " 471 <<
" KnownPositive: " 500 bool DisableRetainReleasePairing =
false;
504 unsigned UsedInThisFunction;
509 void OptimizeIndividualCalls(
Function &F);
513 void OptimizeIndividualCallImpl(
520 bool OptimizeInlinedAutoreleaseRVCall(
527 BBState &MyStates)
const;
556 Value *Arg,
bool KnownSafe,
557 bool &AnyPairsCompletelyEliminated);
563 void OptimizeWeakCalls(
Function &F);
565 bool OptimizeSequences(
Function &F);
570 void GatherStatistics(
Function &F,
bool AfterOptimization =
false);
574 bool doInitialization(
Module &M)
override;
576 void releaseMemory()
override;
591 "objc-arc",
"ObjC ARC optimization",
false,
false)
594 "objc-arc",
"ObjC ARC optimization",
false,
false)
597 return new ObjCARCOpt();
624 if (II->getNormalDest() == RetainRVParent) {
638 LLVM_DEBUG(
dbgs() <<
"Transforming objc_retainAutoreleasedReturnValue => " 639 "objc_retain since the operand is not a return value.\n" 641 << *RetainRV <<
"\n");
644 cast<CallInst>(
RetainRV)->setCalledFunction(NewDecl);
651 bool ObjCARCOpt::OptimizeInlinedAutoreleaseRVCall(
661 if (Arg != AutoreleaseRVArg) {
669 if (
llvm::find(ArgUsers, AutoreleaseRVArg) == ArgUsers.
end())
675 LLVM_DEBUG(
dbgs() <<
"Found inlined objc_autoreleaseReturnValue '" 676 << *AutoreleaseRV <<
"' paired with '" << *Inst <<
"'\n");
680 cast<CallInst>(AutoreleaseRV)->getArgOperand(0));
692 Value *
CallArg = cast<CallInst>(Inst)->getArgOperand(0);
696 "Expected ClaimRV to be safe to tail call");
709 void ObjCARCOpt::OptimizeAutoreleaseRVCall(
Function &F,
717 if (isa<ConstantData>(Ptr))
724 if (
const PHINode *PN = dyn_cast<PHINode>(Ptr))
732 if (isa<BitCastInst>(U))
735 }
while (!Users.
empty());
741 dbgs() <<
"Transforming objc_autoreleaseReturnValue => " 742 "objc_autorelease since its operand is not used as a return " 745 << *AutoreleaseRV <<
"\n");
769 if (!BlockColors.
empty()) {
771 assert(CV.
size() == 1 &&
"non-unique color for block!");
773 if (EHPad->isEHPad())
783 void ObjCARCOpt::OptimizeIndividualCalls(
Function &F) {
784 LLVM_DEBUG(
dbgs() <<
"\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
786 UsedInThisFunction = 0;
796 const Value *DelayedAutoreleaseRVArg =
nullptr;
798 assert(!DelayedAutoreleaseRV || !AutoreleaseRV);
800 DelayedAutoreleaseRVArg =
nullptr;
802 auto optimizeDelayedAutoreleaseRV = [&]() {
803 if (!DelayedAutoreleaseRV)
805 OptimizeIndividualCallImpl(F, BlockColors, DelayedAutoreleaseRV,
807 DelayedAutoreleaseRVArg);
808 setDelayedAutoreleaseRV(
nullptr);
810 auto shouldDelayAutoreleaseRV = [&](
Instruction *NonARCInst) {
812 if (!DelayedAutoreleaseRV)
817 if (NonARCInst->isTerminator())
840 const Value *Arg =
nullptr;
843 optimizeDelayedAutoreleaseRV();
851 if (!shouldDelayAutoreleaseRV(Inst))
852 optimizeDelayedAutoreleaseRV();
855 optimizeDelayedAutoreleaseRV();
856 setDelayedAutoreleaseRV(Inst);
860 if (DelayedAutoreleaseRV) {
862 if (OptimizeInlinedAutoreleaseRVCall(F, BlockColors, Inst, Arg, Class,
863 DelayedAutoreleaseRV,
864 DelayedAutoreleaseRVArg)) {
865 setDelayedAutoreleaseRV(
nullptr);
868 optimizeDelayedAutoreleaseRV();
873 OptimizeIndividualCallImpl(F, BlockColors, Inst, Class, Arg);
877 optimizeDelayedAutoreleaseRV();
880 void ObjCARCOpt::OptimizeIndividualCallImpl(
883 LLVM_DEBUG(
dbgs() <<
"Visiting: Class: " << Class <<
"; " << *Inst <<
"\n");
890 if (GV->hasAttribute(
"objc_arc_inert")) {
923 CallInst *CI = cast<CallInst>(Inst);
931 dbgs() <<
"A null pointer-to-weak-pointer is undefined behavior." 933 << *CI <<
"\nNew = " << *NewValue <<
"\n");
942 CallInst *CI = cast<CallInst>(Inst);
952 dbgs() <<
"A null pointer-to-weak-pointer is undefined behavior." 954 << *CI <<
"\nNew = " << *NewValue <<
"\n");
963 if (OptimizeRetainRVCall(F, Inst))
967 OptimizeAutoreleaseRVCall(F, Inst, Class);
989 LLVM_DEBUG(
dbgs() <<
"Replacing autorelease{,RV}(x) with objc_release(x) " 990 "since x is otherwise unused.\nOld: " 991 << *Call <<
"\nNew: " << *NewCall <<
"\n");
1001 if (
IsAlwaysTail(Class) && !cast<CallInst>(Inst)->isNoTailCall()) {
1004 dbgs() <<
"Adding tail keyword to function since it can never be " 1005 "passed stack args: " 1007 cast<CallInst>(Inst)->setTailCall();
1014 LLVM_DEBUG(
dbgs() <<
"Removing tail keyword from function: " << *Inst
1016 cast<CallInst>(Inst)->setTailCall(
false);
1022 LLVM_DEBUG(
dbgs() <<
"Found no throw class. Setting nounwind on: " << *Inst
1029 UsedInThisFunction |= 1 <<
unsigned(Class);
1041 LLVM_DEBUG(
dbgs() <<
"ARC calls with null are no-ops. Erasing: " << *Inst
1049 UsedInThisFunction |= 1 <<
unsigned(Class);
1062 Worklist.
push_back(std::make_pair(Inst, Arg));
1064 std::pair<Instruction *, const Value *> Pair = Worklist.
pop_back_val();
1074 bool HasNull =
false;
1075 bool HasCriticalEdges =
false;
1082 HasCriticalEdges =
true;
1087 if (HasCriticalEdges)
1106 DependingInstructions, Visited, PA);
1111 DependingInstructions, Visited, PA);
1125 if (DependingInstructions.
size() != 1)
1127 if (*DependingInstructions.
begin() != PN)
1133 CallInst *CInst = cast<CallInst>(Inst);
1142 CloneCallInstForBB(*CInst, *InsertPos->
getParent(), BlockColors));
1149 "And inserting clone at " 1150 << *InsertPos <<
"\n");
1151 Worklist.
push_back(std::make_pair(Clone, Incoming));
1156 }
while (!Worklist.
empty());
1162 const bool SuccSRRIKnownSafe,
1164 bool &SomeSuccHasSame,
1165 bool &AllSuccsHaveSame,
1166 bool &NotAllSeqEqualButKnownSafe,
1167 bool &ShouldContinue) {
1175 ShouldContinue =
true;
1179 SomeSuccHasSame =
true;
1185 AllSuccsHaveSame =
false;
1187 NotAllSeqEqualButKnownSafe =
true;
1200 const bool SuccSRRIKnownSafe,
1202 bool &SomeSuccHasSame,
1203 bool &AllSuccsHaveSame,
1204 bool &NotAllSeqEqualButKnownSafe) {
1207 SomeSuccHasSame =
true;
1214 AllSuccsHaveSame =
false;
1216 NotAllSeqEqualButKnownSafe =
true;
1229 ObjCARCOpt::CheckForCFGHazards(
const BasicBlock *BB,
1231 BBState &MyStates)
const {
1234 for (
auto I = MyStates.top_down_ptr_begin(),
E = MyStates.top_down_ptr_end();
1237 const Sequence Seq =
I->second.GetSeq();
1246 "Unknown top down sequence state.");
1248 const Value *Arg =
I->first;
1249 bool SomeSuccHasSame =
false;
1250 bool AllSuccsHaveSame =
true;
1251 bool NotAllSeqEqualButKnownSafe =
false;
1257 BBStates.
find(Succ);
1260 const Sequence SuccSSeq = SuccS.GetSeq();
1267 if (SuccSSeq ==
S_None) {
1274 const bool SuccSRRIKnownSafe = SuccS.IsKnownSafe();
1280 bool ShouldContinue =
false;
1282 AllSuccsHaveSame, NotAllSeqEqualButKnownSafe,
1290 SomeSuccHasSame, AllSuccsHaveSame,
1291 NotAllSeqEqualButKnownSafe);
1305 if (SomeSuccHasSame && !AllSuccsHaveSame) {
1307 }
else if (NotAllSeqEqualButKnownSafe) {
1317 bool ObjCARCOpt::VisitInstructionBottomUp(
1319 BBState &MyStates) {
1320 bool NestingDetected =
false;
1322 const Value *Arg =
nullptr;
1357 MyStates.clearBottomUpPointers();
1358 return NestingDetected;
1362 return NestingDetected;
1369 for (
auto MI = MyStates.bottom_up_ptr_begin(),
1370 ME = MyStates.bottom_up_ptr_end();
1383 return NestingDetected;
1386 bool ObjCARCOpt::VisitBottomUp(
BasicBlock *BB,
1391 bool NestingDetected =
false;
1392 BBState &MyStates = BBStates[BB];
1396 BBState::edge_iterator
SI(MyStates.succ_begin()),
1397 SE(MyStates.succ_end());
1402 MyStates.InitFromSucc(I->second);
1404 for (;
SI != SE; ++
SI) {
1406 I = BBStates.
find(Succ);
1408 MyStates.MergeSucc(I->second);
1413 << BBStates[BB] <<
"\n" 1414 <<
"Performing Dataflow:\n");
1421 if (isa<InvokeInst>(Inst))
1426 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
1430 if (MyStates.bottom_up_ptr_list_size() >
MaxPtrStates) {
1431 DisableRetainReleasePairing =
true;
1439 for (BBState::edge_iterator PI(MyStates.pred_begin()),
1440 PE(MyStates.pred_end()); PI != PE; ++PI) {
1443 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
1446 LLVM_DEBUG(
dbgs() <<
"\nFinal State:\n" << BBStates[BB] <<
"\n");
1448 return NestingDetected;
1452 ObjCARCOpt::VisitInstructionTopDown(
Instruction *Inst,
1454 BBState &MyStates) {
1455 bool NestingDetected =
false;
1457 const Value *Arg =
nullptr;
1493 MyStates.clearTopDownPointers();
1505 for (
auto MI = MyStates.top_down_ptr_begin(),
1506 ME = MyStates.top_down_ptr_end();
1518 return NestingDetected;
1526 bool NestingDetected =
false;
1527 BBState &MyStates = BBStates[BB];
1531 BBState::edge_iterator PI(MyStates.pred_begin()),
1532 PE(MyStates.pred_end());
1537 MyStates.InitFromPred(I->second);
1539 for (; PI != PE; ++PI) {
1541 I = BBStates.
find(Pred);
1543 MyStates.MergePred(I->second);
1548 << BBStates[BB] <<
"\n" 1549 <<
"Performing Dataflow:\n");
1555 NestingDetected |= VisitInstructionTopDown(&Inst, Releases, MyStates);
1559 if (MyStates.top_down_ptr_list_size() >
MaxPtrStates) {
1560 DisableRetainReleasePairing =
true;
1565 LLVM_DEBUG(
dbgs() <<
"\nState Before Checking for CFG Hazards:\n" 1566 << BBStates[BB] <<
"\n\n");
1567 CheckForCFGHazards(BB, BBStates, MyStates);
1569 return NestingDetected;
1576 unsigned NoObjCARCExceptionsMDKind,
1588 BBState &MyStates = BBStates[EntryBB];
1589 MyStates.SetAsEntry();
1599 while (SuccStack.
back().second != SE) {
1601 if (Visited.
insert(SuccBB).second) {
1604 BBStates[CurrBB].addSucc(SuccBB);
1605 BBState &SuccStates = BBStates[SuccBB];
1606 SuccStates.addPred(CurrBB);
1611 if (!OnStack.
count(SuccBB)) {
1612 BBStates[CurrBB].addSucc(SuccBB);
1613 BBStates[SuccBB].addPred(CurrBB);
1616 OnStack.
erase(CurrBB);
1619 }
while (!SuccStack.
empty());
1628 BBState &MyStates = BBStates[&ExitBB];
1629 if (!MyStates.isExit())
1632 MyStates.SetAsExit();
1634 PredStack.
push_back(std::make_pair(&ExitBB, MyStates.pred_begin()));
1636 while (!PredStack.
empty()) {
1637 reverse_dfs_next_succ:
1638 BBState::edge_iterator PE = BBStates[PredStack.
back().first].pred_end();
1639 while (PredStack.
back().second != PE) {
1641 if (Visited.
insert(BB).second) {
1643 goto reverse_dfs_next_succ;
1652 bool ObjCARCOpt::Visit(
Function &F,
1668 bool BottomUpNestingDetected =
false;
1670 BottomUpNestingDetected |= VisitBottomUp(BB, BBStates, Retains);
1671 if (DisableRetainReleasePairing)
1676 bool TopDownNestingDetected =
false;
1678 TopDownNestingDetected |= VisitTopDown(BB, BBStates, Releases);
1679 if (DisableRetainReleasePairing)
1683 return TopDownNestingDetected && BottomUpNestingDetected;
1687 void ObjCARCOpt::MoveCalls(
Value *Arg,
RRInfo &RetainsToMove,
1700 Value *MyArg = ArgTy == ParamTy ?
Arg :
1709 "At insertion point: " 1710 << *InsertPt <<
"\n");
1713 Value *MyArg = ArgTy == ParamTy ?
Arg :
1726 "At insertion point: " 1727 << *InsertPt <<
"\n");
1732 Retains.
blot(OrigRetain);
1734 LLVM_DEBUG(
dbgs() <<
"Deleting retain: " << *OrigRetain <<
"\n");
1737 Releases.
erase(OrigRelease);
1739 LLVM_DEBUG(
dbgs() <<
"Deleting release: " << *OrigRelease <<
"\n");
1743 bool ObjCARCOpt::PairUpRetainsAndReleases(
1749 RRInfo &ReleasesToMove,
Value *Arg,
bool KnownSafe,
1750 bool &AnyPairsCompletelyEliminated) {
1754 bool KnownSafeTD =
true, KnownSafeBU =
true;
1755 bool CFGHazardAfflicted =
false;
1761 unsigned OldDelta = 0;
1762 unsigned NewDelta = 0;
1763 unsigned OldCount = 0;
1764 unsigned NewCount = 0;
1765 bool FirstRelease =
true;
1769 auto It = Retains.
find(NewRetain);
1771 const RRInfo &NewRetainRRI = It->second;
1772 KnownSafeTD &= NewRetainRRI.KnownSafe;
1773 CFGHazardAfflicted |= NewRetainRRI.CFGHazardAfflicted;
1774 for (
Instruction *NewRetainRelease : NewRetainRRI.Calls) {
1775 auto Jt = Releases.
find(NewRetainRelease);
1776 if (Jt == Releases.
end())
1778 const RRInfo &NewRetainReleaseRRI = Jt->second;
1785 if (!NewRetainReleaseRRI.
Calls.count(NewRetain))
1788 if (ReleasesToMove.
Calls.insert(NewRetainRelease).second) {
1791 const BBState &NRRBBState = BBStates[NewRetainRelease->
getParent()];
1792 unsigned PathCount = BBState::OverflowOccurredValue;
1793 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
1795 assert(PathCount != BBState::OverflowOccurredValue &&
1796 "PathCount at this point can not be " 1797 "OverflowOccurredValue.");
1798 OldDelta -= PathCount;
1806 FirstRelease =
false;
1822 const BBState &RIPBBState = BBStates[RIP->
getParent()];
1823 PathCount = BBState::OverflowOccurredValue;
1824 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
1826 assert(PathCount != BBState::OverflowOccurredValue &&
1827 "PathCount at this point can not be " 1828 "OverflowOccurredValue.");
1829 NewDelta -= PathCount;
1832 NewReleases.
push_back(NewRetainRelease);
1837 if (NewReleases.
empty())
break;
1841 auto It = Releases.
find(NewRelease);
1843 const RRInfo &NewReleaseRRI = It->second;
1845 CFGHazardAfflicted |= NewReleaseRRI.CFGHazardAfflicted;
1846 for (
Instruction *NewReleaseRetain : NewReleaseRRI.Calls) {
1847 auto Jt = Retains.
find(NewReleaseRetain);
1848 if (Jt == Retains.
end())
1850 const RRInfo &NewReleaseRetainRRI = Jt->second;
1857 if (!NewReleaseRetainRRI.
Calls.count(NewRelease))
1860 if (RetainsToMove.
Calls.insert(NewReleaseRetain).second) {
1863 const BBState &NRRBBState = BBStates[NewReleaseRetain->
getParent()];
1864 unsigned PathCount = BBState::OverflowOccurredValue;
1865 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
1867 assert(PathCount != BBState::OverflowOccurredValue &&
1868 "PathCount at this point can not be " 1869 "OverflowOccurredValue.");
1870 OldDelta += PathCount;
1871 OldCount += PathCount;
1879 const BBState &RIPBBState = BBStates[RIP->
getParent()];
1881 PathCount = BBState::OverflowOccurredValue;
1882 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
1884 assert(PathCount != BBState::OverflowOccurredValue &&
1885 "PathCount at this point can not be " 1886 "OverflowOccurredValue.");
1887 NewDelta += PathCount;
1888 NewCount += PathCount;
1891 NewRetains.push_back(NewReleaseRetain);
1895 if (NewRetains.empty())
break;
1899 bool UnconditionallySafe = KnownSafeTD && KnownSafeBU;
1900 if (UnconditionallySafe) {
1915 const bool WillPerformCodeMotion =
1918 if (CFGHazardAfflicted && WillPerformCodeMotion)
1931 assert(OldCount != 0 &&
"Unreachable code?");
1932 NumRRs += OldCount - NewCount;
1934 AnyPairsCompletelyEliminated = NewCount == 0;
1942 bool ObjCARCOpt::PerformCodePlacement(
1946 LLVM_DEBUG(
dbgs() <<
"\n== ObjCARCOpt::PerformCodePlacement ==\n");
1948 bool AnyPairsCompletelyEliminated =
false;
1967 bool KnownSafe = isa<Constant>(
Arg) || isa<AllocaInst>(Arg);
1971 if (
const LoadInst *LI = dyn_cast<LoadInst>(Arg))
1973 dyn_cast<GlobalVariable>(
1975 if (GV->isConstant())
1980 RRInfo RetainsToMove, ReleasesToMove;
1982 bool PerformMoveCalls = PairUpRetainsAndReleases(
1983 BBStates, Retains, Releases, M, Retain, DeadInsts,
1984 RetainsToMove, ReleasesToMove, Arg, KnownSafe,
1985 AnyPairsCompletelyEliminated);
1987 if (PerformMoveCalls) {
1990 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
1991 Retains, Releases, DeadInsts, M);
1997 while (!DeadInsts.
empty())
2000 return AnyPairsCompletelyEliminated;
2004 void ObjCARCOpt::OptimizeWeakCalls(
Function &F) {
2037 switch (EarlierClass) {
2043 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2045 Value *EarlierArg = EarlierCall->getArgOperand(0);
2046 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2072 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2074 Value *EarlierArg = EarlierCall->getArgOperand(0);
2075 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2125 if (
AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
2127 const Instruction *UserInst = cast<Instruction>(U);
2138 for (
auto UI = Alloca->user_begin(), UE = Alloca->user_end(); UI != UE;) {
2139 CallInst *UserInst = cast<CallInst>(*UI++);
2154 Alloca->eraseFromParent();
2162 bool ObjCARCOpt::OptimizeSequences(
Function &F) {
2175 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
2177 if (DisableRetainReleasePairing)
2181 bool AnyPairsCompletelyEliminated = PerformCodePlacement(BBStates, Retains,
2185 return AnyPairsCompletelyEliminated && NestingDetected;
2197 DepInsts, Visited, PA);
2198 if (DepInsts.size() != 1)
2201 auto *
Call = dyn_cast_or_null<CallInst>(*DepInsts.begin());
2222 BB, Autorelease, DepInsts, Visited, PA);
2223 if (DepInsts.
size() != 1)
2226 auto *Retain = dyn_cast_or_null<CallInst>(*DepInsts.
begin());
2247 BB, Ret, DepInsts, V, PA);
2248 if (DepInsts.
size() != 1)
2271 void ObjCARCOpt::OptimizeReturns(
Function &F) {
2292 Arg, &BB, Ret, DependingInstructions, Visited, PA);
2293 DependingInstructions.
clear();
2300 Arg, Autorelease->getParent(),
Autorelease, DependingInstructions,
2302 DependingInstructions.clear();
2311 DependingInstructions,
2313 DependingInstructions.clear();
2316 if (!HasSafePathToCall)
2322 LLVM_DEBUG(
dbgs() <<
"Erasing: " << *Retain <<
"\nErasing: " << *Autorelease
2331 ObjCARCOpt::GatherStatistics(
Function &F,
bool AfterOptimization) {
2333 AfterOptimization ? NumRetainsAfterOpt : NumRetainsBeforeOpt;
2335 AfterOptimization ? NumReleasesAfterOpt : NumReleasesBeforeOpt;
2353 bool ObjCARCOpt::doInitialization(
Module &M) {
2365 MDKindCache.init(&M);
2387 PA.setAA(&getAnalysis<AAResultsWrapperPass>().getAAResults());
2391 GatherStatistics(F,
false);
2400 OptimizeIndividualCalls(F);
2410 OptimizeWeakCalls(F);
2419 while (OptimizeSequences(F)) {}
2429 GatherStatistics(F,
true);
2438 void ObjCARCOpt::releaseMemory() {
Pass interface - Implemented by all 'passes'.
Return a value (possibly void), from a function.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
reference emplace_back(ArgTypes &&... Args)
This file declares special dependency analysis routines used in Objective C ARC Optimizations.
ARCInstKind GetARCInstKind(const Value *V)
Map V to its ARCInstKind equivalence class.
objc_destroyWeak (derived)
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
SmallPtrSet< Instruction *, 2 > Calls
For a top-down sequence, the set of objc_retains or objc_retainBlocks.
This file contains a class ARCRuntimeEntryPoints for use in creating/managing references to entry poi...
This class represents lattice values for constants.
objc_loadWeakRetained (primitive)
typename VectorTy::const_iterator const_iterator
could call objc_release and/or "use" pointers
A Module instance is used to store all the information related to an LLVM module. ...
bool IsTrackingImpreciseReleases() const
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
void push_back(const T &Elt)
bool HandlePotentialAlterRefCount(Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA, ARCInstKind Class)
This class represents a function call, abstracting a target machine's calling convention.
objc_retainedObject, etc.
Value * GetArgRCIdentityRoot(Value *Inst)
Assuming the given instruction is one of the special calls such as objc_retain or objc_release...
Optional< std::vector< StOtherPiece > > Other
The two locations do not alias at all.
LLVMContext & getContext() const
All values hold a context through their type.
bool MatchWithRelease(ARCMDKindCache &Cache, Instruction *Release)
Return true if this set of retains can be paired with the given release.
STATISTIC(NumFunctions, "Total number of functions")
void setArgOperand(unsigned i, Value *v)
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
void initializeObjCARCOptPass(PassRegistry &)
An instruction for reading from memory.
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...
iv Induction Variable Users
OperandBundleUse getOperandBundleAt(unsigned Index) const
Return the operand bundle at a specific index.
SmallPtrSet< Instruction *, 2 > ReverseInsertPts
The set of optimal insert positions for moving calls in the opposite sequence.
TinyPtrVector - This class is specialized for cases where there are normally 0 or 1 element in a vect...
bool IsNoopOnNull(ARCInstKind Class)
Test if the given class represents instructions which do nothing if passed a null pointer...
bool IsForwarding(ARCInstKind Class)
Test if the given class represents instructions which return their argument verbatim.
bool IsObjCIdentifiedObject(const Value *V)
Return true if this value refers to a distinct and identifiable object.
static cl::opt< unsigned > MaxPtrStates("arc-opt-max-ptr-states", cl::Hidden, cl::desc("Maximum number of ptr states the optimizer keeps track of"), cl::init(4095))
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
iterator begin()
Instruction iterator methods.
Value * getArgOperand(unsigned i) const
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
bool HasKnownPositiveRefCount() const
objc_autoreleaseReturnValue
inst_iterator inst_begin(Function *F)
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
bool IsNoopOnGlobal(ARCInstKind Class)
Test if the given class represents instructions which do nothing if passed a global variable...
This class summarizes several per-pointer runtime properties which are propagated through the flow gr...
bool IsNullOrUndef(const Value *V)
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...
bool isScopedEHPersonality(EHPersonality Pers)
Returns true if this personality uses scope-style EH IR instructions: catchswitch, catchpad/ret, and cleanuppad/ret.
bool IsTailCallRelease
True of the objc_release calls are all marked with the "tail" keyword.
bool InitBottomUp(ARCMDKindCache &Cache, Instruction *I)
(Re-)Initialize this bottom up pointer returning true if we detected a pointer with nested releases...
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
InstrTy * getInstruction() const
objc_retainAutoreleasedReturnValue
Type * getType() const
All values are typed, get the type of this value.
static bool setDoesNotThrow(Function &F)
void setCalledFunction(Function *Fn)
Sets the function called, including updating the function type.
bool EnableARCOpts
A handy option to enable/disable all ARC Optimizations.
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.
void HandlePotentialUse(BasicBlock *BB, Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA, ARCInstKind Class)
An instruction for storing to memory.
bool hasPersonalityFn() const
Check whether this function has a personality function.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
bool IsAlwaysTail(ARCInstKind Class)
Test if the given class represents instructions which are always safe to mark with the "tail" keyword...
unsigned getNumOperandBundles() const
Return the number of operand bundles associated with this User.
BBIty & getBasicBlockIterator()
bool ModuleHasARC(const Module &M)
Test if the given module looks interesting to run ARC optimization on.
unsigned getNumSuccessors() const
Return the number of successors that this instruction has.
Value * getOperand(unsigned i) const
Unidirectional information about either a retain-decrement-use-release sequence or release-use-decrem...
Interval::succ_iterator succ_end(Interval *I)
raw_ostream & operator<<(raw_ostream &OS, const ARCInstKind Class)
iterator find(const_arg_type_t< KeyT > Val)
bool isVoidTy() const
Return true if this is 'void'.
const BasicBlock & getEntryBlock() const
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
iterator find(const KeyT &Key)
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
static bool runOnFunction(Function &F, bool PostInlining)
initializer< Ty > init(const Ty &Val)
bool erase(const KeyT &Val)
Type * getReturnType() const
Returns the type of the ret val.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
void HandlePotentialUse(Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA, ARCInstKind Class)
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction...
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
This is an important class for using LLVM in a threaded context.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
bool isPointerTy() const
True if this is an instance of PointerType.
BIty & getInstructionIterator()
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
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...
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &InsertPair)
like S_Release, but code motion is stopped.
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
Represent the analysis usage information of a pass.
const Instruction & back() const
#define LLVM_ATTRIBUTE_UNUSED
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)
static const Value * FindSingleUseIdentifiedObject(const Value *Arg)
This is similar to GetRCIdentityRoot but it stops as soon as it finds a value with multiple uses...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
A cache of MDKinds used by various ARC optimizations.
static CallInst * FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB, ReturnInst *Ret, SmallPtrSetImpl< Instruction *> &DepInsts, SmallPtrSetImpl< const BasicBlock *> &V, ProvenanceAnalysis &PA)
Look for an ``autorelease'' instruction dependent on Arg such that there are no instructions dependen...
bool MatchWithRetain()
Return true if this set of releases can be paired with a release.
static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq, const bool SuccSRRIKnownSafe, TopDownPtrState &S, bool &SomeSuccHasSame, bool &AllSuccsHaveSame, bool &NotAllSeqEqualButKnownSafe)
If we have a Top Down pointer in the S_CanRelease state, make sure that there are no CFG hazards by c...
void setTailCall(bool isTC=true)
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.
This file defines common analysis utilities used by the ObjC ARC Optimizer.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
anything that is inert from an ARC perspective.
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.
This file declares a simple ARC-aware AliasAnalysis using special knowledge of Objective C to enhance...
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
ARCInstKind GetBasicARCInstKind(const Value *V)
Determine which objc runtime call instruction class V belongs to.
objc_release(x), !clang.imprecise_release.
bool IsCFGHazardAfflicted() const
The two locations may or may not alias. This is the least precise result.
The two locations precisely alias each other.
static void EraseInstruction(Instruction *CI)
Erase the given instruction.
Iterator for intrusive lists based on ilist_node.
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the generic address space (address sp...
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false...
This file declares a special form of Alias Analysis called ``Provenance Analysis''.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
ARCInstKind
Equivalence classes of instructions in the ARC Model.
An associative container with fast insertion-order (deterministic) iteration over its elements...
bool IsNoThrow(ARCInstKind Class)
Test if the given class represents instructions which are always safe to mark with the nounwind attri...
objc_unsafeClaimAutoreleasedReturnValue
bool HandlePotentialAlterRefCount(Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA, ARCInstKind Class)
LLVM_NODISCARD T pop_back_val()
void setPreservesCFG()
This function should be called by the pass, iff they do not:
unsigned getNumIncomingValues() const
Return the number of incoming edges.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
MDNode * ReleaseMetadata
If the Calls are objc_release calls and they all have a clang.imprecise_release tag, this is the metadata tag.
Pass * createObjCARCOptPass()
void FindDependencies(DependenceKind Flavor, const Value *Arg, BasicBlock *StartBB, Instruction *StartInst, SmallPtrSetImpl< Instruction *> &DependingInstructions, SmallPtrSetImpl< const BasicBlock *> &Visited, ProvenanceAnalysis &PA)
Walk up the CFG from StartPos (which is in StartBB) and find local and non-local dependencies on Arg...
iterator_range< user_iterator > users()
void ClearSequenceProgress()
bool IsRetain(ARCInstKind Class)
Test if the given class is objc_retain or equivalent.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
static bool HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain, SmallPtrSetImpl< Instruction *> &DepInsts, SmallPtrSetImpl< const BasicBlock *> &Visited, ProvenanceAnalysis &PA)
Check if there is a dependent call earlier that does not have anything in between the Retain and the ...
SuccIterator< Instruction, BasicBlock > succ_iterator
const RRInfo & GetRRInfo() const
LLVM_NODISCARD bool empty() const
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.
objc_storeWeak (primitive)
Sequence
A sequence of states that a pointer may go through in which an objc_retain and objc_release are actua...
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
static void CheckForUseCFGHazard(const Sequence SuccSSeq, const bool SuccSRRIKnownSafe, TopDownPtrState &S, bool &SomeSuccHasSame, bool &AllSuccsHaveSame, bool &NotAllSeqEqualButKnownSafe, bool &ShouldContinue)
If we have a top down pointer in the S_Use state, make sure that there are no CFG hazards by checking...
Declarations for ObjC runtime functions and constants.
void SetCFGHazardAfflicted(const bool NewValue)
raw_ostream & operator<<(raw_ostream &OS, const APInt &I)
LLVM_NODISCARD bool empty() const
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
INITIALIZE_PASS_BEGIN(ObjCARCOpt, "objc-arc", "ObjC ARC optimization", false, false) INITIALIZE_PASS_END(ObjCARCOpt
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
Constant * getPersonalityFn() const
Get the personality function associated with this function.
foo(x) – x could possibly see a ref count decrement.
Legacy wrapper pass to provide the ObjCARCAAResult object.
succ_range successors(Instruction *I)
static void ComputePostOrders(Function &F, SmallVectorImpl< BasicBlock *> &PostOrder, SmallVectorImpl< BasicBlock *> &ReverseCFGPostOrder, unsigned NoObjCARCExceptionsMDKind, DenseMap< const BasicBlock *, BBState > &BBStates)
static const unsigned OverflowOccurredValue
bool KnownSafe
After an objc_retain, the reference count of the referenced object is known to be positive...
This class implements an extremely fast bulk output stream that can only output to a stream...
This is similar to BasicAliasAnalysis, and it uses many of the same techniques, except it uses specia...
bool hasOneUse() const
Return true if there is exactly one user of this value.
const Value * GetRCIdentityRoot(const Value *V)
The RCIdentity root of a value V is a dominating value U for which retaining or releasing U is equiva...
inst_iterator inst_end(Function *F)
static CallInst * FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB, Instruction *Autorelease, SmallPtrSetImpl< Instruction *> &DepInsts, SmallPtrSetImpl< const BasicBlock *> &Visited, ProvenanceAnalysis &PA)
Find a dependent retain that precedes the given autorelease for which there is nothing in between the...
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
The two locations alias, but only due to a partial overlap.
bool InitTopDown(ARCInstKind Kind, Instruction *I)
(Re-)Initialize this bottom up pointer returning true if we detected a pointer with nested releases...
DenseMap< BasicBlock *, ColorVector > colorEHFunclets(Function &F)
If an EH funclet personality is in use (see isFuncletEHPersonality), this will recompute which blocks...
static IntegerType * getInt8Ty(LLVMContext &C)
bool AreStatisticsEnabled()
Check if statistics are enabled.
bool IsNeverTail(ARCInstKind Class)
Test if the given class represents instructions which are never safe to mark with the "tail" keyword...
void blot(const KeyT &Key)
This is similar to erase, but instead of removing the element from the vector, it just zeros out the ...
void getEquivalentPHIs(PHINodeTy &PN, VectorTy &PHIList)
Return the list of PHI nodes that are equivalent to PN.
bool IsNoopInstruction(const Instruction *I)
const BasicBlock * getParent() const
an instruction to allocate memory on the stack
Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
bool IsAutorelease(ARCInstKind Class)
Test if the given class is objc_autorelease or equivalent.