TransAutoreleasePool.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. //===--- TransAutoreleasePool.cpp - Transformations to ARC mode -----------===//
  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. // rewriteAutoreleasePool:
  10. //
  11. // Calls to NSAutoreleasePools will be rewritten as an @autorelease scope.
  12. //
  13. // NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  14. // ...
  15. // [pool release];
  16. // ---->
  17. // @autorelease {
  18. // ...
  19. // }
  20. //
  21. // An NSAutoreleasePool will not be touched if:
  22. // - There is not a corresponding -release/-drain in the same scope
  23. // - Not all references of the NSAutoreleasePool variable can be removed
  24. // - There is a variable that is declared inside the intended @autorelease scope
  25. // which is also used outside it.
  26. //
  27. //===----------------------------------------------------------------------===//
  28. #include "Transforms.h"
  29. #include "Internals.h"
  30. #include "clang/AST/ASTContext.h"
  31. #include "clang/Basic/SourceManager.h"
  32. #include "clang/Sema/SemaDiagnostic.h"
  33. #include <map>
  34. using namespace clang;
  35. using namespace arcmt;
  36. using namespace trans;
  37. namespace {
  38. class ReleaseCollector : public RecursiveASTVisitor<ReleaseCollector> {
  39. Decl *Dcl;
  40. SmallVectorImpl<ObjCMessageExpr *> &Releases;
  41. public:
  42. ReleaseCollector(Decl *D, SmallVectorImpl<ObjCMessageExpr *> &releases)
  43. : Dcl(D), Releases(releases) { }
  44. bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
  45. if (!E->isInstanceMessage())
  46. return true;
  47. if (E->getMethodFamily() != OMF_release)
  48. return true;
  49. Expr *instance = E->getInstanceReceiver()->IgnoreParenCasts();
  50. if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(instance)) {
  51. if (DE->getDecl() == Dcl)
  52. Releases.push_back(E);
  53. }
  54. return true;
  55. }
  56. };
  57. }
  58. namespace {
  59. class AutoreleasePoolRewriter
  60. : public RecursiveASTVisitor<AutoreleasePoolRewriter> {
  61. public:
  62. AutoreleasePoolRewriter(MigrationPass &pass)
  63. : Body(nullptr), Pass(pass) {
  64. PoolII = &pass.Ctx.Idents.get("NSAutoreleasePool");
  65. DrainSel = pass.Ctx.Selectors.getNullarySelector(
  66. &pass.Ctx.Idents.get("drain"));
  67. }
  68. void transformBody(Stmt *body, Decl *ParentD) {
  69. Body = body;
  70. TraverseStmt(body);
  71. }
  72. ~AutoreleasePoolRewriter() {
  73. SmallVector<VarDecl *, 8> VarsToHandle;
  74. for (std::map<VarDecl *, PoolVarInfo>::iterator
  75. I = PoolVars.begin(), E = PoolVars.end(); I != E; ++I) {
  76. VarDecl *var = I->first;
  77. PoolVarInfo &info = I->second;
  78. // Check that we can handle/rewrite all references of the pool.
  79. clearRefsIn(info.Dcl, info.Refs);
  80. for (SmallVectorImpl<PoolScope>::iterator
  81. scpI = info.Scopes.begin(),
  82. scpE = info.Scopes.end(); scpI != scpE; ++scpI) {
  83. PoolScope &scope = *scpI;
  84. clearRefsIn(*scope.Begin, info.Refs);
  85. clearRefsIn(*scope.End, info.Refs);
  86. clearRefsIn(scope.Releases.begin(), scope.Releases.end(), info.Refs);
  87. }
  88. // Even if one reference is not handled we will not do anything about that
  89. // pool variable.
  90. if (info.Refs.empty())
  91. VarsToHandle.push_back(var);
  92. }
  93. for (unsigned i = 0, e = VarsToHandle.size(); i != e; ++i) {
  94. PoolVarInfo &info = PoolVars[VarsToHandle[i]];
  95. Transaction Trans(Pass.TA);
  96. clearUnavailableDiags(info.Dcl);
  97. Pass.TA.removeStmt(info.Dcl);
  98. // Add "@autoreleasepool { }"
  99. for (SmallVectorImpl<PoolScope>::iterator
  100. scpI = info.Scopes.begin(),
  101. scpE = info.Scopes.end(); scpI != scpE; ++scpI) {
  102. PoolScope &scope = *scpI;
  103. clearUnavailableDiags(*scope.Begin);
  104. clearUnavailableDiags(*scope.End);
  105. if (scope.IsFollowedBySimpleReturnStmt) {
  106. // Include the return in the scope.
  107. Pass.TA.replaceStmt(*scope.Begin, "@autoreleasepool {");
  108. Pass.TA.removeStmt(*scope.End);
  109. Stmt::child_iterator retI = scope.End;
  110. ++retI;
  111. SourceLocation afterSemi =
  112. findLocationAfterSemi((*retI)->getEndLoc(), Pass.Ctx);
  113. assert(afterSemi.isValid() &&
  114. "Didn't we check before setting IsFollowedBySimpleReturnStmt "
  115. "to true?");
  116. Pass.TA.insertAfterToken(afterSemi, "\n}");
  117. Pass.TA.increaseIndentation(
  118. SourceRange(scope.getIndentedRange().getBegin(),
  119. (*retI)->getEndLoc()),
  120. scope.CompoundParent->getBeginLoc());
  121. } else {
  122. Pass.TA.replaceStmt(*scope.Begin, "@autoreleasepool {");
  123. Pass.TA.replaceStmt(*scope.End, "}");
  124. Pass.TA.increaseIndentation(scope.getIndentedRange(),
  125. scope.CompoundParent->getBeginLoc());
  126. }
  127. }
  128. // Remove rest of pool var references.
  129. for (SmallVectorImpl<PoolScope>::iterator
  130. scpI = info.Scopes.begin(),
  131. scpE = info.Scopes.end(); scpI != scpE; ++scpI) {
  132. PoolScope &scope = *scpI;
  133. for (SmallVectorImpl<ObjCMessageExpr *>::iterator
  134. relI = scope.Releases.begin(),
  135. relE = scope.Releases.end(); relI != relE; ++relI) {
  136. clearUnavailableDiags(*relI);
  137. Pass.TA.removeStmt(*relI);
  138. }
  139. }
  140. }
  141. }
  142. bool VisitCompoundStmt(CompoundStmt *S) {
  143. SmallVector<PoolScope, 4> Scopes;
  144. for (Stmt::child_iterator
  145. I = S->body_begin(), E = S->body_end(); I != E; ++I) {
  146. Stmt *child = getEssential(*I);
  147. if (DeclStmt *DclS = dyn_cast<DeclStmt>(child)) {
  148. if (DclS->isSingleDecl()) {
  149. if (VarDecl *VD = dyn_cast<VarDecl>(DclS->getSingleDecl())) {
  150. if (isNSAutoreleasePool(VD->getType())) {
  151. PoolVarInfo &info = PoolVars[VD];
  152. info.Dcl = DclS;
  153. collectRefs(VD, S, info.Refs);
  154. // Does this statement follow the pattern:
  155. // NSAutoreleasePool * pool = [NSAutoreleasePool new];
  156. if (isPoolCreation(VD->getInit())) {
  157. Scopes.push_back(PoolScope());
  158. Scopes.back().PoolVar = VD;
  159. Scopes.back().CompoundParent = S;
  160. Scopes.back().Begin = I;
  161. }
  162. }
  163. }
  164. }
  165. } else if (BinaryOperator *bop = dyn_cast<BinaryOperator>(child)) {
  166. if (DeclRefExpr *dref = dyn_cast<DeclRefExpr>(bop->getLHS())) {
  167. if (VarDecl *VD = dyn_cast<VarDecl>(dref->getDecl())) {
  168. // Does this statement follow the pattern:
  169. // pool = [NSAutoreleasePool new];
  170. if (isNSAutoreleasePool(VD->getType()) &&
  171. isPoolCreation(bop->getRHS())) {
  172. Scopes.push_back(PoolScope());
  173. Scopes.back().PoolVar = VD;
  174. Scopes.back().CompoundParent = S;
  175. Scopes.back().Begin = I;
  176. }
  177. }
  178. }
  179. }
  180. if (Scopes.empty())
  181. continue;
  182. if (isPoolDrain(Scopes.back().PoolVar, child)) {
  183. PoolScope &scope = Scopes.back();
  184. scope.End = I;
  185. handlePoolScope(scope, S);
  186. Scopes.pop_back();
  187. }
  188. }
  189. return true;
  190. }
  191. private:
  192. void clearUnavailableDiags(Stmt *S) {
  193. if (S)
  194. Pass.TA.clearDiagnostic(diag::err_unavailable,
  195. diag::err_unavailable_message,
  196. S->getSourceRange());
  197. }
  198. struct PoolScope {
  199. VarDecl *PoolVar;
  200. CompoundStmt *CompoundParent;
  201. Stmt::child_iterator Begin;
  202. Stmt::child_iterator End;
  203. bool IsFollowedBySimpleReturnStmt;
  204. SmallVector<ObjCMessageExpr *, 4> Releases;
  205. PoolScope()
  206. : PoolVar(nullptr), CompoundParent(nullptr),
  207. IsFollowedBySimpleReturnStmt(false) {}
  208. SourceRange getIndentedRange() const {
  209. Stmt::child_iterator rangeS = Begin;
  210. ++rangeS;
  211. if (rangeS == End)
  212. return SourceRange();
  213. Stmt::child_iterator rangeE = Begin;
  214. for (Stmt::child_iterator I = rangeS; I != End; ++I)
  215. ++rangeE;
  216. return SourceRange((*rangeS)->getBeginLoc(), (*rangeE)->getEndLoc());
  217. }
  218. };
  219. class NameReferenceChecker : public RecursiveASTVisitor<NameReferenceChecker>{
  220. ASTContext &Ctx;
  221. SourceRange ScopeRange;
  222. SourceLocation &referenceLoc, &declarationLoc;
  223. public:
  224. NameReferenceChecker(ASTContext &ctx, PoolScope &scope,
  225. SourceLocation &referenceLoc,
  226. SourceLocation &declarationLoc)
  227. : Ctx(ctx), referenceLoc(referenceLoc),
  228. declarationLoc(declarationLoc) {
  229. ScopeRange = SourceRange((*scope.Begin)->getBeginLoc(),
  230. (*scope.End)->getBeginLoc());
  231. }
  232. bool VisitDeclRefExpr(DeclRefExpr *E) {
  233. return checkRef(E->getLocation(), E->getDecl()->getLocation());
  234. }
  235. bool VisitTypedefTypeLoc(TypedefTypeLoc TL) {
  236. return checkRef(TL.getBeginLoc(), TL.getTypedefNameDecl()->getLocation());
  237. }
  238. bool VisitTagTypeLoc(TagTypeLoc TL) {
  239. return checkRef(TL.getBeginLoc(), TL.getDecl()->getLocation());
  240. }
  241. private:
  242. bool checkRef(SourceLocation refLoc, SourceLocation declLoc) {
  243. if (isInScope(declLoc)) {
  244. referenceLoc = refLoc;
  245. declarationLoc = declLoc;
  246. return false;
  247. }
  248. return true;
  249. }
  250. bool isInScope(SourceLocation loc) {
  251. if (loc.isInvalid())
  252. return false;
  253. SourceManager &SM = Ctx.getSourceManager();
  254. if (SM.isBeforeInTranslationUnit(loc, ScopeRange.getBegin()))
  255. return false;
  256. return SM.isBeforeInTranslationUnit(loc, ScopeRange.getEnd());
  257. }
  258. };
  259. void handlePoolScope(PoolScope &scope, CompoundStmt *compoundS) {
  260. // Check that all names declared inside the scope are not used
  261. // outside the scope.
  262. {
  263. bool nameUsedOutsideScope = false;
  264. SourceLocation referenceLoc, declarationLoc;
  265. Stmt::child_iterator SI = scope.End, SE = compoundS->body_end();
  266. ++SI;
  267. // Check if the autoreleasepool scope is followed by a simple return
  268. // statement, in which case we will include the return in the scope.
  269. if (SI != SE)
  270. if (ReturnStmt *retS = dyn_cast<ReturnStmt>(*SI))
  271. if ((retS->getRetValue() == nullptr ||
  272. isa<DeclRefExpr>(retS->getRetValue()->IgnoreParenCasts())) &&
  273. findLocationAfterSemi(retS->getEndLoc(), Pass.Ctx).isValid()) {
  274. scope.IsFollowedBySimpleReturnStmt = true;
  275. ++SI; // the return will be included in scope, don't check it.
  276. }
  277. for (; SI != SE; ++SI) {
  278. nameUsedOutsideScope = !NameReferenceChecker(Pass.Ctx, scope,
  279. referenceLoc,
  280. declarationLoc).TraverseStmt(*SI);
  281. if (nameUsedOutsideScope)
  282. break;
  283. }
  284. // If not all references were cleared it means some variables/typenames/etc
  285. // declared inside the pool scope are used outside of it.
  286. // We won't try to rewrite the pool.
  287. if (nameUsedOutsideScope) {
  288. Pass.TA.reportError("a name is referenced outside the "
  289. "NSAutoreleasePool scope that it was declared in", referenceLoc);
  290. Pass.TA.reportNote("name declared here", declarationLoc);
  291. Pass.TA.reportNote("intended @autoreleasepool scope begins here",
  292. (*scope.Begin)->getBeginLoc());
  293. Pass.TA.reportNote("intended @autoreleasepool scope ends here",
  294. (*scope.End)->getBeginLoc());
  295. return;
  296. }
  297. }
  298. // Collect all releases of the pool; they will be removed.
  299. {
  300. ReleaseCollector releaseColl(scope.PoolVar, scope.Releases);
  301. Stmt::child_iterator I = scope.Begin;
  302. ++I;
  303. for (; I != scope.End; ++I)
  304. releaseColl.TraverseStmt(*I);
  305. }
  306. PoolVars[scope.PoolVar].Scopes.push_back(scope);
  307. }
  308. bool isPoolCreation(Expr *E) {
  309. if (!E) return false;
  310. E = getEssential(E);
  311. ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E);
  312. if (!ME) return false;
  313. if (ME->getMethodFamily() == OMF_new &&
  314. ME->getReceiverKind() == ObjCMessageExpr::Class &&
  315. isNSAutoreleasePool(ME->getReceiverInterface()))
  316. return true;
  317. if (ME->getReceiverKind() == ObjCMessageExpr::Instance &&
  318. ME->getMethodFamily() == OMF_init) {
  319. Expr *rec = getEssential(ME->getInstanceReceiver());
  320. if (ObjCMessageExpr *recME = dyn_cast_or_null<ObjCMessageExpr>(rec)) {
  321. if (recME->getMethodFamily() == OMF_alloc &&
  322. recME->getReceiverKind() == ObjCMessageExpr::Class &&
  323. isNSAutoreleasePool(recME->getReceiverInterface()))
  324. return true;
  325. }
  326. }
  327. return false;
  328. }
  329. bool isPoolDrain(VarDecl *poolVar, Stmt *S) {
  330. if (!S) return false;
  331. S = getEssential(S);
  332. ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S);
  333. if (!ME) return false;
  334. if (ME->getReceiverKind() == ObjCMessageExpr::Instance) {
  335. Expr *rec = getEssential(ME->getInstanceReceiver());
  336. if (DeclRefExpr *dref = dyn_cast<DeclRefExpr>(rec))
  337. if (dref->getDecl() == poolVar)
  338. return ME->getMethodFamily() == OMF_release ||
  339. ME->getSelector() == DrainSel;
  340. }
  341. return false;
  342. }
  343. bool isNSAutoreleasePool(ObjCInterfaceDecl *IDecl) {
  344. return IDecl && IDecl->getIdentifier() == PoolII;
  345. }
  346. bool isNSAutoreleasePool(QualType Ty) {
  347. QualType pointee = Ty->getPointeeType();
  348. if (pointee.isNull())
  349. return false;
  350. if (const ObjCInterfaceType *interT = pointee->getAs<ObjCInterfaceType>())
  351. return isNSAutoreleasePool(interT->getDecl());
  352. return false;
  353. }
  354. static Expr *getEssential(Expr *E) {
  355. return cast<Expr>(getEssential((Stmt*)E));
  356. }
  357. static Stmt *getEssential(Stmt *S) {
  358. if (FullExpr *FE = dyn_cast<FullExpr>(S))
  359. S = FE->getSubExpr();
  360. if (Expr *E = dyn_cast<Expr>(S))
  361. S = E->IgnoreParenCasts();
  362. return S;
  363. }
  364. Stmt *Body;
  365. MigrationPass &Pass;
  366. IdentifierInfo *PoolII;
  367. Selector DrainSel;
  368. struct PoolVarInfo {
  369. DeclStmt *Dcl;
  370. ExprSet Refs;
  371. SmallVector<PoolScope, 2> Scopes;
  372. PoolVarInfo() : Dcl(nullptr) { }
  373. };
  374. std::map<VarDecl *, PoolVarInfo> PoolVars;
  375. };
  376. } // anonymous namespace
  377. void trans::rewriteAutoreleasePool(MigrationPass &pass) {
  378. BodyTransform<AutoreleasePoolRewriter> trans(pass);
  379. trans.TraverseDecl(pass.Ctx.getTranslationUnitDecl());
  380. }