@@ -138,20 +138,17 @@ bool CompletionInstance::performCachedOperaitonIfPossible(
138
138
if (!EnableASTCaching)
139
139
return false ;
140
140
141
- // Temporary move the CI so other threads don't use the same instance.
142
- std::shared_ptr<CachedInstance> CachedI (nullptr );
143
- CachedInst.swap (CachedI);
144
-
145
- if (!CachedI)
141
+ if (!CachedCI)
146
142
return false ;
147
- if (CachedI->ReuseCound >= MaxASTReuseCount)
143
+
144
+ if (CachedReuseCound >= MaxASTReuseCount)
148
145
return false ;
149
- if (CachedI-> ArgHash != ArgsHash)
146
+ if (CachedArgHash != ArgsHash)
150
147
return false ;
151
148
152
- auto &CI = CachedI-> CI ;
149
+ auto &CI = *CachedCI ;
153
150
154
- auto &oldState = CachedI-> CI .getPersistentParserState ();
151
+ auto &oldState = CI.getPersistentParserState ();
155
152
if (!oldState.hasCodeCompletionDelayedDeclState ())
156
153
return false ;
157
154
@@ -242,8 +239,7 @@ bool CompletionInstance::performCachedOperaitonIfPossible(
242
239
if (DiagC)
243
240
CI.removeDiagnosticConsumer (DiagC);
244
241
245
- CachedI->ReuseCound += 1 ;
246
- CachedInst.swap (CachedI);
242
+ CachedReuseCound += 1 ;
247
243
248
244
return true ;
249
245
}
@@ -254,9 +250,9 @@ bool CompletionInstance::performNewOperation(
254
250
llvm::MemoryBuffer *completionBuffer, unsigned int Offset,
255
251
std::string &Error, DiagnosticConsumer *DiagC,
256
252
llvm::function_ref<void (CompilerInstance &)> Callback) {
257
- CachedInst. reset ();
258
- auto TheInstance = std::make_shared<CachedInstance >();
259
- auto &CI = TheInstance-> CI ;
253
+
254
+ auto TheInstance = std::make_unique<CompilerInstance >();
255
+ auto &CI = * TheInstance;
260
256
if (DiagC)
261
257
CI.addDiagnosticConsumer (DiagC);
262
258
@@ -278,8 +274,9 @@ bool CompletionInstance::performNewOperation(
278
274
CI.removeDiagnosticConsumer (DiagC);
279
275
280
276
if (EnableASTCaching) {
281
- TheInstance->ArgHash = ArgsHash;
282
- CachedInst.swap (TheInstance);
277
+ CachedCI = std::move (TheInstance);
278
+ CachedArgHash = ArgsHash;
279
+ CachedReuseCound = 0 ;
283
280
}
284
281
285
282
return true ;
@@ -308,6 +305,12 @@ bool swift::ide::CompletionInstance::performOperation(
308
305
for (auto arg : Args)
309
306
ArgsHash = llvm::hash_combine (ArgsHash, StringRef (arg));
310
307
308
+ // If AST caching is enabled, block completions in other threads. So they
309
+ // have higher chance to use the cached completion instance.
310
+ Optional<std::lock_guard<std::mutex>> lock;
311
+ if (EnableASTCaching)
312
+ lock.emplace (mtx);
313
+
311
314
if (performCachedOperaitonIfPossible (Invocation, ArgsHash, completionBuffer,
312
315
Offset, DiagC, Callback))
313
316
return true ;
0 commit comments