Transforms.cpp revision 263508
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, bool IsDecl) {
126  SourceLocation SemiLoc = findSemiAfterLocation(loc, Ctx, IsDecl);
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                                            bool IsDecl) {
139  SourceManager &SM = Ctx.getSourceManager();
140  if (loc.isMacroID()) {
141    if (!Lexer::isAtEndOfMacroExpansion(loc, SM, Ctx.getLangOpts(), &loc))
142      return SourceLocation();
143  }
144  loc = Lexer::getLocForEndOfToken(loc, /*Offset=*/0, SM, Ctx.getLangOpts());
145
146  // Break down the source location.
147  std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
148
149  // Try to load the file buffer.
150  bool invalidTemp = false;
151  StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
152  if (invalidTemp)
153    return SourceLocation();
154
155  const char *tokenBegin = file.data() + locInfo.second;
156
157  // Lex from the start of the given location.
158  Lexer lexer(SM.getLocForStartOfFile(locInfo.first),
159              Ctx.getLangOpts(),
160              file.begin(), tokenBegin, file.end());
161  Token tok;
162  lexer.LexFromRawLexer(tok);
163  if (tok.isNot(tok::semi)) {
164    if (!IsDecl)
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);
169  }
170
171  return tok.getLocation();
172}
173
174bool trans::hasSideEffects(Expr *E, ASTContext &Ctx) {
175  if (!E || !E->HasSideEffects(Ctx))
176    return false;
177
178  E = E->IgnoreParenCasts();
179  ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E);
180  if (!ME)
181    return true;
182  switch (ME->getMethodFamily()) {
183  case OMF_autorelease:
184  case OMF_dealloc:
185  case OMF_release:
186  case OMF_retain:
187    switch (ME->getReceiverKind()) {
188    case ObjCMessageExpr::SuperInstance:
189      return false;
190    case ObjCMessageExpr::Instance:
191      return hasSideEffects(ME->getInstanceReceiver(), Ctx);
192    default:
193      break;
194    }
195    break;
196  default:
197    break;
198  }
199
200  return true;
201}
202
203bool 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());
211
212  return false;
213}
214
215StringRef trans::getNilString(ASTContext &Ctx) {
216  if (Ctx.Idents.get("nil").hasMacroDefinition())
217    return "nil";
218  else
219    return "0";
220}
221
222namespace {
223
224class ReferenceClear : public RecursiveASTVisitor<ReferenceClear> {
225  ExprSet &Refs;
226public:
227  ReferenceClear(ExprSet &refs) : Refs(refs) { }
228  bool VisitDeclRefExpr(DeclRefExpr *E) { Refs.erase(E); return true; }
229};
230
231class ReferenceCollector : public RecursiveASTVisitor<ReferenceCollector> {
232  ValueDecl *Dcl;
233  ExprSet &Refs;
234
235public:
236  ReferenceCollector(ValueDecl *D, ExprSet &refs)
237    : Dcl(D), Refs(refs) { }
238
239  bool VisitDeclRefExpr(DeclRefExpr *E) {
240    if (E->getDecl() == Dcl)
241      Refs.insert(E);
242    return true;
243  }
244};
245
246class RemovablesCollector : public RecursiveASTVisitor<RemovablesCollector> {
247  ExprSet &Removables;
248
249public:
250  RemovablesCollector(ExprSet &removables)
251  : Removables(removables) { }
252
253  bool shouldWalkTypesOfTypeLocs() const { return false; }
254
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) {
259      if (I != E - 1)
260        mark(*I);
261      TraverseStmt(*I);
262    }
263    return true;
264  }
265
266  bool VisitCompoundStmt(CompoundStmt *S) {
267    for (CompoundStmt::body_iterator
268        I = S->body_begin(), E = S->body_end(); I != E; ++I)
269      mark(*I);
270    return true;
271  }
272
273  bool VisitIfStmt(IfStmt *S) {
274    mark(S->getThen());
275    mark(S->getElse());
276    return true;
277  }
278
279  bool VisitWhileStmt(WhileStmt *S) {
280    mark(S->getBody());
281    return true;
282  }
283
284  bool VisitDoStmt(DoStmt *S) {
285    mark(S->getBody());
286    return true;
287  }
288
289  bool VisitForStmt(ForStmt *S) {
290    mark(S->getInit());
291    mark(S->getInc());
292    mark(S->getBody());
293    return true;
294  }
295
296private:
297  void mark(Stmt *S) {
298    if (!S) return;
299
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);
305  }
306};
307
308} // end anonymous namespace
309
310void trans::clearRefsIn(Stmt *S, ExprSet &refs) {
311  ReferenceClear(refs).TraverseStmt(S);
312}
313
314void trans::collectRefs(ValueDecl *D, Stmt *S, ExprSet &refs) {
315  ReferenceCollector(D, refs).TraverseStmt(S);
316}
317
318void trans::collectRemovables(Stmt *S, ExprSet &exprs) {
319  RemovablesCollector(exprs).TraverseStmt(S);
320}
321
322//===----------------------------------------------------------------------===//
323// MigrationContext
324//===----------------------------------------------------------------------===//
325
326namespace {
327
328class ASTTransform : public RecursiveASTVisitor<ASTTransform> {
329  MigrationContext &MigrateCtx;
330  typedef RecursiveASTVisitor<ASTTransform> base;
331
332public:
333  ASTTransform(MigrationContext &MigrateCtx) : MigrateCtx(MigrateCtx) { }
334
335  bool shouldWalkTypesOfTypeLocs() const { return false; }
336
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);
343
344    return base::TraverseObjCImplementationDecl(D);
345  }
346
347  bool TraverseStmt(Stmt *rootS) {
348    if (!rootS)
349      return true;
350
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);
356
357    return true;
358  }
359};
360
361}
362
363MigrationContext::~MigrationContext() {
364  for (traverser_iterator
365         I = traversers_begin(), E = traversers_end(); I != E; ++I)
366    delete *I;
367}
368
369bool 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();
374    }
375
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();
382    else
383      break;
384  }
385
386  return false;
387}
388
389bool MigrationContext::rewritePropertyAttribute(StringRef fromAttr,
390                                                StringRef toAttr,
391                                                SourceLocation atLoc) {
392  if (atLoc.isMacroID())
393    return false;
394
395  SourceManager &SM = Pass.Ctx.getSourceManager();
396
397  // Break down the source location.
398  std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(atLoc);
399
400  // Try to load the file buffer.
401  bool invalidTemp = false;
402  StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
403  if (invalidTemp)
404    return false;
405
406  const char *tokenBegin = file.data() + locInfo.second;
407
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());
412  Token tok;
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())
418        != "property")
419    return false;
420  lexer.LexFromRawLexer(tok);
421  if (tok.isNot(tok::l_paren)) return false;
422
423  Token BeforeTok = tok;
424  Token AfterTok;
425  AfterTok.startToken();
426  SourceLocation AttrLoc;
427
428  lexer.LexFromRawLexer(tok);
429  if (tok.is(tok::r_paren))
430    return false;
431
432  while (1) {
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);
438        return true;
439      }
440      // We want to remove the attribute.
441      AttrLoc = tok.getLocation();
442    }
443
444    do {
445      lexer.LexFromRawLexer(tok);
446      if (AttrLoc.isValid() && AfterTok.is(tok::unknown))
447        AfterTok = tok;
448    } while (tok.isNot(tok::comma) && tok.isNot(tok::r_paren));
449    if (tok.is(tok::r_paren))
450      break;
451    if (AttrLoc.isInvalid())
452      BeforeTok = tok;
453    lexer.LexFromRawLexer(tok);
454  }
455
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()));
463    } else {
464      Pass.TA.remove(SourceRange(BeforeTok.getLocation(), AttrLoc));
465    }
466
467    return true;
468  }
469
470  return false;
471}
472
473bool MigrationContext::addPropertyAttribute(StringRef attr,
474                                            SourceLocation atLoc) {
475  if (atLoc.isMacroID())
476    return false;
477
478  SourceManager &SM = Pass.Ctx.getSourceManager();
479
480  // Break down the source location.
481  std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(atLoc);
482
483  // Try to load the file buffer.
484  bool invalidTemp = false;
485  StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
486  if (invalidTemp)
487    return false;
488
489  const char *tokenBegin = file.data() + locInfo.second;
490
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());
495  Token tok;
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())
501        != "property")
502    return false;
503  lexer.LexFromRawLexer(tok);
504
505  if (tok.isNot(tok::l_paren)) {
506    Pass.TA.insert(tok.getLocation(), std::string("(") + attr.str() + ") ");
507    return true;
508  }
509
510  lexer.LexFromRawLexer(tok);
511  if (tok.is(tok::r_paren)) {
512    Pass.TA.insert(tok.getLocation(), attr);
513    return true;
514  }
515
516  if (tok.isNot(tok::raw_identifier)) return false;
517
518  Pass.TA.insert(tok.getLocation(), std::string(attr) + ", ");
519  return true;
520}
521
522void MigrationContext::traverse(TranslationUnitDecl *TU) {
523  for (traverser_iterator
524         I = traversers_begin(), E = traversers_end(); I != E; ++I)
525    (*I)->traverseTU(*this);
526
527  ASTTransform(*this).TraverseDecl(TU);
528}
529
530static 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"));
536
537  typedef DeclContext::specific_decl_iterator<ObjCImplementationDecl>
538  impl_iterator;
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;
545      if (!MD->hasBody())
546        continue;
547
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();
556        bool Invalid;
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);
562
563        break;
564      }
565    }
566  }
567}
568
569//===----------------------------------------------------------------------===//
570// getAllTransformations.
571//===----------------------------------------------------------------------===//
572
573static void traverseAST(MigrationPass &pass) {
574  MigrationContext MigrateCtx(pass);
575
576  if (pass.isGCMigration()) {
577    MigrateCtx.addTraverser(new GCCollectableCallsTraverser);
578    MigrateCtx.addTraverser(new GCAttrsTraverser());
579  }
580  MigrateCtx.addTraverser(new PropertyRewriteTraverser());
581  MigrateCtx.addTraverser(new BlockObjCVariableTraverser());
582  MigrateCtx.addTraverser(new ProtectedScopeTraverser());
583
584  MigrateCtx.traverse(pass.Ctx.getTranslationUnitDecl());
585}
586
587static void independentTransforms(MigrationPass &pass) {
588  rewriteAutoreleasePool(pass);
589  removeRetainReleaseDeallocFinalize(pass);
590  rewriteUnusedInitDelegate(pass);
591  removeZeroOutPropsInDeallocFinalize(pass);
592  makeAssignARCSafe(pass);
593  rewriteUnbridgedCasts(pass);
594  checkAPIUses(pass);
595  traverseAST(pass);
596}
597
598std::vector<TransformFn> arcmt::getAllTransformations(
599                                               LangOptions::GCMode OrigGCMode,
600                                               bool NoFinalizeRemoval) {
601  std::vector<TransformFn> transforms;
602
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);
608
609  return transforms;
610}
611