Coverage Report

Created: 2019-07-24 05:18

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