• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===--- 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 
10 #include "Transforms.h"
11 #include "clang/ARCMigrate/ARCMT.h"
12 #include "clang/ARCMigrate/ARCMTActions.h"
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/Attr.h"
16 #include "clang/AST/NSAPI.h"
17 #include "clang/AST/ParentMap.h"
18 #include "clang/AST/RecursiveASTVisitor.h"
19 #include "clang/Analysis/DomainSpecific/CocoaConventions.h"
20 #include "clang/Basic/FileManager.h"
21 #include "clang/Edit/Commit.h"
22 #include "clang/Edit/EditedSource.h"
23 #include "clang/Edit/EditsReceiver.h"
24 #include "clang/Edit/Rewriters.h"
25 #include "clang/Frontend/CompilerInstance.h"
26 #include "clang/Frontend/MultiplexConsumer.h"
27 #include "clang/Lex/PPConditionalDirectiveRecord.h"
28 #include "clang/Lex/Preprocessor.h"
29 #include "clang/Rewrite/Core/Rewriter.h"
30 #include "clang/StaticAnalyzer/Checkers/ObjCRetainCount.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/StringSet.h"
33 #include "llvm/Support/Path.h"
34 #include "llvm/Support/SourceMgr.h"
35 #include "llvm/Support/YAMLParser.h"
36 
37 using namespace clang;
38 using namespace arcmt;
39 using namespace ento::objc_retain;
40 
41 namespace {
42 
43 class ObjCMigrateASTConsumer : public ASTConsumer {
44   enum CF_BRIDGING_KIND {
45     CF_BRIDGING_NONE,
46     CF_BRIDGING_ENABLE,
47     CF_BRIDGING_MAY_INCLUDE
48   };
49 
50   void migrateDecl(Decl *D);
51   void migrateObjCContainerDecl(ASTContext &Ctx, ObjCContainerDecl *D);
52   void migrateProtocolConformance(ASTContext &Ctx,
53                                   const ObjCImplementationDecl *ImpDecl);
54   void CacheObjCNSIntegerTypedefed(const TypedefDecl *TypedefDcl);
55   bool migrateNSEnumDecl(ASTContext &Ctx, const EnumDecl *EnumDcl,
56                      const TypedefDecl *TypedefDcl);
57   void migrateAllMethodInstaceType(ASTContext &Ctx, ObjCContainerDecl *CDecl);
58   void migrateMethodInstanceType(ASTContext &Ctx, ObjCContainerDecl *CDecl,
59                                  ObjCMethodDecl *OM);
60   bool migrateProperty(ASTContext &Ctx, ObjCContainerDecl *D, ObjCMethodDecl *OM);
61   void migrateNsReturnsInnerPointer(ASTContext &Ctx, ObjCMethodDecl *OM);
62   void migratePropertyNsReturnsInnerPointer(ASTContext &Ctx, ObjCPropertyDecl *P);
63   void migrateFactoryMethod(ASTContext &Ctx, ObjCContainerDecl *CDecl,
64                             ObjCMethodDecl *OM,
65                             ObjCInstanceTypeFamily OIT_Family = OIT_None);
66 
67   void migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl);
68   void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE,
69                         const FunctionDecl *FuncDecl, bool ResultAnnotated);
70   void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE,
71                         const ObjCMethodDecl *MethodDecl, bool ResultAnnotated);
72 
73   void AnnotateImplicitBridging(ASTContext &Ctx);
74 
75   CF_BRIDGING_KIND migrateAddFunctionAnnotation(ASTContext &Ctx,
76                                                 const FunctionDecl *FuncDecl);
77 
78   void migrateARCSafeAnnotation(ASTContext &Ctx, ObjCContainerDecl *CDecl);
79 
80   void migrateAddMethodAnnotation(ASTContext &Ctx,
81                                   const ObjCMethodDecl *MethodDecl);
82 
83   void inferDesignatedInitializers(ASTContext &Ctx,
84                                    const ObjCImplementationDecl *ImplD);
85 
86   bool InsertFoundation(ASTContext &Ctx, SourceLocation Loc);
87 
88 public:
89   std::string MigrateDir;
90   unsigned ASTMigrateActions;
91   FileID FileId;
92   const TypedefDecl *NSIntegerTypedefed;
93   const TypedefDecl *NSUIntegerTypedefed;
94   std::unique_ptr<NSAPI> NSAPIObj;
95   std::unique_ptr<edit::EditedSource> Editor;
96   FileRemapper &Remapper;
97   FileManager &FileMgr;
98   const PPConditionalDirectiveRecord *PPRec;
99   Preprocessor &PP;
100   bool IsOutputFile;
101   bool FoundationIncluded;
102   llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ObjCProtocolDecls;
103   llvm::SmallVector<const Decl *, 8> CFFunctionIBCandidates;
104   llvm::StringSet<> WhiteListFilenames;
105 
ObjCMigrateASTConsumer(StringRef migrateDir,unsigned astMigrateActions,FileRemapper & remapper,FileManager & fileMgr,const PPConditionalDirectiveRecord * PPRec,Preprocessor & PP,bool isOutputFile,ArrayRef<std::string> WhiteList)106   ObjCMigrateASTConsumer(StringRef migrateDir,
107                          unsigned astMigrateActions,
108                          FileRemapper &remapper,
109                          FileManager &fileMgr,
110                          const PPConditionalDirectiveRecord *PPRec,
111                          Preprocessor &PP,
112                          bool isOutputFile,
113                          ArrayRef<std::string> WhiteList)
114   : MigrateDir(migrateDir),
115     ASTMigrateActions(astMigrateActions),
116     NSIntegerTypedefed(nullptr), NSUIntegerTypedefed(nullptr),
117     Remapper(remapper), FileMgr(fileMgr), PPRec(PPRec), PP(PP),
118     IsOutputFile(isOutputFile),
119     FoundationIncluded(false){
120 
121     // FIXME: StringSet should have insert(iter, iter) to use here.
122     for (const std::string &Val : WhiteList)
123       WhiteListFilenames.insert(Val);
124   }
125 
126 protected:
Initialize(ASTContext & Context)127   void Initialize(ASTContext &Context) override {
128     NSAPIObj.reset(new NSAPI(Context));
129     Editor.reset(new edit::EditedSource(Context.getSourceManager(),
130                                         Context.getLangOpts(),
131                                         PPRec));
132   }
133 
HandleTopLevelDecl(DeclGroupRef DG)134   bool HandleTopLevelDecl(DeclGroupRef DG) override {
135     for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
136       migrateDecl(*I);
137     return true;
138   }
HandleInterestingDecl(DeclGroupRef DG)139   void HandleInterestingDecl(DeclGroupRef DG) override {
140     // Ignore decls from the PCH.
141   }
HandleTopLevelDeclInObjCContainer(DeclGroupRef DG)142   void HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) override {
143     ObjCMigrateASTConsumer::HandleTopLevelDecl(DG);
144   }
145 
146   void HandleTranslationUnit(ASTContext &Ctx) override;
147 
canModifyFile(StringRef Path)148   bool canModifyFile(StringRef Path) {
149     if (WhiteListFilenames.empty())
150       return true;
151     return WhiteListFilenames.find(llvm::sys::path::filename(Path))
152         != WhiteListFilenames.end();
153   }
canModifyFile(const FileEntry * FE)154   bool canModifyFile(const FileEntry *FE) {
155     if (!FE)
156       return false;
157     return canModifyFile(FE->getName());
158   }
canModifyFile(FileID FID)159   bool canModifyFile(FileID FID) {
160     if (FID.isInvalid())
161       return false;
162     return canModifyFile(PP.getSourceManager().getFileEntryForID(FID));
163   }
164 
canModify(const Decl * D)165   bool canModify(const Decl *D) {
166     if (!D)
167       return false;
168     if (const ObjCCategoryImplDecl *CatImpl = dyn_cast<ObjCCategoryImplDecl>(D))
169       return canModify(CatImpl->getCategoryDecl());
170     if (const ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D))
171       return canModify(Impl->getClassInterface());
172     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
173       return canModify(cast<Decl>(MD->getDeclContext()));
174 
175     FileID FID = PP.getSourceManager().getFileID(D->getLocation());
176     return canModifyFile(FID);
177   }
178 };
179 
180 } // end anonymous namespace
181 
ObjCMigrateAction(std::unique_ptr<FrontendAction> WrappedAction,StringRef migrateDir,unsigned migrateAction)182 ObjCMigrateAction::ObjCMigrateAction(
183                                   std::unique_ptr<FrontendAction> WrappedAction,
184                                      StringRef migrateDir,
185                                      unsigned migrateAction)
186   : WrapperFrontendAction(std::move(WrappedAction)), MigrateDir(migrateDir),
187     ObjCMigAction(migrateAction),
188     CompInst(nullptr) {
189   if (MigrateDir.empty())
190     MigrateDir = "."; // user current directory if none is given.
191 }
192 
193 std::unique_ptr<ASTConsumer>
CreateASTConsumer(CompilerInstance & CI,StringRef InFile)194 ObjCMigrateAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
195   PPConditionalDirectiveRecord *
196     PPRec = new PPConditionalDirectiveRecord(CompInst->getSourceManager());
197   CI.getPreprocessor().addPPCallbacks(std::unique_ptr<PPCallbacks>(PPRec));
198   std::vector<std::unique_ptr<ASTConsumer>> Consumers;
199   Consumers.push_back(WrapperFrontendAction::CreateASTConsumer(CI, InFile));
200   Consumers.push_back(llvm::make_unique<ObjCMigrateASTConsumer>(
201       MigrateDir, ObjCMigAction, Remapper, CompInst->getFileManager(), PPRec,
202       CompInst->getPreprocessor(), false, None));
203   return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
204 }
205 
BeginInvocation(CompilerInstance & CI)206 bool ObjCMigrateAction::BeginInvocation(CompilerInstance &CI) {
207   Remapper.initFromDisk(MigrateDir, CI.getDiagnostics(),
208                         /*ignoreIfFilesChanges=*/true);
209   CompInst = &CI;
210   CI.getDiagnostics().setIgnoreAllWarnings(true);
211   return true;
212 }
213 
214 namespace {
215   // FIXME. This duplicates one in RewriteObjCFoundationAPI.cpp
subscriptOperatorNeedsParens(const Expr * FullExpr)216   bool subscriptOperatorNeedsParens(const Expr *FullExpr) {
217     const Expr* Expr = FullExpr->IgnoreImpCasts();
218     return !(isa<ArraySubscriptExpr>(Expr) || isa<CallExpr>(Expr) ||
219              isa<DeclRefExpr>(Expr) || isa<CXXNamedCastExpr>(Expr) ||
220              isa<CXXConstructExpr>(Expr) || isa<CXXThisExpr>(Expr) ||
221              isa<CXXTypeidExpr>(Expr) ||
222              isa<CXXUnresolvedConstructExpr>(Expr) ||
223              isa<ObjCMessageExpr>(Expr) || isa<ObjCPropertyRefExpr>(Expr) ||
224              isa<ObjCProtocolExpr>(Expr) || isa<MemberExpr>(Expr) ||
225              isa<ObjCIvarRefExpr>(Expr) || isa<ParenExpr>(FullExpr) ||
226              isa<ParenListExpr>(Expr) || isa<SizeOfPackExpr>(Expr));
227   }
228 
229   /// \brief - Rewrite message expression for Objective-C setter and getters into
230   /// property-dot syntax.
rewriteToPropertyDotSyntax(const ObjCMessageExpr * Msg,Preprocessor & PP,const NSAPI & NS,edit::Commit & commit,const ParentMap * PMap)231   bool rewriteToPropertyDotSyntax(const ObjCMessageExpr *Msg,
232                                   Preprocessor &PP,
233                                   const NSAPI &NS, edit::Commit &commit,
234                                   const ParentMap *PMap) {
235     if (!Msg || Msg->isImplicit() ||
236         (Msg->getReceiverKind() != ObjCMessageExpr::Instance &&
237          Msg->getReceiverKind() != ObjCMessageExpr::SuperInstance))
238       return false;
239     if (const Expr *Receiver = Msg->getInstanceReceiver())
240       if (Receiver->getType()->isObjCBuiltinType())
241         return false;
242 
243     const ObjCMethodDecl *Method = Msg->getMethodDecl();
244     if (!Method)
245       return false;
246     if (!Method->isPropertyAccessor())
247       return false;
248 
249     const ObjCPropertyDecl *Prop = Method->findPropertyDecl();
250     if (!Prop)
251       return false;
252 
253     SourceRange MsgRange = Msg->getSourceRange();
254     bool ReceiverIsSuper =
255       (Msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
256     // for 'super' receiver is nullptr.
257     const Expr *receiver = Msg->getInstanceReceiver();
258     bool NeedsParen =
259       ReceiverIsSuper ? false : subscriptOperatorNeedsParens(receiver);
260     bool IsGetter = (Msg->getNumArgs() == 0);
261     if (IsGetter) {
262       // Find space location range between receiver expression and getter method.
263       SourceLocation BegLoc =
264         ReceiverIsSuper ? Msg->getSuperLoc() : receiver->getLocEnd();
265       BegLoc = PP.getLocForEndOfToken(BegLoc);
266       SourceLocation EndLoc = Msg->getSelectorLoc(0);
267       SourceRange SpaceRange(BegLoc, EndLoc);
268       std::string PropertyDotString;
269       // rewrite getter method expression into: receiver.property or
270       // (receiver).property
271       if (NeedsParen) {
272         commit.insertBefore(receiver->getLocStart(), "(");
273         PropertyDotString = ").";
274       }
275       else
276         PropertyDotString = ".";
277       PropertyDotString += Prop->getName();
278       commit.replace(SpaceRange, PropertyDotString);
279 
280       // remove '[' ']'
281       commit.replace(SourceRange(MsgRange.getBegin(), MsgRange.getBegin()), "");
282       commit.replace(SourceRange(MsgRange.getEnd(), MsgRange.getEnd()), "");
283     } else {
284       if (NeedsParen)
285         commit.insertWrap("(", receiver->getSourceRange(), ")");
286       std::string PropertyDotString = ".";
287       PropertyDotString += Prop->getName();
288       PropertyDotString += " =";
289       const Expr*const* Args = Msg->getArgs();
290       const Expr *RHS = Args[0];
291       if (!RHS)
292         return false;
293       SourceLocation BegLoc =
294         ReceiverIsSuper ? Msg->getSuperLoc() : receiver->getLocEnd();
295       BegLoc = PP.getLocForEndOfToken(BegLoc);
296       SourceLocation EndLoc = RHS->getLocStart();
297       EndLoc = EndLoc.getLocWithOffset(-1);
298       const char *colon = PP.getSourceManager().getCharacterData(EndLoc);
299       // Add a space after '=' if there is no space between RHS and '='
300       if (colon && colon[0] == ':')
301         PropertyDotString += " ";
302       SourceRange Range(BegLoc, EndLoc);
303       commit.replace(Range, PropertyDotString);
304       // remove '[' ']'
305       commit.replace(SourceRange(MsgRange.getBegin(), MsgRange.getBegin()), "");
306       commit.replace(SourceRange(MsgRange.getEnd(), MsgRange.getEnd()), "");
307     }
308     return true;
309   }
310 
311 class ObjCMigrator : public RecursiveASTVisitor<ObjCMigrator> {
312   ObjCMigrateASTConsumer &Consumer;
313   ParentMap &PMap;
314 
315 public:
ObjCMigrator(ObjCMigrateASTConsumer & consumer,ParentMap & PMap)316   ObjCMigrator(ObjCMigrateASTConsumer &consumer, ParentMap &PMap)
317     : Consumer(consumer), PMap(PMap) { }
318 
shouldVisitTemplateInstantiations() const319   bool shouldVisitTemplateInstantiations() const { return false; }
shouldWalkTypesOfTypeLocs() const320   bool shouldWalkTypesOfTypeLocs() const { return false; }
321 
VisitObjCMessageExpr(ObjCMessageExpr * E)322   bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
323     if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_Literals) {
324       edit::Commit commit(*Consumer.Editor);
325       edit::rewriteToObjCLiteralSyntax(E, *Consumer.NSAPIObj, commit, &PMap);
326       Consumer.Editor->commit(commit);
327     }
328 
329     if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_Subscripting) {
330       edit::Commit commit(*Consumer.Editor);
331       edit::rewriteToObjCSubscriptSyntax(E, *Consumer.NSAPIObj, commit);
332       Consumer.Editor->commit(commit);
333     }
334 
335     if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_PropertyDotSyntax) {
336       edit::Commit commit(*Consumer.Editor);
337       rewriteToPropertyDotSyntax(E, Consumer.PP, *Consumer.NSAPIObj,
338                                  commit, &PMap);
339       Consumer.Editor->commit(commit);
340     }
341 
342     return true;
343   }
344 
TraverseObjCMessageExpr(ObjCMessageExpr * E)345   bool TraverseObjCMessageExpr(ObjCMessageExpr *E) {
346     // Do depth first; we want to rewrite the subexpressions first so that if
347     // we have to move expressions we will move them already rewritten.
348     for (Stmt *SubStmt : E->children())
349       if (!TraverseStmt(SubStmt))
350         return false;
351 
352     return WalkUpFromObjCMessageExpr(E);
353   }
354 };
355 
356 class BodyMigrator : public RecursiveASTVisitor<BodyMigrator> {
357   ObjCMigrateASTConsumer &Consumer;
358   std::unique_ptr<ParentMap> PMap;
359 
360 public:
BodyMigrator(ObjCMigrateASTConsumer & consumer)361   BodyMigrator(ObjCMigrateASTConsumer &consumer) : Consumer(consumer) { }
362 
shouldVisitTemplateInstantiations() const363   bool shouldVisitTemplateInstantiations() const { return false; }
shouldWalkTypesOfTypeLocs() const364   bool shouldWalkTypesOfTypeLocs() const { return false; }
365 
TraverseStmt(Stmt * S)366   bool TraverseStmt(Stmt *S) {
367     PMap.reset(new ParentMap(S));
368     ObjCMigrator(Consumer, *PMap).TraverseStmt(S);
369     return true;
370   }
371 };
372 } // end anonymous namespace
373 
migrateDecl(Decl * D)374 void ObjCMigrateASTConsumer::migrateDecl(Decl *D) {
375   if (!D)
376     return;
377   if (isa<ObjCMethodDecl>(D))
378     return; // Wait for the ObjC container declaration.
379 
380   BodyMigrator(*this).TraverseDecl(D);
381 }
382 
append_attr(std::string & PropertyString,const char * attr,bool & LParenAdded)383 static void append_attr(std::string &PropertyString, const char *attr,
384                         bool &LParenAdded) {
385   if (!LParenAdded) {
386     PropertyString += "(";
387     LParenAdded = true;
388   }
389   else
390     PropertyString += ", ";
391   PropertyString += attr;
392 }
393 
394 static
MigrateBlockOrFunctionPointerTypeVariable(std::string & PropertyString,const std::string & TypeString,const char * name)395 void MigrateBlockOrFunctionPointerTypeVariable(std::string & PropertyString,
396                                                const std::string& TypeString,
397                                                const char *name) {
398   const char *argPtr = TypeString.c_str();
399   int paren = 0;
400   while (*argPtr) {
401     switch (*argPtr) {
402       case '(':
403         PropertyString += *argPtr;
404         paren++;
405         break;
406       case ')':
407         PropertyString += *argPtr;
408         paren--;
409         break;
410       case '^':
411       case '*':
412         PropertyString += (*argPtr);
413         if (paren == 1) {
414           PropertyString += name;
415           name = "";
416         }
417         break;
418       default:
419         PropertyString += *argPtr;
420         break;
421     }
422     argPtr++;
423   }
424 }
425 
PropertyMemoryAttribute(ASTContext & Context,QualType ArgType)426 static const char *PropertyMemoryAttribute(ASTContext &Context, QualType ArgType) {
427   Qualifiers::ObjCLifetime propertyLifetime = ArgType.getObjCLifetime();
428   bool RetainableObject = ArgType->isObjCRetainableType();
429   if (RetainableObject &&
430       (propertyLifetime == Qualifiers::OCL_Strong
431        || propertyLifetime == Qualifiers::OCL_None)) {
432     if (const ObjCObjectPointerType *ObjPtrTy =
433         ArgType->getAs<ObjCObjectPointerType>()) {
434       ObjCInterfaceDecl *IDecl = ObjPtrTy->getObjectType()->getInterface();
435       if (IDecl &&
436           IDecl->lookupNestedProtocol(&Context.Idents.get("NSCopying")))
437         return "copy";
438       else
439         return "strong";
440     }
441     else if (ArgType->isBlockPointerType())
442       return "copy";
443   } else if (propertyLifetime == Qualifiers::OCL_Weak)
444     // TODO. More precise determination of 'weak' attribute requires
445     // looking into setter's implementation for backing weak ivar.
446     return "weak";
447   else if (RetainableObject)
448     return ArgType->isBlockPointerType() ? "copy" : "strong";
449   return nullptr;
450 }
451 
rewriteToObjCProperty(const ObjCMethodDecl * Getter,const ObjCMethodDecl * Setter,const NSAPI & NS,edit::Commit & commit,unsigned LengthOfPrefix,bool Atomic,bool UseNsIosOnlyMacro,bool AvailabilityArgsMatch)452 static void rewriteToObjCProperty(const ObjCMethodDecl *Getter,
453                                   const ObjCMethodDecl *Setter,
454                                   const NSAPI &NS, edit::Commit &commit,
455                                   unsigned LengthOfPrefix,
456                                   bool Atomic, bool UseNsIosOnlyMacro,
457                                   bool AvailabilityArgsMatch) {
458   ASTContext &Context = NS.getASTContext();
459   bool LParenAdded = false;
460   std::string PropertyString = "@property ";
461   if (UseNsIosOnlyMacro && NS.isMacroDefined("NS_NONATOMIC_IOSONLY")) {
462     PropertyString += "(NS_NONATOMIC_IOSONLY";
463     LParenAdded = true;
464   } else if (!Atomic) {
465     PropertyString += "(nonatomic";
466     LParenAdded = true;
467   }
468 
469   std::string PropertyNameString = Getter->getNameAsString();
470   StringRef PropertyName(PropertyNameString);
471   if (LengthOfPrefix > 0) {
472     if (!LParenAdded) {
473       PropertyString += "(getter=";
474       LParenAdded = true;
475     }
476     else
477       PropertyString += ", getter=";
478     PropertyString += PropertyNameString;
479   }
480   // Property with no setter may be suggested as a 'readonly' property.
481   if (!Setter)
482     append_attr(PropertyString, "readonly", LParenAdded);
483 
484 
485   // Short circuit 'delegate' properties that contain the name "delegate" or
486   // "dataSource", or have exact name "target" to have 'assign' attribute.
487   if (PropertyName.equals("target") ||
488       (PropertyName.find("delegate") != StringRef::npos) ||
489       (PropertyName.find("dataSource") != StringRef::npos)) {
490     QualType QT = Getter->getReturnType();
491     if (!QT->isRealType())
492       append_attr(PropertyString, "assign", LParenAdded);
493   } else if (!Setter) {
494     QualType ResType = Context.getCanonicalType(Getter->getReturnType());
495     if (const char *MemoryManagementAttr = PropertyMemoryAttribute(Context, ResType))
496       append_attr(PropertyString, MemoryManagementAttr, LParenAdded);
497   } else {
498     const ParmVarDecl *argDecl = *Setter->param_begin();
499     QualType ArgType = Context.getCanonicalType(argDecl->getType());
500     if (const char *MemoryManagementAttr = PropertyMemoryAttribute(Context, ArgType))
501       append_attr(PropertyString, MemoryManagementAttr, LParenAdded);
502   }
503   if (LParenAdded)
504     PropertyString += ')';
505   QualType RT = Getter->getReturnType();
506   if (!isa<TypedefType>(RT)) {
507     // strip off any ARC lifetime qualifier.
508     QualType CanResultTy = Context.getCanonicalType(RT);
509     if (CanResultTy.getQualifiers().hasObjCLifetime()) {
510       Qualifiers Qs = CanResultTy.getQualifiers();
511       Qs.removeObjCLifetime();
512       RT = Context.getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
513     }
514   }
515   PropertyString += " ";
516   PrintingPolicy SubPolicy(Context.getPrintingPolicy());
517   SubPolicy.SuppressStrongLifetime = true;
518   SubPolicy.SuppressLifetimeQualifiers = true;
519   std::string TypeString = RT.getAsString(SubPolicy);
520   if (LengthOfPrefix > 0) {
521     // property name must strip off "is" and lower case the first character
522     // after that; e.g. isContinuous will become continuous.
523     StringRef PropertyNameStringRef(PropertyNameString);
524     PropertyNameStringRef = PropertyNameStringRef.drop_front(LengthOfPrefix);
525     PropertyNameString = PropertyNameStringRef;
526     bool NoLowering = (isUppercase(PropertyNameString[0]) &&
527                        PropertyNameString.size() > 1 &&
528                        isUppercase(PropertyNameString[1]));
529     if (!NoLowering)
530       PropertyNameString[0] = toLowercase(PropertyNameString[0]);
531   }
532   if (RT->isBlockPointerType() || RT->isFunctionPointerType())
533     MigrateBlockOrFunctionPointerTypeVariable(PropertyString,
534                                               TypeString,
535                                               PropertyNameString.c_str());
536   else {
537     char LastChar = TypeString[TypeString.size()-1];
538     PropertyString += TypeString;
539     if (LastChar != '*')
540       PropertyString += ' ';
541     PropertyString += PropertyNameString;
542   }
543   SourceLocation StartGetterSelectorLoc = Getter->getSelectorStartLoc();
544   Selector GetterSelector = Getter->getSelector();
545 
546   SourceLocation EndGetterSelectorLoc =
547     StartGetterSelectorLoc.getLocWithOffset(GetterSelector.getNameForSlot(0).size());
548   commit.replace(CharSourceRange::getCharRange(Getter->getLocStart(),
549                                                EndGetterSelectorLoc),
550                  PropertyString);
551   if (Setter && AvailabilityArgsMatch) {
552     SourceLocation EndLoc = Setter->getDeclaratorEndLoc();
553     // Get location past ';'
554     EndLoc = EndLoc.getLocWithOffset(1);
555     SourceLocation BeginOfSetterDclLoc = Setter->getLocStart();
556     // FIXME. This assumes that setter decl; is immediately preceded by eoln.
557     // It is trying to remove the setter method decl. line entirely.
558     BeginOfSetterDclLoc = BeginOfSetterDclLoc.getLocWithOffset(-1);
559     commit.remove(SourceRange(BeginOfSetterDclLoc, EndLoc));
560   }
561 }
562 
IsCategoryNameWithDeprecatedSuffix(ObjCContainerDecl * D)563 static bool IsCategoryNameWithDeprecatedSuffix(ObjCContainerDecl *D) {
564   if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(D)) {
565     StringRef Name = CatDecl->getName();
566     return Name.endswith("Deprecated");
567   }
568   return false;
569 }
570 
migrateObjCContainerDecl(ASTContext & Ctx,ObjCContainerDecl * D)571 void ObjCMigrateASTConsumer::migrateObjCContainerDecl(ASTContext &Ctx,
572                                                       ObjCContainerDecl *D) {
573   if (D->isDeprecated() || IsCategoryNameWithDeprecatedSuffix(D))
574     return;
575 
576   for (auto *Method : D->methods()) {
577     if (Method->isDeprecated())
578       continue;
579     bool PropertyInferred = migrateProperty(Ctx, D, Method);
580     // If a property is inferred, do not attempt to attach NS_RETURNS_INNER_POINTER to
581     // the getter method as it ends up on the property itself which we don't want
582     // to do unless -objcmt-returns-innerpointer-property  option is on.
583     if (!PropertyInferred ||
584         (ASTMigrateActions & FrontendOptions::ObjCMT_ReturnsInnerPointerProperty))
585       if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
586         migrateNsReturnsInnerPointer(Ctx, Method);
587   }
588   if (!(ASTMigrateActions & FrontendOptions::ObjCMT_ReturnsInnerPointerProperty))
589     return;
590 
591   for (auto *Prop : D->instance_properties()) {
592     if ((ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) &&
593         !Prop->isDeprecated())
594       migratePropertyNsReturnsInnerPointer(Ctx, Prop);
595   }
596 }
597 
598 static bool
ClassImplementsAllMethodsAndProperties(ASTContext & Ctx,const ObjCImplementationDecl * ImpDecl,const ObjCInterfaceDecl * IDecl,ObjCProtocolDecl * Protocol)599 ClassImplementsAllMethodsAndProperties(ASTContext &Ctx,
600                                       const ObjCImplementationDecl *ImpDecl,
601                                        const ObjCInterfaceDecl *IDecl,
602                                       ObjCProtocolDecl *Protocol) {
603   // In auto-synthesis, protocol properties are not synthesized. So,
604   // a conforming protocol must have its required properties declared
605   // in class interface.
606   bool HasAtleastOneRequiredProperty = false;
607   if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition())
608     for (const auto *Property : PDecl->instance_properties()) {
609       if (Property->getPropertyImplementation() == ObjCPropertyDecl::Optional)
610         continue;
611       HasAtleastOneRequiredProperty = true;
612       DeclContext::lookup_result R = IDecl->lookup(Property->getDeclName());
613       if (R.size() == 0) {
614         // Relax the rule and look into class's implementation for a synthesize
615         // or dynamic declaration. Class is implementing a property coming from
616         // another protocol. This still makes the target protocol as conforming.
617         if (!ImpDecl->FindPropertyImplDecl(
618                                   Property->getDeclName().getAsIdentifierInfo(),
619                                   Property->getQueryKind()))
620           return false;
621       }
622       else if (ObjCPropertyDecl *ClassProperty = dyn_cast<ObjCPropertyDecl>(R[0])) {
623           if ((ClassProperty->getPropertyAttributes()
624               != Property->getPropertyAttributes()) ||
625               !Ctx.hasSameType(ClassProperty->getType(), Property->getType()))
626             return false;
627       }
628       else
629         return false;
630     }
631 
632   // At this point, all required properties in this protocol conform to those
633   // declared in the class.
634   // Check that class implements the required methods of the protocol too.
635   bool HasAtleastOneRequiredMethod = false;
636   if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition()) {
637     if (PDecl->meth_begin() == PDecl->meth_end())
638       return HasAtleastOneRequiredProperty;
639     for (const auto *MD : PDecl->methods()) {
640       if (MD->isImplicit())
641         continue;
642       if (MD->getImplementationControl() == ObjCMethodDecl::Optional)
643         continue;
644       DeclContext::lookup_result R = ImpDecl->lookup(MD->getDeclName());
645       if (R.size() == 0)
646         return false;
647       bool match = false;
648       HasAtleastOneRequiredMethod = true;
649       for (unsigned I = 0, N = R.size(); I != N; ++I)
650         if (ObjCMethodDecl *ImpMD = dyn_cast<ObjCMethodDecl>(R[0]))
651           if (Ctx.ObjCMethodsAreEqual(MD, ImpMD)) {
652             match = true;
653             break;
654           }
655       if (!match)
656         return false;
657     }
658   }
659   return HasAtleastOneRequiredProperty || HasAtleastOneRequiredMethod;
660 }
661 
rewriteToObjCInterfaceDecl(const ObjCInterfaceDecl * IDecl,llvm::SmallVectorImpl<ObjCProtocolDecl * > & ConformingProtocols,const NSAPI & NS,edit::Commit & commit)662 static bool rewriteToObjCInterfaceDecl(const ObjCInterfaceDecl *IDecl,
663                     llvm::SmallVectorImpl<ObjCProtocolDecl*> &ConformingProtocols,
664                     const NSAPI &NS, edit::Commit &commit) {
665   const ObjCList<ObjCProtocolDecl> &Protocols = IDecl->getReferencedProtocols();
666   std::string ClassString;
667   SourceLocation EndLoc =
668   IDecl->getSuperClass() ? IDecl->getSuperClassLoc() : IDecl->getLocation();
669 
670   if (Protocols.empty()) {
671     ClassString = '<';
672     for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
673       ClassString += ConformingProtocols[i]->getNameAsString();
674       if (i != (e-1))
675         ClassString += ", ";
676     }
677     ClassString += "> ";
678   }
679   else {
680     ClassString = ", ";
681     for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
682       ClassString += ConformingProtocols[i]->getNameAsString();
683       if (i != (e-1))
684         ClassString += ", ";
685     }
686     ObjCInterfaceDecl::protocol_loc_iterator PL = IDecl->protocol_loc_end() - 1;
687     EndLoc = *PL;
688   }
689 
690   commit.insertAfterToken(EndLoc, ClassString);
691   return true;
692 }
693 
GetUnsignedName(StringRef NSIntegerName)694 static StringRef GetUnsignedName(StringRef NSIntegerName) {
695   StringRef UnsignedName = llvm::StringSwitch<StringRef>(NSIntegerName)
696     .Case("int8_t", "uint8_t")
697     .Case("int16_t", "uint16_t")
698     .Case("int32_t", "uint32_t")
699     .Case("NSInteger", "NSUInteger")
700     .Case("int64_t", "uint64_t")
701     .Default(NSIntegerName);
702   return UnsignedName;
703 }
704 
rewriteToNSEnumDecl(const EnumDecl * EnumDcl,const TypedefDecl * TypedefDcl,const NSAPI & NS,edit::Commit & commit,StringRef NSIntegerName,bool NSOptions)705 static bool rewriteToNSEnumDecl(const EnumDecl *EnumDcl,
706                                 const TypedefDecl *TypedefDcl,
707                                 const NSAPI &NS, edit::Commit &commit,
708                                 StringRef NSIntegerName,
709                                 bool NSOptions) {
710   std::string ClassString;
711   if (NSOptions) {
712     ClassString = "typedef NS_OPTIONS(";
713     ClassString += GetUnsignedName(NSIntegerName);
714   }
715   else {
716     ClassString = "typedef NS_ENUM(";
717     ClassString += NSIntegerName;
718   }
719   ClassString += ", ";
720 
721   ClassString += TypedefDcl->getIdentifier()->getName();
722   ClassString += ')';
723   SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
724   commit.replace(R, ClassString);
725   SourceLocation EndOfEnumDclLoc = EnumDcl->getLocEnd();
726   EndOfEnumDclLoc = trans::findSemiAfterLocation(EndOfEnumDclLoc,
727                                                  NS.getASTContext(), /*IsDecl*/true);
728   if (EndOfEnumDclLoc.isValid()) {
729     SourceRange EnumDclRange(EnumDcl->getLocStart(), EndOfEnumDclLoc);
730     commit.insertFromRange(TypedefDcl->getLocStart(), EnumDclRange);
731   }
732   else
733     return false;
734 
735   SourceLocation EndTypedefDclLoc = TypedefDcl->getLocEnd();
736   EndTypedefDclLoc = trans::findSemiAfterLocation(EndTypedefDclLoc,
737                                                  NS.getASTContext(), /*IsDecl*/true);
738   if (EndTypedefDclLoc.isValid()) {
739     SourceRange TDRange(TypedefDcl->getLocStart(), EndTypedefDclLoc);
740     commit.remove(TDRange);
741   }
742   else
743     return false;
744 
745   EndOfEnumDclLoc = trans::findLocationAfterSemi(EnumDcl->getLocEnd(), NS.getASTContext(),
746                                                  /*IsDecl*/true);
747   if (EndOfEnumDclLoc.isValid()) {
748     SourceLocation BeginOfEnumDclLoc = EnumDcl->getLocStart();
749     // FIXME. This assumes that enum decl; is immediately preceded by eoln.
750     // It is trying to remove the enum decl. lines entirely.
751     BeginOfEnumDclLoc = BeginOfEnumDclLoc.getLocWithOffset(-1);
752     commit.remove(SourceRange(BeginOfEnumDclLoc, EndOfEnumDclLoc));
753     return true;
754   }
755   return false;
756 }
757 
rewriteToNSMacroDecl(ASTContext & Ctx,const EnumDecl * EnumDcl,const TypedefDecl * TypedefDcl,const NSAPI & NS,edit::Commit & commit,bool IsNSIntegerType)758 static void rewriteToNSMacroDecl(ASTContext &Ctx,
759                                  const EnumDecl *EnumDcl,
760                                 const TypedefDecl *TypedefDcl,
761                                 const NSAPI &NS, edit::Commit &commit,
762                                  bool IsNSIntegerType) {
763   QualType DesignatedEnumType = EnumDcl->getIntegerType();
764   assert(!DesignatedEnumType.isNull()
765          && "rewriteToNSMacroDecl - underlying enum type is null");
766 
767   PrintingPolicy Policy(Ctx.getPrintingPolicy());
768   std::string TypeString = DesignatedEnumType.getAsString(Policy);
769   std::string ClassString = IsNSIntegerType ? "NS_ENUM(" : "NS_OPTIONS(";
770   ClassString += TypeString;
771   ClassString += ", ";
772 
773   ClassString += TypedefDcl->getIdentifier()->getName();
774   ClassString += ')';
775   SourceLocation EndLoc;
776   if (EnumDcl->getIntegerTypeSourceInfo()) {
777     TypeSourceInfo *TSourceInfo = EnumDcl->getIntegerTypeSourceInfo();
778     TypeLoc TLoc = TSourceInfo->getTypeLoc();
779     EndLoc = TLoc.getLocEnd();
780     const char *lbrace = Ctx.getSourceManager().getCharacterData(EndLoc);
781     unsigned count = 0;
782     if (lbrace)
783       while (lbrace[count] != '{')
784         ++count;
785     if (count > 0)
786       EndLoc = EndLoc.getLocWithOffset(count-1);
787   }
788   else
789     EndLoc = EnumDcl->getLocStart();
790   SourceRange R(EnumDcl->getLocStart(), EndLoc);
791   commit.replace(R, ClassString);
792   // This is to remove spaces between '}' and typedef name.
793   SourceLocation StartTypedefLoc = EnumDcl->getLocEnd();
794   StartTypedefLoc = StartTypedefLoc.getLocWithOffset(+1);
795   SourceLocation EndTypedefLoc = TypedefDcl->getLocEnd();
796 
797   commit.remove(SourceRange(StartTypedefLoc, EndTypedefLoc));
798 }
799 
UseNSOptionsMacro(Preprocessor & PP,ASTContext & Ctx,const EnumDecl * EnumDcl)800 static bool UseNSOptionsMacro(Preprocessor &PP, ASTContext &Ctx,
801                               const EnumDecl *EnumDcl) {
802   bool PowerOfTwo = true;
803   bool AllHexdecimalEnumerator = true;
804   uint64_t MaxPowerOfTwoVal = 0;
805   for (auto Enumerator : EnumDcl->enumerators()) {
806     const Expr *InitExpr = Enumerator->getInitExpr();
807     if (!InitExpr) {
808       PowerOfTwo = false;
809       AllHexdecimalEnumerator = false;
810       continue;
811     }
812     InitExpr = InitExpr->IgnoreParenCasts();
813     if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr))
814       if (BO->isShiftOp() || BO->isBitwiseOp())
815         return true;
816 
817     uint64_t EnumVal = Enumerator->getInitVal().getZExtValue();
818     if (PowerOfTwo && EnumVal) {
819       if (!llvm::isPowerOf2_64(EnumVal))
820         PowerOfTwo = false;
821       else if (EnumVal > MaxPowerOfTwoVal)
822         MaxPowerOfTwoVal = EnumVal;
823     }
824     if (AllHexdecimalEnumerator && EnumVal) {
825       bool FoundHexdecimalEnumerator = false;
826       SourceLocation EndLoc = Enumerator->getLocEnd();
827       Token Tok;
828       if (!PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true))
829         if (Tok.isLiteral() && Tok.getLength() > 2) {
830           if (const char *StringLit = Tok.getLiteralData())
831             FoundHexdecimalEnumerator =
832               (StringLit[0] == '0' && (toLowercase(StringLit[1]) == 'x'));
833         }
834       if (!FoundHexdecimalEnumerator)
835         AllHexdecimalEnumerator = false;
836     }
837   }
838   return AllHexdecimalEnumerator || (PowerOfTwo && (MaxPowerOfTwoVal > 2));
839 }
840 
migrateProtocolConformance(ASTContext & Ctx,const ObjCImplementationDecl * ImpDecl)841 void ObjCMigrateASTConsumer::migrateProtocolConformance(ASTContext &Ctx,
842                                             const ObjCImplementationDecl *ImpDecl) {
843   const ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface();
844   if (!IDecl || ObjCProtocolDecls.empty() || IDecl->isDeprecated())
845     return;
846   // Find all implicit conforming protocols for this class
847   // and make them explicit.
848   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ExplicitProtocols;
849   Ctx.CollectInheritedProtocols(IDecl, ExplicitProtocols);
850   llvm::SmallVector<ObjCProtocolDecl *, 8> PotentialImplicitProtocols;
851 
852   for (ObjCProtocolDecl *ProtDecl : ObjCProtocolDecls)
853     if (!ExplicitProtocols.count(ProtDecl))
854       PotentialImplicitProtocols.push_back(ProtDecl);
855 
856   if (PotentialImplicitProtocols.empty())
857     return;
858 
859   // go through list of non-optional methods and properties in each protocol
860   // in the PotentialImplicitProtocols list. If class implements every one of the
861   // methods and properties, then this class conforms to this protocol.
862   llvm::SmallVector<ObjCProtocolDecl*, 8> ConformingProtocols;
863   for (unsigned i = 0, e = PotentialImplicitProtocols.size(); i != e; i++)
864     if (ClassImplementsAllMethodsAndProperties(Ctx, ImpDecl, IDecl,
865                                               PotentialImplicitProtocols[i]))
866       ConformingProtocols.push_back(PotentialImplicitProtocols[i]);
867 
868   if (ConformingProtocols.empty())
869     return;
870 
871   // Further reduce number of conforming protocols. If protocol P1 is in the list
872   // protocol P2 (P2<P1>), No need to include P1.
873   llvm::SmallVector<ObjCProtocolDecl*, 8> MinimalConformingProtocols;
874   for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
875     bool DropIt = false;
876     ObjCProtocolDecl *TargetPDecl = ConformingProtocols[i];
877     for (unsigned i1 = 0, e1 = ConformingProtocols.size(); i1 != e1; i1++) {
878       ObjCProtocolDecl *PDecl = ConformingProtocols[i1];
879       if (PDecl == TargetPDecl)
880         continue;
881       if (PDecl->lookupProtocolNamed(
882             TargetPDecl->getDeclName().getAsIdentifierInfo())) {
883         DropIt = true;
884         break;
885       }
886     }
887     if (!DropIt)
888       MinimalConformingProtocols.push_back(TargetPDecl);
889   }
890   if (MinimalConformingProtocols.empty())
891     return;
892   edit::Commit commit(*Editor);
893   rewriteToObjCInterfaceDecl(IDecl, MinimalConformingProtocols,
894                              *NSAPIObj, commit);
895   Editor->commit(commit);
896 }
897 
CacheObjCNSIntegerTypedefed(const TypedefDecl * TypedefDcl)898 void ObjCMigrateASTConsumer::CacheObjCNSIntegerTypedefed(
899                                           const TypedefDecl *TypedefDcl) {
900 
901   QualType qt = TypedefDcl->getTypeSourceInfo()->getType();
902   if (NSAPIObj->isObjCNSIntegerType(qt))
903     NSIntegerTypedefed = TypedefDcl;
904   else if (NSAPIObj->isObjCNSUIntegerType(qt))
905     NSUIntegerTypedefed = TypedefDcl;
906 }
907 
migrateNSEnumDecl(ASTContext & Ctx,const EnumDecl * EnumDcl,const TypedefDecl * TypedefDcl)908 bool ObjCMigrateASTConsumer::migrateNSEnumDecl(ASTContext &Ctx,
909                                            const EnumDecl *EnumDcl,
910                                            const TypedefDecl *TypedefDcl) {
911   if (!EnumDcl->isCompleteDefinition() || EnumDcl->getIdentifier() ||
912       EnumDcl->isDeprecated())
913     return false;
914   if (!TypedefDcl) {
915     if (NSIntegerTypedefed) {
916       TypedefDcl = NSIntegerTypedefed;
917       NSIntegerTypedefed = nullptr;
918     }
919     else if (NSUIntegerTypedefed) {
920       TypedefDcl = NSUIntegerTypedefed;
921       NSUIntegerTypedefed = nullptr;
922     }
923     else
924       return false;
925     FileID FileIdOfTypedefDcl =
926       PP.getSourceManager().getFileID(TypedefDcl->getLocation());
927     FileID FileIdOfEnumDcl =
928       PP.getSourceManager().getFileID(EnumDcl->getLocation());
929     if (FileIdOfTypedefDcl != FileIdOfEnumDcl)
930       return false;
931   }
932   if (TypedefDcl->isDeprecated())
933     return false;
934 
935   QualType qt = TypedefDcl->getTypeSourceInfo()->getType();
936   StringRef NSIntegerName = NSAPIObj->GetNSIntegralKind(qt);
937 
938   if (NSIntegerName.empty()) {
939     // Also check for typedef enum {...} TD;
940     if (const EnumType *EnumTy = qt->getAs<EnumType>()) {
941       if (EnumTy->getDecl() == EnumDcl) {
942         bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl);
943         if (!InsertFoundation(Ctx, TypedefDcl->getLocStart()))
944           return false;
945         edit::Commit commit(*Editor);
946         rewriteToNSMacroDecl(Ctx, EnumDcl, TypedefDcl, *NSAPIObj, commit, !NSOptions);
947         Editor->commit(commit);
948         return true;
949       }
950     }
951     return false;
952   }
953 
954   // We may still use NS_OPTIONS based on what we find in the enumertor list.
955   bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl);
956   if (!InsertFoundation(Ctx, TypedefDcl->getLocStart()))
957     return false;
958   edit::Commit commit(*Editor);
959   bool Res = rewriteToNSEnumDecl(EnumDcl, TypedefDcl, *NSAPIObj,
960                                  commit, NSIntegerName, NSOptions);
961   Editor->commit(commit);
962   return Res;
963 }
964 
ReplaceWithInstancetype(ASTContext & Ctx,const ObjCMigrateASTConsumer & ASTC,ObjCMethodDecl * OM)965 static void ReplaceWithInstancetype(ASTContext &Ctx,
966                                     const ObjCMigrateASTConsumer &ASTC,
967                                     ObjCMethodDecl *OM) {
968   if (OM->getReturnType() == Ctx.getObjCInstanceType())
969     return; // already has instancetype.
970 
971   SourceRange R;
972   std::string ClassString;
973   if (TypeSourceInfo *TSInfo = OM->getReturnTypeSourceInfo()) {
974     TypeLoc TL = TSInfo->getTypeLoc();
975     R = SourceRange(TL.getBeginLoc(), TL.getEndLoc());
976     ClassString = "instancetype";
977   }
978   else {
979     R = SourceRange(OM->getLocStart(), OM->getLocStart());
980     ClassString = OM->isInstanceMethod() ? '-' : '+';
981     ClassString += " (instancetype)";
982   }
983   edit::Commit commit(*ASTC.Editor);
984   commit.replace(R, ClassString);
985   ASTC.Editor->commit(commit);
986 }
987 
ReplaceWithClasstype(const ObjCMigrateASTConsumer & ASTC,ObjCMethodDecl * OM)988 static void ReplaceWithClasstype(const ObjCMigrateASTConsumer &ASTC,
989                                     ObjCMethodDecl *OM) {
990   ObjCInterfaceDecl *IDecl = OM->getClassInterface();
991   SourceRange R;
992   std::string ClassString;
993   if (TypeSourceInfo *TSInfo = OM->getReturnTypeSourceInfo()) {
994     TypeLoc TL = TSInfo->getTypeLoc();
995     R = SourceRange(TL.getBeginLoc(), TL.getEndLoc()); {
996       ClassString  = IDecl->getName();
997       ClassString += "*";
998     }
999   }
1000   else {
1001     R = SourceRange(OM->getLocStart(), OM->getLocStart());
1002     ClassString = "+ (";
1003     ClassString += IDecl->getName(); ClassString += "*)";
1004   }
1005   edit::Commit commit(*ASTC.Editor);
1006   commit.replace(R, ClassString);
1007   ASTC.Editor->commit(commit);
1008 }
1009 
migrateMethodInstanceType(ASTContext & Ctx,ObjCContainerDecl * CDecl,ObjCMethodDecl * OM)1010 void ObjCMigrateASTConsumer::migrateMethodInstanceType(ASTContext &Ctx,
1011                                                        ObjCContainerDecl *CDecl,
1012                                                        ObjCMethodDecl *OM) {
1013   ObjCInstanceTypeFamily OIT_Family =
1014     Selector::getInstTypeMethodFamily(OM->getSelector());
1015 
1016   std::string ClassName;
1017   switch (OIT_Family) {
1018     case OIT_None:
1019       migrateFactoryMethod(Ctx, CDecl, OM);
1020       return;
1021     case OIT_Array:
1022       ClassName = "NSArray";
1023       break;
1024     case OIT_Dictionary:
1025       ClassName = "NSDictionary";
1026       break;
1027     case OIT_Singleton:
1028       migrateFactoryMethod(Ctx, CDecl, OM, OIT_Singleton);
1029       return;
1030     case OIT_Init:
1031       if (OM->getReturnType()->isObjCIdType())
1032         ReplaceWithInstancetype(Ctx, *this, OM);
1033       return;
1034     case OIT_ReturnsSelf:
1035       migrateFactoryMethod(Ctx, CDecl, OM, OIT_ReturnsSelf);
1036       return;
1037   }
1038   if (!OM->getReturnType()->isObjCIdType())
1039     return;
1040 
1041   ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
1042   if (!IDecl) {
1043     if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
1044       IDecl = CatDecl->getClassInterface();
1045     else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
1046       IDecl = ImpDecl->getClassInterface();
1047   }
1048   if (!IDecl ||
1049       !IDecl->lookupInheritedClass(&Ctx.Idents.get(ClassName))) {
1050     migrateFactoryMethod(Ctx, CDecl, OM);
1051     return;
1052   }
1053   ReplaceWithInstancetype(Ctx, *this, OM);
1054 }
1055 
TypeIsInnerPointer(QualType T)1056 static bool TypeIsInnerPointer(QualType T) {
1057   if (!T->isAnyPointerType())
1058     return false;
1059   if (T->isObjCObjectPointerType() || T->isObjCBuiltinType() ||
1060       T->isBlockPointerType() || T->isFunctionPointerType() ||
1061       ento::coreFoundation::isCFObjectRef(T))
1062     return false;
1063   // Also, typedef-of-pointer-to-incomplete-struct is something that we assume
1064   // is not an innter pointer type.
1065   QualType OrigT = T;
1066   while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr()))
1067     T = TD->getDecl()->getUnderlyingType();
1068   if (OrigT == T || !T->isPointerType())
1069     return true;
1070   const PointerType* PT = T->getAs<PointerType>();
1071   QualType UPointeeT = PT->getPointeeType().getUnqualifiedType();
1072   if (UPointeeT->isRecordType()) {
1073     const RecordType *RecordTy = UPointeeT->getAs<RecordType>();
1074     if (!RecordTy->getDecl()->isCompleteDefinition())
1075       return false;
1076   }
1077   return true;
1078 }
1079 
1080 /// \brief Check whether the two versions match.
versionsMatch(const VersionTuple & X,const VersionTuple & Y)1081 static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y) {
1082   return (X == Y);
1083 }
1084 
1085 /// AvailabilityAttrsMatch - This routine checks that if comparing two
1086 /// availability attributes, all their components match. It returns
1087 /// true, if not dealing with availability or when all components of
1088 /// availability attributes match. This routine is only called when
1089 /// the attributes are of the same kind.
AvailabilityAttrsMatch(Attr * At1,Attr * At2)1090 static bool AvailabilityAttrsMatch(Attr *At1, Attr *At2) {
1091   const AvailabilityAttr *AA1 = dyn_cast<AvailabilityAttr>(At1);
1092   if (!AA1)
1093     return true;
1094   const AvailabilityAttr *AA2 = dyn_cast<AvailabilityAttr>(At2);
1095 
1096   VersionTuple Introduced1 = AA1->getIntroduced();
1097   VersionTuple Deprecated1 = AA1->getDeprecated();
1098   VersionTuple Obsoleted1 = AA1->getObsoleted();
1099   bool IsUnavailable1 = AA1->getUnavailable();
1100   VersionTuple Introduced2 = AA2->getIntroduced();
1101   VersionTuple Deprecated2 = AA2->getDeprecated();
1102   VersionTuple Obsoleted2 = AA2->getObsoleted();
1103   bool IsUnavailable2 = AA2->getUnavailable();
1104   return (versionsMatch(Introduced1, Introduced2) &&
1105           versionsMatch(Deprecated1, Deprecated2) &&
1106           versionsMatch(Obsoleted1, Obsoleted2) &&
1107           IsUnavailable1 == IsUnavailable2);
1108 }
1109 
MatchTwoAttributeLists(const AttrVec & Attrs1,const AttrVec & Attrs2,bool & AvailabilityArgsMatch)1110 static bool MatchTwoAttributeLists(const AttrVec &Attrs1, const AttrVec &Attrs2,
1111                                    bool &AvailabilityArgsMatch) {
1112   // This list is very small, so this need not be optimized.
1113   for (unsigned i = 0, e = Attrs1.size(); i != e; i++) {
1114     bool match = false;
1115     for (unsigned j = 0, f = Attrs2.size(); j != f; j++) {
1116       // Matching attribute kind only. Except for Availabilty attributes,
1117       // we are not getting into details of the attributes. For all practical purposes
1118       // this is sufficient.
1119       if (Attrs1[i]->getKind() == Attrs2[j]->getKind()) {
1120         if (AvailabilityArgsMatch)
1121           AvailabilityArgsMatch = AvailabilityAttrsMatch(Attrs1[i], Attrs2[j]);
1122         match = true;
1123         break;
1124       }
1125     }
1126     if (!match)
1127       return false;
1128   }
1129   return true;
1130 }
1131 
1132 /// AttributesMatch - This routine checks list of attributes for two
1133 /// decls. It returns false, if there is a mismatch in kind of
1134 /// attributes seen in the decls. It returns true if the two decls
1135 /// have list of same kind of attributes. Furthermore, when there
1136 /// are availability attributes in the two decls, it sets the
1137 /// AvailabilityArgsMatch to false if availability attributes have
1138 /// different versions, etc.
AttributesMatch(const Decl * Decl1,const Decl * Decl2,bool & AvailabilityArgsMatch)1139 static bool AttributesMatch(const Decl *Decl1, const Decl *Decl2,
1140                             bool &AvailabilityArgsMatch) {
1141   if (!Decl1->hasAttrs() || !Decl2->hasAttrs()) {
1142     AvailabilityArgsMatch = (Decl1->hasAttrs() == Decl2->hasAttrs());
1143     return true;
1144   }
1145   AvailabilityArgsMatch = true;
1146   const AttrVec &Attrs1 = Decl1->getAttrs();
1147   const AttrVec &Attrs2 = Decl2->getAttrs();
1148   bool match = MatchTwoAttributeLists(Attrs1, Attrs2, AvailabilityArgsMatch);
1149   if (match && (Attrs2.size() > Attrs1.size()))
1150     return MatchTwoAttributeLists(Attrs2, Attrs1, AvailabilityArgsMatch);
1151   return match;
1152 }
1153 
IsValidIdentifier(ASTContext & Ctx,const char * Name)1154 static bool IsValidIdentifier(ASTContext &Ctx,
1155                               const char *Name) {
1156   if (!isIdentifierHead(Name[0]))
1157     return false;
1158   std::string NameString = Name;
1159   NameString[0] = toLowercase(NameString[0]);
1160   IdentifierInfo *II = &Ctx.Idents.get(NameString);
1161   return II->getTokenID() ==  tok::identifier;
1162 }
1163 
migrateProperty(ASTContext & Ctx,ObjCContainerDecl * D,ObjCMethodDecl * Method)1164 bool ObjCMigrateASTConsumer::migrateProperty(ASTContext &Ctx,
1165                              ObjCContainerDecl *D,
1166                              ObjCMethodDecl *Method) {
1167   if (Method->isPropertyAccessor() || !Method->isInstanceMethod() ||
1168       Method->param_size() != 0)
1169     return false;
1170   // Is this method candidate to be a getter?
1171   QualType GRT = Method->getReturnType();
1172   if (GRT->isVoidType())
1173     return false;
1174 
1175   Selector GetterSelector = Method->getSelector();
1176   ObjCInstanceTypeFamily OIT_Family =
1177     Selector::getInstTypeMethodFamily(GetterSelector);
1178 
1179   if (OIT_Family != OIT_None)
1180     return false;
1181 
1182   IdentifierInfo *getterName = GetterSelector.getIdentifierInfoForSlot(0);
1183   Selector SetterSelector =
1184   SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1185                                          PP.getSelectorTable(),
1186                                          getterName);
1187   ObjCMethodDecl *SetterMethod = D->getInstanceMethod(SetterSelector);
1188   unsigned LengthOfPrefix = 0;
1189   if (!SetterMethod) {
1190     // try a different naming convention for getter: isXxxxx
1191     StringRef getterNameString = getterName->getName();
1192     bool IsPrefix = getterNameString.startswith("is");
1193     // Note that we don't want to change an isXXX method of retainable object
1194     // type to property (readonly or otherwise).
1195     if (IsPrefix && GRT->isObjCRetainableType())
1196       return false;
1197     if (IsPrefix || getterNameString.startswith("get")) {
1198       LengthOfPrefix = (IsPrefix ? 2 : 3);
1199       const char *CGetterName = getterNameString.data() + LengthOfPrefix;
1200       // Make sure that first character after "is" or "get" prefix can
1201       // start an identifier.
1202       if (!IsValidIdentifier(Ctx, CGetterName))
1203         return false;
1204       if (CGetterName[0] && isUppercase(CGetterName[0])) {
1205         getterName = &Ctx.Idents.get(CGetterName);
1206         SetterSelector =
1207         SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1208                                                PP.getSelectorTable(),
1209                                                getterName);
1210         SetterMethod = D->getInstanceMethod(SetterSelector);
1211       }
1212     }
1213   }
1214 
1215   if (SetterMethod) {
1216     if ((ASTMigrateActions & FrontendOptions::ObjCMT_ReadwriteProperty) == 0)
1217       return false;
1218     bool AvailabilityArgsMatch;
1219     if (SetterMethod->isDeprecated() ||
1220         !AttributesMatch(Method, SetterMethod, AvailabilityArgsMatch))
1221       return false;
1222 
1223     // Is this a valid setter, matching the target getter?
1224     QualType SRT = SetterMethod->getReturnType();
1225     if (!SRT->isVoidType())
1226       return false;
1227     const ParmVarDecl *argDecl = *SetterMethod->param_begin();
1228     QualType ArgType = argDecl->getType();
1229     if (!Ctx.hasSameUnqualifiedType(ArgType, GRT))
1230       return false;
1231     edit::Commit commit(*Editor);
1232     rewriteToObjCProperty(Method, SetterMethod, *NSAPIObj, commit,
1233                           LengthOfPrefix,
1234                           (ASTMigrateActions &
1235                            FrontendOptions::ObjCMT_AtomicProperty) != 0,
1236                           (ASTMigrateActions &
1237                            FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty) != 0,
1238                           AvailabilityArgsMatch);
1239     Editor->commit(commit);
1240     return true;
1241   }
1242   else if (ASTMigrateActions & FrontendOptions::ObjCMT_ReadonlyProperty) {
1243     // Try a non-void method with no argument (and no setter or property of same name
1244     // as a 'readonly' property.
1245     edit::Commit commit(*Editor);
1246     rewriteToObjCProperty(Method, nullptr /*SetterMethod*/, *NSAPIObj, commit,
1247                           LengthOfPrefix,
1248                           (ASTMigrateActions &
1249                            FrontendOptions::ObjCMT_AtomicProperty) != 0,
1250                           (ASTMigrateActions &
1251                            FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty) != 0,
1252                           /*AvailabilityArgsMatch*/false);
1253     Editor->commit(commit);
1254     return true;
1255   }
1256   return false;
1257 }
1258 
migrateNsReturnsInnerPointer(ASTContext & Ctx,ObjCMethodDecl * OM)1259 void ObjCMigrateASTConsumer::migrateNsReturnsInnerPointer(ASTContext &Ctx,
1260                                                           ObjCMethodDecl *OM) {
1261   if (OM->isImplicit() ||
1262       !OM->isInstanceMethod() ||
1263       OM->hasAttr<ObjCReturnsInnerPointerAttr>())
1264     return;
1265 
1266   QualType RT = OM->getReturnType();
1267   if (!TypeIsInnerPointer(RT) ||
1268       !NSAPIObj->isMacroDefined("NS_RETURNS_INNER_POINTER"))
1269     return;
1270 
1271   edit::Commit commit(*Editor);
1272   commit.insertBefore(OM->getLocEnd(), " NS_RETURNS_INNER_POINTER");
1273   Editor->commit(commit);
1274 }
1275 
migratePropertyNsReturnsInnerPointer(ASTContext & Ctx,ObjCPropertyDecl * P)1276 void ObjCMigrateASTConsumer::migratePropertyNsReturnsInnerPointer(ASTContext &Ctx,
1277                                                                   ObjCPropertyDecl *P) {
1278   QualType T = P->getType();
1279 
1280   if (!TypeIsInnerPointer(T) ||
1281       !NSAPIObj->isMacroDefined("NS_RETURNS_INNER_POINTER"))
1282     return;
1283   edit::Commit commit(*Editor);
1284   commit.insertBefore(P->getLocEnd(), " NS_RETURNS_INNER_POINTER ");
1285   Editor->commit(commit);
1286 }
1287 
migrateAllMethodInstaceType(ASTContext & Ctx,ObjCContainerDecl * CDecl)1288 void ObjCMigrateASTConsumer::migrateAllMethodInstaceType(ASTContext &Ctx,
1289                                                  ObjCContainerDecl *CDecl) {
1290   if (CDecl->isDeprecated() || IsCategoryNameWithDeprecatedSuffix(CDecl))
1291     return;
1292 
1293   // migrate methods which can have instancetype as their result type.
1294   for (auto *Method : CDecl->methods()) {
1295     if (Method->isDeprecated())
1296       continue;
1297     migrateMethodInstanceType(Ctx, CDecl, Method);
1298   }
1299 }
1300 
migrateFactoryMethod(ASTContext & Ctx,ObjCContainerDecl * CDecl,ObjCMethodDecl * OM,ObjCInstanceTypeFamily OIT_Family)1301 void ObjCMigrateASTConsumer::migrateFactoryMethod(ASTContext &Ctx,
1302                                                   ObjCContainerDecl *CDecl,
1303                                                   ObjCMethodDecl *OM,
1304                                                   ObjCInstanceTypeFamily OIT_Family) {
1305   if (OM->isInstanceMethod() ||
1306       OM->getReturnType() == Ctx.getObjCInstanceType() ||
1307       !OM->getReturnType()->isObjCIdType())
1308     return;
1309 
1310   // Candidate factory methods are + (id) NaMeXXX : ... which belong to a class
1311   // NSYYYNamE with matching names be at least 3 characters long.
1312   ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
1313   if (!IDecl) {
1314     if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
1315       IDecl = CatDecl->getClassInterface();
1316     else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
1317       IDecl = ImpDecl->getClassInterface();
1318   }
1319   if (!IDecl)
1320     return;
1321 
1322   std::string StringClassName = IDecl->getName();
1323   StringRef LoweredClassName(StringClassName);
1324   std::string StringLoweredClassName = LoweredClassName.lower();
1325   LoweredClassName = StringLoweredClassName;
1326 
1327   IdentifierInfo *MethodIdName = OM->getSelector().getIdentifierInfoForSlot(0);
1328   // Handle method with no name at its first selector slot; e.g. + (id):(int)x.
1329   if (!MethodIdName)
1330     return;
1331 
1332   std::string MethodName = MethodIdName->getName();
1333   if (OIT_Family == OIT_Singleton || OIT_Family == OIT_ReturnsSelf) {
1334     StringRef STRefMethodName(MethodName);
1335     size_t len = 0;
1336     if (STRefMethodName.startswith("standard"))
1337       len = strlen("standard");
1338     else if (STRefMethodName.startswith("shared"))
1339       len = strlen("shared");
1340     else if (STRefMethodName.startswith("default"))
1341       len = strlen("default");
1342     else
1343       return;
1344     MethodName = STRefMethodName.substr(len);
1345   }
1346   std::string MethodNameSubStr = MethodName.substr(0, 3);
1347   StringRef MethodNamePrefix(MethodNameSubStr);
1348   std::string StringLoweredMethodNamePrefix = MethodNamePrefix.lower();
1349   MethodNamePrefix = StringLoweredMethodNamePrefix;
1350   size_t Ix = LoweredClassName.rfind(MethodNamePrefix);
1351   if (Ix == StringRef::npos)
1352     return;
1353   std::string ClassNamePostfix = LoweredClassName.substr(Ix);
1354   StringRef LoweredMethodName(MethodName);
1355   std::string StringLoweredMethodName = LoweredMethodName.lower();
1356   LoweredMethodName = StringLoweredMethodName;
1357   if (!LoweredMethodName.startswith(ClassNamePostfix))
1358     return;
1359   if (OIT_Family == OIT_ReturnsSelf)
1360     ReplaceWithClasstype(*this, OM);
1361   else
1362     ReplaceWithInstancetype(Ctx, *this, OM);
1363 }
1364 
IsVoidStarType(QualType Ty)1365 static bool IsVoidStarType(QualType Ty) {
1366   if (!Ty->isPointerType())
1367     return false;
1368 
1369   while (const TypedefType *TD = dyn_cast<TypedefType>(Ty.getTypePtr()))
1370     Ty = TD->getDecl()->getUnderlyingType();
1371 
1372   // Is the type void*?
1373   const PointerType* PT = Ty->getAs<PointerType>();
1374   if (PT->getPointeeType().getUnqualifiedType()->isVoidType())
1375     return true;
1376   return IsVoidStarType(PT->getPointeeType());
1377 }
1378 
1379 /// AuditedType - This routine audits the type AT and returns false if it is one of known
1380 /// CF object types or of the "void *" variety. It returns true if we don't care about the type
1381 /// such as a non-pointer or pointers which have no ownership issues (such as "int *").
AuditedType(QualType AT)1382 static bool AuditedType (QualType AT) {
1383   if (!AT->isAnyPointerType() && !AT->isBlockPointerType())
1384     return true;
1385   // FIXME. There isn't much we can say about CF pointer type; or is there?
1386   if (ento::coreFoundation::isCFObjectRef(AT) ||
1387       IsVoidStarType(AT) ||
1388       // If an ObjC object is type, assuming that it is not a CF function and
1389       // that it is an un-audited function.
1390       AT->isObjCObjectPointerType() || AT->isObjCBuiltinType())
1391     return false;
1392   // All other pointers are assumed audited as harmless.
1393   return true;
1394 }
1395 
AnnotateImplicitBridging(ASTContext & Ctx)1396 void ObjCMigrateASTConsumer::AnnotateImplicitBridging(ASTContext &Ctx) {
1397   if (CFFunctionIBCandidates.empty())
1398     return;
1399   if (!NSAPIObj->isMacroDefined("CF_IMPLICIT_BRIDGING_ENABLED")) {
1400     CFFunctionIBCandidates.clear();
1401     FileId = FileID();
1402     return;
1403   }
1404   // Insert CF_IMPLICIT_BRIDGING_ENABLE/CF_IMPLICIT_BRIDGING_DISABLED
1405   const Decl *FirstFD = CFFunctionIBCandidates[0];
1406   const Decl *LastFD  =
1407     CFFunctionIBCandidates[CFFunctionIBCandidates.size()-1];
1408   const char *PragmaString = "\nCF_IMPLICIT_BRIDGING_ENABLED\n\n";
1409   edit::Commit commit(*Editor);
1410   commit.insertBefore(FirstFD->getLocStart(), PragmaString);
1411   PragmaString = "\n\nCF_IMPLICIT_BRIDGING_DISABLED\n";
1412   SourceLocation EndLoc = LastFD->getLocEnd();
1413   // get location just past end of function location.
1414   EndLoc = PP.getLocForEndOfToken(EndLoc);
1415   if (isa<FunctionDecl>(LastFD)) {
1416     // For Methods, EndLoc points to the ending semcolon. So,
1417     // not of these extra work is needed.
1418     Token Tok;
1419     // get locaiton of token that comes after end of function.
1420     bool Failed = PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true);
1421     if (!Failed)
1422       EndLoc = Tok.getLocation();
1423   }
1424   commit.insertAfterToken(EndLoc, PragmaString);
1425   Editor->commit(commit);
1426   FileId = FileID();
1427   CFFunctionIBCandidates.clear();
1428 }
1429 
migrateCFAnnotation(ASTContext & Ctx,const Decl * Decl)1430 void ObjCMigrateASTConsumer::migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl) {
1431   if (Decl->isDeprecated())
1432     return;
1433 
1434   if (Decl->hasAttr<CFAuditedTransferAttr>()) {
1435     assert(CFFunctionIBCandidates.empty() &&
1436            "Cannot have audited functions/methods inside user "
1437            "provided CF_IMPLICIT_BRIDGING_ENABLE");
1438     return;
1439   }
1440 
1441   // Finction must be annotated first.
1442   if (const FunctionDecl *FuncDecl = dyn_cast<FunctionDecl>(Decl)) {
1443     CF_BRIDGING_KIND AuditKind = migrateAddFunctionAnnotation(Ctx, FuncDecl);
1444     if (AuditKind == CF_BRIDGING_ENABLE) {
1445       CFFunctionIBCandidates.push_back(Decl);
1446       if (FileId.isInvalid())
1447         FileId = PP.getSourceManager().getFileID(Decl->getLocation());
1448     }
1449     else if (AuditKind == CF_BRIDGING_MAY_INCLUDE) {
1450       if (!CFFunctionIBCandidates.empty()) {
1451         CFFunctionIBCandidates.push_back(Decl);
1452         if (FileId.isInvalid())
1453           FileId = PP.getSourceManager().getFileID(Decl->getLocation());
1454       }
1455     }
1456     else
1457       AnnotateImplicitBridging(Ctx);
1458   }
1459   else {
1460     migrateAddMethodAnnotation(Ctx, cast<ObjCMethodDecl>(Decl));
1461     AnnotateImplicitBridging(Ctx);
1462   }
1463 }
1464 
AddCFAnnotations(ASTContext & Ctx,const CallEffects & CE,const FunctionDecl * FuncDecl,bool ResultAnnotated)1465 void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
1466                                               const CallEffects &CE,
1467                                               const FunctionDecl *FuncDecl,
1468                                               bool ResultAnnotated) {
1469   // Annotate function.
1470   if (!ResultAnnotated) {
1471     RetEffect Ret = CE.getReturnValue();
1472     const char *AnnotationString = nullptr;
1473     if (Ret.getObjKind() == RetEffect::CF) {
1474       if (Ret.isOwned() && NSAPIObj->isMacroDefined("CF_RETURNS_RETAINED"))
1475         AnnotationString = " CF_RETURNS_RETAINED";
1476       else if (Ret.notOwned() &&
1477                NSAPIObj->isMacroDefined("CF_RETURNS_NOT_RETAINED"))
1478         AnnotationString = " CF_RETURNS_NOT_RETAINED";
1479     }
1480     else if (Ret.getObjKind() == RetEffect::ObjC) {
1481       if (Ret.isOwned() && NSAPIObj->isMacroDefined("NS_RETURNS_RETAINED"))
1482         AnnotationString = " NS_RETURNS_RETAINED";
1483     }
1484 
1485     if (AnnotationString) {
1486       edit::Commit commit(*Editor);
1487       commit.insertAfterToken(FuncDecl->getLocEnd(), AnnotationString);
1488       Editor->commit(commit);
1489     }
1490   }
1491   ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1492   unsigned i = 0;
1493   for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
1494        pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
1495     const ParmVarDecl *pd = *pi;
1496     ArgEffect AE = AEArgs[i];
1497     if (AE == DecRef && !pd->hasAttr<CFConsumedAttr>() &&
1498         NSAPIObj->isMacroDefined("CF_CONSUMED")) {
1499       edit::Commit commit(*Editor);
1500       commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
1501       Editor->commit(commit);
1502     }
1503     else if (AE == DecRefMsg && !pd->hasAttr<NSConsumedAttr>() &&
1504              NSAPIObj->isMacroDefined("NS_CONSUMED")) {
1505       edit::Commit commit(*Editor);
1506       commit.insertBefore(pd->getLocation(), "NS_CONSUMED ");
1507       Editor->commit(commit);
1508     }
1509   }
1510 }
1511 
1512 ObjCMigrateASTConsumer::CF_BRIDGING_KIND
migrateAddFunctionAnnotation(ASTContext & Ctx,const FunctionDecl * FuncDecl)1513   ObjCMigrateASTConsumer::migrateAddFunctionAnnotation(
1514                                                   ASTContext &Ctx,
1515                                                   const FunctionDecl *FuncDecl) {
1516   if (FuncDecl->hasBody())
1517     return CF_BRIDGING_NONE;
1518 
1519   CallEffects CE  = CallEffects::getEffect(FuncDecl);
1520   bool FuncIsReturnAnnotated = (FuncDecl->hasAttr<CFReturnsRetainedAttr>() ||
1521                                 FuncDecl->hasAttr<CFReturnsNotRetainedAttr>() ||
1522                                 FuncDecl->hasAttr<NSReturnsRetainedAttr>() ||
1523                                 FuncDecl->hasAttr<NSReturnsNotRetainedAttr>() ||
1524                                 FuncDecl->hasAttr<NSReturnsAutoreleasedAttr>());
1525 
1526   // Trivial case of when function is annotated and has no argument.
1527   if (FuncIsReturnAnnotated && FuncDecl->getNumParams() == 0)
1528     return CF_BRIDGING_NONE;
1529 
1530   bool ReturnCFAudited = false;
1531   if (!FuncIsReturnAnnotated) {
1532     RetEffect Ret = CE.getReturnValue();
1533     if (Ret.getObjKind() == RetEffect::CF &&
1534         (Ret.isOwned() || Ret.notOwned()))
1535       ReturnCFAudited = true;
1536     else if (!AuditedType(FuncDecl->getReturnType()))
1537       return CF_BRIDGING_NONE;
1538   }
1539 
1540   // At this point result type is audited for potential inclusion.
1541   // Now, how about argument types.
1542   ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1543   unsigned i = 0;
1544   bool ArgCFAudited = false;
1545   for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
1546        pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
1547     const ParmVarDecl *pd = *pi;
1548     ArgEffect AE = AEArgs[i];
1549     if (AE == DecRef /*CFConsumed annotated*/ || AE == IncRef) {
1550       if (AE == DecRef && !pd->hasAttr<CFConsumedAttr>())
1551         ArgCFAudited = true;
1552       else if (AE == IncRef)
1553         ArgCFAudited = true;
1554     }
1555     else {
1556       QualType AT = pd->getType();
1557       if (!AuditedType(AT)) {
1558         AddCFAnnotations(Ctx, CE, FuncDecl, FuncIsReturnAnnotated);
1559         return CF_BRIDGING_NONE;
1560       }
1561     }
1562   }
1563   if (ReturnCFAudited || ArgCFAudited)
1564     return CF_BRIDGING_ENABLE;
1565 
1566   return CF_BRIDGING_MAY_INCLUDE;
1567 }
1568 
migrateARCSafeAnnotation(ASTContext & Ctx,ObjCContainerDecl * CDecl)1569 void ObjCMigrateASTConsumer::migrateARCSafeAnnotation(ASTContext &Ctx,
1570                                                  ObjCContainerDecl *CDecl) {
1571   if (!isa<ObjCInterfaceDecl>(CDecl) || CDecl->isDeprecated())
1572     return;
1573 
1574   // migrate methods which can have instancetype as their result type.
1575   for (const auto *Method : CDecl->methods())
1576     migrateCFAnnotation(Ctx, Method);
1577 }
1578 
AddCFAnnotations(ASTContext & Ctx,const CallEffects & CE,const ObjCMethodDecl * MethodDecl,bool ResultAnnotated)1579 void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
1580                                               const CallEffects &CE,
1581                                               const ObjCMethodDecl *MethodDecl,
1582                                               bool ResultAnnotated) {
1583   // Annotate function.
1584   if (!ResultAnnotated) {
1585     RetEffect Ret = CE.getReturnValue();
1586     const char *AnnotationString = nullptr;
1587     if (Ret.getObjKind() == RetEffect::CF) {
1588       if (Ret.isOwned() && NSAPIObj->isMacroDefined("CF_RETURNS_RETAINED"))
1589         AnnotationString = " CF_RETURNS_RETAINED";
1590       else if (Ret.notOwned() &&
1591                NSAPIObj->isMacroDefined("CF_RETURNS_NOT_RETAINED"))
1592         AnnotationString = " CF_RETURNS_NOT_RETAINED";
1593     }
1594     else if (Ret.getObjKind() == RetEffect::ObjC) {
1595       ObjCMethodFamily OMF = MethodDecl->getMethodFamily();
1596       switch (OMF) {
1597         case clang::OMF_alloc:
1598         case clang::OMF_new:
1599         case clang::OMF_copy:
1600         case clang::OMF_init:
1601         case clang::OMF_mutableCopy:
1602           break;
1603 
1604         default:
1605           if (Ret.isOwned() && NSAPIObj->isMacroDefined("NS_RETURNS_RETAINED"))
1606             AnnotationString = " NS_RETURNS_RETAINED";
1607           break;
1608       }
1609     }
1610 
1611     if (AnnotationString) {
1612       edit::Commit commit(*Editor);
1613       commit.insertBefore(MethodDecl->getLocEnd(), AnnotationString);
1614       Editor->commit(commit);
1615     }
1616   }
1617   ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1618   unsigned i = 0;
1619   for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
1620        pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
1621     const ParmVarDecl *pd = *pi;
1622     ArgEffect AE = AEArgs[i];
1623     if (AE == DecRef && !pd->hasAttr<CFConsumedAttr>() &&
1624         NSAPIObj->isMacroDefined("CF_CONSUMED")) {
1625       edit::Commit commit(*Editor);
1626       commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
1627       Editor->commit(commit);
1628     }
1629   }
1630 }
1631 
migrateAddMethodAnnotation(ASTContext & Ctx,const ObjCMethodDecl * MethodDecl)1632 void ObjCMigrateASTConsumer::migrateAddMethodAnnotation(
1633                                             ASTContext &Ctx,
1634                                             const ObjCMethodDecl *MethodDecl) {
1635   if (MethodDecl->hasBody() || MethodDecl->isImplicit())
1636     return;
1637 
1638   CallEffects CE  = CallEffects::getEffect(MethodDecl);
1639   bool MethodIsReturnAnnotated = (MethodDecl->hasAttr<CFReturnsRetainedAttr>() ||
1640                                   MethodDecl->hasAttr<CFReturnsNotRetainedAttr>() ||
1641                                   MethodDecl->hasAttr<NSReturnsRetainedAttr>() ||
1642                                   MethodDecl->hasAttr<NSReturnsNotRetainedAttr>() ||
1643                                   MethodDecl->hasAttr<NSReturnsAutoreleasedAttr>());
1644 
1645   if (CE.getReceiver() == DecRefMsg &&
1646       !MethodDecl->hasAttr<NSConsumesSelfAttr>() &&
1647       MethodDecl->getMethodFamily() != OMF_init &&
1648       MethodDecl->getMethodFamily() != OMF_release &&
1649       NSAPIObj->isMacroDefined("NS_CONSUMES_SELF")) {
1650     edit::Commit commit(*Editor);
1651     commit.insertBefore(MethodDecl->getLocEnd(), " NS_CONSUMES_SELF");
1652     Editor->commit(commit);
1653   }
1654 
1655   // Trivial case of when function is annotated and has no argument.
1656   if (MethodIsReturnAnnotated &&
1657       (MethodDecl->param_begin() == MethodDecl->param_end()))
1658     return;
1659 
1660   if (!MethodIsReturnAnnotated) {
1661     RetEffect Ret = CE.getReturnValue();
1662     if ((Ret.getObjKind() == RetEffect::CF ||
1663          Ret.getObjKind() == RetEffect::ObjC) &&
1664         (Ret.isOwned() || Ret.notOwned())) {
1665       AddCFAnnotations(Ctx, CE, MethodDecl, false);
1666       return;
1667     } else if (!AuditedType(MethodDecl->getReturnType()))
1668       return;
1669   }
1670 
1671   // At this point result type is either annotated or audited.
1672   // Now, how about argument types.
1673   ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1674   unsigned i = 0;
1675   for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
1676        pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
1677     const ParmVarDecl *pd = *pi;
1678     ArgEffect AE = AEArgs[i];
1679     if ((AE == DecRef && !pd->hasAttr<CFConsumedAttr>()) || AE == IncRef ||
1680         !AuditedType(pd->getType())) {
1681       AddCFAnnotations(Ctx, CE, MethodDecl, MethodIsReturnAnnotated);
1682       return;
1683     }
1684   }
1685 }
1686 
1687 namespace {
1688 class SuperInitChecker : public RecursiveASTVisitor<SuperInitChecker> {
1689 public:
shouldVisitTemplateInstantiations() const1690   bool shouldVisitTemplateInstantiations() const { return false; }
shouldWalkTypesOfTypeLocs() const1691   bool shouldWalkTypesOfTypeLocs() const { return false; }
1692 
VisitObjCMessageExpr(ObjCMessageExpr * E)1693   bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
1694     if (E->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
1695       if (E->getMethodFamily() == OMF_init)
1696         return false;
1697     }
1698     return true;
1699   }
1700 };
1701 } // end anonymous namespace
1702 
hasSuperInitCall(const ObjCMethodDecl * MD)1703 static bool hasSuperInitCall(const ObjCMethodDecl *MD) {
1704   return !SuperInitChecker().TraverseStmt(MD->getBody());
1705 }
1706 
inferDesignatedInitializers(ASTContext & Ctx,const ObjCImplementationDecl * ImplD)1707 void ObjCMigrateASTConsumer::inferDesignatedInitializers(
1708     ASTContext &Ctx,
1709     const ObjCImplementationDecl *ImplD) {
1710 
1711   const ObjCInterfaceDecl *IFace = ImplD->getClassInterface();
1712   if (!IFace || IFace->hasDesignatedInitializers())
1713     return;
1714   if (!NSAPIObj->isMacroDefined("NS_DESIGNATED_INITIALIZER"))
1715     return;
1716 
1717   for (const auto *MD : ImplD->instance_methods()) {
1718     if (MD->isDeprecated() ||
1719         MD->getMethodFamily() != OMF_init ||
1720         MD->isDesignatedInitializerForTheInterface())
1721       continue;
1722     const ObjCMethodDecl *IFaceM = IFace->getMethod(MD->getSelector(),
1723                                                     /*isInstance=*/true);
1724     if (!IFaceM)
1725       continue;
1726     if (hasSuperInitCall(MD)) {
1727       edit::Commit commit(*Editor);
1728       commit.insert(IFaceM->getLocEnd(), " NS_DESIGNATED_INITIALIZER");
1729       Editor->commit(commit);
1730     }
1731   }
1732 }
1733 
InsertFoundation(ASTContext & Ctx,SourceLocation Loc)1734 bool ObjCMigrateASTConsumer::InsertFoundation(ASTContext &Ctx,
1735                                               SourceLocation  Loc) {
1736   if (FoundationIncluded)
1737     return true;
1738   if (Loc.isInvalid())
1739     return false;
1740   edit::Commit commit(*Editor);
1741   if (Ctx.getLangOpts().Modules)
1742     commit.insert(Loc, "#ifndef NS_ENUM\n@import Foundation;\n#endif\n");
1743   else
1744     commit.insert(Loc, "#ifndef NS_ENUM\n#import <Foundation/Foundation.h>\n#endif\n");
1745   Editor->commit(commit);
1746   FoundationIncluded = true;
1747   return true;
1748 }
1749 
1750 namespace {
1751 
1752 class RewritesReceiver : public edit::EditsReceiver {
1753   Rewriter &Rewrite;
1754 
1755 public:
RewritesReceiver(Rewriter & Rewrite)1756   RewritesReceiver(Rewriter &Rewrite) : Rewrite(Rewrite) { }
1757 
insert(SourceLocation loc,StringRef text)1758   void insert(SourceLocation loc, StringRef text) override {
1759     Rewrite.InsertText(loc, text);
1760   }
replace(CharSourceRange range,StringRef text)1761   void replace(CharSourceRange range, StringRef text) override {
1762     Rewrite.ReplaceText(range.getBegin(), Rewrite.getRangeSize(range), text);
1763   }
1764 };
1765 
1766 class JSONEditWriter : public edit::EditsReceiver {
1767   SourceManager &SourceMgr;
1768   llvm::raw_ostream &OS;
1769 
1770 public:
JSONEditWriter(SourceManager & SM,llvm::raw_ostream & OS)1771   JSONEditWriter(SourceManager &SM, llvm::raw_ostream &OS)
1772     : SourceMgr(SM), OS(OS) {
1773     OS << "[\n";
1774   }
~JSONEditWriter()1775   ~JSONEditWriter() override { OS << "]\n"; }
1776 
1777 private:
1778   struct EntryWriter {
1779     SourceManager &SourceMgr;
1780     llvm::raw_ostream &OS;
1781 
EntryWriter__anonf5f2bde80411::JSONEditWriter::EntryWriter1782     EntryWriter(SourceManager &SM, llvm::raw_ostream &OS)
1783       : SourceMgr(SM), OS(OS) {
1784       OS << " {\n";
1785     }
~EntryWriter__anonf5f2bde80411::JSONEditWriter::EntryWriter1786     ~EntryWriter() {
1787       OS << " },\n";
1788     }
1789 
writeLoc__anonf5f2bde80411::JSONEditWriter::EntryWriter1790     void writeLoc(SourceLocation Loc) {
1791       FileID FID;
1792       unsigned Offset;
1793       std::tie(FID, Offset) = SourceMgr.getDecomposedLoc(Loc);
1794       assert(FID.isValid());
1795       SmallString<200> Path =
1796           StringRef(SourceMgr.getFileEntryForID(FID)->getName());
1797       llvm::sys::fs::make_absolute(Path);
1798       OS << "  \"file\": \"";
1799       OS.write_escaped(Path.str()) << "\",\n";
1800       OS << "  \"offset\": " << Offset << ",\n";
1801     }
1802 
writeRemove__anonf5f2bde80411::JSONEditWriter::EntryWriter1803     void writeRemove(CharSourceRange Range) {
1804       assert(Range.isCharRange());
1805       std::pair<FileID, unsigned> Begin =
1806           SourceMgr.getDecomposedLoc(Range.getBegin());
1807       std::pair<FileID, unsigned> End =
1808           SourceMgr.getDecomposedLoc(Range.getEnd());
1809       assert(Begin.first == End.first);
1810       assert(Begin.second <= End.second);
1811       unsigned Length = End.second - Begin.second;
1812 
1813       OS << "  \"remove\": " << Length << ",\n";
1814     }
1815 
writeText__anonf5f2bde80411::JSONEditWriter::EntryWriter1816     void writeText(StringRef Text) {
1817       OS << "  \"text\": \"";
1818       OS.write_escaped(Text) << "\",\n";
1819     }
1820   };
1821 
insert(SourceLocation Loc,StringRef Text)1822   void insert(SourceLocation Loc, StringRef Text) override {
1823     EntryWriter Writer(SourceMgr, OS);
1824     Writer.writeLoc(Loc);
1825     Writer.writeText(Text);
1826   }
1827 
replace(CharSourceRange Range,StringRef Text)1828   void replace(CharSourceRange Range, StringRef Text) override {
1829     EntryWriter Writer(SourceMgr, OS);
1830     Writer.writeLoc(Range.getBegin());
1831     Writer.writeRemove(Range);
1832     Writer.writeText(Text);
1833   }
1834 
remove(CharSourceRange Range)1835   void remove(CharSourceRange Range) override {
1836     EntryWriter Writer(SourceMgr, OS);
1837     Writer.writeLoc(Range.getBegin());
1838     Writer.writeRemove(Range);
1839   }
1840 };
1841 
1842 } // end anonymous namespace
1843 
HandleTranslationUnit(ASTContext & Ctx)1844 void ObjCMigrateASTConsumer::HandleTranslationUnit(ASTContext &Ctx) {
1845 
1846   TranslationUnitDecl *TU = Ctx.getTranslationUnitDecl();
1847   if (ASTMigrateActions & FrontendOptions::ObjCMT_MigrateDecls) {
1848     for (DeclContext::decl_iterator D = TU->decls_begin(), DEnd = TU->decls_end();
1849          D != DEnd; ++D) {
1850       FileID FID = PP.getSourceManager().getFileID((*D)->getLocation());
1851       if (FID.isValid())
1852         if (FileId.isValid() && FileId != FID) {
1853           if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
1854             AnnotateImplicitBridging(Ctx);
1855         }
1856 
1857       if (ObjCInterfaceDecl *CDecl = dyn_cast<ObjCInterfaceDecl>(*D))
1858         if (canModify(CDecl))
1859           migrateObjCContainerDecl(Ctx, CDecl);
1860       if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(*D)) {
1861         if (canModify(CatDecl))
1862           migrateObjCContainerDecl(Ctx, CatDecl);
1863       }
1864       else if (ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(*D)) {
1865         ObjCProtocolDecls.insert(PDecl->getCanonicalDecl());
1866         if (canModify(PDecl))
1867           migrateObjCContainerDecl(Ctx, PDecl);
1868       }
1869       else if (const ObjCImplementationDecl *ImpDecl =
1870                dyn_cast<ObjCImplementationDecl>(*D)) {
1871         if ((ASTMigrateActions & FrontendOptions::ObjCMT_ProtocolConformance) &&
1872             canModify(ImpDecl))
1873           migrateProtocolConformance(Ctx, ImpDecl);
1874       }
1875       else if (const EnumDecl *ED = dyn_cast<EnumDecl>(*D)) {
1876         if (!(ASTMigrateActions & FrontendOptions::ObjCMT_NsMacros))
1877           continue;
1878         if (!canModify(ED))
1879           continue;
1880         DeclContext::decl_iterator N = D;
1881         if (++N != DEnd) {
1882           const TypedefDecl *TD = dyn_cast<TypedefDecl>(*N);
1883           if (migrateNSEnumDecl(Ctx, ED, TD) && TD)
1884             D++;
1885         }
1886         else
1887           migrateNSEnumDecl(Ctx, ED, /*TypedefDecl */nullptr);
1888       }
1889       else if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(*D)) {
1890         if (!(ASTMigrateActions & FrontendOptions::ObjCMT_NsMacros))
1891           continue;
1892         if (!canModify(TD))
1893           continue;
1894         DeclContext::decl_iterator N = D;
1895         if (++N == DEnd)
1896           continue;
1897         if (const EnumDecl *ED = dyn_cast<EnumDecl>(*N)) {
1898           if (++N != DEnd)
1899             if (const TypedefDecl *TDF = dyn_cast<TypedefDecl>(*N)) {
1900               // prefer typedef-follows-enum to enum-follows-typedef pattern.
1901               if (migrateNSEnumDecl(Ctx, ED, TDF)) {
1902                 ++D; ++D;
1903                 CacheObjCNSIntegerTypedefed(TD);
1904                 continue;
1905               }
1906             }
1907           if (migrateNSEnumDecl(Ctx, ED, TD)) {
1908             ++D;
1909             continue;
1910           }
1911         }
1912         CacheObjCNSIntegerTypedefed(TD);
1913       }
1914       else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*D)) {
1915         if ((ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) &&
1916             canModify(FD))
1917           migrateCFAnnotation(Ctx, FD);
1918       }
1919 
1920       if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(*D)) {
1921         bool CanModify = canModify(CDecl);
1922         // migrate methods which can have instancetype as their result type.
1923         if ((ASTMigrateActions & FrontendOptions::ObjCMT_Instancetype) &&
1924             CanModify)
1925           migrateAllMethodInstaceType(Ctx, CDecl);
1926         // annotate methods with CF annotations.
1927         if ((ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) &&
1928             CanModify)
1929           migrateARCSafeAnnotation(Ctx, CDecl);
1930       }
1931 
1932       if (const ObjCImplementationDecl *
1933             ImplD = dyn_cast<ObjCImplementationDecl>(*D)) {
1934         if ((ASTMigrateActions & FrontendOptions::ObjCMT_DesignatedInitializer) &&
1935             canModify(ImplD))
1936           inferDesignatedInitializers(Ctx, ImplD);
1937       }
1938     }
1939     if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
1940       AnnotateImplicitBridging(Ctx);
1941   }
1942 
1943  if (IsOutputFile) {
1944    std::error_code EC;
1945    llvm::raw_fd_ostream OS(MigrateDir, EC, llvm::sys::fs::F_None);
1946    if (EC) {
1947       DiagnosticsEngine &Diags = Ctx.getDiagnostics();
1948       Diags.Report(Diags.getCustomDiagID(DiagnosticsEngine::Error, "%0"))
1949           << EC.message();
1950       return;
1951     }
1952 
1953    JSONEditWriter Writer(Ctx.getSourceManager(), OS);
1954    Editor->applyRewrites(Writer);
1955    return;
1956  }
1957 
1958   Rewriter rewriter(Ctx.getSourceManager(), Ctx.getLangOpts());
1959   RewritesReceiver Rec(rewriter);
1960   Editor->applyRewrites(Rec);
1961 
1962   for (Rewriter::buffer_iterator
1963         I = rewriter.buffer_begin(), E = rewriter.buffer_end(); I != E; ++I) {
1964     FileID FID = I->first;
1965     RewriteBuffer &buf = I->second;
1966     const FileEntry *file = Ctx.getSourceManager().getFileEntryForID(FID);
1967     assert(file);
1968     SmallString<512> newText;
1969     llvm::raw_svector_ostream vecOS(newText);
1970     buf.write(vecOS);
1971     std::unique_ptr<llvm::MemoryBuffer> memBuf(
1972         llvm::MemoryBuffer::getMemBufferCopy(
1973             StringRef(newText.data(), newText.size()), file->getName()));
1974     SmallString<64> filePath(file->getName());
1975     FileMgr.FixupRelativePath(filePath);
1976     Remapper.remap(filePath.str(), std::move(memBuf));
1977   }
1978 
1979   if (IsOutputFile) {
1980     Remapper.flushToFile(MigrateDir, Ctx.getDiagnostics());
1981   } else {
1982     Remapper.flushToDisk(MigrateDir, Ctx.getDiagnostics());
1983   }
1984 }
1985 
BeginInvocation(CompilerInstance & CI)1986 bool MigrateSourceAction::BeginInvocation(CompilerInstance &CI) {
1987   CI.getDiagnostics().setIgnoreAllWarnings(true);
1988   return true;
1989 }
1990 
getWhiteListFilenames(StringRef DirPath)1991 static std::vector<std::string> getWhiteListFilenames(StringRef DirPath) {
1992   using namespace llvm::sys::fs;
1993   using namespace llvm::sys::path;
1994 
1995   std::vector<std::string> Filenames;
1996   if (DirPath.empty() || !is_directory(DirPath))
1997     return Filenames;
1998 
1999   std::error_code EC;
2000   directory_iterator DI = directory_iterator(DirPath, EC);
2001   directory_iterator DE;
2002   for (; !EC && DI != DE; DI = DI.increment(EC)) {
2003     if (is_regular_file(DI->path()))
2004       Filenames.push_back(filename(DI->path()));
2005   }
2006 
2007   return Filenames;
2008 }
2009 
2010 std::unique_ptr<ASTConsumer>
CreateASTConsumer(CompilerInstance & CI,StringRef InFile)2011 MigrateSourceAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
2012   PPConditionalDirectiveRecord *
2013     PPRec = new PPConditionalDirectiveRecord(CI.getSourceManager());
2014   unsigned ObjCMTAction = CI.getFrontendOpts().ObjCMTAction;
2015   unsigned ObjCMTOpts = ObjCMTAction;
2016   // These are companion flags, they do not enable transformations.
2017   ObjCMTOpts &= ~(FrontendOptions::ObjCMT_AtomicProperty |
2018                   FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty);
2019   if (ObjCMTOpts == FrontendOptions::ObjCMT_None) {
2020     // If no specific option was given, enable literals+subscripting transforms
2021     // by default.
2022     ObjCMTAction |= FrontendOptions::ObjCMT_Literals |
2023                     FrontendOptions::ObjCMT_Subscripting;
2024   }
2025   CI.getPreprocessor().addPPCallbacks(std::unique_ptr<PPCallbacks>(PPRec));
2026   std::vector<std::string> WhiteList =
2027     getWhiteListFilenames(CI.getFrontendOpts().ObjCMTWhiteListPath);
2028   return llvm::make_unique<ObjCMigrateASTConsumer>(
2029       CI.getFrontendOpts().OutputFile, ObjCMTAction, Remapper,
2030       CI.getFileManager(), PPRec, CI.getPreprocessor(),
2031       /*isOutputFile=*/true, WhiteList);
2032 }
2033 
2034 namespace {
2035 struct EditEntry {
2036   const FileEntry *File;
2037   unsigned Offset;
2038   unsigned RemoveLen;
2039   std::string Text;
2040 
EditEntry__anonf5f2bde80511::EditEntry2041   EditEntry() : File(), Offset(), RemoveLen() {}
2042 };
2043 } // end anonymous namespace
2044 
2045 namespace llvm {
2046 template<> struct DenseMapInfo<EditEntry> {
getEmptyKeyllvm::DenseMapInfo2047   static inline EditEntry getEmptyKey() {
2048     EditEntry Entry;
2049     Entry.Offset = unsigned(-1);
2050     return Entry;
2051   }
getTombstoneKeyllvm::DenseMapInfo2052   static inline EditEntry getTombstoneKey() {
2053     EditEntry Entry;
2054     Entry.Offset = unsigned(-2);
2055     return Entry;
2056   }
getHashValuellvm::DenseMapInfo2057   static unsigned getHashValue(const EditEntry& Val) {
2058     llvm::FoldingSetNodeID ID;
2059     ID.AddPointer(Val.File);
2060     ID.AddInteger(Val.Offset);
2061     ID.AddInteger(Val.RemoveLen);
2062     ID.AddString(Val.Text);
2063     return ID.ComputeHash();
2064   }
isEqualllvm::DenseMapInfo2065   static bool isEqual(const EditEntry &LHS, const EditEntry &RHS) {
2066     return LHS.File == RHS.File &&
2067         LHS.Offset == RHS.Offset &&
2068         LHS.RemoveLen == RHS.RemoveLen &&
2069         LHS.Text == RHS.Text;
2070   }
2071 };
2072 } // end namespace llvm
2073 
2074 namespace {
2075 class RemapFileParser {
2076   FileManager &FileMgr;
2077 
2078 public:
RemapFileParser(FileManager & FileMgr)2079   RemapFileParser(FileManager &FileMgr) : FileMgr(FileMgr) { }
2080 
parse(StringRef File,SmallVectorImpl<EditEntry> & Entries)2081   bool parse(StringRef File, SmallVectorImpl<EditEntry> &Entries) {
2082     using namespace llvm::yaml;
2083 
2084     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileBufOrErr =
2085         llvm::MemoryBuffer::getFile(File);
2086     if (!FileBufOrErr)
2087       return true;
2088 
2089     llvm::SourceMgr SM;
2090     Stream YAMLStream(FileBufOrErr.get()->getMemBufferRef(), SM);
2091     document_iterator I = YAMLStream.begin();
2092     if (I == YAMLStream.end())
2093       return true;
2094     Node *Root = I->getRoot();
2095     if (!Root)
2096       return true;
2097 
2098     SequenceNode *SeqNode = dyn_cast<SequenceNode>(Root);
2099     if (!SeqNode)
2100       return true;
2101 
2102     for (SequenceNode::iterator
2103            AI = SeqNode->begin(), AE = SeqNode->end(); AI != AE; ++AI) {
2104       MappingNode *MapNode = dyn_cast<MappingNode>(&*AI);
2105       if (!MapNode)
2106         continue;
2107       parseEdit(MapNode, Entries);
2108     }
2109 
2110     return false;
2111   }
2112 
2113 private:
parseEdit(llvm::yaml::MappingNode * Node,SmallVectorImpl<EditEntry> & Entries)2114   void parseEdit(llvm::yaml::MappingNode *Node,
2115                  SmallVectorImpl<EditEntry> &Entries) {
2116     using namespace llvm::yaml;
2117     EditEntry Entry;
2118     bool Ignore = false;
2119 
2120     for (MappingNode::iterator
2121            KVI = Node->begin(), KVE = Node->end(); KVI != KVE; ++KVI) {
2122       ScalarNode *KeyString = dyn_cast<ScalarNode>((*KVI).getKey());
2123       if (!KeyString)
2124         continue;
2125       SmallString<10> KeyStorage;
2126       StringRef Key = KeyString->getValue(KeyStorage);
2127 
2128       ScalarNode *ValueString = dyn_cast<ScalarNode>((*KVI).getValue());
2129       if (!ValueString)
2130         continue;
2131       SmallString<64> ValueStorage;
2132       StringRef Val = ValueString->getValue(ValueStorage);
2133 
2134       if (Key == "file") {
2135         const FileEntry *FE = FileMgr.getFile(Val);
2136         if (!FE)
2137           Ignore = true;
2138         Entry.File = FE;
2139       } else if (Key == "offset") {
2140         if (Val.getAsInteger(10, Entry.Offset))
2141           Ignore = true;
2142       } else if (Key == "remove") {
2143         if (Val.getAsInteger(10, Entry.RemoveLen))
2144           Ignore = true;
2145       } else if (Key == "text") {
2146         Entry.Text = Val;
2147       }
2148     }
2149 
2150     if (!Ignore)
2151       Entries.push_back(Entry);
2152   }
2153 };
2154 } // end anonymous namespace
2155 
reportDiag(const Twine & Err,DiagnosticsEngine & Diag)2156 static bool reportDiag(const Twine &Err, DiagnosticsEngine &Diag) {
2157   Diag.Report(Diag.getCustomDiagID(DiagnosticsEngine::Error, "%0"))
2158       << Err.str();
2159   return true;
2160 }
2161 
applyEditsToTemp(const FileEntry * FE,ArrayRef<EditEntry> Edits,FileManager & FileMgr,DiagnosticsEngine & Diag)2162 static std::string applyEditsToTemp(const FileEntry *FE,
2163                                     ArrayRef<EditEntry> Edits,
2164                                     FileManager &FileMgr,
2165                                     DiagnosticsEngine &Diag) {
2166   using namespace llvm::sys;
2167 
2168   SourceManager SM(Diag, FileMgr);
2169   FileID FID = SM.createFileID(FE, SourceLocation(), SrcMgr::C_User);
2170   LangOptions LangOpts;
2171   edit::EditedSource Editor(SM, LangOpts);
2172   for (ArrayRef<EditEntry>::iterator
2173         I = Edits.begin(), E = Edits.end(); I != E; ++I) {
2174     const EditEntry &Entry = *I;
2175     assert(Entry.File == FE);
2176     SourceLocation Loc =
2177         SM.getLocForStartOfFile(FID).getLocWithOffset(Entry.Offset);
2178     CharSourceRange Range;
2179     if (Entry.RemoveLen != 0) {
2180       Range = CharSourceRange::getCharRange(Loc,
2181                                          Loc.getLocWithOffset(Entry.RemoveLen));
2182     }
2183 
2184     edit::Commit commit(Editor);
2185     if (Range.isInvalid()) {
2186       commit.insert(Loc, Entry.Text);
2187     } else if (Entry.Text.empty()) {
2188       commit.remove(Range);
2189     } else {
2190       commit.replace(Range, Entry.Text);
2191     }
2192     Editor.commit(commit);
2193   }
2194 
2195   Rewriter rewriter(SM, LangOpts);
2196   RewritesReceiver Rec(rewriter);
2197   Editor.applyRewrites(Rec);
2198 
2199   const RewriteBuffer *Buf = rewriter.getRewriteBufferFor(FID);
2200   SmallString<512> NewText;
2201   llvm::raw_svector_ostream OS(NewText);
2202   Buf->write(OS);
2203 
2204   SmallString<64> TempPath;
2205   int FD;
2206   if (fs::createTemporaryFile(path::filename(FE->getName()),
2207                               path::extension(FE->getName()).drop_front(), FD,
2208                               TempPath)) {
2209     reportDiag("Could not create file: " + TempPath.str(), Diag);
2210     return std::string();
2211   }
2212 
2213   llvm::raw_fd_ostream TmpOut(FD, /*shouldClose=*/true);
2214   TmpOut.write(NewText.data(), NewText.size());
2215   TmpOut.close();
2216 
2217   return TempPath.str();
2218 }
2219 
getFileRemappingsFromFileList(std::vector<std::pair<std::string,std::string>> & remap,ArrayRef<StringRef> remapFiles,DiagnosticConsumer * DiagClient)2220 bool arcmt::getFileRemappingsFromFileList(
2221                         std::vector<std::pair<std::string,std::string> > &remap,
2222                         ArrayRef<StringRef> remapFiles,
2223                         DiagnosticConsumer *DiagClient) {
2224   bool hasErrorOccurred = false;
2225 
2226   FileSystemOptions FSOpts;
2227   FileManager FileMgr(FSOpts);
2228   RemapFileParser Parser(FileMgr);
2229 
2230   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
2231   IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
2232       new DiagnosticsEngine(DiagID, new DiagnosticOptions,
2233                             DiagClient, /*ShouldOwnClient=*/false));
2234 
2235   typedef llvm::DenseMap<const FileEntry *, std::vector<EditEntry> >
2236       FileEditEntriesTy;
2237   FileEditEntriesTy FileEditEntries;
2238 
2239   llvm::DenseSet<EditEntry> EntriesSet;
2240 
2241   for (ArrayRef<StringRef>::iterator
2242          I = remapFiles.begin(), E = remapFiles.end(); I != E; ++I) {
2243     SmallVector<EditEntry, 16> Entries;
2244     if (Parser.parse(*I, Entries))
2245       continue;
2246 
2247     for (SmallVectorImpl<EditEntry>::iterator
2248            EI = Entries.begin(), EE = Entries.end(); EI != EE; ++EI) {
2249       EditEntry &Entry = *EI;
2250       if (!Entry.File)
2251         continue;
2252       std::pair<llvm::DenseSet<EditEntry>::iterator, bool>
2253         Insert = EntriesSet.insert(Entry);
2254       if (!Insert.second)
2255         continue;
2256 
2257       FileEditEntries[Entry.File].push_back(Entry);
2258     }
2259   }
2260 
2261   for (FileEditEntriesTy::iterator
2262          I = FileEditEntries.begin(), E = FileEditEntries.end(); I != E; ++I) {
2263     std::string TempFile = applyEditsToTemp(I->first, I->second,
2264                                             FileMgr, *Diags);
2265     if (TempFile.empty()) {
2266       hasErrorOccurred = true;
2267       continue;
2268     }
2269 
2270     remap.emplace_back(I->first->getName(), TempFile);
2271   }
2272 
2273   return hasErrorOccurred;
2274 }
2275