clang API Documentation

Transforms.cpp
Go to the documentation of this file.
00001 //===--- Transforms.cpp - Transformations to ARC mode ---------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 
00010 #include "Transforms.h"
00011 #include "Internals.h"
00012 #include "clang/AST/ASTContext.h"
00013 #include "clang/AST/RecursiveASTVisitor.h"
00014 #include "clang/AST/StmtVisitor.h"
00015 #include "clang/Analysis/DomainSpecific/CocoaConventions.h"
00016 #include "clang/Basic/SourceManager.h"
00017 #include "clang/Basic/TargetInfo.h"
00018 #include "clang/Lex/Lexer.h"
00019 #include "clang/Sema/Sema.h"
00020 #include "clang/Sema/SemaDiagnostic.h"
00021 #include "llvm/ADT/DenseSet.h"
00022 #include "llvm/ADT/StringSwitch.h"
00023 #include <map>
00024 
00025 using namespace clang;
00026 using namespace arcmt;
00027 using namespace trans;
00028 
00029 ASTTraverser::~ASTTraverser() { }
00030 
00031 bool MigrationPass::CFBridgingFunctionsDefined() {
00032   if (!EnableCFBridgeFns.hasValue())
00033     EnableCFBridgeFns = SemaRef.isKnownName("CFBridgingRetain") &&
00034                         SemaRef.isKnownName("CFBridgingRelease");
00035   return *EnableCFBridgeFns;
00036 }
00037 
00038 //===----------------------------------------------------------------------===//
00039 // Helpers.
00040 //===----------------------------------------------------------------------===//
00041 
00042 bool trans::canApplyWeak(ASTContext &Ctx, QualType type,
00043                          bool AllowOnUnknownClass) {
00044   if (!Ctx.getLangOpts().ObjCARCWeak)
00045     return false;
00046 
00047   QualType T = type;
00048   if (T.isNull())
00049     return false;
00050 
00051   // iOS is always safe to use 'weak'.
00052   if (Ctx.getTargetInfo().getTriple().isiOS())
00053     AllowOnUnknownClass = true;
00054 
00055   while (const PointerType *ptr = T->getAs<PointerType>())
00056     T = ptr->getPointeeType();
00057   if (const ObjCObjectPointerType *ObjT = T->getAs<ObjCObjectPointerType>()) {
00058     ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl();
00059     if (!AllowOnUnknownClass && (!Class || Class->getName() == "NSObject"))
00060       return false; // id/NSObject is not safe for weak.
00061     if (!AllowOnUnknownClass && !Class->hasDefinition())
00062       return false; // forward classes are not verifiable, therefore not safe.
00063     if (Class && Class->isArcWeakrefUnavailable())
00064       return false;
00065   }
00066 
00067   return true;
00068 }
00069 
00070 bool trans::isPlusOneAssign(const BinaryOperator *E) {
00071   if (E->getOpcode() != BO_Assign)
00072     return false;
00073 
00074   return isPlusOne(E->getRHS());
00075 }
00076 
00077 bool trans::isPlusOne(const Expr *E) {
00078   if (!E)
00079     return false;
00080   if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(E))
00081     E = EWC->getSubExpr();
00082 
00083   if (const ObjCMessageExpr *
00084         ME = dyn_cast<ObjCMessageExpr>(E->IgnoreParenCasts()))
00085     if (ME->getMethodFamily() == OMF_retain)
00086       return true;
00087 
00088   if (const CallExpr *
00089         callE = dyn_cast<CallExpr>(E->IgnoreParenCasts())) {
00090     if (const FunctionDecl *FD = callE->getDirectCallee()) {
00091       if (FD->hasAttr<CFReturnsRetainedAttr>())
00092         return true;
00093 
00094       if (FD->isGlobal() &&
00095           FD->getIdentifier() &&
00096           FD->getParent()->isTranslationUnit() &&
00097           FD->isExternallyVisible() &&
00098           ento::cocoa::isRefType(callE->getType(), "CF",
00099                                  FD->getIdentifier()->getName())) {
00100         StringRef fname = FD->getIdentifier()->getName();
00101         if (fname.endswith("Retain") ||
00102             fname.find("Create") != StringRef::npos ||
00103             fname.find("Copy") != StringRef::npos) {
00104           return true;
00105         }
00106       }
00107     }
00108   }
00109 
00110   const ImplicitCastExpr *implCE = dyn_cast<ImplicitCastExpr>(E);
00111   while (implCE && implCE->getCastKind() ==  CK_BitCast)
00112     implCE = dyn_cast<ImplicitCastExpr>(implCE->getSubExpr());
00113 
00114   if (implCE && implCE->getCastKind() == CK_ARCConsumeObject)
00115     return true;
00116 
00117   return false;
00118 }
00119 
00120 /// \brief 'Loc' is the end of a statement range. This returns the location
00121 /// immediately after the semicolon following the statement.
00122 /// If no semicolon is found or the location is inside a macro, the returned
00123 /// source location will be invalid.
00124 SourceLocation trans::findLocationAfterSemi(SourceLocation loc,
00125                                             ASTContext &Ctx, bool IsDecl) {
00126   SourceLocation SemiLoc = findSemiAfterLocation(loc, Ctx, IsDecl);
00127   if (SemiLoc.isInvalid())
00128     return SourceLocation();
00129   return SemiLoc.getLocWithOffset(1);
00130 }
00131 
00132 /// \brief \arg Loc is the end of a statement range. This returns the location
00133 /// of the semicolon following the statement.
00134 /// If no semicolon is found or the location is inside a macro, the returned
00135 /// source location will be invalid.
00136 SourceLocation trans::findSemiAfterLocation(SourceLocation loc,
00137                                             ASTContext &Ctx,
00138                                             bool IsDecl) {
00139   SourceManager &SM = Ctx.getSourceManager();
00140   if (loc.isMacroID()) {
00141     if (!Lexer::isAtEndOfMacroExpansion(loc, SM, Ctx.getLangOpts(), &loc))
00142       return SourceLocation();
00143   }
00144   loc = Lexer::getLocForEndOfToken(loc, /*Offset=*/0, SM, Ctx.getLangOpts());
00145 
00146   // Break down the source location.
00147   std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
00148 
00149   // Try to load the file buffer.
00150   bool invalidTemp = false;
00151   StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
00152   if (invalidTemp)
00153     return SourceLocation();
00154 
00155   const char *tokenBegin = file.data() + locInfo.second;
00156 
00157   // Lex from the start of the given location.
00158   Lexer lexer(SM.getLocForStartOfFile(locInfo.first),
00159               Ctx.getLangOpts(),
00160               file.begin(), tokenBegin, file.end());
00161   Token tok;
00162   lexer.LexFromRawLexer(tok);
00163   if (tok.isNot(tok::semi)) {
00164     if (!IsDecl)
00165       return SourceLocation();
00166     // Declaration may be followed with other tokens; such as an __attribute,
00167     // before ending with a semicolon.
00168     return findSemiAfterLocation(tok.getLocation(), Ctx, /*IsDecl*/true);
00169   }
00170 
00171   return tok.getLocation();
00172 }
00173 
00174 bool trans::hasSideEffects(Expr *E, ASTContext &Ctx) {
00175   if (!E || !E->HasSideEffects(Ctx))
00176     return false;
00177 
00178   E = E->IgnoreParenCasts();
00179   ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E);
00180   if (!ME)
00181     return true;
00182   switch (ME->getMethodFamily()) {
00183   case OMF_autorelease:
00184   case OMF_dealloc:
00185   case OMF_release:
00186   case OMF_retain:
00187     switch (ME->getReceiverKind()) {
00188     case ObjCMessageExpr::SuperInstance:
00189       return false;
00190     case ObjCMessageExpr::Instance:
00191       return hasSideEffects(ME->getInstanceReceiver(), Ctx);
00192     default:
00193       break;
00194     }
00195     break;
00196   default:
00197     break;
00198   }
00199 
00200   return true;
00201 }
00202 
00203 bool trans::isGlobalVar(Expr *E) {
00204   E = E->IgnoreParenCasts();
00205   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
00206     return DRE->getDecl()->getDeclContext()->isFileContext() &&
00207            DRE->getDecl()->isExternallyVisible();
00208   if (ConditionalOperator *condOp = dyn_cast<ConditionalOperator>(E))
00209     return isGlobalVar(condOp->getTrueExpr()) &&
00210            isGlobalVar(condOp->getFalseExpr());
00211 
00212   return false;  
00213 }
00214 
00215 StringRef trans::getNilString(ASTContext &Ctx) {
00216   if (Ctx.Idents.get("nil").hasMacroDefinition())
00217     return "nil";
00218   else
00219     return "0";
00220 }
00221 
00222 namespace {
00223 
00224 class ReferenceClear : public RecursiveASTVisitor<ReferenceClear> {
00225   ExprSet &Refs;
00226 public:
00227   ReferenceClear(ExprSet &refs) : Refs(refs) { }
00228   bool VisitDeclRefExpr(DeclRefExpr *E) { Refs.erase(E); return true; }
00229 };
00230 
00231 class ReferenceCollector : public RecursiveASTVisitor<ReferenceCollector> {
00232   ValueDecl *Dcl;
00233   ExprSet &Refs;
00234 
00235 public:
00236   ReferenceCollector(ValueDecl *D, ExprSet &refs)
00237     : Dcl(D), Refs(refs) { }
00238 
00239   bool VisitDeclRefExpr(DeclRefExpr *E) {
00240     if (E->getDecl() == Dcl)
00241       Refs.insert(E);
00242     return true;
00243   }
00244 };
00245 
00246 class RemovablesCollector : public RecursiveASTVisitor<RemovablesCollector> {
00247   ExprSet &Removables;
00248 
00249 public:
00250   RemovablesCollector(ExprSet &removables)
00251   : Removables(removables) { }
00252   
00253   bool shouldWalkTypesOfTypeLocs() const { return false; }
00254   
00255   bool TraverseStmtExpr(StmtExpr *E) {
00256     CompoundStmt *S = E->getSubStmt();
00257     for (CompoundStmt::body_iterator
00258         I = S->body_begin(), E = S->body_end(); I != E; ++I) {
00259       if (I != E - 1)
00260         mark(*I);
00261       TraverseStmt(*I);
00262     }
00263     return true;
00264   }
00265   
00266   bool VisitCompoundStmt(CompoundStmt *S) {
00267     for (auto *I : S->body())
00268       mark(I);
00269     return true;
00270   }
00271   
00272   bool VisitIfStmt(IfStmt *S) {
00273     mark(S->getThen());
00274     mark(S->getElse());
00275     return true;
00276   }
00277   
00278   bool VisitWhileStmt(WhileStmt *S) {
00279     mark(S->getBody());
00280     return true;
00281   }
00282   
00283   bool VisitDoStmt(DoStmt *S) {
00284     mark(S->getBody());
00285     return true;
00286   }
00287   
00288   bool VisitForStmt(ForStmt *S) {
00289     mark(S->getInit());
00290     mark(S->getInc());
00291     mark(S->getBody());
00292     return true;
00293   }
00294   
00295 private:
00296   void mark(Stmt *S) {
00297     if (!S) return;
00298     
00299     while (LabelStmt *Label = dyn_cast<LabelStmt>(S))
00300       S = Label->getSubStmt();
00301     S = S->IgnoreImplicit();
00302     if (Expr *E = dyn_cast<Expr>(S))
00303       Removables.insert(E);
00304   }
00305 };
00306 
00307 } // end anonymous namespace
00308 
00309 void trans::clearRefsIn(Stmt *S, ExprSet &refs) {
00310   ReferenceClear(refs).TraverseStmt(S);
00311 }
00312 
00313 void trans::collectRefs(ValueDecl *D, Stmt *S, ExprSet &refs) {
00314   ReferenceCollector(D, refs).TraverseStmt(S);
00315 }
00316 
00317 void trans::collectRemovables(Stmt *S, ExprSet &exprs) {
00318   RemovablesCollector(exprs).TraverseStmt(S);
00319 }
00320 
00321 //===----------------------------------------------------------------------===//
00322 // MigrationContext
00323 //===----------------------------------------------------------------------===//
00324 
00325 namespace {
00326 
00327 class ASTTransform : public RecursiveASTVisitor<ASTTransform> {
00328   MigrationContext &MigrateCtx;
00329   typedef RecursiveASTVisitor<ASTTransform> base;
00330 
00331 public:
00332   ASTTransform(MigrationContext &MigrateCtx) : MigrateCtx(MigrateCtx) { }
00333 
00334   bool shouldWalkTypesOfTypeLocs() const { return false; }
00335 
00336   bool TraverseObjCImplementationDecl(ObjCImplementationDecl *D) {
00337     ObjCImplementationContext ImplCtx(MigrateCtx, D);
00338     for (MigrationContext::traverser_iterator
00339            I = MigrateCtx.traversers_begin(),
00340            E = MigrateCtx.traversers_end(); I != E; ++I)
00341       (*I)->traverseObjCImplementation(ImplCtx);
00342 
00343     return base::TraverseObjCImplementationDecl(D);
00344   }
00345 
00346   bool TraverseStmt(Stmt *rootS) {
00347     if (!rootS)
00348       return true;
00349 
00350     BodyContext BodyCtx(MigrateCtx, rootS);
00351     for (MigrationContext::traverser_iterator
00352            I = MigrateCtx.traversers_begin(),
00353            E = MigrateCtx.traversers_end(); I != E; ++I)
00354       (*I)->traverseBody(BodyCtx);
00355 
00356     return true;
00357   }
00358 };
00359 
00360 }
00361 
00362 MigrationContext::~MigrationContext() {
00363   for (traverser_iterator
00364          I = traversers_begin(), E = traversers_end(); I != E; ++I)
00365     delete *I;
00366 }
00367 
00368 bool MigrationContext::isGCOwnedNonObjC(QualType T) {
00369   while (!T.isNull()) {
00370     if (const AttributedType *AttrT = T->getAs<AttributedType>()) {
00371       if (AttrT->getAttrKind() == AttributedType::attr_objc_ownership)
00372         return !AttrT->getModifiedType()->isObjCRetainableType();
00373     }
00374 
00375     if (T->isArrayType())
00376       T = Pass.Ctx.getBaseElementType(T);
00377     else if (const PointerType *PT = T->getAs<PointerType>())
00378       T = PT->getPointeeType();
00379     else if (const ReferenceType *RT = T->getAs<ReferenceType>())
00380       T = RT->getPointeeType();
00381     else
00382       break;
00383   }
00384 
00385   return false;
00386 }
00387 
00388 bool MigrationContext::rewritePropertyAttribute(StringRef fromAttr,
00389                                                 StringRef toAttr,
00390                                                 SourceLocation atLoc) {
00391   if (atLoc.isMacroID())
00392     return false;
00393 
00394   SourceManager &SM = Pass.Ctx.getSourceManager();
00395 
00396   // Break down the source location.
00397   std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(atLoc);
00398 
00399   // Try to load the file buffer.
00400   bool invalidTemp = false;
00401   StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
00402   if (invalidTemp)
00403     return false;
00404 
00405   const char *tokenBegin = file.data() + locInfo.second;
00406 
00407   // Lex from the start of the given location.
00408   Lexer lexer(SM.getLocForStartOfFile(locInfo.first),
00409               Pass.Ctx.getLangOpts(),
00410               file.begin(), tokenBegin, file.end());
00411   Token tok;
00412   lexer.LexFromRawLexer(tok);
00413   if (tok.isNot(tok::at)) return false;
00414   lexer.LexFromRawLexer(tok);
00415   if (tok.isNot(tok::raw_identifier)) return false;
00416   if (tok.getRawIdentifier() != "property")
00417     return false;
00418   lexer.LexFromRawLexer(tok);
00419   if (tok.isNot(tok::l_paren)) return false;
00420   
00421   Token BeforeTok = tok;
00422   Token AfterTok;
00423   AfterTok.startToken();
00424   SourceLocation AttrLoc;
00425   
00426   lexer.LexFromRawLexer(tok);
00427   if (tok.is(tok::r_paren))
00428     return false;
00429 
00430   while (1) {
00431     if (tok.isNot(tok::raw_identifier)) return false;
00432     if (tok.getRawIdentifier() == fromAttr) {
00433       if (!toAttr.empty()) {
00434         Pass.TA.replaceText(tok.getLocation(), fromAttr, toAttr);
00435         return true;
00436       }
00437       // We want to remove the attribute.
00438       AttrLoc = tok.getLocation();
00439     }
00440 
00441     do {
00442       lexer.LexFromRawLexer(tok);
00443       if (AttrLoc.isValid() && AfterTok.is(tok::unknown))
00444         AfterTok = tok;
00445     } while (tok.isNot(tok::comma) && tok.isNot(tok::r_paren));
00446     if (tok.is(tok::r_paren))
00447       break;
00448     if (AttrLoc.isInvalid())
00449       BeforeTok = tok;
00450     lexer.LexFromRawLexer(tok);
00451   }
00452 
00453   if (toAttr.empty() && AttrLoc.isValid() && AfterTok.isNot(tok::unknown)) {
00454     // We want to remove the attribute.
00455     if (BeforeTok.is(tok::l_paren) && AfterTok.is(tok::r_paren)) {
00456       Pass.TA.remove(SourceRange(BeforeTok.getLocation(),
00457                                  AfterTok.getLocation()));
00458     } else if (BeforeTok.is(tok::l_paren) && AfterTok.is(tok::comma)) {
00459       Pass.TA.remove(SourceRange(AttrLoc, AfterTok.getLocation()));
00460     } else {
00461       Pass.TA.remove(SourceRange(BeforeTok.getLocation(), AttrLoc));
00462     }
00463 
00464     return true;
00465   }
00466   
00467   return false;
00468 }
00469 
00470 bool MigrationContext::addPropertyAttribute(StringRef attr,
00471                                             SourceLocation atLoc) {
00472   if (atLoc.isMacroID())
00473     return false;
00474 
00475   SourceManager &SM = Pass.Ctx.getSourceManager();
00476 
00477   // Break down the source location.
00478   std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(atLoc);
00479 
00480   // Try to load the file buffer.
00481   bool invalidTemp = false;
00482   StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
00483   if (invalidTemp)
00484     return false;
00485 
00486   const char *tokenBegin = file.data() + locInfo.second;
00487 
00488   // Lex from the start of the given location.
00489   Lexer lexer(SM.getLocForStartOfFile(locInfo.first),
00490               Pass.Ctx.getLangOpts(),
00491               file.begin(), tokenBegin, file.end());
00492   Token tok;
00493   lexer.LexFromRawLexer(tok);
00494   if (tok.isNot(tok::at)) return false;
00495   lexer.LexFromRawLexer(tok);
00496   if (tok.isNot(tok::raw_identifier)) return false;
00497   if (tok.getRawIdentifier() != "property")
00498     return false;
00499   lexer.LexFromRawLexer(tok);
00500 
00501   if (tok.isNot(tok::l_paren)) {
00502     Pass.TA.insert(tok.getLocation(), std::string("(") + attr.str() + ") ");
00503     return true;
00504   }
00505   
00506   lexer.LexFromRawLexer(tok);
00507   if (tok.is(tok::r_paren)) {
00508     Pass.TA.insert(tok.getLocation(), attr);
00509     return true;
00510   }
00511 
00512   if (tok.isNot(tok::raw_identifier)) return false;
00513 
00514   Pass.TA.insert(tok.getLocation(), std::string(attr) + ", ");
00515   return true;
00516 }
00517 
00518 void MigrationContext::traverse(TranslationUnitDecl *TU) {
00519   for (traverser_iterator
00520          I = traversers_begin(), E = traversers_end(); I != E; ++I)
00521     (*I)->traverseTU(*this);
00522 
00523   ASTTransform(*this).TraverseDecl(TU);
00524 }
00525 
00526 static void GCRewriteFinalize(MigrationPass &pass) {
00527   ASTContext &Ctx = pass.Ctx;
00528   TransformActions &TA = pass.TA;
00529   DeclContext *DC = Ctx.getTranslationUnitDecl();
00530   Selector FinalizeSel =
00531    Ctx.Selectors.getNullarySelector(&pass.Ctx.Idents.get("finalize"));
00532   
00533   typedef DeclContext::specific_decl_iterator<ObjCImplementationDecl>
00534   impl_iterator;
00535   for (impl_iterator I = impl_iterator(DC->decls_begin()),
00536        E = impl_iterator(DC->decls_end()); I != E; ++I) {
00537     for (const auto *MD : I->instance_methods()) {
00538       if (!MD->hasBody())
00539         continue;
00540       
00541       if (MD->isInstanceMethod() && MD->getSelector() == FinalizeSel) {
00542         const ObjCMethodDecl *FinalizeM = MD;
00543         Transaction Trans(TA);
00544         TA.insert(FinalizeM->getSourceRange().getBegin(), 
00545                   "#if !__has_feature(objc_arc)\n");
00546         CharSourceRange::getTokenRange(FinalizeM->getSourceRange());
00547         const SourceManager &SM = pass.Ctx.getSourceManager();
00548         const LangOptions &LangOpts = pass.Ctx.getLangOpts();
00549         bool Invalid;
00550         std::string str = "\n#endif\n";
00551         str += Lexer::getSourceText(
00552                   CharSourceRange::getTokenRange(FinalizeM->getSourceRange()), 
00553                                     SM, LangOpts, &Invalid);
00554         TA.insertAfterToken(FinalizeM->getSourceRange().getEnd(), str);
00555         
00556         break;
00557       }
00558     }
00559   }
00560 }
00561 
00562 //===----------------------------------------------------------------------===//
00563 // getAllTransformations.
00564 //===----------------------------------------------------------------------===//
00565 
00566 static void traverseAST(MigrationPass &pass) {
00567   MigrationContext MigrateCtx(pass);
00568 
00569   if (pass.isGCMigration()) {
00570     MigrateCtx.addTraverser(new GCCollectableCallsTraverser);
00571     MigrateCtx.addTraverser(new GCAttrsTraverser());
00572   }
00573   MigrateCtx.addTraverser(new PropertyRewriteTraverser());
00574   MigrateCtx.addTraverser(new BlockObjCVariableTraverser());
00575   MigrateCtx.addTraverser(new ProtectedScopeTraverser());
00576 
00577   MigrateCtx.traverse(pass.Ctx.getTranslationUnitDecl());
00578 }
00579 
00580 static void independentTransforms(MigrationPass &pass) {
00581   rewriteAutoreleasePool(pass);
00582   removeRetainReleaseDeallocFinalize(pass);
00583   rewriteUnusedInitDelegate(pass);
00584   removeZeroOutPropsInDeallocFinalize(pass);
00585   makeAssignARCSafe(pass);
00586   rewriteUnbridgedCasts(pass);
00587   checkAPIUses(pass);
00588   traverseAST(pass);
00589 }
00590 
00591 std::vector<TransformFn> arcmt::getAllTransformations(
00592                                                LangOptions::GCMode OrigGCMode,
00593                                                bool NoFinalizeRemoval) {
00594   std::vector<TransformFn> transforms;
00595 
00596   if (OrigGCMode ==  LangOptions::GCOnly && NoFinalizeRemoval)
00597     transforms.push_back(GCRewriteFinalize);
00598   transforms.push_back(independentTransforms);
00599   // This depends on previous transformations removing various expressions.
00600   transforms.push_back(removeEmptyStatementsAndDeallocFinalize);
00601 
00602   return transforms;
00603 }