ARCMT.cpp revision 8f0e8d22960d56f8390f4971e2c0f2f0a0884602
1//===--- ARCMT.cpp - Migration to ARC mode --------------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "Internals.h"
11#include "clang/Frontend/ASTUnit.h"
12#include "clang/Frontend/CompilerInstance.h"
13#include "clang/Frontend/Utils.h"
14#include "clang/AST/ASTConsumer.h"
15#include "clang/Rewrite/Rewriter.h"
16#include "clang/Sema/SemaDiagnostic.h"
17#include "clang/Basic/DiagnosticCategories.h"
18#include "clang/Lex/Preprocessor.h"
19#include "llvm/Support/MemoryBuffer.h"
20#include "llvm/ADT/Triple.h"
21
22using namespace clang;
23using namespace arcmt;
24using llvm::StringRef;
25
26bool CapturedDiagList::clearDiagnostic(llvm::ArrayRef<unsigned> IDs,
27                                       SourceRange range) {
28  if (range.isInvalid())
29    return false;
30
31  bool cleared = false;
32  ListTy::iterator I = List.begin();
33  while (I != List.end()) {
34    FullSourceLoc diagLoc = I->getLocation();
35    if ((IDs.empty() || // empty means clear all diagnostics in the range.
36         std::find(IDs.begin(), IDs.end(), I->getID()) != IDs.end()) &&
37        !diagLoc.isBeforeInTranslationUnitThan(range.getBegin()) &&
38        (diagLoc == range.getEnd() ||
39           diagLoc.isBeforeInTranslationUnitThan(range.getEnd()))) {
40      cleared = true;
41      ListTy::iterator eraseS = I++;
42      while (I != List.end() && I->getLevel() == Diagnostic::Note)
43        ++I;
44      // Clear the diagnostic and any notes following it.
45      List.erase(eraseS, I);
46      continue;
47    }
48
49    ++I;
50  }
51
52  return cleared;
53}
54
55bool CapturedDiagList::hasDiagnostic(llvm::ArrayRef<unsigned> IDs,
56                                     SourceRange range) {
57  if (range.isInvalid())
58    return false;
59
60  ListTy::iterator I = List.begin();
61  while (I != List.end()) {
62    FullSourceLoc diagLoc = I->getLocation();
63    if ((IDs.empty() || // empty means any diagnostic in the range.
64         std::find(IDs.begin(), IDs.end(), I->getID()) != IDs.end()) &&
65        !diagLoc.isBeforeInTranslationUnitThan(range.getBegin()) &&
66        (diagLoc == range.getEnd() ||
67           diagLoc.isBeforeInTranslationUnitThan(range.getEnd()))) {
68      return true;
69    }
70
71    ++I;
72  }
73
74  return false;
75}
76
77void CapturedDiagList::reportDiagnostics(Diagnostic &Diags) {
78  for (ListTy::iterator I = List.begin(), E = List.end(); I != E; ++I)
79    Diags.Report(*I);
80}
81
82namespace {
83
84class CaptureDiagnosticClient : public DiagnosticClient {
85  Diagnostic &Diags;
86  CapturedDiagList &CapturedDiags;
87public:
88  CaptureDiagnosticClient(Diagnostic &diags,
89                          CapturedDiagList &capturedDiags)
90    : Diags(diags), CapturedDiags(capturedDiags) { }
91
92  virtual void HandleDiagnostic(Diagnostic::Level level,
93                                const DiagnosticInfo &Info) {
94    if (arcmt::isARCDiagnostic(Info.getID(), Diags) ||
95        level >= Diagnostic::Error || level == Diagnostic::Note) {
96      CapturedDiags.push_back(StoredDiagnostic(level, Info));
97      return;
98    }
99
100    // Non-ARC warnings are ignored.
101    Diags.setLastDiagnosticIgnored();
102  }
103};
104
105} // end anonymous namespace
106
107CompilerInvocation *createInvocationForMigration(CompilerInvocation &origCI) {
108  llvm::OwningPtr<CompilerInvocation> CInvok;
109  CInvok.reset(new CompilerInvocation(origCI));
110  CInvok->getPreprocessorOpts().ImplicitPCHInclude = std::string();
111  CInvok->getPreprocessorOpts().ImplicitPTHInclude = std::string();
112  std::string define = getARCMTMacroName();
113  define += '=';
114  CInvok->getPreprocessorOpts().addMacroDef(define);
115  CInvok->getLangOpts().ObjCAutoRefCount = true;
116  CInvok->getDiagnosticOpts().ErrorLimit = 0;
117
118  // FIXME: Hackety hack! Try to find out if there is an ARC runtime.
119  bool hasARCRuntime = false;
120  llvm::SmallVector<std::string, 16> args;
121  args.push_back("-x");
122  args.push_back("objective-c");
123  args.push_back("-fobjc-arc");
124
125  llvm::Triple triple(CInvok->getTargetOpts().Triple);
126  if (triple.getOS() == llvm::Triple::IOS ||
127      triple.getOS() == llvm::Triple::MacOSX) {
128    unsigned Major, Minor, Micro;
129    triple.getOSVersion(Major, Minor, Micro);
130    llvm::SmallString<100> flag;
131    if (triple.getOS() == llvm::Triple::IOS)
132      flag += "-miphoneos-version-min=";
133    else
134      flag += "-mmacosx-version-min=";
135    llvm::raw_svector_ostream(flag) << Major << '.' << Minor << '.' << Micro;
136    args.push_back(flag.str());
137  }
138
139  args.push_back(origCI.getFrontendOpts().Inputs[0].second.c_str());
140  // Also push all defines to deal with the iOS simulator hack.
141  for (unsigned i = 0, e = origCI.getPreprocessorOpts().Macros.size();
142         i != e; ++i) {
143    std::string &def = origCI.getPreprocessorOpts().Macros[i].first;
144    bool isUndef = origCI.getPreprocessorOpts().Macros[i].second;
145    if (!isUndef) {
146      std::string newdef = "-D";
147      newdef += def;
148      args.push_back(newdef);
149    }
150  }
151
152  llvm::SmallVector<const char *, 16> cargs;
153  for (unsigned i = 0, e = args.size(); i != e; ++i)
154    cargs.push_back(args[i].c_str());
155
156  llvm::OwningPtr<CompilerInvocation> checkCI;
157  checkCI.reset(clang::createInvocationFromCommandLine(cargs));
158  if (checkCI)
159    hasARCRuntime = !checkCI->getLangOpts().ObjCNoAutoRefCountRuntime;
160
161  CInvok->getLangOpts().ObjCNoAutoRefCountRuntime = !hasARCRuntime;
162
163  return CInvok.take();
164}
165
166//===----------------------------------------------------------------------===//
167// checkForManualIssues.
168//===----------------------------------------------------------------------===//
169
170bool arcmt::checkForManualIssues(CompilerInvocation &origCI,
171                                 llvm::StringRef Filename, InputKind Kind,
172                                 DiagnosticClient *DiagClient) {
173  if (!origCI.getLangOpts().ObjC1)
174    return false;
175
176  std::vector<TransformFn> transforms = arcmt::getAllTransformations();
177  assert(!transforms.empty());
178
179  llvm::OwningPtr<CompilerInvocation> CInvok;
180  CInvok.reset(createInvocationForMigration(origCI));
181  CInvok->getFrontendOpts().Inputs.clear();
182  CInvok->getFrontendOpts().Inputs.push_back(std::make_pair(Kind, Filename));
183
184  CapturedDiagList capturedDiags;
185
186  assert(DiagClient);
187  llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
188  llvm::IntrusiveRefCntPtr<Diagnostic> Diags(
189                 new Diagnostic(DiagID, DiagClient, /*ShouldOwnClient=*/false));
190
191  // Filter of all diagnostics.
192  CaptureDiagnosticClient errRec(*Diags, capturedDiags);
193  Diags->setClient(&errRec, /*ShouldOwnClient=*/false);
194
195  llvm::OwningPtr<ASTUnit> Unit(
196      ASTUnit::LoadFromCompilerInvocationAction(CInvok.take(), Diags));
197  if (!Unit)
198    return true;
199
200  // Don't filter diagnostics anymore.
201  Diags->setClient(DiagClient, /*ShouldOwnClient=*/false);
202
203  ASTContext &Ctx = Unit->getASTContext();
204
205  if (Diags->hasFatalErrorOccurred()) {
206    Diags->Reset();
207    DiagClient->BeginSourceFile(Ctx.getLangOptions(), &Unit->getPreprocessor());
208    capturedDiags.reportDiagnostics(*Diags);
209    DiagClient->EndSourceFile();
210    return true;
211  }
212
213  // After parsing of source files ended, we want to reuse the
214  // diagnostics objects to emit further diagnostics.
215  // We call BeginSourceFile because DiagnosticClient requires that
216  // diagnostics with source range information are emitted only in between
217  // BeginSourceFile() and EndSourceFile().
218  DiagClient->BeginSourceFile(Ctx.getLangOptions(), &Unit->getPreprocessor());
219
220  // No macros will be added since we are just checking and we won't modify
221  // source code.
222  std::vector<SourceLocation> ARCMTMacroLocs;
223
224  TransformActions testAct(*Diags, capturedDiags, Ctx, Unit->getPreprocessor());
225  MigrationPass pass(Ctx, Unit->getSema(), testAct, ARCMTMacroLocs);
226
227  for (unsigned i=0, e = transforms.size(); i != e; ++i)
228    transforms[i](pass);
229
230  capturedDiags.reportDiagnostics(*Diags);
231
232  DiagClient->EndSourceFile();
233
234  return Diags->getClient()->getNumErrors() > 0;
235}
236
237//===----------------------------------------------------------------------===//
238// applyTransformations.
239//===----------------------------------------------------------------------===//
240
241bool arcmt::applyTransformations(CompilerInvocation &origCI,
242                                 llvm::StringRef Filename, InputKind Kind,
243                                 DiagnosticClient *DiagClient) {
244  if (!origCI.getLangOpts().ObjC1)
245    return false;
246
247  // Make sure checking is successful first.
248  CompilerInvocation CInvokForCheck(origCI);
249  if (arcmt::checkForManualIssues(CInvokForCheck, Filename, Kind, DiagClient))
250    return true;
251
252  CompilerInvocation CInvok(origCI);
253  CInvok.getFrontendOpts().Inputs.clear();
254  CInvok.getFrontendOpts().Inputs.push_back(std::make_pair(Kind, Filename));
255
256  MigrationProcess migration(CInvok, DiagClient);
257
258  std::vector<TransformFn> transforms = arcmt::getAllTransformations();
259  assert(!transforms.empty());
260
261  for (unsigned i=0, e = transforms.size(); i != e; ++i) {
262    bool err = migration.applyTransform(transforms[i]);
263    if (err) return true;
264  }
265
266  origCI.getLangOpts().ObjCAutoRefCount = true;
267
268  llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
269  llvm::IntrusiveRefCntPtr<Diagnostic> Diags(
270                 new Diagnostic(DiagID, DiagClient, /*ShouldOwnClient=*/false));
271  return migration.getRemapper().overwriteOriginal(*Diags);
272}
273
274//===----------------------------------------------------------------------===//
275// applyTransformationsInMemory.
276//===----------------------------------------------------------------------===//
277
278bool arcmt::applyTransformationsInMemory(CompilerInvocation &origCI,
279                                       llvm::StringRef Filename, InputKind Kind,
280                                       DiagnosticClient *DiagClient) {
281  if (!origCI.getLangOpts().ObjC1)
282    return false;
283
284  // Make sure checking is successful first.
285  CompilerInvocation CInvokForCheck(origCI);
286  if (arcmt::checkForManualIssues(CInvokForCheck, Filename, Kind, DiagClient))
287    return true;
288
289  CompilerInvocation CInvok(origCI);
290  CInvok.getFrontendOpts().Inputs.clear();
291  CInvok.getFrontendOpts().Inputs.push_back(std::make_pair(Kind, Filename));
292
293  MigrationProcess migration(CInvok, DiagClient);
294
295  std::vector<TransformFn> transforms = arcmt::getAllTransformations();
296  assert(!transforms.empty());
297
298  for (unsigned i=0, e = transforms.size(); i != e; ++i) {
299    bool err = migration.applyTransform(transforms[i]);
300    if (err) return true;
301  }
302
303  origCI.getLangOpts().ObjCAutoRefCount = true;
304  migration.getRemapper().transferMappingsAndClear(origCI);
305
306  return false;
307}
308
309//===----------------------------------------------------------------------===//
310// CollectTransformActions.
311//===----------------------------------------------------------------------===//
312
313namespace {
314
315class ARCMTMacroTrackerPPCallbacks : public PPCallbacks {
316  std::vector<SourceLocation> &ARCMTMacroLocs;
317
318public:
319  ARCMTMacroTrackerPPCallbacks(std::vector<SourceLocation> &ARCMTMacroLocs)
320    : ARCMTMacroLocs(ARCMTMacroLocs) { }
321
322  virtual void MacroExpands(const Token &MacroNameTok, const MacroInfo *MI) {
323    if (MacroNameTok.getIdentifierInfo()->getName() == getARCMTMacroName())
324      ARCMTMacroLocs.push_back(MacroNameTok.getLocation());
325  }
326};
327
328class ARCMTMacroTrackerAction : public ASTFrontendAction {
329  std::vector<SourceLocation> &ARCMTMacroLocs;
330
331public:
332  ARCMTMacroTrackerAction(std::vector<SourceLocation> &ARCMTMacroLocs)
333    : ARCMTMacroLocs(ARCMTMacroLocs) { }
334
335  virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
336                                         llvm::StringRef InFile) {
337    CI.getPreprocessor().addPPCallbacks(
338                              new ARCMTMacroTrackerPPCallbacks(ARCMTMacroLocs));
339    return new ASTConsumer();
340  }
341};
342
343class RewritesApplicator : public TransformActions::RewriteReceiver {
344  Rewriter &rewriter;
345  ASTContext &Ctx;
346  MigrationProcess::RewriteListener *Listener;
347
348public:
349  RewritesApplicator(Rewriter &rewriter, ASTContext &ctx,
350                     MigrationProcess::RewriteListener *listener)
351    : rewriter(rewriter), Ctx(ctx), Listener(listener) {
352    if (Listener)
353      Listener->start(ctx);
354  }
355  ~RewritesApplicator() {
356    if (Listener)
357      Listener->finish();
358  }
359
360  virtual void insert(SourceLocation loc, llvm::StringRef text) {
361    bool err = rewriter.InsertText(loc, text, /*InsertAfter=*/true,
362                                   /*indentNewLines=*/true);
363    if (!err && Listener)
364      Listener->insert(loc, text);
365  }
366
367  virtual void remove(CharSourceRange range) {
368    Rewriter::RewriteOptions removeOpts;
369    removeOpts.IncludeInsertsAtBeginOfRange = false;
370    removeOpts.IncludeInsertsAtEndOfRange = false;
371    removeOpts.RemoveLineIfEmpty = true;
372
373    bool err = rewriter.RemoveText(range, removeOpts);
374    if (!err && Listener)
375      Listener->remove(range);
376  }
377
378  virtual void increaseIndentation(CharSourceRange range,
379                                    SourceLocation parentIndent) {
380    rewriter.IncreaseIndentation(range, parentIndent);
381  }
382};
383
384} // end anonymous namespace.
385
386/// \brief Anchor for VTable.
387MigrationProcess::RewriteListener::~RewriteListener() { }
388
389bool MigrationProcess::applyTransform(TransformFn trans,
390                                      RewriteListener *listener) {
391  llvm::OwningPtr<CompilerInvocation> CInvok;
392  CInvok.reset(createInvocationForMigration(OrigCI));
393  CInvok->getDiagnosticOpts().IgnoreWarnings = true;
394
395  Remapper.applyMappings(*CInvok);
396
397  CapturedDiagList capturedDiags;
398  std::vector<SourceLocation> ARCMTMacroLocs;
399
400  assert(DiagClient);
401  llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
402  llvm::IntrusiveRefCntPtr<Diagnostic> Diags(
403               new Diagnostic(DiagID, DiagClient, /*ShouldOwnClient=*/false));
404
405  // Filter of all diagnostics.
406  CaptureDiagnosticClient errRec(*Diags, capturedDiags);
407  Diags->setClient(&errRec, /*ShouldOwnClient=*/false);
408
409  llvm::OwningPtr<ARCMTMacroTrackerAction> ASTAction;
410  ASTAction.reset(new ARCMTMacroTrackerAction(ARCMTMacroLocs));
411
412  llvm::OwningPtr<ASTUnit> Unit(
413      ASTUnit::LoadFromCompilerInvocationAction(CInvok.take(), Diags,
414                                                ASTAction.get()));
415  if (!Unit)
416    return true;
417  Unit->setOwnsRemappedFileBuffers(false); // FileRemapper manages that.
418
419  // Don't filter diagnostics anymore.
420  Diags->setClient(DiagClient, /*ShouldOwnClient=*/false);
421
422  ASTContext &Ctx = Unit->getASTContext();
423
424  if (Diags->hasFatalErrorOccurred()) {
425    Diags->Reset();
426    DiagClient->BeginSourceFile(Ctx.getLangOptions(), &Unit->getPreprocessor());
427    capturedDiags.reportDiagnostics(*Diags);
428    DiagClient->EndSourceFile();
429    return true;
430  }
431
432  // After parsing of source files ended, we want to reuse the
433  // diagnostics objects to emit further diagnostics.
434  // We call BeginSourceFile because DiagnosticClient requires that
435  // diagnostics with source range information are emitted only in between
436  // BeginSourceFile() and EndSourceFile().
437  DiagClient->BeginSourceFile(Ctx.getLangOptions(), &Unit->getPreprocessor());
438
439  Rewriter rewriter(Ctx.getSourceManager(), Ctx.getLangOptions());
440  TransformActions TA(*Diags, capturedDiags, Ctx, Unit->getPreprocessor());
441  MigrationPass pass(Ctx, Unit->getSema(), TA, ARCMTMacroLocs);
442
443  trans(pass);
444
445  {
446    RewritesApplicator applicator(rewriter, Ctx, listener);
447    TA.applyRewrites(applicator);
448  }
449
450  DiagClient->EndSourceFile();
451
452  if (DiagClient->getNumErrors())
453    return true;
454
455  for (Rewriter::buffer_iterator
456        I = rewriter.buffer_begin(), E = rewriter.buffer_end(); I != E; ++I) {
457    FileID FID = I->first;
458    RewriteBuffer &buf = I->second;
459    const FileEntry *file = Ctx.getSourceManager().getFileEntryForID(FID);
460    assert(file);
461    std::string newFname = file->getName();
462    newFname += "-trans";
463    llvm::SmallString<512> newText;
464    llvm::raw_svector_ostream vecOS(newText);
465    buf.write(vecOS);
466    vecOS.flush();
467    llvm::MemoryBuffer *memBuf = llvm::MemoryBuffer::getMemBufferCopy(
468                   llvm::StringRef(newText.data(), newText.size()), newFname);
469    llvm::SmallString<64> filePath(file->getName());
470    Unit->getFileManager().FixupRelativePath(filePath);
471    Remapper.remap(filePath.str(), memBuf);
472  }
473
474  return false;
475}
476
477//===----------------------------------------------------------------------===//
478// isARCDiagnostic.
479//===----------------------------------------------------------------------===//
480
481bool arcmt::isARCDiagnostic(unsigned diagID, Diagnostic &Diag) {
482  return Diag.getDiagnosticIDs()->getCategoryNumberForDiag(diagID) ==
483           diag::DiagCat_Automatic_Reference_Counting_Issue;
484}
485