1 //===- ObjCARCOpts.cpp - ObjC ARC Optimization ----------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 /// \file 10 /// This file defines ObjC ARC optimizations. ARC stands for Automatic 11 /// Reference Counting and is a system for managing reference counts for objects 12 /// in Objective C. 13 /// 14 /// The optimizations performed include elimination of redundant, partially 15 /// redundant, and inconsequential reference count operations, elimination of 16 /// redundant weak pointer operations, and numerous minor simplifications. 17 /// 18 /// WARNING: This file knows about certain library functions. It recognizes them 19 /// by name, and hardwires knowledge of their semantics. 20 /// 21 /// WARNING: This file knows about how certain Objective-C library functions are 22 /// used. Naive LLVM IR transformations which would otherwise be 23 /// behavior-preserving may break these assumptions. 24 // 25 //===----------------------------------------------------------------------===// 26 27 #include "ARCRuntimeEntryPoints.h" 28 #include "BlotMapVector.h" 29 #include "DependencyAnalysis.h" 30 #include "ObjCARC.h" 31 #include "ProvenanceAnalysis.h" 32 #include "PtrState.h" 33 #include "llvm/ADT/DenseMap.h" 34 #include "llvm/ADT/None.h" 35 #include "llvm/ADT/STLExtras.h" 36 #include "llvm/ADT/SmallPtrSet.h" 37 #include "llvm/ADT/SmallVector.h" 38 #include "llvm/ADT/Statistic.h" 39 #include "llvm/Analysis/AliasAnalysis.h" 40 #include "llvm/Analysis/EHPersonalities.h" 41 #include "llvm/Analysis/ObjCARCAliasAnalysis.h" 42 #include "llvm/Analysis/ObjCARCAnalysisUtils.h" 43 #include "llvm/Analysis/ObjCARCInstKind.h" 44 #include "llvm/IR/BasicBlock.h" 45 #include "llvm/IR/CFG.h" 46 #include "llvm/IR/CallSite.h" 47 #include "llvm/IR/Constant.h" 48 #include "llvm/IR/Constants.h" 49 #include "llvm/IR/DerivedTypes.h" 50 #include "llvm/IR/Function.h" 51 #include "llvm/IR/GlobalVariable.h" 52 #include "llvm/IR/InstIterator.h" 53 #include "llvm/IR/InstrTypes.h" 54 #include "llvm/IR/Instruction.h" 55 #include "llvm/IR/Instructions.h" 56 #include "llvm/IR/LLVMContext.h" 57 #include "llvm/IR/Metadata.h" 58 #include "llvm/IR/Type.h" 59 #include "llvm/IR/User.h" 60 #include "llvm/IR/Value.h" 61 #include "llvm/InitializePasses.h" 62 #include "llvm/Pass.h" 63 #include "llvm/Support/Casting.h" 64 #include "llvm/Support/CommandLine.h" 65 #include "llvm/Support/Compiler.h" 66 #include "llvm/Support/Debug.h" 67 #include "llvm/Support/ErrorHandling.h" 68 #include "llvm/Support/raw_ostream.h" 69 #include <cassert> 70 #include <iterator> 71 #include <utility> 72 73 using namespace llvm; 74 using namespace llvm::objcarc; 75 76 #define DEBUG_TYPE "objc-arc-opts" 77 78 static cl::opt<unsigned> MaxPtrStates("arc-opt-max-ptr-states", 79 cl::Hidden, 80 cl::desc("Maximum number of ptr states the optimizer keeps track of"), 81 cl::init(4095)); 82 83 /// \defgroup ARCUtilities Utility declarations/definitions specific to ARC. 84 /// @{ 85 86 /// This is similar to GetRCIdentityRoot but it stops as soon 87 /// as it finds a value with multiple uses. 88 static const Value *FindSingleUseIdentifiedObject(const Value *Arg) { 89 // ConstantData (like ConstantPointerNull and UndefValue) is used across 90 // modules. It's never a single-use value. 91 if (isa<ConstantData>(Arg)) 92 return nullptr; 93 94 if (Arg->hasOneUse()) { 95 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg)) 96 return FindSingleUseIdentifiedObject(BC->getOperand(0)); 97 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg)) 98 if (GEP->hasAllZeroIndices()) 99 return FindSingleUseIdentifiedObject(GEP->getPointerOperand()); 100 if (IsForwarding(GetBasicARCInstKind(Arg))) 101 return FindSingleUseIdentifiedObject( 102 cast<CallInst>(Arg)->getArgOperand(0)); 103 if (!IsObjCIdentifiedObject(Arg)) 104 return nullptr; 105 return Arg; 106 } 107 108 // If we found an identifiable object but it has multiple uses, but they are 109 // trivial uses, we can still consider this to be a single-use value. 110 if (IsObjCIdentifiedObject(Arg)) { 111 for (const User *U : Arg->users()) 112 if (!U->use_empty() || GetRCIdentityRoot(U) != Arg) 113 return nullptr; 114 115 return Arg; 116 } 117 118 return nullptr; 119 } 120 121 /// @} 122 /// 123 /// \defgroup ARCOpt ARC Optimization. 124 /// @{ 125 126 // TODO: On code like this: 127 // 128 // objc_retain(%x) 129 // stuff_that_cannot_release() 130 // objc_autorelease(%x) 131 // stuff_that_cannot_release() 132 // objc_retain(%x) 133 // stuff_that_cannot_release() 134 // objc_autorelease(%x) 135 // 136 // The second retain and autorelease can be deleted. 137 138 // TODO: It should be possible to delete 139 // objc_autoreleasePoolPush and objc_autoreleasePoolPop 140 // pairs if nothing is actually autoreleased between them. Also, autorelease 141 // calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code 142 // after inlining) can be turned into plain release calls. 143 144 // TODO: Critical-edge splitting. If the optimial insertion point is 145 // a critical edge, the current algorithm has to fail, because it doesn't 146 // know how to split edges. It should be possible to make the optimizer 147 // think in terms of edges, rather than blocks, and then split critical 148 // edges on demand. 149 150 // TODO: OptimizeSequences could generalized to be Interprocedural. 151 152 // TODO: Recognize that a bunch of other objc runtime calls have 153 // non-escaping arguments and non-releasing arguments, and may be 154 // non-autoreleasing. 155 156 // TODO: Sink autorelease calls as far as possible. Unfortunately we 157 // usually can't sink them past other calls, which would be the main 158 // case where it would be useful. 159 160 // TODO: The pointer returned from objc_loadWeakRetained is retained. 161 162 // TODO: Delete release+retain pairs (rare). 163 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"); 171 #ifndef NDEBUG 172 STATISTIC(NumRetainsBeforeOpt, 173 "Number of retains before optimization"); 174 STATISTIC(NumReleasesBeforeOpt, 175 "Number of releases before optimization"); 176 STATISTIC(NumRetainsAfterOpt, 177 "Number of retains after optimization"); 178 STATISTIC(NumReleasesAfterOpt, 179 "Number of releases after optimization"); 180 #endif 181 182 namespace { 183 184 /// Per-BasicBlock state. 185 class BBState { 186 /// The number of unique control paths from the entry which can reach this 187 /// block. 188 unsigned TopDownPathCount = 0; 189 190 /// The number of unique control paths to exits from this block. 191 unsigned BottomUpPathCount = 0; 192 193 /// The top-down traversal uses this to record information known about a 194 /// pointer at the bottom of each block. 195 BlotMapVector<const Value *, TopDownPtrState> PerPtrTopDown; 196 197 /// The bottom-up traversal uses this to record information known about a 198 /// pointer at the top of each block. 199 BlotMapVector<const Value *, BottomUpPtrState> PerPtrBottomUp; 200 201 /// Effective predecessors of the current block ignoring ignorable edges and 202 /// ignored backedges. 203 SmallVector<BasicBlock *, 2> Preds; 204 205 /// Effective successors of the current block ignoring ignorable edges and 206 /// ignored backedges. 207 SmallVector<BasicBlock *, 2> Succs; 208 209 public: 210 static const unsigned OverflowOccurredValue; 211 212 BBState() = default; 213 214 using top_down_ptr_iterator = decltype(PerPtrTopDown)::iterator; 215 using const_top_down_ptr_iterator = decltype(PerPtrTopDown)::const_iterator; 216 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(); 221 } 222 const_top_down_ptr_iterator top_down_ptr_end() const { 223 return PerPtrTopDown.end(); 224 } 225 bool hasTopDownPtrs() const { 226 return !PerPtrTopDown.empty(); 227 } 228 229 unsigned top_down_ptr_list_size() const { 230 return std::distance(top_down_ptr_begin(), top_down_ptr_end()); 231 } 232 233 using bottom_up_ptr_iterator = decltype(PerPtrBottomUp)::iterator; 234 using const_bottom_up_ptr_iterator = 235 decltype(PerPtrBottomUp)::const_iterator; 236 237 bottom_up_ptr_iterator bottom_up_ptr_begin() { 238 return PerPtrBottomUp.begin(); 239 } 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(); 243 } 244 const_bottom_up_ptr_iterator bottom_up_ptr_end() const { 245 return PerPtrBottomUp.end(); 246 } 247 bool hasBottomUpPtrs() const { 248 return !PerPtrBottomUp.empty(); 249 } 250 251 unsigned bottom_up_ptr_list_size() const { 252 return std::distance(bottom_up_ptr_begin(), bottom_up_ptr_end()); 253 } 254 255 /// Mark this block as being an entry block, which has one path from the 256 /// entry by definition. 257 void SetAsEntry() { TopDownPathCount = 1; } 258 259 /// Mark this block as being an exit block, which has one path to an exit by 260 /// definition. 261 void SetAsExit() { BottomUpPathCount = 1; } 262 263 /// Attempt to find the PtrState object describing the top down state for 264 /// pointer Arg. Return a new initialized PtrState describing the top down 265 /// state for Arg if we do not find one. 266 TopDownPtrState &getPtrTopDownState(const Value *Arg) { 267 return PerPtrTopDown[Arg]; 268 } 269 270 /// Attempt to find the PtrState object describing the bottom up state for 271 /// pointer Arg. Return a new initialized PtrState describing the bottom up 272 /// state for Arg if we do not find one. 273 BottomUpPtrState &getPtrBottomUpState(const Value *Arg) { 274 return PerPtrBottomUp[Arg]; 275 } 276 277 /// Attempt to find the PtrState object describing the bottom up state for 278 /// pointer Arg. 279 bottom_up_ptr_iterator findPtrBottomUpState(const Value *Arg) { 280 return PerPtrBottomUp.find(Arg); 281 } 282 283 void clearBottomUpPointers() { 284 PerPtrBottomUp.clear(); 285 } 286 287 void clearTopDownPointers() { 288 PerPtrTopDown.clear(); 289 } 290 291 void InitFromPred(const BBState &Other); 292 void InitFromSucc(const BBState &Other); 293 void MergePred(const BBState &Other); 294 void MergeSucc(const BBState &Other); 295 296 /// Compute the number of possible unique paths from an entry to an exit 297 /// which pass through this block. This is only valid after both the 298 /// top-down and bottom-up traversals are complete. 299 /// 300 /// Returns true if overflow occurred. Returns false if overflow did not 301 /// occur. 302 bool GetAllPathCountWithOverflow(unsigned &PathCount) const { 303 if (TopDownPathCount == OverflowOccurredValue || 304 BottomUpPathCount == OverflowOccurredValue) 305 return true; 306 unsigned long long Product = 307 (unsigned long long)TopDownPathCount*BottomUpPathCount; 308 // Overflow occurred if any of the upper bits of Product are set or if all 309 // the lower bits of Product are all set. 310 return (Product >> 32) || 311 ((PathCount = Product) == OverflowOccurredValue); 312 } 313 314 // Specialized CFG utilities. 315 using edge_iterator = SmallVectorImpl<BasicBlock *>::const_iterator; 316 317 edge_iterator pred_begin() const { return Preds.begin(); } 318 edge_iterator pred_end() const { return Preds.end(); } 319 edge_iterator succ_begin() const { return Succs.begin(); } 320 edge_iterator succ_end() const { return Succs.end(); } 321 322 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); } 323 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); } 324 325 bool isExit() const { return Succs.empty(); } 326 }; 327 328 } // end anonymous namespace 329 330 const unsigned BBState::OverflowOccurredValue = 0xffffffff; 331 332 namespace llvm { 333 334 raw_ostream &operator<<(raw_ostream &OS, 335 BBState &BBState) LLVM_ATTRIBUTE_UNUSED; 336 337 } // end namespace llvm 338 339 void BBState::InitFromPred(const BBState &Other) { 340 PerPtrTopDown = Other.PerPtrTopDown; 341 TopDownPathCount = Other.TopDownPathCount; 342 } 343 344 void BBState::InitFromSucc(const BBState &Other) { 345 PerPtrBottomUp = Other.PerPtrBottomUp; 346 BottomUpPathCount = Other.BottomUpPathCount; 347 } 348 349 /// The top-down traversal uses this to merge information about predecessors to 350 /// form the initial state for a new block. 351 void BBState::MergePred(const BBState &Other) { 352 if (TopDownPathCount == OverflowOccurredValue) 353 return; 354 355 // Other.TopDownPathCount can be 0, in which case it is either dead or a 356 // loop backedge. Loop backedges are special. 357 TopDownPathCount += Other.TopDownPathCount; 358 359 // In order to be consistent, we clear the top down pointers when by adding 360 // TopDownPathCount becomes OverflowOccurredValue even though "true" overflow 361 // has not occurred. 362 if (TopDownPathCount == OverflowOccurredValue) { 363 clearTopDownPointers(); 364 return; 365 } 366 367 // Check for overflow. If we have overflow, fall back to conservative 368 // behavior. 369 if (TopDownPathCount < Other.TopDownPathCount) { 370 TopDownPathCount = OverflowOccurredValue; 371 clearTopDownPointers(); 372 return; 373 } 374 375 // For each entry in the other set, if our set has an entry with the same key, 376 // merge the entries. Otherwise, copy the entry and merge it with an empty 377 // entry. 378 for (auto MI = Other.top_down_ptr_begin(), ME = Other.top_down_ptr_end(); 379 MI != ME; ++MI) { 380 auto Pair = PerPtrTopDown.insert(*MI); 381 Pair.first->second.Merge(Pair.second ? TopDownPtrState() : MI->second, 382 /*TopDown=*/true); 383 } 384 385 // For each entry in our set, if the other set doesn't have an entry with the 386 // same key, force it to merge with an empty entry. 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()) 389 MI->second.Merge(TopDownPtrState(), /*TopDown=*/true); 390 } 391 392 /// The bottom-up traversal uses this to merge information about successors to 393 /// form the initial state for a new block. 394 void BBState::MergeSucc(const BBState &Other) { 395 if (BottomUpPathCount == OverflowOccurredValue) 396 return; 397 398 // Other.BottomUpPathCount can be 0, in which case it is either dead or a 399 // loop backedge. Loop backedges are special. 400 BottomUpPathCount += Other.BottomUpPathCount; 401 402 // In order to be consistent, we clear the top down pointers when by adding 403 // BottomUpPathCount becomes OverflowOccurredValue even though "true" overflow 404 // has not occurred. 405 if (BottomUpPathCount == OverflowOccurredValue) { 406 clearBottomUpPointers(); 407 return; 408 } 409 410 // Check for overflow. If we have overflow, fall back to conservative 411 // behavior. 412 if (BottomUpPathCount < Other.BottomUpPathCount) { 413 BottomUpPathCount = OverflowOccurredValue; 414 clearBottomUpPointers(); 415 return; 416 } 417 418 // For each entry in the other set, if our set has an entry with the 419 // same key, merge the entries. Otherwise, copy the entry and merge 420 // it with an empty entry. 421 for (auto MI = Other.bottom_up_ptr_begin(), ME = Other.bottom_up_ptr_end(); 422 MI != ME; ++MI) { 423 auto Pair = PerPtrBottomUp.insert(*MI); 424 Pair.first->second.Merge(Pair.second ? BottomUpPtrState() : MI->second, 425 /*TopDown=*/false); 426 } 427 428 // For each entry in our set, if the other set doesn't have an entry 429 // with the same key, force it to merge with an empty entry. 430 for (auto MI = bottom_up_ptr_begin(), ME = bottom_up_ptr_end(); MI != ME; 431 ++MI) 432 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end()) 433 MI->second.Merge(BottomUpPtrState(), /*TopDown=*/false); 434 } 435 436 raw_ostream &llvm::operator<<(raw_ostream &OS, BBState &BBInfo) { 437 // Dump the pointers we are tracking. 438 OS << " TopDown State:\n"; 439 if (!BBInfo.hasTopDownPtrs()) { 440 LLVM_DEBUG(dbgs() << " NONE!\n"); 441 } else { 442 for (auto I = BBInfo.top_down_ptr_begin(), E = BBInfo.top_down_ptr_end(); 443 I != E; ++I) { 444 const PtrState &P = I->second; 445 OS << " Ptr: " << *I->first 446 << "\n KnownSafe: " << (P.IsKnownSafe()?"true":"false") 447 << "\n ImpreciseRelease: " 448 << (P.IsTrackingImpreciseReleases()?"true":"false") << "\n" 449 << " HasCFGHazards: " 450 << (P.IsCFGHazardAfflicted()?"true":"false") << "\n" 451 << " KnownPositive: " 452 << (P.HasKnownPositiveRefCount()?"true":"false") << "\n" 453 << " Seq: " 454 << P.GetSeq() << "\n"; 455 } 456 } 457 458 OS << " BottomUp State:\n"; 459 if (!BBInfo.hasBottomUpPtrs()) { 460 LLVM_DEBUG(dbgs() << " NONE!\n"); 461 } else { 462 for (auto I = BBInfo.bottom_up_ptr_begin(), E = BBInfo.bottom_up_ptr_end(); 463 I != E; ++I) { 464 const PtrState &P = I->second; 465 OS << " Ptr: " << *I->first 466 << "\n KnownSafe: " << (P.IsKnownSafe()?"true":"false") 467 << "\n ImpreciseRelease: " 468 << (P.IsTrackingImpreciseReleases()?"true":"false") << "\n" 469 << " HasCFGHazards: " 470 << (P.IsCFGHazardAfflicted()?"true":"false") << "\n" 471 << " KnownPositive: " 472 << (P.HasKnownPositiveRefCount()?"true":"false") << "\n" 473 << " Seq: " 474 << P.GetSeq() << "\n"; 475 } 476 } 477 478 return OS; 479 } 480 481 namespace { 482 483 /// The main ARC optimization pass. 484 class ObjCARCOpt : public FunctionPass { 485 bool Changed; 486 ProvenanceAnalysis PA; 487 488 /// A cache of references to runtime entry point constants. 489 ARCRuntimeEntryPoints EP; 490 491 /// A cache of MDKinds that can be passed into other functions to propagate 492 /// MDKind identifiers. 493 ARCMDKindCache MDKindCache; 494 495 /// A flag indicating whether this optimization pass should run. 496 bool Run; 497 498 /// A flag indicating whether the optimization that removes or moves 499 /// retain/release pairs should be performed. 500 bool DisableRetainReleasePairing = false; 501 502 /// Flags which determine whether each of the interesting runtime functions 503 /// is in fact used in the current function. 504 unsigned UsedInThisFunction; 505 506 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV); 507 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV, 508 ARCInstKind &Class); 509 void OptimizeIndividualCalls(Function &F); 510 511 /// Optimize an individual call, optionally passing the 512 /// GetArgRCIdentityRoot if it has already been computed. 513 void OptimizeIndividualCallImpl( 514 Function &F, DenseMap<BasicBlock *, ColorVector> &BlockColors, 515 Instruction *Inst, ARCInstKind Class, const Value *Arg); 516 517 /// Try to optimize an AutoreleaseRV with a RetainRV or ClaimRV. If the 518 /// optimization occurs, returns true to indicate that the caller should 519 /// assume the instructions are dead. 520 bool OptimizeInlinedAutoreleaseRVCall( 521 Function &F, DenseMap<BasicBlock *, ColorVector> &BlockColors, 522 Instruction *Inst, const Value *&Arg, ARCInstKind Class, 523 Instruction *AutoreleaseRV, const Value *&AutoreleaseRVArg); 524 525 void CheckForCFGHazards(const BasicBlock *BB, 526 DenseMap<const BasicBlock *, BBState> &BBStates, 527 BBState &MyStates) const; 528 bool VisitInstructionBottomUp(Instruction *Inst, BasicBlock *BB, 529 BlotMapVector<Value *, RRInfo> &Retains, 530 BBState &MyStates); 531 bool VisitBottomUp(BasicBlock *BB, 532 DenseMap<const BasicBlock *, BBState> &BBStates, 533 BlotMapVector<Value *, RRInfo> &Retains); 534 bool VisitInstructionTopDown(Instruction *Inst, 535 DenseMap<Value *, RRInfo> &Releases, 536 BBState &MyStates); 537 bool VisitTopDown(BasicBlock *BB, 538 DenseMap<const BasicBlock *, BBState> &BBStates, 539 DenseMap<Value *, RRInfo> &Releases); 540 bool Visit(Function &F, DenseMap<const BasicBlock *, BBState> &BBStates, 541 BlotMapVector<Value *, RRInfo> &Retains, 542 DenseMap<Value *, RRInfo> &Releases); 543 544 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove, 545 BlotMapVector<Value *, RRInfo> &Retains, 546 DenseMap<Value *, RRInfo> &Releases, 547 SmallVectorImpl<Instruction *> &DeadInsts, Module *M); 548 549 bool 550 PairUpRetainsAndReleases(DenseMap<const BasicBlock *, BBState> &BBStates, 551 BlotMapVector<Value *, RRInfo> &Retains, 552 DenseMap<Value *, RRInfo> &Releases, Module *M, 553 Instruction * Retain, 554 SmallVectorImpl<Instruction *> &DeadInsts, 555 RRInfo &RetainsToMove, RRInfo &ReleasesToMove, 556 Value *Arg, bool KnownSafe, 557 bool &AnyPairsCompletelyEliminated); 558 559 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates, 560 BlotMapVector<Value *, RRInfo> &Retains, 561 DenseMap<Value *, RRInfo> &Releases, Module *M); 562 563 void OptimizeWeakCalls(Function &F); 564 565 bool OptimizeSequences(Function &F); 566 567 void OptimizeReturns(Function &F); 568 569 #ifndef NDEBUG 570 void GatherStatistics(Function &F, bool AfterOptimization = false); 571 #endif 572 573 void getAnalysisUsage(AnalysisUsage &AU) const override; 574 bool doInitialization(Module &M) override; 575 bool runOnFunction(Function &F) override; 576 void releaseMemory() override; 577 578 public: 579 static char ID; 580 581 ObjCARCOpt() : FunctionPass(ID) { 582 initializeObjCARCOptPass(*PassRegistry::getPassRegistry()); 583 } 584 }; 585 586 } // end anonymous namespace 587 588 char ObjCARCOpt::ID = 0; 589 590 INITIALIZE_PASS_BEGIN(ObjCARCOpt, 591 "objc-arc", "ObjC ARC optimization", false, false) 592 INITIALIZE_PASS_DEPENDENCY(ObjCARCAAWrapperPass) 593 INITIALIZE_PASS_END(ObjCARCOpt, 594 "objc-arc", "ObjC ARC optimization", false, false) 595 596 Pass *llvm::createObjCARCOptPass() { 597 return new ObjCARCOpt(); 598 } 599 600 void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const { 601 AU.addRequired<ObjCARCAAWrapperPass>(); 602 AU.addRequired<AAResultsWrapperPass>(); 603 // ARC optimization doesn't currently split critical edges. 604 AU.setPreservesCFG(); 605 } 606 607 /// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is 608 /// not a return value. 609 bool 610 ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) { 611 // Check for the argument being from an immediately preceding call or invoke. 612 const Value *Arg = GetArgRCIdentityRoot(RetainRV); 613 ImmutableCallSite CS(Arg); 614 if (const Instruction *Call = CS.getInstruction()) { 615 if (Call->getParent() == RetainRV->getParent()) { 616 BasicBlock::const_iterator I(Call); 617 ++I; 618 while (IsNoopInstruction(&*I)) 619 ++I; 620 if (&*I == RetainRV) 621 return false; 622 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) { 623 BasicBlock *RetainRVParent = RetainRV->getParent(); 624 if (II->getNormalDest() == RetainRVParent) { 625 BasicBlock::const_iterator I = RetainRVParent->begin(); 626 while (IsNoopInstruction(&*I)) 627 ++I; 628 if (&*I == RetainRV) 629 return false; 630 } 631 } 632 } 633 634 // Turn it to a plain objc_retain. 635 Changed = true; 636 ++NumPeeps; 637 638 LLVM_DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => " 639 "objc_retain since the operand is not a return value.\n" 640 "Old = " 641 << *RetainRV << "\n"); 642 643 Function *NewDecl = EP.get(ARCRuntimeEntryPointKind::Retain); 644 cast<CallInst>(RetainRV)->setCalledFunction(NewDecl); 645 646 LLVM_DEBUG(dbgs() << "New = " << *RetainRV << "\n"); 647 648 return false; 649 } 650 651 bool ObjCARCOpt::OptimizeInlinedAutoreleaseRVCall( 652 Function &F, DenseMap<BasicBlock *, ColorVector> &BlockColors, 653 Instruction *Inst, const Value *&Arg, ARCInstKind Class, 654 Instruction *AutoreleaseRV, const Value *&AutoreleaseRVArg) { 655 // Must be in the same basic block. 656 assert(Inst->getParent() == AutoreleaseRV->getParent()); 657 658 // Must operate on the same root. 659 Arg = GetArgRCIdentityRoot(Inst); 660 AutoreleaseRVArg = GetArgRCIdentityRoot(AutoreleaseRV); 661 if (Arg != AutoreleaseRVArg) { 662 // If there isn't an exact match, check if we have equivalent PHIs. 663 const PHINode *PN = dyn_cast<PHINode>(Arg); 664 if (!PN) 665 return false; 666 667 SmallVector<const Value *, 4> ArgUsers; 668 getEquivalentPHIs(*PN, ArgUsers); 669 if (llvm::find(ArgUsers, AutoreleaseRVArg) == ArgUsers.end()) 670 return false; 671 } 672 673 // Okay, this is a match. Merge them. 674 ++NumPeeps; 675 LLVM_DEBUG(dbgs() << "Found inlined objc_autoreleaseReturnValue '" 676 << *AutoreleaseRV << "' paired with '" << *Inst << "'\n"); 677 678 // Delete the RV pair, starting with the AutoreleaseRV. 679 AutoreleaseRV->replaceAllUsesWith( 680 cast<CallInst>(AutoreleaseRV)->getArgOperand(0)); 681 EraseInstruction(AutoreleaseRV); 682 if (Class == ARCInstKind::RetainRV) { 683 // AutoreleaseRV and RetainRV cancel out. Delete the RetainRV. 684 Inst->replaceAllUsesWith(cast<CallInst>(Inst)->getArgOperand(0)); 685 EraseInstruction(Inst); 686 return true; 687 } 688 689 // ClaimRV is a frontend peephole for RetainRV + Release. Since the 690 // AutoreleaseRV and RetainRV cancel out, replace the ClaimRV with a Release. 691 assert(Class == ARCInstKind::ClaimRV); 692 Value *CallArg = cast<CallInst>(Inst)->getArgOperand(0); 693 CallInst *Release = CallInst::Create( 694 EP.get(ARCRuntimeEntryPointKind::Release), CallArg, "", Inst); 695 assert(IsAlwaysTail(ARCInstKind::ClaimRV) && 696 "Expected ClaimRV to be safe to tail call"); 697 Release->setTailCall(); 698 Inst->replaceAllUsesWith(CallArg); 699 EraseInstruction(Inst); 700 701 // Run the normal optimizations on Release. 702 OptimizeIndividualCallImpl(F, BlockColors, Release, ARCInstKind::Release, 703 Arg); 704 return true; 705 } 706 707 /// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not 708 /// used as a return value. 709 void ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, 710 Instruction *AutoreleaseRV, 711 ARCInstKind &Class) { 712 // Check for a return of the pointer value. 713 const Value *Ptr = GetArgRCIdentityRoot(AutoreleaseRV); 714 715 // If the argument is ConstantPointerNull or UndefValue, its other users 716 // aren't actually interesting to look at. 717 if (isa<ConstantData>(Ptr)) 718 return; 719 720 SmallVector<const Value *, 2> Users; 721 Users.push_back(Ptr); 722 723 // Add PHIs that are equivalent to Ptr to Users. 724 if (const PHINode *PN = dyn_cast<PHINode>(Ptr)) 725 getEquivalentPHIs(*PN, Users); 726 727 do { 728 Ptr = Users.pop_back_val(); 729 for (const User *U : Ptr->users()) { 730 if (isa<ReturnInst>(U) || GetBasicARCInstKind(U) == ARCInstKind::RetainRV) 731 return; 732 if (isa<BitCastInst>(U)) 733 Users.push_back(U); 734 } 735 } while (!Users.empty()); 736 737 Changed = true; 738 ++NumPeeps; 739 740 LLVM_DEBUG( 741 dbgs() << "Transforming objc_autoreleaseReturnValue => " 742 "objc_autorelease since its operand is not used as a return " 743 "value.\n" 744 "Old = " 745 << *AutoreleaseRV << "\n"); 746 747 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV); 748 Function *NewDecl = EP.get(ARCRuntimeEntryPointKind::Autorelease); 749 AutoreleaseRVCI->setCalledFunction(NewDecl); 750 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease. 751 Class = ARCInstKind::Autorelease; 752 753 LLVM_DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n"); 754 } 755 756 namespace { 757 Instruction * 758 CloneCallInstForBB(CallInst &CI, BasicBlock &BB, 759 const DenseMap<BasicBlock *, ColorVector> &BlockColors) { 760 SmallVector<OperandBundleDef, 1> OpBundles; 761 for (unsigned I = 0, E = CI.getNumOperandBundles(); I != E; ++I) { 762 auto Bundle = CI.getOperandBundleAt(I); 763 // Funclets will be reassociated in the future. 764 if (Bundle.getTagID() == LLVMContext::OB_funclet) 765 continue; 766 OpBundles.emplace_back(Bundle); 767 } 768 769 if (!BlockColors.empty()) { 770 const ColorVector &CV = BlockColors.find(&BB)->second; 771 assert(CV.size() == 1 && "non-unique color for block!"); 772 Instruction *EHPad = CV.front()->getFirstNonPHI(); 773 if (EHPad->isEHPad()) 774 OpBundles.emplace_back("funclet", EHPad); 775 } 776 777 return CallInst::Create(&CI, OpBundles); 778 } 779 } 780 781 /// Visit each call, one at a time, and make simplifications without doing any 782 /// additional analysis. 783 void ObjCARCOpt::OptimizeIndividualCalls(Function &F) { 784 LLVM_DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n"); 785 // Reset all the flags in preparation for recomputing them. 786 UsedInThisFunction = 0; 787 788 DenseMap<BasicBlock *, ColorVector> BlockColors; 789 if (F.hasPersonalityFn() && 790 isScopedEHPersonality(classifyEHPersonality(F.getPersonalityFn()))) 791 BlockColors = colorEHFunclets(F); 792 793 // Store any delayed AutoreleaseRV intrinsics, so they can be easily paired 794 // with RetainRV and ClaimRV. 795 Instruction *DelayedAutoreleaseRV = nullptr; 796 const Value *DelayedAutoreleaseRVArg = nullptr; 797 auto setDelayedAutoreleaseRV = [&](Instruction *AutoreleaseRV) { 798 assert(!DelayedAutoreleaseRV || !AutoreleaseRV); 799 DelayedAutoreleaseRV = AutoreleaseRV; 800 DelayedAutoreleaseRVArg = nullptr; 801 }; 802 auto optimizeDelayedAutoreleaseRV = [&]() { 803 if (!DelayedAutoreleaseRV) 804 return; 805 OptimizeIndividualCallImpl(F, BlockColors, DelayedAutoreleaseRV, 806 ARCInstKind::AutoreleaseRV, 807 DelayedAutoreleaseRVArg); 808 setDelayedAutoreleaseRV(nullptr); 809 }; 810 auto shouldDelayAutoreleaseRV = [&](Instruction *NonARCInst) { 811 // Nothing to delay, but we may as well skip the logic below. 812 if (!DelayedAutoreleaseRV) 813 return true; 814 815 // If we hit the end of the basic block we're not going to find an RV-pair. 816 // Stop delaying. 817 if (NonARCInst->isTerminator()) 818 return false; 819 820 // Given the frontend rules for emitting AutoreleaseRV, RetainRV, and 821 // ClaimRV, it's probably safe to skip over even opaque function calls 822 // here since OptimizeInlinedAutoreleaseRVCall will confirm that they 823 // have the same RCIdentityRoot. However, what really matters is 824 // skipping instructions or intrinsics that the inliner could leave behind; 825 // be conservative for now and don't skip over opaque calls, which could 826 // potentially include other ARC calls. 827 auto *CB = dyn_cast<CallBase>(NonARCInst); 828 if (!CB) 829 return true; 830 return CB->getIntrinsicID() != Intrinsic::not_intrinsic; 831 }; 832 833 // Visit all objc_* calls in F. 834 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) { 835 Instruction *Inst = &*I++; 836 837 ARCInstKind Class = GetBasicARCInstKind(Inst); 838 839 // Skip this loop if this instruction isn't itself an ARC intrinsic. 840 const Value *Arg = nullptr; 841 switch (Class) { 842 default: 843 optimizeDelayedAutoreleaseRV(); 844 break; 845 case ARCInstKind::CallOrUser: 846 case ARCInstKind::User: 847 case ARCInstKind::None: 848 // This is a non-ARC instruction. If we're delaying an AutoreleaseRV, 849 // check if it's safe to skip over it; if not, optimize the AutoreleaseRV 850 // now. 851 if (!shouldDelayAutoreleaseRV(Inst)) 852 optimizeDelayedAutoreleaseRV(); 853 continue; 854 case ARCInstKind::AutoreleaseRV: 855 optimizeDelayedAutoreleaseRV(); 856 setDelayedAutoreleaseRV(Inst); 857 continue; 858 case ARCInstKind::RetainRV: 859 case ARCInstKind::ClaimRV: 860 if (DelayedAutoreleaseRV) { 861 // We have a potential RV pair. Check if they cancel out. 862 if (OptimizeInlinedAutoreleaseRVCall(F, BlockColors, Inst, Arg, Class, 863 DelayedAutoreleaseRV, 864 DelayedAutoreleaseRVArg)) { 865 setDelayedAutoreleaseRV(nullptr); 866 continue; 867 } 868 optimizeDelayedAutoreleaseRV(); 869 } 870 break; 871 } 872 873 OptimizeIndividualCallImpl(F, BlockColors, Inst, Class, Arg); 874 } 875 876 // Catch the final delayed AutoreleaseRV. 877 optimizeDelayedAutoreleaseRV(); 878 } 879 880 /// This function returns true if the value is inert. An ObjC ARC runtime call 881 /// taking an inert operand can be safely deleted. 882 static bool isInertARCValue(Value *V, SmallPtrSet<Value *, 1> &VisitedPhis) { 883 V = V->stripPointerCasts(); 884 885 if (IsNullOrUndef(V)) 886 return true; 887 888 // See if this is a global attribute annotated with an 'objc_arc_inert'. 889 if (auto *GV = dyn_cast<GlobalVariable>(V)) 890 if (GV->hasAttribute("objc_arc_inert")) 891 return true; 892 893 if (auto PN = dyn_cast<PHINode>(V)) { 894 // Ignore this phi if it has already been discovered. 895 if (!VisitedPhis.insert(PN).second) 896 return true; 897 // Look through phis's operands. 898 for (Value *Opnd : PN->incoming_values()) 899 if (!isInertARCValue(Opnd, VisitedPhis)) 900 return false; 901 return true; 902 } 903 904 return false; 905 } 906 907 void ObjCARCOpt::OptimizeIndividualCallImpl( 908 Function &F, DenseMap<BasicBlock *, ColorVector> &BlockColors, 909 Instruction *Inst, ARCInstKind Class, const Value *Arg) { 910 LLVM_DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n"); 911 912 // We can delete this call if it takes an inert value. 913 SmallPtrSet<Value *, 1> VisitedPhis; 914 915 if (IsNoopOnGlobal(Class)) 916 if (isInertARCValue(Inst->getOperand(0), VisitedPhis)) { 917 if (!Inst->getType()->isVoidTy()) 918 Inst->replaceAllUsesWith(Inst->getOperand(0)); 919 Inst->eraseFromParent(); 920 return; 921 } 922 923 switch (Class) { 924 default: 925 break; 926 927 // Delete no-op casts. These function calls have special semantics, but 928 // the semantics are entirely implemented via lowering in the front-end, 929 // so by the time they reach the optimizer, they are just no-op calls 930 // which return their argument. 931 // 932 // There are gray areas here, as the ability to cast reference-counted 933 // pointers to raw void* and back allows code to break ARC assumptions, 934 // however these are currently considered to be unimportant. 935 case ARCInstKind::NoopCast: 936 Changed = true; 937 ++NumNoops; 938 LLVM_DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n"); 939 EraseInstruction(Inst); 940 return; 941 942 // If the pointer-to-weak-pointer is null, it's undefined behavior. 943 case ARCInstKind::StoreWeak: 944 case ARCInstKind::LoadWeak: 945 case ARCInstKind::LoadWeakRetained: 946 case ARCInstKind::InitWeak: 947 case ARCInstKind::DestroyWeak: { 948 CallInst *CI = cast<CallInst>(Inst); 949 if (IsNullOrUndef(CI->getArgOperand(0))) { 950 Changed = true; 951 Type *Ty = CI->getArgOperand(0)->getType(); 952 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()), 953 Constant::getNullValue(Ty), CI); 954 Value *NewValue = UndefValue::get(CI->getType()); 955 LLVM_DEBUG( 956 dbgs() << "A null pointer-to-weak-pointer is undefined behavior." 957 "\nOld = " 958 << *CI << "\nNew = " << *NewValue << "\n"); 959 CI->replaceAllUsesWith(NewValue); 960 CI->eraseFromParent(); 961 return; 962 } 963 break; 964 } 965 case ARCInstKind::CopyWeak: 966 case ARCInstKind::MoveWeak: { 967 CallInst *CI = cast<CallInst>(Inst); 968 if (IsNullOrUndef(CI->getArgOperand(0)) || 969 IsNullOrUndef(CI->getArgOperand(1))) { 970 Changed = true; 971 Type *Ty = CI->getArgOperand(0)->getType(); 972 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()), 973 Constant::getNullValue(Ty), CI); 974 975 Value *NewValue = UndefValue::get(CI->getType()); 976 LLVM_DEBUG( 977 dbgs() << "A null pointer-to-weak-pointer is undefined behavior." 978 "\nOld = " 979 << *CI << "\nNew = " << *NewValue << "\n"); 980 981 CI->replaceAllUsesWith(NewValue); 982 CI->eraseFromParent(); 983 return; 984 } 985 break; 986 } 987 case ARCInstKind::RetainRV: 988 if (OptimizeRetainRVCall(F, Inst)) 989 return; 990 break; 991 case ARCInstKind::AutoreleaseRV: 992 OptimizeAutoreleaseRVCall(F, Inst, Class); 993 break; 994 } 995 996 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused. 997 if (IsAutorelease(Class) && Inst->use_empty()) { 998 CallInst *Call = cast<CallInst>(Inst); 999 const Value *Arg = Call->getArgOperand(0); 1000 Arg = FindSingleUseIdentifiedObject(Arg); 1001 if (Arg) { 1002 Changed = true; 1003 ++NumAutoreleases; 1004 1005 // Create the declaration lazily. 1006 LLVMContext &C = Inst->getContext(); 1007 1008 Function *Decl = EP.get(ARCRuntimeEntryPointKind::Release); 1009 CallInst *NewCall = 1010 CallInst::Create(Decl, Call->getArgOperand(0), "", Call); 1011 NewCall->setMetadata(MDKindCache.get(ARCMDKindID::ImpreciseRelease), 1012 MDNode::get(C, None)); 1013 1014 LLVM_DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) " 1015 "since x is otherwise unused.\nOld: " 1016 << *Call << "\nNew: " << *NewCall << "\n"); 1017 1018 EraseInstruction(Call); 1019 Inst = NewCall; 1020 Class = ARCInstKind::Release; 1021 } 1022 } 1023 1024 // For functions which can never be passed stack arguments, add 1025 // a tail keyword. 1026 if (IsAlwaysTail(Class) && !cast<CallInst>(Inst)->isNoTailCall()) { 1027 Changed = true; 1028 LLVM_DEBUG( 1029 dbgs() << "Adding tail keyword to function since it can never be " 1030 "passed stack args: " 1031 << *Inst << "\n"); 1032 cast<CallInst>(Inst)->setTailCall(); 1033 } 1034 1035 // Ensure that functions that can never have a "tail" keyword due to the 1036 // semantics of ARC truly do not do so. 1037 if (IsNeverTail(Class)) { 1038 Changed = true; 1039 LLVM_DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst 1040 << "\n"); 1041 cast<CallInst>(Inst)->setTailCall(false); 1042 } 1043 1044 // Set nounwind as needed. 1045 if (IsNoThrow(Class)) { 1046 Changed = true; 1047 LLVM_DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst 1048 << "\n"); 1049 cast<CallInst>(Inst)->setDoesNotThrow(); 1050 } 1051 1052 // Note: This catches instructions unrelated to ARC. 1053 if (!IsNoopOnNull(Class)) { 1054 UsedInThisFunction |= 1 << unsigned(Class); 1055 return; 1056 } 1057 1058 // If we haven't already looked up the root, look it up now. 1059 if (!Arg) 1060 Arg = GetArgRCIdentityRoot(Inst); 1061 1062 // ARC calls with null are no-ops. Delete them. 1063 if (IsNullOrUndef(Arg)) { 1064 Changed = true; 1065 ++NumNoops; 1066 LLVM_DEBUG(dbgs() << "ARC calls with null are no-ops. Erasing: " << *Inst 1067 << "\n"); 1068 EraseInstruction(Inst); 1069 return; 1070 } 1071 1072 // Keep track of which of retain, release, autorelease, and retain_block 1073 // are actually present in this function. 1074 UsedInThisFunction |= 1 << unsigned(Class); 1075 1076 // If Arg is a PHI, and one or more incoming values to the 1077 // PHI are null, and the call is control-equivalent to the PHI, and there 1078 // are no relevant side effects between the PHI and the call, and the call 1079 // is not a release that doesn't have the clang.imprecise_release tag, the 1080 // call could be pushed up to just those paths with non-null incoming 1081 // values. For now, don't bother splitting critical edges for this. 1082 if (Class == ARCInstKind::Release && 1083 !Inst->getMetadata(MDKindCache.get(ARCMDKindID::ImpreciseRelease))) 1084 return; 1085 1086 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist; 1087 Worklist.push_back(std::make_pair(Inst, Arg)); 1088 do { 1089 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val(); 1090 Inst = Pair.first; 1091 Arg = Pair.second; 1092 1093 const PHINode *PN = dyn_cast<PHINode>(Arg); 1094 if (!PN) 1095 continue; 1096 1097 // Determine if the PHI has any null operands, or any incoming 1098 // critical edges. 1099 bool HasNull = false; 1100 bool HasCriticalEdges = false; 1101 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 1102 Value *Incoming = GetRCIdentityRoot(PN->getIncomingValue(i)); 1103 if (IsNullOrUndef(Incoming)) 1104 HasNull = true; 1105 else if (PN->getIncomingBlock(i)->getTerminator()->getNumSuccessors() != 1106 1) { 1107 HasCriticalEdges = true; 1108 break; 1109 } 1110 } 1111 // If we have null operands and no critical edges, optimize. 1112 if (HasCriticalEdges) 1113 continue; 1114 if (!HasNull) 1115 continue; 1116 1117 SmallPtrSet<Instruction *, 4> DependingInstructions; 1118 SmallPtrSet<const BasicBlock *, 4> Visited; 1119 1120 // Check that there is nothing that cares about the reference 1121 // count between the call and the phi. 1122 switch (Class) { 1123 case ARCInstKind::Retain: 1124 case ARCInstKind::RetainBlock: 1125 // These can always be moved up. 1126 break; 1127 case ARCInstKind::Release: 1128 // These can't be moved across things that care about the retain 1129 // count. 1130 FindDependencies(NeedsPositiveRetainCount, Arg, Inst->getParent(), Inst, 1131 DependingInstructions, Visited, PA); 1132 break; 1133 case ARCInstKind::Autorelease: 1134 // These can't be moved across autorelease pool scope boundaries. 1135 FindDependencies(AutoreleasePoolBoundary, Arg, Inst->getParent(), Inst, 1136 DependingInstructions, Visited, PA); 1137 break; 1138 case ARCInstKind::ClaimRV: 1139 case ARCInstKind::RetainRV: 1140 case ARCInstKind::AutoreleaseRV: 1141 // Don't move these; the RV optimization depends on the autoreleaseRV 1142 // being tail called, and the retainRV being immediately after a call 1143 // (which might still happen if we get lucky with codegen layout, but 1144 // it's not worth taking the chance). 1145 continue; 1146 default: 1147 llvm_unreachable("Invalid dependence flavor"); 1148 } 1149 1150 if (DependingInstructions.size() != 1) 1151 continue; 1152 if (*DependingInstructions.begin() != PN) 1153 continue; 1154 1155 Changed = true; 1156 ++NumPartialNoops; 1157 // Clone the call into each predecessor that has a non-null value. 1158 CallInst *CInst = cast<CallInst>(Inst); 1159 Type *ParamTy = CInst->getArgOperand(0)->getType(); 1160 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 1161 Value *Incoming = GetRCIdentityRoot(PN->getIncomingValue(i)); 1162 if (IsNullOrUndef(Incoming)) 1163 continue; 1164 Value *Op = PN->getIncomingValue(i); 1165 Instruction *InsertPos = &PN->getIncomingBlock(i)->back(); 1166 CallInst *Clone = cast<CallInst>( 1167 CloneCallInstForBB(*CInst, *InsertPos->getParent(), BlockColors)); 1168 if (Op->getType() != ParamTy) 1169 Op = new BitCastInst(Op, ParamTy, "", InsertPos); 1170 Clone->setArgOperand(0, Op); 1171 Clone->insertBefore(InsertPos); 1172 1173 LLVM_DEBUG(dbgs() << "Cloning " << *CInst << "\n" 1174 "And inserting clone at " 1175 << *InsertPos << "\n"); 1176 Worklist.push_back(std::make_pair(Clone, Incoming)); 1177 } 1178 // Erase the original call. 1179 LLVM_DEBUG(dbgs() << "Erasing: " << *CInst << "\n"); 1180 EraseInstruction(CInst); 1181 } while (!Worklist.empty()); 1182 } 1183 1184 /// If we have a top down pointer in the S_Use state, make sure that there are 1185 /// no CFG hazards by checking the states of various bottom up pointers. 1186 static void CheckForUseCFGHazard(const Sequence SuccSSeq, 1187 const bool SuccSRRIKnownSafe, 1188 TopDownPtrState &S, 1189 bool &SomeSuccHasSame, 1190 bool &AllSuccsHaveSame, 1191 bool &NotAllSeqEqualButKnownSafe, 1192 bool &ShouldContinue) { 1193 switch (SuccSSeq) { 1194 case S_CanRelease: { 1195 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe) { 1196 S.ClearSequenceProgress(); 1197 break; 1198 } 1199 S.SetCFGHazardAfflicted(true); 1200 ShouldContinue = true; 1201 break; 1202 } 1203 case S_Use: 1204 SomeSuccHasSame = true; 1205 break; 1206 case S_Stop: 1207 case S_Release: 1208 case S_MovableRelease: 1209 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe) 1210 AllSuccsHaveSame = false; 1211 else 1212 NotAllSeqEqualButKnownSafe = true; 1213 break; 1214 case S_Retain: 1215 llvm_unreachable("bottom-up pointer in retain state!"); 1216 case S_None: 1217 llvm_unreachable("This should have been handled earlier."); 1218 } 1219 } 1220 1221 /// If we have a Top Down pointer in the S_CanRelease state, make sure that 1222 /// there are no CFG hazards by checking the states of various bottom up 1223 /// pointers. 1224 static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq, 1225 const bool SuccSRRIKnownSafe, 1226 TopDownPtrState &S, 1227 bool &SomeSuccHasSame, 1228 bool &AllSuccsHaveSame, 1229 bool &NotAllSeqEqualButKnownSafe) { 1230 switch (SuccSSeq) { 1231 case S_CanRelease: 1232 SomeSuccHasSame = true; 1233 break; 1234 case S_Stop: 1235 case S_Release: 1236 case S_MovableRelease: 1237 case S_Use: 1238 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe) 1239 AllSuccsHaveSame = false; 1240 else 1241 NotAllSeqEqualButKnownSafe = true; 1242 break; 1243 case S_Retain: 1244 llvm_unreachable("bottom-up pointer in retain state!"); 1245 case S_None: 1246 llvm_unreachable("This should have been handled earlier."); 1247 } 1248 } 1249 1250 /// Check for critical edges, loop boundaries, irreducible control flow, or 1251 /// other CFG structures where moving code across the edge would result in it 1252 /// being executed more. 1253 void 1254 ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB, 1255 DenseMap<const BasicBlock *, BBState> &BBStates, 1256 BBState &MyStates) const { 1257 // If any top-down local-use or possible-dec has a succ which is earlier in 1258 // the sequence, forget it. 1259 for (auto I = MyStates.top_down_ptr_begin(), E = MyStates.top_down_ptr_end(); 1260 I != E; ++I) { 1261 TopDownPtrState &S = I->second; 1262 const Sequence Seq = I->second.GetSeq(); 1263 1264 // We only care about S_Retain, S_CanRelease, and S_Use. 1265 if (Seq == S_None) 1266 continue; 1267 1268 // Make sure that if extra top down states are added in the future that this 1269 // code is updated to handle it. 1270 assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) && 1271 "Unknown top down sequence state."); 1272 1273 const Value *Arg = I->first; 1274 bool SomeSuccHasSame = false; 1275 bool AllSuccsHaveSame = true; 1276 bool NotAllSeqEqualButKnownSafe = false; 1277 1278 for (const BasicBlock *Succ : successors(BB)) { 1279 // If VisitBottomUp has pointer information for this successor, take 1280 // what we know about it. 1281 const DenseMap<const BasicBlock *, BBState>::iterator BBI = 1282 BBStates.find(Succ); 1283 assert(BBI != BBStates.end()); 1284 const BottomUpPtrState &SuccS = BBI->second.getPtrBottomUpState(Arg); 1285 const Sequence SuccSSeq = SuccS.GetSeq(); 1286 1287 // If bottom up, the pointer is in an S_None state, clear the sequence 1288 // progress since the sequence in the bottom up state finished 1289 // suggesting a mismatch in between retains/releases. This is true for 1290 // all three cases that we are handling here: S_Retain, S_Use, and 1291 // S_CanRelease. 1292 if (SuccSSeq == S_None) { 1293 S.ClearSequenceProgress(); 1294 continue; 1295 } 1296 1297 // If we have S_Use or S_CanRelease, perform our check for cfg hazard 1298 // checks. 1299 const bool SuccSRRIKnownSafe = SuccS.IsKnownSafe(); 1300 1301 // *NOTE* We do not use Seq from above here since we are allowing for 1302 // S.GetSeq() to change while we are visiting basic blocks. 1303 switch(S.GetSeq()) { 1304 case S_Use: { 1305 bool ShouldContinue = false; 1306 CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S, SomeSuccHasSame, 1307 AllSuccsHaveSame, NotAllSeqEqualButKnownSafe, 1308 ShouldContinue); 1309 if (ShouldContinue) 1310 continue; 1311 break; 1312 } 1313 case S_CanRelease: 1314 CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S, 1315 SomeSuccHasSame, AllSuccsHaveSame, 1316 NotAllSeqEqualButKnownSafe); 1317 break; 1318 case S_Retain: 1319 case S_None: 1320 case S_Stop: 1321 case S_Release: 1322 case S_MovableRelease: 1323 break; 1324 } 1325 } 1326 1327 // If the state at the other end of any of the successor edges 1328 // matches the current state, require all edges to match. This 1329 // guards against loops in the middle of a sequence. 1330 if (SomeSuccHasSame && !AllSuccsHaveSame) { 1331 S.ClearSequenceProgress(); 1332 } else if (NotAllSeqEqualButKnownSafe) { 1333 // If we would have cleared the state foregoing the fact that we are known 1334 // safe, stop code motion. This is because whether or not it is safe to 1335 // remove RR pairs via KnownSafe is an orthogonal concept to whether we 1336 // are allowed to perform code motion. 1337 S.SetCFGHazardAfflicted(true); 1338 } 1339 } 1340 } 1341 1342 bool ObjCARCOpt::VisitInstructionBottomUp( 1343 Instruction *Inst, BasicBlock *BB, BlotMapVector<Value *, RRInfo> &Retains, 1344 BBState &MyStates) { 1345 bool NestingDetected = false; 1346 ARCInstKind Class = GetARCInstKind(Inst); 1347 const Value *Arg = nullptr; 1348 1349 LLVM_DEBUG(dbgs() << " Class: " << Class << "\n"); 1350 1351 switch (Class) { 1352 case ARCInstKind::Release: { 1353 Arg = GetArgRCIdentityRoot(Inst); 1354 1355 BottomUpPtrState &S = MyStates.getPtrBottomUpState(Arg); 1356 NestingDetected |= S.InitBottomUp(MDKindCache, Inst); 1357 break; 1358 } 1359 case ARCInstKind::RetainBlock: 1360 // In OptimizeIndividualCalls, we have strength reduced all optimizable 1361 // objc_retainBlocks to objc_retains. Thus at this point any 1362 // objc_retainBlocks that we see are not optimizable. 1363 break; 1364 case ARCInstKind::Retain: 1365 case ARCInstKind::RetainRV: { 1366 Arg = GetArgRCIdentityRoot(Inst); 1367 BottomUpPtrState &S = MyStates.getPtrBottomUpState(Arg); 1368 if (S.MatchWithRetain()) { 1369 // Don't do retain+release tracking for ARCInstKind::RetainRV, because 1370 // it's better to let it remain as the first instruction after a call. 1371 if (Class != ARCInstKind::RetainRV) { 1372 LLVM_DEBUG(dbgs() << " Matching with: " << *Inst << "\n"); 1373 Retains[Inst] = S.GetRRInfo(); 1374 } 1375 S.ClearSequenceProgress(); 1376 } 1377 // A retain moving bottom up can be a use. 1378 break; 1379 } 1380 case ARCInstKind::AutoreleasepoolPop: 1381 // Conservatively, clear MyStates for all known pointers. 1382 MyStates.clearBottomUpPointers(); 1383 return NestingDetected; 1384 case ARCInstKind::AutoreleasepoolPush: 1385 case ARCInstKind::None: 1386 // These are irrelevant. 1387 return NestingDetected; 1388 default: 1389 break; 1390 } 1391 1392 // Consider any other possible effects of this instruction on each 1393 // pointer being tracked. 1394 for (auto MI = MyStates.bottom_up_ptr_begin(), 1395 ME = MyStates.bottom_up_ptr_end(); 1396 MI != ME; ++MI) { 1397 const Value *Ptr = MI->first; 1398 if (Ptr == Arg) 1399 continue; // Handled above. 1400 BottomUpPtrState &S = MI->second; 1401 1402 if (S.HandlePotentialAlterRefCount(Inst, Ptr, PA, Class)) 1403 continue; 1404 1405 S.HandlePotentialUse(BB, Inst, Ptr, PA, Class); 1406 } 1407 1408 return NestingDetected; 1409 } 1410 1411 bool ObjCARCOpt::VisitBottomUp(BasicBlock *BB, 1412 DenseMap<const BasicBlock *, BBState> &BBStates, 1413 BlotMapVector<Value *, RRInfo> &Retains) { 1414 LLVM_DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n"); 1415 1416 bool NestingDetected = false; 1417 BBState &MyStates = BBStates[BB]; 1418 1419 // Merge the states from each successor to compute the initial state 1420 // for the current block. 1421 BBState::edge_iterator SI(MyStates.succ_begin()), 1422 SE(MyStates.succ_end()); 1423 if (SI != SE) { 1424 const BasicBlock *Succ = *SI; 1425 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ); 1426 assert(I != BBStates.end()); 1427 MyStates.InitFromSucc(I->second); 1428 ++SI; 1429 for (; SI != SE; ++SI) { 1430 Succ = *SI; 1431 I = BBStates.find(Succ); 1432 assert(I != BBStates.end()); 1433 MyStates.MergeSucc(I->second); 1434 } 1435 } 1436 1437 LLVM_DEBUG(dbgs() << "Before:\n" 1438 << BBStates[BB] << "\n" 1439 << "Performing Dataflow:\n"); 1440 1441 // Visit all the instructions, bottom-up. 1442 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) { 1443 Instruction *Inst = &*std::prev(I); 1444 1445 // Invoke instructions are visited as part of their successors (below). 1446 if (isa<InvokeInst>(Inst)) 1447 continue; 1448 1449 LLVM_DEBUG(dbgs() << " Visiting " << *Inst << "\n"); 1450 1451 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates); 1452 1453 // Bail out if the number of pointers being tracked becomes too large so 1454 // that this pass can complete in a reasonable amount of time. 1455 if (MyStates.bottom_up_ptr_list_size() > MaxPtrStates) { 1456 DisableRetainReleasePairing = true; 1457 return false; 1458 } 1459 } 1460 1461 // If there's a predecessor with an invoke, visit the invoke as if it were 1462 // part of this block, since we can't insert code after an invoke in its own 1463 // block, and we don't want to split critical edges. 1464 for (BBState::edge_iterator PI(MyStates.pred_begin()), 1465 PE(MyStates.pred_end()); PI != PE; ++PI) { 1466 BasicBlock *Pred = *PI; 1467 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back())) 1468 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates); 1469 } 1470 1471 LLVM_DEBUG(dbgs() << "\nFinal State:\n" << BBStates[BB] << "\n"); 1472 1473 return NestingDetected; 1474 } 1475 1476 bool 1477 ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst, 1478 DenseMap<Value *, RRInfo> &Releases, 1479 BBState &MyStates) { 1480 bool NestingDetected = false; 1481 ARCInstKind Class = GetARCInstKind(Inst); 1482 const Value *Arg = nullptr; 1483 1484 LLVM_DEBUG(dbgs() << " Class: " << Class << "\n"); 1485 1486 switch (Class) { 1487 case ARCInstKind::RetainBlock: 1488 // In OptimizeIndividualCalls, we have strength reduced all optimizable 1489 // objc_retainBlocks to objc_retains. Thus at this point any 1490 // objc_retainBlocks that we see are not optimizable. We need to break since 1491 // a retain can be a potential use. 1492 break; 1493 case ARCInstKind::Retain: 1494 case ARCInstKind::RetainRV: { 1495 Arg = GetArgRCIdentityRoot(Inst); 1496 TopDownPtrState &S = MyStates.getPtrTopDownState(Arg); 1497 NestingDetected |= S.InitTopDown(Class, Inst); 1498 // A retain can be a potential use; proceed to the generic checking 1499 // code below. 1500 break; 1501 } 1502 case ARCInstKind::Release: { 1503 Arg = GetArgRCIdentityRoot(Inst); 1504 TopDownPtrState &S = MyStates.getPtrTopDownState(Arg); 1505 // Try to form a tentative pair in between this release instruction and the 1506 // top down pointers that we are tracking. 1507 if (S.MatchWithRelease(MDKindCache, Inst)) { 1508 // If we succeed, copy S's RRInfo into the Release -> {Retain Set 1509 // Map}. Then we clear S. 1510 LLVM_DEBUG(dbgs() << " Matching with: " << *Inst << "\n"); 1511 Releases[Inst] = S.GetRRInfo(); 1512 S.ClearSequenceProgress(); 1513 } 1514 break; 1515 } 1516 case ARCInstKind::AutoreleasepoolPop: 1517 // Conservatively, clear MyStates for all known pointers. 1518 MyStates.clearTopDownPointers(); 1519 return false; 1520 case ARCInstKind::AutoreleasepoolPush: 1521 case ARCInstKind::None: 1522 // These can not be uses of 1523 return false; 1524 default: 1525 break; 1526 } 1527 1528 // Consider any other possible effects of this instruction on each 1529 // pointer being tracked. 1530 for (auto MI = MyStates.top_down_ptr_begin(), 1531 ME = MyStates.top_down_ptr_end(); 1532 MI != ME; ++MI) { 1533 const Value *Ptr = MI->first; 1534 if (Ptr == Arg) 1535 continue; // Handled above. 1536 TopDownPtrState &S = MI->second; 1537 if (S.HandlePotentialAlterRefCount(Inst, Ptr, PA, Class)) 1538 continue; 1539 1540 S.HandlePotentialUse(Inst, Ptr, PA, Class); 1541 } 1542 1543 return NestingDetected; 1544 } 1545 1546 bool 1547 ObjCARCOpt::VisitTopDown(BasicBlock *BB, 1548 DenseMap<const BasicBlock *, BBState> &BBStates, 1549 DenseMap<Value *, RRInfo> &Releases) { 1550 LLVM_DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n"); 1551 bool NestingDetected = false; 1552 BBState &MyStates = BBStates[BB]; 1553 1554 // Merge the states from each predecessor to compute the initial state 1555 // for the current block. 1556 BBState::edge_iterator PI(MyStates.pred_begin()), 1557 PE(MyStates.pred_end()); 1558 if (PI != PE) { 1559 const BasicBlock *Pred = *PI; 1560 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred); 1561 assert(I != BBStates.end()); 1562 MyStates.InitFromPred(I->second); 1563 ++PI; 1564 for (; PI != PE; ++PI) { 1565 Pred = *PI; 1566 I = BBStates.find(Pred); 1567 assert(I != BBStates.end()); 1568 MyStates.MergePred(I->second); 1569 } 1570 } 1571 1572 // Check that BB and MyStates have the same number of predecessors. This 1573 // prevents retain calls that live outside a loop from being moved into the 1574 // loop. 1575 if (!BB->hasNPredecessors(MyStates.pred_end() - MyStates.pred_begin())) 1576 for (auto I = MyStates.top_down_ptr_begin(), 1577 E = MyStates.top_down_ptr_end(); 1578 I != E; ++I) 1579 I->second.SetCFGHazardAfflicted(true); 1580 1581 LLVM_DEBUG(dbgs() << "Before:\n" 1582 << BBStates[BB] << "\n" 1583 << "Performing Dataflow:\n"); 1584 1585 // Visit all the instructions, top-down. 1586 for (Instruction &Inst : *BB) { 1587 LLVM_DEBUG(dbgs() << " Visiting " << Inst << "\n"); 1588 1589 NestingDetected |= VisitInstructionTopDown(&Inst, Releases, MyStates); 1590 1591 // Bail out if the number of pointers being tracked becomes too large so 1592 // that this pass can complete in a reasonable amount of time. 1593 if (MyStates.top_down_ptr_list_size() > MaxPtrStates) { 1594 DisableRetainReleasePairing = true; 1595 return false; 1596 } 1597 } 1598 1599 LLVM_DEBUG(dbgs() << "\nState Before Checking for CFG Hazards:\n" 1600 << BBStates[BB] << "\n\n"); 1601 CheckForCFGHazards(BB, BBStates, MyStates); 1602 LLVM_DEBUG(dbgs() << "Final State:\n" << BBStates[BB] << "\n"); 1603 return NestingDetected; 1604 } 1605 1606 static void 1607 ComputePostOrders(Function &F, 1608 SmallVectorImpl<BasicBlock *> &PostOrder, 1609 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder, 1610 unsigned NoObjCARCExceptionsMDKind, 1611 DenseMap<const BasicBlock *, BBState> &BBStates) { 1612 /// The visited set, for doing DFS walks. 1613 SmallPtrSet<BasicBlock *, 16> Visited; 1614 1615 // Do DFS, computing the PostOrder. 1616 SmallPtrSet<BasicBlock *, 16> OnStack; 1617 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack; 1618 1619 // Functions always have exactly one entry block, and we don't have 1620 // any other block that we treat like an entry block. 1621 BasicBlock *EntryBB = &F.getEntryBlock(); 1622 BBState &MyStates = BBStates[EntryBB]; 1623 MyStates.SetAsEntry(); 1624 Instruction *EntryTI = EntryBB->getTerminator(); 1625 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI))); 1626 Visited.insert(EntryBB); 1627 OnStack.insert(EntryBB); 1628 do { 1629 dfs_next_succ: 1630 BasicBlock *CurrBB = SuccStack.back().first; 1631 succ_iterator SE(CurrBB->getTerminator(), false); 1632 1633 while (SuccStack.back().second != SE) { 1634 BasicBlock *SuccBB = *SuccStack.back().second++; 1635 if (Visited.insert(SuccBB).second) { 1636 SuccStack.push_back( 1637 std::make_pair(SuccBB, succ_iterator(SuccBB->getTerminator()))); 1638 BBStates[CurrBB].addSucc(SuccBB); 1639 BBState &SuccStates = BBStates[SuccBB]; 1640 SuccStates.addPred(CurrBB); 1641 OnStack.insert(SuccBB); 1642 goto dfs_next_succ; 1643 } 1644 1645 if (!OnStack.count(SuccBB)) { 1646 BBStates[CurrBB].addSucc(SuccBB); 1647 BBStates[SuccBB].addPred(CurrBB); 1648 } 1649 } 1650 OnStack.erase(CurrBB); 1651 PostOrder.push_back(CurrBB); 1652 SuccStack.pop_back(); 1653 } while (!SuccStack.empty()); 1654 1655 Visited.clear(); 1656 1657 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder. 1658 // Functions may have many exits, and there also blocks which we treat 1659 // as exits due to ignored edges. 1660 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack; 1661 for (BasicBlock &ExitBB : F) { 1662 BBState &MyStates = BBStates[&ExitBB]; 1663 if (!MyStates.isExit()) 1664 continue; 1665 1666 MyStates.SetAsExit(); 1667 1668 PredStack.push_back(std::make_pair(&ExitBB, MyStates.pred_begin())); 1669 Visited.insert(&ExitBB); 1670 while (!PredStack.empty()) { 1671 reverse_dfs_next_succ: 1672 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end(); 1673 while (PredStack.back().second != PE) { 1674 BasicBlock *BB = *PredStack.back().second++; 1675 if (Visited.insert(BB).second) { 1676 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin())); 1677 goto reverse_dfs_next_succ; 1678 } 1679 } 1680 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first); 1681 } 1682 } 1683 } 1684 1685 // Visit the function both top-down and bottom-up. 1686 bool ObjCARCOpt::Visit(Function &F, 1687 DenseMap<const BasicBlock *, BBState> &BBStates, 1688 BlotMapVector<Value *, RRInfo> &Retains, 1689 DenseMap<Value *, RRInfo> &Releases) { 1690 // Use reverse-postorder traversals, because we magically know that loops 1691 // will be well behaved, i.e. they won't repeatedly call retain on a single 1692 // pointer without doing a release. We can't use the ReversePostOrderTraversal 1693 // class here because we want the reverse-CFG postorder to consider each 1694 // function exit point, and we want to ignore selected cycle edges. 1695 SmallVector<BasicBlock *, 16> PostOrder; 1696 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder; 1697 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder, 1698 MDKindCache.get(ARCMDKindID::NoObjCARCExceptions), 1699 BBStates); 1700 1701 // Use reverse-postorder on the reverse CFG for bottom-up. 1702 bool BottomUpNestingDetected = false; 1703 for (BasicBlock *BB : llvm::reverse(ReverseCFGPostOrder)) { 1704 BottomUpNestingDetected |= VisitBottomUp(BB, BBStates, Retains); 1705 if (DisableRetainReleasePairing) 1706 return false; 1707 } 1708 1709 // Use reverse-postorder for top-down. 1710 bool TopDownNestingDetected = false; 1711 for (BasicBlock *BB : llvm::reverse(PostOrder)) { 1712 TopDownNestingDetected |= VisitTopDown(BB, BBStates, Releases); 1713 if (DisableRetainReleasePairing) 1714 return false; 1715 } 1716 1717 return TopDownNestingDetected && BottomUpNestingDetected; 1718 } 1719 1720 /// Move the calls in RetainsToMove and ReleasesToMove. 1721 void ObjCARCOpt::MoveCalls(Value *Arg, RRInfo &RetainsToMove, 1722 RRInfo &ReleasesToMove, 1723 BlotMapVector<Value *, RRInfo> &Retains, 1724 DenseMap<Value *, RRInfo> &Releases, 1725 SmallVectorImpl<Instruction *> &DeadInsts, 1726 Module *M) { 1727 Type *ArgTy = Arg->getType(); 1728 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext())); 1729 1730 LLVM_DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n"); 1731 1732 // Insert the new retain and release calls. 1733 for (Instruction *InsertPt : ReleasesToMove.ReverseInsertPts) { 1734 Value *MyArg = ArgTy == ParamTy ? Arg : 1735 new BitCastInst(Arg, ParamTy, "", InsertPt); 1736 Function *Decl = EP.get(ARCRuntimeEntryPointKind::Retain); 1737 CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt); 1738 Call->setDoesNotThrow(); 1739 Call->setTailCall(); 1740 1741 LLVM_DEBUG(dbgs() << "Inserting new Retain: " << *Call 1742 << "\n" 1743 "At insertion point: " 1744 << *InsertPt << "\n"); 1745 } 1746 for (Instruction *InsertPt : RetainsToMove.ReverseInsertPts) { 1747 Value *MyArg = ArgTy == ParamTy ? Arg : 1748 new BitCastInst(Arg, ParamTy, "", InsertPt); 1749 Function *Decl = EP.get(ARCRuntimeEntryPointKind::Release); 1750 CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt); 1751 // Attach a clang.imprecise_release metadata tag, if appropriate. 1752 if (MDNode *M = ReleasesToMove.ReleaseMetadata) 1753 Call->setMetadata(MDKindCache.get(ARCMDKindID::ImpreciseRelease), M); 1754 Call->setDoesNotThrow(); 1755 if (ReleasesToMove.IsTailCallRelease) 1756 Call->setTailCall(); 1757 1758 LLVM_DEBUG(dbgs() << "Inserting new Release: " << *Call 1759 << "\n" 1760 "At insertion point: " 1761 << *InsertPt << "\n"); 1762 } 1763 1764 // Delete the original retain and release calls. 1765 for (Instruction *OrigRetain : RetainsToMove.Calls) { 1766 Retains.blot(OrigRetain); 1767 DeadInsts.push_back(OrigRetain); 1768 LLVM_DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n"); 1769 } 1770 for (Instruction *OrigRelease : ReleasesToMove.Calls) { 1771 Releases.erase(OrigRelease); 1772 DeadInsts.push_back(OrigRelease); 1773 LLVM_DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n"); 1774 } 1775 } 1776 1777 bool ObjCARCOpt::PairUpRetainsAndReleases( 1778 DenseMap<const BasicBlock *, BBState> &BBStates, 1779 BlotMapVector<Value *, RRInfo> &Retains, 1780 DenseMap<Value *, RRInfo> &Releases, Module *M, 1781 Instruction *Retain, 1782 SmallVectorImpl<Instruction *> &DeadInsts, RRInfo &RetainsToMove, 1783 RRInfo &ReleasesToMove, Value *Arg, bool KnownSafe, 1784 bool &AnyPairsCompletelyEliminated) { 1785 // If a pair happens in a region where it is known that the reference count 1786 // is already incremented, we can similarly ignore possible decrements unless 1787 // we are dealing with a retainable object with multiple provenance sources. 1788 bool KnownSafeTD = true, KnownSafeBU = true; 1789 bool CFGHazardAfflicted = false; 1790 1791 // Connect the dots between the top-down-collected RetainsToMove and 1792 // bottom-up-collected ReleasesToMove to form sets of related calls. 1793 // This is an iterative process so that we connect multiple releases 1794 // to multiple retains if needed. 1795 unsigned OldDelta = 0; 1796 unsigned NewDelta = 0; 1797 unsigned OldCount = 0; 1798 unsigned NewCount = 0; 1799 bool FirstRelease = true; 1800 for (SmallVector<Instruction *, 4> NewRetains{Retain};;) { 1801 SmallVector<Instruction *, 4> NewReleases; 1802 for (Instruction *NewRetain : NewRetains) { 1803 auto It = Retains.find(NewRetain); 1804 assert(It != Retains.end()); 1805 const RRInfo &NewRetainRRI = It->second; 1806 KnownSafeTD &= NewRetainRRI.KnownSafe; 1807 CFGHazardAfflicted |= NewRetainRRI.CFGHazardAfflicted; 1808 for (Instruction *NewRetainRelease : NewRetainRRI.Calls) { 1809 auto Jt = Releases.find(NewRetainRelease); 1810 if (Jt == Releases.end()) 1811 return false; 1812 const RRInfo &NewRetainReleaseRRI = Jt->second; 1813 1814 // If the release does not have a reference to the retain as well, 1815 // something happened which is unaccounted for. Do not do anything. 1816 // 1817 // This can happen if we catch an additive overflow during path count 1818 // merging. 1819 if (!NewRetainReleaseRRI.Calls.count(NewRetain)) 1820 return false; 1821 1822 if (ReleasesToMove.Calls.insert(NewRetainRelease).second) { 1823 // If we overflow when we compute the path count, don't remove/move 1824 // anything. 1825 const BBState &NRRBBState = BBStates[NewRetainRelease->getParent()]; 1826 unsigned PathCount = BBState::OverflowOccurredValue; 1827 if (NRRBBState.GetAllPathCountWithOverflow(PathCount)) 1828 return false; 1829 assert(PathCount != BBState::OverflowOccurredValue && 1830 "PathCount at this point can not be " 1831 "OverflowOccurredValue."); 1832 OldDelta -= PathCount; 1833 1834 // Merge the ReleaseMetadata and IsTailCallRelease values. 1835 if (FirstRelease) { 1836 ReleasesToMove.ReleaseMetadata = 1837 NewRetainReleaseRRI.ReleaseMetadata; 1838 ReleasesToMove.IsTailCallRelease = 1839 NewRetainReleaseRRI.IsTailCallRelease; 1840 FirstRelease = false; 1841 } else { 1842 if (ReleasesToMove.ReleaseMetadata != 1843 NewRetainReleaseRRI.ReleaseMetadata) 1844 ReleasesToMove.ReleaseMetadata = nullptr; 1845 if (ReleasesToMove.IsTailCallRelease != 1846 NewRetainReleaseRRI.IsTailCallRelease) 1847 ReleasesToMove.IsTailCallRelease = false; 1848 } 1849 1850 // Collect the optimal insertion points. 1851 if (!KnownSafe) 1852 for (Instruction *RIP : NewRetainReleaseRRI.ReverseInsertPts) { 1853 if (ReleasesToMove.ReverseInsertPts.insert(RIP).second) { 1854 // If we overflow when we compute the path count, don't 1855 // remove/move anything. 1856 const BBState &RIPBBState = BBStates[RIP->getParent()]; 1857 PathCount = BBState::OverflowOccurredValue; 1858 if (RIPBBState.GetAllPathCountWithOverflow(PathCount)) 1859 return false; 1860 assert(PathCount != BBState::OverflowOccurredValue && 1861 "PathCount at this point can not be " 1862 "OverflowOccurredValue."); 1863 NewDelta -= PathCount; 1864 } 1865 } 1866 NewReleases.push_back(NewRetainRelease); 1867 } 1868 } 1869 } 1870 NewRetains.clear(); 1871 if (NewReleases.empty()) break; 1872 1873 // Back the other way. 1874 for (Instruction *NewRelease : NewReleases) { 1875 auto It = Releases.find(NewRelease); 1876 assert(It != Releases.end()); 1877 const RRInfo &NewReleaseRRI = It->second; 1878 KnownSafeBU &= NewReleaseRRI.KnownSafe; 1879 CFGHazardAfflicted |= NewReleaseRRI.CFGHazardAfflicted; 1880 for (Instruction *NewReleaseRetain : NewReleaseRRI.Calls) { 1881 auto Jt = Retains.find(NewReleaseRetain); 1882 if (Jt == Retains.end()) 1883 return false; 1884 const RRInfo &NewReleaseRetainRRI = Jt->second; 1885 1886 // If the retain does not have a reference to the release as well, 1887 // something happened which is unaccounted for. Do not do anything. 1888 // 1889 // This can happen if we catch an additive overflow during path count 1890 // merging. 1891 if (!NewReleaseRetainRRI.Calls.count(NewRelease)) 1892 return false; 1893 1894 if (RetainsToMove.Calls.insert(NewReleaseRetain).second) { 1895 // If we overflow when we compute the path count, don't remove/move 1896 // anything. 1897 const BBState &NRRBBState = BBStates[NewReleaseRetain->getParent()]; 1898 unsigned PathCount = BBState::OverflowOccurredValue; 1899 if (NRRBBState.GetAllPathCountWithOverflow(PathCount)) 1900 return false; 1901 assert(PathCount != BBState::OverflowOccurredValue && 1902 "PathCount at this point can not be " 1903 "OverflowOccurredValue."); 1904 OldDelta += PathCount; 1905 OldCount += PathCount; 1906 1907 // Collect the optimal insertion points. 1908 if (!KnownSafe) 1909 for (Instruction *RIP : NewReleaseRetainRRI.ReverseInsertPts) { 1910 if (RetainsToMove.ReverseInsertPts.insert(RIP).second) { 1911 // If we overflow when we compute the path count, don't 1912 // remove/move anything. 1913 const BBState &RIPBBState = BBStates[RIP->getParent()]; 1914 1915 PathCount = BBState::OverflowOccurredValue; 1916 if (RIPBBState.GetAllPathCountWithOverflow(PathCount)) 1917 return false; 1918 assert(PathCount != BBState::OverflowOccurredValue && 1919 "PathCount at this point can not be " 1920 "OverflowOccurredValue."); 1921 NewDelta += PathCount; 1922 NewCount += PathCount; 1923 } 1924 } 1925 NewRetains.push_back(NewReleaseRetain); 1926 } 1927 } 1928 } 1929 if (NewRetains.empty()) break; 1930 } 1931 1932 // We can only remove pointers if we are known safe in both directions. 1933 bool UnconditionallySafe = KnownSafeTD && KnownSafeBU; 1934 if (UnconditionallySafe) { 1935 RetainsToMove.ReverseInsertPts.clear(); 1936 ReleasesToMove.ReverseInsertPts.clear(); 1937 NewCount = 0; 1938 } else { 1939 // Determine whether the new insertion points we computed preserve the 1940 // balance of retain and release calls through the program. 1941 // TODO: If the fully aggressive solution isn't valid, try to find a 1942 // less aggressive solution which is. 1943 if (NewDelta != 0) 1944 return false; 1945 1946 // At this point, we are not going to remove any RR pairs, but we still are 1947 // able to move RR pairs. If one of our pointers is afflicted with 1948 // CFGHazards, we cannot perform such code motion so exit early. 1949 const bool WillPerformCodeMotion = 1950 !RetainsToMove.ReverseInsertPts.empty() || 1951 !ReleasesToMove.ReverseInsertPts.empty(); 1952 if (CFGHazardAfflicted && WillPerformCodeMotion) 1953 return false; 1954 } 1955 1956 // Determine whether the original call points are balanced in the retain and 1957 // release calls through the program. If not, conservatively don't touch 1958 // them. 1959 // TODO: It's theoretically possible to do code motion in this case, as 1960 // long as the existing imbalances are maintained. 1961 if (OldDelta != 0) 1962 return false; 1963 1964 Changed = true; 1965 assert(OldCount != 0 && "Unreachable code?"); 1966 NumRRs += OldCount - NewCount; 1967 // Set to true if we completely removed any RR pairs. 1968 AnyPairsCompletelyEliminated = NewCount == 0; 1969 1970 // We can move calls! 1971 return true; 1972 } 1973 1974 /// Identify pairings between the retains and releases, and delete and/or move 1975 /// them. 1976 bool ObjCARCOpt::PerformCodePlacement( 1977 DenseMap<const BasicBlock *, BBState> &BBStates, 1978 BlotMapVector<Value *, RRInfo> &Retains, 1979 DenseMap<Value *, RRInfo> &Releases, Module *M) { 1980 LLVM_DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n"); 1981 1982 bool AnyPairsCompletelyEliminated = false; 1983 SmallVector<Instruction *, 8> DeadInsts; 1984 1985 // Visit each retain. 1986 for (BlotMapVector<Value *, RRInfo>::const_iterator I = Retains.begin(), 1987 E = Retains.end(); 1988 I != E; ++I) { 1989 Value *V = I->first; 1990 if (!V) continue; // blotted 1991 1992 Instruction *Retain = cast<Instruction>(V); 1993 1994 LLVM_DEBUG(dbgs() << "Visiting: " << *Retain << "\n"); 1995 1996 Value *Arg = GetArgRCIdentityRoot(Retain); 1997 1998 // If the object being released is in static or stack storage, we know it's 1999 // not being managed by ObjC reference counting, so we can delete pairs 2000 // regardless of what possible decrements or uses lie between them. 2001 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg); 2002 2003 // A constant pointer can't be pointing to an object on the heap. It may 2004 // be reference-counted, but it won't be deleted. 2005 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg)) 2006 if (const GlobalVariable *GV = 2007 dyn_cast<GlobalVariable>( 2008 GetRCIdentityRoot(LI->getPointerOperand()))) 2009 if (GV->isConstant()) 2010 KnownSafe = true; 2011 2012 // Connect the dots between the top-down-collected RetainsToMove and 2013 // bottom-up-collected ReleasesToMove to form sets of related calls. 2014 RRInfo RetainsToMove, ReleasesToMove; 2015 2016 bool PerformMoveCalls = PairUpRetainsAndReleases( 2017 BBStates, Retains, Releases, M, Retain, DeadInsts, 2018 RetainsToMove, ReleasesToMove, Arg, KnownSafe, 2019 AnyPairsCompletelyEliminated); 2020 2021 if (PerformMoveCalls) { 2022 // Ok, everything checks out and we're all set. Let's move/delete some 2023 // code! 2024 MoveCalls(Arg, RetainsToMove, ReleasesToMove, 2025 Retains, Releases, DeadInsts, M); 2026 } 2027 } 2028 2029 // Now that we're done moving everything, we can delete the newly dead 2030 // instructions, as we no longer need them as insert points. 2031 while (!DeadInsts.empty()) 2032 EraseInstruction(DeadInsts.pop_back_val()); 2033 2034 return AnyPairsCompletelyEliminated; 2035 } 2036 2037 /// Weak pointer optimizations. 2038 void ObjCARCOpt::OptimizeWeakCalls(Function &F) { 2039 LLVM_DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n"); 2040 2041 // First, do memdep-style RLE and S2L optimizations. We can't use memdep 2042 // itself because it uses AliasAnalysis and we need to do provenance 2043 // queries instead. 2044 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) { 2045 Instruction *Inst = &*I++; 2046 2047 LLVM_DEBUG(dbgs() << "Visiting: " << *Inst << "\n"); 2048 2049 ARCInstKind Class = GetBasicARCInstKind(Inst); 2050 if (Class != ARCInstKind::LoadWeak && 2051 Class != ARCInstKind::LoadWeakRetained) 2052 continue; 2053 2054 // Delete objc_loadWeak calls with no users. 2055 if (Class == ARCInstKind::LoadWeak && Inst->use_empty()) { 2056 Inst->eraseFromParent(); 2057 continue; 2058 } 2059 2060 // TODO: For now, just look for an earlier available version of this value 2061 // within the same block. Theoretically, we could do memdep-style non-local 2062 // analysis too, but that would want caching. A better approach would be to 2063 // use the technique that EarlyCSE uses. 2064 inst_iterator Current = std::prev(I); 2065 BasicBlock *CurrentBB = &*Current.getBasicBlockIterator(); 2066 for (BasicBlock::iterator B = CurrentBB->begin(), 2067 J = Current.getInstructionIterator(); 2068 J != B; --J) { 2069 Instruction *EarlierInst = &*std::prev(J); 2070 ARCInstKind EarlierClass = GetARCInstKind(EarlierInst); 2071 switch (EarlierClass) { 2072 case ARCInstKind::LoadWeak: 2073 case ARCInstKind::LoadWeakRetained: { 2074 // If this is loading from the same pointer, replace this load's value 2075 // with that one. 2076 CallInst *Call = cast<CallInst>(Inst); 2077 CallInst *EarlierCall = cast<CallInst>(EarlierInst); 2078 Value *Arg = Call->getArgOperand(0); 2079 Value *EarlierArg = EarlierCall->getArgOperand(0); 2080 switch (PA.getAA()->alias(Arg, EarlierArg)) { 2081 case MustAlias: 2082 Changed = true; 2083 // If the load has a builtin retain, insert a plain retain for it. 2084 if (Class == ARCInstKind::LoadWeakRetained) { 2085 Function *Decl = EP.get(ARCRuntimeEntryPointKind::Retain); 2086 CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call); 2087 CI->setTailCall(); 2088 } 2089 // Zap the fully redundant load. 2090 Call->replaceAllUsesWith(EarlierCall); 2091 Call->eraseFromParent(); 2092 goto clobbered; 2093 case MayAlias: 2094 case PartialAlias: 2095 goto clobbered; 2096 case NoAlias: 2097 break; 2098 } 2099 break; 2100 } 2101 case ARCInstKind::StoreWeak: 2102 case ARCInstKind::InitWeak: { 2103 // If this is storing to the same pointer and has the same size etc. 2104 // replace this load's value with the stored value. 2105 CallInst *Call = cast<CallInst>(Inst); 2106 CallInst *EarlierCall = cast<CallInst>(EarlierInst); 2107 Value *Arg = Call->getArgOperand(0); 2108 Value *EarlierArg = EarlierCall->getArgOperand(0); 2109 switch (PA.getAA()->alias(Arg, EarlierArg)) { 2110 case MustAlias: 2111 Changed = true; 2112 // If the load has a builtin retain, insert a plain retain for it. 2113 if (Class == ARCInstKind::LoadWeakRetained) { 2114 Function *Decl = EP.get(ARCRuntimeEntryPointKind::Retain); 2115 CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call); 2116 CI->setTailCall(); 2117 } 2118 // Zap the fully redundant load. 2119 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1)); 2120 Call->eraseFromParent(); 2121 goto clobbered; 2122 case MayAlias: 2123 case PartialAlias: 2124 goto clobbered; 2125 case NoAlias: 2126 break; 2127 } 2128 break; 2129 } 2130 case ARCInstKind::MoveWeak: 2131 case ARCInstKind::CopyWeak: 2132 // TOOD: Grab the copied value. 2133 goto clobbered; 2134 case ARCInstKind::AutoreleasepoolPush: 2135 case ARCInstKind::None: 2136 case ARCInstKind::IntrinsicUser: 2137 case ARCInstKind::User: 2138 // Weak pointers are only modified through the weak entry points 2139 // (and arbitrary calls, which could call the weak entry points). 2140 break; 2141 default: 2142 // Anything else could modify the weak pointer. 2143 goto clobbered; 2144 } 2145 } 2146 clobbered:; 2147 } 2148 2149 // Then, for each destroyWeak with an alloca operand, check to see if 2150 // the alloca and all its users can be zapped. 2151 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) { 2152 Instruction *Inst = &*I++; 2153 ARCInstKind Class = GetBasicARCInstKind(Inst); 2154 if (Class != ARCInstKind::DestroyWeak) 2155 continue; 2156 2157 CallInst *Call = cast<CallInst>(Inst); 2158 Value *Arg = Call->getArgOperand(0); 2159 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) { 2160 for (User *U : Alloca->users()) { 2161 const Instruction *UserInst = cast<Instruction>(U); 2162 switch (GetBasicARCInstKind(UserInst)) { 2163 case ARCInstKind::InitWeak: 2164 case ARCInstKind::StoreWeak: 2165 case ARCInstKind::DestroyWeak: 2166 continue; 2167 default: 2168 goto done; 2169 } 2170 } 2171 Changed = true; 2172 for (auto UI = Alloca->user_begin(), UE = Alloca->user_end(); UI != UE;) { 2173 CallInst *UserInst = cast<CallInst>(*UI++); 2174 switch (GetBasicARCInstKind(UserInst)) { 2175 case ARCInstKind::InitWeak: 2176 case ARCInstKind::StoreWeak: 2177 // These functions return their second argument. 2178 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1)); 2179 break; 2180 case ARCInstKind::DestroyWeak: 2181 // No return value. 2182 break; 2183 default: 2184 llvm_unreachable("alloca really is used!"); 2185 } 2186 UserInst->eraseFromParent(); 2187 } 2188 Alloca->eraseFromParent(); 2189 done:; 2190 } 2191 } 2192 } 2193 2194 /// Identify program paths which execute sequences of retains and releases which 2195 /// can be eliminated. 2196 bool ObjCARCOpt::OptimizeSequences(Function &F) { 2197 // Releases, Retains - These are used to store the results of the main flow 2198 // analysis. These use Value* as the key instead of Instruction* so that the 2199 // map stays valid when we get around to rewriting code and calls get 2200 // replaced by arguments. 2201 DenseMap<Value *, RRInfo> Releases; 2202 BlotMapVector<Value *, RRInfo> Retains; 2203 2204 // This is used during the traversal of the function to track the 2205 // states for each identified object at each block. 2206 DenseMap<const BasicBlock *, BBState> BBStates; 2207 2208 // Analyze the CFG of the function, and all instructions. 2209 bool NestingDetected = Visit(F, BBStates, Retains, Releases); 2210 2211 if (DisableRetainReleasePairing) 2212 return false; 2213 2214 // Transform. 2215 bool AnyPairsCompletelyEliminated = PerformCodePlacement(BBStates, Retains, 2216 Releases, 2217 F.getParent()); 2218 2219 return AnyPairsCompletelyEliminated && NestingDetected; 2220 } 2221 2222 /// Check if there is a dependent call earlier that does not have anything in 2223 /// between the Retain and the call that can affect the reference count of their 2224 /// shared pointer argument. Note that Retain need not be in BB. 2225 static bool 2226 HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain, 2227 SmallPtrSetImpl<Instruction *> &DepInsts, 2228 SmallPtrSetImpl<const BasicBlock *> &Visited, 2229 ProvenanceAnalysis &PA) { 2230 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain, 2231 DepInsts, Visited, PA); 2232 if (DepInsts.size() != 1) 2233 return false; 2234 2235 auto *Call = dyn_cast_or_null<CallInst>(*DepInsts.begin()); 2236 2237 // Check that the pointer is the return value of the call. 2238 if (!Call || Arg != Call) 2239 return false; 2240 2241 // Check that the call is a regular call. 2242 ARCInstKind Class = GetBasicARCInstKind(Call); 2243 return Class == ARCInstKind::CallOrUser || Class == ARCInstKind::Call; 2244 } 2245 2246 /// Find a dependent retain that precedes the given autorelease for which there 2247 /// is nothing in between the two instructions that can affect the ref count of 2248 /// Arg. 2249 static CallInst * 2250 FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB, 2251 Instruction *Autorelease, 2252 SmallPtrSetImpl<Instruction *> &DepInsts, 2253 SmallPtrSetImpl<const BasicBlock *> &Visited, 2254 ProvenanceAnalysis &PA) { 2255 FindDependencies(CanChangeRetainCount, Arg, 2256 BB, Autorelease, DepInsts, Visited, PA); 2257 if (DepInsts.size() != 1) 2258 return nullptr; 2259 2260 auto *Retain = dyn_cast_or_null<CallInst>(*DepInsts.begin()); 2261 2262 // Check that we found a retain with the same argument. 2263 if (!Retain || !IsRetain(GetBasicARCInstKind(Retain)) || 2264 GetArgRCIdentityRoot(Retain) != Arg) { 2265 return nullptr; 2266 } 2267 2268 return Retain; 2269 } 2270 2271 /// Look for an ``autorelease'' instruction dependent on Arg such that there are 2272 /// no instructions dependent on Arg that need a positive ref count in between 2273 /// the autorelease and the ret. 2274 static CallInst * 2275 FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB, 2276 ReturnInst *Ret, 2277 SmallPtrSetImpl<Instruction *> &DepInsts, 2278 SmallPtrSetImpl<const BasicBlock *> &V, 2279 ProvenanceAnalysis &PA) { 2280 FindDependencies(NeedsPositiveRetainCount, Arg, 2281 BB, Ret, DepInsts, V, PA); 2282 if (DepInsts.size() != 1) 2283 return nullptr; 2284 2285 auto *Autorelease = dyn_cast_or_null<CallInst>(*DepInsts.begin()); 2286 if (!Autorelease) 2287 return nullptr; 2288 ARCInstKind AutoreleaseClass = GetBasicARCInstKind(Autorelease); 2289 if (!IsAutorelease(AutoreleaseClass)) 2290 return nullptr; 2291 if (GetArgRCIdentityRoot(Autorelease) != Arg) 2292 return nullptr; 2293 2294 return Autorelease; 2295 } 2296 2297 /// Look for this pattern: 2298 /// \code 2299 /// %call = call i8* @something(...) 2300 /// %2 = call i8* @objc_retain(i8* %call) 2301 /// %3 = call i8* @objc_autorelease(i8* %2) 2302 /// ret i8* %3 2303 /// \endcode 2304 /// And delete the retain and autorelease. 2305 void ObjCARCOpt::OptimizeReturns(Function &F) { 2306 if (!F.getReturnType()->isPointerTy()) 2307 return; 2308 2309 LLVM_DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n"); 2310 2311 SmallPtrSet<Instruction *, 4> DependingInstructions; 2312 SmallPtrSet<const BasicBlock *, 4> Visited; 2313 for (BasicBlock &BB: F) { 2314 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB.back()); 2315 if (!Ret) 2316 continue; 2317 2318 LLVM_DEBUG(dbgs() << "Visiting: " << *Ret << "\n"); 2319 2320 const Value *Arg = GetRCIdentityRoot(Ret->getOperand(0)); 2321 2322 // Look for an ``autorelease'' instruction that is a predecessor of Ret and 2323 // dependent on Arg such that there are no instructions dependent on Arg 2324 // that need a positive ref count in between the autorelease and Ret. 2325 CallInst *Autorelease = FindPredecessorAutoreleaseWithSafePath( 2326 Arg, &BB, Ret, DependingInstructions, Visited, PA); 2327 DependingInstructions.clear(); 2328 Visited.clear(); 2329 2330 if (!Autorelease) 2331 continue; 2332 2333 CallInst *Retain = FindPredecessorRetainWithSafePath( 2334 Arg, Autorelease->getParent(), Autorelease, DependingInstructions, 2335 Visited, PA); 2336 DependingInstructions.clear(); 2337 Visited.clear(); 2338 2339 if (!Retain) 2340 continue; 2341 2342 // Check that there is nothing that can affect the reference count 2343 // between the retain and the call. Note that Retain need not be in BB. 2344 bool HasSafePathToCall = HasSafePathToPredecessorCall(Arg, Retain, 2345 DependingInstructions, 2346 Visited, PA); 2347 2348 // Don't remove retainRV/autoreleaseRV pairs if the call isn't a tail call. 2349 if (HasSafePathToCall && 2350 GetBasicARCInstKind(Retain) == ARCInstKind::RetainRV && 2351 GetBasicARCInstKind(Autorelease) == ARCInstKind::AutoreleaseRV && 2352 !cast<CallInst>(*DependingInstructions.begin())->isTailCall()) 2353 continue; 2354 2355 DependingInstructions.clear(); 2356 Visited.clear(); 2357 2358 if (!HasSafePathToCall) 2359 continue; 2360 2361 // If so, we can zap the retain and autorelease. 2362 Changed = true; 2363 ++NumRets; 2364 LLVM_DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: " << *Autorelease 2365 << "\n"); 2366 EraseInstruction(Retain); 2367 EraseInstruction(Autorelease); 2368 } 2369 } 2370 2371 #ifndef NDEBUG 2372 void 2373 ObjCARCOpt::GatherStatistics(Function &F, bool AfterOptimization) { 2374 Statistic &NumRetains = 2375 AfterOptimization ? NumRetainsAfterOpt : NumRetainsBeforeOpt; 2376 Statistic &NumReleases = 2377 AfterOptimization ? NumReleasesAfterOpt : NumReleasesBeforeOpt; 2378 2379 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) { 2380 Instruction *Inst = &*I++; 2381 switch (GetBasicARCInstKind(Inst)) { 2382 default: 2383 break; 2384 case ARCInstKind::Retain: 2385 ++NumRetains; 2386 break; 2387 case ARCInstKind::Release: 2388 ++NumReleases; 2389 break; 2390 } 2391 } 2392 } 2393 #endif 2394 2395 bool ObjCARCOpt::doInitialization(Module &M) { 2396 if (!EnableARCOpts) 2397 return false; 2398 2399 // If nothing in the Module uses ARC, don't do anything. 2400 Run = ModuleHasARC(M); 2401 if (!Run) 2402 return false; 2403 2404 // Intuitively, objc_retain and others are nocapture, however in practice 2405 // they are not, because they return their argument value. And objc_release 2406 // calls finalizers which can have arbitrary side effects. 2407 MDKindCache.init(&M); 2408 2409 // Initialize our runtime entry point cache. 2410 EP.init(&M); 2411 2412 return false; 2413 } 2414 2415 bool ObjCARCOpt::runOnFunction(Function &F) { 2416 if (!EnableARCOpts) 2417 return false; 2418 2419 // If nothing in the Module uses ARC, don't do anything. 2420 if (!Run) 2421 return false; 2422 2423 Changed = false; 2424 2425 LLVM_DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() 2426 << " >>>" 2427 "\n"); 2428 2429 PA.setAA(&getAnalysis<AAResultsWrapperPass>().getAAResults()); 2430 2431 #ifndef NDEBUG 2432 if (AreStatisticsEnabled()) { 2433 GatherStatistics(F, false); 2434 } 2435 #endif 2436 2437 // This pass performs several distinct transformations. As a compile-time aid 2438 // when compiling code that isn't ObjC, skip these if the relevant ObjC 2439 // library functions aren't declared. 2440 2441 // Preliminary optimizations. This also computes UsedInThisFunction. 2442 OptimizeIndividualCalls(F); 2443 2444 // Optimizations for weak pointers. 2445 if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::LoadWeak)) | 2446 (1 << unsigned(ARCInstKind::LoadWeakRetained)) | 2447 (1 << unsigned(ARCInstKind::StoreWeak)) | 2448 (1 << unsigned(ARCInstKind::InitWeak)) | 2449 (1 << unsigned(ARCInstKind::CopyWeak)) | 2450 (1 << unsigned(ARCInstKind::MoveWeak)) | 2451 (1 << unsigned(ARCInstKind::DestroyWeak)))) 2452 OptimizeWeakCalls(F); 2453 2454 // Optimizations for retain+release pairs. 2455 if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::Retain)) | 2456 (1 << unsigned(ARCInstKind::RetainRV)) | 2457 (1 << unsigned(ARCInstKind::RetainBlock)))) 2458 if (UsedInThisFunction & (1 << unsigned(ARCInstKind::Release))) 2459 // Run OptimizeSequences until it either stops making changes or 2460 // no retain+release pair nesting is detected. 2461 while (OptimizeSequences(F)) {} 2462 2463 // Optimizations if objc_autorelease is used. 2464 if (UsedInThisFunction & ((1 << unsigned(ARCInstKind::Autorelease)) | 2465 (1 << unsigned(ARCInstKind::AutoreleaseRV)))) 2466 OptimizeReturns(F); 2467 2468 // Gather statistics after optimization. 2469 #ifndef NDEBUG 2470 if (AreStatisticsEnabled()) { 2471 GatherStatistics(F, true); 2472 } 2473 #endif 2474 2475 LLVM_DEBUG(dbgs() << "\n"); 2476 2477 return Changed; 2478 } 2479 2480 void ObjCARCOpt::releaseMemory() { 2481 PA.clear(); 2482 } 2483 2484 /// @} 2485 /// 2486