blob: df96ac8eaa8f2898825bc87937596e5e9db1982e [file] [log] [blame]
John McCalld70fb982011-06-15 23:25:17 +00001//===--- 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"
Chandler Carruth3a022472012-12-04 09:13:33 +000011#include "clang/AST/ASTConsumer.h"
12#include "clang/Basic/DiagnosticCategories.h"
John McCalld70fb982011-06-15 23:25:17 +000013#include "clang/Frontend/ASTUnit.h"
14#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor32fbe312012-01-20 16:28:04 +000015#include "clang/Frontend/FrontendAction.h"
Argyrios Kyrtzidisd5713632011-07-19 17:20:03 +000016#include "clang/Frontend/TextDiagnosticPrinter.h"
John McCalld70fb982011-06-15 23:25:17 +000017#include "clang/Frontend/Utils.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/Lex/Preprocessor.h"
Ted Kremenekcdf81492012-09-01 05:09:24 +000019#include "clang/Rewrite/Core/Rewriter.h"
John McCalld70fb982011-06-15 23:25:17 +000020#include "clang/Sema/SemaDiagnostic.h"
John McCalld70fb982011-06-15 23:25:17 +000021#include "llvm/ADT/Triple.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "llvm/Support/MemoryBuffer.h"
John McCalld70fb982011-06-15 23:25:17 +000023using namespace clang;
24using namespace arcmt;
John McCalld70fb982011-06-15 23:25:17 +000025
Chris Lattner54b16772011-07-23 17:14:25 +000026bool CapturedDiagList::clearDiagnostic(ArrayRef<unsigned> IDs,
John McCalld70fb982011-06-15 23:25:17 +000027 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++;
David Blaikie9c902b52011-09-25 23:23:43 +000042 while (I != List.end() && I->getLevel() == DiagnosticsEngine::Note)
John McCalld70fb982011-06-15 23:25:17 +000043 ++I;
44 // Clear the diagnostic and any notes following it.
Joao Matos0e167f72012-08-31 17:28:09 +000045 I = List.erase(eraseS, I);
John McCalld70fb982011-06-15 23:25:17 +000046 continue;
47 }
48
49 ++I;
50 }
51
52 return cleared;
53}
54
Chris Lattner54b16772011-07-23 17:14:25 +000055bool CapturedDiagList::hasDiagnostic(ArrayRef<unsigned> IDs,
Argyrios Kyrtzidis0f3f9f72011-06-18 00:53:34 +000056 SourceRange range) const {
John McCalld70fb982011-06-15 23:25:17 +000057 if (range.isInvalid())
58 return false;
59
Argyrios Kyrtzidis0f3f9f72011-06-18 00:53:34 +000060 ListTy::const_iterator I = List.begin();
John McCalld70fb982011-06-15 23:25:17 +000061 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
David Blaikie9c902b52011-09-25 23:23:43 +000077void CapturedDiagList::reportDiagnostics(DiagnosticsEngine &Diags) const {
Argyrios Kyrtzidis0f3f9f72011-06-18 00:53:34 +000078 for (ListTy::const_iterator I = List.begin(), E = List.end(); I != E; ++I)
John McCalld70fb982011-06-15 23:25:17 +000079 Diags.Report(*I);
80}
81
Argyrios Kyrtzidis90b6a2a2011-06-18 00:53:41 +000082bool CapturedDiagList::hasErrors() const {
83 for (ListTy::const_iterator I = List.begin(), E = List.end(); I != E; ++I)
David Blaikie9c902b52011-09-25 23:23:43 +000084 if (I->getLevel() >= DiagnosticsEngine::Error)
Argyrios Kyrtzidis90b6a2a2011-06-18 00:53:41 +000085 return true;
86
87 return false;
88}
89
John McCalld70fb982011-06-15 23:25:17 +000090namespace {
91
David Blaikiea24a0bc2011-09-25 23:54:33 +000092class CaptureDiagnosticConsumer : public DiagnosticConsumer {
David Blaikie9c902b52011-09-25 23:23:43 +000093 DiagnosticsEngine &Diags;
Jordan Roseb00073d2012-08-10 01:06:16 +000094 DiagnosticConsumer &DiagClient;
John McCalld70fb982011-06-15 23:25:17 +000095 CapturedDiagList &CapturedDiags;
Jordan Roseb00073d2012-08-10 01:06:16 +000096 bool HasBegunSourceFile;
John McCalld70fb982011-06-15 23:25:17 +000097public:
David Blaikiea24a0bc2011-09-25 23:54:33 +000098 CaptureDiagnosticConsumer(DiagnosticsEngine &diags,
Jordan Roseb00073d2012-08-10 01:06:16 +000099 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 }
John McCalld70fb982011-06-15 23:25:17 +0000128
David Blaikie9c902b52011-09-25 23:23:43 +0000129 virtual void HandleDiagnostic(DiagnosticsEngine::Level level,
David Blaikieb5784322011-09-26 01:18:08 +0000130 const Diagnostic &Info) {
Ted Kremenek337c5b82011-10-20 05:07:47 +0000131 if (DiagnosticIDs::isARCDiagnostic(Info.getID()) ||
David Blaikie9c902b52011-09-25 23:23:43 +0000132 level >= DiagnosticsEngine::Error || level == DiagnosticsEngine::Note) {
John McCalld70fb982011-06-15 23:25:17 +0000133 CapturedDiags.push_back(StoredDiagnostic(level, Info));
134 return;
135 }
136
137 // Non-ARC warnings are ignored.
138 Diags.setLastDiagnosticIgnored();
139 }
Douglas Gregord0e9e3a2011-09-29 00:38:00 +0000140
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 }
John McCalld70fb982011-06-15 23:25:17 +0000146};
147
148} // end anonymous namespace
149
Argyrios Kyrtzidis81a35902011-06-20 19:59:52 +0000150static 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.
Argyrios Kyrtzidis81a35902011-06-20 19:59:52 +0000154 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
Benjamin Kramer3c05b7c2011-08-02 04:50:49 +0000171static CompilerInvocation *
172createInvocationForMigration(CompilerInvocation &origCI) {
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000173 OwningPtr<CompilerInvocation> CInvok;
John McCalld70fb982011-06-15 23:25:17 +0000174 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);
Ted Kremenek8cf47df2011-11-17 23:01:24 +0000180 CInvok->getLangOpts()->ObjCAutoRefCount = true;
181 CInvok->getLangOpts()->setGC(LangOptions::NonGC);
John McCalld70fb982011-06-15 23:25:17 +0000182 CInvok->getDiagnosticOpts().ErrorLimit = 0;
Argyrios Kyrtzidisaa38f692012-06-20 01:46:26 +0000183 CInvok->getDiagnosticOpts().PedanticErrors = 0;
Argyrios Kyrtzidis692bf8c2012-06-20 01:10:40 +0000184
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");
Argyrios Kyrtzidisaa38f692012-06-20 01:46:26 +0000194 CInvok->getDiagnosticOpts().Warnings = llvm_move(WarnOpts);
Argyrios Kyrtzidis692bf8c2012-06-20 01:10:40 +0000195
John McCall3deb1ad2012-08-21 02:47:43 +0000196 CInvok->getLangOpts()->ObjCARCWeak = HasARCRuntime(origCI);
John McCalld70fb982011-06-15 23:25:17 +0000197
198 return CInvok.take();
199}
200
Benjamin Kramer3c05b7c2011-08-02 04:50:49 +0000201static void emitPremigrationErrors(const CapturedDiagList &arcDiags,
Douglas Gregor811db4e2012-10-23 22:26:28 +0000202 DiagnosticOptions *diagOpts,
Benjamin Kramer3c05b7c2011-08-02 04:50:49 +0000203 Preprocessor &PP) {
Argyrios Kyrtzidisd5713632011-07-19 17:20:03 +0000204 TextDiagnosticPrinter printer(llvm::errs(), diagOpts);
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000205 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
206 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Douglas Gregor811db4e2012-10-23 22:26:28 +0000207 new DiagnosticsEngine(DiagID, diagOpts, &printer,
208 /*ShouldOwnClient=*/false));
Argyrios Kyrtzidisd5713632011-07-19 17:20:03 +0000209 Diags->setSourceManager(&PP.getSourceManager());
210
David Blaikiebbafb8a2012-03-11 07:00:24 +0000211 printer.BeginSourceFile(PP.getLangOpts(), &PP);
Argyrios Kyrtzidisd5713632011-07-19 17:20:03 +0000212 arcDiags.reportDiagnostics(*Diags);
213 printer.EndSourceFile();
214}
215
John McCalld70fb982011-06-15 23:25:17 +0000216//===----------------------------------------------------------------------===//
217// checkForManualIssues.
218//===----------------------------------------------------------------------===//
219
220bool arcmt::checkForManualIssues(CompilerInvocation &origCI,
Douglas Gregor32fbe312012-01-20 16:28:04 +0000221 const FrontendInputFile &Input,
David Blaikiee2eefae2011-09-25 23:39:51 +0000222 DiagnosticConsumer *DiagClient,
Argyrios Kyrtzidisd5713632011-07-19 17:20:03 +0000223 bool emitPremigrationARCErrors,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000224 StringRef plistOut) {
Ted Kremenek8cf47df2011-11-17 23:01:24 +0000225 if (!origCI.getLangOpts()->ObjC1)
John McCalld70fb982011-06-15 23:25:17 +0000226 return false;
227
Ted Kremenek8cf47df2011-11-17 23:01:24 +0000228 LangOptions::GCMode OrigGCMode = origCI.getLangOpts()->getGC();
Fariborz Jahanianaa7b9aa2012-01-25 00:20:29 +0000229 bool NoNSAllocReallocError = origCI.getMigratorOpts().NoNSAllocReallocError;
Fariborz Jahanian0c859d62012-01-26 00:08:04 +0000230 bool NoFinalizeRemoval = origCI.getMigratorOpts().NoFinalizeRemoval;
Argyrios Kyrtzidisd208ef92011-11-04 15:58:08 +0000231
Fariborz Jahanian48fd81b2012-01-26 20:57:58 +0000232 std::vector<TransformFn> transforms = arcmt::getAllTransformations(OrigGCMode,
233 NoFinalizeRemoval);
John McCalld70fb982011-06-15 23:25:17 +0000234 assert(!transforms.empty());
235
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000236 OwningPtr<CompilerInvocation> CInvok;
John McCalld70fb982011-06-15 23:25:17 +0000237 CInvok.reset(createInvocationForMigration(origCI));
238 CInvok->getFrontendOpts().Inputs.clear();
Douglas Gregor32fbe312012-01-20 16:28:04 +0000239 CInvok->getFrontendOpts().Inputs.push_back(Input);
John McCalld70fb982011-06-15 23:25:17 +0000240
241 CapturedDiagList capturedDiags;
242
243 assert(DiagClient);
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000244 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
245 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Douglas Gregor811db4e2012-10-23 22:26:28 +0000246 new DiagnosticsEngine(DiagID, &origCI.getDiagnosticOpts(),
247 DiagClient, /*ShouldOwnClient=*/false));
John McCalld70fb982011-06-15 23:25:17 +0000248
249 // Filter of all diagnostics.
Jordan Roseb00073d2012-08-10 01:06:16 +0000250 CaptureDiagnosticConsumer errRec(*Diags, *DiagClient, capturedDiags);
John McCalld70fb982011-06-15 23:25:17 +0000251 Diags->setClient(&errRec, /*ShouldOwnClient=*/false);
252
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000253 OwningPtr<ASTUnit> Unit(
John McCalld70fb982011-06-15 23:25:17 +0000254 ASTUnit::LoadFromCompilerInvocationAction(CInvok.take(), Diags));
Jordan Roseb00073d2012-08-10 01:06:16 +0000255 if (!Unit) {
256 errRec.FinishCapture();
John McCalld70fb982011-06-15 23:25:17 +0000257 return true;
Jordan Roseb00073d2012-08-10 01:06:16 +0000258 }
John McCalld70fb982011-06-15 23:25:17 +0000259
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();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000267 DiagClient->BeginSourceFile(Ctx.getLangOpts(), &Unit->getPreprocessor());
John McCalld70fb982011-06-15 23:25:17 +0000268 capturedDiags.reportDiagnostics(*Diags);
269 DiagClient->EndSourceFile();
Jordan Roseb00073d2012-08-10 01:06:16 +0000270 errRec.FinishCapture();
John McCalld70fb982011-06-15 23:25:17 +0000271 return true;
272 }
273
Argyrios Kyrtzidisd5713632011-07-19 17:20:03 +0000274 if (emitPremigrationARCErrors)
Douglas Gregor811db4e2012-10-23 22:26:28 +0000275 emitPremigrationErrors(capturedDiags, &origCI.getDiagnosticOpts(),
Argyrios Kyrtzidisd5713632011-07-19 17:20:03 +0000276 Unit->getPreprocessor());
277 if (!plistOut.empty()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000278 SmallVector<StoredDiagnostic, 8> arcDiags;
Argyrios Kyrtzidisd5713632011-07-19 17:20:03 +0000279 for (CapturedDiagList::iterator
280 I = capturedDiags.begin(), E = capturedDiags.end(); I != E; ++I)
281 arcDiags.push_back(*I);
282 writeARCDiagsToPlist(plistOut, arcDiags,
David Blaikiebbafb8a2012-03-11 07:00:24 +0000283 Ctx.getSourceManager(), Ctx.getLangOpts());
Argyrios Kyrtzidisd5713632011-07-19 17:20:03 +0000284 }
285
John McCalld70fb982011-06-15 23:25:17 +0000286 // After parsing of source files ended, we want to reuse the
287 // diagnostics objects to emit further diagnostics.
David Blaikiee2eefae2011-09-25 23:39:51 +0000288 // We call BeginSourceFile because DiagnosticConsumer requires that
John McCalld70fb982011-06-15 23:25:17 +0000289 // diagnostics with source range information are emitted only in between
290 // BeginSourceFile() and EndSourceFile().
David Blaikiebbafb8a2012-03-11 07:00:24 +0000291 DiagClient->BeginSourceFile(Ctx.getLangOpts(), &Unit->getPreprocessor());
John McCalld70fb982011-06-15 23:25:17 +0000292
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());
Argyrios Kyrtzidisd208ef92011-11-04 15:58:08 +0000298 MigrationPass pass(Ctx, OrigGCMode, Unit->getSema(), testAct, ARCMTMacroLocs);
Fariborz Jahanianaa7b9aa2012-01-25 00:20:29 +0000299 pass.setNSAllocReallocError(NoNSAllocReallocError);
Fariborz Jahanian0c859d62012-01-26 00:08:04 +0000300 pass.setNoFinalizeRemoval(NoFinalizeRemoval);
John McCalld70fb982011-06-15 23:25:17 +0000301
302 for (unsigned i=0, e = transforms.size(); i != e; ++i)
303 transforms[i](pass);
304
305 capturedDiags.reportDiagnostics(*Diags);
306
307 DiagClient->EndSourceFile();
Jordan Roseb00073d2012-08-10 01:06:16 +0000308 errRec.FinishCapture();
John McCalld70fb982011-06-15 23:25:17 +0000309
Argyrios Kyrtzidise2e40b42011-07-14 00:17:54 +0000310 // 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.
Ted Kremenek8cf47df2011-11-17 23:01:24 +0000312 origCI.getLangOpts()->ObjCAutoRefCount = false;
Argyrios Kyrtzidise2e40b42011-07-14 00:17:54 +0000313
Argyrios Kyrtzidis73a0d322011-07-18 07:44:45 +0000314 return capturedDiags.hasErrors() || testAct.hasReportedErrors();
John McCalld70fb982011-06-15 23:25:17 +0000315}
316
317//===----------------------------------------------------------------------===//
318// applyTransformations.
319//===----------------------------------------------------------------------===//
320
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000321static bool applyTransforms(CompilerInvocation &origCI,
Douglas Gregor32fbe312012-01-20 16:28:04 +0000322 const FrontendInputFile &Input,
David Blaikiee2eefae2011-09-25 23:39:51 +0000323 DiagnosticConsumer *DiagClient,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000324 StringRef outputDir,
Argyrios Kyrtzidisd5713632011-07-19 17:20:03 +0000325 bool emitPremigrationARCErrors,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000326 StringRef plistOut) {
Ted Kremenek8cf47df2011-11-17 23:01:24 +0000327 if (!origCI.getLangOpts()->ObjC1)
John McCalld70fb982011-06-15 23:25:17 +0000328 return false;
329
Ted Kremenek8cf47df2011-11-17 23:01:24 +0000330 LangOptions::GCMode OrigGCMode = origCI.getLangOpts()->getGC();
Argyrios Kyrtzidisd208ef92011-11-04 15:58:08 +0000331
John McCalld70fb982011-06-15 23:25:17 +0000332 // Make sure checking is successful first.
333 CompilerInvocation CInvokForCheck(origCI);
Douglas Gregor32fbe312012-01-20 16:28:04 +0000334 if (arcmt::checkForManualIssues(CInvokForCheck, Input, DiagClient,
Argyrios Kyrtzidisd5713632011-07-19 17:20:03 +0000335 emitPremigrationARCErrors, plistOut))
John McCalld70fb982011-06-15 23:25:17 +0000336 return true;
337
338 CompilerInvocation CInvok(origCI);
339 CInvok.getFrontendOpts().Inputs.clear();
Douglas Gregor32fbe312012-01-20 16:28:04 +0000340 CInvok.getFrontendOpts().Inputs.push_back(Input);
John McCalld70fb982011-06-15 23:25:17 +0000341
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000342 MigrationProcess migration(CInvok, DiagClient, outputDir);
Fariborz Jahanian48fd81b2012-01-26 20:57:58 +0000343 bool NoFinalizeRemoval = origCI.getMigratorOpts().NoFinalizeRemoval;
John McCalld70fb982011-06-15 23:25:17 +0000344
Fariborz Jahanian48fd81b2012-01-26 20:57:58 +0000345 std::vector<TransformFn> transforms = arcmt::getAllTransformations(OrigGCMode,
346 NoFinalizeRemoval);
John McCalld70fb982011-06-15 23:25:17 +0000347 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
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000354 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
355 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Douglas Gregor811db4e2012-10-23 22:26:28 +0000356 new DiagnosticsEngine(DiagID, &origCI.getDiagnosticOpts(),
357 DiagClient, /*ShouldOwnClient=*/false));
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000358
359 if (outputDir.empty()) {
Ted Kremenek8cf47df2011-11-17 23:01:24 +0000360 origCI.getLangOpts()->ObjCAutoRefCount = true;
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000361 return migration.getRemapper().overwriteOriginal(*Diags);
Argyrios Kyrtzidise2e40b42011-07-14 00:17:54 +0000362 } 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.
Ted Kremenek8cf47df2011-11-17 23:01:24 +0000365 origCI.getLangOpts()->ObjCAutoRefCount = false;
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000366 return migration.getRemapper().flushToDisk(outputDir, *Diags);
Argyrios Kyrtzidise2e40b42011-07-14 00:17:54 +0000367 }
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000368}
369
370bool arcmt::applyTransformations(CompilerInvocation &origCI,
Douglas Gregor32fbe312012-01-20 16:28:04 +0000371 const FrontendInputFile &Input,
David Blaikiee2eefae2011-09-25 23:39:51 +0000372 DiagnosticConsumer *DiagClient) {
Douglas Gregor32fbe312012-01-20 16:28:04 +0000373 return applyTransforms(origCI, Input, DiagClient,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000374 StringRef(), false, StringRef());
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000375}
376
377bool arcmt::migrateWithTemporaryFiles(CompilerInvocation &origCI,
Douglas Gregor32fbe312012-01-20 16:28:04 +0000378 const FrontendInputFile &Input,
David Blaikiee2eefae2011-09-25 23:39:51 +0000379 DiagnosticConsumer *DiagClient,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000380 StringRef outputDir,
Argyrios Kyrtzidisd5713632011-07-19 17:20:03 +0000381 bool emitPremigrationARCErrors,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000382 StringRef plistOut) {
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000383 assert(!outputDir.empty() && "Expected output directory path");
Douglas Gregor32fbe312012-01-20 16:28:04 +0000384 return applyTransforms(origCI, Input, DiagClient,
Argyrios Kyrtzidisd5713632011-07-19 17:20:03 +0000385 outputDir, emitPremigrationARCErrors, plistOut);
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000386}
387
388bool arcmt::getFileRemappings(std::vector<std::pair<std::string,std::string> > &
389 remap,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000390 StringRef outputDir,
David Blaikiee2eefae2011-09-25 23:39:51 +0000391 DiagnosticConsumer *DiagClient) {
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000392 assert(!outputDir.empty());
John McCalld70fb982011-06-15 23:25:17 +0000393
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000394 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
395 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Douglas Gregor811db4e2012-10-23 22:26:28 +0000396 new DiagnosticsEngine(DiagID, new DiagnosticOptions,
397 DiagClient, /*ShouldOwnClient=*/false));
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000398
399 FileRemapper remapper;
400 bool err = remapper.initFromDisk(outputDir, *Diags,
401 /*ignoreIfFilesChanged=*/true);
402 if (err)
403 return true;
404
Ted Kremenekf7639e12012-03-06 20:06:33 +0000405 PreprocessorOptions PPOpts;
406 remapper.applyMappings(PPOpts);
407 remap = PPOpts.RemappedFiles;
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000408
409 return false;
John McCalld70fb982011-06-15 23:25:17 +0000410}
411
Ted Kremenekf7639e12012-03-06 20:06:33 +0000412bool 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(
Douglas Gregor811db4e2012-10-23 22:26:28 +0000421 new DiagnosticsEngine(DiagID, new DiagnosticOptions,
422 DiagClient, /*ShouldOwnClient=*/false));
Ted Kremenekf7639e12012-03-06 20:06:33 +0000423
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
John McCalld70fb982011-06-15 23:25:17 +0000451//===----------------------------------------------------------------------===//
John McCalld70fb982011-06-15 23:25:17 +0000452// 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
Argyrios Kyrtzidis85a14bb2011-08-18 01:05:45 +0000464 virtual void MacroExpands(const Token &MacroNameTok, const MacroInfo *MI,
465 SourceRange Range) {
John McCalld70fb982011-06-15 23:25:17 +0000466 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,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000479 StringRef InFile) {
John McCalld70fb982011-06-15 23:25:17 +0000480 CI.getPreprocessor().addPPCallbacks(
481 new ARCMTMacroTrackerPPCallbacks(ARCMTMacroLocs));
482 return new ASTConsumer();
483 }
484};
485
486class RewritesApplicator : public TransformActions::RewriteReceiver {
487 Rewriter &rewriter;
John McCalld70fb982011-06-15 23:25:17 +0000488 MigrationProcess::RewriteListener *Listener;
489
490public:
491 RewritesApplicator(Rewriter &rewriter, ASTContext &ctx,
492 MigrationProcess::RewriteListener *listener)
Benjamin Kramerd1d76b22012-06-06 17:32:50 +0000493 : rewriter(rewriter), Listener(listener) {
John McCalld70fb982011-06-15 23:25:17 +0000494 if (Listener)
495 Listener->start(ctx);
496 }
497 ~RewritesApplicator() {
498 if (Listener)
499 Listener->finish();
500 }
501
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000502 virtual void insert(SourceLocation loc, StringRef text) {
John McCalld70fb982011-06-15 23:25:17 +0000503 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
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000531MigrationProcess::MigrationProcess(const CompilerInvocation &CI,
David Blaikiee2eefae2011-09-25 23:39:51 +0000532 DiagnosticConsumer *diagClient,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000533 StringRef outputDir)
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000534 : OrigCI(CI), DiagClient(diagClient) {
535 if (!outputDir.empty()) {
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000536 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
537 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Douglas Gregor811db4e2012-10-23 22:26:28 +0000538 new DiagnosticsEngine(DiagID, &CI.getDiagnosticOpts(),
539 DiagClient, /*ShouldOwnClient=*/false));
Argyrios Kyrtzidis7fbd97f2011-07-09 20:00:58 +0000540 Remapper.initFromDisk(outputDir, *Diags, /*ignoreIfFilesChanges=*/true);
541 }
542}
543
John McCalld70fb982011-06-15 23:25:17 +0000544bool MigrationProcess::applyTransform(TransformFn trans,
545 RewriteListener *listener) {
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000546 OwningPtr<CompilerInvocation> CInvok;
John McCalld70fb982011-06-15 23:25:17 +0000547 CInvok.reset(createInvocationForMigration(OrigCI));
548 CInvok->getDiagnosticOpts().IgnoreWarnings = true;
549
Ted Kremenekf7639e12012-03-06 20:06:33 +0000550 Remapper.applyMappings(CInvok->getPreprocessorOpts());
John McCalld70fb982011-06-15 23:25:17 +0000551
552 CapturedDiagList capturedDiags;
553 std::vector<SourceLocation> ARCMTMacroLocs;
554
555 assert(DiagClient);
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000556 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
557 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
Douglas Gregor811db4e2012-10-23 22:26:28 +0000558 new DiagnosticsEngine(DiagID, new DiagnosticOptions,
559 DiagClient, /*ShouldOwnClient=*/false));
John McCalld70fb982011-06-15 23:25:17 +0000560
561 // Filter of all diagnostics.
Jordan Roseb00073d2012-08-10 01:06:16 +0000562 CaptureDiagnosticConsumer errRec(*Diags, *DiagClient, capturedDiags);
John McCalld70fb982011-06-15 23:25:17 +0000563 Diags->setClient(&errRec, /*ShouldOwnClient=*/false);
564
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000565 OwningPtr<ARCMTMacroTrackerAction> ASTAction;
John McCalld70fb982011-06-15 23:25:17 +0000566 ASTAction.reset(new ARCMTMacroTrackerAction(ARCMTMacroLocs));
567
Dylan Noblesmithe2778992012-02-05 02:12:40 +0000568 OwningPtr<ASTUnit> Unit(
John McCalld70fb982011-06-15 23:25:17 +0000569 ASTUnit::LoadFromCompilerInvocationAction(CInvok.take(), Diags,
570 ASTAction.get()));
Jordan Roseb00073d2012-08-10 01:06:16 +0000571 if (!Unit) {
572 errRec.FinishCapture();
John McCalld70fb982011-06-15 23:25:17 +0000573 return true;
Jordan Roseb00073d2012-08-10 01:06:16 +0000574 }
John McCalld70fb982011-06-15 23:25:17 +0000575 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();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000584 DiagClient->BeginSourceFile(Ctx.getLangOpts(), &Unit->getPreprocessor());
John McCalld70fb982011-06-15 23:25:17 +0000585 capturedDiags.reportDiagnostics(*Diags);
586 DiagClient->EndSourceFile();
Jordan Roseb00073d2012-08-10 01:06:16 +0000587 errRec.FinishCapture();
John McCalld70fb982011-06-15 23:25:17 +0000588 return true;
589 }
590
591 // After parsing of source files ended, we want to reuse the
592 // diagnostics objects to emit further diagnostics.
David Blaikiee2eefae2011-09-25 23:39:51 +0000593 // We call BeginSourceFile because DiagnosticConsumer requires that
John McCalld70fb982011-06-15 23:25:17 +0000594 // diagnostics with source range information are emitted only in between
595 // BeginSourceFile() and EndSourceFile().
David Blaikiebbafb8a2012-03-11 07:00:24 +0000596 DiagClient->BeginSourceFile(Ctx.getLangOpts(), &Unit->getPreprocessor());
John McCalld70fb982011-06-15 23:25:17 +0000597
David Blaikiebbafb8a2012-03-11 07:00:24 +0000598 Rewriter rewriter(Ctx.getSourceManager(), Ctx.getLangOpts());
John McCalld70fb982011-06-15 23:25:17 +0000599 TransformActions TA(*Diags, capturedDiags, Ctx, Unit->getPreprocessor());
Ted Kremenek8cf47df2011-11-17 23:01:24 +0000600 MigrationPass pass(Ctx, OrigCI.getLangOpts()->getGC(),
Argyrios Kyrtzidisd208ef92011-11-04 15:58:08 +0000601 Unit->getSema(), TA, ARCMTMacroLocs);
John McCalld70fb982011-06-15 23:25:17 +0000602
603 trans(pass);
604
605 {
606 RewritesApplicator applicator(rewriter, Ctx, listener);
607 TA.applyRewrites(applicator);
608 }
609
610 DiagClient->EndSourceFile();
Jordan Roseb00073d2012-08-10 01:06:16 +0000611 errRec.FinishCapture();
John McCalld70fb982011-06-15 23:25:17 +0000612
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";
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000624 SmallString<512> newText;
John McCalld70fb982011-06-15 23:25:17 +0000625 llvm::raw_svector_ostream vecOS(newText);
626 buf.write(vecOS);
627 vecOS.flush();
628 llvm::MemoryBuffer *memBuf = llvm::MemoryBuffer::getMemBufferCopy(
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000629 StringRef(newText.data(), newText.size()), newFname);
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000630 SmallString<64> filePath(file->getName());
John McCalld70fb982011-06-15 23:25:17 +0000631 Unit->getFileManager().FixupRelativePath(filePath);
632 Remapper.remap(filePath.str(), memBuf);
633 }
634
635 return false;
636}