blob: 1dd8b0dfbd33f13ee86db15d258f7b100774f7e0 [file] [log] [blame]
Ted Kremenekf7639e12012-03-06 20:06:33 +00001//===--- ObjCMT.cpp - ObjC Migrate Tool -----------------------------------===//
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
Fariborz Jahanian85e988b2013-07-18 22:17:33 +000010#include "Transforms.h"
Ted Kremenekf7639e12012-03-06 20:06:33 +000011#include "clang/ARCMigrate/ARCMTActions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000012#include "clang/AST/ASTConsumer.h"
13#include "clang/AST/ASTContext.h"
14#include "clang/AST/NSAPI.h"
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +000015#include "clang/AST/ParentMap.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "clang/AST/RecursiveASTVisitor.h"
17#include "clang/Basic/FileManager.h"
18#include "clang/Edit/Commit.h"
19#include "clang/Edit/EditedSource.h"
20#include "clang/Edit/EditsReceiver.h"
21#include "clang/Edit/Rewriters.h"
Ted Kremenekf7639e12012-03-06 20:06:33 +000022#include "clang/Frontend/CompilerInstance.h"
23#include "clang/Frontend/MultiplexConsumer.h"
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +000024#include "clang/Lex/PPConditionalDirectiveRecord.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Lex/Preprocessor.h"
26#include "clang/Rewrite/Core/Rewriter.h"
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +000027#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +000028#include "clang/StaticAnalyzer/Checkers/ObjCRetainCount.h"
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +000029#include "clang/AST/Attr.h"
Ted Kremenekf7639e12012-03-06 20:06:33 +000030#include "llvm/ADT/SmallString.h"
31
32using namespace clang;
33using namespace arcmt;
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +000034using namespace ento::objc_retain;
Ted Kremenekf7639e12012-03-06 20:06:33 +000035
36namespace {
37
38class ObjCMigrateASTConsumer : public ASTConsumer {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000039 enum CF_BRIDGING_KIND {
40 CF_BRIDGING_NONE,
41 CF_BRIDGING_ENABLE,
42 CF_BRIDGING_MAY_INCLUDE
43 };
44
Ted Kremenekf7639e12012-03-06 20:06:33 +000045 void migrateDecl(Decl *D);
Fariborz Jahanian92f72422013-09-17 19:00:30 +000046 void migrateObjCInterfaceDecl(ASTContext &Ctx, ObjCContainerDecl *D);
Fariborz Jahanian1be01532013-07-12 22:32:19 +000047 void migrateProtocolConformance(ASTContext &Ctx,
48 const ObjCImplementationDecl *ImpDecl);
Fariborz Jahanian92463272013-07-18 20:11:45 +000049 void migrateNSEnumDecl(ASTContext &Ctx, const EnumDecl *EnumDcl,
50 const TypedefDecl *TypedefDcl);
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +000051 void migrateMethods(ASTContext &Ctx, ObjCContainerDecl *CDecl);
Fariborz Jahanian670ef262013-07-23 23:34:42 +000052 void migrateMethodInstanceType(ASTContext &Ctx, ObjCContainerDecl *CDecl,
53 ObjCMethodDecl *OM);
Fariborz Jahanian92f72422013-09-17 19:00:30 +000054 bool migrateProperty(ASTContext &Ctx, ObjCContainerDecl *D, ObjCMethodDecl *OM);
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +000055 void migrateNsReturnsInnerPointer(ASTContext &Ctx, ObjCMethodDecl *OM);
Fariborz Jahanianc4291852013-08-02 18:00:53 +000056 void migrateFactoryMethod(ASTContext &Ctx, ObjCContainerDecl *CDecl,
Fariborz Jahanian9275c682013-08-02 20:54:18 +000057 ObjCMethodDecl *OM,
58 ObjCInstanceTypeFamily OIT_Family = OIT_None);
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +000059
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +000060 void migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000061 void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +000062 const FunctionDecl *FuncDecl, bool ResultAnnotated);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000063 void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +000064 const ObjCMethodDecl *MethodDecl, bool ResultAnnotated);
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +000065
Fariborz Jahanian301b5212013-08-20 22:42:13 +000066 void AnnotateImplicitBridging(ASTContext &Ctx);
67
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000068 CF_BRIDGING_KIND migrateAddFunctionAnnotation(ASTContext &Ctx,
69 const FunctionDecl *FuncDecl);
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +000070
Fariborz Jahanian926fafb2013-08-22 18:35:27 +000071 void migrateARCSafeAnnotation(ASTContext &Ctx, ObjCContainerDecl *CDecl);
72
Fariborz Jahanian89f6d102013-09-04 00:10:06 +000073 void migrateAddMethodAnnotation(ASTContext &Ctx,
74 const ObjCMethodDecl *MethodDecl);
Ted Kremenekf7639e12012-03-06 20:06:33 +000075public:
76 std::string MigrateDir;
77 bool MigrateLiterals;
78 bool MigrateSubscripting;
Fariborz Jahaniand83ef842013-07-09 16:59:14 +000079 bool MigrateProperty;
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +000080 bool MigrateReadonlyProperty;
Fariborz Jahanianb8343522013-08-20 23:35:26 +000081 unsigned FileId;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000082 OwningPtr<NSAPI> NSAPIObj;
83 OwningPtr<edit::EditedSource> Editor;
Ted Kremenekf7639e12012-03-06 20:06:33 +000084 FileRemapper &Remapper;
85 FileManager &FileMgr;
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +000086 const PPConditionalDirectiveRecord *PPRec;
Fariborz Jahaniana7437f02013-07-03 23:05:00 +000087 Preprocessor &PP;
Ted Kremenekf7639e12012-03-06 20:06:33 +000088 bool IsOutputFile;
Fariborz Jahanian1be01532013-07-12 22:32:19 +000089 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ObjCProtocolDecls;
Fariborz Jahanian926fafb2013-08-22 18:35:27 +000090 llvm::SmallVector<const Decl *, 8> CFFunctionIBCandidates;
Fariborz Jahanian1be01532013-07-12 22:32:19 +000091
Ted Kremenekf7639e12012-03-06 20:06:33 +000092 ObjCMigrateASTConsumer(StringRef migrateDir,
93 bool migrateLiterals,
94 bool migrateSubscripting,
Fariborz Jahaniand83ef842013-07-09 16:59:14 +000095 bool migrateProperty,
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +000096 bool migrateReadonlyProperty,
Ted Kremenekf7639e12012-03-06 20:06:33 +000097 FileRemapper &remapper,
98 FileManager &fileMgr,
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +000099 const PPConditionalDirectiveRecord *PPRec,
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000100 Preprocessor &PP,
Ted Kremenekf7639e12012-03-06 20:06:33 +0000101 bool isOutputFile = false)
102 : MigrateDir(migrateDir),
103 MigrateLiterals(migrateLiterals),
104 MigrateSubscripting(migrateSubscripting),
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000105 MigrateProperty(migrateProperty),
106 MigrateReadonlyProperty(migrateReadonlyProperty),
107 FileId(0), Remapper(remapper), FileMgr(fileMgr), PPRec(PPRec), PP(PP),
Ted Kremenekf7639e12012-03-06 20:06:33 +0000108 IsOutputFile(isOutputFile) { }
109
110protected:
111 virtual void Initialize(ASTContext &Context) {
112 NSAPIObj.reset(new NSAPI(Context));
113 Editor.reset(new edit::EditedSource(Context.getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +0000114 Context.getLangOpts(),
Ted Kremenekf7639e12012-03-06 20:06:33 +0000115 PPRec));
116 }
117
118 virtual bool HandleTopLevelDecl(DeclGroupRef DG) {
119 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
120 migrateDecl(*I);
121 return true;
122 }
123 virtual void HandleInterestingDecl(DeclGroupRef DG) {
124 // Ignore decls from the PCH.
125 }
126 virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
127 ObjCMigrateASTConsumer::HandleTopLevelDecl(DG);
128 }
129
130 virtual void HandleTranslationUnit(ASTContext &Ctx);
131};
132
133}
134
135ObjCMigrateAction::ObjCMigrateAction(FrontendAction *WrappedAction,
136 StringRef migrateDir,
137 bool migrateLiterals,
Fariborz Jahaniand83ef842013-07-09 16:59:14 +0000138 bool migrateSubscripting,
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000139 bool migrateProperty,
140 bool migrateReadonlyProperty)
Ted Kremenekf7639e12012-03-06 20:06:33 +0000141 : WrapperFrontendAction(WrappedAction), MigrateDir(migrateDir),
142 MigrateLiterals(migrateLiterals), MigrateSubscripting(migrateSubscripting),
Fariborz Jahaniand83ef842013-07-09 16:59:14 +0000143 MigrateProperty(migrateProperty),
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000144 MigrateReadonlyProperty(migrateReadonlyProperty),
Ted Kremenekf7639e12012-03-06 20:06:33 +0000145 CompInst(0) {
146 if (MigrateDir.empty())
147 MigrateDir = "."; // user current directory if none is given.
148}
149
150ASTConsumer *ObjCMigrateAction::CreateASTConsumer(CompilerInstance &CI,
151 StringRef InFile) {
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000152 PPConditionalDirectiveRecord *
153 PPRec = new PPConditionalDirectiveRecord(CompInst->getSourceManager());
154 CompInst->getPreprocessor().addPPCallbacks(PPRec);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000155 ASTConsumer *
156 WrappedConsumer = WrapperFrontendAction::CreateASTConsumer(CI, InFile);
157 ASTConsumer *MTConsumer = new ObjCMigrateASTConsumer(MigrateDir,
158 MigrateLiterals,
159 MigrateSubscripting,
Fariborz Jahaniand83ef842013-07-09 16:59:14 +0000160 MigrateProperty,
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000161 MigrateReadonlyProperty,
Ted Kremenekf7639e12012-03-06 20:06:33 +0000162 Remapper,
163 CompInst->getFileManager(),
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000164 PPRec,
165 CompInst->getPreprocessor());
Ted Kremenekf7639e12012-03-06 20:06:33 +0000166 ASTConsumer *Consumers[] = { MTConsumer, WrappedConsumer };
167 return new MultiplexConsumer(Consumers);
168}
169
170bool ObjCMigrateAction::BeginInvocation(CompilerInstance &CI) {
171 Remapper.initFromDisk(MigrateDir, CI.getDiagnostics(),
172 /*ignoreIfFilesChanges=*/true);
173 CompInst = &CI;
174 CI.getDiagnostics().setIgnoreAllWarnings(true);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000175 return true;
176}
177
178namespace {
179class ObjCMigrator : public RecursiveASTVisitor<ObjCMigrator> {
180 ObjCMigrateASTConsumer &Consumer;
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000181 ParentMap &PMap;
Ted Kremenekf7639e12012-03-06 20:06:33 +0000182
183public:
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000184 ObjCMigrator(ObjCMigrateASTConsumer &consumer, ParentMap &PMap)
185 : Consumer(consumer), PMap(PMap) { }
Ted Kremenekf7639e12012-03-06 20:06:33 +0000186
187 bool shouldVisitTemplateInstantiations() const { return false; }
188 bool shouldWalkTypesOfTypeLocs() const { return false; }
189
190 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
191 if (Consumer.MigrateLiterals) {
192 edit::Commit commit(*Consumer.Editor);
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000193 edit::rewriteToObjCLiteralSyntax(E, *Consumer.NSAPIObj, commit, &PMap);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000194 Consumer.Editor->commit(commit);
195 }
196
197 if (Consumer.MigrateSubscripting) {
198 edit::Commit commit(*Consumer.Editor);
199 edit::rewriteToObjCSubscriptSyntax(E, *Consumer.NSAPIObj, commit);
200 Consumer.Editor->commit(commit);
201 }
202
203 return true;
204 }
205
206 bool TraverseObjCMessageExpr(ObjCMessageExpr *E) {
207 // Do depth first; we want to rewrite the subexpressions first so that if
208 // we have to move expressions we will move them already rewritten.
209 for (Stmt::child_range range = E->children(); range; ++range)
210 if (!TraverseStmt(*range))
211 return false;
212
213 return WalkUpFromObjCMessageExpr(E);
214 }
215};
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000216
217class BodyMigrator : public RecursiveASTVisitor<BodyMigrator> {
218 ObjCMigrateASTConsumer &Consumer;
219 OwningPtr<ParentMap> PMap;
220
221public:
222 BodyMigrator(ObjCMigrateASTConsumer &consumer) : Consumer(consumer) { }
223
224 bool shouldVisitTemplateInstantiations() const { return false; }
225 bool shouldWalkTypesOfTypeLocs() const { return false; }
226
227 bool TraverseStmt(Stmt *S) {
228 PMap.reset(new ParentMap(S));
229 ObjCMigrator(Consumer, *PMap).TraverseStmt(S);
230 return true;
231 }
232};
Ted Kremenekf7639e12012-03-06 20:06:33 +0000233}
234
235void ObjCMigrateASTConsumer::migrateDecl(Decl *D) {
236 if (!D)
237 return;
238 if (isa<ObjCMethodDecl>(D))
239 return; // Wait for the ObjC container declaration.
240
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000241 BodyMigrator(*this).TraverseDecl(D);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000242}
243
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000244static void append_attr(std::string &PropertyString, const char *attr) {
245 PropertyString += ", ";
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000246 PropertyString += attr;
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000247}
248
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000249static bool rewriteToObjCProperty(const ObjCMethodDecl *Getter,
250 const ObjCMethodDecl *Setter,
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000251 const NSAPI &NS, edit::Commit &commit,
Fariborz Jahanianca399602013-09-11 17:05:15 +0000252 unsigned LengthOfPrefix) {
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000253 ASTContext &Context = NS.getASTContext();
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000254 std::string PropertyString = "@property(nonatomic";
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000255 std::string PropertyNameString = Getter->getNameAsString();
256 StringRef PropertyName(PropertyNameString);
Fariborz Jahanianca399602013-09-11 17:05:15 +0000257 if (LengthOfPrefix > 0) {
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000258 PropertyString += ", getter=";
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000259 PropertyString += PropertyNameString;
260 }
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000261 // Property with no setter may be suggested as a 'readonly' property.
262 if (!Setter)
263 append_attr(PropertyString, "readonly");
264
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000265 // Short circuit properties that contain the name "delegate" or "dataSource",
266 // or have exact name "target" to have unsafe_unretained attribute.
267 if (PropertyName.equals("target") ||
268 (PropertyName.find("delegate") != StringRef::npos) ||
269 (PropertyName.find("dataSource") != StringRef::npos))
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000270 append_attr(PropertyString, "unsafe_unretained");
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000271 else if (Setter) {
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000272 const ParmVarDecl *argDecl = *Setter->param_begin();
273 QualType ArgType = Context.getCanonicalType(argDecl->getType());
274 Qualifiers::ObjCLifetime propertyLifetime = ArgType.getObjCLifetime();
275 bool RetainableObject = ArgType->isObjCRetainableType();
276 if (RetainableObject && propertyLifetime == Qualifiers::OCL_Strong) {
277 if (const ObjCObjectPointerType *ObjPtrTy =
278 ArgType->getAs<ObjCObjectPointerType>()) {
279 ObjCInterfaceDecl *IDecl = ObjPtrTy->getObjectType()->getInterface();
280 if (IDecl &&
281 IDecl->lookupNestedProtocol(&Context.Idents.get("NSCopying")))
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000282 append_attr(PropertyString, "copy");
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000283 else
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000284 append_attr(PropertyString, "retain");
285 }
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000286 } else if (propertyLifetime == Qualifiers::OCL_Weak)
287 // TODO. More precise determination of 'weak' attribute requires
288 // looking into setter's implementation for backing weak ivar.
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000289 append_attr(PropertyString, "weak");
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000290 else if (RetainableObject)
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000291 append_attr(PropertyString, "retain");
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000292 }
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000293 PropertyString += ')';
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000294
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000295 QualType RT = Getter->getResultType();
296 if (!isa<TypedefType>(RT)) {
297 // strip off any ARC lifetime qualifier.
298 QualType CanResultTy = Context.getCanonicalType(RT);
299 if (CanResultTy.getQualifiers().hasObjCLifetime()) {
300 Qualifiers Qs = CanResultTy.getQualifiers();
301 Qs.removeObjCLifetime();
302 RT = Context.getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
303 }
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000304 }
305 PropertyString += " ";
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000306 PropertyString += RT.getAsString(Context.getPrintingPolicy());
Fariborz Jahanianc71eb6a2013-09-23 23:18:46 +0000307 char LastChar = PropertyString[PropertyString.size()-1] ;
308 if (LastChar != '*')
309 PropertyString += " ";
Fariborz Jahanianca399602013-09-11 17:05:15 +0000310 if (LengthOfPrefix > 0) {
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000311 // property name must strip off "is" and lower case the first character
312 // after that; e.g. isContinuous will become continuous.
313 StringRef PropertyNameStringRef(PropertyNameString);
Fariborz Jahanianca399602013-09-11 17:05:15 +0000314 PropertyNameStringRef = PropertyNameStringRef.drop_front(LengthOfPrefix);
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000315 PropertyNameString = PropertyNameStringRef;
316 std::string NewPropertyNameString = PropertyNameString;
Fariborz Jahanian34fea362013-09-11 18:27:16 +0000317 bool NoLowering = (isUppercase(NewPropertyNameString[0]) &&
318 NewPropertyNameString.size() > 1 &&
319 isUppercase(NewPropertyNameString[1]));
320 if (!NoLowering)
321 NewPropertyNameString[0] = toLowercase(NewPropertyNameString[0]);
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000322 PropertyString += NewPropertyNameString;
323 }
324 else
325 PropertyString += PropertyNameString;
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000326 SourceLocation StartGetterSelectorLoc = Getter->getSelectorStartLoc();
327 Selector GetterSelector = Getter->getSelector();
328
329 SourceLocation EndGetterSelectorLoc =
330 StartGetterSelectorLoc.getLocWithOffset(GetterSelector.getNameForSlot(0).size());
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000331 commit.replace(CharSourceRange::getCharRange(Getter->getLocStart(),
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000332 EndGetterSelectorLoc),
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000333 PropertyString);
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000334 if (Setter) {
335 SourceLocation EndLoc = Setter->getDeclaratorEndLoc();
336 // Get location past ';'
337 EndLoc = EndLoc.getLocWithOffset(1);
338 commit.remove(CharSourceRange::getCharRange(Setter->getLocStart(), EndLoc));
339 }
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000340 return true;
341}
342
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000343void ObjCMigrateASTConsumer::migrateObjCInterfaceDecl(ASTContext &Ctx,
Fariborz Jahanian92f72422013-09-17 19:00:30 +0000344 ObjCContainerDecl *D) {
Fariborz Jahanian75226d52013-09-17 21:56:04 +0000345 if (D->isDeprecated())
346 return;
347
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000348 for (ObjCContainerDecl::method_iterator M = D->meth_begin(), MEnd = D->meth_end();
349 M != MEnd; ++M) {
350 ObjCMethodDecl *Method = (*M);
Fariborz Jahanian75226d52013-09-17 21:56:04 +0000351 if (Method->isDeprecated())
352 continue;
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000353 if (!migrateProperty(Ctx, D, Method))
354 migrateNsReturnsInnerPointer(Ctx, Method);
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000355 }
356}
357
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000358static bool
Fariborz Jahanian9a3512b2013-07-13 17:16:41 +0000359ClassImplementsAllMethodsAndProperties(ASTContext &Ctx,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000360 const ObjCImplementationDecl *ImpDecl,
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000361 const ObjCInterfaceDecl *IDecl,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000362 ObjCProtocolDecl *Protocol) {
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000363 // In auto-synthesis, protocol properties are not synthesized. So,
364 // a conforming protocol must have its required properties declared
365 // in class interface.
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000366 bool HasAtleastOneRequiredProperty = false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000367 if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition())
368 for (ObjCProtocolDecl::prop_iterator P = PDecl->prop_begin(),
369 E = PDecl->prop_end(); P != E; ++P) {
370 ObjCPropertyDecl *Property = *P;
371 if (Property->getPropertyImplementation() == ObjCPropertyDecl::Optional)
372 continue;
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000373 HasAtleastOneRequiredProperty = true;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000374 DeclContext::lookup_const_result R = IDecl->lookup(Property->getDeclName());
Fariborz Jahanian2bc3dda2013-07-16 21:59:42 +0000375 if (R.size() == 0) {
376 // Relax the rule and look into class's implementation for a synthesize
377 // or dynamic declaration. Class is implementing a property coming from
378 // another protocol. This still makes the target protocol as conforming.
379 if (!ImpDecl->FindPropertyImplDecl(
380 Property->getDeclName().getAsIdentifierInfo()))
381 return false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000382 }
Fariborz Jahanian2bc3dda2013-07-16 21:59:42 +0000383 else if (ObjCPropertyDecl *ClassProperty = dyn_cast<ObjCPropertyDecl>(R[0])) {
384 if ((ClassProperty->getPropertyAttributes()
385 != Property->getPropertyAttributes()) ||
386 !Ctx.hasSameType(ClassProperty->getType(), Property->getType()))
387 return false;
388 }
389 else
390 return false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000391 }
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000392
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000393 // At this point, all required properties in this protocol conform to those
394 // declared in the class.
395 // Check that class implements the required methods of the protocol too.
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000396 bool HasAtleastOneRequiredMethod = false;
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000397 if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition()) {
398 if (PDecl->meth_begin() == PDecl->meth_end())
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000399 return HasAtleastOneRequiredProperty;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000400 for (ObjCContainerDecl::method_iterator M = PDecl->meth_begin(),
401 MEnd = PDecl->meth_end(); M != MEnd; ++M) {
402 ObjCMethodDecl *MD = (*M);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000403 if (MD->isImplicit())
404 continue;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000405 if (MD->getImplementationControl() == ObjCMethodDecl::Optional)
406 continue;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000407 DeclContext::lookup_const_result R = ImpDecl->lookup(MD->getDeclName());
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000408 if (R.size() == 0)
409 return false;
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000410 bool match = false;
411 HasAtleastOneRequiredMethod = true;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000412 for (unsigned I = 0, N = R.size(); I != N; ++I)
413 if (ObjCMethodDecl *ImpMD = dyn_cast<ObjCMethodDecl>(R[0]))
414 if (Ctx.ObjCMethodsAreEqual(MD, ImpMD)) {
415 match = true;
416 break;
417 }
418 if (!match)
419 return false;
420 }
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000421 }
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000422 if (HasAtleastOneRequiredProperty || HasAtleastOneRequiredMethod)
423 return true;
424 return false;
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000425}
426
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000427static bool rewriteToObjCInterfaceDecl(const ObjCInterfaceDecl *IDecl,
428 llvm::SmallVectorImpl<ObjCProtocolDecl*> &ConformingProtocols,
429 const NSAPI &NS, edit::Commit &commit) {
430 const ObjCList<ObjCProtocolDecl> &Protocols = IDecl->getReferencedProtocols();
431 std::string ClassString;
432 SourceLocation EndLoc =
433 IDecl->getSuperClass() ? IDecl->getSuperClassLoc() : IDecl->getLocation();
434
435 if (Protocols.empty()) {
436 ClassString = '<';
437 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
438 ClassString += ConformingProtocols[i]->getNameAsString();
439 if (i != (e-1))
440 ClassString += ", ";
441 }
442 ClassString += "> ";
443 }
444 else {
445 ClassString = ", ";
446 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
447 ClassString += ConformingProtocols[i]->getNameAsString();
448 if (i != (e-1))
449 ClassString += ", ";
450 }
451 ObjCInterfaceDecl::protocol_loc_iterator PL = IDecl->protocol_loc_end() - 1;
452 EndLoc = *PL;
453 }
454
455 commit.insertAfterToken(EndLoc, ClassString);
456 return true;
457}
458
459static bool rewriteToNSEnumDecl(const EnumDecl *EnumDcl,
460 const TypedefDecl *TypedefDcl,
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000461 const NSAPI &NS, edit::Commit &commit,
Fariborz Jahanianff3476e2013-08-30 17:46:01 +0000462 bool IsNSIntegerType,
463 bool NSOptions) {
464 std::string ClassString;
465 if (NSOptions)
466 ClassString = "typedef NS_OPTIONS(NSUInteger, ";
467 else
468 ClassString =
469 IsNSIntegerType ? "typedef NS_ENUM(NSInteger, "
470 : "typedef NS_ENUM(NSUInteger, ";
471
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000472 ClassString += TypedefDcl->getIdentifier()->getName();
473 ClassString += ')';
474 SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
475 commit.replace(R, ClassString);
476 SourceLocation EndOfTypedefLoc = TypedefDcl->getLocEnd();
477 EndOfTypedefLoc = trans::findLocationAfterSemi(EndOfTypedefLoc, NS.getASTContext());
478 if (!EndOfTypedefLoc.isInvalid()) {
479 commit.remove(SourceRange(TypedefDcl->getLocStart(), EndOfTypedefLoc));
480 return true;
481 }
482 return false;
483}
484
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000485static bool rewriteToNSMacroDecl(const EnumDecl *EnumDcl,
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000486 const TypedefDecl *TypedefDcl,
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000487 const NSAPI &NS, edit::Commit &commit,
488 bool IsNSIntegerType) {
489 std::string ClassString =
490 IsNSIntegerType ? "NS_ENUM(NSInteger, " : "NS_OPTIONS(NSUInteger, ";
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000491 ClassString += TypedefDcl->getIdentifier()->getName();
492 ClassString += ')';
493 SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
494 commit.replace(R, ClassString);
495 SourceLocation TypedefLoc = TypedefDcl->getLocEnd();
496 commit.remove(SourceRange(TypedefLoc, TypedefLoc));
497 return true;
498}
499
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000500static bool UseNSOptionsMacro(Preprocessor &PP, ASTContext &Ctx,
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000501 const EnumDecl *EnumDcl) {
502 bool PowerOfTwo = true;
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000503 bool AllHexdecimalEnumerator = true;
Fariborz Jahanianbe7bc112013-08-15 18:46:37 +0000504 uint64_t MaxPowerOfTwoVal = 0;
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000505 for (EnumDecl::enumerator_iterator EI = EnumDcl->enumerator_begin(),
506 EE = EnumDcl->enumerator_end(); EI != EE; ++EI) {
507 EnumConstantDecl *Enumerator = (*EI);
508 const Expr *InitExpr = Enumerator->getInitExpr();
509 if (!InitExpr) {
510 PowerOfTwo = false;
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000511 AllHexdecimalEnumerator = false;
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000512 continue;
513 }
Fariborz Jahanian6e1798e2013-09-17 23:32:51 +0000514 InitExpr = InitExpr->IgnoreParenCasts();
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000515 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr))
516 if (BO->isShiftOp() || BO->isBitwiseOp())
517 return true;
518
519 uint64_t EnumVal = Enumerator->getInitVal().getZExtValue();
Fariborz Jahanianbe7bc112013-08-15 18:46:37 +0000520 if (PowerOfTwo && EnumVal) {
521 if (!llvm::isPowerOf2_64(EnumVal))
522 PowerOfTwo = false;
523 else if (EnumVal > MaxPowerOfTwoVal)
524 MaxPowerOfTwoVal = EnumVal;
525 }
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000526 if (AllHexdecimalEnumerator && EnumVal) {
527 bool FoundHexdecimalEnumerator = false;
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000528 SourceLocation EndLoc = Enumerator->getLocEnd();
529 Token Tok;
530 if (!PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true))
531 if (Tok.isLiteral() && Tok.getLength() > 2) {
532 if (const char *StringLit = Tok.getLiteralData())
533 FoundHexdecimalEnumerator =
534 (StringLit[0] == '0' && (toLowercase(StringLit[1]) == 'x'));
535 }
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000536 if (!FoundHexdecimalEnumerator)
537 AllHexdecimalEnumerator = false;
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000538 }
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000539 }
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000540 return AllHexdecimalEnumerator || (PowerOfTwo && (MaxPowerOfTwoVal > 2));
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000541}
542
Fariborz Jahanian008ef722013-07-19 17:44:32 +0000543void ObjCMigrateASTConsumer::migrateProtocolConformance(ASTContext &Ctx,
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000544 const ObjCImplementationDecl *ImpDecl) {
545 const ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface();
Fariborz Jahanian75226d52013-09-17 21:56:04 +0000546 if (!IDecl || ObjCProtocolDecls.empty() || IDecl->isDeprecated())
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000547 return;
548 // Find all implicit conforming protocols for this class
549 // and make them explicit.
550 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ExplicitProtocols;
551 Ctx.CollectInheritedProtocols(IDecl, ExplicitProtocols);
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000552 llvm::SmallVector<ObjCProtocolDecl *, 8> PotentialImplicitProtocols;
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000553
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000554 for (llvm::SmallPtrSet<ObjCProtocolDecl*, 32>::iterator I =
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000555 ObjCProtocolDecls.begin(),
556 E = ObjCProtocolDecls.end(); I != E; ++I)
557 if (!ExplicitProtocols.count(*I))
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000558 PotentialImplicitProtocols.push_back(*I);
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000559
560 if (PotentialImplicitProtocols.empty())
561 return;
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000562
563 // go through list of non-optional methods and properties in each protocol
564 // in the PotentialImplicitProtocols list. If class implements every one of the
565 // methods and properties, then this class conforms to this protocol.
566 llvm::SmallVector<ObjCProtocolDecl*, 8> ConformingProtocols;
567 for (unsigned i = 0, e = PotentialImplicitProtocols.size(); i != e; i++)
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000568 if (ClassImplementsAllMethodsAndProperties(Ctx, ImpDecl, IDecl,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000569 PotentialImplicitProtocols[i]))
570 ConformingProtocols.push_back(PotentialImplicitProtocols[i]);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000571
572 if (ConformingProtocols.empty())
573 return;
Fariborz Jahaniancb7b8de2013-07-17 00:02:22 +0000574
575 // Further reduce number of conforming protocols. If protocol P1 is in the list
576 // protocol P2 (P2<P1>), No need to include P1.
577 llvm::SmallVector<ObjCProtocolDecl*, 8> MinimalConformingProtocols;
578 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
579 bool DropIt = false;
580 ObjCProtocolDecl *TargetPDecl = ConformingProtocols[i];
581 for (unsigned i1 = 0, e1 = ConformingProtocols.size(); i1 != e1; i1++) {
582 ObjCProtocolDecl *PDecl = ConformingProtocols[i1];
583 if (PDecl == TargetPDecl)
584 continue;
585 if (PDecl->lookupProtocolNamed(
586 TargetPDecl->getDeclName().getAsIdentifierInfo())) {
587 DropIt = true;
588 break;
589 }
590 }
591 if (!DropIt)
592 MinimalConformingProtocols.push_back(TargetPDecl);
593 }
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000594 edit::Commit commit(*Editor);
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000595 rewriteToObjCInterfaceDecl(IDecl, MinimalConformingProtocols,
596 *NSAPIObj, commit);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000597 Editor->commit(commit);
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000598}
599
Fariborz Jahanian92463272013-07-18 20:11:45 +0000600void ObjCMigrateASTConsumer::migrateNSEnumDecl(ASTContext &Ctx,
601 const EnumDecl *EnumDcl,
602 const TypedefDecl *TypedefDcl) {
603 if (!EnumDcl->isCompleteDefinition() || EnumDcl->getIdentifier() ||
Fariborz Jahanian75226d52013-09-17 21:56:04 +0000604 !TypedefDcl->getIdentifier() ||
605 EnumDcl->isDeprecated() || TypedefDcl->isDeprecated())
Fariborz Jahanian92463272013-07-18 20:11:45 +0000606 return;
607
608 QualType qt = TypedefDcl->getTypeSourceInfo()->getType();
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000609 bool IsNSIntegerType = NSAPIObj->isObjCNSIntegerType(qt);
610 bool IsNSUIntegerType = !IsNSIntegerType && NSAPIObj->isObjCNSUIntegerType(qt);
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000611
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000612 if (!IsNSIntegerType && !IsNSUIntegerType) {
613 // Also check for typedef enum {...} TD;
614 if (const EnumType *EnumTy = qt->getAs<EnumType>()) {
615 if (EnumTy->getDecl() == EnumDcl) {
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000616 bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl);
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000617 if (NSOptions) {
618 if (!Ctx.Idents.get("NS_OPTIONS").hasMacroDefinition())
619 return;
620 }
621 else if (!Ctx.Idents.get("NS_ENUM").hasMacroDefinition())
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000622 return;
623 edit::Commit commit(*Editor);
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000624 rewriteToNSMacroDecl(EnumDcl, TypedefDcl, *NSAPIObj, commit, !NSOptions);
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000625 Editor->commit(commit);
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000626 }
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000627 }
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000628 return;
629 }
Fariborz Jahanian92463272013-07-18 20:11:45 +0000630
Fariborz Jahanianff3476e2013-08-30 17:46:01 +0000631 // We may still use NS_OPTIONS based on what we find in the enumertor list.
632 bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl);
Fariborz Jahanian92463272013-07-18 20:11:45 +0000633 // NS_ENUM must be available.
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000634 if (IsNSIntegerType && !Ctx.Idents.get("NS_ENUM").hasMacroDefinition())
635 return;
636 // NS_OPTIONS must be available.
637 if (IsNSUIntegerType && !Ctx.Idents.get("NS_OPTIONS").hasMacroDefinition())
Fariborz Jahanian92463272013-07-18 20:11:45 +0000638 return;
639 edit::Commit commit(*Editor);
Fariborz Jahanianff3476e2013-08-30 17:46:01 +0000640 rewriteToNSEnumDecl(EnumDcl, TypedefDcl, *NSAPIObj, commit, IsNSIntegerType, NSOptions);
Fariborz Jahanian92463272013-07-18 20:11:45 +0000641 Editor->commit(commit);
642}
643
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000644static void ReplaceWithInstancetype(const ObjCMigrateASTConsumer &ASTC,
645 ObjCMethodDecl *OM) {
646 SourceRange R;
647 std::string ClassString;
648 if (TypeSourceInfo *TSInfo = OM->getResultTypeSourceInfo()) {
649 TypeLoc TL = TSInfo->getTypeLoc();
650 R = SourceRange(TL.getBeginLoc(), TL.getEndLoc());
651 ClassString = "instancetype";
652 }
653 else {
654 R = SourceRange(OM->getLocStart(), OM->getLocStart());
655 ClassString = OM->isInstanceMethod() ? '-' : '+';
656 ClassString += " (instancetype)";
657 }
658 edit::Commit commit(*ASTC.Editor);
659 commit.replace(R, ClassString);
660 ASTC.Editor->commit(commit);
661}
662
Fariborz Jahanian670ef262013-07-23 23:34:42 +0000663void ObjCMigrateASTConsumer::migrateMethodInstanceType(ASTContext &Ctx,
664 ObjCContainerDecl *CDecl,
665 ObjCMethodDecl *OM) {
Fariborz Jahanian71221352013-07-23 22:42:28 +0000666 ObjCInstanceTypeFamily OIT_Family =
667 Selector::getInstTypeMethodFamily(OM->getSelector());
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000668
Fariborz Jahanian267bae32013-07-24 19:18:37 +0000669 std::string ClassName;
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000670 switch (OIT_Family) {
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000671 case OIT_None:
672 migrateFactoryMethod(Ctx, CDecl, OM);
673 return;
Fariborz Jahanian7dd71432013-08-28 21:23:00 +0000674 case OIT_Array:
675 ClassName = "NSArray";
676 break;
677 case OIT_Dictionary:
678 ClassName = "NSDictionary";
679 break;
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000680 case OIT_Singleton:
681 migrateFactoryMethod(Ctx, CDecl, OM, OIT_Singleton);
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000682 return;
Fariborz Jahanian1c900bc2013-09-18 20:35:47 +0000683 case OIT_Init:
684 if (OM->getResultType()->isObjCIdType())
685 ReplaceWithInstancetype(*this, OM);
686 return;
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000687 }
Fariborz Jahanian71221352013-07-23 22:42:28 +0000688 if (!OM->getResultType()->isObjCIdType())
689 return;
690
691 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
692 if (!IDecl) {
693 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
694 IDecl = CatDecl->getClassInterface();
695 else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
696 IDecl = ImpDecl->getClassInterface();
697 }
Fariborz Jahanian267bae32013-07-24 19:18:37 +0000698 if (!IDecl ||
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000699 !IDecl->lookupInheritedClass(&Ctx.Idents.get(ClassName))) {
700 migrateFactoryMethod(Ctx, CDecl, OM);
Fariborz Jahanian71221352013-07-23 22:42:28 +0000701 return;
Fariborz Jahanian280954a2013-07-24 18:31:42 +0000702 }
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000703 ReplaceWithInstancetype(*this, OM);
Fariborz Jahanian71221352013-07-23 22:42:28 +0000704}
705
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +0000706static bool TypeIsInnerPointer(QualType T) {
707 if (!T->isAnyPointerType())
708 return false;
709 if (T->isObjCObjectPointerType() || T->isObjCBuiltinType() ||
710 T->isBlockPointerType() || ento::coreFoundation::isCFObjectRef(T))
711 return false;
Fariborz Jahanian9d5fffb2013-09-09 23:56:14 +0000712 // Also, typedef-of-pointer-to-incomplete-struct is something that we assume
713 // is not an innter pointer type.
714 QualType OrigT = T;
715 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr()))
716 T = TD->getDecl()->getUnderlyingType();
717 if (OrigT == T || !T->isPointerType())
718 return true;
719 const PointerType* PT = T->getAs<PointerType>();
720 QualType UPointeeT = PT->getPointeeType().getUnqualifiedType();
721 if (UPointeeT->isRecordType()) {
722 const RecordType *RecordTy = UPointeeT->getAs<RecordType>();
723 if (!RecordTy->getDecl()->isCompleteDefinition())
724 return false;
725 }
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +0000726 return true;
727}
728
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +0000729static bool AttributesMatch(const Decl *Decl1, const Decl *Decl2) {
730 if (Decl1->hasAttrs() != Decl2->hasAttrs())
731 return false;
732
733 if (!Decl1->hasAttrs())
734 return true;
735
736 const AttrVec &Attrs1 = Decl1->getAttrs();
737 const AttrVec &Attrs2 = Decl2->getAttrs();
738 // This list is very small, so this need not be optimized.
739 for (unsigned i = 0, e = Attrs1.size(); i != e; i++) {
740 bool match = false;
741 for (unsigned j = 0, f = Attrs2.size(); j != f; j++) {
742 // Matching attribute kind only. We are not getting into
743 // details of the attributes. For all practical purposes
744 // this is sufficient.
745 if (Attrs1[i]->getKind() == Attrs2[j]->getKind()) {
746 match = true;
747 break;
748 }
749 }
750 if (!match)
751 return false;
752 }
753 return true;
754}
755
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000756bool ObjCMigrateASTConsumer::migrateProperty(ASTContext &Ctx,
Fariborz Jahanian92f72422013-09-17 19:00:30 +0000757 ObjCContainerDecl *D,
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000758 ObjCMethodDecl *Method) {
759 if (Method->isPropertyAccessor() || !Method->isInstanceMethod() ||
760 Method->param_size() != 0)
761 return false;
762 // Is this method candidate to be a getter?
763 QualType GRT = Method->getResultType();
764 if (GRT->isVoidType())
765 return false;
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000766
767 Selector GetterSelector = Method->getSelector();
768 IdentifierInfo *getterName = GetterSelector.getIdentifierInfoForSlot(0);
769 Selector SetterSelector =
770 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
771 PP.getSelectorTable(),
772 getterName);
Fariborz Jahanian92f72422013-09-17 19:00:30 +0000773 ObjCMethodDecl *SetterMethod = D->getInstanceMethod(SetterSelector);
Fariborz Jahanianca399602013-09-11 17:05:15 +0000774 unsigned LengthOfPrefix = 0;
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000775 if (!SetterMethod) {
776 // try a different naming convention for getter: isXxxxx
777 StringRef getterNameString = getterName->getName();
Fariborz Jahanianca399602013-09-11 17:05:15 +0000778 bool IsPrefix = getterNameString.startswith("is");
Fariborz Jahanian4c3d9c52013-09-17 19:38:55 +0000779 // Note that we don't want to change an isXXX method of retainable object
780 // type to property (readonly or otherwise).
781 if (IsPrefix && GRT->isObjCRetainableType())
782 return false;
783 if (IsPrefix || getterNameString.startswith("get")) {
Fariborz Jahanianca399602013-09-11 17:05:15 +0000784 LengthOfPrefix = (IsPrefix ? 2 : 3);
785 const char *CGetterName = getterNameString.data() + LengthOfPrefix;
786 // Make sure that first character after "is" or "get" prefix can
787 // start an identifier.
788 if (!isIdentifierHead(CGetterName[0]))
789 return false;
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000790 if (CGetterName[0] && isUppercase(CGetterName[0])) {
791 getterName = &Ctx.Idents.get(CGetterName);
792 SetterSelector =
793 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
794 PP.getSelectorTable(),
795 getterName);
Fariborz Jahanian92f72422013-09-17 19:00:30 +0000796 SetterMethod = D->getInstanceMethod(SetterSelector);
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000797 }
798 }
799 }
Fariborz Jahanian4c3d9c52013-09-17 19:38:55 +0000800
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000801 if (SetterMethod) {
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +0000802 if (SetterMethod->isDeprecated() ||
803 !AttributesMatch(Method, SetterMethod))
Fariborz Jahanianf6c65052013-09-17 22:41:25 +0000804 return false;
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +0000805
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000806 // Is this a valid setter, matching the target getter?
807 QualType SRT = SetterMethod->getResultType();
808 if (!SRT->isVoidType())
809 return false;
810 const ParmVarDecl *argDecl = *SetterMethod->param_begin();
811 QualType ArgType = argDecl->getType();
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +0000812 if (!Ctx.hasSameUnqualifiedType(ArgType, GRT))
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000813 return false;
814 edit::Commit commit(*Editor);
815 rewriteToObjCProperty(Method, SetterMethod, *NSAPIObj, commit,
Fariborz Jahanianca399602013-09-11 17:05:15 +0000816 LengthOfPrefix);
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000817 Editor->commit(commit);
818 return true;
819 }
820 else if (MigrateReadonlyProperty) {
821 // Try a non-void method with no argument (and no setter or property of same name
822 // as a 'readonly' property.
823 edit::Commit commit(*Editor);
824 rewriteToObjCProperty(Method, 0 /*SetterMethod*/, *NSAPIObj, commit,
Fariborz Jahanianca399602013-09-11 17:05:15 +0000825 LengthOfPrefix);
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000826 Editor->commit(commit);
827 return true;
828 }
829 return false;
830}
831
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +0000832void ObjCMigrateASTConsumer::migrateNsReturnsInnerPointer(ASTContext &Ctx,
833 ObjCMethodDecl *OM) {
834 if (OM->hasAttr<ObjCReturnsInnerPointerAttr>())
835 return;
836
837 QualType RT = OM->getResultType();
838 if (!TypeIsInnerPointer(RT) ||
839 !Ctx.Idents.get("NS_RETURNS_INNER_POINTER").hasMacroDefinition())
840 return;
841
842 edit::Commit commit(*Editor);
843 commit.insertBefore(OM->getLocEnd(), " NS_RETURNS_INNER_POINTER");
844 Editor->commit(commit);
845}
846
847void ObjCMigrateASTConsumer::migrateMethods(ASTContext &Ctx,
Fariborz Jahanian71221352013-07-23 22:42:28 +0000848 ObjCContainerDecl *CDecl) {
Fariborz Jahaniane47a14a2013-09-18 15:43:52 +0000849 if (CDecl->isDeprecated())
850 return;
851
Fariborz Jahanian71221352013-07-23 22:42:28 +0000852 // migrate methods which can have instancetype as their result type.
853 for (ObjCContainerDecl::method_iterator M = CDecl->meth_begin(),
854 MEnd = CDecl->meth_end();
855 M != MEnd; ++M) {
856 ObjCMethodDecl *Method = (*M);
Fariborz Jahanian75226d52013-09-17 21:56:04 +0000857 if (Method->isDeprecated())
858 continue;
Fariborz Jahanian71221352013-07-23 22:42:28 +0000859 migrateMethodInstanceType(Ctx, CDecl, Method);
860 }
861}
862
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000863void ObjCMigrateASTConsumer::migrateFactoryMethod(ASTContext &Ctx,
864 ObjCContainerDecl *CDecl,
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000865 ObjCMethodDecl *OM,
866 ObjCInstanceTypeFamily OIT_Family) {
Fariborz Jahanian3bfc35e2013-08-02 22:34:18 +0000867 if (OM->isInstanceMethod() ||
868 OM->getResultType() == Ctx.getObjCInstanceType() ||
869 !OM->getResultType()->isObjCIdType())
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000870 return;
871
872 // Candidate factory methods are + (id) NaMeXXX : ... which belong to a class
873 // NSYYYNamE with matching names be at least 3 characters long.
874 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
875 if (!IDecl) {
876 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
877 IDecl = CatDecl->getClassInterface();
878 else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
879 IDecl = ImpDecl->getClassInterface();
880 }
881 if (!IDecl)
882 return;
883
884 std::string StringClassName = IDecl->getName();
885 StringRef LoweredClassName(StringClassName);
886 std::string StringLoweredClassName = LoweredClassName.lower();
887 LoweredClassName = StringLoweredClassName;
888
889 IdentifierInfo *MethodIdName = OM->getSelector().getIdentifierInfoForSlot(0);
Fariborz Jahanianc13c1b02013-08-13 18:01:42 +0000890 // Handle method with no name at its first selector slot; e.g. + (id):(int)x.
891 if (!MethodIdName)
892 return;
893
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000894 std::string MethodName = MethodIdName->getName();
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000895 if (OIT_Family == OIT_Singleton) {
896 StringRef STRefMethodName(MethodName);
897 size_t len = 0;
898 if (STRefMethodName.startswith("standard"))
899 len = strlen("standard");
900 else if (STRefMethodName.startswith("shared"))
901 len = strlen("shared");
902 else if (STRefMethodName.startswith("default"))
903 len = strlen("default");
904 else
905 return;
906 MethodName = STRefMethodName.substr(len);
907 }
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000908 std::string MethodNameSubStr = MethodName.substr(0, 3);
909 StringRef MethodNamePrefix(MethodNameSubStr);
910 std::string StringLoweredMethodNamePrefix = MethodNamePrefix.lower();
911 MethodNamePrefix = StringLoweredMethodNamePrefix;
912 size_t Ix = LoweredClassName.rfind(MethodNamePrefix);
913 if (Ix == StringRef::npos)
914 return;
915 std::string ClassNamePostfix = LoweredClassName.substr(Ix);
916 StringRef LoweredMethodName(MethodName);
917 std::string StringLoweredMethodName = LoweredMethodName.lower();
918 LoweredMethodName = StringLoweredMethodName;
919 if (!LoweredMethodName.startswith(ClassNamePostfix))
920 return;
921 ReplaceWithInstancetype(*this, OM);
922}
923
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +0000924static bool IsVoidStarType(QualType Ty) {
925 if (!Ty->isPointerType())
926 return false;
927
928 while (const TypedefType *TD = dyn_cast<TypedefType>(Ty.getTypePtr()))
929 Ty = TD->getDecl()->getUnderlyingType();
930
931 // Is the type void*?
932 const PointerType* PT = Ty->getAs<PointerType>();
933 if (PT->getPointeeType().getUnqualifiedType()->isVoidType())
934 return true;
935 return IsVoidStarType(PT->getPointeeType());
936}
937
Fariborz Jahanian94279392013-08-20 18:54:39 +0000938/// AuditedType - This routine audits the type AT and returns false if it is one of known
939/// CF object types or of the "void *" variety. It returns true if we don't care about the type
940/// such as a non-pointer or pointers which have no ownership issues (such as "int *").
Fariborz Jahanian63ffce22013-08-27 22:42:30 +0000941static bool AuditedType (QualType AT) {
942 if (!AT->isAnyPointerType() && !AT->isBlockPointerType())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +0000943 return true;
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +0000944 // FIXME. There isn't much we can say about CF pointer type; or is there?
Fariborz Jahanian94279392013-08-20 18:54:39 +0000945 if (ento::coreFoundation::isCFObjectRef(AT) ||
946 IsVoidStarType(AT) ||
947 // If an ObjC object is type, assuming that it is not a CF function and
948 // that it is an un-audited function.
Fariborz Jahanian2e9c19c2013-08-22 22:27:36 +0000949 AT->isObjCObjectPointerType() || AT->isObjCBuiltinType())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +0000950 return false;
Fariborz Jahanian94279392013-08-20 18:54:39 +0000951 // All other pointers are assumed audited as harmless.
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +0000952 return true;
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +0000953}
954
Fariborz Jahanian301b5212013-08-20 22:42:13 +0000955void ObjCMigrateASTConsumer::AnnotateImplicitBridging(ASTContext &Ctx) {
Fariborz Jahanian926fafb2013-08-22 18:35:27 +0000956 if (CFFunctionIBCandidates.empty())
957 return;
Fariborz Jahanian301b5212013-08-20 22:42:13 +0000958 if (!Ctx.Idents.get("CF_IMPLICIT_BRIDGING_ENABLED").hasMacroDefinition()) {
959 CFFunctionIBCandidates.clear();
Fariborz Jahanianb8343522013-08-20 23:35:26 +0000960 FileId = 0;
Fariborz Jahanian301b5212013-08-20 22:42:13 +0000961 return;
962 }
963 // Insert CF_IMPLICIT_BRIDGING_ENABLE/CF_IMPLICIT_BRIDGING_DISABLED
Fariborz Jahanian926fafb2013-08-22 18:35:27 +0000964 const Decl *FirstFD = CFFunctionIBCandidates[0];
965 const Decl *LastFD =
966 CFFunctionIBCandidates[CFFunctionIBCandidates.size()-1];
Fariborz Jahanian301b5212013-08-20 22:42:13 +0000967 const char *PragmaString = "\nCF_IMPLICIT_BRIDGING_ENABLED\n\n";
968 edit::Commit commit(*Editor);
969 commit.insertBefore(FirstFD->getLocStart(), PragmaString);
970 PragmaString = "\n\nCF_IMPLICIT_BRIDGING_DISABLED\n";
971 SourceLocation EndLoc = LastFD->getLocEnd();
972 // get location just past end of function location.
973 EndLoc = PP.getLocForEndOfToken(EndLoc);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +0000974 if (isa<FunctionDecl>(LastFD)) {
975 // For Methods, EndLoc points to the ending semcolon. So,
976 // not of these extra work is needed.
977 Token Tok;
978 // get locaiton of token that comes after end of function.
979 bool Failed = PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true);
980 if (!Failed)
981 EndLoc = Tok.getLocation();
982 }
Fariborz Jahanian301b5212013-08-20 22:42:13 +0000983 commit.insertAfterToken(EndLoc, PragmaString);
984 Editor->commit(commit);
Fariborz Jahanianb8343522013-08-20 23:35:26 +0000985 FileId = 0;
Fariborz Jahanian301b5212013-08-20 22:42:13 +0000986 CFFunctionIBCandidates.clear();
987}
988
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +0000989void ObjCMigrateASTConsumer::migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl) {
Fariborz Jahanian75226d52013-09-17 21:56:04 +0000990 if (Decl->isDeprecated())
991 return;
992
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +0000993 if (Decl->hasAttr<CFAuditedTransferAttr>()) {
Fariborz Jahanianc6dfd3f2013-08-19 22:00:50 +0000994 assert(CFFunctionIBCandidates.empty() &&
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +0000995 "Cannot have audited functions/methods inside user "
Fariborz Jahanianc6dfd3f2013-08-19 22:00:50 +0000996 "provided CF_IMPLICIT_BRIDGING_ENABLE");
997 return;
998 }
999
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +00001000 // Finction must be annotated first.
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001001 if (const FunctionDecl *FuncDecl = dyn_cast<FunctionDecl>(Decl)) {
1002 CF_BRIDGING_KIND AuditKind = migrateAddFunctionAnnotation(Ctx, FuncDecl);
1003 if (AuditKind == CF_BRIDGING_ENABLE) {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001004 CFFunctionIBCandidates.push_back(Decl);
1005 if (!FileId)
1006 FileId = PP.getSourceManager().getFileID(Decl->getLocation()).getHashValue();
1007 }
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001008 else if (AuditKind == CF_BRIDGING_MAY_INCLUDE) {
1009 if (!CFFunctionIBCandidates.empty()) {
1010 CFFunctionIBCandidates.push_back(Decl);
1011 if (!FileId)
1012 FileId = PP.getSourceManager().getFileID(Decl->getLocation()).getHashValue();
1013 }
1014 }
1015 else
1016 AnnotateImplicitBridging(Ctx);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001017 }
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001018 else {
1019 migrateAddMethodAnnotation(Ctx, cast<ObjCMethodDecl>(Decl));
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001020 AnnotateImplicitBridging(Ctx);
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001021 }
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +00001022}
1023
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001024void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
1025 const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001026 const FunctionDecl *FuncDecl,
1027 bool ResultAnnotated) {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001028 // Annotate function.
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001029 if (!ResultAnnotated) {
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001030 RetEffect Ret = CE.getReturnValue();
1031 const char *AnnotationString = 0;
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001032 if (Ret.getObjKind() == RetEffect::CF) {
1033 if (Ret.isOwned() &&
1034 Ctx.Idents.get("CF_RETURNS_RETAINED").hasMacroDefinition())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001035 AnnotationString = " CF_RETURNS_RETAINED";
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001036 else if (Ret.notOwned() &&
1037 Ctx.Idents.get("CF_RETURNS_NOT_RETAINED").hasMacroDefinition())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001038 AnnotationString = " CF_RETURNS_NOT_RETAINED";
1039 }
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001040 else if (Ret.getObjKind() == RetEffect::ObjC) {
1041 if (Ret.isOwned() &&
1042 Ctx.Idents.get("NS_RETURNS_RETAINED").hasMacroDefinition())
1043 AnnotationString = " NS_RETURNS_RETAINED";
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001044 }
1045
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001046 if (AnnotationString) {
1047 edit::Commit commit(*Editor);
1048 commit.insertAfterToken(FuncDecl->getLocEnd(), AnnotationString);
1049 Editor->commit(commit);
1050 }
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +00001051 }
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001052 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1053 unsigned i = 0;
1054 for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
1055 pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
Fariborz Jahanianb918d7a2013-08-21 19:37:47 +00001056 const ParmVarDecl *pd = *pi;
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001057 ArgEffect AE = AEArgs[i];
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001058 if (AE == DecRef && !pd->getAttr<CFConsumedAttr>() &&
1059 Ctx.Idents.get("CF_CONSUMED").hasMacroDefinition()) {
1060 edit::Commit commit(*Editor);
1061 commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
1062 Editor->commit(commit);
Fariborz Jahanian94279392013-08-20 18:54:39 +00001063 }
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001064 else if (AE == DecRefMsg && !pd->getAttr<NSConsumedAttr>() &&
1065 Ctx.Idents.get("NS_CONSUMED").hasMacroDefinition()) {
1066 edit::Commit commit(*Editor);
1067 commit.insertBefore(pd->getLocation(), "NS_CONSUMED ");
1068 Editor->commit(commit);
1069 }
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +00001070 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001071}
1072
1073
1074ObjCMigrateASTConsumer::CF_BRIDGING_KIND
1075 ObjCMigrateASTConsumer::migrateAddFunctionAnnotation(
1076 ASTContext &Ctx,
1077 const FunctionDecl *FuncDecl) {
1078 if (FuncDecl->hasBody())
1079 return CF_BRIDGING_NONE;
1080
1081 CallEffects CE = CallEffects::getEffect(FuncDecl);
1082 bool FuncIsReturnAnnotated = (FuncDecl->getAttr<CFReturnsRetainedAttr>() ||
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001083 FuncDecl->getAttr<CFReturnsNotRetainedAttr>() ||
1084 FuncDecl->getAttr<NSReturnsRetainedAttr>() ||
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001085 FuncDecl->getAttr<NSReturnsNotRetainedAttr>() ||
1086 FuncDecl->getAttr<NSReturnsAutoreleasedAttr>());
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001087
1088 // Trivial case of when funciton is annotated and has no argument.
1089 if (FuncIsReturnAnnotated && FuncDecl->getNumParams() == 0)
1090 return CF_BRIDGING_NONE;
1091
1092 bool ReturnCFAudited = false;
1093 if (!FuncIsReturnAnnotated) {
1094 RetEffect Ret = CE.getReturnValue();
1095 if (Ret.getObjKind() == RetEffect::CF &&
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001096 (Ret.isOwned() || Ret.notOwned()))
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001097 ReturnCFAudited = true;
1098 else if (!AuditedType(FuncDecl->getResultType()))
1099 return CF_BRIDGING_NONE;
1100 }
1101
1102 // At this point result type is audited for potential inclusion.
1103 // Now, how about argument types.
1104 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1105 unsigned i = 0;
1106 bool ArgCFAudited = false;
1107 for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
1108 pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
1109 const ParmVarDecl *pd = *pi;
1110 ArgEffect AE = AEArgs[i];
1111 if (AE == DecRef /*CFConsumed annotated*/ || AE == IncRef) {
1112 if (AE == DecRef && !pd->getAttr<CFConsumedAttr>())
1113 ArgCFAudited = true;
1114 else if (AE == IncRef)
1115 ArgCFAudited = true;
1116 }
1117 else {
1118 QualType AT = pd->getType();
1119 if (!AuditedType(AT)) {
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001120 AddCFAnnotations(Ctx, CE, FuncDecl, FuncIsReturnAnnotated);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001121 return CF_BRIDGING_NONE;
1122 }
1123 }
1124 }
1125 if (ReturnCFAudited || ArgCFAudited)
1126 return CF_BRIDGING_ENABLE;
1127
1128 return CF_BRIDGING_MAY_INCLUDE;
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +00001129}
1130
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001131void ObjCMigrateASTConsumer::migrateARCSafeAnnotation(ASTContext &Ctx,
1132 ObjCContainerDecl *CDecl) {
Fariborz Jahanian75226d52013-09-17 21:56:04 +00001133 if (!isa<ObjCInterfaceDecl>(CDecl) || CDecl->isDeprecated())
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001134 return;
1135
1136 // migrate methods which can have instancetype as their result type.
1137 for (ObjCContainerDecl::method_iterator M = CDecl->meth_begin(),
1138 MEnd = CDecl->meth_end();
1139 M != MEnd; ++M) {
1140 ObjCMethodDecl *Method = (*M);
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +00001141 migrateCFAnnotation(Ctx, Method);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001142 }
1143}
1144
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001145void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
1146 const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001147 const ObjCMethodDecl *MethodDecl,
1148 bool ResultAnnotated) {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001149 // Annotate function.
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001150 if (!ResultAnnotated) {
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001151 RetEffect Ret = CE.getReturnValue();
1152 const char *AnnotationString = 0;
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001153 if (Ret.getObjKind() == RetEffect::CF) {
1154 if (Ret.isOwned() &&
1155 Ctx.Idents.get("CF_RETURNS_RETAINED").hasMacroDefinition())
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001156 AnnotationString = " CF_RETURNS_RETAINED";
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001157 else if (Ret.notOwned() &&
1158 Ctx.Idents.get("CF_RETURNS_NOT_RETAINED").hasMacroDefinition())
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001159 AnnotationString = " CF_RETURNS_NOT_RETAINED";
1160 }
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001161 else if (Ret.getObjKind() == RetEffect::ObjC) {
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001162 ObjCMethodFamily OMF = MethodDecl->getMethodFamily();
1163 switch (OMF) {
1164 case clang::OMF_alloc:
1165 case clang::OMF_new:
1166 case clang::OMF_copy:
1167 case clang::OMF_init:
1168 case clang::OMF_mutableCopy:
1169 break;
1170
1171 default:
1172 if (Ret.isOwned() &&
1173 Ctx.Idents.get("NS_RETURNS_RETAINED").hasMacroDefinition())
1174 AnnotationString = " NS_RETURNS_RETAINED";
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001175 break;
1176 }
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001177 }
1178
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001179 if (AnnotationString) {
1180 edit::Commit commit(*Editor);
1181 commit.insertBefore(MethodDecl->getLocEnd(), AnnotationString);
1182 Editor->commit(commit);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001183 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001184 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001185 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1186 unsigned i = 0;
1187 for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
1188 pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
1189 const ParmVarDecl *pd = *pi;
1190 ArgEffect AE = AEArgs[i];
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001191 if (AE == DecRef && !pd->getAttr<CFConsumedAttr>() &&
1192 Ctx.Idents.get("CF_CONSUMED").hasMacroDefinition()) {
1193 edit::Commit commit(*Editor);
1194 commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
1195 Editor->commit(commit);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001196 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001197 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001198}
1199
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001200void ObjCMigrateASTConsumer::migrateAddMethodAnnotation(
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001201 ASTContext &Ctx,
1202 const ObjCMethodDecl *MethodDecl) {
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001203 if (MethodDecl->hasBody() || MethodDecl->isImplicit())
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001204 return;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001205
1206 CallEffects CE = CallEffects::getEffect(MethodDecl);
1207 bool MethodIsReturnAnnotated = (MethodDecl->getAttr<CFReturnsRetainedAttr>() ||
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001208 MethodDecl->getAttr<CFReturnsNotRetainedAttr>() ||
1209 MethodDecl->getAttr<NSReturnsRetainedAttr>() ||
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001210 MethodDecl->getAttr<NSReturnsNotRetainedAttr>() ||
1211 MethodDecl->getAttr<NSReturnsAutoreleasedAttr>());
1212
1213 if (CE.getReceiver() == DecRefMsg &&
1214 !MethodDecl->getAttr<NSConsumesSelfAttr>() &&
1215 MethodDecl->getMethodFamily() != OMF_init &&
1216 MethodDecl->getMethodFamily() != OMF_release &&
1217 Ctx.Idents.get("NS_CONSUMES_SELF").hasMacroDefinition()) {
1218 edit::Commit commit(*Editor);
1219 commit.insertBefore(MethodDecl->getLocEnd(), " NS_CONSUMES_SELF");
1220 Editor->commit(commit);
1221 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001222
1223 // Trivial case of when funciton is annotated and has no argument.
1224 if (MethodIsReturnAnnotated &&
1225 (MethodDecl->param_begin() == MethodDecl->param_end()))
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001226 return;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001227
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001228 if (!MethodIsReturnAnnotated) {
1229 RetEffect Ret = CE.getReturnValue();
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001230 if ((Ret.getObjKind() == RetEffect::CF ||
1231 Ret.getObjKind() == RetEffect::ObjC) &&
1232 (Ret.isOwned() || Ret.notOwned())) {
Fariborz Jahanian8b102302013-09-04 16:43:57 +00001233 AddCFAnnotations(Ctx, CE, MethodDecl, false);
1234 return;
1235 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001236 else if (!AuditedType(MethodDecl->getResultType()))
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001237 return;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001238 }
1239
1240 // At this point result type is either annotated or audited.
1241 // Now, how about argument types.
1242 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1243 unsigned i = 0;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001244 for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
1245 pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
1246 const ParmVarDecl *pd = *pi;
1247 ArgEffect AE = AEArgs[i];
Fariborz Jahanian8b102302013-09-04 16:43:57 +00001248 if ((AE == DecRef && !pd->getAttr<CFConsumedAttr>()) || AE == IncRef ||
1249 !AuditedType(pd->getType())) {
1250 AddCFAnnotations(Ctx, CE, MethodDecl, MethodIsReturnAnnotated);
1251 return;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001252 }
1253 }
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001254 return;
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +00001255}
1256
Ted Kremenekf7639e12012-03-06 20:06:33 +00001257namespace {
1258
1259class RewritesReceiver : public edit::EditsReceiver {
1260 Rewriter &Rewrite;
1261
1262public:
1263 RewritesReceiver(Rewriter &Rewrite) : Rewrite(Rewrite) { }
1264
1265 virtual void insert(SourceLocation loc, StringRef text) {
1266 Rewrite.InsertText(loc, text);
1267 }
1268 virtual void replace(CharSourceRange range, StringRef text) {
1269 Rewrite.ReplaceText(range.getBegin(), Rewrite.getRangeSize(range), text);
1270 }
1271};
1272
1273}
1274
1275void ObjCMigrateASTConsumer::HandleTranslationUnit(ASTContext &Ctx) {
Fariborz Jahaniana7437f02013-07-03 23:05:00 +00001276
1277 TranslationUnitDecl *TU = Ctx.getTranslationUnitDecl();
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001278 if (MigrateProperty) {
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001279 for (DeclContext::decl_iterator D = TU->decls_begin(), DEnd = TU->decls_end();
1280 D != DEnd; ++D) {
Fariborz Jahanianb8343522013-08-20 23:35:26 +00001281 if (unsigned FID =
1282 PP.getSourceManager().getFileID((*D)->getLocation()).getHashValue())
Fariborz Jahanian75226d52013-09-17 21:56:04 +00001283 if (FileId && FileId != FID)
Fariborz Jahanianb8343522013-08-20 23:35:26 +00001284 AnnotateImplicitBridging(Ctx);
Fariborz Jahanianb8343522013-08-20 23:35:26 +00001285
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001286 if (ObjCInterfaceDecl *CDecl = dyn_cast<ObjCInterfaceDecl>(*D))
1287 migrateObjCInterfaceDecl(Ctx, CDecl);
Fariborz Jahanian92f72422013-09-17 19:00:30 +00001288 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(*D))
1289 migrateObjCInterfaceDecl(Ctx, CatDecl);
Fariborz Jahanian1be01532013-07-12 22:32:19 +00001290 else if (ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(*D))
1291 ObjCProtocolDecls.insert(PDecl);
1292 else if (const ObjCImplementationDecl *ImpDecl =
1293 dyn_cast<ObjCImplementationDecl>(*D))
1294 migrateProtocolConformance(Ctx, ImpDecl);
Fariborz Jahanian92463272013-07-18 20:11:45 +00001295 else if (const EnumDecl *ED = dyn_cast<EnumDecl>(*D)) {
1296 DeclContext::decl_iterator N = D;
1297 ++N;
Fariborz Jahanian008ef722013-07-19 17:44:32 +00001298 if (N != DEnd)
1299 if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(*N))
1300 migrateNSEnumDecl(Ctx, ED, TD);
Fariborz Jahanian92463272013-07-18 20:11:45 +00001301 }
Fariborz Jahanianc13c1b02013-08-13 18:01:42 +00001302 else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*D))
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +00001303 migrateCFAnnotation(Ctx, FD);
Fariborz Jahanianc13c1b02013-08-13 18:01:42 +00001304
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001305 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(*D)) {
1306 // migrate methods which can have instancetype as their result type.
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +00001307 migrateMethods(Ctx, CDecl);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001308 // annotate methods with CF annotations.
1309 migrateARCSafeAnnotation(Ctx, CDecl);
1310 }
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001311 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001312 AnnotateImplicitBridging(Ctx);
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001313 }
Fariborz Jahaniana7437f02013-07-03 23:05:00 +00001314
David Blaikiebbafb8a2012-03-11 07:00:24 +00001315 Rewriter rewriter(Ctx.getSourceManager(), Ctx.getLangOpts());
Ted Kremenekf7639e12012-03-06 20:06:33 +00001316 RewritesReceiver Rec(rewriter);
1317 Editor->applyRewrites(Rec);
1318
1319 for (Rewriter::buffer_iterator
1320 I = rewriter.buffer_begin(), E = rewriter.buffer_end(); I != E; ++I) {
1321 FileID FID = I->first;
1322 RewriteBuffer &buf = I->second;
1323 const FileEntry *file = Ctx.getSourceManager().getFileEntryForID(FID);
1324 assert(file);
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001325 SmallString<512> newText;
Ted Kremenekf7639e12012-03-06 20:06:33 +00001326 llvm::raw_svector_ostream vecOS(newText);
1327 buf.write(vecOS);
1328 vecOS.flush();
1329 llvm::MemoryBuffer *memBuf = llvm::MemoryBuffer::getMemBufferCopy(
1330 StringRef(newText.data(), newText.size()), file->getName());
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001331 SmallString<64> filePath(file->getName());
Ted Kremenekf7639e12012-03-06 20:06:33 +00001332 FileMgr.FixupRelativePath(filePath);
1333 Remapper.remap(filePath.str(), memBuf);
1334 }
1335
1336 if (IsOutputFile) {
1337 Remapper.flushToFile(MigrateDir, Ctx.getDiagnostics());
1338 } else {
1339 Remapper.flushToDisk(MigrateDir, Ctx.getDiagnostics());
1340 }
1341}
1342
1343bool MigrateSourceAction::BeginInvocation(CompilerInstance &CI) {
Argyrios Kyrtzidisb4822602012-05-24 16:48:23 +00001344 CI.getDiagnostics().setIgnoreAllWarnings(true);
Ted Kremenekf7639e12012-03-06 20:06:33 +00001345 return true;
1346}
1347
1348ASTConsumer *MigrateSourceAction::CreateASTConsumer(CompilerInstance &CI,
1349 StringRef InFile) {
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +00001350 PPConditionalDirectiveRecord *
1351 PPRec = new PPConditionalDirectiveRecord(CI.getSourceManager());
1352 CI.getPreprocessor().addPPCallbacks(PPRec);
Ted Kremenekf7639e12012-03-06 20:06:33 +00001353 return new ObjCMigrateASTConsumer(CI.getFrontendOpts().OutputFile,
1354 /*MigrateLiterals=*/true,
1355 /*MigrateSubscripting=*/true,
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001356 /*MigrateProperty*/true,
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +00001357 /*MigrateReadonlyProperty*/true,
Ted Kremenekf7639e12012-03-06 20:06:33 +00001358 Remapper,
1359 CI.getFileManager(),
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +00001360 PPRec,
Fariborz Jahaniana7437f02013-07-03 23:05:00 +00001361 CI.getPreprocessor(),
Ted Kremenekf7639e12012-03-06 20:06:33 +00001362 /*isOutputFile=*/true);
1363}