blob: dd9461b33d1c454b46e86c4eb26b6a93c6ed551c [file] [log] [blame]
John McCall8f0e8d22011-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"
11#include "clang/Frontend/ASTUnit.h"
12#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor1f6b2b52012-01-20 16:28:04 +000013#include "clang/Frontend/FrontendAction.h"
Argyrios Kyrtzidis7ee20492011-07-19 17:20:03 +000014#include "clang/Frontend/TextDiagnosticPrinter.h"
John McCall8f0e8d22011-06-15 23:25:17 +000015#include "clang/Frontend/Utils.h"
16#include "clang/AST/ASTConsumer.h"
17#include "clang/Rewrite/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"
John McCall8f0e8d22011-06-15 23:25:17 +000023using namespace clang;
24using namespace arcmt;
John McCall8f0e8d22011-06-15 23:25:17 +000025
Chris Lattner2d3ba4f2011-07-23 17:14:25 +000026bool CapturedDiagList::clearDiagnostic(ArrayRef<unsigned> IDs,
John McCall8f0e8d22011-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 Blaikied6471f72011-09-25 23:23:43 +000042 while (I != List.end() && I->getLevel() == DiagnosticsEngine::Note)
John McCall8f0e8d22011-06-15 23:25:17 +000043 ++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
Chris Lattner2d3ba4f2011-07-23 17:14:25 +000055bool CapturedDiagList::hasDiagnostic(ArrayRef<unsigned> IDs,
Argyrios Kyrtzidis60a5e3f2011-06-18 00:53:34 +000056 SourceRange range) const {
John McCall8f0e8d22011-06-15 23:25:17 +000057 if (range.isInvalid())
58 return false;
59
Argyrios Kyrtzidis60a5e3f2011-06-18 00:53:34 +000060 ListTy::const_iterator I = List.begin();
John McCall8f0e8d22011-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 Blaikied6471f72011-09-25 23:23:43 +000077void CapturedDiagList::reportDiagnostics(DiagnosticsEngine &Diags) const {
Argyrios Kyrtzidis60a5e3f2011-06-18 00:53:34 +000078 for (ListTy::const_iterator I = List.begin(), E = List.end(); I != E; ++I)
John McCall8f0e8d22011-06-15 23:25:17 +000079 Diags.Report(*I);
80}
81
Argyrios Kyrtzidise665d692011-06-18 00:53:41 +000082bool CapturedDiagList::hasErrors() const {
83 for (ListTy::const_iterator I = List.begin(), E = List.end(); I != E; ++I)
David Blaikied6471f72011-09-25 23:23:43 +000084 if (I->getLevel() >= DiagnosticsEngine::Error)
Argyrios Kyrtzidise665d692011-06-18 00:53:41 +000085 return true;
86
87 return false;
88}
89
John McCall8f0e8d22011-06-15 23:25:17 +000090namespace {
91
David Blaikieaee37ba2011-09-25 23:54:33 +000092class CaptureDiagnosticConsumer : public DiagnosticConsumer {
David Blaikied6471f72011-09-25 23:23:43 +000093 DiagnosticsEngine &Diags;
John McCall8f0e8d22011-06-15 23:25:17 +000094 CapturedDiagList &CapturedDiags;
95public:
David Blaikieaee37ba2011-09-25 23:54:33 +000096 CaptureDiagnosticConsumer(DiagnosticsEngine &diags,
Douglas Gregoraee526e2011-09-29 00:38:00 +000097 CapturedDiagList &capturedDiags)
John McCall8f0e8d22011-06-15 23:25:17 +000098 : Diags(diags), CapturedDiags(capturedDiags) { }
99
David Blaikied6471f72011-09-25 23:23:43 +0000100 virtual void HandleDiagnostic(DiagnosticsEngine::Level level,
David Blaikie40847cf2011-09-26 01:18:08 +0000101 const Diagnostic &Info) {
Ted Kremenekafdc21a2011-10-20 05:07:47 +0000102 if (DiagnosticIDs::isARCDiagnostic(Info.getID()) ||
David Blaikied6471f72011-09-25 23:23:43 +0000103 level >= DiagnosticsEngine::Error || level == DiagnosticsEngine::Note) {
John McCall8f0e8d22011-06-15 23:25:17 +0000104 CapturedDiags.push_back(StoredDiagnostic(level, Info));
105 return;
106 }
107
108 // Non-ARC warnings are ignored.
109 Diags.setLastDiagnosticIgnored();
110 }
Douglas Gregoraee526e2011-09-29 00:38:00 +0000111
112 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
113 // Just drop any diagnostics that come from cloned consumers; they'll
114 // have different source managers anyway.
115 return new IgnoringDiagConsumer();
116 }
John McCall8f0e8d22011-06-15 23:25:17 +0000117};
118
119} // end anonymous namespace
120
Argyrios Kyrtzidisdceb11f2011-10-18 00:22:49 +0000121static inline StringRef SimulatorVersionDefineName() {
122 return "__IPHONE_OS_VERSION_MIN_REQUIRED=";
123}
124
125/// \brief Parse the simulator version define:
126/// __IPHONE_OS_VERSION_MIN_REQUIRED=([0-9])([0-9][0-9])([0-9][0-9])
127// and return the grouped values as integers, e.g:
128// __IPHONE_OS_VERSION_MIN_REQUIRED=40201
129// will return Major=4, Minor=2, Micro=1.
130static bool GetVersionFromSimulatorDefine(StringRef define,
131 unsigned &Major, unsigned &Minor,
132 unsigned &Micro) {
133 assert(define.startswith(SimulatorVersionDefineName()));
134 StringRef name, version;
135 llvm::tie(name, version) = define.split('=');
136 if (version.empty())
137 return false;
138 std::string verstr = version.str();
139 char *end;
140 unsigned num = (unsigned) strtol(verstr.c_str(), &end, 10);
141 if (*end != '\0')
142 return false;
143 Major = num / 10000;
144 num = num % 10000;
145 Minor = num / 100;
146 Micro = num % 100;
147 return true;
148}
149
Argyrios Kyrtzidis9c479732011-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.
154
Argyrios Kyrtzidisdceb11f2011-10-18 00:22:49 +0000155 for (unsigned i = 0, e = origCI.getPreprocessorOpts().Macros.size();
156 i != e; ++i) {
157 StringRef define = origCI.getPreprocessorOpts().Macros[i].first;
158 bool isUndef = origCI.getPreprocessorOpts().Macros[i].second;
159 if (isUndef)
160 continue;
161 if (!define.startswith(SimulatorVersionDefineName()))
162 continue;
163 unsigned Major = 0, Minor = 0, Micro = 0;
164 if (GetVersionFromSimulatorDefine(define, Major, Minor, Micro) &&
165 Major < 10 && Minor < 100 && Micro < 100)
166 return Major >= 5;
167 }
168
Argyrios Kyrtzidis9c479732011-06-20 19:59:52 +0000169 llvm::Triple triple(origCI.getTargetOpts().Triple);
170
171 if (triple.getOS() == llvm::Triple::IOS)
172 return triple.getOSMajorVersion() >= 5;
173
174 if (triple.getOS() == llvm::Triple::Darwin)
175 return triple.getOSMajorVersion() >= 11;
176
177 if (triple.getOS() == llvm::Triple::MacOSX) {
178 unsigned Major, Minor, Micro;
179 triple.getOSVersion(Major, Minor, Micro);
180 return Major > 10 || (Major == 10 && Minor >= 7);
181 }
182
183 return false;
184}
185
Benjamin Kramer39997fc2011-08-02 04:50:49 +0000186static CompilerInvocation *
187createInvocationForMigration(CompilerInvocation &origCI) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000188 OwningPtr<CompilerInvocation> CInvok;
John McCall8f0e8d22011-06-15 23:25:17 +0000189 CInvok.reset(new CompilerInvocation(origCI));
190 CInvok->getPreprocessorOpts().ImplicitPCHInclude = std::string();
191 CInvok->getPreprocessorOpts().ImplicitPTHInclude = std::string();
192 std::string define = getARCMTMacroName();
193 define += '=';
194 CInvok->getPreprocessorOpts().addMacroDef(define);
Ted Kremenekd3b74d92011-11-17 23:01:24 +0000195 CInvok->getLangOpts()->ObjCAutoRefCount = true;
196 CInvok->getLangOpts()->setGC(LangOptions::NonGC);
John McCall8f0e8d22011-06-15 23:25:17 +0000197 CInvok->getDiagnosticOpts().ErrorLimit = 0;
Argyrios Kyrtzidis19129822012-06-20 01:46:26 +0000198 CInvok->getDiagnosticOpts().PedanticErrors = 0;
Argyrios Kyrtzidisffe76dd2012-06-20 01:10:40 +0000199
200 // Ignore -Werror flags when migrating.
201 std::vector<std::string> WarnOpts;
202 for (std::vector<std::string>::iterator
203 I = CInvok->getDiagnosticOpts().Warnings.begin(),
204 E = CInvok->getDiagnosticOpts().Warnings.end(); I != E; ++I) {
205 if (!StringRef(*I).startswith("error"))
206 WarnOpts.push_back(*I);
207 }
208 WarnOpts.push_back("error=arc-unsafe-retained-assign");
Argyrios Kyrtzidis19129822012-06-20 01:46:26 +0000209 CInvok->getDiagnosticOpts().Warnings = llvm_move(WarnOpts);
Argyrios Kyrtzidisffe76dd2012-06-20 01:10:40 +0000210
Ted Kremenekd3b74d92011-11-17 23:01:24 +0000211 CInvok->getLangOpts()->ObjCRuntimeHasWeak = HasARCRuntime(origCI);
John McCall8f0e8d22011-06-15 23:25:17 +0000212
213 return CInvok.take();
214}
215
Benjamin Kramer39997fc2011-08-02 04:50:49 +0000216static void emitPremigrationErrors(const CapturedDiagList &arcDiags,
217 const DiagnosticOptions &diagOpts,
218 Preprocessor &PP) {
Argyrios Kyrtzidis7ee20492011-07-19 17:20:03 +0000219 TextDiagnosticPrinter printer(llvm::errs(), diagOpts);
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000220 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
221 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
David Blaikied6471f72011-09-25 23:23:43 +0000222 new DiagnosticsEngine(DiagID, &printer, /*ShouldOwnClient=*/false));
Argyrios Kyrtzidis7ee20492011-07-19 17:20:03 +0000223 Diags->setSourceManager(&PP.getSourceManager());
224
David Blaikie4e4d0842012-03-11 07:00:24 +0000225 printer.BeginSourceFile(PP.getLangOpts(), &PP);
Argyrios Kyrtzidis7ee20492011-07-19 17:20:03 +0000226 arcDiags.reportDiagnostics(*Diags);
227 printer.EndSourceFile();
228}
229
John McCall8f0e8d22011-06-15 23:25:17 +0000230//===----------------------------------------------------------------------===//
231// checkForManualIssues.
232//===----------------------------------------------------------------------===//
233
234bool arcmt::checkForManualIssues(CompilerInvocation &origCI,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +0000235 const FrontendInputFile &Input,
David Blaikie78ad0b92011-09-25 23:39:51 +0000236 DiagnosticConsumer *DiagClient,
Argyrios Kyrtzidis7ee20492011-07-19 17:20:03 +0000237 bool emitPremigrationARCErrors,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000238 StringRef plistOut) {
Ted Kremenekd3b74d92011-11-17 23:01:24 +0000239 if (!origCI.getLangOpts()->ObjC1)
John McCall8f0e8d22011-06-15 23:25:17 +0000240 return false;
241
Ted Kremenekd3b74d92011-11-17 23:01:24 +0000242 LangOptions::GCMode OrigGCMode = origCI.getLangOpts()->getGC();
Fariborz Jahanianb5c6bab2012-01-25 00:20:29 +0000243 bool NoNSAllocReallocError = origCI.getMigratorOpts().NoNSAllocReallocError;
Fariborz Jahanian26f0e4e2012-01-26 00:08:04 +0000244 bool NoFinalizeRemoval = origCI.getMigratorOpts().NoFinalizeRemoval;
Argyrios Kyrtzidise0ac7452011-11-04 15:58:08 +0000245
Fariborz Jahanianbbdfad52012-01-26 20:57:58 +0000246 std::vector<TransformFn> transforms = arcmt::getAllTransformations(OrigGCMode,
247 NoFinalizeRemoval);
John McCall8f0e8d22011-06-15 23:25:17 +0000248 assert(!transforms.empty());
249
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000250 OwningPtr<CompilerInvocation> CInvok;
John McCall8f0e8d22011-06-15 23:25:17 +0000251 CInvok.reset(createInvocationForMigration(origCI));
252 CInvok->getFrontendOpts().Inputs.clear();
Douglas Gregor1f6b2b52012-01-20 16:28:04 +0000253 CInvok->getFrontendOpts().Inputs.push_back(Input);
John McCall8f0e8d22011-06-15 23:25:17 +0000254
255 CapturedDiagList capturedDiags;
256
257 assert(DiagClient);
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000258 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
259 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
David Blaikied6471f72011-09-25 23:23:43 +0000260 new DiagnosticsEngine(DiagID, DiagClient, /*ShouldOwnClient=*/false));
John McCall8f0e8d22011-06-15 23:25:17 +0000261
262 // Filter of all diagnostics.
David Blaikieaee37ba2011-09-25 23:54:33 +0000263 CaptureDiagnosticConsumer errRec(*Diags, capturedDiags);
John McCall8f0e8d22011-06-15 23:25:17 +0000264 Diags->setClient(&errRec, /*ShouldOwnClient=*/false);
265
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000266 OwningPtr<ASTUnit> Unit(
John McCall8f0e8d22011-06-15 23:25:17 +0000267 ASTUnit::LoadFromCompilerInvocationAction(CInvok.take(), Diags));
268 if (!Unit)
269 return true;
270
271 // Don't filter diagnostics anymore.
272 Diags->setClient(DiagClient, /*ShouldOwnClient=*/false);
273
274 ASTContext &Ctx = Unit->getASTContext();
275
276 if (Diags->hasFatalErrorOccurred()) {
277 Diags->Reset();
David Blaikie4e4d0842012-03-11 07:00:24 +0000278 DiagClient->BeginSourceFile(Ctx.getLangOpts(), &Unit->getPreprocessor());
John McCall8f0e8d22011-06-15 23:25:17 +0000279 capturedDiags.reportDiagnostics(*Diags);
280 DiagClient->EndSourceFile();
281 return true;
282 }
283
Argyrios Kyrtzidis7ee20492011-07-19 17:20:03 +0000284 if (emitPremigrationARCErrors)
285 emitPremigrationErrors(capturedDiags, origCI.getDiagnosticOpts(),
286 Unit->getPreprocessor());
287 if (!plistOut.empty()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000288 SmallVector<StoredDiagnostic, 8> arcDiags;
Argyrios Kyrtzidis7ee20492011-07-19 17:20:03 +0000289 for (CapturedDiagList::iterator
290 I = capturedDiags.begin(), E = capturedDiags.end(); I != E; ++I)
291 arcDiags.push_back(*I);
292 writeARCDiagsToPlist(plistOut, arcDiags,
David Blaikie4e4d0842012-03-11 07:00:24 +0000293 Ctx.getSourceManager(), Ctx.getLangOpts());
Argyrios Kyrtzidis7ee20492011-07-19 17:20:03 +0000294 }
295
John McCall8f0e8d22011-06-15 23:25:17 +0000296 // After parsing of source files ended, we want to reuse the
297 // diagnostics objects to emit further diagnostics.
David Blaikie78ad0b92011-09-25 23:39:51 +0000298 // We call BeginSourceFile because DiagnosticConsumer requires that
John McCall8f0e8d22011-06-15 23:25:17 +0000299 // diagnostics with source range information are emitted only in between
300 // BeginSourceFile() and EndSourceFile().
David Blaikie4e4d0842012-03-11 07:00:24 +0000301 DiagClient->BeginSourceFile(Ctx.getLangOpts(), &Unit->getPreprocessor());
John McCall8f0e8d22011-06-15 23:25:17 +0000302
303 // No macros will be added since we are just checking and we won't modify
304 // source code.
305 std::vector<SourceLocation> ARCMTMacroLocs;
306
307 TransformActions testAct(*Diags, capturedDiags, Ctx, Unit->getPreprocessor());
Argyrios Kyrtzidise0ac7452011-11-04 15:58:08 +0000308 MigrationPass pass(Ctx, OrigGCMode, Unit->getSema(), testAct, ARCMTMacroLocs);
Fariborz Jahanianb5c6bab2012-01-25 00:20:29 +0000309 pass.setNSAllocReallocError(NoNSAllocReallocError);
Fariborz Jahanian26f0e4e2012-01-26 00:08:04 +0000310 pass.setNoFinalizeRemoval(NoFinalizeRemoval);
John McCall8f0e8d22011-06-15 23:25:17 +0000311
312 for (unsigned i=0, e = transforms.size(); i != e; ++i)
313 transforms[i](pass);
314
315 capturedDiags.reportDiagnostics(*Diags);
316
317 DiagClient->EndSourceFile();
318
Argyrios Kyrtzidisa944b122011-07-14 00:17:54 +0000319 // If we are migrating code that gets the '-fobjc-arc' flag, make sure
320 // to remove it so that we don't get errors from normal compilation.
Ted Kremenekd3b74d92011-11-17 23:01:24 +0000321 origCI.getLangOpts()->ObjCAutoRefCount = false;
Argyrios Kyrtzidisa944b122011-07-14 00:17:54 +0000322
Argyrios Kyrtzidisfd103982011-07-18 07:44:45 +0000323 return capturedDiags.hasErrors() || testAct.hasReportedErrors();
John McCall8f0e8d22011-06-15 23:25:17 +0000324}
325
326//===----------------------------------------------------------------------===//
327// applyTransformations.
328//===----------------------------------------------------------------------===//
329
Argyrios Kyrtzidis69325d52011-07-09 20:00:58 +0000330static bool applyTransforms(CompilerInvocation &origCI,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +0000331 const FrontendInputFile &Input,
David Blaikie78ad0b92011-09-25 23:39:51 +0000332 DiagnosticConsumer *DiagClient,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000333 StringRef outputDir,
Argyrios Kyrtzidis7ee20492011-07-19 17:20:03 +0000334 bool emitPremigrationARCErrors,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000335 StringRef plistOut) {
Ted Kremenekd3b74d92011-11-17 23:01:24 +0000336 if (!origCI.getLangOpts()->ObjC1)
John McCall8f0e8d22011-06-15 23:25:17 +0000337 return false;
338
Ted Kremenekd3b74d92011-11-17 23:01:24 +0000339 LangOptions::GCMode OrigGCMode = origCI.getLangOpts()->getGC();
Argyrios Kyrtzidise0ac7452011-11-04 15:58:08 +0000340
John McCall8f0e8d22011-06-15 23:25:17 +0000341 // Make sure checking is successful first.
342 CompilerInvocation CInvokForCheck(origCI);
Douglas Gregor1f6b2b52012-01-20 16:28:04 +0000343 if (arcmt::checkForManualIssues(CInvokForCheck, Input, DiagClient,
Argyrios Kyrtzidis7ee20492011-07-19 17:20:03 +0000344 emitPremigrationARCErrors, plistOut))
John McCall8f0e8d22011-06-15 23:25:17 +0000345 return true;
346
347 CompilerInvocation CInvok(origCI);
348 CInvok.getFrontendOpts().Inputs.clear();
Douglas Gregor1f6b2b52012-01-20 16:28:04 +0000349 CInvok.getFrontendOpts().Inputs.push_back(Input);
John McCall8f0e8d22011-06-15 23:25:17 +0000350
Argyrios Kyrtzidis69325d52011-07-09 20:00:58 +0000351 MigrationProcess migration(CInvok, DiagClient, outputDir);
Fariborz Jahanianbbdfad52012-01-26 20:57:58 +0000352 bool NoFinalizeRemoval = origCI.getMigratorOpts().NoFinalizeRemoval;
John McCall8f0e8d22011-06-15 23:25:17 +0000353
Fariborz Jahanianbbdfad52012-01-26 20:57:58 +0000354 std::vector<TransformFn> transforms = arcmt::getAllTransformations(OrigGCMode,
355 NoFinalizeRemoval);
John McCall8f0e8d22011-06-15 23:25:17 +0000356 assert(!transforms.empty());
357
358 for (unsigned i=0, e = transforms.size(); i != e; ++i) {
359 bool err = migration.applyTransform(transforms[i]);
360 if (err) return true;
361 }
362
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000363 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
364 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
David Blaikied6471f72011-09-25 23:23:43 +0000365 new DiagnosticsEngine(DiagID, DiagClient, /*ShouldOwnClient=*/false));
Argyrios Kyrtzidis69325d52011-07-09 20:00:58 +0000366
367 if (outputDir.empty()) {
Ted Kremenekd3b74d92011-11-17 23:01:24 +0000368 origCI.getLangOpts()->ObjCAutoRefCount = true;
Argyrios Kyrtzidis69325d52011-07-09 20:00:58 +0000369 return migration.getRemapper().overwriteOriginal(*Diags);
Argyrios Kyrtzidisa944b122011-07-14 00:17:54 +0000370 } else {
371 // If we are migrating code that gets the '-fobjc-arc' flag, make sure
372 // to remove it so that we don't get errors from normal compilation.
Ted Kremenekd3b74d92011-11-17 23:01:24 +0000373 origCI.getLangOpts()->ObjCAutoRefCount = false;
Argyrios Kyrtzidis69325d52011-07-09 20:00:58 +0000374 return migration.getRemapper().flushToDisk(outputDir, *Diags);
Argyrios Kyrtzidisa944b122011-07-14 00:17:54 +0000375 }
Argyrios Kyrtzidis69325d52011-07-09 20:00:58 +0000376}
377
378bool arcmt::applyTransformations(CompilerInvocation &origCI,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +0000379 const FrontendInputFile &Input,
David Blaikie78ad0b92011-09-25 23:39:51 +0000380 DiagnosticConsumer *DiagClient) {
Douglas Gregor1f6b2b52012-01-20 16:28:04 +0000381 return applyTransforms(origCI, Input, DiagClient,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000382 StringRef(), false, StringRef());
Argyrios Kyrtzidis69325d52011-07-09 20:00:58 +0000383}
384
385bool arcmt::migrateWithTemporaryFiles(CompilerInvocation &origCI,
Douglas Gregor1f6b2b52012-01-20 16:28:04 +0000386 const FrontendInputFile &Input,
David Blaikie78ad0b92011-09-25 23:39:51 +0000387 DiagnosticConsumer *DiagClient,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000388 StringRef outputDir,
Argyrios Kyrtzidis7ee20492011-07-19 17:20:03 +0000389 bool emitPremigrationARCErrors,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000390 StringRef plistOut) {
Argyrios Kyrtzidis69325d52011-07-09 20:00:58 +0000391 assert(!outputDir.empty() && "Expected output directory path");
Douglas Gregor1f6b2b52012-01-20 16:28:04 +0000392 return applyTransforms(origCI, Input, DiagClient,
Argyrios Kyrtzidis7ee20492011-07-19 17:20:03 +0000393 outputDir, emitPremigrationARCErrors, plistOut);
Argyrios Kyrtzidis69325d52011-07-09 20:00:58 +0000394}
395
396bool arcmt::getFileRemappings(std::vector<std::pair<std::string,std::string> > &
397 remap,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000398 StringRef outputDir,
David Blaikie78ad0b92011-09-25 23:39:51 +0000399 DiagnosticConsumer *DiagClient) {
Argyrios Kyrtzidis69325d52011-07-09 20:00:58 +0000400 assert(!outputDir.empty());
John McCall8f0e8d22011-06-15 23:25:17 +0000401
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000402 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
403 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
David Blaikied6471f72011-09-25 23:23:43 +0000404 new DiagnosticsEngine(DiagID, DiagClient, /*ShouldOwnClient=*/false));
Argyrios Kyrtzidis69325d52011-07-09 20:00:58 +0000405
406 FileRemapper remapper;
407 bool err = remapper.initFromDisk(outputDir, *Diags,
408 /*ignoreIfFilesChanged=*/true);
409 if (err)
410 return true;
411
Ted Kremenek30660a82012-03-06 20:06:33 +0000412 PreprocessorOptions PPOpts;
413 remapper.applyMappings(PPOpts);
414 remap = PPOpts.RemappedFiles;
Argyrios Kyrtzidis69325d52011-07-09 20:00:58 +0000415
416 return false;
John McCall8f0e8d22011-06-15 23:25:17 +0000417}
418
Ted Kremenek30660a82012-03-06 20:06:33 +0000419bool arcmt::getFileRemappingsFromFileList(
420 std::vector<std::pair<std::string,std::string> > &remap,
421 ArrayRef<StringRef> remapFiles,
422 DiagnosticConsumer *DiagClient) {
423 bool hasErrorOccurred = false;
424 llvm::StringMap<bool> Uniquer;
425
426 llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
427 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
428 new DiagnosticsEngine(DiagID, DiagClient, /*ShouldOwnClient=*/false));
429
430 for (ArrayRef<StringRef>::iterator
431 I = remapFiles.begin(), E = remapFiles.end(); I != E; ++I) {
432 StringRef file = *I;
433
434 FileRemapper remapper;
435 bool err = remapper.initFromFile(file, *Diags,
436 /*ignoreIfFilesChanged=*/true);
437 hasErrorOccurred = hasErrorOccurred || err;
438 if (err)
439 continue;
440
441 PreprocessorOptions PPOpts;
442 remapper.applyMappings(PPOpts);
443 for (PreprocessorOptions::remapped_file_iterator
444 RI = PPOpts.remapped_file_begin(), RE = PPOpts.remapped_file_end();
445 RI != RE; ++RI) {
446 bool &inserted = Uniquer[RI->first];
447 if (inserted)
448 continue;
449 inserted = true;
450 remap.push_back(*RI);
451 }
452 }
453
454 return hasErrorOccurred;
455}
456
John McCall8f0e8d22011-06-15 23:25:17 +0000457//===----------------------------------------------------------------------===//
John McCall8f0e8d22011-06-15 23:25:17 +0000458// CollectTransformActions.
459//===----------------------------------------------------------------------===//
460
461namespace {
462
463class ARCMTMacroTrackerPPCallbacks : public PPCallbacks {
464 std::vector<SourceLocation> &ARCMTMacroLocs;
465
466public:
467 ARCMTMacroTrackerPPCallbacks(std::vector<SourceLocation> &ARCMTMacroLocs)
468 : ARCMTMacroLocs(ARCMTMacroLocs) { }
469
Argyrios Kyrtzidis1b2d5362011-08-18 01:05:45 +0000470 virtual void MacroExpands(const Token &MacroNameTok, const MacroInfo *MI,
471 SourceRange Range) {
John McCall8f0e8d22011-06-15 23:25:17 +0000472 if (MacroNameTok.getIdentifierInfo()->getName() == getARCMTMacroName())
473 ARCMTMacroLocs.push_back(MacroNameTok.getLocation());
474 }
475};
476
477class ARCMTMacroTrackerAction : public ASTFrontendAction {
478 std::vector<SourceLocation> &ARCMTMacroLocs;
479
480public:
481 ARCMTMacroTrackerAction(std::vector<SourceLocation> &ARCMTMacroLocs)
482 : ARCMTMacroLocs(ARCMTMacroLocs) { }
483
484 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000485 StringRef InFile) {
John McCall8f0e8d22011-06-15 23:25:17 +0000486 CI.getPreprocessor().addPPCallbacks(
487 new ARCMTMacroTrackerPPCallbacks(ARCMTMacroLocs));
488 return new ASTConsumer();
489 }
490};
491
492class RewritesApplicator : public TransformActions::RewriteReceiver {
493 Rewriter &rewriter;
John McCall8f0e8d22011-06-15 23:25:17 +0000494 MigrationProcess::RewriteListener *Listener;
495
496public:
497 RewritesApplicator(Rewriter &rewriter, ASTContext &ctx,
498 MigrationProcess::RewriteListener *listener)
Benjamin Kramerfacde172012-06-06 17:32:50 +0000499 : rewriter(rewriter), Listener(listener) {
John McCall8f0e8d22011-06-15 23:25:17 +0000500 if (Listener)
501 Listener->start(ctx);
502 }
503 ~RewritesApplicator() {
504 if (Listener)
505 Listener->finish();
506 }
507
Chris Lattner5f9e2722011-07-23 10:55:15 +0000508 virtual void insert(SourceLocation loc, StringRef text) {
John McCall8f0e8d22011-06-15 23:25:17 +0000509 bool err = rewriter.InsertText(loc, text, /*InsertAfter=*/true,
510 /*indentNewLines=*/true);
511 if (!err && Listener)
512 Listener->insert(loc, text);
513 }
514
515 virtual void remove(CharSourceRange range) {
516 Rewriter::RewriteOptions removeOpts;
517 removeOpts.IncludeInsertsAtBeginOfRange = false;
518 removeOpts.IncludeInsertsAtEndOfRange = false;
519 removeOpts.RemoveLineIfEmpty = true;
520
521 bool err = rewriter.RemoveText(range, removeOpts);
522 if (!err && Listener)
523 Listener->remove(range);
524 }
525
526 virtual void increaseIndentation(CharSourceRange range,
527 SourceLocation parentIndent) {
528 rewriter.IncreaseIndentation(range, parentIndent);
529 }
530};
531
532} // end anonymous namespace.
533
534/// \brief Anchor for VTable.
535MigrationProcess::RewriteListener::~RewriteListener() { }
536
Argyrios Kyrtzidis69325d52011-07-09 20:00:58 +0000537MigrationProcess::MigrationProcess(const CompilerInvocation &CI,
David Blaikie78ad0b92011-09-25 23:39:51 +0000538 DiagnosticConsumer *diagClient,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000539 StringRef outputDir)
Argyrios Kyrtzidis69325d52011-07-09 20:00:58 +0000540 : OrigCI(CI), DiagClient(diagClient) {
541 if (!outputDir.empty()) {
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000542 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
543 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
David Blaikied6471f72011-09-25 23:23:43 +0000544 new DiagnosticsEngine(DiagID, DiagClient, /*ShouldOwnClient=*/false));
Argyrios Kyrtzidis69325d52011-07-09 20:00:58 +0000545 Remapper.initFromDisk(outputDir, *Diags, /*ignoreIfFilesChanges=*/true);
546 }
547}
548
John McCall8f0e8d22011-06-15 23:25:17 +0000549bool MigrationProcess::applyTransform(TransformFn trans,
550 RewriteListener *listener) {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000551 OwningPtr<CompilerInvocation> CInvok;
John McCall8f0e8d22011-06-15 23:25:17 +0000552 CInvok.reset(createInvocationForMigration(OrigCI));
553 CInvok->getDiagnosticOpts().IgnoreWarnings = true;
554
Ted Kremenek30660a82012-03-06 20:06:33 +0000555 Remapper.applyMappings(CInvok->getPreprocessorOpts());
John McCall8f0e8d22011-06-15 23:25:17 +0000556
557 CapturedDiagList capturedDiags;
558 std::vector<SourceLocation> ARCMTMacroLocs;
559
560 assert(DiagClient);
Dylan Noblesmithc93dc782012-02-20 14:00:23 +0000561 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
562 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
David Blaikied6471f72011-09-25 23:23:43 +0000563 new DiagnosticsEngine(DiagID, DiagClient, /*ShouldOwnClient=*/false));
John McCall8f0e8d22011-06-15 23:25:17 +0000564
565 // Filter of all diagnostics.
David Blaikieaee37ba2011-09-25 23:54:33 +0000566 CaptureDiagnosticConsumer errRec(*Diags, capturedDiags);
John McCall8f0e8d22011-06-15 23:25:17 +0000567 Diags->setClient(&errRec, /*ShouldOwnClient=*/false);
568
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000569 OwningPtr<ARCMTMacroTrackerAction> ASTAction;
John McCall8f0e8d22011-06-15 23:25:17 +0000570 ASTAction.reset(new ARCMTMacroTrackerAction(ARCMTMacroLocs));
571
Dylan Noblesmith6f42b622012-02-05 02:12:40 +0000572 OwningPtr<ASTUnit> Unit(
John McCall8f0e8d22011-06-15 23:25:17 +0000573 ASTUnit::LoadFromCompilerInvocationAction(CInvok.take(), Diags,
574 ASTAction.get()));
575 if (!Unit)
576 return true;
577 Unit->setOwnsRemappedFileBuffers(false); // FileRemapper manages that.
578
579 // Don't filter diagnostics anymore.
580 Diags->setClient(DiagClient, /*ShouldOwnClient=*/false);
581
582 ASTContext &Ctx = Unit->getASTContext();
583
584 if (Diags->hasFatalErrorOccurred()) {
585 Diags->Reset();
David Blaikie4e4d0842012-03-11 07:00:24 +0000586 DiagClient->BeginSourceFile(Ctx.getLangOpts(), &Unit->getPreprocessor());
John McCall8f0e8d22011-06-15 23:25:17 +0000587 capturedDiags.reportDiagnostics(*Diags);
588 DiagClient->EndSourceFile();
589 return true;
590 }
591
592 // After parsing of source files ended, we want to reuse the
593 // diagnostics objects to emit further diagnostics.
David Blaikie78ad0b92011-09-25 23:39:51 +0000594 // We call BeginSourceFile because DiagnosticConsumer requires that
John McCall8f0e8d22011-06-15 23:25:17 +0000595 // diagnostics with source range information are emitted only in between
596 // BeginSourceFile() and EndSourceFile().
David Blaikie4e4d0842012-03-11 07:00:24 +0000597 DiagClient->BeginSourceFile(Ctx.getLangOpts(), &Unit->getPreprocessor());
John McCall8f0e8d22011-06-15 23:25:17 +0000598
David Blaikie4e4d0842012-03-11 07:00:24 +0000599 Rewriter rewriter(Ctx.getSourceManager(), Ctx.getLangOpts());
John McCall8f0e8d22011-06-15 23:25:17 +0000600 TransformActions TA(*Diags, capturedDiags, Ctx, Unit->getPreprocessor());
Ted Kremenekd3b74d92011-11-17 23:01:24 +0000601 MigrationPass pass(Ctx, OrigCI.getLangOpts()->getGC(),
Argyrios Kyrtzidise0ac7452011-11-04 15:58:08 +0000602 Unit->getSema(), TA, ARCMTMacroLocs);
John McCall8f0e8d22011-06-15 23:25:17 +0000603
604 trans(pass);
605
606 {
607 RewritesApplicator applicator(rewriter, Ctx, listener);
608 TA.applyRewrites(applicator);
609 }
610
611 DiagClient->EndSourceFile();
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";
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000624 SmallString<512> newText;
John McCall8f0e8d22011-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 Lattner5f9e2722011-07-23 10:55:15 +0000629 StringRef(newText.data(), newText.size()), newFname);
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000630 SmallString<64> filePath(file->getName());
John McCall8f0e8d22011-06-15 23:25:17 +0000631 Unit->getFileManager().FixupRelativePath(filePath);
632 Remapper.remap(filePath.str(), memBuf);
633 }
634
635 return false;
636}