Coverage Report

Created: 2021-08-24 07:12

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Frontend/ASTUnit.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- ASTUnit.cpp - ASTUnit utility --------------------------------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// ASTUnit Implementation.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/Frontend/ASTUnit.h"
14
#include "clang/AST/ASTConsumer.h"
15
#include "clang/AST/ASTContext.h"
16
#include "clang/AST/CommentCommandTraits.h"
17
#include "clang/AST/Decl.h"
18
#include "clang/AST/DeclBase.h"
19
#include "clang/AST/DeclCXX.h"
20
#include "clang/AST/DeclGroup.h"
21
#include "clang/AST/DeclObjC.h"
22
#include "clang/AST/DeclTemplate.h"
23
#include "clang/AST/DeclarationName.h"
24
#include "clang/AST/ExternalASTSource.h"
25
#include "clang/AST/PrettyPrinter.h"
26
#include "clang/AST/Type.h"
27
#include "clang/AST/TypeOrdering.h"
28
#include "clang/Basic/Diagnostic.h"
29
#include "clang/Basic/FileManager.h"
30
#include "clang/Basic/IdentifierTable.h"
31
#include "clang/Basic/LLVM.h"
32
#include "clang/Basic/LangOptions.h"
33
#include "clang/Basic/LangStandard.h"
34
#include "clang/Basic/Module.h"
35
#include "clang/Basic/SourceLocation.h"
36
#include "clang/Basic/SourceManager.h"
37
#include "clang/Basic/TargetInfo.h"
38
#include "clang/Basic/TargetOptions.h"
39
#include "clang/Frontend/CompilerInstance.h"
40
#include "clang/Frontend/CompilerInvocation.h"
41
#include "clang/Frontend/FrontendAction.h"
42
#include "clang/Frontend/FrontendActions.h"
43
#include "clang/Frontend/FrontendDiagnostic.h"
44
#include "clang/Frontend/FrontendOptions.h"
45
#include "clang/Frontend/MultiplexConsumer.h"
46
#include "clang/Frontend/PrecompiledPreamble.h"
47
#include "clang/Frontend/Utils.h"
48
#include "clang/Lex/HeaderSearch.h"
49
#include "clang/Lex/HeaderSearchOptions.h"
50
#include "clang/Lex/Lexer.h"
51
#include "clang/Lex/PPCallbacks.h"
52
#include "clang/Lex/PreprocessingRecord.h"
53
#include "clang/Lex/Preprocessor.h"
54
#include "clang/Lex/PreprocessorOptions.h"
55
#include "clang/Lex/Token.h"
56
#include "clang/Sema/CodeCompleteConsumer.h"
57
#include "clang/Sema/CodeCompleteOptions.h"
58
#include "clang/Sema/Sema.h"
59
#include "clang/Serialization/ASTBitCodes.h"
60
#include "clang/Serialization/ASTReader.h"
61
#include "clang/Serialization/ASTWriter.h"
62
#include "clang/Serialization/ContinuousRangeMap.h"
63
#include "clang/Serialization/InMemoryModuleCache.h"
64
#include "clang/Serialization/ModuleFile.h"
65
#include "clang/Serialization/PCHContainerOperations.h"
66
#include "llvm/ADT/ArrayRef.h"
67
#include "llvm/ADT/DenseMap.h"
68
#include "llvm/ADT/IntrusiveRefCntPtr.h"
69
#include "llvm/ADT/None.h"
70
#include "llvm/ADT/Optional.h"
71
#include "llvm/ADT/STLExtras.h"
72
#include "llvm/ADT/ScopeExit.h"
73
#include "llvm/ADT/SmallString.h"
74
#include "llvm/ADT/SmallVector.h"
75
#include "llvm/ADT/StringMap.h"
76
#include "llvm/ADT/StringRef.h"
77
#include "llvm/ADT/StringSet.h"
78
#include "llvm/ADT/Twine.h"
79
#include "llvm/ADT/iterator_range.h"
80
#include "llvm/Bitstream/BitstreamWriter.h"
81
#include "llvm/Support/Allocator.h"
82
#include "llvm/Support/Casting.h"
83
#include "llvm/Support/CrashRecoveryContext.h"
84
#include "llvm/Support/DJB.h"
85
#include "llvm/Support/ErrorHandling.h"
86
#include "llvm/Support/ErrorOr.h"
87
#include "llvm/Support/FileSystem.h"
88
#include "llvm/Support/FileUtilities.h"
89
#include "llvm/Support/MemoryBuffer.h"
90
#include "llvm/Support/Timer.h"
91
#include "llvm/Support/VirtualFileSystem.h"
92
#include "llvm/Support/raw_ostream.h"
93
#include <algorithm>
94
#include <atomic>
95
#include <cassert>
96
#include <cstdint>
97
#include <cstdio>
98
#include <cstdlib>
99
#include <memory>
100
#include <mutex>
101
#include <string>
102
#include <tuple>
103
#include <utility>
104
#include <vector>
105
106
using namespace clang;
107
108
using llvm::TimeRecord;
109
110
namespace {
111
112
  class SimpleTimer {
113
    bool WantTiming;
114
    TimeRecord Start;
115
    std::string Output;
116
117
  public:
118
9.03k
    explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
119
9.03k
      if (WantTiming)
120
18
        Start = TimeRecord::getCurrentTime();
121
9.03k
    }
122
123
9.02k
    ~SimpleTimer() {
124
9.02k
      if (WantTiming) {
125
18
        TimeRecord Elapsed = TimeRecord::getCurrentTime();
126
18
        Elapsed -= Start;
127
18
        llvm::errs() << Output << ':';
128
18
        Elapsed.print(Elapsed, llvm::errs());
129
18
        llvm::errs() << '\n';
130
18
      }
131
9.02k
    }
132
133
9.03k
    void setOutput(const Twine &Output) {
134
9.03k
      if (WantTiming)
135
18
        this->Output = Output.str();
136
9.03k
    }
137
  };
138
139
} // namespace
140
141
template <class T>
142
503
static std::unique_ptr<T> valueOrNull(llvm::ErrorOr<std::unique_ptr<T>> Val) {
143
503
  if (!Val)
144
0
    return nullptr;
145
503
  return std::move(*Val);
146
503
}
147
148
template <class T>
149
static bool moveOnNoError(llvm::ErrorOr<T> Val, T &Output) {
150
  if (!Val)
151
    return false;
152
  Output = std::move(*Val);
153
  return true;
154
}
155
156
/// Get a source buffer for \p MainFilePath, handling all file-to-file
157
/// and file-to-buffer remappings inside \p Invocation.
158
static std::unique_ptr<llvm::MemoryBuffer>
159
getBufferForFileHandlingRemapping(const CompilerInvocation &Invocation,
160
                                  llvm::vfs::FileSystem *VFS,
161
514
                                  StringRef FilePath, bool isVolatile) {
162
514
  const auto &PreprocessorOpts = Invocation.getPreprocessorOpts();
163
164
  // Try to determine if the main file has been remapped, either from the
165
  // command line (to another file) or directly through the compiler
166
  // invocation (to a memory buffer).
167
514
  llvm::MemoryBuffer *Buffer = nullptr;
168
514
  std::unique_ptr<llvm::MemoryBuffer> BufferOwner;
169
514
  auto FileStatus = VFS->status(FilePath);
170
514
  if (FileStatus) {
171
514
    llvm::sys::fs::UniqueID MainFileID = FileStatus->getUniqueID();
172
173
    // Check whether there is a file-file remapping of the main file
174
514
    for (const auto &RF : PreprocessorOpts.RemappedFiles) {
175
0
      std::string MPath(RF.first);
176
0
      auto MPathStatus = VFS->status(MPath);
177
0
      if (MPathStatus) {
178
0
        llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
179
0
        if (MainFileID == MID) {
180
          // We found a remapping. Try to load the resulting, remapped source.
181
0
          BufferOwner = valueOrNull(VFS->getBufferForFile(RF.second, -1, true, isVolatile));
182
0
          if (!BufferOwner)
183
0
            return nullptr;
184
0
        }
185
0
      }
186
0
    }
187
188
    // Check whether there is a file-buffer remapping. It supercedes the
189
    // file-file remapping.
190
514
    for (const auto &RB : PreprocessorOpts.RemappedFileBuffers) {
191
23
      std::string MPath(RB.first);
192
23
      auto MPathStatus = VFS->status(MPath);
193
23
      if (MPathStatus) {
194
19
        llvm::sys::fs::UniqueID MID = MPathStatus->getUniqueID();
195
19
        if (MainFileID == MID) {
196
          // We found a remapping.
197
11
          BufferOwner.reset();
198
11
          Buffer = const_cast<llvm::MemoryBuffer *>(RB.second);
199
11
        }
200
19
      }
201
23
    }
202
514
  }
203
204
  // If the main source file was not remapped, load it now.
205
514
  if (!Buffer && 
!BufferOwner503
) {
206
503
    BufferOwner = valueOrNull(VFS->getBufferForFile(FilePath, -1, true, isVolatile));
207
503
    if (!BufferOwner)
208
0
      return nullptr;
209
503
  }
210
211
514
  if (BufferOwner)
212
503
    return BufferOwner;
213
11
  if (!Buffer)
214
0
    return nullptr;
215
11
  return llvm::MemoryBuffer::getMemBufferCopy(Buffer->getBuffer(), FilePath);
216
11
}
217
218
struct ASTUnit::ASTWriterData {
219
  SmallString<128> Buffer;
220
  llvm::BitstreamWriter Stream;
221
  ASTWriter Writer;
222
223
  ASTWriterData(InMemoryModuleCache &ModuleCache)
224
60
      : Stream(Buffer), Writer(Stream, Buffer, ModuleCache, {}) {}
225
};
226
227
16.5k
void ASTUnit::clearFileLevelDecls() {
228
16.5k
  FileDecls.clear();
229
16.5k
}
230
231
/// After failing to build a precompiled preamble (due to
232
/// errors in the source that occurs in the preamble), the number of
233
/// reparses during which we'll skip even trying to precompile the
234
/// preamble.
235
const unsigned DefaultPreambleRebuildInterval = 5;
236
237
/// Tracks the number of ASTUnit objects that are currently active.
238
///
239
/// Used for debugging purposes only.
240
static std::atomic<unsigned> ActiveASTUnitObjects;
241
242
ASTUnit::ASTUnit(bool _MainFileIsAST)
243
    : MainFileIsAST(_MainFileIsAST), WantTiming(getenv("LIBCLANG_TIMING")),
244
      ShouldCacheCodeCompletionResults(false),
245
      IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
246
7.63k
      UnsafeToFree(false) {
247
7.63k
  if (getenv("LIBCLANG_OBJTRACKING"))
248
0
    fprintf(stderr, "+++ %u translation units\n", ++ActiveASTUnitObjects);
249
7.63k
}
250
251
7.62k
ASTUnit::~ASTUnit() {
252
  // If we loaded from an AST file, balance out the BeginSourceFile call.
253
7.62k
  if (MainFileIsAST && 
getDiagnostics().getClient()141
) {
254
141
    getDiagnostics().getClient()->EndSourceFile();
255
141
  }
256
257
7.62k
  clearFileLevelDecls();
258
259
  // Free the buffers associated with remapped files. We are required to
260
  // perform this operation here because we explicitly request that the
261
  // compiler instance *not* free these buffers for each invocation of the
262
  // parser.
263
7.62k
  if (Invocation && 
OwnsRemappedFileBuffers7.48k
) {
264
7.40k
    PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
265
7.40k
    for (const auto &RB : PPOpts.RemappedFileBuffers)
266
13
      delete RB.second;
267
7.40k
  }
268
269
7.62k
  ClearCachedCompletionResults();
270
271
7.62k
  if (getenv("LIBCLANG_OBJTRACKING"))
272
0
    fprintf(stderr, "--- %u translation units\n", --ActiveASTUnitObjects);
273
7.62k
}
274
275
87
void ASTUnit::setPreprocessor(std::shared_ptr<Preprocessor> PP) {
276
87
  this->PP = std::move(PP);
277
87
}
278
279
4.56k
void ASTUnit::enableSourceFileDiagnostics() {
280
4.56k
  assert(getDiagnostics().getClient() && Ctx &&
281
4.56k
      "Bad context for source file");
282
0
  getDiagnostics().getClient()->BeginSourceFile(Ctx->getLangOpts(), PP.get());
283
4.56k
}
284
285
/// Determine the set of code-completion contexts in which this
286
/// declaration should be shown.
287
static uint64_t getDeclShowContexts(const NamedDecl *ND,
288
                                    const LangOptions &LangOpts,
289
516
                                    bool &IsNestedNameSpecifier) {
290
516
  IsNestedNameSpecifier = false;
291
292
516
  if (isa<UsingShadowDecl>(ND))
293
2
    ND = ND->getUnderlyingDecl();
294
516
  if (!ND)
295
0
    return 0;
296
297
516
  uint64_t Contexts = 0;
298
516
  if (isa<TypeDecl>(ND) || 
isa<ObjCInterfaceDecl>(ND)343
||
299
516
      
isa<ClassTemplateDecl>(ND)293
||
isa<TemplateTemplateParmDecl>(ND)286
||
300
516
      
isa<TypeAliasTemplateDecl>(ND)286
) {
301
    // Types can appear in these contexts.
302
231
    if (LangOpts.CPlusPlus || 
!isa<TagDecl>(ND)185
)
303
212
      Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
304
212
               |  (1LL << CodeCompletionContext::CCC_ObjCIvarList)
305
212
               |  (1LL << CodeCompletionContext::CCC_ClassStructUnion)
306
212
               |  (1LL << CodeCompletionContext::CCC_Statement)
307
212
               |  (1LL << CodeCompletionContext::CCC_Type)
308
212
               |  (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
309
310
    // In C++, types can appear in expressions contexts (for functional casts).
311
231
    if (LangOpts.CPlusPlus)
312
46
      Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
313
314
    // In Objective-C, message sends can send interfaces. In Objective-C++,
315
    // all types are available due to functional casts.
316
231
    if (LangOpts.CPlusPlus || 
isa<ObjCInterfaceDecl>(ND)185
)
317
94
      Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
318
319
    // In Objective-C, you can only be a subclass of another Objective-C class
320
231
    if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND)) {
321
      // Objective-C interfaces can be used in a class property expression.
322
50
      if (ID->getDefinition())
323
14
        Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
324
50
      Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
325
50
    }
326
327
    // Deal with tag names.
328
231
    if (isa<EnumDecl>(ND)) {
329
2
      Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
330
331
      // Part of the nested-name-specifier in C++0x.
332
2
      if (LangOpts.CPlusPlus11)
333
0
        IsNestedNameSpecifier = true;
334
229
    } else if (const auto *Record = dyn_cast<RecordDecl>(ND)) {
335
50
      if (Record->isUnion())
336
0
        Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
337
50
      else
338
50
        Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
339
340
50
      if (LangOpts.CPlusPlus)
341
33
        IsNestedNameSpecifier = true;
342
179
    } else if (isa<ClassTemplateDecl>(ND))
343
7
      IsNestedNameSpecifier = true;
344
285
  } else if (isa<ValueDecl>(ND) || 
isa<FunctionTemplateDecl>(ND)21
) {
345
    // Values can appear in these contexts.
346
268
    Contexts = (1LL << CodeCompletionContext::CCC_Statement)
347
268
             | (1LL << CodeCompletionContext::CCC_Expression)
348
268
             | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
349
268
             | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
350
268
  } else 
if (17
isa<ObjCProtocolDecl>(ND)17
) {
351
4
    Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
352
13
  } else if (isa<ObjCCategoryDecl>(ND)) {
353
0
    Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
354
13
  } else if (isa<NamespaceDecl>(ND) || 
isa<NamespaceAliasDecl>(ND)1
) {
355
12
    Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
356
357
    // Part of the nested-name-specifier.
358
12
    IsNestedNameSpecifier = true;
359
12
  }
360
361
516
  return Contexts;
362
516
}
363
364
103
void ASTUnit::CacheCodeCompletionResults() {
365
103
  if (!TheSema)
366
0
    return;
367
368
103
  SimpleTimer Timer(WantTiming);
369
103
  Timer.setOutput("Cache global code completions for " + getMainFileName());
370
371
  // Clear out the previous results.
372
103
  ClearCachedCompletionResults();
373
374
  // Gather the set of global code completions.
375
103
  using Result = CodeCompletionResult;
376
103
  SmallVector<Result, 8> Results;
377
103
  CachedCompletionAllocator = std::make_shared<GlobalCodeCompletionAllocator>();
378
103
  CodeCompletionTUInfo CCTUInfo(CachedCompletionAllocator);
379
103
  TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
380
103
                                       CCTUInfo, Results);
381
382
  // Translate global code completions into cached completions.
383
103
  llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
384
103
  CodeCompletionContext CCContext(CodeCompletionContext::CCC_TopLevel);
385
386
41.3k
  for (auto &R : Results) {
387
41.3k
    switch (R.Kind) {
388
516
    case Result::RK_Declaration: {
389
516
      bool IsNestedNameSpecifier = false;
390
516
      CachedCodeCompletionResult CachedResult;
391
516
      CachedResult.Completion = R.CreateCodeCompletionString(
392
516
          *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
393
516
          IncludeBriefCommentsInCodeCompletion);
394
516
      CachedResult.ShowInContexts = getDeclShowContexts(
395
516
          R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier);
396
516
      CachedResult.Priority = R.Priority;
397
516
      CachedResult.Kind = R.CursorKind;
398
516
      CachedResult.Availability = R.Availability;
399
400
      // Keep track of the type of this completion in an ASTContext-agnostic
401
      // way.
402
516
      QualType UsageType = getDeclUsageType(*Ctx, R.Declaration);
403
516
      if (UsageType.isNull()) {
404
25
        CachedResult.TypeClass = STC_Void;
405
25
        CachedResult.Type = 0;
406
491
      } else {
407
491
        CanQualType CanUsageType
408
491
          = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
409
491
        CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
410
411
        // Determine whether we have already seen this type. If so, we save
412
        // ourselves the work of formatting the type string by using the
413
        // temporary, CanQualType-based hash table to find the associated value.
414
491
        unsigned &TypeValue = CompletionTypes[CanUsageType];
415
491
        if (TypeValue == 0) {
416
345
          TypeValue = CompletionTypes.size();
417
345
          CachedCompletionTypes[QualType(CanUsageType).getAsString()]
418
345
            = TypeValue;
419
345
        }
420
421
491
        CachedResult.Type = TypeValue;
422
491
      }
423
424
516
      CachedCompletionResults.push_back(CachedResult);
425
426
      /// Handle nested-name-specifiers in C++.
427
516
      if (TheSema->Context.getLangOpts().CPlusPlus && 
IsNestedNameSpecifier139
&&
428
516
          
!R.StartsNestedNameSpecifier52
) {
429
        // The contexts in which a nested-name-specifier can appear in C++.
430
52
        uint64_t NNSContexts
431
52
          = (1LL << CodeCompletionContext::CCC_TopLevel)
432
52
          | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
433
52
          | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
434
52
          | (1LL << CodeCompletionContext::CCC_Statement)
435
52
          | (1LL << CodeCompletionContext::CCC_Expression)
436
52
          | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
437
52
          | (1LL << CodeCompletionContext::CCC_EnumTag)
438
52
          | (1LL << CodeCompletionContext::CCC_UnionTag)
439
52
          | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
440
52
          | (1LL << CodeCompletionContext::CCC_Type)
441
52
          | (1LL << CodeCompletionContext::CCC_SymbolOrNewName)
442
52
          | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
443
444
52
        if (isa<NamespaceDecl>(R.Declaration) ||
445
52
            
isa<NamespaceAliasDecl>(R.Declaration)40
)
446
12
          NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
447
448
52
        if (uint64_t RemainingContexts
449
52
                                = NNSContexts & ~CachedResult.ShowInContexts) {
450
          // If there any contexts where this completion can be a
451
          // nested-name-specifier but isn't already an option, create a
452
          // nested-name-specifier completion.
453
52
          R.StartsNestedNameSpecifier = true;
454
52
          CachedResult.Completion = R.CreateCodeCompletionString(
455
52
              *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
456
52
              IncludeBriefCommentsInCodeCompletion);
457
52
          CachedResult.ShowInContexts = RemainingContexts;
458
52
          CachedResult.Priority = CCP_NestedNameSpecifier;
459
52
          CachedResult.TypeClass = STC_Void;
460
52
          CachedResult.Type = 0;
461
52
          CachedCompletionResults.push_back(CachedResult);
462
52
        }
463
52
      }
464
516
      break;
465
0
    }
466
467
0
    case Result::RK_Keyword:
468
0
    case Result::RK_Pattern:
469
      // Ignore keywords and patterns; we don't care, since they are so
470
      // easily regenerated.
471
0
      break;
472
473
40.8k
    case Result::RK_Macro: {
474
40.8k
      CachedCodeCompletionResult CachedResult;
475
40.8k
      CachedResult.Completion = R.CreateCodeCompletionString(
476
40.8k
          *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo,
477
40.8k
          IncludeBriefCommentsInCodeCompletion);
478
40.8k
      CachedResult.ShowInContexts
479
40.8k
        = (1LL << CodeCompletionContext::CCC_TopLevel)
480
40.8k
        | (1LL << CodeCompletionContext::CCC_ObjCInterface)
481
40.8k
        | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
482
40.8k
        | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
483
40.8k
        | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
484
40.8k
        | (1LL << CodeCompletionContext::CCC_Statement)
485
40.8k
        | (1LL << CodeCompletionContext::CCC_Expression)
486
40.8k
        | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
487
40.8k
        | (1LL << CodeCompletionContext::CCC_MacroNameUse)
488
40.8k
        | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
489
40.8k
        | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
490
40.8k
        | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
491
492
40.8k
      CachedResult.Priority = R.Priority;
493
40.8k
      CachedResult.Kind = R.CursorKind;
494
40.8k
      CachedResult.Availability = R.Availability;
495
40.8k
      CachedResult.TypeClass = STC_Void;
496
40.8k
      CachedResult.Type = 0;
497
40.8k
      CachedCompletionResults.push_back(CachedResult);
498
40.8k
      break;
499
0
    }
500
41.3k
    }
501
41.3k
  }
502
503
  // Save the current top-level hash value.
504
103
  CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
505
103
}
506
507
7.72k
void ASTUnit::ClearCachedCompletionResults() {
508
7.72k
  CachedCompletionResults.clear();
509
7.72k
  CachedCompletionTypes.clear();
510
7.72k
  CachedCompletionAllocator = nullptr;
511
7.72k
}
512
513
namespace {
514
515
/// Gathers information from ASTReader that will be used to initialize
516
/// a Preprocessor.
517
class ASTInfoCollector : public ASTReaderListener {
518
  Preprocessor &PP;
519
  ASTContext *Context;
520
  HeaderSearchOptions &HSOpts;
521
  PreprocessorOptions &PPOpts;
522
  LangOptions &LangOpt;
523
  std::shared_ptr<TargetOptions> &TargetOpts;
524
  IntrusiveRefCntPtr<TargetInfo> &Target;
525
  unsigned &Counter;
526
  bool InitializedLanguage = false;
527
528
public:
529
  ASTInfoCollector(Preprocessor &PP, ASTContext *Context,
530
                   HeaderSearchOptions &HSOpts, PreprocessorOptions &PPOpts,
531
                   LangOptions &LangOpt,
532
                   std::shared_ptr<TargetOptions> &TargetOpts,
533
                   IntrusiveRefCntPtr<TargetInfo> &Target, unsigned &Counter)
534
      : PP(PP), Context(Context), HSOpts(HSOpts), PPOpts(PPOpts),
535
        LangOpt(LangOpt), TargetOpts(TargetOpts), Target(Target),
536
150
        Counter(Counter) {}
537
538
  bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
539
150
                           bool AllowCompatibleDifferences) override {
540
150
    if (InitializedLanguage)
541
0
      return false;
542
543
150
    LangOpt = LangOpts;
544
150
    InitializedLanguage = true;
545
546
150
    updated();
547
150
    return false;
548
150
  }
549
550
  bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
551
                               StringRef SpecificModuleCachePath,
552
150
                               bool Complain) override {
553
150
    this->HSOpts = HSOpts;
554
150
    return false;
555
150
  }
556
557
  bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, bool Complain,
558
150
                               std::string &SuggestedPredefines) override {
559
150
    this->PPOpts = PPOpts;
560
150
    return false;
561
150
  }
562
563
  bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
564
150
                         bool AllowCompatibleDifferences) override {
565
    // If we've already initialized the target, don't do it again.
566
150
    if (Target)
567
0
      return false;
568
569
150
    this->TargetOpts = std::make_shared<TargetOptions>(TargetOpts);
570
150
    Target =
571
150
        TargetInfo::CreateTargetInfo(PP.getDiagnostics(), this->TargetOpts);
572
573
150
    updated();
574
150
    return false;
575
150
  }
576
577
  void ReadCounter(const serialization::ModuleFile &M,
578
0
                   unsigned Value) override {
579
0
    Counter = Value;
580
0
  }
581
582
private:
583
300
  void updated() {
584
300
    if (!Target || 
!InitializedLanguage150
)
585
150
      return;
586
587
    // Inform the target of the language options.
588
    //
589
    // FIXME: We shouldn't need to do this, the target should be immutable once
590
    // created. This complexity should be lifted elsewhere.
591
150
    Target->adjust(PP.getDiagnostics(), LangOpt);
592
593
    // Initialize the preprocessor.
594
150
    PP.Initialize(*Target);
595
596
150
    if (!Context)
597
15
      return;
598
599
    // Initialize the ASTContext
600
135
    Context->InitBuiltinTypes(*Target);
601
602
    // Adjust printing policy based on language options.
603
135
    Context->setPrintingPolicy(PrintingPolicy(LangOpt));
604
605
    // We didn't have access to the comment options when the ASTContext was
606
    // constructed, so register them now.
607
135
    Context->getCommentCommandTraits().registerCommentOptions(
608
135
        LangOpt.CommentOpts);
609
135
  }
610
};
611
612
/// Diagnostic consumer that saves each diagnostic it is given.
613
class FilterAndStoreDiagnosticConsumer : public DiagnosticConsumer {
614
  SmallVectorImpl<StoredDiagnostic> *StoredDiags;
615
  SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags;
616
  bool CaptureNonErrorsFromIncludes = true;
617
  const LangOptions *LangOpts = nullptr;
618
  SourceManager *SourceMgr = nullptr;
619
620
public:
621
  FilterAndStoreDiagnosticConsumer(
622
      SmallVectorImpl<StoredDiagnostic> *StoredDiags,
623
      SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags,
624
      bool CaptureNonErrorsFromIncludes)
625
      : StoredDiags(StoredDiags), StandaloneDiags(StandaloneDiags),
626
2.85k
        CaptureNonErrorsFromIncludes(CaptureNonErrorsFromIncludes) {
627
2.85k
    assert((StoredDiags || StandaloneDiags) &&
628
2.85k
           "No output collections were passed to StoredDiagnosticConsumer.");
629
2.85k
  }
630
631
  void BeginSourceFile(const LangOptions &LangOpts,
632
2.67k
                       const Preprocessor *PP = nullptr) override {
633
2.67k
    this->LangOpts = &LangOpts;
634
2.67k
    if (PP)
635
2.67k
      SourceMgr = &PP->getSourceManager();
636
2.67k
  }
637
638
  void HandleDiagnostic(DiagnosticsEngine::Level Level,
639
                        const Diagnostic &Info) override;
640
};
641
642
/// RAII object that optionally captures and filters diagnostics, if
643
/// there is no diagnostic client to capture them already.
644
class CaptureDroppedDiagnostics {
645
  DiagnosticsEngine &Diags;
646
  FilterAndStoreDiagnosticConsumer Client;
647
  DiagnosticConsumer *PreviousClient = nullptr;
648
  std::unique_ptr<DiagnosticConsumer> OwningPreviousClient;
649
650
public:
651
  CaptureDroppedDiagnostics(
652
      CaptureDiagsKind CaptureDiagnostics, DiagnosticsEngine &Diags,
653
      SmallVectorImpl<StoredDiagnostic> *StoredDiags,
654
      SmallVectorImpl<ASTUnit::StandaloneDiagnostic> *StandaloneDiags)
655
      : Diags(Diags),
656
        Client(StoredDiags, StandaloneDiags,
657
               CaptureDiagnostics !=
658
1.79k
                   CaptureDiagsKind::AllWithoutNonErrorsFromIncludes) {
659
1.79k
    if (CaptureDiagnostics != CaptureDiagsKind::None ||
660
1.79k
        
Diags.getClient() == nullptr0
) {
661
1.79k
      OwningPreviousClient = Diags.takeClient();
662
1.79k
      PreviousClient = Diags.getClient();
663
1.79k
      Diags.setClient(&Client, false);
664
1.79k
    }
665
1.79k
  }
666
667
1.79k
  ~CaptureDroppedDiagnostics() {
668
1.79k
    if (Diags.getClient() == &Client)
669
1.79k
      Diags.setClient(PreviousClient, !!OwningPreviousClient.release());
670
1.79k
  }
671
};
672
673
} // namespace
674
675
static ASTUnit::StandaloneDiagnostic
676
makeStandaloneDiagnostic(const LangOptions &LangOpts,
677
                         const StoredDiagnostic &InDiag);
678
679
2
static bool isInMainFile(const clang::Diagnostic &D) {
680
2
  if (!D.hasSourceManager() || !D.getLocation().isValid())
681
0
    return false;
682
683
2
  auto &M = D.getSourceManager();
684
2
  return M.isWrittenInMainFile(M.getExpansionLoc(D.getLocation()));
685
2
}
686
687
void FilterAndStoreDiagnosticConsumer::HandleDiagnostic(
688
9.78k
    DiagnosticsEngine::Level Level, const Diagnostic &Info) {
689
  // Default implementation (Warnings/errors count).
690
9.78k
  DiagnosticConsumer::HandleDiagnostic(Level, Info);
691
692
  // Only record the diagnostic if it's part of the source manager we know
693
  // about. This effectively drops diagnostics from modules we're building.
694
  // FIXME: In the long run, ee don't want to drop source managers from modules.
695
9.78k
  if (!Info.hasSourceManager() || 
&Info.getSourceManager() == SourceMgr9.76k
) {
696
9.76k
    if (!CaptureNonErrorsFromIncludes && 
Level <= DiagnosticsEngine::Warning2
&&
697
9.76k
        
!isInMainFile(Info)2
) {
698
1
      return;
699
1
    }
700
701
9.76k
    StoredDiagnostic *ResultDiag = nullptr;
702
9.76k
    if (StoredDiags) {
703
9.76k
      StoredDiags->emplace_back(Level, Info);
704
9.76k
      ResultDiag = &StoredDiags->back();
705
9.76k
    }
706
707
9.76k
    if (StandaloneDiags) {
708
25
      llvm::Optional<StoredDiagnostic> StoredDiag = None;
709
25
      if (!ResultDiag) {
710
0
        StoredDiag.emplace(Level, Info);
711
0
        ResultDiag = StoredDiag.getPointer();
712
0
      }
713
25
      StandaloneDiags->push_back(
714
25
          makeStandaloneDiagnostic(*LangOpts, *ResultDiag));
715
25
    }
716
9.76k
  }
717
9.78k
}
718
719
16
IntrusiveRefCntPtr<ASTReader> ASTUnit::getASTReader() const {
720
16
  return Reader;
721
16
}
722
723
12.2k
ASTMutationListener *ASTUnit::getASTMutationListener() {
724
12.2k
  if (WriterData)
725
60
    return &WriterData->Writer;
726
12.1k
  return nullptr;
727
12.2k
}
728
729
532
ASTDeserializationListener *ASTUnit::getDeserializationListener() {
730
532
  if (WriterData)
731
7
    return &WriterData->Writer;
732
525
  return nullptr;
733
532
}
734
735
std::unique_ptr<llvm::MemoryBuffer>
736
269
ASTUnit::getBufferForFile(StringRef Filename, std::string *ErrorStr) {
737
269
  assert(FileMgr);
738
0
  auto Buffer = FileMgr->getBufferForFile(Filename, UserFilesAreVolatile);
739
269
  if (Buffer)
740
269
    return std::move(*Buffer);
741
0
  if (ErrorStr)
742
0
    *ErrorStr = Buffer.getError().message();
743
0
  return nullptr;
744
269
}
745
746
/// Configure the diagnostics object for use with ASTUnit.
747
void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
748
                             ASTUnit &AST,
749
7.63k
                             CaptureDiagsKind CaptureDiagnostics) {
750
7.63k
  assert(Diags.get() && "no DiagnosticsEngine was provided");
751
7.63k
  if (CaptureDiagnostics != CaptureDiagsKind::None)
752
1.06k
    Diags->setClient(new FilterAndStoreDiagnosticConsumer(
753
1.06k
        &AST.StoredDiagnostics, nullptr,
754
1.06k
        CaptureDiagnostics != CaptureDiagsKind::AllWithoutNonErrorsFromIncludes));
755
7.63k
}
756
757
std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile(
758
    const std::string &Filename, const PCHContainerReader &PCHContainerRdr,
759
    WhatToLoad ToLoad, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
760
    const FileSystemOptions &FileSystemOpts, bool UseDebugInfo,
761
    bool OnlyLocalDecls, CaptureDiagsKind CaptureDiagnostics,
762
150
    bool AllowASTWithCompilerErrors, bool UserFilesAreVolatile) {
763
150
  std::unique_ptr<ASTUnit> AST(new ASTUnit(true));
764
765
  // Recover resources if we crash before exiting this method.
766
150
  llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
767
150
    ASTUnitCleanup(AST.get());
768
150
  llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
769
150
    llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
770
150
    DiagCleanup(Diags.get());
771
772
150
  ConfigureDiags(Diags, *AST, CaptureDiagnostics);
773
774
150
  AST->LangOpts = std::make_shared<LangOptions>();
775
150
  AST->OnlyLocalDecls = OnlyLocalDecls;
776
150
  AST->CaptureDiagnostics = CaptureDiagnostics;
777
150
  AST->Diagnostics = Diags;
778
150
  IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS =
779
150
      llvm::vfs::getRealFileSystem();
780
150
  AST->FileMgr = new FileManager(FileSystemOpts, VFS);
781
150
  AST->UserFilesAreVolatile = UserFilesAreVolatile;
782
150
  AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
783
150
                                     AST->getFileManager(),
784
150
                                     UserFilesAreVolatile);
785
150
  AST->ModuleCache = new InMemoryModuleCache;
786
150
  AST->HSOpts = std::make_shared<HeaderSearchOptions>();
787
150
  AST->HSOpts->ModuleFormat = std::string(PCHContainerRdr.getFormat());
788
150
  AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
789
150
                                         AST->getSourceManager(),
790
150
                                         AST->getDiagnostics(),
791
150
                                         AST->getLangOpts(),
792
150
                                         /*Target=*/nullptr));
793
150
  AST->PPOpts = std::make_shared<PreprocessorOptions>();
794
795
  // Gather Info for preprocessor construction later on.
796
797
150
  HeaderSearch &HeaderInfo = *AST->HeaderInfo;
798
150
  unsigned Counter;
799
800
150
  AST->PP = std::make_shared<Preprocessor>(
801
150
      AST->PPOpts, AST->getDiagnostics(), *AST->LangOpts,
802
150
      AST->getSourceManager(), HeaderInfo, AST->ModuleLoader,
803
150
      /*IILookup=*/nullptr,
804
150
      /*OwnsHeaderSearch=*/false);
805
150
  Preprocessor &PP = *AST->PP;
806
807
150
  if (ToLoad >= LoadASTOnly)
808
135
    AST->Ctx = new ASTContext(*AST->LangOpts, AST->getSourceManager(),
809
135
                              PP.getIdentifierTable(), PP.getSelectorTable(),
810
135
                              PP.getBuiltinInfo(),
811
135
                              AST->getTranslationUnitKind());
812
813
150
  DisableValidationForModuleKind disableValid =
814
150
      DisableValidationForModuleKind::None;
815
150
  if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
816
0
    disableValid = DisableValidationForModuleKind::All;
817
150
  AST->Reader = new ASTReader(
818
150
      PP, *AST->ModuleCache, AST->Ctx.get(), PCHContainerRdr, {},
819
150
      /*isysroot=*/"",
820
150
      /*DisableValidation=*/disableValid, AllowASTWithCompilerErrors);
821
822
150
  AST->Reader->setListener(std::make_unique<ASTInfoCollector>(
823
150
      *AST->PP, AST->Ctx.get(), *AST->HSOpts, *AST->PPOpts, *AST->LangOpts,
824
150
      AST->TargetOpts, AST->Target, Counter));
825
826
  // Attach the AST reader to the AST context as an external AST
827
  // source, so that declarations will be deserialized from the
828
  // AST file as needed.
829
  // We need the external source to be set up before we read the AST, because
830
  // eagerly-deserialized declarations may use it.
831
150
  if (AST->Ctx)
832
135
    AST->Ctx->setExternalSource(AST->Reader);
833
834
150
  switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile,
835
150
                          SourceLocation(), ASTReader::ARR_None)) {
836
149
  case ASTReader::Success:
837
149
    break;
838
839
0
  case ASTReader::Failure:
840
0
  case ASTReader::Missing:
841
1
  case ASTReader::OutOfDate:
842
1
  case ASTReader::VersionMismatch:
843
1
  case ASTReader::ConfigurationMismatch:
844
1
  case ASTReader::HadErrors:
845
1
    AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
846
1
    return nullptr;
847
150
  }
848
849
149
  AST->OriginalSourceFile = std::string(AST->Reader->getOriginalSourceFile());
850
851
149
  PP.setCounterValue(Counter);
852
853
  // Create an AST consumer, even though it isn't used.
854
149
  if (ToLoad >= LoadASTOnly)
855
134
    AST->Consumer.reset(new ASTConsumer);
856
857
  // Create a semantic analysis object and tell the AST reader about it.
858
149
  if (ToLoad >= LoadEverything) {
859
132
    AST->TheSema.reset(new Sema(PP, *AST->Ctx, *AST->Consumer));
860
132
    AST->TheSema->Initialize();
861
132
    AST->Reader->InitializeSema(*AST->TheSema);
862
132
  }
863
864
  // Tell the diagnostic client that we have started a source file.
865
149
  AST->getDiagnostics().getClient()->BeginSourceFile(PP.getLangOpts(), &PP);
866
867
149
  return AST;
868
150
}
869
870
/// Add the given macro to the hash of all top-level entities.
871
2.95M
static void AddDefinedMacroToHash(const Token &MacroNameTok, unsigned &Hash) {
872
2.95M
  Hash = llvm::djbHash(MacroNameTok.getIdentifierInfo()->getName(), Hash);
873
2.95M
}
874
875
namespace {
876
877
/// Preprocessor callback class that updates a hash value with the names
878
/// of all macros that have been defined by the translation unit.
879
class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
880
  unsigned &Hash;
881
882
public:
883
8.35k
  explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) {}
884
885
  void MacroDefined(const Token &MacroNameTok,
886
2.95M
                    const MacroDirective *MD) override {
887
2.95M
    AddDefinedMacroToHash(MacroNameTok, Hash);
888
2.95M
  }
889
};
890
891
} // namespace
892
893
/// Add the given declaration to the hash of all top-level entities.
894
28.4k
static void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
895
28.4k
  if (!D)
896
0
    return;
897
898
28.4k
  DeclContext *DC = D->getDeclContext();
899
28.4k
  if (!DC)
900
0
    return;
901
902
28.4k
  if (!(DC->isTranslationUnit() || 
DC->getLookupParent()->isTranslationUnit()675
))
903
55
    return;
904
905
28.3k
  if (const auto *ND = dyn_cast<NamedDecl>(D)) {
906
28.0k
    if (const auto *EnumD = dyn_cast<EnumDecl>(D)) {
907
      // For an unscoped enum include the enumerators in the hash since they
908
      // enter the top-level namespace.
909
436
      if (!EnumD->isScoped()) {
910
418
        for (const auto *EI : EnumD->enumerators()) {
911
418
          if (EI->getIdentifier())
912
418
            Hash = llvm::djbHash(EI->getIdentifier()->getName(), Hash);
913
418
        }
914
300
      }
915
436
    }
916
917
28.0k
    if (ND->getIdentifier())
918
26.1k
      Hash = llvm::djbHash(ND->getIdentifier()->getName(), Hash);
919
1.85k
    else if (DeclarationName Name = ND->getDeclName()) {
920
907
      std::string NameStr = Name.getAsString();
921
907
      Hash = llvm::djbHash(NameStr, Hash);
922
907
    }
923
28.0k
    return;
924
28.0k
  }
925
926
327
  if (const auto *ImportD = dyn_cast<ImportDecl>(D)) {
927
58
    if (const Module *Mod = ImportD->getImportedModule()) {
928
58
      std::string ModName = Mod->getFullModuleName();
929
58
      Hash = llvm::djbHash(ModName, Hash);
930
58
    }
931
58
    return;
932
58
  }
933
327
}
934
935
namespace {
936
937
class TopLevelDeclTrackerConsumer : public ASTConsumer {
938
  ASTUnit &Unit;
939
  unsigned &Hash;
940
941
public:
942
  TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
943
8.26k
      : Unit(_Unit), Hash(Hash) {
944
8.26k
    Hash = 0;
945
8.26k
  }
946
947
30.3k
  void handleTopLevelDecl(Decl *D) {
948
30.3k
    if (!D)
949
0
      return;
950
951
    // FIXME: Currently ObjC method declarations are incorrectly being
952
    // reported as top-level declarations, even though their DeclContext
953
    // is the containing ObjC @interface/@implementation.  This is a
954
    // fundamental problem in the parser right now.
955
30.3k
    if (isa<ObjCMethodDecl>(D))
956
2.08k
      return;
957
958
28.3k
    AddTopLevelDeclarationToHash(D, Hash);
959
28.3k
    Unit.addTopLevelDecl(D);
960
961
28.3k
    handleFileLevelDecl(D);
962
28.3k
  }
963
964
29.6k
  void handleFileLevelDecl(Decl *D) {
965
29.6k
    Unit.addFileLevelDecl(D);
966
29.6k
    if (auto *NSD = dyn_cast<NamespaceDecl>(D)) {
967
1.00k
      for (auto *I : NSD->decls())
968
1.38k
        handleFileLevelDecl(I);
969
1.00k
    }
970
29.6k
  }
971
972
27.3k
  bool HandleTopLevelDecl(DeclGroupRef D) override {
973
27.3k
    for (auto *TopLevelDecl : D)
974
30.3k
      handleTopLevelDecl(TopLevelDecl);
975
27.3k
    return true;
976
27.3k
  }
977
978
  // We're not interested in "interesting" decls.
979
69
  void HandleInterestingDecl(DeclGroupRef) override {}
980
981
17
  void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
982
17
    for (auto *TopLevelDecl : D)
983
9
      handleTopLevelDecl(TopLevelDecl);
984
17
  }
985
986
12.2k
  ASTMutationListener *GetASTMutationListener() override {
987
12.2k
    return Unit.getASTMutationListener();
988
12.2k
  }
989
990
532
  ASTDeserializationListener *GetASTDeserializationListener() override {
991
532
    return Unit.getDeserializationListener();
992
532
  }
993
};
994
995
class TopLevelDeclTrackerAction : public ASTFrontendAction {
996
public:
997
  ASTUnit &Unit;
998
999
  std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
1000
8.17k
                                                 StringRef InFile) override {
1001
8.17k
    CI.getPreprocessor().addPPCallbacks(
1002
8.17k
        std::make_unique<MacroDefinitionTrackerPPCallbacks>(
1003
8.17k
                                           Unit.getCurrentTopLevelHashValue()));
1004
8.17k
    return std::make_unique<TopLevelDeclTrackerConsumer>(
1005
8.17k
        Unit, Unit.getCurrentTopLevelHashValue());
1006
8.17k
  }
1007
1008
public:
1009
8.17k
  TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
1010
1011
8.17k
  bool hasCodeCompletionSupport() const override { return false; }
1012
1013
16.3k
  TranslationUnitKind getTranslationUnitKind() override {
1014
16.3k
    return Unit.getTranslationUnitKind();
1015
16.3k
  }
1016
};
1017
1018
class ASTUnitPreambleCallbacks : public PreambleCallbacks {
1019
public:
1020
90
  unsigned getHash() const { return Hash; }
1021
1022
0
  std::vector<Decl *> takeTopLevelDecls() { return std::move(TopLevelDecls); }
1023
1024
90
  std::vector<serialization::DeclID> takeTopLevelDeclIDs() {
1025
90
    return std::move(TopLevelDeclIDs);
1026
90
  }
1027
1028
90
  void AfterPCHEmitted(ASTWriter &Writer) override {
1029
90
    TopLevelDeclIDs.reserve(TopLevelDecls.size());
1030
92
    for (const auto *D : TopLevelDecls) {
1031
      // Invalid top-level decls may not have been serialized.
1032
92
      if (D->isInvalidDecl())
1033
6
        continue;
1034
86
      TopLevelDeclIDs.push_back(Writer.getDeclID(D));
1035
86
    }
1036
90
  }
1037
1038
87
  void HandleTopLevelDecl(DeclGroupRef DG) override {
1039
92
    for (auto *D : DG) {
1040
      // FIXME: Currently ObjC method declarations are incorrectly being
1041
      // reported as top-level declarations, even though their DeclContext
1042
      // is the containing ObjC @interface/@implementation.  This is a
1043
      // fundamental problem in the parser right now.
1044
92
      if (isa<ObjCMethodDecl>(D))
1045
0
        continue;
1046
92
      AddTopLevelDeclarationToHash(D, Hash);
1047
92
      TopLevelDecls.push_back(D);
1048
92
    }
1049
87
  }
1050
1051
90
  std::unique_ptr<PPCallbacks> createPPCallbacks() override {
1052
90
    return std::make_unique<MacroDefinitionTrackerPPCallbacks>(Hash);
1053
90
  }
1054
1055
private:
1056
  unsigned Hash = 0;
1057
  std::vector<Decl *> TopLevelDecls;
1058
  std::vector<serialization::DeclID> TopLevelDeclIDs;
1059
  llvm::SmallVector<ASTUnit::StandaloneDiagnostic, 4> PreambleDiags;
1060
};
1061
1062
} // namespace
1063
1064
4.44k
static bool isNonDriverDiag(const StoredDiagnostic &StoredDiag) {
1065
4.44k
  return StoredDiag.getLocation().isValid();
1066
4.44k
}
1067
1068
static void
1069
7.95k
checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &StoredDiags) {
1070
  // Get rid of stored diagnostics except the ones from the driver which do not
1071
  // have a source location.
1072
7.95k
  StoredDiags.erase(
1073
7.95k
      std::remove_if(StoredDiags.begin(), StoredDiags.end(), isNonDriverDiag),
1074
7.95k
      StoredDiags.end());
1075
7.95k
}
1076
1077
static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1078
                                                              StoredDiagnostics,
1079
258
                                  SourceManager &SM) {
1080
  // The stored diagnostic has the old source manager in it; update
1081
  // the locations to refer into the new source manager. Since we've
1082
  // been careful to make sure that the source manager's state
1083
  // before and after are identical, so that we can reuse the source
1084
  // location itself.
1085
258
  for (auto &SD : StoredDiagnostics) {
1086
97
    if (SD.getLocation().isValid()) {
1087
97
      FullSourceLoc Loc(SD.getLocation(), SM);
1088
97
      SD.setLocation(Loc);
1089
97
    }
1090
97
  }
1091
258
}
1092
1093
/// Parse the source file into a translation unit using the given compiler
1094
/// invocation, replacing the current translation unit.
1095
///
1096
/// \returns True if a failure occurred that causes the ASTUnit not to
1097
/// contain any translation-unit information, false otherwise.
1098
bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1099
                    std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer,
1100
8.12k
                    IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
1101
8.12k
  if (!Invocation)
1102
0
    return true;
1103
1104
8.12k
  if (VFS && FileMgr)
1105
7.30k
    assert(VFS == &FileMgr->getVirtualFileSystem() &&
1106
8.12k
           "VFS passed to Parse and VFS in FileMgr are different");
1107
1108
0
  auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
1109
8.12k
  if (OverrideMainBuffer) {
1110
258
    assert(Preamble &&
1111
258
           "No preamble was built, but OverrideMainBuffer is not null");
1112
0
    Preamble->AddImplicitPreamble(*CCInvocation, VFS, OverrideMainBuffer.get());
1113
    // VFS may have changed...
1114
258
  }
1115
1116
  // Create the compiler instance to use for building the AST.
1117
0
  std::unique_ptr<CompilerInstance> Clang(
1118
8.12k
      new CompilerInstance(std::move(PCHContainerOps)));
1119
1120
  // Clean up on error, disengage it if the function returns successfully.
1121
8.12k
  auto CleanOnError = llvm::make_scope_exit([&]() {
1122
    // Remove the overridden buffer we used for the preamble.
1123
3
    SavedMainFileBuffer = nullptr;
1124
1125
    // Keep the ownership of the data in the ASTUnit because the client may
1126
    // want to see the diagnostics.
1127
3
    transferASTDataFromCompilerInstance(*Clang);
1128
3
    FailedParseDiagnostics.swap(StoredDiagnostics);
1129
3
    StoredDiagnostics.clear();
1130
3
    NumStoredDiagnosticsFromDriver = 0;
1131
3
  });
1132
1133
  // Ensure that Clang has a FileManager with the right VFS, which may have
1134
  // changed above in AddImplicitPreamble.  If VFS is nullptr, rely on
1135
  // createFileManager to create one.
1136
8.12k
  if (VFS && FileMgr && 
&FileMgr->getVirtualFileSystem() == VFS7.30k
)
1137
7.29k
    Clang->setFileManager(&*FileMgr);
1138
827
  else
1139
827
    FileMgr = Clang->createFileManager(std::move(VFS));
1140
1141
  // Recover resources if we crash before exiting this method.
1142
8.12k
  llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1143
8.12k
    CICleanup(Clang.get());
1144
1145
8.12k
  Clang->setInvocation(CCInvocation);
1146
8.12k
  OriginalSourceFile =
1147
8.12k
      std::string(Clang->getFrontendOpts().Inputs[0].getFile());
1148
1149
  // Set up diagnostics, capturing any diagnostics that would
1150
  // otherwise be dropped.
1151
8.12k
  Clang->setDiagnostics(&getDiagnostics());
1152
1153
  // Create the target instance.
1154
8.12k
  if (!Clang->createTarget())
1155
1
    return true;
1156
1157
8.12k
  assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1158
8.12k
         "Invocation must have exactly one source file!");
1159
0
  assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1160
8.12k
             InputKind::Source &&
1161
8.12k
         "FIXME: AST inputs not yet supported here!");
1162
0
  assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1163
8.12k
             Language::LLVM_IR &&
1164
8.12k
         "IR inputs not support here!");
1165
1166
  // Configure the various subsystems.
1167
0
  LangOpts = Clang->getInvocation().LangOpts;
1168
8.12k
  FileSystemOpts = Clang->getFileSystemOpts();
1169
1170
8.12k
  ResetForParse();
1171
1172
8.12k
  SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1173
8.12k
                                UserFilesAreVolatile);
1174
8.12k
  if (!OverrideMainBuffer) {
1175
7.86k
    checkAndRemoveNonDriverDiags(StoredDiagnostics);
1176
7.86k
    TopLevelDeclsInPreamble.clear();
1177
7.86k
  }
1178
1179
  // Create the source manager.
1180
8.12k
  Clang->setSourceManager(&getSourceManager());
1181
1182
  // If the main file has been overridden due to the use of a preamble,
1183
  // make that override happen and introduce the preamble.
1184
8.12k
  if (OverrideMainBuffer) {
1185
    // The stored diagnostic has the old source manager in it; update
1186
    // the locations to refer into the new source manager. Since we've
1187
    // been careful to make sure that the source manager's state
1188
    // before and after are identical, so that we can reuse the source
1189
    // location itself.
1190
258
    checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
1191
1192
    // Keep track of the override buffer;
1193
258
    SavedMainFileBuffer = std::move(OverrideMainBuffer);
1194
258
  }
1195
1196
8.12k
  std::unique_ptr<TopLevelDeclTrackerAction> Act(
1197
8.12k
      new TopLevelDeclTrackerAction(*this));
1198
1199
  // Recover resources if we crash before exiting this method.
1200
8.12k
  llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1201
8.12k
    ActCleanup(Act.get());
1202
1203
8.12k
  if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
1204
2
    return true;
1205
1206
8.12k
  if (SavedMainFileBuffer)
1207
258
    TranslateStoredDiagnostics(getFileManager(), getSourceManager(),
1208
258
                               PreambleDiagnostics, StoredDiagnostics);
1209
7.86k
  else
1210
7.86k
    PreambleSrcLocCache.clear();
1211
1212
8.12k
  if (llvm::Error Err = Act->Execute()) {
1213
0
    consumeError(std::move(Err)); // FIXME this drops errors on the floor.
1214
0
    return true;
1215
0
  }
1216
1217
8.12k
  transferASTDataFromCompilerInstance(*Clang);
1218
1219
8.12k
  Act->EndSourceFile();
1220
1221
8.12k
  FailedParseDiagnostics.clear();
1222
1223
8.12k
  CleanOnError.release();
1224
1225
8.12k
  return false;
1226
8.12k
}
1227
1228
static std::pair<unsigned, unsigned>
1229
makeStandaloneRange(CharSourceRange Range, const SourceManager &SM,
1230
16
                    const LangOptions &LangOpts) {
1231
16
  CharSourceRange FileRange = Lexer::makeFileCharRange(Range, SM, LangOpts);
1232
16
  unsigned Offset = SM.getFileOffset(FileRange.getBegin());
1233
16
  unsigned EndOffset = SM.getFileOffset(FileRange.getEnd());
1234
16
  return std::make_pair(Offset, EndOffset);
1235
16
}
1236
1237
static ASTUnit::StandaloneFixIt makeStandaloneFixIt(const SourceManager &SM,
1238
                                                    const LangOptions &LangOpts,
1239
3
                                                    const FixItHint &InFix) {
1240
3
  ASTUnit::StandaloneFixIt OutFix;
1241
3
  OutFix.RemoveRange = makeStandaloneRange(InFix.RemoveRange, SM, LangOpts);
1242
3
  OutFix.InsertFromRange = makeStandaloneRange(InFix.InsertFromRange, SM,
1243
3
                                               LangOpts);
1244
3
  OutFix.CodeToInsert = InFix.CodeToInsert;
1245
3
  OutFix.BeforePreviousInsertions = InFix.BeforePreviousInsertions;
1246
3
  return OutFix;
1247
3
}
1248
1249
static ASTUnit::StandaloneDiagnostic
1250
makeStandaloneDiagnostic(const LangOptions &LangOpts,
1251
25
                         const StoredDiagnostic &InDiag) {
1252
25
  ASTUnit::StandaloneDiagnostic OutDiag;
1253
25
  OutDiag.ID = InDiag.getID();
1254
25
  OutDiag.Level = InDiag.getLevel();
1255
25
  OutDiag.Message = std::string(InDiag.getMessage());
1256
25
  OutDiag.LocOffset = 0;
1257
25
  if (InDiag.getLocation().isInvalid())
1258
0
    return OutDiag;
1259
25
  const SourceManager &SM = InDiag.getLocation().getManager();
1260
25
  SourceLocation FileLoc = SM.getFileLoc(InDiag.getLocation());
1261
25
  OutDiag.Filename = std::string(SM.getFilename(FileLoc));
1262
25
  if (OutDiag.Filename.empty())
1263
0
    return OutDiag;
1264
25
  OutDiag.LocOffset = SM.getFileOffset(FileLoc);
1265
25
  for (const auto &Range : InDiag.getRanges())
1266
10
    OutDiag.Ranges.push_back(makeStandaloneRange(Range, SM, LangOpts));
1267
25
  for (const auto &FixIt : InDiag.getFixIts())
1268
3
    OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, FixIt));
1269
1270
25
  return OutDiag;
1271
25
}
1272
1273
/// Attempt to build or re-use a precompiled preamble when (re-)parsing
1274
/// the source file.
1275
///
1276
/// This routine will compute the preamble of the main source file. If a
1277
/// non-trivial preamble is found, it will precompile that preamble into a
1278
/// precompiled header so that the precompiled preamble can be used to reduce
1279
/// reparsing time. If a precompiled preamble has already been constructed,
1280
/// this routine will determine if it is still valid and, if so, avoid
1281
/// rebuilding the precompiled preamble.
1282
///
1283
/// \param AllowRebuild When true (the default), this routine is
1284
/// allowed to rebuild the precompiled preamble if it is found to be
1285
/// out-of-date.
1286
///
1287
/// \param MaxLines When non-zero, the maximum number of lines that
1288
/// can occur within the preamble.
1289
///
1290
/// \returns If the precompiled preamble can be used, returns a newly-allocated
1291
/// buffer that should be used in place of the main file when doing so.
1292
/// Otherwise, returns a NULL pointer.
1293
std::unique_ptr<llvm::MemoryBuffer>
1294
ASTUnit::getMainBufferWithPrecompiledPreamble(
1295
    std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1296
    CompilerInvocation &PreambleInvocationIn,
1297
    IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS, bool AllowRebuild,
1298
514
    unsigned MaxLines) {
1299
514
  auto MainFilePath =
1300
514
      PreambleInvocationIn.getFrontendOpts().Inputs[0].getFile();
1301
514
  std::unique_ptr<llvm::MemoryBuffer> MainFileBuffer =
1302
514
      getBufferForFileHandlingRemapping(PreambleInvocationIn, VFS.get(),
1303
514
                                        MainFilePath, UserFilesAreVolatile);
1304
514
  if (!MainFileBuffer)
1305
0
    return nullptr;
1306
1307
514
  PreambleBounds Bounds = ComputePreambleBounds(
1308
514
      *PreambleInvocationIn.getLangOpts(), *MainFileBuffer, MaxLines);
1309
514
  if (!Bounds.Size)
1310
97
    return nullptr;
1311
1312
417
  if (Preamble) {
1313
253
    if (Preamble->CanReuse(PreambleInvocationIn, *MainFileBuffer, Bounds,
1314
253
                           *VFS)) {
1315
      // Okay! We can re-use the precompiled preamble.
1316
1317
      // Set the state of the diagnostic object to mimic its state
1318
      // after parsing the preamble.
1319
243
      getDiagnostics().Reset();
1320
243
      ProcessWarningOptions(getDiagnostics(),
1321
243
                            PreambleInvocationIn.getDiagnosticOpts());
1322
243
      getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1323
1324
243
      PreambleRebuildCountdown = 1;
1325
243
      return MainFileBuffer;
1326
243
    } else {
1327
10
      Preamble.reset();
1328
10
      PreambleDiagnostics.clear();
1329
10
      TopLevelDeclsInPreamble.clear();
1330
10
      PreambleSrcLocCache.clear();
1331
10
      PreambleRebuildCountdown = 1;
1332
10
    }
1333
253
  }
1334
1335
  // If the preamble rebuild counter > 1, it's because we previously
1336
  // failed to build a preamble and we're not yet ready to try
1337
  // again. Decrement the counter and return a failure.
1338
174
  if (PreambleRebuildCountdown > 1) {
1339
80
    --PreambleRebuildCountdown;
1340
80
    return nullptr;
1341
80
  }
1342
1343
94
  assert(!Preamble && "No Preamble should be stored at that point");
1344
  // If we aren't allowed to rebuild the precompiled preamble, just
1345
  // return now.
1346
94
  if (!AllowRebuild)
1347
4
    return nullptr;
1348
1349
90
  ++PreambleCounter;
1350
1351
90
  SmallVector<StandaloneDiagnostic, 4> NewPreambleDiagsStandalone;
1352
90
  SmallVector<StoredDiagnostic, 4> NewPreambleDiags;
1353
90
  ASTUnitPreambleCallbacks Callbacks;
1354
90
  {
1355
90
    llvm::Optional<CaptureDroppedDiagnostics> Capture;
1356
90
    if (CaptureDiagnostics != CaptureDiagsKind::None)
1357
82
      Capture.emplace(CaptureDiagnostics, *Diagnostics, &NewPreambleDiags,
1358
82
                      &NewPreambleDiagsStandalone);
1359
1360
    // We did not previously compute a preamble, or it can't be reused anyway.
1361
90
    SimpleTimer PreambleTimer(WantTiming);
1362
90
    PreambleTimer.setOutput("Precompiling preamble");
1363
1364
90
    const bool PreviousSkipFunctionBodies =
1365
90
        PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies;
1366
90
    if (SkipFunctionBodies == SkipFunctionBodiesScope::Preamble)
1367
1
      PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies = true;
1368
1369
90
    llvm::ErrorOr<PrecompiledPreamble> NewPreamble = PrecompiledPreamble::Build(
1370
90
        PreambleInvocationIn, MainFileBuffer.get(), Bounds, *Diagnostics, VFS,
1371
90
        PCHContainerOps, /*StoreInMemory=*/false, Callbacks);
1372
1373
90
    PreambleInvocationIn.getFrontendOpts().SkipFunctionBodies =
1374
90
        PreviousSkipFunctionBodies;
1375
1376
90
    if (NewPreamble) {
1377
90
      Preamble = std::move(*NewPreamble);
1378
90
      PreambleRebuildCountdown = 1;
1379
90
    } else {
1380
0
      switch (static_cast<BuildPreambleError>(NewPreamble.getError().value())) {
1381
0
      case BuildPreambleError::CouldntCreateTempFile:
1382
        // Try again next time.
1383
0
        PreambleRebuildCountdown = 1;
1384
0
        return nullptr;
1385
0
      case BuildPreambleError::CouldntCreateTargetInfo:
1386
0
      case BuildPreambleError::BeginSourceFileFailed:
1387
0
      case BuildPreambleError::CouldntEmitPCH:
1388
0
      case BuildPreambleError::BadInputs:
1389
        // These erros are more likely to repeat, retry after some period.
1390
0
        PreambleRebuildCountdown = DefaultPreambleRebuildInterval;
1391
0
        return nullptr;
1392
0
      }
1393
0
      llvm_unreachable("unexpected BuildPreambleError");
1394
0
    }
1395
90
  }
1396
1397
90
  assert(Preamble && "Preamble wasn't built");
1398
1399
0
  TopLevelDecls.clear();
1400
90
  TopLevelDeclsInPreamble = Callbacks.takeTopLevelDeclIDs();
1401
90
  PreambleTopLevelHashValue = Callbacks.getHash();
1402
1403
90
  NumWarningsInPreamble = getDiagnostics().getNumWarnings();
1404
1405
90
  checkAndRemoveNonDriverDiags(NewPreambleDiags);
1406
90
  StoredDiagnostics = std::move(NewPreambleDiags);
1407
90
  PreambleDiagnostics = std::move(NewPreambleDiagsStandalone);
1408
1409
  // If the hash of top-level entities differs from the hash of the top-level
1410
  // entities the last time we rebuilt the preamble, clear out the completion
1411
  // cache.
1412
90
  if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1413
79
    CompletionCacheTopLevelHashValue = 0;
1414
79
    PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1415
79
  }
1416
1417
90
  return MainFileBuffer;
1418
90
}
1419
1420
5
void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1421
5
  assert(Preamble && "Should only be called when preamble was built");
1422
1423
0
  std::vector<Decl *> Resolved;
1424
5
  Resolved.reserve(TopLevelDeclsInPreamble.size());
1425
5
  ExternalASTSource &Source = *getASTContext().getExternalSource();
1426
9
  for (const auto TopLevelDecl : TopLevelDeclsInPreamble) {
1427
    // Resolve the declaration ID to an actual declaration, possibly
1428
    // deserializing the declaration in the process.
1429
9
    if (Decl *D = Source.GetExternalDecl(TopLevelDecl))
1430
9
      Resolved.push_back(D);
1431
9
  }
1432
5
  TopLevelDeclsInPreamble.clear();
1433
5
  TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1434
5
}
1435
1436
8.29k
void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1437
  // Steal the created target, context, and preprocessor if they have been
1438
  // created.
1439
8.29k
  assert(CI.hasInvocation() && "missing invocation");
1440
0
  LangOpts = CI.getInvocation().LangOpts;
1441
8.29k
  TheSema = CI.takeSema();
1442
8.29k
  Consumer = CI.takeASTConsumer();
1443
8.29k
  if (CI.hasASTContext())
1444
8.29k
    Ctx = &CI.getASTContext();
1445
8.29k
  if (CI.hasPreprocessor())
1446
8.29k
    PP = CI.getPreprocessorPtr();
1447
8.29k
  CI.setSourceManager(nullptr);
1448
8.29k
  CI.setFileManager(nullptr);
1449
8.29k
  if (CI.hasTarget())
1450
8.29k
    Target = &CI.getTarget();
1451
8.29k
  Reader = CI.getASTReader();
1452
8.29k
  HadModuleLoaderFatalFailure = CI.hadModuleLoaderFatalFailure();
1453
8.29k
}
1454
1455
8.49k
StringRef ASTUnit::getMainFileName() const {
1456
8.49k
  if (Invocation && 
!Invocation->getFrontendOpts().Inputs.empty()8.49k
) {
1457
8.49k
    const FrontendInputFile &Input = Invocation->getFrontendOpts().Inputs[0];
1458
8.49k
    if (Input.isFile())
1459
8.49k
      return Input.getFile();
1460
0
    else
1461
0
      return Input.getBuffer().getBufferIdentifier();
1462
8.49k
  }
1463
1464
1
  if (SourceMgr) {
1465
1
    if (const FileEntry *
1466
1
          FE = SourceMgr->getFileEntryForID(SourceMgr->getMainFileID()))
1467
1
      return FE->getName();
1468
1
  }
1469
1470
0
  return {};
1471
1
}
1472
1473
0
StringRef ASTUnit::getASTFileName() const {
1474
0
  if (!isMainFileAST())
1475
0
    return {};
1476
1477
0
  serialization::ModuleFile &
1478
0
    Mod = Reader->getModuleManager().getPrimaryModule();
1479
0
  return Mod.FileName;
1480
0
}
1481
1482
std::unique_ptr<ASTUnit>
1483
ASTUnit::create(std::shared_ptr<CompilerInvocation> CI,
1484
                IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1485
                CaptureDiagsKind CaptureDiagnostics,
1486
183
                bool UserFilesAreVolatile) {
1487
183
  std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
1488
183
  ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1489
183
  IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS =
1490
183
      createVFSFromCompilerInvocation(*CI, *Diags);
1491
183
  AST->Diagnostics = Diags;
1492
183
  AST->FileSystemOpts = CI->getFileSystemOpts();
1493
183
  AST->Invocation = std::move(CI);
1494
183
  AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
1495
183
  AST->UserFilesAreVolatile = UserFilesAreVolatile;
1496
183
  AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1497
183
                                     UserFilesAreVolatile);
1498
183
  AST->ModuleCache = new InMemoryModuleCache;
1499
1500
183
  return AST;
1501
183
}
1502
1503
ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(
1504
    std::shared_ptr<CompilerInvocation> CI,
1505
    std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1506
    IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FrontendAction *Action,
1507
    ASTUnit *Unit, bool Persistent, StringRef ResourceFilesPath,
1508
    bool OnlyLocalDecls, CaptureDiagsKind CaptureDiagnostics,
1509
    unsigned PrecompilePreambleAfterNParses, bool CacheCodeCompletionResults,
1510
183
    bool UserFilesAreVolatile, std::unique_ptr<ASTUnit> *ErrAST) {
1511
183
  assert(CI && "A CompilerInvocation is required");
1512
1513
0
  std::unique_ptr<ASTUnit> OwnAST;
1514
183
  ASTUnit *AST = Unit;
1515
183
  if (!AST) {
1516
    // Create the AST unit.
1517
144
    OwnAST = create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile);
1518
144
    AST = OwnAST.get();
1519
144
    if (!AST)
1520
0
      return nullptr;
1521
144
  }
1522
1523
183
  if (!ResourceFilesPath.empty()) {
1524
    // Override the resources path.
1525
39
    CI->getHeaderSearchOpts().ResourceDir = std::string(ResourceFilesPath);
1526
39
  }
1527
183
  AST->OnlyLocalDecls = OnlyLocalDecls;
1528
183
  AST->CaptureDiagnostics = CaptureDiagnostics;
1529
183
  if (PrecompilePreambleAfterNParses > 0)
1530
0
    AST->PreambleRebuildCountdown = PrecompilePreambleAfterNParses;
1531
183
  AST->TUKind = Action ? 
Action->getTranslationUnitKind()133
:
TU_Complete50
;
1532
183
  AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1533
183
  AST->IncludeBriefCommentsInCodeCompletion = false;
1534
1535
  // Recover resources if we crash before exiting this method.
1536
183
  llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1537
183
    ASTUnitCleanup(OwnAST.get());
1538
183
  llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1539
183
    llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
1540
183
    DiagCleanup(Diags.get());
1541
1542
  // We'll manage file buffers ourselves.
1543
183
  CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1544
183
  CI->getFrontendOpts().DisableFree = false;
1545
183
  ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1546
1547
  // Create the compiler instance to use for building the AST.
1548
183
  std::unique_ptr<CompilerInstance> Clang(
1549
183
      new CompilerInstance(std::move(PCHContainerOps)));
1550
1551
  // Recover resources if we crash before exiting this method.
1552
183
  llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1553
183
    CICleanup(Clang.get());
1554
1555
183
  Clang->setInvocation(std::move(CI));
1556
183
  AST->OriginalSourceFile =
1557
183
      std::string(Clang->getFrontendOpts().Inputs[0].getFile());
1558
1559
  // Set up diagnostics, capturing any diagnostics that would
1560
  // otherwise be dropped.
1561
183
  Clang->setDiagnostics(&AST->getDiagnostics());
1562
1563
  // Create the target instance.
1564
183
  if (!Clang->createTarget())
1565
0
    return nullptr;
1566
1567
183
  assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1568
183
         "Invocation must have exactly one source file!");
1569
0
  assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
1570
183
             InputKind::Source &&
1571
183
         "FIXME: AST inputs not yet supported here!");
1572
0
  assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
1573
183
             Language::LLVM_IR &&
1574
183
         "IR inputs not support here!");
1575
1576
  // Configure the various subsystems.
1577
0
  AST->TheSema.reset();
1578
183
  AST->Ctx = nullptr;
1579
183
  AST->PP = nullptr;
1580
183
  AST->Reader = nullptr;
1581
1582
  // Create a file manager object to provide access to and cache the filesystem.
1583
183
  Clang->setFileManager(&AST->getFileManager());
1584
1585
  // Create the source manager.
1586
183
  Clang->setSourceManager(&AST->getSourceManager());
1587
1588
183
  FrontendAction *Act = Action;
1589
1590
183
  std::unique_ptr<TopLevelDeclTrackerAction> TrackerAct;
1591
183
  if (!Act) {
1592
50
    TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1593
50
    Act = TrackerAct.get();
1594
50
  }
1595
1596
  // Recover resources if we crash before exiting this method.
1597
183
  llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1598
183
    ActCleanup(TrackerAct.get());
1599
1600
183
  if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1601
0
    AST->transferASTDataFromCompilerInstance(*Clang);
1602
0
    if (OwnAST && ErrAST)
1603
0
      ErrAST->swap(OwnAST);
1604
1605
0
    return nullptr;
1606
0
  }
1607
1608
183
  if (Persistent && 
!TrackerAct144
) {
1609
94
    Clang->getPreprocessor().addPPCallbacks(
1610
94
        std::make_unique<MacroDefinitionTrackerPPCallbacks>(
1611
94
                                           AST->getCurrentTopLevelHashValue()));
1612
94
    std::vector<std::unique_ptr<ASTConsumer>> Consumers;
1613
94
    if (Clang->hasASTConsumer())
1614
94
      Consumers.push_back(Clang->takeASTConsumer());
1615
94
    Consumers.push_back(std::make_unique<TopLevelDeclTrackerConsumer>(
1616
94
        *AST, AST->getCurrentTopLevelHashValue()));
1617
94
    Clang->setASTConsumer(
1618
94
        std::make_unique<MultiplexConsumer>(std::move(Consumers)));
1619
94
  }
1620
183
  if (llvm::Error Err = Act->Execute()) {
1621
0
    consumeError(std::move(Err)); // FIXME this drops errors on the floor.
1622
0
    AST->transferASTDataFromCompilerInstance(*Clang);
1623
0
    if (OwnAST && ErrAST)
1624
0
      ErrAST->swap(OwnAST);
1625
1626
0
    return nullptr;
1627
0
  }
1628
1629
  // Steal the created target, context, and preprocessor.
1630
183
  AST->transferASTDataFromCompilerInstance(*Clang);
1631
1632
183
  Act->EndSourceFile();
1633
1634
183
  if (OwnAST)
1635
144
    return OwnAST.release();
1636
39
  else
1637
39
    return AST;
1638
183
}
1639
1640
bool ASTUnit::LoadFromCompilerInvocation(
1641
    std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1642
    unsigned PrecompilePreambleAfterNParses,
1643
7.30k
    IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
1644
7.30k
  if (!Invocation)
1645
0
    return true;
1646
1647
7.30k
  assert(VFS && "VFS is null");
1648
1649
  // We'll manage file buffers ourselves.
1650
0
  Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1651
7.30k
  Invocation->getFrontendOpts().DisableFree = false;
1652
7.30k
  getDiagnostics().Reset();
1653
7.30k
  ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1654
1655
7.30k
  std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1656
7.30k
  if (PrecompilePreambleAfterNParses > 0) {
1657
132
    PreambleRebuildCountdown = PrecompilePreambleAfterNParses;
1658
132
    OverrideMainBuffer =
1659
132
        getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
1660
132
    getDiagnostics().Reset();
1661
132
    ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1662
132
  }
1663
1664
7.30k
  SimpleTimer ParsingTimer(WantTiming);
1665
7.30k
  ParsingTimer.setOutput("Parsing " + getMainFileName());
1666
1667
  // Recover resources if we crash before exiting this method.
1668
7.30k
  llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1669
7.30k
    MemBufferCleanup(OverrideMainBuffer.get());
1670
1671
7.30k
  return Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
1672
7.30k
}
1673
1674
std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation(
1675
    std::shared_ptr<CompilerInvocation> CI,
1676
    std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1677
    IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr,
1678
    bool OnlyLocalDecls, CaptureDiagsKind CaptureDiagnostics,
1679
    unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1680
    bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1681
6.31k
    bool UserFilesAreVolatile) {
1682
  // Create the AST unit.
1683
6.31k
  std::unique_ptr<ASTUnit> AST(new ASTUnit(false));
1684
6.31k
  ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1685
6.31k
  AST->Diagnostics = Diags;
1686
6.31k
  AST->OnlyLocalDecls = OnlyLocalDecls;
1687
6.31k
  AST->CaptureDiagnostics = CaptureDiagnostics;
1688
6.31k
  AST->TUKind = TUKind;
1689
6.31k
  AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1690
6.31k
  AST->IncludeBriefCommentsInCodeCompletion
1691
6.31k
    = IncludeBriefCommentsInCodeCompletion;
1692
6.31k
  AST->Invocation = std::move(CI);
1693
6.31k
  AST->FileSystemOpts = FileMgr->getFileSystemOpts();
1694
6.31k
  AST->FileMgr = FileMgr;
1695
6.31k
  AST->UserFilesAreVolatile = UserFilesAreVolatile;
1696
1697
  // Recover resources if we crash before exiting this method.
1698
6.31k
  llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1699
6.31k
    ASTUnitCleanup(AST.get());
1700
6.31k
  llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1701
6.31k
    llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine>>
1702
6.31k
    DiagCleanup(Diags.get());
1703
1704
6.31k
  if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
1705
6.31k
                                      PrecompilePreambleAfterNParses,
1706
6.31k
                                      &AST->FileMgr->getVirtualFileSystem()))
1707
0
    return nullptr;
1708
6.31k
  return AST;
1709
6.31k
}
1710
1711
ASTUnit *ASTUnit::LoadFromCommandLine(
1712
    const char **ArgBegin, const char **ArgEnd,
1713
    std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1714
    IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
1715
    bool OnlyLocalDecls, CaptureDiagsKind CaptureDiagnostics,
1716
    ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName,
1717
    unsigned PrecompilePreambleAfterNParses, TranslationUnitKind TUKind,
1718
    bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion,
1719
    bool AllowPCHWithCompilerErrors, SkipFunctionBodiesScope SkipFunctionBodies,
1720
    bool SingleFileParse, bool UserFilesAreVolatile, bool ForSerialization,
1721
    bool RetainExcludedConditionalBlocks,
1722
    llvm::Optional<StringRef> ModuleFormat, std::unique_ptr<ASTUnit> *ErrAST,
1723
992
    IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
1724
992
  assert(Diags.get() && "no DiagnosticsEngine was provided");
1725
1726
0
  SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1727
1728
992
  std::shared_ptr<CompilerInvocation> CI;
1729
1730
992
  {
1731
992
    CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
1732
992
                                      &StoredDiagnostics, nullptr);
1733
1734
992
    CI = createInvocationFromCommandLine(
1735
992
        llvm::makeArrayRef(ArgBegin, ArgEnd), Diags, VFS);
1736
992
    if (!CI)
1737
0
      return nullptr;
1738
992
  }
1739
1740
  // Override any files that need remapping
1741
992
  for (const auto &RemappedFile : RemappedFiles) {
1742
4
    CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1743
4
                                              RemappedFile.second);
1744
4
  }
1745
992
  PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1746
992
  PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1747
992
  PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
1748
992
  PPOpts.SingleFileParseMode = SingleFileParse;
1749
992
  PPOpts.RetainExcludedConditionalBlocks = RetainExcludedConditionalBlocks;
1750
1751
  // Override the resources path.
1752
992
  CI->getHeaderSearchOpts().ResourceDir = std::string(ResourceFilesPath);
1753
1754
992
  CI->getFrontendOpts().SkipFunctionBodies =
1755
992
      SkipFunctionBodies == SkipFunctionBodiesScope::PreambleAndMainFile;
1756
1757
992
  if (ModuleFormat)
1758
991
    CI->getHeaderSearchOpts().ModuleFormat =
1759
991
        std::string(ModuleFormat.getValue());
1760
1761
  // Create the AST unit.
1762
992
  std::unique_ptr<ASTUnit> AST;
1763
992
  AST.reset(new ASTUnit(false));
1764
992
  AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1765
992
  AST->StoredDiagnostics.swap(StoredDiagnostics);
1766
992
  ConfigureDiags(Diags, *AST, CaptureDiagnostics);
1767
992
  AST->Diagnostics = Diags;
1768
992
  AST->FileSystemOpts = CI->getFileSystemOpts();
1769
992
  if (!VFS)
1770
992
    VFS = llvm::vfs::getRealFileSystem();
1771
992
  VFS = createVFSFromCompilerInvocation(*CI, *Diags, VFS);
1772
992
  AST->FileMgr = new FileManager(AST->FileSystemOpts, VFS);
1773
992
  AST->ModuleCache = new InMemoryModuleCache;
1774
992
  AST->OnlyLocalDecls = OnlyLocalDecls;
1775
992
  AST->CaptureDiagnostics = CaptureDiagnostics;
1776
992
  AST->TUKind = TUKind;
1777
992
  AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1778
992
  AST->IncludeBriefCommentsInCodeCompletion
1779
992
    = IncludeBriefCommentsInCodeCompletion;
1780
992
  AST->UserFilesAreVolatile = UserFilesAreVolatile;
1781
992
  AST->Invocation = CI;
1782
992
  AST->SkipFunctionBodies = SkipFunctionBodies;
1783
992
  if (ForSerialization)
1784
60
    AST->WriterData.reset(new ASTWriterData(*AST->ModuleCache));
1785
  // Zero out now to ease cleanup during crash recovery.
1786
992
  CI = nullptr;
1787
992
  Diags = nullptr;
1788
1789
  // Recover resources if we crash before exiting this method.
1790
992
  llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1791
992
    ASTUnitCleanup(AST.get());
1792
1793
992
  if (AST->LoadFromCompilerInvocation(std::move(PCHContainerOps),
1794
992
                                      PrecompilePreambleAfterNParses,
1795
992
                                      VFS)) {
1796
    // Some error occurred, if caller wants to examine diagnostics, pass it the
1797
    // ASTUnit.
1798
3
    if (ErrAST) {
1799
3
      AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
1800
3
      ErrAST->swap(AST);
1801
3
    }
1802
3
    return nullptr;
1803
3
  }
1804
1805
989
  return AST.release();
1806
992
}
1807
1808
bool ASTUnit::Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
1809
                      ArrayRef<RemappedFile> RemappedFiles,
1810
821
                      IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) {
1811
821
  if (!Invocation)
1812
0
    return true;
1813
1814
821
  if (!VFS) {
1815
814
    assert(FileMgr && "FileMgr is null on Reparse call");
1816
0
    VFS = &FileMgr->getVirtualFileSystem();
1817
814
  }
1818
1819
0
  clearFileLevelDecls();
1820
1821
821
  SimpleTimer ParsingTimer(WantTiming);
1822
821
  ParsingTimer.setOutput("Reparsing " + getMainFileName());
1823
1824
  // Remap files.
1825
821
  PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1826
821
  for (const auto &RB : PPOpts.RemappedFileBuffers)
1827
12
    delete RB.second;
1828
1829
821
  Invocation->getPreprocessorOpts().clearRemappedFiles();
1830
821
  for (const auto &RemappedFile : RemappedFiles) {
1831
18
    Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first,
1832
18
                                                      RemappedFile.second);
1833
18
  }
1834
1835
  // If we have a preamble file lying around, or if we might try to
1836
  // build a precompiled preamble, do so now.
1837
821
  std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
1838
821
  if (Preamble || 
PreambleRebuildCountdown > 0647
)
1839
298
    OverrideMainBuffer =
1840
298
        getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation, VFS);
1841
1842
  // Clear out the diagnostics state.
1843
821
  FileMgr.reset();
1844
821
  getDiagnostics().Reset();
1845
821
  ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1846
821
  if (OverrideMainBuffer)
1847
249
    getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1848
1849
  // Parse the sources
1850
821
  bool Result =
1851
821
      Parse(std::move(PCHContainerOps), std::move(OverrideMainBuffer), VFS);
1852
1853
  // If we're caching global code-completion results, and the top-level
1854
  // declarations have changed, clear out the code-completion cache.
1855
821
  if (!Result && 
ShouldCacheCodeCompletionResults820
&&
1856
821
      
CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue233
)
1857
103
    CacheCodeCompletionResults();
1858
1859
  // We now need to clear out the completion info related to this translation
1860
  // unit; it'll be recreated if necessary.
1861
821
  CCTUInfo.reset();
1862
1863
821
  return Result;
1864
821
}
1865
1866
8.14k
void ASTUnit::ResetForParse() {
1867
8.14k
  SavedMainFileBuffer.reset();
1868
1869
8.14k
  SourceMgr.reset();
1870
8.14k
  TheSema.reset();
1871
8.14k
  Ctx.reset();
1872
8.14k
  PP.reset();
1873
8.14k
  Reader.reset();
1874
1875
8.14k
  TopLevelDecls.clear();
1876
8.14k
  clearFileLevelDecls();
1877
8.14k
}
1878
1879
//----------------------------------------------------------------------------//
1880
// Code completion
1881
//----------------------------------------------------------------------------//
1882
1883
namespace {
1884
1885
  /// Code completion consumer that combines the cached code-completion
1886
  /// results from an ASTUnit with the code-completion results provided to it,
1887
  /// then passes the result on to
1888
  class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1889
    uint64_t NormalContexts;
1890
    ASTUnit &AST;
1891
    CodeCompleteConsumer &Next;
1892
1893
  public:
1894
    AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
1895
                                  const CodeCompleteOptions &CodeCompleteOpts)
1896
721
        : CodeCompleteConsumer(CodeCompleteOpts), AST(AST), Next(Next) {
1897
      // Compute the set of contexts in which we will look when we don't have
1898
      // any information about the specific context.
1899
721
      NormalContexts
1900
721
        = (1LL << CodeCompletionContext::CCC_TopLevel)
1901
721
        | (1LL << CodeCompletionContext::CCC_ObjCInterface)
1902
721
        | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
1903
721
        | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
1904
721
        | (1LL << CodeCompletionContext::CCC_Statement)
1905
721
        | (1LL << CodeCompletionContext::CCC_Expression)
1906
721
        | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
1907
721
        | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
1908
721
        | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
1909
721
        | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
1910
721
        | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
1911
721
        | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
1912
721
        | (1LL << CodeCompletionContext::CCC_Recovery);
1913
1914
721
      if (AST.getASTContext().getLangOpts().CPlusPlus)
1915
257
        NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
1916
257
                       |  (1LL << CodeCompletionContext::CCC_UnionTag)
1917
257
                       |  (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
1918
721
    }
1919
1920
    void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
1921
                                    CodeCompletionResult *Results,
1922
                                    unsigned NumResults) override;
1923
1924
    void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1925
                                   OverloadCandidate *Candidates,
1926
                                   unsigned NumCandidates,
1927
101
                                   SourceLocation OpenParLoc) override {
1928
101
      Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates,
1929
101
                                     OpenParLoc);
1930
101
    }
1931
1932
2.64k
    CodeCompletionAllocator &getAllocator() override {
1933
2.64k
      return Next.getAllocator();
1934
2.64k
    }
1935
1936
2.64k
    CodeCompletionTUInfo &getCodeCompletionTUInfo() override {
1937
2.64k
      return Next.getCodeCompletionTUInfo();
1938
2.64k
    }
1939
  };
1940
1941
} // namespace
1942
1943
/// Helper function that computes which global names are hidden by the
1944
/// local code-completion results.
1945
static void CalculateHiddenNames(const CodeCompletionContext &Context,
1946
                                 CodeCompletionResult *Results,
1947
                                 unsigned NumResults,
1948
                                 ASTContext &Ctx,
1949
156
                          llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
1950
156
  bool OnlyTagNames = false;
1951
156
  switch (Context.getKind()) {
1952
0
  case CodeCompletionContext::CCC_Recovery:
1953
25
  case CodeCompletionContext::CCC_TopLevel:
1954
25
  case CodeCompletionContext::CCC_ObjCInterface:
1955
25
  case CodeCompletionContext::CCC_ObjCImplementation:
1956
25
  case CodeCompletionContext::CCC_ObjCIvarList:
1957
25
  case CodeCompletionContext::CCC_ClassStructUnion:
1958
66
  case CodeCompletionContext::CCC_Statement:
1959
111
  case CodeCompletionContext::CCC_Expression:
1960
111
  case CodeCompletionContext::CCC_ObjCMessageReceiver:
1961
111
  case CodeCompletionContext::CCC_DotMemberAccess:
1962
111
  case CodeCompletionContext::CCC_ArrowMemberAccess:
1963
111
  case CodeCompletionContext::CCC_ObjCPropertyAccess:
1964
111
  case CodeCompletionContext::CCC_Namespace:
1965
111
  case CodeCompletionContext::CCC_Type:
1966
111
  case CodeCompletionContext::CCC_Symbol:
1967
121
  case CodeCompletionContext::CCC_SymbolOrNewName:
1968
131
  case CodeCompletionContext::CCC_ParenthesizedExpression:
1969
136
  case CodeCompletionContext::CCC_ObjCInterfaceName:
1970
136
    break;
1971
1972
0
  case CodeCompletionContext::CCC_EnumTag:
1973
0
  case CodeCompletionContext::CCC_UnionTag:
1974
5
  case CodeCompletionContext::CCC_ClassOrStructTag:
1975
5
    OnlyTagNames = true;
1976
5
    break;
1977
1978
5
  case CodeCompletionContext::CCC_ObjCProtocolName:
1979
5
  case CodeCompletionContext::CCC_MacroName:
1980
10
  case CodeCompletionContext::CCC_MacroNameUse:
1981
15
  case CodeCompletionContext::CCC_PreprocessorExpression:
1982
15
  case CodeCompletionContext::CCC_PreprocessorDirective:
1983
15
  case CodeCompletionContext::CCC_NaturalLanguage:
1984
15
  case CodeCompletionContext::CCC_SelectorName:
1985
15
  case CodeCompletionContext::CCC_TypeQualifiers:
1986
15
  case CodeCompletionContext::CCC_Other:
1987
15
  case CodeCompletionContext::CCC_OtherWithMacros:
1988
15
  case CodeCompletionContext::CCC_ObjCInstanceMessage:
1989
15
  case CodeCompletionContext::CCC_ObjCClassMessage:
1990
15
  case CodeCompletionContext::CCC_ObjCCategoryName:
1991
15
  case CodeCompletionContext::CCC_IncludedFile:
1992
15
  case CodeCompletionContext::CCC_Attribute:
1993
15
  case CodeCompletionContext::CCC_NewName:
1994
    // We're looking for nothing, or we're looking for names that cannot
1995
    // be hidden.
1996
15
    return;
1997
156
  }
1998
1999
141
  using Result = CodeCompletionResult;
2000
3.70k
  for (unsigned I = 0; I != NumResults; 
++I3.55k
) {
2001
3.55k
    if (Results[I].Kind != Result::RK_Declaration)
2002
3.40k
      continue;
2003
2004
155
    unsigned IDNS
2005
155
      = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2006
2007
155
    bool Hiding = false;
2008
155
    if (OnlyTagNames)
2009
5
      Hiding = (IDNS & Decl::IDNS_Tag);
2010
150
    else {
2011
150
      unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
2012
150
                             Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2013
150
                             Decl::IDNS_NonMemberOperator);
2014
150
      if (Ctx.getLangOpts().CPlusPlus)
2015
5
        HiddenIDNS |= Decl::IDNS_Tag;
2016
150
      Hiding = (IDNS & HiddenIDNS);
2017
150
    }
2018
2019
155
    if (!Hiding)
2020
10
      continue;
2021
2022
145
    DeclarationName Name = Results[I].Declaration->getDeclName();
2023
145
    if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2024
145
      HiddenNames.insert(Identifier->getName());
2025
0
    else
2026
0
      HiddenNames.insert(Name.getAsString());
2027
145
  }
2028
141
}
2029
2030
void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2031
                                            CodeCompletionContext Context,
2032
                                            CodeCompletionResult *Results,
2033
716
                                            unsigned NumResults) {
2034
  // Merge the results we were given with the results we cached.
2035
716
  bool AddedResult = false;
2036
716
  uint64_t InContexts =
2037
716
      Context.getKind() == CodeCompletionContext::CCC_Recovery
2038
716
        ? 
NormalContexts1
:
(1LL << Context.getKind())715
;
2039
  // Contains the set of names that are hidden by "local" completion results.
2040
716
  llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
2041
716
  using Result = CodeCompletionResult;
2042
716
  SmallVector<Result, 8> AllResults;
2043
716
  for (ASTUnit::cached_completion_iterator
2044
716
            C = AST.cached_completion_begin(),
2045
716
         CEnd = AST.cached_completion_end();
2046
93.8k
       C != CEnd; 
++C93.0k
) {
2047
    // If the context we are in matches any of the contexts we are
2048
    // interested in, we'll add this result.
2049
93.0k
    if ((C->ShowInContexts & InContexts) == 0)
2050
40.8k
      continue;
2051
2052
    // If we haven't added any results previously, do so now.
2053
52.2k
    if (!AddedResult) {
2054
156
      CalculateHiddenNames(Context, Results, NumResults, S.Context,
2055
156
                           HiddenNames);
2056
156
      AllResults.insert(AllResults.end(), Results, Results + NumResults);
2057
156
      AddedResult = true;
2058
156
    }
2059
2060
    // Determine whether this global completion result is hidden by a local
2061
    // completion result. If so, skip it.
2062
52.2k
    if (C->Kind != CXCursor_MacroDefinition &&
2063
52.2k
        
HiddenNames.count(C->Completion->getTypedText())743
)
2064
20
      continue;
2065
2066
    // Adjust priority based on similar type classes.
2067
52.2k
    unsigned Priority = C->Priority;
2068
52.2k
    CodeCompletionString *Completion = C->Completion;
2069
52.2k
    if (!Context.getPreferredType().isNull()) {
2070
13.7k
      if (C->Kind == CXCursor_MacroDefinition) {
2071
13.5k
        Priority = getMacroUsagePriority(C->Completion->getTypedText(),
2072
13.5k
                                         S.getLangOpts(),
2073
13.5k
                               Context.getPreferredType()->isAnyPointerType());
2074
13.5k
      } else 
if (200
C->Type200
) {
2075
200
        CanQualType Expected
2076
200
          = S.Context.getCanonicalType(
2077
200
                               Context.getPreferredType().getUnqualifiedType());
2078
200
        SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2079
200
        if (ExpectedSTC == C->TypeClass) {
2080
          // We know this type is similar; check for an exact match.
2081
60
          llvm::StringMap<unsigned> &CachedCompletionTypes
2082
60
            = AST.getCachedCompletionTypes();
2083
60
          llvm::StringMap<unsigned>::iterator Pos
2084
60
            = CachedCompletionTypes.find(QualType(Expected).getAsString());
2085
60
          if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2086
60
            Priority /= CCF_ExactTypeMatch;
2087
0
          else
2088
0
            Priority /= CCF_SimilarTypeMatch;
2089
60
        }
2090
200
      }
2091
13.7k
    }
2092
2093
    // Adjust the completion string, if required.
2094
52.2k
    if (C->Kind == CXCursor_MacroDefinition &&
2095
52.2k
        
Context.getKind() == CodeCompletionContext::CCC_MacroNameUse51.5k
) {
2096
      // Create a new code-completion string that just contains the
2097
      // macro name, without its arguments.
2098
1.96k
      CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2099
1.96k
                                    CCP_CodePattern, C->Availability);
2100
1.96k
      Builder.AddTypedTextChunk(C->Completion->getTypedText());
2101
1.96k
      Priority = CCP_CodePattern;
2102
1.96k
      Completion = Builder.TakeString();
2103
1.96k
    }
2104
2105
52.2k
    AllResults.push_back(Result(Completion, Priority, C->Kind,
2106
52.2k
                                C->Availability));
2107
52.2k
  }
2108
2109
  // If we did not add any cached completion results, just forward the
2110
  // results we were given to the next consumer.
2111
716
  if (!AddedResult) {
2112
560
    Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2113
560
    return;
2114
560
  }
2115
2116
156
  Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2117
156
                                  AllResults.size());
2118
156
}
2119
2120
void ASTUnit::CodeComplete(
2121
    StringRef File, unsigned Line, unsigned Column,
2122
    ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros,
2123
    bool IncludeCodePatterns, bool IncludeBriefComments,
2124
    CodeCompleteConsumer &Consumer,
2125
    std::shared_ptr<PCHContainerOperations> PCHContainerOps,
2126
    DiagnosticsEngine &Diag, LangOptions &LangOpts, SourceManager &SourceMgr,
2127
    FileManager &FileMgr, SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2128
721
    SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
2129
721
  if (!Invocation)
2130
0
    return;
2131
2132
721
  SimpleTimer CompletionTimer(WantTiming);
2133
721
  CompletionTimer.setOutput("Code completion @ " + File + ":" +
2134
721
                            Twine(Line) + ":" + Twine(Column));
2135
2136
721
  auto CCInvocation = std::make_shared<CompilerInvocation>(*Invocation);
2137
2138
721
  FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2139
721
  CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
2140
721
  PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
2141
2142
721
  CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2143
721
                                   CachedCompletionResults.empty();
2144
721
  CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2145
721
  CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2146
721
  CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2147
721
  CodeCompleteOpts.LoadExternal = Consumer.loadExternal();
2148
721
  CodeCompleteOpts.IncludeFixIts = Consumer.includeFixIts();
2149
2150
721
  assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2151
2152
0
  FrontendOpts.CodeCompletionAt.FileName = std::string(File);
2153
721
  FrontendOpts.CodeCompletionAt.Line = Line;
2154
721
  FrontendOpts.CodeCompletionAt.Column = Column;
2155
2156
  // Set the language options appropriately.
2157
721
  LangOpts = *CCInvocation->getLangOpts();
2158
2159
  // Spell-checking and warnings are wasteful during code-completion.
2160
721
  LangOpts.SpellChecking = false;
2161
721
  CCInvocation->getDiagnosticOpts().IgnoreWarnings = true;
2162
2163
721
  std::unique_ptr<CompilerInstance> Clang(
2164
721
      new CompilerInstance(PCHContainerOps));
2165
2166
  // Recover resources if we crash before exiting this method.
2167
721
  llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2168
721
    CICleanup(Clang.get());
2169
2170
721
  auto &Inv = *CCInvocation;
2171
721
  Clang->setInvocation(std::move(CCInvocation));
2172
721
  OriginalSourceFile =
2173
721
      std::string(Clang->getFrontendOpts().Inputs[0].getFile());
2174
2175
  // Set up diagnostics, capturing any diagnostics produced.
2176
721
  Clang->setDiagnostics(&Diag);
2177
721
  CaptureDroppedDiagnostics Capture(CaptureDiagsKind::All,
2178
721
                                    Clang->getDiagnostics(),
2179
721
                                    &StoredDiagnostics, nullptr);
2180
721
  ProcessWarningOptions(Diag, Inv.getDiagnosticOpts());
2181
2182
  // Create the target instance.
2183
721
  if (!Clang->createTarget()) {
2184
0
    Clang->setInvocation(nullptr);
2185
0
    return;
2186
0
  }
2187
2188
721
  assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
2189
721
         "Invocation must have exactly one source file!");
2190
0
  assert(Clang->getFrontendOpts().Inputs[0].getKind().getFormat() ==
2191
721
             InputKind::Source &&
2192
721
         "FIXME: AST inputs not yet supported here!");
2193
0
  assert(Clang->getFrontendOpts().Inputs[0].getKind().getLanguage() !=
2194
721
             Language::LLVM_IR &&
2195
721
         "IR inputs not support here!");
2196
2197
  // Use the source and file managers that we were given.
2198
0
  Clang->setFileManager(&FileMgr);
2199
721
  Clang->setSourceManager(&SourceMgr);
2200
2201
  // Remap files.
2202
721
  PreprocessorOpts.clearRemappedFiles();
2203
721
  PreprocessorOpts.RetainRemappedFileBuffers = true;
2204
721
  for (const auto &RemappedFile : RemappedFiles) {
2205
4
    PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second);
2206
4
    OwnedBuffers.push_back(RemappedFile.second);
2207
4
  }
2208
2209
  // Use the code completion consumer we were given, but adding any cached
2210
  // code-completion results.
2211
721
  AugmentedCodeCompleteConsumer *AugmentedConsumer
2212
721
    = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
2213
721
  Clang->setCodeCompletionConsumer(AugmentedConsumer);
2214
2215
721
  auto getUniqueID =
2216
721
      [&FileMgr](StringRef Filename) -> Optional<llvm::sys::fs::UniqueID> {
2217
0
    if (auto Status = FileMgr.getVirtualFileSystem().status(Filename))
2218
0
      return Status->getUniqueID();
2219
0
    return None;
2220
0
  };
2221
2222
721
  auto hasSameUniqueID = [getUniqueID](StringRef LHS, StringRef RHS) {
2223
84
    if (LHS == RHS)
2224
84
      return true;
2225
0
    if (auto LHSID = getUniqueID(LHS))
2226
0
      if (auto RHSID = getUniqueID(RHS))
2227
0
        return *LHSID == *RHSID;
2228
0
    return false;
2229
0
  };
2230
2231
  // If we have a precompiled preamble, try to use it. We only allow
2232
  // the use of the precompiled preamble if we're if the completion
2233
  // point is within the main file, after the end of the precompiled
2234
  // preamble.
2235
721
  std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer;
2236
721
  if (Preamble && 
Line > 184
&&
hasSameUniqueID(File, OriginalSourceFile)84
) {
2237
84
    OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(
2238
84
        PCHContainerOps, Inv, &FileMgr.getVirtualFileSystem(), false, Line - 1);
2239
84
  }
2240
2241
  // If the main file has been overridden due to the use of a preamble,
2242
  // make that override happen and introduce the preamble.
2243
721
  if (OverrideMainBuffer) {
2244
75
    assert(Preamble &&
2245
75
           "No preamble was built, but OverrideMainBuffer is not null");
2246
2247
0
    IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS =
2248
75
        &FileMgr.getVirtualFileSystem();
2249
75
    Preamble->AddImplicitPreamble(Clang->getInvocation(), VFS,
2250
75
                                  OverrideMainBuffer.get());
2251
    // FIXME: there is no way to update VFS if it was changed by
2252
    // AddImplicitPreamble as FileMgr is accepted as a parameter by this method.
2253
    // We use on-disk preambles instead and rely on FileMgr's VFS to ensure the
2254
    // PCH files are always readable.
2255
75
    OwnedBuffers.push_back(OverrideMainBuffer.release());
2256
646
  } else {
2257
646
    PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2258
646
    PreprocessorOpts.PrecompiledPreambleBytes.second = false;
2259
646
  }
2260
2261
  // Disable the preprocessing record if modules are not enabled.
2262
721
  if (!Clang->getLangOpts().Modules)
2263
707
    PreprocessorOpts.DetailedRecord = false;
2264
2265
721
  std::unique_ptr<SyntaxOnlyAction> Act;
2266
721
  Act.reset(new SyntaxOnlyAction);
2267
721
  if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
2268
721
    if (llvm::Error Err = Act->Execute()) {
2269
0
      consumeError(std::move(Err)); // FIXME this drops errors on the floor.
2270
0
    }
2271
721
    Act->EndSourceFile();
2272
721
  }
2273
721
}
2274
2275
62
bool ASTUnit::Save(StringRef File) {
2276
62
  if (HadModuleLoaderFatalFailure)
2277
0
    return true;
2278
2279
  // Write to a temporary file and later rename it to the actual file, to avoid
2280
  // possible race conditions.
2281
62
  SmallString<128> TempPath;
2282
62
  TempPath = File;
2283
62
  TempPath += "-%%%%%%%%";
2284
  // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2285
  // unconditionally create a stat cache when we parse the file?
2286
2287
62
  if (llvm::Error Err = llvm::writeFileAtomically(
2288
62
          TempPath, File, [this](llvm::raw_ostream &Out) {
2289
62
            return serialize(Out) ? llvm::make_error<llvm::StringError>(
2290
0
                                        "ASTUnit serialization failed",
2291
0
                                        llvm::inconvertibleErrorCode())
2292
62
                                  : llvm::Error::success();
2293
62
          })) {
2294
0
    consumeError(std::move(Err));
2295
0
    return true;
2296
0
  }
2297
62
  return false;
2298
62
}
2299
2300
static bool serializeUnit(ASTWriter &Writer,
2301
                          SmallVectorImpl<char> &Buffer,
2302
                          Sema &S,
2303
                          bool hasErrors,
2304
62
                          raw_ostream &OS) {
2305
62
  Writer.WriteAST(S, std::string(), nullptr, "", hasErrors);
2306
2307
  // Write the generated bitstream to "Out".
2308
62
  if (!Buffer.empty())
2309
62
    OS.write(Buffer.data(), Buffer.size());
2310
2311
62
  return false;
2312
62
}
2313
2314
62
bool ASTUnit::serialize(raw_ostream &OS) {
2315
  // For serialization we are lenient if the errors were only warn-as-error kind.
2316
62
  bool hasErrors = getDiagnostics().hasUncompilableErrorOccurred();
2317
2318
62
  if (WriterData)
2319
58
    return serializeUnit(WriterData->Writer, WriterData->Buffer,
2320
58
                         getSema(), hasErrors, OS);
2321
2322
4
  SmallString<128> Buffer;
2323
4
  llvm::BitstreamWriter Stream(Buffer);
2324
4
  InMemoryModuleCache ModuleCache;
2325
4
  ASTWriter Writer(Stream, Buffer, ModuleCache, {});
2326
4
  return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
2327
62
}
2328
2329
using SLocRemap = ContinuousRangeMap<unsigned, int, 2>;
2330
2331
void ASTUnit::TranslateStoredDiagnostics(
2332
                          FileManager &FileMgr,
2333
                          SourceManager &SrcMgr,
2334
                          const SmallVectorImpl<StandaloneDiagnostic> &Diags,
2335
258
                          SmallVectorImpl<StoredDiagnostic> &Out) {
2336
  // Map the standalone diagnostic into the new source manager. We also need to
2337
  // remap all the locations to the new view. This includes the diag location,
2338
  // any associated source ranges, and the source ranges of associated fix-its.
2339
  // FIXME: There should be a cleaner way to do this.
2340
258
  SmallVector<StoredDiagnostic, 4> Result;
2341
258
  Result.reserve(Diags.size());
2342
2343
258
  for (const auto &SD : Diags) {
2344
    // Rebuild the StoredDiagnostic.
2345
85
    if (SD.Filename.empty())
2346
0
      continue;
2347
85
    auto FE = FileMgr.getFile(SD.Filename);
2348
85
    if (!FE)
2349
0
      continue;
2350
85
    SourceLocation FileLoc;
2351
85
    auto ItFileID = PreambleSrcLocCache.find(SD.Filename);
2352
85
    if (ItFileID == PreambleSrcLocCache.end()) {
2353
15
      FileID FID = SrcMgr.translateFile(*FE);
2354
15
      FileLoc = SrcMgr.getLocForStartOfFile(FID);
2355
15
      PreambleSrcLocCache[SD.Filename] = FileLoc;
2356
70
    } else {
2357
70
      FileLoc = ItFileID->getValue();
2358
70
    }
2359
2360
85
    if (FileLoc.isInvalid())
2361
0
      continue;
2362
85
    SourceLocation L = FileLoc.getLocWithOffset(SD.LocOffset);
2363
85
    FullSourceLoc Loc(L, SrcMgr);
2364
2365
85
    SmallVector<CharSourceRange, 4> Ranges;
2366
85
    Ranges.reserve(SD.Ranges.size());
2367
85
    for (const auto &Range : SD.Ranges) {
2368
38
      SourceLocation BL = FileLoc.getLocWithOffset(Range.first);
2369
38
      SourceLocation EL = FileLoc.getLocWithOffset(Range.second);
2370
38
      Ranges.push_back(CharSourceRange::getCharRange(BL, EL));
2371
38
    }
2372
2373
85
    SmallVector<FixItHint, 2> FixIts;
2374
85
    FixIts.reserve(SD.FixIts.size());
2375
85
    for (const auto &FixIt : SD.FixIts) {
2376
9
      FixIts.push_back(FixItHint());
2377
9
      FixItHint &FH = FixIts.back();
2378
9
      FH.CodeToInsert = FixIt.CodeToInsert;
2379
9
      SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first);
2380
9
      SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second);
2381
9
      FH.RemoveRange = CharSourceRange::getCharRange(BL, EL);
2382
9
    }
2383
2384
85
    Result.push_back(StoredDiagnostic(SD.Level, SD.ID,
2385
85
                                      SD.Message, Loc, Ranges, FixIts));
2386
85
  }
2387
258
  Result.swap(Out);
2388
258
}
2389
2390
29.6k
void ASTUnit::addFileLevelDecl(Decl *D) {
2391
29.6k
  assert(D);
2392
2393
  // We only care about local declarations.
2394
29.6k
  if (D->isFromASTFile())
2395
6
    return;
2396
2397
29.6k
  SourceManager &SM = *SourceMgr;
2398
29.6k
  SourceLocation Loc = D->getLocation();
2399
29.6k
  if (Loc.isInvalid() || 
!SM.isLocalSourceLocation(Loc)29.1k
)
2400
562
    return;
2401
2402
  // We only keep track of the file-level declarations of each file.
2403
29.1k
  if (!D->getLexicalDeclContext()->isFileContext())
2404
265
    return;
2405
2406
28.8k
  SourceLocation FileLoc = SM.getFileLoc(Loc);
2407
28.8k
  assert(SM.isLocalSourceLocation(FileLoc));
2408
0
  FileID FID;
2409
28.8k
  unsigned Offset;
2410
28.8k
  std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2411
28.8k
  if (FID.isInvalid())
2412
0
    return;
2413
2414
28.8k
  std::unique_ptr<LocDeclsTy> &Decls = FileDecls[FID];
2415
28.8k
  if (!Decls)
2416
6.91k
    Decls = std::make_unique<LocDeclsTy>();
2417
2418
28.8k
  std::pair<unsigned, Decl *> LocDecl(Offset, D);
2419
2420
28.8k
  if (Decls->empty() || 
Decls->back().first <= Offset21.9k
) {
2421
28.6k
    Decls->push_back(LocDecl);
2422
28.6k
    return;
2423
28.6k
  }
2424
2425
192
  LocDeclsTy::iterator I =
2426
192
      llvm::upper_bound(*Decls, LocDecl, llvm::less_first());
2427
2428
192
  Decls->insert(I, LocDecl);
2429
192
}
2430
2431
void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2432
9.54k
                                  SmallVectorImpl<Decl *> &Decls) {
2433
9.54k
  if (File.isInvalid())
2434
0
    return;
2435
2436
9.54k
  if (SourceMgr->isLoadedFileID(File)) {
2437
9.16k
    assert(Ctx->getExternalSource() && "No external source!");
2438
0
    return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2439
9.16k
                                                         Decls);
2440
9.16k
  }
2441
2442
385
  FileDeclsTy::iterator I = FileDecls.find(File);
2443
385
  if (I == FileDecls.end())
2444
20
    return;
2445
2446
365
  LocDeclsTy &LocDecls = *I->second;
2447
365
  if (LocDecls.empty())
2448
0
    return;
2449
2450
365
  LocDeclsTy::iterator BeginIt =
2451
1.25k
      llvm::partition_point(LocDecls, [=](std::pair<unsigned, Decl *> LD) {
2452
1.25k
        return LD.first < Offset;
2453
1.25k
      });
2454
365
  if (BeginIt != LocDecls.begin())
2455
293
    --BeginIt;
2456
2457
  // If we are pointing at a top-level decl inside an objc container, we need
2458
  // to backtrack until we find it otherwise we will fail to report that the
2459
  // region overlaps with an objc container.
2460
373
  while (BeginIt != LocDecls.begin() &&
2461
373
         
BeginIt->second->isTopLevelDeclInObjCContainer()272
)
2462
8
    --BeginIt;
2463
2464
365
  LocDeclsTy::iterator EndIt = llvm::upper_bound(
2465
365
      LocDecls, std::make_pair(Offset + Length, (Decl *)nullptr),
2466
365
      llvm::less_first());
2467
365
  if (EndIt != LocDecls.end())
2468
257
    ++EndIt;
2469
2470
1.30k
  for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; 
++DIt938
)
2471
938
    Decls.push_back(DIt->second);
2472
365
}
2473
2474
SourceLocation ASTUnit::getLocation(const FileEntry *File,
2475
9.58k
                                    unsigned Line, unsigned Col) const {
2476
9.58k
  const SourceManager &SM = getSourceManager();
2477
9.58k
  SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
2478
9.58k
  return SM.getMacroArgExpandedLocation(Loc);
2479
9.58k
}
2480
2481
SourceLocation ASTUnit::getLocation(const FileEntry *File,
2482
0
                                    unsigned Offset) const {
2483
0
  const SourceManager &SM = getSourceManager();
2484
0
  SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
2485
0
  return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2486
0
}
2487
2488
/// If \arg Loc is a loaded location from the preamble, returns
2489
/// the corresponding local location of the main file, otherwise it returns
2490
/// \arg Loc.
2491
462k
SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) const {
2492
462k
  FileID PreambleID;
2493
462k
  if (SourceMgr)
2494
462k
    PreambleID = SourceMgr->getPreambleFileID();
2495
2496
462k
  if (Loc.isInvalid() || !Preamble || 
PreambleID.isInvalid()15.6k
)
2497
446k
    return Loc;
2498
2499
15.6k
  unsigned Offs;
2500
15.6k
  if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && 
Offs < Preamble->getBounds().Size314
) {
2501
314
    SourceLocation FileLoc
2502
314
        = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2503
314
    return FileLoc.getLocWithOffset(Offs);
2504
314
  }
2505
2506
15.3k
  return Loc;
2507
15.6k
}
2508
2509
/// If \arg Loc is a local location of the main file but inside the
2510
/// preamble chunk, returns the corresponding loaded location from the
2511
/// preamble, otherwise it returns \arg Loc.
2512
81.7k
SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) const {
2513
81.7k
  FileID PreambleID;
2514
81.7k
  if (SourceMgr)
2515
81.7k
    PreambleID = SourceMgr->getPreambleFileID();
2516
2517
81.7k
  if (Loc.isInvalid() || 
!Preamble19.3k
||
PreambleID.isInvalid()363
)
2518
81.3k
    return Loc;
2519
2520
363
  unsigned Offs;
2521
363
  if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2522
363
      
Offs < Preamble->getBounds().Size225
) {
2523
72
    SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2524
72
    return FileLoc.getLocWithOffset(Offs);
2525
72
  }
2526
2527
291
  return Loc;
2528
363
}
2529
2530
9.59k
bool ASTUnit::isInPreambleFileID(SourceLocation Loc) const {
2531
9.59k
  FileID FID;
2532
9.59k
  if (SourceMgr)
2533
9.59k
    FID = SourceMgr->getPreambleFileID();
2534
2535
9.59k
  if (Loc.isInvalid() || FID.isInvalid())
2536
9.45k
    return false;
2537
2538
141
  return SourceMgr->isInFileID(Loc, FID);
2539
9.59k
}
2540
2541
29
bool ASTUnit::isInMainFileID(SourceLocation Loc) const {
2542
29
  FileID FID;
2543
29
  if (SourceMgr)
2544
29
    FID = SourceMgr->getMainFileID();
2545
2546
29
  if (Loc.isInvalid() || 
FID.isInvalid()28
)
2547
1
    return false;
2548
2549
28
  return SourceMgr->isInFileID(Loc, FID);
2550
29
}
2551
2552
7
SourceLocation ASTUnit::getEndOfPreambleFileID() const {
2553
7
  FileID FID;
2554
7
  if (SourceMgr)
2555
7
    FID = SourceMgr->getPreambleFileID();
2556
2557
7
  if (FID.isInvalid())
2558
0
    return {};
2559
2560
7
  return SourceMgr->getLocForEndOfFile(FID);
2561
7
}
2562
2563
9
SourceLocation ASTUnit::getStartOfMainFileID() const {
2564
9
  FileID FID;
2565
9
  if (SourceMgr)
2566
9
    FID = SourceMgr->getMainFileID();
2567
2568
9
  if (FID.isInvalid())
2569
0
    return {};
2570
2571
9
  return SourceMgr->getLocForStartOfFile(FID);
2572
9
}
2573
2574
llvm::iterator_range<PreprocessingRecord::iterator>
2575
9
ASTUnit::getLocalPreprocessingEntities() const {
2576
9
  if (isMainFileAST()) {
2577
9
    serialization::ModuleFile &
2578
9
      Mod = Reader->getModuleManager().getPrimaryModule();
2579
9
    return Reader->getModulePreprocessedEntities(Mod);
2580
9
  }
2581
2582
0
  if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2583
0
    return llvm::make_range(PPRec->local_begin(), PPRec->local_end());
2584
2585
0
  return llvm::make_range(PreprocessingRecord::iterator(),
2586
0
                          PreprocessingRecord::iterator());
2587
0
}
2588
2589
11
bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
2590
11
  if (isMainFileAST()) {
2591
11
    serialization::ModuleFile &
2592
11
      Mod = Reader->getModuleManager().getPrimaryModule();
2593
66
    for (const auto *D : Reader->getModuleFileLevelDecls(Mod)) {
2594
66
      if (!Fn(context, D))
2595
0
        return false;
2596
66
    }
2597
2598
11
    return true;
2599
11
  }
2600
2601
0
  for (ASTUnit::top_level_iterator TL = top_level_begin(),
2602
0
                                TLEnd = top_level_end();
2603
0
         TL != TLEnd; ++TL) {
2604
0
    if (!Fn(context, *TL))
2605
0
      return false;
2606
0
  }
2607
2608
0
  return true;
2609
0
}
2610
2611
9
const FileEntry *ASTUnit::getPCHFile() {
2612
9
  if (!Reader)
2613
0
    return nullptr;
2614
2615
9
  serialization::ModuleFile *Mod = nullptr;
2616
13
  Reader->getModuleManager().visit([&Mod](serialization::ModuleFile &M) {
2617
13
    switch (M.Kind) {
2618
4
    case serialization::MK_ImplicitModule:
2619
4
    case serialization::MK_ExplicitModule:
2620
4
    case serialization::MK_PrebuiltModule:
2621
4
      return true; // skip dependencies.
2622
0
    case serialization::MK_PCH:
2623
0
      Mod = &M;
2624
0
      return true; // found it.
2625
0
    case serialization::MK_Preamble:
2626
0
      return false; // look in dependencies.
2627
9
    case serialization::MK_MainFile:
2628
9
      return false; // look in dependencies.
2629
13
    }
2630
2631
0
    return true;
2632
13
  });
2633
9
  if (Mod)
2634
0
    return Mod->File;
2635
2636
9
  return nullptr;
2637
9
}
2638
2639
9
bool ASTUnit::isModuleFile() const {
2640
9
  return isMainFileAST() && getLangOpts().isCompilingModule();
2641
9
}
2642
2643
15
InputKind ASTUnit::getInputKind() const {
2644
15
  auto &LangOpts = getLangOpts();
2645
2646
15
  Language Lang;
2647
15
  if (LangOpts.OpenCL)
2648
0
    Lang = Language::OpenCL;
2649
15
  else if (LangOpts.CUDA)
2650
0
    Lang = Language::CUDA;
2651
15
  else if (LangOpts.RenderScript)
2652
0
    Lang = Language::RenderScript;
2653
15
  else if (LangOpts.CPlusPlus)
2654
11
    Lang = LangOpts.ObjC ? 
Language::ObjCXX0
: Language::CXX;
2655
4
  else
2656
4
    Lang = LangOpts.ObjC ? Language::ObjC : 
Language::C0
;
2657
2658
15
  InputKind::Format Fmt = InputKind::Source;
2659
15
  if (LangOpts.getCompilingModule() == LangOptions::CMK_ModuleMap)
2660
13
    Fmt = InputKind::ModuleMap;
2661
2662
  // We don't know if input was preprocessed. Assume not.
2663
15
  bool PP = false;
2664
2665
15
  return InputKind(Lang, Fmt, PP);
2666
15
}
2667
2668
#ifndef NDEBUG
2669
7.63k
ASTUnit::ConcurrencyState::ConcurrencyState() {
2670
7.63k
  Mutex = new std::recursive_mutex;
2671
7.63k
}
2672
2673
7.62k
ASTUnit::ConcurrencyState::~ConcurrencyState() {
2674
7.62k
  delete static_cast<std::recursive_mutex *>(Mutex);
2675
7.62k
}
2676
2677
20.8k
void ASTUnit::ConcurrencyState::start() {
2678
20.8k
  bool acquired = static_cast<std::recursive_mutex *>(Mutex)->try_lock();
2679
20.8k
  assert(acquired && "Concurrent access to ASTUnit!");
2680
20.8k
}
2681
2682
20.8k
void ASTUnit::ConcurrencyState::finish() {
2683
20.8k
  static_cast<std::recursive_mutex *>(Mutex)->unlock();
2684
20.8k
}
2685
2686
#else // NDEBUG
2687
2688
ASTUnit::ConcurrencyState::ConcurrencyState() { Mutex = nullptr; }
2689
ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2690
void ASTUnit::ConcurrencyState::start() {}
2691
void ASTUnit::ConcurrencyState::finish() {}
2692
2693
#endif // NDEBUG