1 //===--- Transforms.cpp - Transformations 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 #include "Transforms.h"
11 #include "Internals.h"
12 #include "clang/AST/ASTContext.h"
13 #include "clang/AST/RecursiveASTVisitor.h"
14 #include "clang/AST/StmtVisitor.h"
15 #include "clang/Analysis/DomainSpecific/CocoaConventions.h"
16 #include "clang/Basic/SourceManager.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "clang/Lex/Lexer.h"
19 #include "clang/Sema/Sema.h"
20 #include "clang/Sema/SemaDiagnostic.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/StringSwitch.h"
25 using namespace clang;
26 using namespace arcmt;
27 using namespace trans;
29 ASTTraverser::~ASTTraverser() { }
31 bool MigrationPass::CFBridgingFunctionsDefined() {
32 if (!EnableCFBridgeFns.hasValue())
33 EnableCFBridgeFns = SemaRef.isKnownName("CFBridgingRetain") &&
34 SemaRef.isKnownName("CFBridgingRelease");
35 return *EnableCFBridgeFns;
38 //===----------------------------------------------------------------------===//
40 //===----------------------------------------------------------------------===//
42 bool trans::canApplyWeak(ASTContext &Ctx, QualType type,
43 bool AllowOnUnknownClass) {
44 if (!Ctx.getLangOpts().ObjCARCWeak)
51 // iOS is always safe to use 'weak'.
52 if (Ctx.getTargetInfo().getTriple().isiOS())
53 AllowOnUnknownClass = true;
55 while (const PointerType *ptr = T->getAs<PointerType>())
56 T = ptr->getPointeeType();
57 if (const ObjCObjectPointerType *ObjT = T->getAs<ObjCObjectPointerType>()) {
58 ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl();
59 if (!AllowOnUnknownClass && (!Class || Class->getName() == "NSObject"))
60 return false; // id/NSObject is not safe for weak.
61 if (!AllowOnUnknownClass && !Class->hasDefinition())
62 return false; // forward classes are not verifiable, therefore not safe.
63 if (Class && Class->isArcWeakrefUnavailable())
70 bool trans::isPlusOneAssign(const BinaryOperator *E) {
71 if (E->getOpcode() != BO_Assign)
74 return isPlusOne(E->getRHS());
77 bool trans::isPlusOne(const Expr *E) {
80 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(E))
81 E = EWC->getSubExpr();
83 if (const ObjCMessageExpr *
84 ME = dyn_cast<ObjCMessageExpr>(E->IgnoreParenCasts()))
85 if (ME->getMethodFamily() == OMF_retain)
89 callE = dyn_cast<CallExpr>(E->IgnoreParenCasts())) {
90 if (const FunctionDecl *FD = callE->getDirectCallee()) {
91 if (FD->getAttr<CFReturnsRetainedAttr>())
95 FD->getIdentifier() &&
96 FD->getParent()->isTranslationUnit() &&
97 FD->isExternallyVisible() &&
98 ento::cocoa::isRefType(callE->getType(), "CF",
99 FD->getIdentifier()->getName())) {
100 StringRef fname = FD->getIdentifier()->getName();
101 if (fname.endswith("Retain") ||
102 fname.find("Create") != StringRef::npos ||
103 fname.find("Copy") != StringRef::npos) {
110 const ImplicitCastExpr *implCE = dyn_cast<ImplicitCastExpr>(E);
111 while (implCE && implCE->getCastKind() == CK_BitCast)
112 implCE = dyn_cast<ImplicitCastExpr>(implCE->getSubExpr());
114 if (implCE && implCE->getCastKind() == CK_ARCConsumeObject)
120 /// \brief 'Loc' is the end of a statement range. This returns the location
121 /// immediately after the semicolon following the statement.
122 /// If no semicolon is found or the location is inside a macro, the returned
123 /// source location will be invalid.
124 SourceLocation trans::findLocationAfterSemi(SourceLocation loc,
125 ASTContext &Ctx, bool IsDecl) {
126 SourceLocation SemiLoc = findSemiAfterLocation(loc, Ctx, IsDecl);
127 if (SemiLoc.isInvalid())
128 return SourceLocation();
129 return SemiLoc.getLocWithOffset(1);
132 /// \brief \arg Loc is the end of a statement range. This returns the location
133 /// of the semicolon following the statement.
134 /// If no semicolon is found or the location is inside a macro, the returned
135 /// source location will be invalid.
136 SourceLocation trans::findSemiAfterLocation(SourceLocation loc,
139 SourceManager &SM = Ctx.getSourceManager();
140 if (loc.isMacroID()) {
141 if (!Lexer::isAtEndOfMacroExpansion(loc, SM, Ctx.getLangOpts(), &loc))
142 return SourceLocation();
144 loc = Lexer::getLocForEndOfToken(loc, /*Offset=*/0, SM, Ctx.getLangOpts());
146 // Break down the source location.
147 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
149 // Try to load the file buffer.
150 bool invalidTemp = false;
151 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
153 return SourceLocation();
155 const char *tokenBegin = file.data() + locInfo.second;
157 // Lex from the start of the given location.
158 Lexer lexer(SM.getLocForStartOfFile(locInfo.first),
160 file.begin(), tokenBegin, file.end());
162 lexer.LexFromRawLexer(tok);
163 if (tok.isNot(tok::semi)) {
165 return SourceLocation();
166 // Declaration may be followed with other tokens; such as an __attribute,
167 // before ending with a semicolon.
168 return findSemiAfterLocation(tok.getLocation(), Ctx, /*IsDecl*/true);
171 return tok.getLocation();
174 bool trans::hasSideEffects(Expr *E, ASTContext &Ctx) {
175 if (!E || !E->HasSideEffects(Ctx))
178 E = E->IgnoreParenCasts();
179 ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E);
182 switch (ME->getMethodFamily()) {
183 case OMF_autorelease:
187 switch (ME->getReceiverKind()) {
188 case ObjCMessageExpr::SuperInstance:
190 case ObjCMessageExpr::Instance:
191 return hasSideEffects(ME->getInstanceReceiver(), Ctx);
203 bool trans::isGlobalVar(Expr *E) {
204 E = E->IgnoreParenCasts();
205 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
206 return DRE->getDecl()->getDeclContext()->isFileContext() &&
207 DRE->getDecl()->isExternallyVisible();
208 if (ConditionalOperator *condOp = dyn_cast<ConditionalOperator>(E))
209 return isGlobalVar(condOp->getTrueExpr()) &&
210 isGlobalVar(condOp->getFalseExpr());
215 StringRef trans::getNilString(ASTContext &Ctx) {
216 if (Ctx.Idents.get("nil").hasMacroDefinition())
224 class ReferenceClear : public RecursiveASTVisitor<ReferenceClear> {
227 ReferenceClear(ExprSet &refs) : Refs(refs) { }
228 bool VisitDeclRefExpr(DeclRefExpr *E) { Refs.erase(E); return true; }
231 class ReferenceCollector : public RecursiveASTVisitor<ReferenceCollector> {
236 ReferenceCollector(ValueDecl *D, ExprSet &refs)
237 : Dcl(D), Refs(refs) { }
239 bool VisitDeclRefExpr(DeclRefExpr *E) {
240 if (E->getDecl() == Dcl)
246 class RemovablesCollector : public RecursiveASTVisitor<RemovablesCollector> {
250 RemovablesCollector(ExprSet &removables)
251 : Removables(removables) { }
253 bool shouldWalkTypesOfTypeLocs() const { return false; }
255 bool TraverseStmtExpr(StmtExpr *E) {
256 CompoundStmt *S = E->getSubStmt();
257 for (CompoundStmt::body_iterator
258 I = S->body_begin(), E = S->body_end(); I != E; ++I) {
266 bool VisitCompoundStmt(CompoundStmt *S) {
267 for (CompoundStmt::body_iterator
268 I = S->body_begin(), E = S->body_end(); I != E; ++I)
273 bool VisitIfStmt(IfStmt *S) {
279 bool VisitWhileStmt(WhileStmt *S) {
284 bool VisitDoStmt(DoStmt *S) {
289 bool VisitForStmt(ForStmt *S) {
300 while (LabelStmt *Label = dyn_cast<LabelStmt>(S))
301 S = Label->getSubStmt();
302 S = S->IgnoreImplicit();
303 if (Expr *E = dyn_cast<Expr>(S))
304 Removables.insert(E);
308 } // end anonymous namespace
310 void trans::clearRefsIn(Stmt *S, ExprSet &refs) {
311 ReferenceClear(refs).TraverseStmt(S);
314 void trans::collectRefs(ValueDecl *D, Stmt *S, ExprSet &refs) {
315 ReferenceCollector(D, refs).TraverseStmt(S);
318 void trans::collectRemovables(Stmt *S, ExprSet &exprs) {
319 RemovablesCollector(exprs).TraverseStmt(S);
322 //===----------------------------------------------------------------------===//
324 //===----------------------------------------------------------------------===//
328 class ASTTransform : public RecursiveASTVisitor<ASTTransform> {
329 MigrationContext &MigrateCtx;
330 typedef RecursiveASTVisitor<ASTTransform> base;
333 ASTTransform(MigrationContext &MigrateCtx) : MigrateCtx(MigrateCtx) { }
335 bool shouldWalkTypesOfTypeLocs() const { return false; }
337 bool TraverseObjCImplementationDecl(ObjCImplementationDecl *D) {
338 ObjCImplementationContext ImplCtx(MigrateCtx, D);
339 for (MigrationContext::traverser_iterator
340 I = MigrateCtx.traversers_begin(),
341 E = MigrateCtx.traversers_end(); I != E; ++I)
342 (*I)->traverseObjCImplementation(ImplCtx);
344 return base::TraverseObjCImplementationDecl(D);
347 bool TraverseStmt(Stmt *rootS) {
351 BodyContext BodyCtx(MigrateCtx, rootS);
352 for (MigrationContext::traverser_iterator
353 I = MigrateCtx.traversers_begin(),
354 E = MigrateCtx.traversers_end(); I != E; ++I)
355 (*I)->traverseBody(BodyCtx);
363 MigrationContext::~MigrationContext() {
364 for (traverser_iterator
365 I = traversers_begin(), E = traversers_end(); I != E; ++I)
369 bool MigrationContext::isGCOwnedNonObjC(QualType T) {
370 while (!T.isNull()) {
371 if (const AttributedType *AttrT = T->getAs<AttributedType>()) {
372 if (AttrT->getAttrKind() == AttributedType::attr_objc_ownership)
373 return !AttrT->getModifiedType()->isObjCRetainableType();
376 if (T->isArrayType())
377 T = Pass.Ctx.getBaseElementType(T);
378 else if (const PointerType *PT = T->getAs<PointerType>())
379 T = PT->getPointeeType();
380 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
381 T = RT->getPointeeType();
389 bool MigrationContext::rewritePropertyAttribute(StringRef fromAttr,
391 SourceLocation atLoc) {
392 if (atLoc.isMacroID())
395 SourceManager &SM = Pass.Ctx.getSourceManager();
397 // Break down the source location.
398 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(atLoc);
400 // Try to load the file buffer.
401 bool invalidTemp = false;
402 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
406 const char *tokenBegin = file.data() + locInfo.second;
408 // Lex from the start of the given location.
409 Lexer lexer(SM.getLocForStartOfFile(locInfo.first),
410 Pass.Ctx.getLangOpts(),
411 file.begin(), tokenBegin, file.end());
413 lexer.LexFromRawLexer(tok);
414 if (tok.isNot(tok::at)) return false;
415 lexer.LexFromRawLexer(tok);
416 if (tok.isNot(tok::raw_identifier)) return false;
417 if (StringRef(tok.getRawIdentifierData(), tok.getLength())
420 lexer.LexFromRawLexer(tok);
421 if (tok.isNot(tok::l_paren)) return false;
423 Token BeforeTok = tok;
425 AfterTok.startToken();
426 SourceLocation AttrLoc;
428 lexer.LexFromRawLexer(tok);
429 if (tok.is(tok::r_paren))
433 if (tok.isNot(tok::raw_identifier)) return false;
434 StringRef ident(tok.getRawIdentifierData(), tok.getLength());
435 if (ident == fromAttr) {
436 if (!toAttr.empty()) {
437 Pass.TA.replaceText(tok.getLocation(), fromAttr, toAttr);
440 // We want to remove the attribute.
441 AttrLoc = tok.getLocation();
445 lexer.LexFromRawLexer(tok);
446 if (AttrLoc.isValid() && AfterTok.is(tok::unknown))
448 } while (tok.isNot(tok::comma) && tok.isNot(tok::r_paren));
449 if (tok.is(tok::r_paren))
451 if (AttrLoc.isInvalid())
453 lexer.LexFromRawLexer(tok);
456 if (toAttr.empty() && AttrLoc.isValid() && AfterTok.isNot(tok::unknown)) {
457 // We want to remove the attribute.
458 if (BeforeTok.is(tok::l_paren) && AfterTok.is(tok::r_paren)) {
459 Pass.TA.remove(SourceRange(BeforeTok.getLocation(),
460 AfterTok.getLocation()));
461 } else if (BeforeTok.is(tok::l_paren) && AfterTok.is(tok::comma)) {
462 Pass.TA.remove(SourceRange(AttrLoc, AfterTok.getLocation()));
464 Pass.TA.remove(SourceRange(BeforeTok.getLocation(), AttrLoc));
473 bool MigrationContext::addPropertyAttribute(StringRef attr,
474 SourceLocation atLoc) {
475 if (atLoc.isMacroID())
478 SourceManager &SM = Pass.Ctx.getSourceManager();
480 // Break down the source location.
481 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(atLoc);
483 // Try to load the file buffer.
484 bool invalidTemp = false;
485 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
489 const char *tokenBegin = file.data() + locInfo.second;
491 // Lex from the start of the given location.
492 Lexer lexer(SM.getLocForStartOfFile(locInfo.first),
493 Pass.Ctx.getLangOpts(),
494 file.begin(), tokenBegin, file.end());
496 lexer.LexFromRawLexer(tok);
497 if (tok.isNot(tok::at)) return false;
498 lexer.LexFromRawLexer(tok);
499 if (tok.isNot(tok::raw_identifier)) return false;
500 if (StringRef(tok.getRawIdentifierData(), tok.getLength())
503 lexer.LexFromRawLexer(tok);
505 if (tok.isNot(tok::l_paren)) {
506 Pass.TA.insert(tok.getLocation(), std::string("(") + attr.str() + ") ");
510 lexer.LexFromRawLexer(tok);
511 if (tok.is(tok::r_paren)) {
512 Pass.TA.insert(tok.getLocation(), attr);
516 if (tok.isNot(tok::raw_identifier)) return false;
518 Pass.TA.insert(tok.getLocation(), std::string(attr) + ", ");
522 void MigrationContext::traverse(TranslationUnitDecl *TU) {
523 for (traverser_iterator
524 I = traversers_begin(), E = traversers_end(); I != E; ++I)
525 (*I)->traverseTU(*this);
527 ASTTransform(*this).TraverseDecl(TU);
530 static void GCRewriteFinalize(MigrationPass &pass) {
531 ASTContext &Ctx = pass.Ctx;
532 TransformActions &TA = pass.TA;
533 DeclContext *DC = Ctx.getTranslationUnitDecl();
534 Selector FinalizeSel =
535 Ctx.Selectors.getNullarySelector(&pass.Ctx.Idents.get("finalize"));
537 typedef DeclContext::specific_decl_iterator<ObjCImplementationDecl>
539 for (impl_iterator I = impl_iterator(DC->decls_begin()),
540 E = impl_iterator(DC->decls_end()); I != E; ++I) {
541 for (ObjCImplementationDecl::instmeth_iterator
542 MI = I->instmeth_begin(),
543 ME = I->instmeth_end(); MI != ME; ++MI) {
544 ObjCMethodDecl *MD = *MI;
548 if (MD->isInstanceMethod() && MD->getSelector() == FinalizeSel) {
549 ObjCMethodDecl *FinalizeM = MD;
550 Transaction Trans(TA);
551 TA.insert(FinalizeM->getSourceRange().getBegin(),
552 "#if !__has_feature(objc_arc)\n");
553 CharSourceRange::getTokenRange(FinalizeM->getSourceRange());
554 const SourceManager &SM = pass.Ctx.getSourceManager();
555 const LangOptions &LangOpts = pass.Ctx.getLangOpts();
557 std::string str = "\n#endif\n";
558 str += Lexer::getSourceText(
559 CharSourceRange::getTokenRange(FinalizeM->getSourceRange()),
560 SM, LangOpts, &Invalid);
561 TA.insertAfterToken(FinalizeM->getSourceRange().getEnd(), str);
569 //===----------------------------------------------------------------------===//
570 // getAllTransformations.
571 //===----------------------------------------------------------------------===//
573 static void traverseAST(MigrationPass &pass) {
574 MigrationContext MigrateCtx(pass);
576 if (pass.isGCMigration()) {
577 MigrateCtx.addTraverser(new GCCollectableCallsTraverser);
578 MigrateCtx.addTraverser(new GCAttrsTraverser());
580 MigrateCtx.addTraverser(new PropertyRewriteTraverser());
581 MigrateCtx.addTraverser(new BlockObjCVariableTraverser());
582 MigrateCtx.addTraverser(new ProtectedScopeTraverser());
584 MigrateCtx.traverse(pass.Ctx.getTranslationUnitDecl());
587 static void independentTransforms(MigrationPass &pass) {
588 rewriteAutoreleasePool(pass);
589 removeRetainReleaseDeallocFinalize(pass);
590 rewriteUnusedInitDelegate(pass);
591 removeZeroOutPropsInDeallocFinalize(pass);
592 makeAssignARCSafe(pass);
593 rewriteUnbridgedCasts(pass);
598 std::vector<TransformFn> arcmt::getAllTransformations(
599 LangOptions::GCMode OrigGCMode,
600 bool NoFinalizeRemoval) {
601 std::vector<TransformFn> transforms;
603 if (OrigGCMode == LangOptions::GCOnly && NoFinalizeRemoval)
604 transforms.push_back(GCRewriteFinalize);
605 transforms.push_back(independentTransforms);
606 // This depends on previous transformations removing various expressions.
607 transforms.push_back(removeEmptyStatementsAndDeallocFinalize);