-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathCompileInstance.cpp
373 lines (312 loc) · 13.3 KB
/
CompileInstance.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
//===--- CompileInstance.cpp ----------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/IDE/CompileInstance.h"
#include "DependencyChecking.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/DiagnosticEngine.h"
#include "swift/AST/Module.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/SourceFile.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/LangOptions.h"
#include "swift/Basic/PrettyStackTrace.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Driver/FrontendUtil.h"
#include "swift/Frontend/Frontend.h"
#include "swift/FrontendTool/FrontendTool.h"
#include "swift/IDE/Utils.h"
#include "swift/Parse/Lexer.h"
#include "swift/Parse/PersistentParserState.h"
#include "swift/Subsystems.h"
#include "swift/SymbolGraphGen/SymbolGraphOptions.h"
#include "clang/AST/ASTContext.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/Support/MemoryBuffer.h"
using namespace swift;
using namespace swift::ide;
// Interface fingerprint check and modified function body collection.
namespace {
/// Information of modified function body.
struct ModInfo {
/// Function decl in the *original* AST.
AbstractFunctionDecl *FD;
/// Range of the body in the *new* source file buffer.
SourceRange NewSourceRange;
ModInfo(AbstractFunctionDecl *FD, const SourceRange &NewSourceRange)
: FD(FD), NewSourceRange(NewSourceRange) {}
};
static bool collectModifiedFunctions(ArrayRef<Decl *> r1, ArrayRef<Decl *> r2,
llvm::SmallVectorImpl<ModInfo> &result) {
assert(r1.size() == r2.size() &&
"interface fingerprint matches but diffrent number of children");
for (auto i1 = r1.begin(), i2 = r2.begin(), e1 = r1.end(), e2 = r2.end();
i1 != e1 && i2 != e2; ++i1, ++i2) {
auto &d1 = *i1, &d2 = *i2;
assert(d1->getKind() == d2->getKind() &&
"interface fingerprint matches but diffrent structure");
/// FIXME: Nested types.
/// func foo() {
/// struct S {
/// func bar() { ... }
/// }
/// }
/// * Could editing a local-type interface lead to the need for
/// retypechecking other functions?
/// * Can we retypecheck only a function in local types? If only 'bar()'
/// body have changed, we want to only retypecheck 'bar()'.
auto *f1 = dyn_cast<AbstractFunctionDecl>(d1);
auto *f2 = dyn_cast<AbstractFunctionDecl>(d2);
if (f1 && f2) {
auto fp1 = f1->getBodyFingerprintIncludingLocalTypeMembers();
auto fp2 = f2->getBodyFingerprintIncludingLocalTypeMembers();
if (fp1 != fp2) {
// The fingerprint of the body has changed. Record it.
result.emplace_back(f1, f2->getBodySourceRange());
}
continue;
}
auto *idc1 = dyn_cast<IterableDeclContext>(d1);
auto *idc2 = dyn_cast<IterableDeclContext>(d2);
if (idc1 && idc2) {
if (idc1->getBodyFingerprint() != idc2->getBodyFingerprint()) {
// The fingerprint of the interface has changed. We can't reuse this.
return true;
}
// Recurse into the child IDC members.
if (collectModifiedFunctions(idc1->getParsedMembers(),
idc2->getParsedMembers(), result)) {
return true;
}
}
}
return false;
}
/// Collect functions in \p SF with modified bodies into \p result .
/// \p tmpSM is used for managing source buffers for new source files. Source
/// range for collected modified function body info is managed by \tmpSM.
/// \p tmpSM must be different from the source manager of \p SF .
static bool
getModifiedFunctionDeclList(const SourceFile &SF, SourceManager &tmpSM,
llvm::SmallVectorImpl<ModInfo> &result) {
auto &ctx = SF.getASTContext();
auto tmpBuffer = tmpSM.getFileSystem()->getBufferForFile(SF.getFilename());
if (!tmpBuffer) {
// The file is deleted?
return true;
}
// Parse the new buffer into temporary SourceFile.
LangOptions langOpts = ctx.LangOpts;
TypeCheckerOptions typeckOpts = ctx.TypeCheckerOpts;
SearchPathOptions searchPathOpts = ctx.SearchPathOpts;
ClangImporterOptions clangOpts = ctx.ClangImporterOpts;
SILOptions silOpts = ctx.SILOpts;
symbolgraphgen::SymbolGraphOptions symbolOpts = ctx.SymbolGraphOpts;
DiagnosticEngine tmpDiags(tmpSM);
auto &tmpCtx = *ASTContext::get(langOpts, typeckOpts, silOpts, searchPathOpts,
clangOpts, symbolOpts, tmpSM, tmpDiags);
registerParseRequestFunctions(tmpCtx.evaluator);
registerTypeCheckerRequestFunctions(tmpCtx.evaluator);
ModuleDecl *tmpM = ModuleDecl::create(Identifier(), tmpCtx);
auto tmpBufferID = tmpSM.addNewSourceBuffer(std::move(*tmpBuffer));
SourceFile *tmpSF = new (tmpCtx)
SourceFile(*tmpM, SF.Kind, tmpBufferID, SF.getParsingOptions());
// If the top-level code has been changed, we can't do anything.
if (SF.getInterfaceHash() != tmpSF->getInterfaceHash())
return true;
return collectModifiedFunctions(SF.getTopLevelDecls(),
tmpSF->getTopLevelDecls(), result);
}
/// Typecheck the body of \p func with the new source text specified with
/// \p newBodyRange managed by \p newSM .
///
/// This copies the source text of \p newBodyRange to the source manger
/// \p func originally parsed.
void retypeCheckFunctionBody(AbstractFunctionDecl *func,
SourceRange newBodyRange, SourceManager &newSM) {
// To save the persistent memory in the source manager, add the sliced range
// of the new function body to the source manager.
// NOTE: Using 'getLocForStartOfLine' is to get the correct column value for
// diagnostics on the first line.
auto tmpBufferID = newSM.findBufferContainingLoc(newBodyRange.Start);
auto bufStartLoc = Lexer::getLocForStartOfLine(newSM, newBodyRange.Start);
auto bufEndLoc = Lexer::getLocForEndOfToken(newSM, newBodyRange.End);
auto bufStartOffset = newSM.getLocOffsetInBuffer(bufStartLoc, tmpBufferID);
auto bufEndOffset = newSM.getLocOffsetInBuffer(bufEndLoc, tmpBufferID);
auto slicedSourceText = newSM.getEntireTextForBuffer(tmpBufferID)
.slice(bufStartOffset, bufEndOffset);
auto &origSM = func->getASTContext().SourceMgr;
auto sliceBufferID = origSM.addMemBufferCopy(
slicedSourceText, newSM.getIdentifierForBuffer(tmpBufferID));
origSM.openVirtualFile(
origSM.getLocForBufferStart(sliceBufferID),
newSM.getDisplayNameForLoc(bufStartLoc),
newSM.getPresumedLineAndColumnForLoc(bufStartLoc).first - 1);
// Calculate the body range in the sliced source buffer.
auto rangeStartOffset =
newSM.getLocOffsetInBuffer(newBodyRange.Start, tmpBufferID);
auto rangeEndOffset =
newSM.getLocOffsetInBuffer(newBodyRange.End, tmpBufferID);
auto rangeStartLoc =
origSM.getLocForOffset(sliceBufferID, rangeStartOffset - bufStartOffset);
auto rangeEndLoc =
origSM.getLocForOffset(sliceBufferID, rangeEndOffset - bufStartOffset);
SourceRange newRange{rangeStartLoc, rangeEndLoc};
// Reset the body range of the function decl, and re-typecheck it.
origSM.setReplacedRange(func->getOriginalBodySourceRange(), newRange);
func->setBodyToBeReparsed(newRange);
(void)func->getTypecheckedBody();
}
} // namespace
bool CompileInstance::performCachedSemaIfPossible(DiagnosticConsumer *DiagC) {
// Currently, only '-c' (aka. '-emit-object') action is supported.
assert(CI->getInvocation().getFrontendOptions().RequestedAction ==
FrontendOptions::ActionType::EmitObject &&
"Unsupported action; only 'EmitObject' is supported");
SourceManager &SM = CI->getSourceMgr();
auto FS = SM.getFileSystem();
if (shouldCheckDependencies()) {
if (areAnyDependentFilesInvalidated(*CI, *FS, /*excludeBufferID=*/None,
DependencyCheckedTimestamp,
InMemoryDependencyHash)) {
return true;
}
DependencyCheckedTimestamp = std::chrono::system_clock::now();
}
SourceManager tmpSM(FS);
// Collect modified function body.
SmallVector<ModInfo, 2> modifiedFuncDecls;
bool isNotResuable = CI->forEachFileToTypeCheck([&](SourceFile &oldSF) {
return getModifiedFunctionDeclList(oldSF, tmpSM, modifiedFuncDecls);
});
if (isNotResuable)
return true;
// OK, we can reuse the AST.
CI->addDiagnosticConsumer(DiagC);
SWIFT_DEFER { CI->removeDiagnosticConsumer(DiagC); };
for (const auto &info : modifiedFuncDecls) {
retypeCheckFunctionBody(info.FD, info.NewSourceRange, tmpSM);
}
return false;
}
bool CompileInstance::setupCI(
llvm::ArrayRef<const char *> origArgs,
llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fileSystem,
DiagnosticConsumer *diagC) {
auto &Diags = CI->getDiags();
SmallVector<const char *, 16> args;
// Put '-resource-dir' and '-diagnostic-documentation-path' at the top to
// allow overriding them with the passed in arguments.
args.append({"-resource-dir", RuntimeResourcePath.c_str()});
args.append({"-Xfrontend", "-diagnostic-documentation-path", "-Xfrontend",
DiagnosticDocumentationPath.c_str()});
args.append(origArgs.begin(), origArgs.end());
CompilerInvocation invocation;
bool invocationCreationFailed =
driver::getSingleFrontendInvocationFromDriverArguments(
args, Diags,
[&](ArrayRef<const char *> FrontendArgs) {
return invocation.parseArgs(FrontendArgs, Diags);
},
/*ForceNoOutputs=*/false);
if (invocationCreationFailed) {
assert(Diags.hadAnyError());
return false;
}
if (invocation.getFrontendOptions().RequestedAction !=
FrontendOptions::ActionType::EmitObject) {
Diags.diagnose(SourceLoc(), diag::not_implemented,
"only -c (aka. -emit-object) action is supported");
return false;
}
// Since LLVM arguments are parsed into a global state, LLVM can't handle
// multiple argument sets in a process simultaneously. So let's ignore them.
// FIXME: Remove this if possible.
invocation.getFrontendOptions().LLVMArgs.clear();
/// Declare the frontend to be used for multiple compilations.
invocation.getFrontendOptions().ReuseFrontendForMultipleCompilations = true;
// Enable dependency trakcing (excluding system modules) to invalidate the
// compiler instance if any dependent files are modified.
invocation.getFrontendOptions().IntermoduleDependencyTracking =
IntermoduleDepTrackingMode::ExcludeSystem;
std::string InstanceSetupError;
if (CI->setup(invocation, InstanceSetupError)) {
assert(Diags.hadAnyError());
return false;
}
return true;
}
bool CompileInstance::performSema(
llvm::ArrayRef<const char *> Args,
llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fileSystem,
DiagnosticConsumer *DiagC,
std::shared_ptr<std::atomic<bool>> CancellationFlag) {
// Compute the signature of the invocation.
llvm::hash_code ArgsHash(0);
for (auto arg : Args)
ArgsHash = llvm::hash_combine(ArgsHash, StringRef(arg));
if (CI && ArgsHash == CachedArgHash &&
CachedReuseCount < Opts.MaxASTReuseCount) {
CI->getASTContext().CancellationFlag = CancellationFlag;
if (!performCachedSemaIfPossible(DiagC)) {
// If we compileted cacehd Sema operation. We're done.
++CachedReuseCount;
return CI->getDiags().hadAnyError();
}
}
// Performing a new operation. Reset the compiler instance.
CI = std::make_unique<CompilerInstance>();
CI->addDiagnosticConsumer(DiagC);
if (!setupCI(Args, fileSystem, DiagC)) {
// Failed to setup the CI.
CI.reset();
return true;
}
// Remember cache related information.
DependencyCheckedTimestamp = std::chrono::system_clock::now();
CachedArgHash = ArgsHash;
CachedReuseCount = 0;
InMemoryDependencyHash.clear();
cacheDependencyHashIfNeeded(*CI, /*excludeBufferID=*/None,
InMemoryDependencyHash);
// Perform!
CI->getASTContext().CancellationFlag = CancellationFlag;
CI->performSema();
CI->removeDiagnosticConsumer(DiagC);
return CI->getDiags().hadAnyError();
}
bool CompileInstance::performCompile(
llvm::ArrayRef<const char *> Args,
llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fileSystem,
DiagnosticConsumer *DiagC,
std::shared_ptr<std::atomic<bool>> CancellationFlag) {
// Cancellation check. This gives a chance to cancel queued up requests before
// processing anything.
if (CancellationFlag && CancellationFlag->load(std::memory_order_relaxed))
return true;
if (performSema(Args, fileSystem, DiagC, CancellationFlag))
return true;
// Cancellation check after Sema.
if (CI->isCancellationRequested())
return true;
CI->addDiagnosticConsumer(DiagC);
SWIFT_DEFER { CI->removeDiagnosticConsumer(DiagC); };
int ReturnValue = 0;
return performCompileStepsPostSema(*CI, ReturnValue, /*observer=*/nullptr);
}
bool CompileInstance::shouldCheckDependencies() const {
assert(CI);
using namespace std::chrono;
auto now = system_clock::now();
auto threshold =
DependencyCheckedTimestamp + seconds(Opts.DependencyCheckIntervalSecond);
return threshold <= now;
}