1 //===--- TransAutoreleasePool.cpp - Tranformations to ARC mode ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // rewriteAutoreleasePool:
12 // Calls to NSAutoreleasePools will be rewritten as an @autorelease scope.
14 // NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
22 // An NSAutoreleasePool will not be touched if:
23 // - There is not a corresponding -release/-drain in the same scope
24 // - Not all references of the NSAutoreleasePool variable can be removed
25 // - There is a variable that is declared inside the intended @autorelease scope
26 // which is also used outside it.
28 //===----------------------------------------------------------------------===//
30 #include "Transforms.h"
31 #include "Internals.h"
32 #include "clang/Sema/SemaDiagnostic.h"
33 #include "clang/Basic/SourceManager.h"
36 using namespace clang;
37 using namespace arcmt;
38 using namespace trans;
42 class ReleaseCollector : public RecursiveASTVisitor<ReleaseCollector> {
44 SmallVectorImpl<ObjCMessageExpr *> &Releases;
47 ReleaseCollector(Decl *D, SmallVectorImpl<ObjCMessageExpr *> &releases)
48 : Dcl(D), Releases(releases) { }
50 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
51 if (!E->isInstanceMessage())
53 if (E->getMethodFamily() != OMF_release)
55 Expr *instance = E->getInstanceReceiver()->IgnoreParenCasts();
56 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(instance)) {
57 if (DE->getDecl() == Dcl)
58 Releases.push_back(E);
68 class AutoreleasePoolRewriter
69 : public RecursiveASTVisitor<AutoreleasePoolRewriter> {
71 AutoreleasePoolRewriter(MigrationPass &pass)
72 : Body(0), Pass(pass) {
73 PoolII = &pass.Ctx.Idents.get("NSAutoreleasePool");
74 DrainSel = pass.Ctx.Selectors.getNullarySelector(
75 &pass.Ctx.Idents.get("drain"));
78 void transformBody(Stmt *body) {
83 ~AutoreleasePoolRewriter() {
84 SmallVector<VarDecl *, 8> VarsToHandle;
86 for (std::map<VarDecl *, PoolVarInfo>::iterator
87 I = PoolVars.begin(), E = PoolVars.end(); I != E; ++I) {
88 VarDecl *var = I->first;
89 PoolVarInfo &info = I->second;
91 // Check that we can handle/rewrite all references of the pool.
93 clearRefsIn(info.Dcl, info.Refs);
94 for (SmallVectorImpl<PoolScope>::iterator
95 scpI = info.Scopes.begin(),
96 scpE = info.Scopes.end(); scpI != scpE; ++scpI) {
97 PoolScope &scope = *scpI;
98 clearRefsIn(*scope.Begin, info.Refs);
99 clearRefsIn(*scope.End, info.Refs);
100 clearRefsIn(scope.Releases.begin(), scope.Releases.end(), info.Refs);
103 // Even if one reference is not handled we will not do anything about that
105 if (info.Refs.empty())
106 VarsToHandle.push_back(var);
109 for (unsigned i = 0, e = VarsToHandle.size(); i != e; ++i) {
110 PoolVarInfo &info = PoolVars[VarsToHandle[i]];
112 Transaction Trans(Pass.TA);
114 clearUnavailableDiags(info.Dcl);
115 Pass.TA.removeStmt(info.Dcl);
117 // Add "@autoreleasepool { }"
118 for (SmallVectorImpl<PoolScope>::iterator
119 scpI = info.Scopes.begin(),
120 scpE = info.Scopes.end(); scpI != scpE; ++scpI) {
121 PoolScope &scope = *scpI;
122 clearUnavailableDiags(*scope.Begin);
123 clearUnavailableDiags(*scope.End);
124 if (scope.IsFollowedBySimpleReturnStmt) {
125 // Include the return in the scope.
126 Pass.TA.replaceStmt(*scope.Begin, "@autoreleasepool {");
127 Pass.TA.removeStmt(*scope.End);
128 Stmt::child_iterator retI = scope.End;
130 SourceLocation afterSemi = findLocationAfterSemi((*retI)->getLocEnd(),
132 assert(afterSemi.isValid() &&
133 "Didn't we check before setting IsFollowedBySimpleReturnStmt "
135 Pass.TA.insertAfterToken(afterSemi, "\n}");
136 Pass.TA.increaseIndentation(
137 SourceRange(scope.getIndentedRange().getBegin(),
138 (*retI)->getLocEnd()),
139 scope.CompoundParent->getLocStart());
141 Pass.TA.replaceStmt(*scope.Begin, "@autoreleasepool {");
142 Pass.TA.replaceStmt(*scope.End, "}");
143 Pass.TA.increaseIndentation(scope.getIndentedRange(),
144 scope.CompoundParent->getLocStart());
148 // Remove rest of pool var references.
149 for (SmallVectorImpl<PoolScope>::iterator
150 scpI = info.Scopes.begin(),
151 scpE = info.Scopes.end(); scpI != scpE; ++scpI) {
152 PoolScope &scope = *scpI;
153 for (SmallVectorImpl<ObjCMessageExpr *>::iterator
154 relI = scope.Releases.begin(),
155 relE = scope.Releases.end(); relI != relE; ++relI) {
156 clearUnavailableDiags(*relI);
157 Pass.TA.removeStmt(*relI);
163 bool VisitCompoundStmt(CompoundStmt *S) {
164 SmallVector<PoolScope, 4> Scopes;
166 for (Stmt::child_iterator
167 I = S->body_begin(), E = S->body_end(); I != E; ++I) {
168 Stmt *child = getEssential(*I);
169 if (DeclStmt *DclS = dyn_cast<DeclStmt>(child)) {
170 if (DclS->isSingleDecl()) {
171 if (VarDecl *VD = dyn_cast<VarDecl>(DclS->getSingleDecl())) {
172 if (isNSAutoreleasePool(VD->getType())) {
173 PoolVarInfo &info = PoolVars[VD];
175 collectRefs(VD, S, info.Refs);
176 // Does this statement follow the pattern:
177 // NSAutoreleasePool * pool = [NSAutoreleasePool new];
178 if (isPoolCreation(VD->getInit())) {
179 Scopes.push_back(PoolScope());
180 Scopes.back().PoolVar = VD;
181 Scopes.back().CompoundParent = S;
182 Scopes.back().Begin = I;
187 } else if (BinaryOperator *bop = dyn_cast<BinaryOperator>(child)) {
188 if (DeclRefExpr *dref = dyn_cast<DeclRefExpr>(bop->getLHS())) {
189 if (VarDecl *VD = dyn_cast<VarDecl>(dref->getDecl())) {
190 // Does this statement follow the pattern:
191 // pool = [NSAutoreleasePool new];
192 if (isNSAutoreleasePool(VD->getType()) &&
193 isPoolCreation(bop->getRHS())) {
194 Scopes.push_back(PoolScope());
195 Scopes.back().PoolVar = VD;
196 Scopes.back().CompoundParent = S;
197 Scopes.back().Begin = I;
206 if (isPoolDrain(Scopes.back().PoolVar, child)) {
207 PoolScope &scope = Scopes.back();
209 handlePoolScope(scope, S);
217 void clearUnavailableDiags(Stmt *S) {
219 Pass.TA.clearDiagnostic(diag::err_unavailable,
220 diag::err_unavailable_message,
221 S->getSourceRange());
226 CompoundStmt *CompoundParent;
227 Stmt::child_iterator Begin;
228 Stmt::child_iterator End;
229 bool IsFollowedBySimpleReturnStmt;
230 SmallVector<ObjCMessageExpr *, 4> Releases;
232 PoolScope() : PoolVar(0), CompoundParent(0), Begin(), End(),
233 IsFollowedBySimpleReturnStmt(false) { }
235 SourceRange getIndentedRange() const {
236 Stmt::child_iterator rangeS = Begin;
239 return SourceRange();
240 Stmt::child_iterator rangeE = Begin;
241 for (Stmt::child_iterator I = rangeS; I != End; ++I)
243 return SourceRange((*rangeS)->getLocStart(), (*rangeE)->getLocEnd());
247 class NameReferenceChecker : public RecursiveASTVisitor<NameReferenceChecker>{
249 SourceRange ScopeRange;
250 SourceLocation &referenceLoc, &declarationLoc;
253 NameReferenceChecker(ASTContext &ctx, PoolScope &scope,
254 SourceLocation &referenceLoc,
255 SourceLocation &declarationLoc)
256 : Ctx(ctx), referenceLoc(referenceLoc),
257 declarationLoc(declarationLoc) {
258 ScopeRange = SourceRange((*scope.Begin)->getLocStart(),
259 (*scope.End)->getLocStart());
262 bool VisitDeclRefExpr(DeclRefExpr *E) {
263 return checkRef(E->getLocation(), E->getDecl()->getLocation());
266 bool VisitTypedefTypeLoc(TypedefTypeLoc TL) {
267 return checkRef(TL.getBeginLoc(), TL.getTypedefNameDecl()->getLocation());
270 bool VisitTagTypeLoc(TagTypeLoc TL) {
271 return checkRef(TL.getBeginLoc(), TL.getDecl()->getLocation());
275 bool checkRef(SourceLocation refLoc, SourceLocation declLoc) {
276 if (isInScope(declLoc)) {
277 referenceLoc = refLoc;
278 declarationLoc = declLoc;
284 bool isInScope(SourceLocation loc) {
288 SourceManager &SM = Ctx.getSourceManager();
289 if (SM.isBeforeInTranslationUnit(loc, ScopeRange.getBegin()))
291 return SM.isBeforeInTranslationUnit(loc, ScopeRange.getEnd());
295 void handlePoolScope(PoolScope &scope, CompoundStmt *compoundS) {
296 // Check that all names declared inside the scope are not used
297 // outside the scope.
299 bool nameUsedOutsideScope = false;
300 SourceLocation referenceLoc, declarationLoc;
301 Stmt::child_iterator SI = scope.End, SE = compoundS->body_end();
303 // Check if the autoreleasepool scope is followed by a simple return
304 // statement, in which case we will include the return in the scope.
306 if (ReturnStmt *retS = dyn_cast<ReturnStmt>(*SI))
307 if ((retS->getRetValue() == 0 ||
308 isa<DeclRefExpr>(retS->getRetValue()->IgnoreParenCasts())) &&
309 findLocationAfterSemi(retS->getLocEnd(), Pass.Ctx).isValid()) {
310 scope.IsFollowedBySimpleReturnStmt = true;
311 ++SI; // the return will be included in scope, don't check it.
314 for (; SI != SE; ++SI) {
315 nameUsedOutsideScope = !NameReferenceChecker(Pass.Ctx, scope,
317 declarationLoc).TraverseStmt(*SI);
318 if (nameUsedOutsideScope)
322 // If not all references were cleared it means some variables/typenames/etc
323 // declared inside the pool scope are used outside of it.
324 // We won't try to rewrite the pool.
325 if (nameUsedOutsideScope) {
326 Pass.TA.reportError("a name is referenced outside the "
327 "NSAutoreleasePool scope that it was declared in", referenceLoc);
328 Pass.TA.reportNote("name declared here", declarationLoc);
329 Pass.TA.reportNote("intended @autoreleasepool scope begins here",
330 (*scope.Begin)->getLocStart());
331 Pass.TA.reportNote("intended @autoreleasepool scope ends here",
332 (*scope.End)->getLocStart());
337 // Collect all releases of the pool; they will be removed.
339 ReleaseCollector releaseColl(scope.PoolVar, scope.Releases);
340 Stmt::child_iterator I = scope.Begin;
342 for (; I != scope.End; ++I)
343 releaseColl.TraverseStmt(*I);
346 PoolVars[scope.PoolVar].Scopes.push_back(scope);
349 bool isPoolCreation(Expr *E) {
350 if (!E) return false;
352 ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E);
353 if (!ME) return false;
354 if (ME->getMethodFamily() == OMF_new &&
355 ME->getReceiverKind() == ObjCMessageExpr::Class &&
356 isNSAutoreleasePool(ME->getReceiverInterface()))
358 if (ME->getReceiverKind() == ObjCMessageExpr::Instance &&
359 ME->getMethodFamily() == OMF_init) {
360 Expr *rec = getEssential(ME->getInstanceReceiver());
361 if (ObjCMessageExpr *recME = dyn_cast_or_null<ObjCMessageExpr>(rec)) {
362 if (recME->getMethodFamily() == OMF_alloc &&
363 recME->getReceiverKind() == ObjCMessageExpr::Class &&
364 isNSAutoreleasePool(recME->getReceiverInterface()))
372 bool isPoolDrain(VarDecl *poolVar, Stmt *S) {
373 if (!S) return false;
375 ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S);
376 if (!ME) return false;
377 if (ME->getReceiverKind() == ObjCMessageExpr::Instance) {
378 Expr *rec = getEssential(ME->getInstanceReceiver());
379 if (DeclRefExpr *dref = dyn_cast<DeclRefExpr>(rec))
380 if (dref->getDecl() == poolVar)
381 return ME->getMethodFamily() == OMF_release ||
382 ME->getSelector() == DrainSel;
388 bool isNSAutoreleasePool(ObjCInterfaceDecl *IDecl) {
389 return IDecl && IDecl->getIdentifier() == PoolII;
392 bool isNSAutoreleasePool(QualType Ty) {
393 QualType pointee = Ty->getPointeeType();
394 if (pointee.isNull())
396 if (const ObjCInterfaceType *interT = pointee->getAs<ObjCInterfaceType>())
397 return isNSAutoreleasePool(interT->getDecl());
401 static Expr *getEssential(Expr *E) {
402 return cast<Expr>(getEssential((Stmt*)E));
404 static Stmt *getEssential(Stmt *S) {
405 if (ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(S))
406 S = EWC->getSubExpr();
407 if (Expr *E = dyn_cast<Expr>(S))
408 S = E->IgnoreParenCasts();
415 IdentifierInfo *PoolII;
421 SmallVector<PoolScope, 2> Scopes;
423 PoolVarInfo() : Dcl(0) { }
426 std::map<VarDecl *, PoolVarInfo> PoolVars;
429 } // anonymous namespace
431 void trans::rewriteAutoreleasePool(MigrationPass &pass) {
432 BodyTransform<AutoreleasePoolRewriter> trans(pass);
433 trans.TraverseDecl(pass.Ctx.getTranslationUnitDecl());