ObjCARCOpts.cpp 92 KB

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