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