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().getOS() == llvm::Triple::IOS)
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->hasExternalLinkage() &&
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,
126 SourceLocation SemiLoc = findSemiAfterLocation(loc, Ctx);
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,
138 SourceManager &SM = Ctx.getSourceManager();
139 if (loc.isMacroID()) {
140 if (!Lexer::isAtEndOfMacroExpansion(loc, SM, Ctx.getLangOpts(), &loc))
141 return SourceLocation();
143 loc = Lexer::getLocForEndOfToken(loc, /*Offset=*/0, SM, Ctx.getLangOpts());
145 // Break down the source location.
146 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
148 // Try to load the file buffer.
149 bool invalidTemp = false;
150 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
152 return SourceLocation();
154 const char *tokenBegin = file.data() + locInfo.second;
156 // Lex from the start of the given location.
157 Lexer lexer(SM.getLocForStartOfFile(locInfo.first),
159 file.begin(), tokenBegin, file.end());
161 lexer.LexFromRawLexer(tok);
162 if (tok.isNot(tok::semi))
163 return SourceLocation();
165 return tok.getLocation();
168 bool trans::hasSideEffects(Expr *E, ASTContext &Ctx) {
169 if (!E || !E->HasSideEffects(Ctx))
172 E = E->IgnoreParenCasts();
173 ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E);
176 switch (ME->getMethodFamily()) {
177 case OMF_autorelease:
181 switch (ME->getReceiverKind()) {
182 case ObjCMessageExpr::SuperInstance:
184 case ObjCMessageExpr::Instance:
185 return hasSideEffects(ME->getInstanceReceiver(), Ctx);
197 bool trans::isGlobalVar(Expr *E) {
198 E = E->IgnoreParenCasts();
199 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
200 return DRE->getDecl()->getDeclContext()->isFileContext() &&
201 DRE->getDecl()->hasExternalLinkage();
202 if (ConditionalOperator *condOp = dyn_cast<ConditionalOperator>(E))
203 return isGlobalVar(condOp->getTrueExpr()) &&
204 isGlobalVar(condOp->getFalseExpr());
209 StringRef trans::getNilString(ASTContext &Ctx) {
210 if (Ctx.Idents.get("nil").hasMacroDefinition())
218 class ReferenceClear : public RecursiveASTVisitor<ReferenceClear> {
221 ReferenceClear(ExprSet &refs) : Refs(refs) { }
222 bool VisitDeclRefExpr(DeclRefExpr *E) { Refs.erase(E); return true; }
225 class ReferenceCollector : public RecursiveASTVisitor<ReferenceCollector> {
230 ReferenceCollector(ValueDecl *D, ExprSet &refs)
231 : Dcl(D), Refs(refs) { }
233 bool VisitDeclRefExpr(DeclRefExpr *E) {
234 if (E->getDecl() == Dcl)
240 class RemovablesCollector : public RecursiveASTVisitor<RemovablesCollector> {
244 RemovablesCollector(ExprSet &removables)
245 : Removables(removables) { }
247 bool shouldWalkTypesOfTypeLocs() const { return false; }
249 bool TraverseStmtExpr(StmtExpr *E) {
250 CompoundStmt *S = E->getSubStmt();
251 for (CompoundStmt::body_iterator
252 I = S->body_begin(), E = S->body_end(); I != E; ++I) {
260 bool VisitCompoundStmt(CompoundStmt *S) {
261 for (CompoundStmt::body_iterator
262 I = S->body_begin(), E = S->body_end(); I != E; ++I)
267 bool VisitIfStmt(IfStmt *S) {
273 bool VisitWhileStmt(WhileStmt *S) {
278 bool VisitDoStmt(DoStmt *S) {
283 bool VisitForStmt(ForStmt *S) {
294 while (LabelStmt *Label = dyn_cast<LabelStmt>(S))
295 S = Label->getSubStmt();
296 S = S->IgnoreImplicit();
297 if (Expr *E = dyn_cast<Expr>(S))
298 Removables.insert(E);
302 } // end anonymous namespace
304 void trans::clearRefsIn(Stmt *S, ExprSet &refs) {
305 ReferenceClear(refs).TraverseStmt(S);
308 void trans::collectRefs(ValueDecl *D, Stmt *S, ExprSet &refs) {
309 ReferenceCollector(D, refs).TraverseStmt(S);
312 void trans::collectRemovables(Stmt *S, ExprSet &exprs) {
313 RemovablesCollector(exprs).TraverseStmt(S);
316 //===----------------------------------------------------------------------===//
318 //===----------------------------------------------------------------------===//
322 class ASTTransform : public RecursiveASTVisitor<ASTTransform> {
323 MigrationContext &MigrateCtx;
324 typedef RecursiveASTVisitor<ASTTransform> base;
327 ASTTransform(MigrationContext &MigrateCtx) : MigrateCtx(MigrateCtx) { }
329 bool shouldWalkTypesOfTypeLocs() const { return false; }
331 bool TraverseObjCImplementationDecl(ObjCImplementationDecl *D) {
332 ObjCImplementationContext ImplCtx(MigrateCtx, D);
333 for (MigrationContext::traverser_iterator
334 I = MigrateCtx.traversers_begin(),
335 E = MigrateCtx.traversers_end(); I != E; ++I)
336 (*I)->traverseObjCImplementation(ImplCtx);
338 return base::TraverseObjCImplementationDecl(D);
341 bool TraverseStmt(Stmt *rootS) {
345 BodyContext BodyCtx(MigrateCtx, rootS);
346 for (MigrationContext::traverser_iterator
347 I = MigrateCtx.traversers_begin(),
348 E = MigrateCtx.traversers_end(); I != E; ++I)
349 (*I)->traverseBody(BodyCtx);
357 MigrationContext::~MigrationContext() {
358 for (traverser_iterator
359 I = traversers_begin(), E = traversers_end(); I != E; ++I)
363 bool MigrationContext::isGCOwnedNonObjC(QualType T) {
364 while (!T.isNull()) {
365 if (const AttributedType *AttrT = T->getAs<AttributedType>()) {
366 if (AttrT->getAttrKind() == AttributedType::attr_objc_ownership)
367 return !AttrT->getModifiedType()->isObjCRetainableType();
370 if (T->isArrayType())
371 T = Pass.Ctx.getBaseElementType(T);
372 else if (const PointerType *PT = T->getAs<PointerType>())
373 T = PT->getPointeeType();
374 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
375 T = RT->getPointeeType();
383 bool MigrationContext::rewritePropertyAttribute(StringRef fromAttr,
385 SourceLocation atLoc) {
386 if (atLoc.isMacroID())
389 SourceManager &SM = Pass.Ctx.getSourceManager();
391 // Break down the source location.
392 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(atLoc);
394 // Try to load the file buffer.
395 bool invalidTemp = false;
396 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
400 const char *tokenBegin = file.data() + locInfo.second;
402 // Lex from the start of the given location.
403 Lexer lexer(SM.getLocForStartOfFile(locInfo.first),
404 Pass.Ctx.getLangOpts(),
405 file.begin(), tokenBegin, file.end());
407 lexer.LexFromRawLexer(tok);
408 if (tok.isNot(tok::at)) return false;
409 lexer.LexFromRawLexer(tok);
410 if (tok.isNot(tok::raw_identifier)) return false;
411 if (StringRef(tok.getRawIdentifierData(), tok.getLength())
414 lexer.LexFromRawLexer(tok);
415 if (tok.isNot(tok::l_paren)) return false;
417 Token BeforeTok = tok;
419 AfterTok.startToken();
420 SourceLocation AttrLoc;
422 lexer.LexFromRawLexer(tok);
423 if (tok.is(tok::r_paren))
427 if (tok.isNot(tok::raw_identifier)) return false;
428 StringRef ident(tok.getRawIdentifierData(), tok.getLength());
429 if (ident == fromAttr) {
430 if (!toAttr.empty()) {
431 Pass.TA.replaceText(tok.getLocation(), fromAttr, toAttr);
434 // We want to remove the attribute.
435 AttrLoc = tok.getLocation();
439 lexer.LexFromRawLexer(tok);
440 if (AttrLoc.isValid() && AfterTok.is(tok::unknown))
442 } while (tok.isNot(tok::comma) && tok.isNot(tok::r_paren));
443 if (tok.is(tok::r_paren))
445 if (AttrLoc.isInvalid())
447 lexer.LexFromRawLexer(tok);
450 if (toAttr.empty() && AttrLoc.isValid() && AfterTok.isNot(tok::unknown)) {
451 // We want to remove the attribute.
452 if (BeforeTok.is(tok::l_paren) && AfterTok.is(tok::r_paren)) {
453 Pass.TA.remove(SourceRange(BeforeTok.getLocation(),
454 AfterTok.getLocation()));
455 } else if (BeforeTok.is(tok::l_paren) && AfterTok.is(tok::comma)) {
456 Pass.TA.remove(SourceRange(AttrLoc, AfterTok.getLocation()));
458 Pass.TA.remove(SourceRange(BeforeTok.getLocation(), AttrLoc));
467 bool MigrationContext::addPropertyAttribute(StringRef attr,
468 SourceLocation atLoc) {
469 if (atLoc.isMacroID())
472 SourceManager &SM = Pass.Ctx.getSourceManager();
474 // Break down the source location.
475 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(atLoc);
477 // Try to load the file buffer.
478 bool invalidTemp = false;
479 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
483 const char *tokenBegin = file.data() + locInfo.second;
485 // Lex from the start of the given location.
486 Lexer lexer(SM.getLocForStartOfFile(locInfo.first),
487 Pass.Ctx.getLangOpts(),
488 file.begin(), tokenBegin, file.end());
490 lexer.LexFromRawLexer(tok);
491 if (tok.isNot(tok::at)) return false;
492 lexer.LexFromRawLexer(tok);
493 if (tok.isNot(tok::raw_identifier)) return false;
494 if (StringRef(tok.getRawIdentifierData(), tok.getLength())
497 lexer.LexFromRawLexer(tok);
499 if (tok.isNot(tok::l_paren)) {
500 Pass.TA.insert(tok.getLocation(), std::string("(") + attr.str() + ") ");
504 lexer.LexFromRawLexer(tok);
505 if (tok.is(tok::r_paren)) {
506 Pass.TA.insert(tok.getLocation(), attr);
510 if (tok.isNot(tok::raw_identifier)) return false;
512 Pass.TA.insert(tok.getLocation(), std::string(attr) + ", ");
516 void MigrationContext::traverse(TranslationUnitDecl *TU) {
517 for (traverser_iterator
518 I = traversers_begin(), E = traversers_end(); I != E; ++I)
519 (*I)->traverseTU(*this);
521 ASTTransform(*this).TraverseDecl(TU);
524 static void GCRewriteFinalize(MigrationPass &pass) {
525 ASTContext &Ctx = pass.Ctx;
526 TransformActions &TA = pass.TA;
527 DeclContext *DC = Ctx.getTranslationUnitDecl();
528 Selector FinalizeSel =
529 Ctx.Selectors.getNullarySelector(&pass.Ctx.Idents.get("finalize"));
531 typedef DeclContext::specific_decl_iterator<ObjCImplementationDecl>
533 for (impl_iterator I = impl_iterator(DC->decls_begin()),
534 E = impl_iterator(DC->decls_end()); I != E; ++I) {
535 for (ObjCImplementationDecl::instmeth_iterator
536 MI = I->instmeth_begin(),
537 ME = I->instmeth_end(); MI != ME; ++MI) {
538 ObjCMethodDecl *MD = *MI;
542 if (MD->isInstanceMethod() && MD->getSelector() == FinalizeSel) {
543 ObjCMethodDecl *FinalizeM = MD;
544 Transaction Trans(TA);
545 TA.insert(FinalizeM->getSourceRange().getBegin(),
546 "#if !__has_feature(objc_arc)\n");
547 CharSourceRange::getTokenRange(FinalizeM->getSourceRange());
548 const SourceManager &SM = pass.Ctx.getSourceManager();
549 const LangOptions &LangOpts = pass.Ctx.getLangOpts();
551 std::string str = "\n#endif\n";
552 str += Lexer::getSourceText(
553 CharSourceRange::getTokenRange(FinalizeM->getSourceRange()),
554 SM, LangOpts, &Invalid);
555 TA.insertAfterToken(FinalizeM->getSourceRange().getEnd(), str);
563 //===----------------------------------------------------------------------===//
564 // getAllTransformations.
565 //===----------------------------------------------------------------------===//
567 static void traverseAST(MigrationPass &pass) {
568 MigrationContext MigrateCtx(pass);
570 if (pass.isGCMigration()) {
571 MigrateCtx.addTraverser(new GCCollectableCallsTraverser);
572 MigrateCtx.addTraverser(new GCAttrsTraverser());
574 MigrateCtx.addTraverser(new PropertyRewriteTraverser());
575 MigrateCtx.addTraverser(new BlockObjCVariableTraverser());
576 MigrateCtx.addTraverser(new ProtectedScopeTraverser());
578 MigrateCtx.traverse(pass.Ctx.getTranslationUnitDecl());
581 static void independentTransforms(MigrationPass &pass) {
582 rewriteAutoreleasePool(pass);
583 removeRetainReleaseDeallocFinalize(pass);
584 rewriteUnusedInitDelegate(pass);
585 removeZeroOutPropsInDeallocFinalize(pass);
586 makeAssignARCSafe(pass);
587 rewriteUnbridgedCasts(pass);
592 std::vector<TransformFn> arcmt::getAllTransformations(
593 LangOptions::GCMode OrigGCMode,
594 bool NoFinalizeRemoval) {
595 std::vector<TransformFn> transforms;
597 if (OrigGCMode == LangOptions::GCOnly && NoFinalizeRemoval)
598 transforms.push_back(GCRewriteFinalize);
599 transforms.push_back(independentTransforms);
600 // This depends on previous transformations removing various expressions.
601 transforms.push_back(removeEmptyStatementsAndDeallocFinalize);