Transforms.cpp revision 57b1da1588a3f5785ad8bd5d9f2d795d685e1058
1//===--- Transforms.cpp - Transformations to ARC mode ---------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
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"
23#include <map>
24
25using namespace clang;
26using namespace arcmt;
27using namespace trans;
28
29ASTTraverser::~ASTTraverser() { }
30
31bool MigrationPass::CFBridgingFunctionsDefined() {
32  if (!EnableCFBridgeFns.hasValue())
33    EnableCFBridgeFns = SemaRef.isKnownName("CFBridgingRetain") &&
34                        SemaRef.isKnownName("CFBridgingRelease");
35  return *EnableCFBridgeFns;
36}
37
38//===----------------------------------------------------------------------===//
39// Helpers.
40//===----------------------------------------------------------------------===//
41
42bool trans::canApplyWeak(ASTContext &Ctx, QualType type,
43                         bool AllowOnUnknownClass) {
44  if (!Ctx.getLangOpts().ObjCARCWeak)
45    return false;
46
47  QualType T = type;
48  if (T.isNull())
49    return false;
50
51  // iOS is always safe to use 'weak'.
52  if (Ctx.getTargetInfo().getTriple().isiOS())
53    AllowOnUnknownClass = true;
54
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())
64      return false;
65  }
66
67  return true;
68}
69
70bool trans::isPlusOneAssign(const BinaryOperator *E) {
71  if (E->getOpcode() != BO_Assign)
72    return false;
73
74  return isPlusOne(E->getRHS());
75}
76
77bool trans::isPlusOne(const Expr *E) {
78  if (!E)
79    return false;
80  if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(E))
81    E = EWC->getSubExpr();
82
83  if (const ObjCMessageExpr *
84        ME = dyn_cast<ObjCMessageExpr>(E->IgnoreParenCasts()))
85    if (ME->getMethodFamily() == OMF_retain)
86      return true;
87
88  if (const CallExpr *
89        callE = dyn_cast<CallExpr>(E->IgnoreParenCasts())) {
90    if (const FunctionDecl *FD = callE->getDirectCallee()) {
91      if (FD->getAttr<CFReturnsRetainedAttr>())
92        return true;
93
94      if (FD->isGlobal() &&
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) {
104          return true;
105        }
106      }
107    }
108  }
109
110  const ImplicitCastExpr *implCE = dyn_cast<ImplicitCastExpr>(E);
111  while (implCE && implCE->getCastKind() ==  CK_BitCast)
112    implCE = dyn_cast<ImplicitCastExpr>(implCE->getSubExpr());
113
114  if (implCE && implCE->getCastKind() == CK_ARCConsumeObject)
115    return true;
116
117  return false;
118}
119
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.
124SourceLocation trans::findLocationAfterSemi(SourceLocation loc,
125                                            ASTContext &Ctx) {
126  SourceLocation SemiLoc = findSemiAfterLocation(loc, Ctx);
127  if (SemiLoc.isInvalid())
128    return SourceLocation();
129  return SemiLoc.getLocWithOffset(1);
130}
131
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.
136SourceLocation trans::findSemiAfterLocation(SourceLocation loc,
137                                            ASTContext &Ctx) {
138  SourceManager &SM = Ctx.getSourceManager();
139  if (loc.isMacroID()) {
140    if (!Lexer::isAtEndOfMacroExpansion(loc, SM, Ctx.getLangOpts(), &loc))
141      return SourceLocation();
142  }
143  loc = Lexer::getLocForEndOfToken(loc, /*Offset=*/0, SM, Ctx.getLangOpts());
144
145  // Break down the source location.
146  std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
147
148  // Try to load the file buffer.
149  bool invalidTemp = false;
150  StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
151  if (invalidTemp)
152    return SourceLocation();
153
154  const char *tokenBegin = file.data() + locInfo.second;
155
156  // Lex from the start of the given location.
157  Lexer lexer(SM.getLocForStartOfFile(locInfo.first),
158              Ctx.getLangOpts(),
159              file.begin(), tokenBegin, file.end());
160  Token tok;
161  lexer.LexFromRawLexer(tok);
162  if (tok.isNot(tok::semi))
163    return SourceLocation();
164
165  return tok.getLocation();
166}
167
168bool trans::hasSideEffects(Expr *E, ASTContext &Ctx) {
169  if (!E || !E->HasSideEffects(Ctx))
170    return false;
171
172  E = E->IgnoreParenCasts();
173  ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E);
174  if (!ME)
175    return true;
176  switch (ME->getMethodFamily()) {
177  case OMF_autorelease:
178  case OMF_dealloc:
179  case OMF_release:
180  case OMF_retain:
181    switch (ME->getReceiverKind()) {
182    case ObjCMessageExpr::SuperInstance:
183      return false;
184    case ObjCMessageExpr::Instance:
185      return hasSideEffects(ME->getInstanceReceiver(), Ctx);
186    default:
187      break;
188    }
189    break;
190  default:
191    break;
192  }
193
194  return true;
195}
196
197bool 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()->isExternallyVisible();
202  if (ConditionalOperator *condOp = dyn_cast<ConditionalOperator>(E))
203    return isGlobalVar(condOp->getTrueExpr()) &&
204           isGlobalVar(condOp->getFalseExpr());
205
206  return false;
207}
208
209StringRef trans::getNilString(ASTContext &Ctx) {
210  if (Ctx.Idents.get("nil").hasMacroDefinition())
211    return "nil";
212  else
213    return "0";
214}
215
216namespace {
217
218class ReferenceClear : public RecursiveASTVisitor<ReferenceClear> {
219  ExprSet &Refs;
220public:
221  ReferenceClear(ExprSet &refs) : Refs(refs) { }
222  bool VisitDeclRefExpr(DeclRefExpr *E) { Refs.erase(E); return true; }
223};
224
225class ReferenceCollector : public RecursiveASTVisitor<ReferenceCollector> {
226  ValueDecl *Dcl;
227  ExprSet &Refs;
228
229public:
230  ReferenceCollector(ValueDecl *D, ExprSet &refs)
231    : Dcl(D), Refs(refs) { }
232
233  bool VisitDeclRefExpr(DeclRefExpr *E) {
234    if (E->getDecl() == Dcl)
235      Refs.insert(E);
236    return true;
237  }
238};
239
240class RemovablesCollector : public RecursiveASTVisitor<RemovablesCollector> {
241  ExprSet &Removables;
242
243public:
244  RemovablesCollector(ExprSet &removables)
245  : Removables(removables) { }
246
247  bool shouldWalkTypesOfTypeLocs() const { return false; }
248
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) {
253      if (I != E - 1)
254        mark(*I);
255      TraverseStmt(*I);
256    }
257    return true;
258  }
259
260  bool VisitCompoundStmt(CompoundStmt *S) {
261    for (CompoundStmt::body_iterator
262        I = S->body_begin(), E = S->body_end(); I != E; ++I)
263      mark(*I);
264    return true;
265  }
266
267  bool VisitIfStmt(IfStmt *S) {
268    mark(S->getThen());
269    mark(S->getElse());
270    return true;
271  }
272
273  bool VisitWhileStmt(WhileStmt *S) {
274    mark(S->getBody());
275    return true;
276  }
277
278  bool VisitDoStmt(DoStmt *S) {
279    mark(S->getBody());
280    return true;
281  }
282
283  bool VisitForStmt(ForStmt *S) {
284    mark(S->getInit());
285    mark(S->getInc());
286    mark(S->getBody());
287    return true;
288  }
289
290private:
291  void mark(Stmt *S) {
292    if (!S) return;
293
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);
299  }
300};
301
302} // end anonymous namespace
303
304void trans::clearRefsIn(Stmt *S, ExprSet &refs) {
305  ReferenceClear(refs).TraverseStmt(S);
306}
307
308void trans::collectRefs(ValueDecl *D, Stmt *S, ExprSet &refs) {
309  ReferenceCollector(D, refs).TraverseStmt(S);
310}
311
312void trans::collectRemovables(Stmt *S, ExprSet &exprs) {
313  RemovablesCollector(exprs).TraverseStmt(S);
314}
315
316//===----------------------------------------------------------------------===//
317// MigrationContext
318//===----------------------------------------------------------------------===//
319
320namespace {
321
322class ASTTransform : public RecursiveASTVisitor<ASTTransform> {
323  MigrationContext &MigrateCtx;
324  typedef RecursiveASTVisitor<ASTTransform> base;
325
326public:
327  ASTTransform(MigrationContext &MigrateCtx) : MigrateCtx(MigrateCtx) { }
328
329  bool shouldWalkTypesOfTypeLocs() const { return false; }
330
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);
337
338    return base::TraverseObjCImplementationDecl(D);
339  }
340
341  bool TraverseStmt(Stmt *rootS) {
342    if (!rootS)
343      return true;
344
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);
350
351    return true;
352  }
353};
354
355}
356
357MigrationContext::~MigrationContext() {
358  for (traverser_iterator
359         I = traversers_begin(), E = traversers_end(); I != E; ++I)
360    delete *I;
361}
362
363bool 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();
368    }
369
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();
376    else
377      break;
378  }
379
380  return false;
381}
382
383bool MigrationContext::rewritePropertyAttribute(StringRef fromAttr,
384                                                StringRef toAttr,
385                                                SourceLocation atLoc) {
386  if (atLoc.isMacroID())
387    return false;
388
389  SourceManager &SM = Pass.Ctx.getSourceManager();
390
391  // Break down the source location.
392  std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(atLoc);
393
394  // Try to load the file buffer.
395  bool invalidTemp = false;
396  StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
397  if (invalidTemp)
398    return false;
399
400  const char *tokenBegin = file.data() + locInfo.second;
401
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());
406  Token tok;
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())
412        != "property")
413    return false;
414  lexer.LexFromRawLexer(tok);
415  if (tok.isNot(tok::l_paren)) return false;
416
417  Token BeforeTok = tok;
418  Token AfterTok;
419  AfterTok.startToken();
420  SourceLocation AttrLoc;
421
422  lexer.LexFromRawLexer(tok);
423  if (tok.is(tok::r_paren))
424    return false;
425
426  while (1) {
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);
432        return true;
433      }
434      // We want to remove the attribute.
435      AttrLoc = tok.getLocation();
436    }
437
438    do {
439      lexer.LexFromRawLexer(tok);
440      if (AttrLoc.isValid() && AfterTok.is(tok::unknown))
441        AfterTok = tok;
442    } while (tok.isNot(tok::comma) && tok.isNot(tok::r_paren));
443    if (tok.is(tok::r_paren))
444      break;
445    if (AttrLoc.isInvalid())
446      BeforeTok = tok;
447    lexer.LexFromRawLexer(tok);
448  }
449
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()));
457    } else {
458      Pass.TA.remove(SourceRange(BeforeTok.getLocation(), AttrLoc));
459    }
460
461    return true;
462  }
463
464  return false;
465}
466
467bool MigrationContext::addPropertyAttribute(StringRef attr,
468                                            SourceLocation atLoc) {
469  if (atLoc.isMacroID())
470    return false;
471
472  SourceManager &SM = Pass.Ctx.getSourceManager();
473
474  // Break down the source location.
475  std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(atLoc);
476
477  // Try to load the file buffer.
478  bool invalidTemp = false;
479  StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
480  if (invalidTemp)
481    return false;
482
483  const char *tokenBegin = file.data() + locInfo.second;
484
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());
489  Token tok;
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())
495        != "property")
496    return false;
497  lexer.LexFromRawLexer(tok);
498
499  if (tok.isNot(tok::l_paren)) {
500    Pass.TA.insert(tok.getLocation(), std::string("(") + attr.str() + ") ");
501    return true;
502  }
503
504  lexer.LexFromRawLexer(tok);
505  if (tok.is(tok::r_paren)) {
506    Pass.TA.insert(tok.getLocation(), attr);
507    return true;
508  }
509
510  if (tok.isNot(tok::raw_identifier)) return false;
511
512  Pass.TA.insert(tok.getLocation(), std::string(attr) + ", ");
513  return true;
514}
515
516void MigrationContext::traverse(TranslationUnitDecl *TU) {
517  for (traverser_iterator
518         I = traversers_begin(), E = traversers_end(); I != E; ++I)
519    (*I)->traverseTU(*this);
520
521  ASTTransform(*this).TraverseDecl(TU);
522}
523
524static 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"));
530
531  typedef DeclContext::specific_decl_iterator<ObjCImplementationDecl>
532  impl_iterator;
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;
539      if (!MD->hasBody())
540        continue;
541
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();
550        bool Invalid;
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);
556
557        break;
558      }
559    }
560  }
561}
562
563//===----------------------------------------------------------------------===//
564// getAllTransformations.
565//===----------------------------------------------------------------------===//
566
567static void traverseAST(MigrationPass &pass) {
568  MigrationContext MigrateCtx(pass);
569
570  if (pass.isGCMigration()) {
571    MigrateCtx.addTraverser(new GCCollectableCallsTraverser);
572    MigrateCtx.addTraverser(new GCAttrsTraverser());
573  }
574  MigrateCtx.addTraverser(new PropertyRewriteTraverser());
575  MigrateCtx.addTraverser(new BlockObjCVariableTraverser());
576  MigrateCtx.addTraverser(new ProtectedScopeTraverser());
577
578  MigrateCtx.traverse(pass.Ctx.getTranslationUnitDecl());
579}
580
581static void independentTransforms(MigrationPass &pass) {
582  rewriteAutoreleasePool(pass);
583  removeRetainReleaseDeallocFinalize(pass);
584  rewriteUnusedInitDelegate(pass);
585  removeZeroOutPropsInDeallocFinalize(pass);
586  makeAssignARCSafe(pass);
587  rewriteUnbridgedCasts(pass);
588  checkAPIUses(pass);
589  traverseAST(pass);
590}
591
592std::vector<TransformFn> arcmt::getAllTransformations(
593                                               LangOptions::GCMode OrigGCMode,
594                                               bool NoFinalizeRemoval) {
595  std::vector<TransformFn> transforms;
596
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);
602
603  return transforms;
604}
605