blob: a736c2419ed0efeef0acd21951a9752fcd0184c2 [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;
73 while (const PointerType *ptr = T->getAs<PointerType>())
74 T = ptr->getPointeeType();
75 if (const ObjCObjectPointerType *ObjT = T->getAs<ObjCObjectPointerType>()) {
76 ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl();
Argyrios Kyrtzidis12192cf2011-11-07 18:40:29 +000077 if (!AllowOnUnknownClass && (!Class || Class->getName() == "NSObject"))
Argyrios Kyrtzidis86625b52011-07-12 22:05:17 +000078 return false; // id/NSObject is not safe for weak.
Argyrios Kyrtzidis12192cf2011-11-07 18:40:29 +000079 if (!AllowOnUnknownClass && Class->isForwardDecl())
Argyrios Kyrtzidis5363e8d2011-07-12 22:16:25 +000080 return false; // forward classes are not verifiable, therefore not safe.
Argyrios Kyrtzidis86625b52011-07-12 22:05:17 +000081 if (Class->isArcWeakrefUnavailable())
82 return false;
83 if (isClassInWeakBlacklist(Class))
84 return false;
85 }
86
87 return true;
88}
89
Argyrios Kyrtzidis7196d062011-06-21 20:20:39 +000090/// \brief 'Loc' is the end of a statement range. This returns the location
91/// immediately after the semicolon following the statement.
92/// If no semicolon is found or the location is inside a macro, the returned
93/// source location will be invalid.
94SourceLocation trans::findLocationAfterSemi(SourceLocation loc,
95 ASTContext &Ctx) {
Argyrios Kyrtzidisaec230d2011-09-01 20:53:18 +000096 SourceLocation SemiLoc = findSemiAfterLocation(loc, Ctx);
97 if (SemiLoc.isInvalid())
98 return SourceLocation();
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +000099 return SemiLoc.getLocWithOffset(1);
Argyrios Kyrtzidisaec230d2011-09-01 20:53:18 +0000100}
101
102/// \brief \arg Loc is the end of a statement range. This returns the location
103/// of the semicolon following the statement.
104/// If no semicolon is found or the location is inside a macro, the returned
105/// source location will be invalid.
106SourceLocation trans::findSemiAfterLocation(SourceLocation loc,
107 ASTContext &Ctx) {
Argyrios Kyrtzidis7196d062011-06-21 20:20:39 +0000108 SourceManager &SM = Ctx.getSourceManager();
109 if (loc.isMacroID()) {
Chandler Carruth433db062011-07-14 08:20:40 +0000110 if (!Lexer::isAtEndOfMacroExpansion(loc, SM, Ctx.getLangOptions()))
Argyrios Kyrtzidis7196d062011-06-21 20:20:39 +0000111 return SourceLocation();
Chandler Carruthedc3dcc2011-07-25 16:56:02 +0000112 loc = SM.getExpansionRange(loc).second;
Argyrios Kyrtzidis7196d062011-06-21 20:20:39 +0000113 }
114 loc = Lexer::getLocForEndOfToken(loc, /*Offset=*/0, SM, Ctx.getLangOptions());
115
116 // Break down the source location.
117 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
118
119 // Try to load the file buffer.
120 bool invalidTemp = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000121 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
Argyrios Kyrtzidis7196d062011-06-21 20:20:39 +0000122 if (invalidTemp)
123 return SourceLocation();
124
125 const char *tokenBegin = file.data() + locInfo.second;
126
127 // Lex from the start of the given location.
128 Lexer lexer(SM.getLocForStartOfFile(locInfo.first),
129 Ctx.getLangOptions(),
130 file.begin(), tokenBegin, file.end());
131 Token tok;
132 lexer.LexFromRawLexer(tok);
133 if (tok.isNot(tok::semi))
134 return SourceLocation();
135
Argyrios Kyrtzidisaec230d2011-09-01 20:53:18 +0000136 return tok.getLocation();
Argyrios Kyrtzidis7196d062011-06-21 20:20:39 +0000137}
138
139bool trans::hasSideEffects(Expr *E, ASTContext &Ctx) {
140 if (!E || !E->HasSideEffects(Ctx))
141 return false;
142
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
165 return true;
166}
167
Argyrios Kyrtzidis2c18ca02011-07-14 23:32:04 +0000168bool trans::isGlobalVar(Expr *E) {
169 E = E->IgnoreParenCasts();
170 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Argyrios Kyrtzidis18fd0c62011-07-27 05:28:18 +0000171 return DRE->getDecl()->getDeclContext()->isFileContext() &&
172 DRE->getDecl()->getLinkage() == ExternalLinkage;
Argyrios Kyrtzidis2c18ca02011-07-14 23:32:04 +0000173 if (ConditionalOperator *condOp = dyn_cast<ConditionalOperator>(E))
174 return isGlobalVar(condOp->getTrueExpr()) &&
175 isGlobalVar(condOp->getFalseExpr());
176
177 return false;
178}
179
Argyrios Kyrtzidis18fd0c62011-07-27 05:28:18 +0000180StringRef trans::getNilString(ASTContext &Ctx) {
181 if (Ctx.Idents.get("nil").hasMacroDefinition())
182 return "nil";
183 else
184 return "0";
185}
186
John McCall8f0e8d22011-06-15 23:25:17 +0000187namespace {
188
Argyrios Kyrtzidis7196d062011-06-21 20:20:39 +0000189class ReferenceClear : public RecursiveASTVisitor<ReferenceClear> {
190 ExprSet &Refs;
191public:
192 ReferenceClear(ExprSet &refs) : Refs(refs) { }
193 bool VisitDeclRefExpr(DeclRefExpr *E) { Refs.erase(E); return true; }
194 bool VisitBlockDeclRefExpr(BlockDeclRefExpr *E) { Refs.erase(E); return true; }
195};
196
197class ReferenceCollector : public RecursiveASTVisitor<ReferenceCollector> {
198 ValueDecl *Dcl;
199 ExprSet &Refs;
John McCall8f0e8d22011-06-15 23:25:17 +0000200
201public:
Argyrios Kyrtzidis7196d062011-06-21 20:20:39 +0000202 ReferenceCollector(ValueDecl *D, ExprSet &refs)
203 : Dcl(D), Refs(refs) { }
204
205 bool VisitDeclRefExpr(DeclRefExpr *E) {
206 if (E->getDecl() == Dcl)
207 Refs.insert(E);
208 return true;
209 }
210
211 bool VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
212 if (E->getDecl() == Dcl)
213 Refs.insert(E);
214 return true;
215 }
216};
217
218class RemovablesCollector : public RecursiveASTVisitor<RemovablesCollector> {
219 ExprSet &Removables;
220
221public:
222 RemovablesCollector(ExprSet &removables)
John McCall8f0e8d22011-06-15 23:25:17 +0000223 : Removables(removables) { }
224
225 bool shouldWalkTypesOfTypeLocs() const { return false; }
226
227 bool TraverseStmtExpr(StmtExpr *E) {
228 CompoundStmt *S = E->getSubStmt();
229 for (CompoundStmt::body_iterator
230 I = S->body_begin(), E = S->body_end(); I != E; ++I) {
231 if (I != E - 1)
232 mark(*I);
233 TraverseStmt(*I);
234 }
235 return true;
236 }
237
238 bool VisitCompoundStmt(CompoundStmt *S) {
239 for (CompoundStmt::body_iterator
240 I = S->body_begin(), E = S->body_end(); I != E; ++I)
241 mark(*I);
242 return true;
243 }
244
245 bool VisitIfStmt(IfStmt *S) {
246 mark(S->getThen());
247 mark(S->getElse());
248 return true;
249 }
250
251 bool VisitWhileStmt(WhileStmt *S) {
252 mark(S->getBody());
253 return true;
254 }
255
256 bool VisitDoStmt(DoStmt *S) {
257 mark(S->getBody());
258 return true;
259 }
260
261 bool VisitForStmt(ForStmt *S) {
262 mark(S->getInit());
263 mark(S->getInc());
264 mark(S->getBody());
265 return true;
266 }
267
268private:
269 void mark(Stmt *S) {
270 if (!S) return;
271
John McCall7e5e5f42011-07-07 06:58:02 +0000272 while (LabelStmt *Label = dyn_cast<LabelStmt>(S))
273 S = Label->getSubStmt();
274 S = S->IgnoreImplicit();
John McCall8f0e8d22011-06-15 23:25:17 +0000275 if (Expr *E = dyn_cast<Expr>(S))
276 Removables.insert(E);
277 }
278};
279
John McCall8f0e8d22011-06-15 23:25:17 +0000280} // end anonymous namespace
281
Argyrios Kyrtzidis7196d062011-06-21 20:20:39 +0000282void trans::clearRefsIn(Stmt *S, ExprSet &refs) {
283 ReferenceClear(refs).TraverseStmt(S);
John McCall8f0e8d22011-06-15 23:25:17 +0000284}
285
Argyrios Kyrtzidis7196d062011-06-21 20:20:39 +0000286void trans::collectRefs(ValueDecl *D, Stmt *S, ExprSet &refs) {
287 ReferenceCollector(D, refs).TraverseStmt(S);
John McCall8f0e8d22011-06-15 23:25:17 +0000288}
289
Argyrios Kyrtzidis7196d062011-06-21 20:20:39 +0000290void trans::collectRemovables(Stmt *S, ExprSet &exprs) {
291 RemovablesCollector(exprs).TraverseStmt(S);
John McCall8f0e8d22011-06-15 23:25:17 +0000292}
293
294//===----------------------------------------------------------------------===//
Argyrios Kyrtzidise0ac7452011-11-04 15:58:08 +0000295// MigrationContext
296//===----------------------------------------------------------------------===//
297
298namespace {
299
300class ASTTransform : public RecursiveASTVisitor<ASTTransform> {
301 MigrationContext &MigrateCtx;
302
303public:
304 ASTTransform(MigrationContext &MigrateCtx) : MigrateCtx(MigrateCtx) { }
305
Argyrios Kyrtzidisf38fa732011-11-06 18:58:03 +0000306 bool shouldWalkTypesOfTypeLocs() const { return false; }
307
Argyrios Kyrtzidisb0d5db12011-11-06 18:57:57 +0000308 bool TraverseObjCImplementationDecl(ObjCImplementationDecl *D) {
309 ObjCImplementationContext ImplCtx(MigrateCtx, D);
310 for (MigrationContext::traverser_iterator
311 I = MigrateCtx.traversers_begin(),
312 E = MigrateCtx.traversers_end(); I != E; ++I)
313 (*I)->traverseObjCImplementation(ImplCtx);
314
315 return true;
316 }
317
Argyrios Kyrtzidise0ac7452011-11-04 15:58:08 +0000318 bool TraverseStmt(Stmt *rootS) {
319 if (!rootS)
320 return true;
321
322 BodyContext BodyCtx(MigrateCtx, rootS);
323 for (MigrationContext::traverser_iterator
324 I = MigrateCtx.traversers_begin(),
325 E = MigrateCtx.traversers_end(); I != E; ++I)
326 (*I)->traverseBody(BodyCtx);
327
328 return true;
329 }
330};
331
332}
333
334MigrationContext::~MigrationContext() {
335 for (traverser_iterator
336 I = traversers_begin(), E = traversers_end(); I != E; ++I)
337 delete *I;
338}
339
Argyrios Kyrtzidis1fe42032011-11-04 23:43:03 +0000340bool MigrationContext::isGCOwnedNonObjC(QualType T) {
341 while (!T.isNull()) {
342 if (const AttributedType *AttrT = T->getAs<AttributedType>()) {
343 if (AttrT->getAttrKind() == AttributedType::attr_objc_ownership)
344 return !AttrT->getModifiedType()->isObjCRetainableType();
345 }
346
347 if (T->isArrayType())
348 T = Pass.Ctx.getBaseElementType(T);
349 else if (const PointerType *PT = T->getAs<PointerType>())
350 T = PT->getPointeeType();
351 else if (const ReferenceType *RT = T->getAs<ReferenceType>())
352 T = RT->getPointeeType();
353 else
354 break;
355 }
356
357 return false;
358}
359
Argyrios Kyrtzidise0ac7452011-11-04 15:58:08 +0000360void MigrationContext::traverse(TranslationUnitDecl *TU) {
Argyrios Kyrtzidisf38fa732011-11-06 18:58:03 +0000361 for (traverser_iterator
362 I = traversers_begin(), E = traversers_end(); I != E; ++I)
363 (*I)->traverseTU(*this);
364
Argyrios Kyrtzidise0ac7452011-11-04 15:58:08 +0000365 ASTTransform(*this).TraverseDecl(TU);
366}
367
368//===----------------------------------------------------------------------===//
John McCall8f0e8d22011-06-15 23:25:17 +0000369// getAllTransformations.
370//===----------------------------------------------------------------------===//
371
Argyrios Kyrtzidise0ac7452011-11-04 15:58:08 +0000372static void traverseAST(MigrationPass &pass) {
373 MigrationContext MigrateCtx(pass);
374
375 if (pass.isGCMigration()) {
376 MigrateCtx.addTraverser(new GCCollectableCallsTraverser);
Argyrios Kyrtzidisf38fa732011-11-06 18:58:03 +0000377 MigrateCtx.addTraverser(new GCAttrsTraverser());
Argyrios Kyrtzidise0ac7452011-11-04 15:58:08 +0000378 }
Argyrios Kyrtzidisb0d5db12011-11-06 18:57:57 +0000379 MigrateCtx.addTraverser(new PropertyRewriteTraverser());
Argyrios Kyrtzidise0ac7452011-11-04 15:58:08 +0000380
381 MigrateCtx.traverse(pass.Ctx.getTranslationUnitDecl());
382}
383
John McCall8f0e8d22011-06-15 23:25:17 +0000384static void independentTransforms(MigrationPass &pass) {
385 rewriteAutoreleasePool(pass);
Argyrios Kyrtzidise7ef8552011-11-04 15:58:22 +0000386 removeRetainReleaseDeallocFinalize(pass);
Argyrios Kyrtzidis7196d062011-06-21 20:20:39 +0000387 rewriteUnusedInitDelegate(pass);
Argyrios Kyrtzidise7ef8552011-11-04 15:58:22 +0000388 removeZeroOutPropsInDeallocFinalize(pass);
John McCall8f0e8d22011-06-15 23:25:17 +0000389 makeAssignARCSafe(pass);
Argyrios Kyrtzidis7196d062011-06-21 20:20:39 +0000390 rewriteUnbridgedCasts(pass);
John McCall8f0e8d22011-06-15 23:25:17 +0000391 rewriteBlockObjCVariable(pass);
Argyrios Kyrtzidisfd103982011-07-18 07:44:45 +0000392 checkAPIUses(pass);
Argyrios Kyrtzidise0ac7452011-11-04 15:58:08 +0000393 traverseAST(pass);
John McCall8f0e8d22011-06-15 23:25:17 +0000394}
395
Argyrios Kyrtzidise0ac7452011-11-04 15:58:08 +0000396std::vector<TransformFn> arcmt::getAllTransformations(
397 LangOptions::GCMode OrigGCMode) {
John McCall8f0e8d22011-06-15 23:25:17 +0000398 std::vector<TransformFn> transforms;
399
John McCall8f0e8d22011-06-15 23:25:17 +0000400 transforms.push_back(independentTransforms);
Argyrios Kyrtzidisfd3455a2011-06-21 20:20:42 +0000401 // This depends on previous transformations removing various expressions.
Argyrios Kyrtzidise7ef8552011-11-04 15:58:22 +0000402 transforms.push_back(removeEmptyStatementsAndDeallocFinalize);
John McCall8f0e8d22011-06-15 23:25:17 +0000403
404 return transforms;
405}