ARCMT.cpp revision 377e5c108bd299930ca8e8cb6ebce1d22dfe35f9
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/FrontendAction.h"
14#include "clang/Frontend/TextDiagnosticPrinter.h"
15#include "clang/Frontend/Utils.h"
16#include "clang/AST/ASTConsumer.h"
17#include "clang/Rewrite/Core/Rewriter.h"
18#include "clang/Sema/SemaDiagnostic.h"
19#include "clang/Basic/DiagnosticCategories.h"
20#include "clang/Lex/Preprocessor.h"
21#include "llvm/Support/MemoryBuffer.h"
22#include "llvm/ADT/Triple.h"
23using namespace clang;
24using namespace arcmt;
25
26bool CapturedDiagList::clearDiagnostic(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() == DiagnosticsEngine::Note)
43        ++I;
44      // Clear the diagnostic and any notes following it.
45      I = List.erase(eraseS, I);
46      continue;
47    }
48
49    ++I;
50  }
51
52  return cleared;
53}
54
55bool CapturedDiagList::hasDiagnostic(ArrayRef<unsigned> IDs,
56                                     SourceRange range) const {
57  if (range.isInvalid())
58    return false;
59
60  ListTy::const_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(DiagnosticsEngine &Diags) const {
78  for (ListTy::const_iterator I = List.begin(), E = List.end(); I != E; ++I)
79    Diags.Report(*I);
80}
81
82bool CapturedDiagList::hasErrors() const {
83  for (ListTy::const_iterator I = List.begin(), E = List.end(); I != E; ++I)
84    if (I->getLevel() >= DiagnosticsEngine::Error)
85      return true;
86
87  return false;
88}
89
90namespace {
91
92class CaptureDiagnosticConsumer : public DiagnosticConsumer {
93  DiagnosticsEngine &Diags;
94  DiagnosticConsumer &DiagClient;
95  CapturedDiagList &CapturedDiags;
96  bool HasBegunSourceFile;
97public:
98  CaptureDiagnosticConsumer(DiagnosticsEngine &diags,
99                            DiagnosticConsumer &client,
100                            CapturedDiagList &capturedDiags)
101    : Diags(diags), DiagClient(client), CapturedDiags(capturedDiags),
102      HasBegunSourceFile(false) { }
103
104  virtual void BeginSourceFile(const LangOptions &Opts,
105                               const Preprocessor *PP) {
106    // Pass BeginSourceFile message onto DiagClient on first call.
107    // The corresponding EndSourceFile call will be made from an
108    // explicit call to FinishCapture.
109    if (!HasBegunSourceFile) {
110      DiagClient.BeginSourceFile(Opts, PP);
111      HasBegunSourceFile = true;
112    }
113  }
114
115  void FinishCapture() {
116    // Call EndSourceFile on DiagClient on completion of capture to
117    // enable VerifyDiagnosticConsumer to check diagnostics *after*
118    // it has received the diagnostic list.
119    if (HasBegunSourceFile) {
120      DiagClient.EndSourceFile();
121      HasBegunSourceFile = false;
122    }
123  }
124
125  virtual ~CaptureDiagnosticConsumer() {
126    assert(!HasBegunSourceFile && "FinishCapture not called!");
127  }
128
129  virtual void HandleDiagnostic(DiagnosticsEngine::Level level,
130                                const Diagnostic &Info) {
131    if (DiagnosticIDs::isARCDiagnostic(Info.getID()) ||
132        level >= DiagnosticsEngine::Error || level == DiagnosticsEngine::Note) {
133      CapturedDiags.push_back(StoredDiagnostic(level, Info));
134      return;
135    }
136
137    // Non-ARC warnings are ignored.
138    Diags.setLastDiagnosticIgnored();
139  }
140
141  DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
142    // Just drop any diagnostics that come from cloned consumers; they'll
143    // have different source managers anyway.
144    return new IgnoringDiagConsumer();
145  }
146};
147
148} // end anonymous namespace
149
150static bool HasARCRuntime(CompilerInvocation &origCI) {
151  // This duplicates some functionality from Darwin::AddDeploymentTarget
152  // but this function is well defined, so keep it decoupled from the driver
153  // and avoid unrelated complications.
154  llvm::Triple triple(origCI.getTargetOpts().Triple);
155
156  if (triple.getOS() == llvm::Triple::IOS)
157    return triple.getOSMajorVersion() >= 5;
158
159  if (triple.getOS() == llvm::Triple::Darwin)
160    return triple.getOSMajorVersion() >= 11;
161
162  if (triple.getOS() == llvm::Triple::MacOSX) {
163    unsigned Major, Minor, Micro;
164    triple.getOSVersion(Major, Minor, Micro);
165    return Major > 10 || (Major == 10 && Minor >= 7);
166  }
167
168  return false;
169}
170
171static CompilerInvocation *
172createInvocationForMigration(CompilerInvocation &origCI) {
173  OwningPtr<CompilerInvocation> CInvok;
174  CInvok.reset(new CompilerInvocation(origCI));
175  CInvok->getPreprocessorOpts().ImplicitPCHInclude = std::string();
176  CInvok->getPreprocessorOpts().ImplicitPTHInclude = std::string();
177  std::string define = getARCMTMacroName();
178  define += '=';
179  CInvok->getPreprocessorOpts().addMacroDef(define);
180  CInvok->getLangOpts()->ObjCAutoRefCount = true;
181  CInvok->getLangOpts()->setGC(LangOptions::NonGC);
182  CInvok->getDiagnosticOpts().ErrorLimit = 0;
183  CInvok->getDiagnosticOpts().PedanticErrors = 0;
184
185  // Ignore -Werror flags when migrating.
186  std::vector<std::string> WarnOpts;
187  for (std::vector<std::string>::iterator
188         I = CInvok->getDiagnosticOpts().Warnings.begin(),
189         E = CInvok->getDiagnosticOpts().Warnings.end(); I != E; ++I) {
190    if (!StringRef(*I).startswith("error"))
191      WarnOpts.push_back(*I);
192  }
193  WarnOpts.push_back("error=arc-unsafe-retained-assign");
194  CInvok->getDiagnosticOpts().Warnings = llvm_move(WarnOpts);
195
196  CInvok->getLangOpts()->ObjCARCWeak = HasARCRuntime(origCI);
197
198  return CInvok.take();
199}
200
201static void emitPremigrationErrors(const CapturedDiagList &arcDiags,
202                                   DiagnosticOptions *diagOpts,
203                                   Preprocessor &PP) {
204  TextDiagnosticPrinter printer(llvm::errs(), diagOpts);
205  IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
206  IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
207      new DiagnosticsEngine(DiagID, diagOpts, &printer,
208                            /*ShouldOwnClient=*/false));
209  Diags->setSourceManager(&PP.getSourceManager());
210
211  printer.BeginSourceFile(PP.getLangOpts(), &PP);
212  arcDiags.reportDiagnostics(*Diags);
213  printer.EndSourceFile();
214}
215
216//===----------------------------------------------------------------------===//
217// checkForManualIssues.
218//===----------------------------------------------------------------------===//
219
220bool arcmt::checkForManualIssues(CompilerInvocation &origCI,
221                                 const FrontendInputFile &Input,
222                                 DiagnosticConsumer *DiagClient,
223                                 bool emitPremigrationARCErrors,
224                                 StringRef plistOut) {
225  if (!origCI.getLangOpts()->ObjC1)
226    return false;
227
228  LangOptions::GCMode OrigGCMode = origCI.getLangOpts()->getGC();
229  bool NoNSAllocReallocError = origCI.getMigratorOpts().NoNSAllocReallocError;
230  bool NoFinalizeRemoval = origCI.getMigratorOpts().NoFinalizeRemoval;
231
232  std::vector<TransformFn> transforms = arcmt::getAllTransformations(OrigGCMode,
233                                                                     NoFinalizeRemoval);
234  assert(!transforms.empty());
235
236  OwningPtr<CompilerInvocation> CInvok;
237  CInvok.reset(createInvocationForMigration(origCI));
238  CInvok->getFrontendOpts().Inputs.clear();
239  CInvok->getFrontendOpts().Inputs.push_back(Input);
240
241  CapturedDiagList capturedDiags;
242
243  assert(DiagClient);
244  IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
245  IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
246      new DiagnosticsEngine(DiagID, &origCI.getDiagnosticOpts(),
247                            DiagClient, /*ShouldOwnClient=*/false));
248
249  // Filter of all diagnostics.
250  CaptureDiagnosticConsumer errRec(*Diags, *DiagClient, capturedDiags);
251  Diags->setClient(&errRec, /*ShouldOwnClient=*/false);
252
253  OwningPtr<ASTUnit> Unit(
254      ASTUnit::LoadFromCompilerInvocationAction(CInvok.take(), Diags));
255  if (!Unit) {
256    errRec.FinishCapture();
257    return true;
258  }
259
260  // Don't filter diagnostics anymore.
261  Diags->setClient(DiagClient, /*ShouldOwnClient=*/false);
262
263  ASTContext &Ctx = Unit->getASTContext();
264
265  if (Diags->hasFatalErrorOccurred()) {
266    Diags->Reset();
267    DiagClient->BeginSourceFile(Ctx.getLangOpts(), &Unit->getPreprocessor());
268    capturedDiags.reportDiagnostics(*Diags);
269    DiagClient->EndSourceFile();
270    errRec.FinishCapture();
271    return true;
272  }
273
274  if (emitPremigrationARCErrors)
275    emitPremigrationErrors(capturedDiags, &origCI.getDiagnosticOpts(),
276                           Unit->getPreprocessor());
277  if (!plistOut.empty()) {
278    SmallVector<StoredDiagnostic, 8> arcDiags;
279    for (CapturedDiagList::iterator
280           I = capturedDiags.begin(), E = capturedDiags.end(); I != E; ++I)
281      arcDiags.push_back(*I);
282    writeARCDiagsToPlist(plistOut, arcDiags,
283                         Ctx.getSourceManager(), Ctx.getLangOpts());
284  }
285
286  // After parsing of source files ended, we want to reuse the
287  // diagnostics objects to emit further diagnostics.
288  // We call BeginSourceFile because DiagnosticConsumer requires that
289  // diagnostics with source range information are emitted only in between
290  // BeginSourceFile() and EndSourceFile().
291  DiagClient->BeginSourceFile(Ctx.getLangOpts(), &Unit->getPreprocessor());
292
293  // No macros will be added since we are just checking and we won't modify
294  // source code.
295  std::vector<SourceLocation> ARCMTMacroLocs;
296
297  TransformActions testAct(*Diags, capturedDiags, Ctx, Unit->getPreprocessor());
298  MigrationPass pass(Ctx, OrigGCMode, Unit->getSema(), testAct, ARCMTMacroLocs);
299  pass.setNSAllocReallocError(NoNSAllocReallocError);
300  pass.setNoFinalizeRemoval(NoFinalizeRemoval);
301
302  for (unsigned i=0, e = transforms.size(); i != e; ++i)
303    transforms[i](pass);
304
305  capturedDiags.reportDiagnostics(*Diags);
306
307  DiagClient->EndSourceFile();
308  errRec.FinishCapture();
309
310  // If we are migrating code that gets the '-fobjc-arc' flag, make sure
311  // to remove it so that we don't get errors from normal compilation.
312  origCI.getLangOpts()->ObjCAutoRefCount = false;
313
314  return capturedDiags.hasErrors() || testAct.hasReportedErrors();
315}
316
317//===----------------------------------------------------------------------===//
318// applyTransformations.
319//===----------------------------------------------------------------------===//
320
321static bool applyTransforms(CompilerInvocation &origCI,
322                            const FrontendInputFile &Input,
323                            DiagnosticConsumer *DiagClient,
324                            StringRef outputDir,
325                            bool emitPremigrationARCErrors,
326                            StringRef plistOut) {
327  if (!origCI.getLangOpts()->ObjC1)
328    return false;
329
330  LangOptions::GCMode OrigGCMode = origCI.getLangOpts()->getGC();
331
332  // Make sure checking is successful first.
333  CompilerInvocation CInvokForCheck(origCI);
334  if (arcmt::checkForManualIssues(CInvokForCheck, Input, DiagClient,
335                                  emitPremigrationARCErrors, plistOut))
336    return true;
337
338  CompilerInvocation CInvok(origCI);
339  CInvok.getFrontendOpts().Inputs.clear();
340  CInvok.getFrontendOpts().Inputs.push_back(Input);
341
342  MigrationProcess migration(CInvok, DiagClient, outputDir);
343  bool NoFinalizeRemoval = origCI.getMigratorOpts().NoFinalizeRemoval;
344
345  std::vector<TransformFn> transforms = arcmt::getAllTransformations(OrigGCMode,
346                                                                     NoFinalizeRemoval);
347  assert(!transforms.empty());
348
349  for (unsigned i=0, e = transforms.size(); i != e; ++i) {
350    bool err = migration.applyTransform(transforms[i]);
351    if (err) return true;
352  }
353
354  IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
355  IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
356      new DiagnosticsEngine(DiagID, &origCI.getDiagnosticOpts(),
357                            DiagClient, /*ShouldOwnClient=*/false));
358
359  if (outputDir.empty()) {
360    origCI.getLangOpts()->ObjCAutoRefCount = true;
361    return migration.getRemapper().overwriteOriginal(*Diags);
362  } else {
363    // If we are migrating code that gets the '-fobjc-arc' flag, make sure
364    // to remove it so that we don't get errors from normal compilation.
365    origCI.getLangOpts()->ObjCAutoRefCount = false;
366    return migration.getRemapper().flushToDisk(outputDir, *Diags);
367  }
368}
369
370bool arcmt::applyTransformations(CompilerInvocation &origCI,
371                                 const FrontendInputFile &Input,
372                                 DiagnosticConsumer *DiagClient) {
373  return applyTransforms(origCI, Input, DiagClient,
374                         StringRef(), false, StringRef());
375}
376
377bool arcmt::migrateWithTemporaryFiles(CompilerInvocation &origCI,
378                                      const FrontendInputFile &Input,
379                                      DiagnosticConsumer *DiagClient,
380                                      StringRef outputDir,
381                                      bool emitPremigrationARCErrors,
382                                      StringRef plistOut) {
383  assert(!outputDir.empty() && "Expected output directory path");
384  return applyTransforms(origCI, Input, DiagClient,
385                         outputDir, emitPremigrationARCErrors, plistOut);
386}
387
388bool arcmt::getFileRemappings(std::vector<std::pair<std::string,std::string> > &
389                                  remap,
390                              StringRef outputDir,
391                              DiagnosticConsumer *DiagClient) {
392  assert(!outputDir.empty());
393
394  IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
395  IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
396      new DiagnosticsEngine(DiagID, new DiagnosticOptions,
397                            DiagClient, /*ShouldOwnClient=*/false));
398
399  FileRemapper remapper;
400  bool err = remapper.initFromDisk(outputDir, *Diags,
401                                   /*ignoreIfFilesChanged=*/true);
402  if (err)
403    return true;
404
405  PreprocessorOptions PPOpts;
406  remapper.applyMappings(PPOpts);
407  remap = PPOpts.RemappedFiles;
408
409  return false;
410}
411
412bool arcmt::getFileRemappingsFromFileList(
413                        std::vector<std::pair<std::string,std::string> > &remap,
414                        ArrayRef<StringRef> remapFiles,
415                        DiagnosticConsumer *DiagClient) {
416  bool hasErrorOccurred = false;
417  llvm::StringMap<bool> Uniquer;
418
419  llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
420  llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
421      new DiagnosticsEngine(DiagID, new DiagnosticOptions,
422                            DiagClient, /*ShouldOwnClient=*/false));
423
424  for (ArrayRef<StringRef>::iterator
425         I = remapFiles.begin(), E = remapFiles.end(); I != E; ++I) {
426    StringRef file = *I;
427
428    FileRemapper remapper;
429    bool err = remapper.initFromFile(file, *Diags,
430                                     /*ignoreIfFilesChanged=*/true);
431    hasErrorOccurred = hasErrorOccurred || err;
432    if (err)
433      continue;
434
435    PreprocessorOptions PPOpts;
436    remapper.applyMappings(PPOpts);
437    for (PreprocessorOptions::remapped_file_iterator
438           RI = PPOpts.remapped_file_begin(), RE = PPOpts.remapped_file_end();
439           RI != RE; ++RI) {
440      bool &inserted = Uniquer[RI->first];
441      if (inserted)
442        continue;
443      inserted = true;
444      remap.push_back(*RI);
445    }
446  }
447
448  return hasErrorOccurred;
449}
450
451//===----------------------------------------------------------------------===//
452// CollectTransformActions.
453//===----------------------------------------------------------------------===//
454
455namespace {
456
457class ARCMTMacroTrackerPPCallbacks : public PPCallbacks {
458  std::vector<SourceLocation> &ARCMTMacroLocs;
459
460public:
461  ARCMTMacroTrackerPPCallbacks(std::vector<SourceLocation> &ARCMTMacroLocs)
462    : ARCMTMacroLocs(ARCMTMacroLocs) { }
463
464  virtual void MacroExpands(const Token &MacroNameTok, const MacroInfo *MI,
465                            SourceRange Range) {
466    if (MacroNameTok.getIdentifierInfo()->getName() == getARCMTMacroName())
467      ARCMTMacroLocs.push_back(MacroNameTok.getLocation());
468  }
469};
470
471class ARCMTMacroTrackerAction : public ASTFrontendAction {
472  std::vector<SourceLocation> &ARCMTMacroLocs;
473
474public:
475  ARCMTMacroTrackerAction(std::vector<SourceLocation> &ARCMTMacroLocs)
476    : ARCMTMacroLocs(ARCMTMacroLocs) { }
477
478  virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
479                                         StringRef InFile) {
480    CI.getPreprocessor().addPPCallbacks(
481                              new ARCMTMacroTrackerPPCallbacks(ARCMTMacroLocs));
482    return new ASTConsumer();
483  }
484};
485
486class RewritesApplicator : public TransformActions::RewriteReceiver {
487  Rewriter &rewriter;
488  MigrationProcess::RewriteListener *Listener;
489
490public:
491  RewritesApplicator(Rewriter &rewriter, ASTContext &ctx,
492                     MigrationProcess::RewriteListener *listener)
493    : rewriter(rewriter), Listener(listener) {
494    if (Listener)
495      Listener->start(ctx);
496  }
497  ~RewritesApplicator() {
498    if (Listener)
499      Listener->finish();
500  }
501
502  virtual void insert(SourceLocation loc, StringRef text) {
503    bool err = rewriter.InsertText(loc, text, /*InsertAfter=*/true,
504                                   /*indentNewLines=*/true);
505    if (!err && Listener)
506      Listener->insert(loc, text);
507  }
508
509  virtual void remove(CharSourceRange range) {
510    Rewriter::RewriteOptions removeOpts;
511    removeOpts.IncludeInsertsAtBeginOfRange = false;
512    removeOpts.IncludeInsertsAtEndOfRange = false;
513    removeOpts.RemoveLineIfEmpty = true;
514
515    bool err = rewriter.RemoveText(range, removeOpts);
516    if (!err && Listener)
517      Listener->remove(range);
518  }
519
520  virtual void increaseIndentation(CharSourceRange range,
521                                    SourceLocation parentIndent) {
522    rewriter.IncreaseIndentation(range, parentIndent);
523  }
524};
525
526} // end anonymous namespace.
527
528/// \brief Anchor for VTable.
529MigrationProcess::RewriteListener::~RewriteListener() { }
530
531MigrationProcess::MigrationProcess(const CompilerInvocation &CI,
532                                   DiagnosticConsumer *diagClient,
533                                   StringRef outputDir)
534  : OrigCI(CI), DiagClient(diagClient) {
535  if (!outputDir.empty()) {
536    IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
537    IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
538      new DiagnosticsEngine(DiagID, &CI.getDiagnosticOpts(),
539                            DiagClient, /*ShouldOwnClient=*/false));
540    Remapper.initFromDisk(outputDir, *Diags, /*ignoreIfFilesChanges=*/true);
541  }
542}
543
544bool MigrationProcess::applyTransform(TransformFn trans,
545                                      RewriteListener *listener) {
546  OwningPtr<CompilerInvocation> CInvok;
547  CInvok.reset(createInvocationForMigration(OrigCI));
548  CInvok->getDiagnosticOpts().IgnoreWarnings = true;
549
550  Remapper.applyMappings(CInvok->getPreprocessorOpts());
551
552  CapturedDiagList capturedDiags;
553  std::vector<SourceLocation> ARCMTMacroLocs;
554
555  assert(DiagClient);
556  IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
557  IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
558      new DiagnosticsEngine(DiagID, new DiagnosticOptions,
559                            DiagClient, /*ShouldOwnClient=*/false));
560
561  // Filter of all diagnostics.
562  CaptureDiagnosticConsumer errRec(*Diags, *DiagClient, capturedDiags);
563  Diags->setClient(&errRec, /*ShouldOwnClient=*/false);
564
565  OwningPtr<ARCMTMacroTrackerAction> ASTAction;
566  ASTAction.reset(new ARCMTMacroTrackerAction(ARCMTMacroLocs));
567
568  OwningPtr<ASTUnit> Unit(
569      ASTUnit::LoadFromCompilerInvocationAction(CInvok.take(), Diags,
570                                                ASTAction.get()));
571  if (!Unit) {
572    errRec.FinishCapture();
573    return true;
574  }
575  Unit->setOwnsRemappedFileBuffers(false); // FileRemapper manages that.
576
577  // Don't filter diagnostics anymore.
578  Diags->setClient(DiagClient, /*ShouldOwnClient=*/false);
579
580  ASTContext &Ctx = Unit->getASTContext();
581
582  if (Diags->hasFatalErrorOccurred()) {
583    Diags->Reset();
584    DiagClient->BeginSourceFile(Ctx.getLangOpts(), &Unit->getPreprocessor());
585    capturedDiags.reportDiagnostics(*Diags);
586    DiagClient->EndSourceFile();
587    errRec.FinishCapture();
588    return true;
589  }
590
591  // After parsing of source files ended, we want to reuse the
592  // diagnostics objects to emit further diagnostics.
593  // We call BeginSourceFile because DiagnosticConsumer requires that
594  // diagnostics with source range information are emitted only in between
595  // BeginSourceFile() and EndSourceFile().
596  DiagClient->BeginSourceFile(Ctx.getLangOpts(), &Unit->getPreprocessor());
597
598  Rewriter rewriter(Ctx.getSourceManager(), Ctx.getLangOpts());
599  TransformActions TA(*Diags, capturedDiags, Ctx, Unit->getPreprocessor());
600  MigrationPass pass(Ctx, OrigCI.getLangOpts()->getGC(),
601                     Unit->getSema(), TA, ARCMTMacroLocs);
602
603  trans(pass);
604
605  {
606    RewritesApplicator applicator(rewriter, Ctx, listener);
607    TA.applyRewrites(applicator);
608  }
609
610  DiagClient->EndSourceFile();
611  errRec.FinishCapture();
612
613  if (DiagClient->getNumErrors())
614    return true;
615
616  for (Rewriter::buffer_iterator
617        I = rewriter.buffer_begin(), E = rewriter.buffer_end(); I != E; ++I) {
618    FileID FID = I->first;
619    RewriteBuffer &buf = I->second;
620    const FileEntry *file = Ctx.getSourceManager().getFileEntryForID(FID);
621    assert(file);
622    std::string newFname = file->getName();
623    newFname += "-trans";
624    SmallString<512> newText;
625    llvm::raw_svector_ostream vecOS(newText);
626    buf.write(vecOS);
627    vecOS.flush();
628    llvm::MemoryBuffer *memBuf = llvm::MemoryBuffer::getMemBufferCopy(
629                   StringRef(newText.data(), newText.size()), newFname);
630    SmallString<64> filePath(file->getName());
631    Unit->getFileManager().FixupRelativePath(filePath);
632    Remapper.remap(filePath.str(), memBuf);
633  }
634
635  return false;
636}
637