blob: 86812a5f8771359726940b01081c0840be1d7b57 [file] [log] [blame]
John McCall8f0e8d22011-06-15 23:25:17 +00001//===--- Tranforms.cpp - Tranformations 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//===----------------------------------------------------------------------===//
John McCall8f0e8d22011-06-15 23:25:17 +00009
Argyrios Kyrtzidis7196d062011-06-21 20:20:39 +000010#include "Transforms.h"
John McCall8f0e8d22011-06-15 23:25:17 +000011#include "Internals.h"
12#include "clang/Sema/SemaDiagnostic.h"
13#include "clang/AST/RecursiveASTVisitor.h"
14#include "clang/AST/StmtVisitor.h"
John McCall8f0e8d22011-06-15 23:25:17 +000015#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
16#include "clang/Lex/Lexer.h"
17#include "clang/Basic/SourceManager.h"
18#include "llvm/ADT/StringSwitch.h"
19#include "llvm/ADT/DenseSet.h"
20#include <map>
21
22using namespace clang;
23using namespace arcmt;
Argyrios Kyrtzidis7196d062011-06-21 20:20:39 +000024using namespace trans;
John McCall8f0e8d22011-06-15 23:25:17 +000025
Argyrios Kyrtzidise0ac7452011-11-04 15:58:08 +000026ASTTraverser::~ASTTraverser() { }
27
John McCall8f0e8d22011-06-15 23:25:17 +000028//===----------------------------------------------------------------------===//
Argyrios Kyrtzidis7196d062011-06-21 20:20:39 +000029// Helpers.
John McCall8f0e8d22011-06-15 23:25:17 +000030//===----------------------------------------------------------------------===//
31
Argyrios Kyrtzidis86625b52011-07-12 22:05:17 +000032/// \brief True if the class is one that does not support weak.
33static bool isClassInWeakBlacklist(ObjCInterfaceDecl *cls) {
34 if (!cls)
35 return false;
36
37 bool inList = llvm::StringSwitch<bool>(cls->getName())
38 .Case("NSColorSpace", true)
39 .Case("NSFont", true)
40 .Case("NSFontPanel", true)
41 .Case("NSImage", true)
42 .Case("NSLazyBrowserCell", true)
43 .Case("NSWindow", true)
44 .Case("NSWindowController", true)
45 .Case("NSMenuView", true)
46 .Case("NSPersistentUIWindowInfo", true)
47 .Case("NSTableCellView", true)
48 .Case("NSATSTypeSetter", true)
49 .Case("NSATSGlyphStorage", true)
50 .Case("NSLineFragmentRenderingContext", true)
51 .Case("NSAttributeDictionary", true)
52 .Case("NSParagraphStyle", true)
53 .Case("NSTextTab", true)
54 .Case("NSSimpleHorizontalTypesetter", true)
55 .Case("_NSCachedAttributedString", true)
56 .Case("NSStringDrawingTextStorage", true)
57 .Case("NSTextView", true)
58 .Case("NSSubTextStorage", true)
59 .Default(false);
60
61 if (inList)
62 return true;
63
64 return isClassInWeakBlacklist(cls->getSuperClass());
65}
66
Argyrios Kyrtzidis12192cf2011-11-07 18:40:29 +000067bool trans::canApplyWeak(ASTContext &Ctx, QualType type,
68 bool AllowOnUnknownClass) {
Argyrios Kyrtzidis86625b52011-07-12 22:05:17 +000069 if (!Ctx.getLangOptions().ObjCRuntimeHasWeak)
70 return false;
71
72 QualType T = type;
Argyrios Kyrtzidisb0e1e122011-11-07 18:46:46 +000073 if (T.isNull())
74 return false;
75
Argyrios Kyrtzidis86625b52011-07-12 22:05:17 +000076 while (const PointerType *ptr = T->getAs<PointerType>())
77 T = ptr->getPointeeType();
78 if (const ObjCObjectPointerType *ObjT = T->getAs<ObjCObjectPointerType>()) {
79 ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl();
Argyrios Kyrtzidis12192cf2011-11-07 18:40:29 +000080 if (!AllowOnUnknownClass && (!Class || Class->getName() == "NSObject"))
Argyrios Kyrtzidis86625b52011-07-12 22:05:17 +000081 return false; // id/NSObject is not safe for weak.
Argyrios Kyrtzidis12192cf2011-11-07 18:40:29 +000082 if (!AllowOnUnknownClass && Class->isForwardDecl())
Argyrios Kyrtzidis5363e8d2011-07-12 22:16:25 +000083 return false; // forward classes are not verifiable, therefore not safe.
Argyrios Kyrtzidis86625b52011-07-12 22:05:17 +000084 if (Class->isArcWeakrefUnavailable())
85 return false;
86 if (isClassInWeakBlacklist(Class))
87 return false;
88 }
89
90 return true;
91}
92
Argyrios Kyrtzidis7196d062011-06-21 20:20:39 +000093/// \brief '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.
97SourceLocation trans::findLocationAfterSemi(SourceLocation loc,
98 ASTContext &Ctx) {
Argyrios Kyrtzidisaec230d2011-09-01 20:53:18 +000099 SourceLocation SemiLoc = findSemiAfterLocation(loc, Ctx);
100 if (SemiLoc.isInvalid())
101 return SourceLocation();
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000102 return SemiLoc.getLocWithOffset(1);
Argyrios Kyrtzidisaec230d2011-09-01 20:53:18 +0000103}
104
105/// \brief \arg Loc is the end of a statement range. This returns the location
106/// of the semicolon following the statement.
107/// If no semicolon is found or the location is inside a macro, the returned
108/// source location will be invalid.
109SourceLocation trans::findSemiAfterLocation(SourceLocation loc,
110 ASTContext &Ctx) {
Argyrios Kyrtzidis7196d062011-06-21 20:20:39 +0000111 SourceManager &SM = Ctx.getSourceManager();
112 if (loc.isMacroID()) {
Chandler Carruth433db062011-07-14 08:20:40 +0000113 if (!Lexer::isAtEndOfMacroExpansion(loc, SM, Ctx.getLangOptions()))
Argyrios Kyrtzidis7196d062011-06-21 20:20:39 +0000114 return SourceLocation();
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000115 loc = SM.getExpansionRange(loc).second;
Argyrios Kyrtzidis7196d062011-06-21 20:20:39 +0000116 }
117 loc = Lexer::getLocForEndOfToken(loc, /*Offset=*/0, SM, Ctx.getLangOptions());
118
119 // Break down the source location.
120 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
121
122 // Try to load the file buffer.
123 bool invalidTemp = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000124 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
Argyrios Kyrtzidis7196d062011-06-21 20:20:39 +0000125 if (invalidTemp)
126 return SourceLocation();
127
128 const char *tokenBegin = file.data() + locInfo.second;
129
130 // Lex from the start of the given location.
131 Lexer lexer(SM.getLocForStartOfFile(locInfo.first),
132 Ctx.getLangOptions(),
133 file.begin(), tokenBegin, file.end());
134 Token tok;
135 lexer.LexFromRawLexer(tok);
136 if (tok.isNot(tok::semi))
137 return SourceLocation();
138
Argyrios Kyrtzidisaec230d2011-09-01 20:53:18 +0000139 return tok.getLocation();
Argyrios Kyrtzidis7196d062011-06-21 20:20:39 +0000140}
141
142bool trans::hasSideEffects(Expr *E, ASTContext &Ctx) {
143 if (!E || !E->HasSideEffects(Ctx))
144 return false;
145
146 E = E->IgnoreParenCasts();
147 ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E);
148 if (!ME)
149 return true;
150 switch (ME->getMethodFamily()) {
151 case OMF_autorelease:
152 case OMF_dealloc:
153 case OMF_release:
154 case OMF_retain:
155 switch (ME->getReceiverKind()) {
156 case ObjCMessageExpr::SuperInstance:
157 return false;
158 case ObjCMessageExpr::Instance:
159 return hasSideEffects(ME->getInstanceReceiver(), Ctx);
160 default:
161 break;
162 }
163 break;
164 default:
165 break;
166 }
167
168 return true;
169}
170
Argyrios Kyrtzidis2c18ca02011-07-14 23:32:04 +0000171bool trans::isGlobalVar(Expr *E) {
172 E = E->IgnoreParenCasts();
173 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Argyrios Kyrtzidis18fd0c62011-07-27 05:28:18 +0000174 return DRE->getDecl()->getDeclContext()->isFileContext() &&
175 DRE->getDecl()->getLinkage() == ExternalLinkage;
Argyrios Kyrtzidis2c18ca02011-07-14 23:32:04 +0000176 if (ConditionalOperator *condOp = dyn_cast<ConditionalOperator>(E))
177 return isGlobalVar(condOp->getTrueExpr()) &&
178 isGlobalVar(condOp->getFalseExpr());
179
180 return false;
181}
182
Argyrios Kyrtzidis18fd0c62011-07-27 05:28:18 +0000183StringRef trans::getNilString(ASTContext &Ctx) {
184 if (Ctx.Idents.get("nil").hasMacroDefinition())
185 return "nil";
186 else
187 return "0";
188}
189
John McCall8f0e8d22011-06-15 23:25:17 +0000190namespace {
191
Argyrios Kyrtzidis7196d062011-06-21 20:20:39 +0000192class ReferenceClear : public RecursiveASTVisitor<ReferenceClear> {
193 ExprSet &Refs;
194public:
195 ReferenceClear(ExprSet &refs) : Refs(refs) { }
196 bool VisitDeclRefExpr(DeclRefExpr *E) { Refs.erase(E); return true; }
197 bool VisitBlockDeclRefExpr(BlockDeclRefExpr *E) { Refs.erase(E); return true; }
198};
199
200class ReferenceCollector : public RecursiveASTVisitor<ReferenceCollector> {
201 ValueDecl *Dcl;
202 ExprSet &Refs;
John McCall8f0e8d22011-06-15 23:25:17 +0000203
204public:
Argyrios Kyrtzidis7196d062011-06-21 20:20:39 +0000205 ReferenceCollector(ValueDecl *D, ExprSet &refs)
206 : Dcl(D), Refs(refs) { }
207
208 bool VisitDeclRefExpr(DeclRefExpr *E) {
209 if (E->getDecl() == Dcl)
210 Refs.insert(E);
211 return true;
212 }
213
214 bool VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
215 if (E->getDecl() == Dcl)
216 Refs.insert(E);
217 return true;
218 }
219};
220
221class RemovablesCollector : public RecursiveASTVisitor<RemovablesCollector> {
222 ExprSet &Removables;
223
224public:
225 RemovablesCollector(ExprSet &removables)
John McCall8f0e8d22011-06-15 23:25:17 +0000226 : Removables(removables) { }
227
228 bool shouldWalkTypesOfTypeLocs() const { return false; }
229
230 bool TraverseStmtExpr(StmtExpr *E) {
231 CompoundStmt *S = E->getSubStmt();
232 for (CompoundStmt::body_iterator
233 I = S->body_begin(), E = S->body_end(); I != E; ++I) {
234 if (I != E - 1)
235 mark(*I);
236 TraverseStmt(*I);
237 }
238 return true;
239 }
240
241 bool VisitCompoundStmt(CompoundStmt *S) {
242 for (CompoundStmt::body_iterator
243 I = S->body_begin(), E = S->body_end(); I != E; ++I)
244 mark(*I);
245 return true;
246 }
247
248 bool VisitIfStmt(IfStmt *S) {
249 mark(S->getThen());
250 mark(S->getElse());
251 return true;
252 }
253
254 bool VisitWhileStmt(WhileStmt *S) {
255 mark(S->getBody());
256 return true;
257 }
258
259 bool VisitDoStmt(DoStmt *S) {
260 mark(S->getBody());
261 return true;
262 }
263
264 bool VisitForStmt(ForStmt *S) {
265 mark(S->getInit());
266 mark(S->getInc());
267 mark(S->getBody());
268 return true;
269 }
270
271private:
272 void mark(Stmt *S) {
273 if (!S) return;
274
John McCall7e5e5f42011-07-07 06:58:02 +0000275 while (LabelStmt *Label = dyn_cast<LabelStmt>(S))
276 S = Label->getSubStmt();
277 S = S->IgnoreImplicit();
John McCall8f0e8d22011-06-15 23:25:17 +0000278 if (Expr *E = dyn_cast<Expr>(S))
279 Removables.insert(E);
280 }
281};
282
John McCall8f0e8d22011-06-15 23:25:17 +0000283} // end anonymous namespace
284
Argyrios Kyrtzidis7196d062011-06-21 20:20:39 +0000285void trans::clearRefsIn(Stmt *S, ExprSet &refs) {
286 ReferenceClear(refs).TraverseStmt(S);
John McCall8f0e8d22011-06-15 23:25:17 +0000287}
288
Argyrios Kyrtzidis7196d062011-06-21 20:20:39 +0000289void trans::collectRefs(ValueDecl *D, Stmt *S, ExprSet &refs) {
290 ReferenceCollector(D, refs).TraverseStmt(S);
John McCall8f0e8d22011-06-15 23:25:17 +0000291}
292
Argyrios Kyrtzidis7196d062011-06-21 20:20:39 +0000293void trans::collectRemovables(Stmt *S, ExprSet &exprs) {
294 RemovablesCollector(exprs).TraverseStmt(S);
John McCall8f0e8d22011-06-15 23:25:17 +0000295}
296
297//===----------------------------------------------------------------------===//
Argyrios Kyrtzidise0ac7452011-11-04 15:58:08 +0000298// MigrationContext
299//===----------------------------------------------------------------------===//
300
301namespace {
302
303class ASTTransform : public RecursiveASTVisitor<ASTTransform> {
304 MigrationContext &MigrateCtx;
305
306public:
307 ASTTransform(MigrationContext &MigrateCtx) : MigrateCtx(MigrateCtx) { }
308
Argyrios Kyrtzidisf38fa732011-11-06 18:58:03 +0000309 bool shouldWalkTypesOfTypeLocs() const { return false; }
310
Argyrios Kyrtzidisb0d5db12011-11-06 18:57:57 +0000311 bool TraverseObjCImplementationDecl(ObjCImplementationDecl *D) {
312 ObjCImplementationContext ImplCtx(MigrateCtx, D);
313 for (MigrationContext::traverser_iterator
314 I = MigrateCtx.traversers_begin(),
315 E = MigrateCtx.traversers_end(); I != E; ++I)
316 (*I)->traverseObjCImplementation(ImplCtx);
317
318 return true;
319 }
320
Argyrios Kyrtzidise0ac7452011-11-04 15:58:08 +0000321 bool TraverseStmt(Stmt *rootS) {
322 if (!rootS)
323 return true;
324
325 BodyContext BodyCtx(MigrateCtx, rootS);
326 for (MigrationContext::traverser_iterator
327 I = MigrateCtx.traversers_begin(),
328 E = MigrateCtx.traversers_end(); I != E; ++I)
329 (*I)->traverseBody(BodyCtx);
330
331 return true;
332 }
333};
334
335}
336
337MigrationContext::~MigrationContext() {
338 for (traverser_iterator
339 I = traversers_begin(), E = traversers_end(); I != E; ++I)
340 delete *I;
341}
342
Argyrios Kyrtzidis1fe42032011-11-04 23:43:03 +0000343bool MigrationContext::isGCOwnedNonObjC(QualType T) {
344 while (!T.isNull()) {
345 if (const AttributedType *AttrT = T->getAs<AttributedType>()) {
346 if (AttrT->getAttrKind() == AttributedType::attr_objc_ownership)
347 return !AttrT->getModifiedType()->isObjCRetainableType();
348 }
349
350 if (T->isArrayType())
351 T = Pass.Ctx.getBaseElementType(T);
352 else if (const PointerType *PT = T->getAs<PointerType>())
353 T = PT->getPointeeType();
354 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
355 T = RT->getPointeeType();
356 else
357 break;
358 }
359
360 return false;
361}
362
Argyrios Kyrtzidisb0e1e122011-11-07 18:46:46 +0000363bool MigrationContext::rewritePropertyAttribute(StringRef fromAttr,
364 StringRef toAttr,
365 SourceLocation atLoc) {
366 if (atLoc.isMacroID())
367 return false;
368
369 SourceManager &SM = Pass.Ctx.getSourceManager();
370
371 // Break down the source location.
372 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(atLoc);
373
374 // Try to load the file buffer.
375 bool invalidTemp = false;
376 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
377 if (invalidTemp)
378 return false;
379
380 const char *tokenBegin = file.data() + locInfo.second;
381
382 // Lex from the start of the given location.
383 Lexer lexer(SM.getLocForStartOfFile(locInfo.first),
384 Pass.Ctx.getLangOptions(),
385 file.begin(), tokenBegin, file.end());
386 Token tok;
387 lexer.LexFromRawLexer(tok);
388 if (tok.isNot(tok::at)) return false;
389 lexer.LexFromRawLexer(tok);
390 if (tok.isNot(tok::raw_identifier)) return false;
391 if (StringRef(tok.getRawIdentifierData(), tok.getLength())
392 != "property")
393 return false;
394 lexer.LexFromRawLexer(tok);
395 if (tok.isNot(tok::l_paren)) return false;
396
397 Token BeforeTok = tok;
398 Token AfterTok;
399 AfterTok.startToken();
400 SourceLocation AttrLoc;
401
402 lexer.LexFromRawLexer(tok);
403 if (tok.is(tok::r_paren))
404 return false;
405
406 while (1) {
407 if (tok.isNot(tok::raw_identifier)) return false;
408 StringRef ident(tok.getRawIdentifierData(), tok.getLength());
409 if (ident == fromAttr) {
410 if (!toAttr.empty()) {
411 Pass.TA.replaceText(tok.getLocation(), fromAttr, toAttr);
412 return true;
413 }
414 // We want to remove the attribute.
415 AttrLoc = tok.getLocation();
416 }
417
418 do {
419 lexer.LexFromRawLexer(tok);
420 if (AttrLoc.isValid() && AfterTok.is(tok::unknown))
421 AfterTok = tok;
422 } while (tok.isNot(tok::comma) && tok.isNot(tok::r_paren));
423 if (tok.is(tok::r_paren))
424 break;
425 if (AttrLoc.isInvalid())
426 BeforeTok = tok;
427 lexer.LexFromRawLexer(tok);
428 }
429
430 if (toAttr.empty() && AttrLoc.isValid() && AfterTok.isNot(tok::unknown)) {
431 // We want to remove the attribute.
432 if (BeforeTok.is(tok::l_paren) && AfterTok.is(tok::r_paren)) {
433 Pass.TA.remove(SourceRange(BeforeTok.getLocation(),
434 AfterTok.getLocation()));
435 } else if (BeforeTok.is(tok::l_paren) && AfterTok.is(tok::comma)) {
436 Pass.TA.remove(SourceRange(AttrLoc, AfterTok.getLocation()));
437 } else {
438 Pass.TA.remove(SourceRange(BeforeTok.getLocation(), AttrLoc));
439 }
440
441 return true;
442 }
443
444 return false;
445}
446
Argyrios Kyrtzidise0ac7452011-11-04 15:58:08 +0000447void MigrationContext::traverse(TranslationUnitDecl *TU) {
Argyrios Kyrtzidisf38fa732011-11-06 18:58:03 +0000448 for (traverser_iterator
449 I = traversers_begin(), E = traversers_end(); I != E; ++I)
450 (*I)->traverseTU(*this);
451
Argyrios Kyrtzidise0ac7452011-11-04 15:58:08 +0000452 ASTTransform(*this).TraverseDecl(TU);
453}
454
455//===----------------------------------------------------------------------===//
John McCall8f0e8d22011-06-15 23:25:17 +0000456// getAllTransformations.
457//===----------------------------------------------------------------------===//
458
Argyrios Kyrtzidise0ac7452011-11-04 15:58:08 +0000459static void traverseAST(MigrationPass &pass) {
460 MigrationContext MigrateCtx(pass);
461
462 if (pass.isGCMigration()) {
463 MigrateCtx.addTraverser(new GCCollectableCallsTraverser);
Argyrios Kyrtzidisf38fa732011-11-06 18:58:03 +0000464 MigrateCtx.addTraverser(new GCAttrsTraverser());
Argyrios Kyrtzidise0ac7452011-11-04 15:58:08 +0000465 }
Argyrios Kyrtzidisb0d5db12011-11-06 18:57:57 +0000466 MigrateCtx.addTraverser(new PropertyRewriteTraverser());
Argyrios Kyrtzidise0ac7452011-11-04 15:58:08 +0000467
468 MigrateCtx.traverse(pass.Ctx.getTranslationUnitDecl());
469}
470
John McCall8f0e8d22011-06-15 23:25:17 +0000471static void independentTransforms(MigrationPass &pass) {
472 rewriteAutoreleasePool(pass);
Argyrios Kyrtzidise7ef8552011-11-04 15:58:22 +0000473 removeRetainReleaseDeallocFinalize(pass);
Argyrios Kyrtzidis7196d062011-06-21 20:20:39 +0000474 rewriteUnusedInitDelegate(pass);
Argyrios Kyrtzidise7ef8552011-11-04 15:58:22 +0000475 removeZeroOutPropsInDeallocFinalize(pass);
John McCall8f0e8d22011-06-15 23:25:17 +0000476 makeAssignARCSafe(pass);
Argyrios Kyrtzidis7196d062011-06-21 20:20:39 +0000477 rewriteUnbridgedCasts(pass);
John McCall8f0e8d22011-06-15 23:25:17 +0000478 rewriteBlockObjCVariable(pass);
Argyrios Kyrtzidisfd103982011-07-18 07:44:45 +0000479 checkAPIUses(pass);
Argyrios Kyrtzidise0ac7452011-11-04 15:58:08 +0000480 traverseAST(pass);
John McCall8f0e8d22011-06-15 23:25:17 +0000481}
482
Argyrios Kyrtzidise0ac7452011-11-04 15:58:08 +0000483std::vector<TransformFn> arcmt::getAllTransformations(
484 LangOptions::GCMode OrigGCMode) {
John McCall8f0e8d22011-06-15 23:25:17 +0000485 std::vector<TransformFn> transforms;
486
John McCall8f0e8d22011-06-15 23:25:17 +0000487 transforms.push_back(independentTransforms);
Argyrios Kyrtzidisfd3455a2011-06-21 20:20:42 +0000488 // This depends on previous transformations removing various expressions.
Argyrios Kyrtzidise7ef8552011-11-04 15:58:22 +0000489 transforms.push_back(removeEmptyStatementsAndDeallocFinalize);
John McCall8f0e8d22011-06-15 23:25:17 +0000490
491 return transforms;
492}