ObjCARCOpts.cpp 91 KB

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