46 using namespace llvm::objcarc;
48 #define DEBUG_TYPE "objc-arc-opts"
58 if (isa<ConstantData>(Arg))
62 if (
const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
65 if (
GEP->hasAllZeroIndices())
69 cast<CallInst>(Arg)->getArgOperand(0));
131 STATISTIC(NumNoops,
"Number of no-op objc calls eliminated");
132 STATISTIC(NumPartialNoops,
"Number of partially no-op objc calls eliminated");
133 STATISTIC(NumAutoreleases,
"Number of autoreleases converted to releases");
134 STATISTIC(NumRets,
"Number of return value forwarding "
135 "retain+autoreleases eliminated");
136 STATISTIC(NumRRs,
"Number of retain+release paths eliminated");
137 STATISTIC(NumPeeps,
"Number of calls peephole-optimized");
140 "Number of retains before optimization");
142 "Number of releases before optimization");
144 "Number of retains after optimization");
146 "Number of releases after optimization");
154 unsigned TopDownPathCount;
157 unsigned BottomUpPathCount;
176 static const unsigned OverflowOccurredValue;
178 BBState() : TopDownPathCount(0), BottomUpPathCount(0) { }
180 typedef decltype(PerPtrTopDown)::iterator top_down_ptr_iterator;
181 typedef decltype(PerPtrTopDown)::const_iterator const_top_down_ptr_iterator;
183 top_down_ptr_iterator top_down_ptr_begin() {
return PerPtrTopDown.begin(); }
184 top_down_ptr_iterator top_down_ptr_end() {
return PerPtrTopDown.end(); }
185 const_top_down_ptr_iterator top_down_ptr_begin()
const {
186 return PerPtrTopDown.begin();
188 const_top_down_ptr_iterator top_down_ptr_end()
const {
189 return PerPtrTopDown.end();
191 bool hasTopDownPtrs()
const {
192 return !PerPtrTopDown.empty();
195 typedef decltype(PerPtrBottomUp)::iterator bottom_up_ptr_iterator;
197 PerPtrBottomUp)::const_iterator const_bottom_up_ptr_iterator;
199 bottom_up_ptr_iterator bottom_up_ptr_begin() {
200 return PerPtrBottomUp.begin();
202 bottom_up_ptr_iterator bottom_up_ptr_end() {
return PerPtrBottomUp.end(); }
203 const_bottom_up_ptr_iterator bottom_up_ptr_begin()
const {
204 return PerPtrBottomUp.begin();
206 const_bottom_up_ptr_iterator bottom_up_ptr_end()
const {
207 return PerPtrBottomUp.end();
209 bool hasBottomUpPtrs()
const {
210 return !PerPtrBottomUp.empty();
215 void SetAsEntry() { TopDownPathCount = 1; }
219 void SetAsExit() { BottomUpPathCount = 1; }
225 return PerPtrTopDown[Arg];
232 return PerPtrBottomUp[Arg];
237 bottom_up_ptr_iterator findPtrBottomUpState(
const Value *Arg) {
238 return PerPtrBottomUp.find(Arg);
241 void clearBottomUpPointers() {
242 PerPtrBottomUp.clear();
245 void clearTopDownPointers() {
246 PerPtrTopDown.clear();
249 void InitFromPred(
const BBState &Other);
250 void InitFromSucc(
const BBState &Other);
251 void MergePred(
const BBState &Other);
252 void MergeSucc(
const BBState &Other);
260 bool GetAllPathCountWithOverflow(
unsigned &PathCount)
const {
261 if (TopDownPathCount == OverflowOccurredValue ||
262 BottomUpPathCount == OverflowOccurredValue)
264 unsigned long long Product =
265 (
unsigned long long)TopDownPathCount*BottomUpPathCount;
268 return (Product >> 32) ||
269 ((PathCount = Product) == OverflowOccurredValue);
274 edge_iterator
pred_begin()
const {
return Preds.begin(); }
275 edge_iterator
pred_end()
const {
return Preds.end(); }
276 edge_iterator
succ_begin()
const {
return Succs.begin(); }
277 edge_iterator
succ_end()
const {
return Succs.end(); }
279 void addSucc(
BasicBlock *Succ) { Succs.push_back(Succ); }
280 void addPred(
BasicBlock *Pred) { Preds.push_back(Pred); }
282 bool isExit()
const {
return Succs.empty(); }
285 const unsigned BBState::OverflowOccurredValue = 0xffffffff;
293 void BBState::InitFromPred(
const BBState &Other) {
294 PerPtrTopDown = Other.PerPtrTopDown;
295 TopDownPathCount = Other.TopDownPathCount;
298 void BBState::InitFromSucc(
const BBState &Other) {
299 PerPtrBottomUp = Other.PerPtrBottomUp;
300 BottomUpPathCount = Other.BottomUpPathCount;
305 void BBState::MergePred(
const BBState &Other) {
306 if (TopDownPathCount == OverflowOccurredValue)
311 TopDownPathCount += Other.TopDownPathCount;
316 if (TopDownPathCount == OverflowOccurredValue) {
317 clearTopDownPointers();
323 if (TopDownPathCount < Other.TopDownPathCount) {
324 TopDownPathCount = OverflowOccurredValue;
325 clearTopDownPointers();
332 for (
auto MI = Other.top_down_ptr_begin(), ME = Other.top_down_ptr_end();
334 auto Pair = PerPtrTopDown.insert(*
MI);
341 for (
auto MI = top_down_ptr_begin(), ME = top_down_ptr_end();
MI != ME; ++
MI)
342 if (Other.PerPtrTopDown.find(
MI->first) == Other.PerPtrTopDown.end())
348 void BBState::MergeSucc(
const BBState &Other) {
349 if (BottomUpPathCount == OverflowOccurredValue)
354 BottomUpPathCount += Other.BottomUpPathCount;
359 if (BottomUpPathCount == OverflowOccurredValue) {
360 clearBottomUpPointers();
366 if (BottomUpPathCount < Other.BottomUpPathCount) {
367 BottomUpPathCount = OverflowOccurredValue;
368 clearBottomUpPointers();
375 for (
auto MI = Other.bottom_up_ptr_begin(), ME = Other.bottom_up_ptr_end();
377 auto Pair = PerPtrBottomUp.insert(*
MI);
384 for (
auto MI = bottom_up_ptr_begin(), ME = bottom_up_ptr_end();
MI != ME;
386 if (Other.PerPtrBottomUp.find(
MI->first) == Other.PerPtrBottomUp.end())
392 OS <<
" TopDown State:\n";
393 if (!BBInfo.hasTopDownPtrs()) {
396 for (
auto I = BBInfo.top_down_ptr_begin(),
E = BBInfo.top_down_ptr_end();
399 OS <<
" Ptr: " << *
I->first
400 <<
"\n KnownSafe: " << (P.
IsKnownSafe()?
"true":
"false")
401 <<
"\n ImpreciseRelease: "
403 <<
" HasCFGHazards: "
405 <<
" KnownPositive: "
412 OS <<
" BottomUp State:\n";
413 if (!BBInfo.hasBottomUpPtrs()) {
416 for (
auto I = BBInfo.bottom_up_ptr_begin(),
E = BBInfo.bottom_up_ptr_end();
419 OS <<
" Ptr: " << *
I->first
420 <<
"\n KnownSafe: " << (P.
IsKnownSafe()?
"true":
"false")
421 <<
"\n ImpreciseRelease: "
423 <<
" HasCFGHazards: "
425 <<
" KnownPositive: "
454 unsigned UsedInThisFunction;
459 void OptimizeIndividualCalls(
Function &
F);
463 BBState &MyStates)
const;
492 Value *Arg,
bool KnownSafe,
493 bool &AnyPairsCompletelyEliminated);
506 void GatherStatistics(
Function &
F,
bool AfterOptimization =
false);
510 bool doInitialization(
Module &M)
override;
511 bool runOnFunction(
Function &
F)
override;
512 void releaseMemory()
override;
524 "objc-arc",
"ObjC ARC optimization",
false,
false)
530 return new ObjCARCOpt();
556 }
else if (
const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
558 if (II->getNormalDest() == RetainRVParent) {
581 DEBUG(
dbgs() <<
"Erasing autoreleaseRV,retainRV pair: " << *I <<
"\n"
582 <<
"Erasing " << *RetainRV <<
"\n");
594 DEBUG(
dbgs() <<
"Transforming objc_retainAutoreleasedReturnValue => "
595 "objc_retain since the operand is not a return value.\n"
596 "Old = " << *RetainRV <<
"\n");
599 cast<CallInst>(RetainRV)->setCalledFunction(NewDecl);
601 DEBUG(
dbgs() <<
"New = " << *RetainRV <<
"\n");
608 void ObjCARCOpt::OptimizeAutoreleaseRVCall(
Function &F,
616 if (isa<ConstantData>(Ptr))
626 if (isa<BitCastInst>(U))
629 }
while (!Users.
empty());
634 DEBUG(
dbgs() <<
"Transforming objc_autoreleaseReturnValue => "
635 "objc_autorelease since its operand is not used as a return "
637 "Old = " << *AutoreleaseRV <<
"\n");
639 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
645 DEBUG(
dbgs() <<
"New: " << *AutoreleaseRV <<
"\n");
651 void ObjCARCOpt::OptimizeIndividualCalls(
Function &F) {
652 DEBUG(
dbgs() <<
"\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
654 UsedInThisFunction = 0;
662 DEBUG(
dbgs() <<
"Visiting: Class: " << Class <<
"; " << *Inst <<
"\n");
678 DEBUG(
dbgs() <<
"Erasing no-op cast: " << *Inst <<
"\n");
688 CallInst *CI = cast<CallInst>(Inst);
696 DEBUG(
dbgs() <<
"A null pointer-to-weak-pointer is undefined behavior."
697 "\nOld = " << *CI <<
"\nNew = " << *NewValue <<
"\n");
706 CallInst *CI = cast<CallInst>(Inst);
716 DEBUG(
dbgs() <<
"A null pointer-to-weak-pointer is undefined behavior."
717 "\nOld = " << *CI <<
"\nNew = " << *NewValue <<
"\n");
726 if (OptimizeRetainRVCall(F, Inst))
730 OptimizeAutoreleaseRVCall(F, Inst, Class);
752 DEBUG(
dbgs() <<
"Replacing autorelease{,RV}(x) with objc_release(x) "
753 "since x is otherwise unused.\nOld: " << *Call <<
"\nNew: "
754 << *NewCall <<
"\n");
766 DEBUG(
dbgs() <<
"Adding tail keyword to function since it can never be "
767 "passed stack args: " << *Inst <<
"\n");
768 cast<CallInst>(Inst)->setTailCall();
775 DEBUG(
dbgs() <<
"Removing tail keyword from function: " << *Inst <<
777 cast<CallInst>(Inst)->setTailCall(
false);
783 DEBUG(
dbgs() <<
"Found no throw class. Setting nounwind on: " << *Inst
789 UsedInThisFunction |= 1 <<
unsigned(Class);
799 DEBUG(
dbgs() <<
"ARC calls with null are no-ops. Erasing: " << *Inst
807 UsedInThisFunction |= 1 <<
unsigned(Class);
815 Worklist.
push_back(std::make_pair(Inst, Arg));
817 std::pair<Instruction *, const Value *> Pair = Worklist.
pop_back_val();
826 bool HasNull =
false;
827 bool HasCriticalEdges =
false;
834 .getNumSuccessors() != 1) {
835 HasCriticalEdges =
true;
840 if (!HasCriticalEdges && HasNull) {
856 DependingInstructions, Visited, PA);
862 DependingInstructions, Visited, PA);
876 if (DependingInstructions.size() == 1 &&
877 *DependingInstructions.begin() == PN) {
881 CallInst *CInst = cast<CallInst>(Inst);
890 if (Op->getType() != ParamTy)
897 "And inserting clone at " << *InsertPos <<
"\n");
898 Worklist.
push_back(std::make_pair(Clone, Incoming));
902 DEBUG(
dbgs() <<
"Erasing: " << *CInst <<
"\n");
907 }
while (!Worklist.
empty());
914 const bool SuccSRRIKnownSafe,
916 bool &SomeSuccHasSame,
917 bool &AllSuccsHaveSame,
918 bool &NotAllSeqEqualButKnownSafe,
919 bool &ShouldContinue) {
927 ShouldContinue =
true;
931 SomeSuccHasSame =
true;
937 AllSuccsHaveSame =
false;
939 NotAllSeqEqualButKnownSafe =
true;
952 const bool SuccSRRIKnownSafe,
954 bool &SomeSuccHasSame,
955 bool &AllSuccsHaveSame,
956 bool &NotAllSeqEqualButKnownSafe) {
959 SomeSuccHasSame =
true;
966 AllSuccsHaveSame =
false;
968 NotAllSeqEqualButKnownSafe =
true;
981 ObjCARCOpt::CheckForCFGHazards(
const BasicBlock *BB,
983 BBState &MyStates)
const {
986 for (
auto I = MyStates.top_down_ptr_begin(),
E = MyStates.top_down_ptr_end();
989 const Sequence Seq = I->second.GetSeq();
998 "Unknown top down sequence state.");
1000 const Value *Arg = I->first;
1002 bool SomeSuccHasSame =
false;
1003 bool AllSuccsHaveSame =
true;
1004 bool NotAllSeqEqualButKnownSafe =
false;
1008 for (;
SI != SE; ++
SI) {
1015 const Sequence SuccSSeq = SuccS.GetSeq();
1022 if (SuccSSeq ==
S_None) {
1029 const bool SuccSRRIKnownSafe = SuccS.IsKnownSafe();
1035 bool ShouldContinue =
false;
1037 AllSuccsHaveSame, NotAllSeqEqualButKnownSafe,
1045 SomeSuccHasSame, AllSuccsHaveSame,
1046 NotAllSeqEqualButKnownSafe);
1061 if (SomeSuccHasSame && !AllSuccsHaveSame) {
1063 }
else if (NotAllSeqEqualButKnownSafe) {
1073 bool ObjCARCOpt::VisitInstructionBottomUp(
1075 BBState &MyStates) {
1076 bool NestingDetected =
false;
1078 const Value *Arg =
nullptr;
1080 DEBUG(
dbgs() <<
" Class: " << Class <<
"\n");
1113 MyStates.clearBottomUpPointers();
1114 return NestingDetected;
1118 return NestingDetected;
1125 for (
auto MI = MyStates.bottom_up_ptr_begin(),
1126 ME = MyStates.bottom_up_ptr_end();
1139 return NestingDetected;
1142 bool ObjCARCOpt::VisitBottomUp(
BasicBlock *BB,
1146 DEBUG(
dbgs() <<
"\n== ObjCARCOpt::VisitBottomUp ==\n");
1148 bool NestingDetected =
false;
1149 BBState &MyStates = BBStates[BB];
1153 BBState::edge_iterator
SI(MyStates.succ_begin()),
1154 SE(MyStates.succ_end());
1159 MyStates.InitFromSucc(I->second);
1161 for (;
SI != SE; ++
SI) {
1163 I = BBStates.
find(Succ);
1165 MyStates.MergeSucc(I->second);
1170 <<
"Performing Dataflow:\n");
1177 if (isa<InvokeInst>(Inst))
1180 DEBUG(
dbgs() <<
" Visiting " << *Inst <<
"\n");
1182 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
1188 for (BBState::edge_iterator PI(MyStates.pred_begin()),
1189 PE(MyStates.pred_end()); PI != PE; ++PI) {
1192 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
1197 return NestingDetected;
1201 ObjCARCOpt::VisitInstructionTopDown(
Instruction *Inst,
1203 BBState &MyStates) {
1204 bool NestingDetected =
false;
1206 const Value *Arg =
nullptr;
1242 MyStates.clearTopDownPointers();
1254 for (
auto MI = MyStates.top_down_ptr_begin(),
1255 ME = MyStates.top_down_ptr_end();
1267 return NestingDetected;
1274 DEBUG(
dbgs() <<
"\n== ObjCARCOpt::VisitTopDown ==\n");
1275 bool NestingDetected =
false;
1276 BBState &MyStates = BBStates[BB];
1280 BBState::edge_iterator PI(MyStates.pred_begin()),
1281 PE(MyStates.pred_end());
1286 MyStates.InitFromPred(I->second);
1288 for (; PI != PE; ++PI) {
1290 I = BBStates.
find(Pred);
1292 MyStates.MergePred(I->second);
1297 <<
"Performing Dataflow:\n");
1301 DEBUG(
dbgs() <<
" Visiting " << Inst <<
"\n");
1303 NestingDetected |= VisitInstructionTopDown(&Inst, Releases, MyStates);
1307 << BBStates[BB] <<
"\n\n");
1308 CheckForCFGHazards(BB, BBStates, MyStates);
1310 return NestingDetected;
1317 unsigned NoObjCARCExceptionsMDKind,
1329 BBState &MyStates = BBStates[EntryBB];
1330 MyStates.SetAsEntry();
1341 while (SuccStack.
back().second != SE) {
1343 if (Visited.
insert(SuccBB).second) {
1346 BBStates[CurrBB].addSucc(SuccBB);
1347 BBState &SuccStates = BBStates[SuccBB];
1348 SuccStates.addPred(CurrBB);
1353 if (!OnStack.
count(SuccBB)) {
1354 BBStates[CurrBB].addSucc(SuccBB);
1355 BBStates[SuccBB].addPred(CurrBB);
1358 OnStack.
erase(CurrBB);
1361 }
while (!SuccStack.
empty());
1370 BBState &MyStates = BBStates[&ExitBB];
1371 if (!MyStates.isExit())
1374 MyStates.SetAsExit();
1376 PredStack.
push_back(std::make_pair(&ExitBB, MyStates.pred_begin()));
1378 while (!PredStack.
empty()) {
1379 reverse_dfs_next_succ:
1380 BBState::edge_iterator PE = BBStates[PredStack.
back().first].pred_end();
1381 while (PredStack.
back().second != PE) {
1383 if (Visited.
insert(BB).second) {
1385 goto reverse_dfs_next_succ;
1394 bool ObjCARCOpt::Visit(
Function &F,
1411 bool BottomUpNestingDetected =
false;
1413 BottomUpNestingDetected |= VisitBottomUp(BB, BBStates, Retains);
1416 bool TopDownNestingDetected =
false;
1418 TopDownNestingDetected |= VisitTopDown(BB, BBStates, Releases);
1420 return TopDownNestingDetected && BottomUpNestingDetected;
1424 void ObjCARCOpt::MoveCalls(
Value *Arg,
RRInfo &RetainsToMove,
1433 DEBUG(
dbgs() <<
"== ObjCARCOpt::MoveCalls ==\n");
1437 Value *MyArg = ArgTy == ParamTy ? Arg :
1444 DEBUG(
dbgs() <<
"Inserting new Retain: " << *Call <<
"\n"
1445 "At insertion point: " << *InsertPt <<
"\n");
1448 Value *MyArg = ArgTy == ParamTy ? Arg :
1459 DEBUG(
dbgs() <<
"Inserting new Release: " << *Call <<
"\n"
1460 "At insertion point: " << *InsertPt <<
"\n");
1465 Retains.
blot(OrigRetain);
1467 DEBUG(
dbgs() <<
"Deleting retain: " << *OrigRetain <<
"\n");
1470 Releases.
erase(OrigRelease);
1472 DEBUG(
dbgs() <<
"Deleting release: " << *OrigRelease <<
"\n");
1477 bool ObjCARCOpt::PairUpRetainsAndReleases(
1483 RRInfo &ReleasesToMove,
Value *Arg,
bool KnownSafe,
1484 bool &AnyPairsCompletelyEliminated) {
1488 bool KnownSafeTD =
true, KnownSafeBU =
true;
1489 bool CFGHazardAfflicted =
false;
1495 unsigned OldDelta = 0;
1496 unsigned NewDelta = 0;
1497 unsigned OldCount = 0;
1498 unsigned NewCount = 0;
1499 bool FirstRelease =
true;
1503 auto It = Retains.
find(NewRetain);
1505 const RRInfo &NewRetainRRI = It->second;
1506 KnownSafeTD &= NewRetainRRI.KnownSafe;
1507 for (
Instruction *NewRetainRelease : NewRetainRRI.Calls) {
1508 auto Jt = Releases.
find(NewRetainRelease);
1509 if (Jt == Releases.
end())
1511 const RRInfo &NewRetainReleaseRRI = Jt->second;
1518 if (!NewRetainReleaseRRI.
Calls.count(NewRetain))
1521 if (ReleasesToMove.
Calls.insert(NewRetainRelease).second) {
1525 const BBState &NRRBBState = BBStates[NewRetainRelease->
getParent()];
1526 unsigned PathCount = BBState::OverflowOccurredValue;
1527 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
1529 assert(PathCount != BBState::OverflowOccurredValue &&
1530 "PathCount at this point can not be "
1531 "OverflowOccurredValue.");
1532 OldDelta -= PathCount;
1540 FirstRelease =
false;
1556 const BBState &RIPBBState = BBStates[RIP->
getParent()];
1557 PathCount = BBState::OverflowOccurredValue;
1558 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
1560 assert(PathCount != BBState::OverflowOccurredValue &&
1561 "PathCount at this point can not be "
1562 "OverflowOccurredValue.");
1563 NewDelta -= PathCount;
1566 NewReleases.
push_back(NewRetainRelease);
1571 if (NewReleases.
empty())
break;
1575 auto It = Releases.
find(NewRelease);
1577 const RRInfo &NewReleaseRRI = It->second;
1579 CFGHazardAfflicted |= NewReleaseRRI.CFGHazardAfflicted;
1580 for (
Instruction *NewReleaseRetain : NewReleaseRRI.Calls) {
1581 auto Jt = Retains.
find(NewReleaseRetain);
1582 if (Jt == Retains.
end())
1584 const RRInfo &NewReleaseRetainRRI = Jt->second;
1591 if (!NewReleaseRetainRRI.
Calls.count(NewRelease))
1594 if (RetainsToMove.
Calls.insert(NewReleaseRetain).second) {
1597 const BBState &NRRBBState = BBStates[NewReleaseRetain->
getParent()];
1598 unsigned PathCount = BBState::OverflowOccurredValue;
1599 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
1601 assert(PathCount != BBState::OverflowOccurredValue &&
1602 "PathCount at this point can not be "
1603 "OverflowOccurredValue.");
1604 OldDelta += PathCount;
1605 OldCount += PathCount;
1613 const BBState &RIPBBState = BBStates[RIP->
getParent()];
1615 PathCount = BBState::OverflowOccurredValue;
1616 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
1618 assert(PathCount != BBState::OverflowOccurredValue &&
1619 "PathCount at this point can not be "
1620 "OverflowOccurredValue.");
1621 NewDelta += PathCount;
1622 NewCount += PathCount;
1625 NewRetains.push_back(NewReleaseRetain);
1629 if (NewRetains.empty())
break;
1633 bool UnconditionallySafe = KnownSafeTD && KnownSafeBU;
1634 if (UnconditionallySafe) {
1649 const bool WillPerformCodeMotion = RetainsToMove.
ReverseInsertPts.size() ||
1651 if (CFGHazardAfflicted && WillPerformCodeMotion)
1664 assert(OldCount != 0 &&
"Unreachable code?");
1665 NumRRs += OldCount - NewCount;
1667 AnyPairsCompletelyEliminated = NewCount == 0;
1675 bool ObjCARCOpt::PerformCodePlacement(
1679 DEBUG(
dbgs() <<
"\n== ObjCARCOpt::PerformCodePlacement ==\n");
1681 bool AnyPairsCompletelyEliminated =
false;
1688 Value *V = I->first;
1693 DEBUG(
dbgs() <<
"Visiting: " << *Retain <<
"\n");
1700 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
1704 if (
const LoadInst *LI = dyn_cast<LoadInst>(Arg))
1706 dyn_cast<GlobalVariable>(
1708 if (GV->isConstant())
1713 RRInfo RetainsToMove, ReleasesToMove;
1715 bool PerformMoveCalls = PairUpRetainsAndReleases(
1716 BBStates, Retains, Releases, M, Retain, DeadInsts,
1717 RetainsToMove, ReleasesToMove, Arg, KnownSafe,
1718 AnyPairsCompletelyEliminated);
1720 if (PerformMoveCalls) {
1723 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
1724 Retains, Releases, DeadInsts, M);
1730 while (!DeadInsts.
empty())
1733 return AnyPairsCompletelyEliminated;
1737 void ObjCARCOpt::OptimizeWeakCalls(
Function &F) {
1738 DEBUG(
dbgs() <<
"\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
1746 DEBUG(
dbgs() <<
"Visiting: " << *Inst <<
"\n");
1770 switch (EarlierClass) {
1775 CallInst *Call = cast<CallInst>(Inst);
1776 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
1778 Value *EarlierArg = EarlierCall->getArgOperand(0);
1779 switch (PA.getAA()->alias(Arg, EarlierArg)) {
1804 CallInst *Call = cast<CallInst>(Inst);
1805 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
1807 Value *EarlierArg = EarlierCall->getArgOperand(0);
1808 switch (PA.getAA()->alias(Arg, EarlierArg)) {
1856 CallInst *Call = cast<CallInst>(Inst);
1858 if (
AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
1860 const Instruction *UserInst = cast<Instruction>(U);
1871 for (
auto UI = Alloca->user_begin(), UE = Alloca->user_end(); UI != UE;) {
1872 CallInst *UserInst = cast<CallInst>(*UI++);
1887 Alloca->eraseFromParent();
1895 bool ObjCARCOpt::OptimizeSequences(
Function &F) {
1908 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
1911 bool AnyPairsCompletelyEliminated = PerformCodePlacement(BBStates, Retains,
1915 return AnyPairsCompletelyEliminated && NestingDetected;
1927 DepInsts, Visited, PA);
1928 if (DepInsts.size() != 1)
1931 auto *Call = dyn_cast_or_null<CallInst>(*DepInsts.begin());
1934 if (!Call || Arg != Call)
1952 BB, Autorelease, DepInsts, Visited, PA);
1953 if (DepInsts.
size() != 1)
1956 auto *Retain = dyn_cast_or_null<CallInst>(*DepInsts.
begin());
1977 BB, Ret, DepInsts, V, PA);
1978 if (DepInsts.
size() != 1)
2001 void ObjCARCOpt::OptimizeReturns(
Function &F) {
2005 DEBUG(
dbgs() <<
"\n== ObjCARCOpt::OptimizeReturns ==\n");
2014 DEBUG(
dbgs() <<
"Visiting: " << *Ret <<
"\n");
2022 Arg, &BB, Ret, DependingInstructions, Visited, PA);
2023 DependingInstructions.
clear();
2030 Arg, &BB, Autorelease, DependingInstructions, Visited, PA);
2031 DependingInstructions.
clear();
2040 DependingInstructions,
2042 DependingInstructions.
clear();
2045 if (!HasSafePathToCall)
2051 DEBUG(
dbgs() <<
"Erasing: " << *Retain <<
"\nErasing: "
2052 << *Autorelease <<
"\n");
2060 ObjCARCOpt::GatherStatistics(
Function &F,
bool AfterOptimization) {
2062 AfterOptimization? NumRetainsAfterOpt : NumRetainsBeforeOpt;
2064 AfterOptimization? NumReleasesAfterOpt : NumReleasesBeforeOpt;
2082 bool ObjCARCOpt::doInitialization(
Module &M) {
2094 MDKindCache.init(&M);
2102 bool ObjCARCOpt::runOnFunction(
Function &F) {
2112 DEBUG(
dbgs() <<
"<<< ObjCARCOpt: Visiting Function: " << F.
getName() <<
" >>>"
2115 PA.setAA(&getAnalysis<AAResultsWrapperPass>().getAAResults());
2119 GatherStatistics(F,
false);
2128 OptimizeIndividualCalls(F);
2138 OptimizeWeakCalls(F);
2147 while (OptimizeSequences(F)) {}
2157 GatherStatistics(F,
true);
2166 void ObjCARCOpt::releaseMemory() {
Pass interface - Implemented by all 'passes'.
The two locations precisely alias each other.
Return a value (possibly void), from a function.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void push_back(const T &Elt)
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.
typename SuperClass::const_iterator const_iterator
const Instruction & back() const
This file contains a class ARCRuntimeEntryPoints for use in creating/managing references to entry poi...
STATISTIC(NumFunctions,"Total number of functions")
objc_loadWeakRetained (primitive)
could call objc_release and/or "use" pointers
A Module instance is used to store all the information related to an LLVM module. ...
The two locations alias, but only due to a partial overlap.
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...
bool MatchWithRelease(ARCMDKindCache &Cache, Instruction *Release)
Return true if this set of retains can be paired with the given release.
The two locations do not alias at all.
void initializeObjCARCOptPass(PassRegistry &)
An instruction for reading from memory.
TerminatorInst::SuccIterator< TerminatorInst *, BasicBlock > succ_iterator
iv Induction Variable Users
SmallPtrSet< Instruction *, 2 > ReverseInsertPts
The set of optimal insert positions for moving calls in the opposite sequence.
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.
The two locations may or may not alias. This is the least precise result.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
StringRef getName() const
Return a constant reference to the value's name.
iterator begin()
Instruction iterator methods.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
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...
This class summarizes several per-pointer runtime properties which are propagated through the flow gr...
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following: ...
bool IsNullOrUndef(const Value *V)
LLVM_NODISCARD bool empty() const
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 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()))
objc_retainAutoreleasedReturnValue
static bool setDoesNotThrow(Function &F)
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
bool EnableARCOpts
A handy option to enable/disable all ARC Optimizations.
This class represents a no-op cast from one type to another.
void HandlePotentialUse(BasicBlock *BB, Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA, ARCInstKind Class)
An instruction for storing to memory.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
const RRInfo & GetRRInfo() const
bool IsAlwaysTail(ARCInstKind Class)
Test if the given class represents instructions which are always safe to mark with the "tail" keyword...
BBIty & getBasicBlockIterator()
bool ModuleHasARC(const Module &M)
Test if the given module looks interesting to run ARC optimization on.
Unidirectional information about either a retain-decrement-use-release sequence or release-use-decrem...
unsigned getNumIncomingValues() const
Return the number of incoming edges.
Interval::succ_iterator succ_end(Interval *I)
raw_ostream & operator<<(raw_ostream &OS, const ARCInstKind Class)
iterator find(const_arg_type_t< KeyT > Val)
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
iterator find(const KeyT &Key)
Type * getReturnType() const
Returns the type of the ret val.
bool erase(const KeyT &Val)
Subclasses of this class are all able to terminate a basic block.
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.
bool IsCFGHazardAfflicted() const
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.
This is an important base class in LLVM.
VectorTy::const_iterator const_iterator
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...
like S_Release, but code motion is stopped.
Represent the analysis usage information of a pass.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
#define LLVM_ATTRIBUTE_UNUSED
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
FunctionPass class - This class is used to implement most global optimizations.
Value * getOperand(unsigned i) const
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...
self_iterator getIterator()
A cache of MDKinds used by various ARC optimizations.
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...
INITIALIZE_PASS_BEGIN(ObjCARCOpt,"objc-arc","ObjC ARC optimization", false, false) INITIALIZE_PASS_END(ObjCARCOpt
void setTailCall(bool isTC=true)
bool isPointerTy() const
True if this is an instance of PointerType.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
LLVMContext & getContext() const
All values hold a context through their type.
anything that is inert from an ARC perspective.
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.
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...
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...
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
static CallInst * Create(Value *Func, ArrayRef< Value * > Args, ArrayRef< OperandBundleDef > Bundles=None, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
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.
Type * getType() const
All values are typed, get the type of this value.
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)
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
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 ...
LLVM_NODISCARD T pop_back_val()
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...
void setPreservesCFG()
This function should be called by the pass, iff they do not:
const BasicBlock & getEntryBlock() const
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
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()
iterator_range< user_iterator > users()
llvm_unreachable("Unknown RegBank!")
void ClearSequenceProgress()
objc ObjC ARC optimization
bool IsRetain(ARCInstKind Class)
Test if the given class is objc_retain or equivalent.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
void setCalledFunction(Value *Fn)
Set the function called.
Establish a view to a call site for examination.
objc_storeWeak (primitive)
bool hasOneUse() const
Return true if there is exactly one user of this value.
void setArgOperand(unsigned i, Value *v)
Sequence
A sequence of states that a pointer may go through in which an objc_retain and objc_release are actua...
bool IsTrackingImpreciseReleases() const
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)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Module * getParent()
Get the module that this global value is contained inside of...
LLVM Value Representation.
foo(x) – x could possibly see a ref count decrement.
Legacy wrapper pass to provide the ObjCARCAAResult object.
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...
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 void ComputePostOrders(Function &F, SmallVectorImpl< BasicBlock * > &PostOrder, SmallVectorImpl< BasicBlock * > &ReverseCFGPostOrder, unsigned NoObjCARCExceptionsMDKind, DenseMap< const BasicBlock *, BBState > &BBStates)
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
bool InitTopDown(ARCInstKind Kind, Instruction *I)
(Re-)Initialize this bottom up pointer returning true if we detected a pointer with nested releases...
bool HasKnownPositiveRefCount() const
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...
static IntegerType * getInt8Ty(LLVMContext &C)
bool AreStatisticsEnabled()
Check if statistics are enabled.
const BasicBlock * getParent() const
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 ...
bool IsNoopInstruction(const Instruction *I)
an instruction to allocate memory on the stack
bool IsAutorelease(ARCInstKind Class)
Test if the given class is objc_autorelease or equivalent.