Transforms.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  1. //===--- Transforms.cpp - Transformations to ARC mode ---------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "Transforms.h"
  9. #include "Internals.h"
  10. #include "clang/ARCMigrate/ARCMT.h"
  11. #include "clang/AST/ASTContext.h"
  12. #include "clang/AST/RecursiveASTVisitor.h"
  13. #include "clang/Analysis/DomainSpecific/CocoaConventions.h"
  14. #include "clang/Basic/SourceManager.h"
  15. #include "clang/Basic/TargetInfo.h"
  16. #include "clang/Lex/Lexer.h"
  17. #include "clang/Lex/Preprocessor.h"
  18. #include "clang/Sema/Sema.h"
  19. using namespace clang;
  20. using namespace arcmt;
  21. using namespace trans;
  22. ASTTraverser::~ASTTraverser() { }
  23. bool MigrationPass::CFBridgingFunctionsDefined() {
  24. if (!EnableCFBridgeFns)
  25. EnableCFBridgeFns = SemaRef.isKnownName("CFBridgingRetain") &&
  26. SemaRef.isKnownName("CFBridgingRelease");
  27. return *EnableCFBridgeFns;
  28. }
  29. //===----------------------------------------------------------------------===//
  30. // Helpers.
  31. //===----------------------------------------------------------------------===//
  32. bool trans::canApplyWeak(ASTContext &Ctx, QualType type,
  33. bool AllowOnUnknownClass) {
  34. if (!Ctx.getLangOpts().ObjCWeakRuntime)
  35. return false;
  36. QualType T = type;
  37. if (T.isNull())
  38. return false;
  39. // iOS is always safe to use 'weak'.
  40. if (Ctx.getTargetInfo().getTriple().isiOS() ||
  41. Ctx.getTargetInfo().getTriple().isWatchOS())
  42. AllowOnUnknownClass = true;
  43. while (const PointerType *ptr = T->getAs<PointerType>())
  44. T = ptr->getPointeeType();
  45. if (const ObjCObjectPointerType *ObjT = T->getAs<ObjCObjectPointerType>()) {
  46. ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl();
  47. if (!AllowOnUnknownClass && (!Class || Class->getName() == "NSObject"))
  48. return false; // id/NSObject is not safe for weak.
  49. if (!AllowOnUnknownClass && !Class->hasDefinition())
  50. return false; // forward classes are not verifiable, therefore not safe.
  51. if (Class && Class->isArcWeakrefUnavailable())
  52. return false;
  53. }
  54. return true;
  55. }
  56. bool trans::isPlusOneAssign(const BinaryOperator *E) {
  57. if (E->getOpcode() != BO_Assign)
  58. return false;
  59. return isPlusOne(E->getRHS());
  60. }
  61. bool trans::isPlusOne(const Expr *E) {
  62. if (!E)
  63. return false;
  64. if (const FullExpr *FE = dyn_cast<FullExpr>(E))
  65. E = FE->getSubExpr();
  66. if (const ObjCMessageExpr *
  67. ME = dyn_cast<ObjCMessageExpr>(E->IgnoreParenCasts()))
  68. if (ME->getMethodFamily() == OMF_retain)
  69. return true;
  70. if (const CallExpr *
  71. callE = dyn_cast<CallExpr>(E->IgnoreParenCasts())) {
  72. if (const FunctionDecl *FD = callE->getDirectCallee()) {
  73. if (FD->hasAttr<CFReturnsRetainedAttr>())
  74. return true;
  75. if (FD->isGlobal() &&
  76. FD->getIdentifier() &&
  77. FD->getParent()->isTranslationUnit() &&
  78. FD->isExternallyVisible() &&
  79. ento::cocoa::isRefType(callE->getType(), "CF",
  80. FD->getIdentifier()->getName())) {
  81. StringRef fname = FD->getIdentifier()->getName();
  82. if (fname.endswith("Retain") || fname.contains("Create") ||
  83. fname.contains("Copy"))
  84. return true;
  85. }
  86. }
  87. }
  88. const ImplicitCastExpr *implCE = dyn_cast<ImplicitCastExpr>(E);
  89. while (implCE && implCE->getCastKind() == CK_BitCast)
  90. implCE = dyn_cast<ImplicitCastExpr>(implCE->getSubExpr());
  91. return implCE && implCE->getCastKind() == CK_ARCConsumeObject;
  92. }
  93. /// 'Loc' is the end of a statement range. This returns the location
  94. /// immediately after the semicolon following the statement.
  95. /// If no semicolon is found or the location is inside a macro, the returned
  96. /// source location will be invalid.
  97. SourceLocation trans::findLocationAfterSemi(SourceLocation loc,
  98. ASTContext &Ctx, bool IsDecl) {
  99. SourceLocation SemiLoc = findSemiAfterLocation(loc, Ctx, IsDecl);
  100. if (SemiLoc.isInvalid())
  101. return SourceLocation();
  102. return SemiLoc.getLocWithOffset(1);
  103. }
  104. /// \arg Loc is the end of a statement range. This returns the location
  105. /// of the semicolon following the statement.
  106. /// If no semicolon is found or the location is inside a macro, the returned
  107. /// source location will be invalid.
  108. SourceLocation trans::findSemiAfterLocation(SourceLocation loc,
  109. ASTContext &Ctx,
  110. bool IsDecl) {
  111. SourceManager &SM = Ctx.getSourceManager();
  112. if (loc.isMacroID()) {
  113. if (!Lexer::isAtEndOfMacroExpansion(loc, SM, Ctx.getLangOpts(), &loc))
  114. return SourceLocation();
  115. }
  116. loc = Lexer::getLocForEndOfToken(loc, /*Offset=*/0, SM, Ctx.getLangOpts());
  117. // Break down the source location.
  118. std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
  119. // Try to load the file buffer.
  120. bool invalidTemp = false;
  121. StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
  122. if (invalidTemp)
  123. return SourceLocation();
  124. const char *tokenBegin = file.data() + locInfo.second;
  125. // Lex from the start of the given location.
  126. Lexer lexer(SM.getLocForStartOfFile(locInfo.first),
  127. Ctx.getLangOpts(),
  128. file.begin(), tokenBegin, file.end());
  129. Token tok;
  130. lexer.LexFromRawLexer(tok);
  131. if (tok.isNot(tok::semi)) {
  132. if (!IsDecl)
  133. return SourceLocation();
  134. // Declaration may be followed with other tokens; such as an __attribute,
  135. // before ending with a semicolon.
  136. return findSemiAfterLocation(tok.getLocation(), Ctx, /*IsDecl*/true);
  137. }
  138. return tok.getLocation();
  139. }
  140. bool trans::hasSideEffects(Expr *E, ASTContext &Ctx) {
  141. if (!E || !E->HasSideEffects(Ctx))
  142. return false;
  143. E = E->IgnoreParenCasts();
  144. ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E);
  145. if (!ME)
  146. return true;
  147. switch (ME->getMethodFamily()) {
  148. case OMF_autorelease:
  149. case OMF_dealloc:
  150. case OMF_release:
  151. case OMF_retain:
  152. switch (ME->getReceiverKind()) {
  153. case ObjCMessageExpr::SuperInstance:
  154. return false;
  155. case ObjCMessageExpr::Instance:
  156. return hasSideEffects(ME->getInstanceReceiver(), Ctx);
  157. default:
  158. break;
  159. }
  160. break;
  161. default:
  162. break;
  163. }
  164. return true;
  165. }
  166. bool trans::isGlobalVar(Expr *E) {
  167. E = E->IgnoreParenCasts();
  168. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  169. return DRE->getDecl()->getDeclContext()->isFileContext() &&
  170. DRE->getDecl()->isExternallyVisible();
  171. if (ConditionalOperator *condOp = dyn_cast<ConditionalOperator>(E))
  172. return isGlobalVar(condOp->getTrueExpr()) &&
  173. isGlobalVar(condOp->getFalseExpr());
  174. return false;
  175. }
  176. StringRef trans::getNilString(MigrationPass &Pass) {
  177. return Pass.SemaRef.PP.isMacroDefined("nil") ? "nil" : "0";
  178. }
  179. namespace {
  180. class ReferenceClear : public RecursiveASTVisitor<ReferenceClear> {
  181. ExprSet &Refs;
  182. public:
  183. ReferenceClear(ExprSet &refs) : Refs(refs) { }
  184. bool VisitDeclRefExpr(DeclRefExpr *E) { Refs.erase(E); return true; }
  185. };
  186. class ReferenceCollector : public RecursiveASTVisitor<ReferenceCollector> {
  187. ValueDecl *Dcl;
  188. ExprSet &Refs;
  189. public:
  190. ReferenceCollector(ValueDecl *D, ExprSet &refs)
  191. : Dcl(D), Refs(refs) { }
  192. bool VisitDeclRefExpr(DeclRefExpr *E) {
  193. if (E->getDecl() == Dcl)
  194. Refs.insert(E);
  195. return true;
  196. }
  197. };
  198. class RemovablesCollector : public RecursiveASTVisitor<RemovablesCollector> {
  199. ExprSet &Removables;
  200. public:
  201. RemovablesCollector(ExprSet &removables)
  202. : Removables(removables) { }
  203. bool shouldWalkTypesOfTypeLocs() const { return false; }
  204. bool TraverseStmtExpr(StmtExpr *E) {
  205. CompoundStmt *S = E->getSubStmt();
  206. for (CompoundStmt::body_iterator
  207. I = S->body_begin(), E = S->body_end(); I != E; ++I) {
  208. if (I != E - 1)
  209. mark(*I);
  210. TraverseStmt(*I);
  211. }
  212. return true;
  213. }
  214. bool VisitCompoundStmt(CompoundStmt *S) {
  215. for (auto *I : S->body())
  216. mark(I);
  217. return true;
  218. }
  219. bool VisitIfStmt(IfStmt *S) {
  220. mark(S->getThen());
  221. mark(S->getElse());
  222. return true;
  223. }
  224. bool VisitWhileStmt(WhileStmt *S) {
  225. mark(S->getBody());
  226. return true;
  227. }
  228. bool VisitDoStmt(DoStmt *S) {
  229. mark(S->getBody());
  230. return true;
  231. }
  232. bool VisitForStmt(ForStmt *S) {
  233. mark(S->getInit());
  234. mark(S->getInc());
  235. mark(S->getBody());
  236. return true;
  237. }
  238. private:
  239. void mark(Stmt *S) {
  240. if (!S) return;
  241. while (auto *Label = dyn_cast<LabelStmt>(S))
  242. S = Label->getSubStmt();
  243. if (auto *E = dyn_cast<Expr>(S))
  244. S = E->IgnoreImplicit();
  245. if (auto *E = dyn_cast<Expr>(S))
  246. Removables.insert(E);
  247. }
  248. };
  249. } // end anonymous namespace
  250. void trans::clearRefsIn(Stmt *S, ExprSet &refs) {
  251. ReferenceClear(refs).TraverseStmt(S);
  252. }
  253. void trans::collectRefs(ValueDecl *D, Stmt *S, ExprSet &refs) {
  254. ReferenceCollector(D, refs).TraverseStmt(S);
  255. }
  256. void trans::collectRemovables(Stmt *S, ExprSet &exprs) {
  257. RemovablesCollector(exprs).TraverseStmt(S);
  258. }
  259. //===----------------------------------------------------------------------===//
  260. // MigrationContext
  261. //===----------------------------------------------------------------------===//
  262. namespace {
  263. class ASTTransform : public RecursiveASTVisitor<ASTTransform> {
  264. MigrationContext &MigrateCtx;
  265. typedef RecursiveASTVisitor<ASTTransform> base;
  266. public:
  267. ASTTransform(MigrationContext &MigrateCtx) : MigrateCtx(MigrateCtx) { }
  268. bool shouldWalkTypesOfTypeLocs() const { return false; }
  269. bool TraverseObjCImplementationDecl(ObjCImplementationDecl *D) {
  270. ObjCImplementationContext ImplCtx(MigrateCtx, D);
  271. for (MigrationContext::traverser_iterator
  272. I = MigrateCtx.traversers_begin(),
  273. E = MigrateCtx.traversers_end(); I != E; ++I)
  274. (*I)->traverseObjCImplementation(ImplCtx);
  275. return base::TraverseObjCImplementationDecl(D);
  276. }
  277. bool TraverseStmt(Stmt *rootS) {
  278. if (!rootS)
  279. return true;
  280. BodyContext BodyCtx(MigrateCtx, rootS);
  281. for (MigrationContext::traverser_iterator
  282. I = MigrateCtx.traversers_begin(),
  283. E = MigrateCtx.traversers_end(); I != E; ++I)
  284. (*I)->traverseBody(BodyCtx);
  285. return true;
  286. }
  287. };
  288. }
  289. MigrationContext::~MigrationContext() {
  290. for (traverser_iterator
  291. I = traversers_begin(), E = traversers_end(); I != E; ++I)
  292. delete *I;
  293. }
  294. bool MigrationContext::isGCOwnedNonObjC(QualType T) {
  295. while (!T.isNull()) {
  296. if (const AttributedType *AttrT = T->getAs<AttributedType>()) {
  297. if (AttrT->getAttrKind() == attr::ObjCOwnership)
  298. return !AttrT->getModifiedType()->isObjCRetainableType();
  299. }
  300. if (T->isArrayType())
  301. T = Pass.Ctx.getBaseElementType(T);
  302. else if (const PointerType *PT = T->getAs<PointerType>())
  303. T = PT->getPointeeType();
  304. else if (const ReferenceType *RT = T->getAs<ReferenceType>())
  305. T = RT->getPointeeType();
  306. else
  307. break;
  308. }
  309. return false;
  310. }
  311. bool MigrationContext::rewritePropertyAttribute(StringRef fromAttr,
  312. StringRef toAttr,
  313. SourceLocation atLoc) {
  314. if (atLoc.isMacroID())
  315. return false;
  316. SourceManager &SM = Pass.Ctx.getSourceManager();
  317. // Break down the source location.
  318. std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(atLoc);
  319. // Try to load the file buffer.
  320. bool invalidTemp = false;
  321. StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
  322. if (invalidTemp)
  323. return false;
  324. const char *tokenBegin = file.data() + locInfo.second;
  325. // Lex from the start of the given location.
  326. Lexer lexer(SM.getLocForStartOfFile(locInfo.first),
  327. Pass.Ctx.getLangOpts(),
  328. file.begin(), tokenBegin, file.end());
  329. Token tok;
  330. lexer.LexFromRawLexer(tok);
  331. if (tok.isNot(tok::at)) return false;
  332. lexer.LexFromRawLexer(tok);
  333. if (tok.isNot(tok::raw_identifier)) return false;
  334. if (tok.getRawIdentifier() != "property")
  335. return false;
  336. lexer.LexFromRawLexer(tok);
  337. if (tok.isNot(tok::l_paren)) return false;
  338. Token BeforeTok = tok;
  339. Token AfterTok;
  340. AfterTok.startToken();
  341. SourceLocation AttrLoc;
  342. lexer.LexFromRawLexer(tok);
  343. if (tok.is(tok::r_paren))
  344. return false;
  345. while (true) {
  346. if (tok.isNot(tok::raw_identifier)) return false;
  347. if (tok.getRawIdentifier() == fromAttr) {
  348. if (!toAttr.empty()) {
  349. Pass.TA.replaceText(tok.getLocation(), fromAttr, toAttr);
  350. return true;
  351. }
  352. // We want to remove the attribute.
  353. AttrLoc = tok.getLocation();
  354. }
  355. do {
  356. lexer.LexFromRawLexer(tok);
  357. if (AttrLoc.isValid() && AfterTok.is(tok::unknown))
  358. AfterTok = tok;
  359. } while (tok.isNot(tok::comma) && tok.isNot(tok::r_paren));
  360. if (tok.is(tok::r_paren))
  361. break;
  362. if (AttrLoc.isInvalid())
  363. BeforeTok = tok;
  364. lexer.LexFromRawLexer(tok);
  365. }
  366. if (toAttr.empty() && AttrLoc.isValid() && AfterTok.isNot(tok::unknown)) {
  367. // We want to remove the attribute.
  368. if (BeforeTok.is(tok::l_paren) && AfterTok.is(tok::r_paren)) {
  369. Pass.TA.remove(SourceRange(BeforeTok.getLocation(),
  370. AfterTok.getLocation()));
  371. } else if (BeforeTok.is(tok::l_paren) && AfterTok.is(tok::comma)) {
  372. Pass.TA.remove(SourceRange(AttrLoc, AfterTok.getLocation()));
  373. } else {
  374. Pass.TA.remove(SourceRange(BeforeTok.getLocation(), AttrLoc));
  375. }
  376. return true;
  377. }
  378. return false;
  379. }
  380. bool MigrationContext::addPropertyAttribute(StringRef attr,
  381. SourceLocation atLoc) {
  382. if (atLoc.isMacroID())
  383. return false;
  384. SourceManager &SM = Pass.Ctx.getSourceManager();
  385. // Break down the source location.
  386. std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(atLoc);
  387. // Try to load the file buffer.
  388. bool invalidTemp = false;
  389. StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
  390. if (invalidTemp)
  391. return false;
  392. const char *tokenBegin = file.data() + locInfo.second;
  393. // Lex from the start of the given location.
  394. Lexer lexer(SM.getLocForStartOfFile(locInfo.first),
  395. Pass.Ctx.getLangOpts(),
  396. file.begin(), tokenBegin, file.end());
  397. Token tok;
  398. lexer.LexFromRawLexer(tok);
  399. if (tok.isNot(tok::at)) return false;
  400. lexer.LexFromRawLexer(tok);
  401. if (tok.isNot(tok::raw_identifier)) return false;
  402. if (tok.getRawIdentifier() != "property")
  403. return false;
  404. lexer.LexFromRawLexer(tok);
  405. if (tok.isNot(tok::l_paren)) {
  406. Pass.TA.insert(tok.getLocation(), std::string("(") + attr.str() + ") ");
  407. return true;
  408. }
  409. lexer.LexFromRawLexer(tok);
  410. if (tok.is(tok::r_paren)) {
  411. Pass.TA.insert(tok.getLocation(), attr);
  412. return true;
  413. }
  414. if (tok.isNot(tok::raw_identifier)) return false;
  415. Pass.TA.insert(tok.getLocation(), std::string(attr) + ", ");
  416. return true;
  417. }
  418. void MigrationContext::traverse(TranslationUnitDecl *TU) {
  419. for (traverser_iterator
  420. I = traversers_begin(), E = traversers_end(); I != E; ++I)
  421. (*I)->traverseTU(*this);
  422. ASTTransform(*this).TraverseDecl(TU);
  423. }
  424. static void GCRewriteFinalize(MigrationPass &pass) {
  425. ASTContext &Ctx = pass.Ctx;
  426. TransformActions &TA = pass.TA;
  427. DeclContext *DC = Ctx.getTranslationUnitDecl();
  428. Selector FinalizeSel =
  429. Ctx.Selectors.getNullarySelector(&pass.Ctx.Idents.get("finalize"));
  430. typedef DeclContext::specific_decl_iterator<ObjCImplementationDecl>
  431. impl_iterator;
  432. for (impl_iterator I = impl_iterator(DC->decls_begin()),
  433. E = impl_iterator(DC->decls_end()); I != E; ++I) {
  434. for (const auto *MD : I->instance_methods()) {
  435. if (!MD->hasBody())
  436. continue;
  437. if (MD->isInstanceMethod() && MD->getSelector() == FinalizeSel) {
  438. const ObjCMethodDecl *FinalizeM = MD;
  439. Transaction Trans(TA);
  440. TA.insert(FinalizeM->getSourceRange().getBegin(),
  441. "#if !__has_feature(objc_arc)\n");
  442. CharSourceRange::getTokenRange(FinalizeM->getSourceRange());
  443. const SourceManager &SM = pass.Ctx.getSourceManager();
  444. const LangOptions &LangOpts = pass.Ctx.getLangOpts();
  445. bool Invalid;
  446. std::string str = "\n#endif\n";
  447. str += Lexer::getSourceText(
  448. CharSourceRange::getTokenRange(FinalizeM->getSourceRange()),
  449. SM, LangOpts, &Invalid);
  450. TA.insertAfterToken(FinalizeM->getSourceRange().getEnd(), str);
  451. break;
  452. }
  453. }
  454. }
  455. }
  456. //===----------------------------------------------------------------------===//
  457. // getAllTransformations.
  458. //===----------------------------------------------------------------------===//
  459. static void traverseAST(MigrationPass &pass) {
  460. MigrationContext MigrateCtx(pass);
  461. if (pass.isGCMigration()) {
  462. MigrateCtx.addTraverser(new GCCollectableCallsTraverser);
  463. MigrateCtx.addTraverser(new GCAttrsTraverser());
  464. }
  465. MigrateCtx.addTraverser(new PropertyRewriteTraverser());
  466. MigrateCtx.addTraverser(new BlockObjCVariableTraverser());
  467. MigrateCtx.addTraverser(new ProtectedScopeTraverser());
  468. MigrateCtx.traverse(pass.Ctx.getTranslationUnitDecl());
  469. }
  470. static void independentTransforms(MigrationPass &pass) {
  471. rewriteAutoreleasePool(pass);
  472. removeRetainReleaseDeallocFinalize(pass);
  473. rewriteUnusedInitDelegate(pass);
  474. removeZeroOutPropsInDeallocFinalize(pass);
  475. makeAssignARCSafe(pass);
  476. rewriteUnbridgedCasts(pass);
  477. checkAPIUses(pass);
  478. traverseAST(pass);
  479. }
  480. std::vector<TransformFn> arcmt::getAllTransformations(
  481. LangOptions::GCMode OrigGCMode,
  482. bool NoFinalizeRemoval) {
  483. std::vector<TransformFn> transforms;
  484. if (OrigGCMode == LangOptions::GCOnly && NoFinalizeRemoval)
  485. transforms.push_back(GCRewriteFinalize);
  486. transforms.push_back(independentTransforms);
  487. // This depends on previous transformations removing various expressions.
  488. transforms.push_back(removeEmptyStatementsAndDeallocFinalize);
  489. return transforms;
  490. }