1 //===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // ASTUnit Implementation.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Frontend/ASTUnit.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/DeclVisitor.h"
18 #include "clang/AST/TypeOrdering.h"
19 #include "clang/AST/StmtVisitor.h"
20 #include "clang/Frontend/CompilerInstance.h"
21 #include "clang/Frontend/FrontendActions.h"
22 #include "clang/Frontend/FrontendDiagnostic.h"
23 #include "clang/Frontend/FrontendOptions.h"
24 #include "clang/Frontend/MultiplexConsumer.h"
25 #include "clang/Frontend/Utils.h"
26 #include "clang/Serialization/ASTReader.h"
27 #include "clang/Serialization/ASTWriter.h"
28 #include "clang/Lex/HeaderSearch.h"
29 #include "clang/Lex/Preprocessor.h"
30 #include "clang/Lex/PreprocessorOptions.h"
31 #include "clang/Basic/TargetOptions.h"
32 #include "clang/Basic/TargetInfo.h"
33 #include "clang/Basic/Diagnostic.h"
34 #include "llvm/ADT/ArrayRef.h"
35 #include "llvm/ADT/StringExtras.h"
36 #include "llvm/ADT/StringSet.h"
37 #include "llvm/Support/Atomic.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/Host.h"
40 #include "llvm/Support/Path.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/Support/Timer.h"
43 #include "llvm/Support/FileSystem.h"
44 #include "llvm/Support/Mutex.h"
45 #include "llvm/Support/MutexGuard.h"
46 #include "llvm/Support/CrashRecoveryContext.h"
50 using namespace clang;
52 using llvm::TimeRecord;
61 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
63 Start = TimeRecord::getCurrentTime();
66 void setOutput(const Twine &Output) {
68 this->Output = Output.str();
73 TimeRecord Elapsed = TimeRecord::getCurrentTime();
75 llvm::errs() << Output << ':';
76 Elapsed.print(Elapsed, llvm::errs());
83 /// \brief The file in which the precompiled preamble is stored.
84 std::string PreambleFile;
86 /// \brief Temporary files that should be removed when the ASTUnit is
88 SmallVector<llvm::sys::Path, 4> TemporaryFiles;
90 /// \brief Erase temporary files.
91 void CleanTemporaryFiles();
93 /// \brief Erase the preamble file.
94 void CleanPreambleFile();
96 /// \brief Erase temporary files and the preamble file.
101 static llvm::sys::SmartMutex<false> &getOnDiskMutex() {
102 static llvm::sys::SmartMutex<false> M(/* recursive = */ true);
106 static void cleanupOnDiskMapAtExit(void);
108 typedef llvm::DenseMap<const ASTUnit *, OnDiskData *> OnDiskDataMap;
109 static OnDiskDataMap &getOnDiskDataMap() {
110 static OnDiskDataMap M;
111 static bool hasRegisteredAtExit = false;
112 if (!hasRegisteredAtExit) {
113 hasRegisteredAtExit = true;
114 atexit(cleanupOnDiskMapAtExit);
119 static void cleanupOnDiskMapAtExit(void) {
120 // Use the mutex because there can be an alive thread destroying an ASTUnit.
121 llvm::MutexGuard Guard(getOnDiskMutex());
122 OnDiskDataMap &M = getOnDiskDataMap();
123 for (OnDiskDataMap::iterator I = M.begin(), E = M.end(); I != E; ++I) {
124 // We don't worry about freeing the memory associated with OnDiskDataMap.
125 // All we care about is erasing stale files.
126 I->second->Cleanup();
130 static OnDiskData &getOnDiskData(const ASTUnit *AU) {
131 // We require the mutex since we are modifying the structure of the
133 llvm::MutexGuard Guard(getOnDiskMutex());
134 OnDiskDataMap &M = getOnDiskDataMap();
135 OnDiskData *&D = M[AU];
137 D = new OnDiskData();
141 static void erasePreambleFile(const ASTUnit *AU) {
142 getOnDiskData(AU).CleanPreambleFile();
145 static void removeOnDiskEntry(const ASTUnit *AU) {
146 // We require the mutex since we are modifying the structure of the
148 llvm::MutexGuard Guard(getOnDiskMutex());
149 OnDiskDataMap &M = getOnDiskDataMap();
150 OnDiskDataMap::iterator I = M.find(AU);
152 I->second->Cleanup();
158 static void setPreambleFile(const ASTUnit *AU, llvm::StringRef preambleFile) {
159 getOnDiskData(AU).PreambleFile = preambleFile;
162 static const std::string &getPreambleFile(const ASTUnit *AU) {
163 return getOnDiskData(AU).PreambleFile;
166 void OnDiskData::CleanTemporaryFiles() {
167 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
168 TemporaryFiles[I].eraseFromDisk();
169 TemporaryFiles.clear();
172 void OnDiskData::CleanPreambleFile() {
173 if (!PreambleFile.empty()) {
174 llvm::sys::Path(PreambleFile).eraseFromDisk();
175 PreambleFile.clear();
179 void OnDiskData::Cleanup() {
180 CleanTemporaryFiles();
184 struct ASTUnit::ASTWriterData {
185 SmallString<128> Buffer;
186 llvm::BitstreamWriter Stream;
189 ASTWriterData() : Stream(Buffer), Writer(Stream) { }
192 void ASTUnit::clearFileLevelDecls() {
193 for (FileDeclsTy::iterator
194 I = FileDecls.begin(), E = FileDecls.end(); I != E; ++I)
199 void ASTUnit::CleanTemporaryFiles() {
200 getOnDiskData(this).CleanTemporaryFiles();
203 void ASTUnit::addTemporaryFile(const llvm::sys::Path &TempFile) {
204 getOnDiskData(this).TemporaryFiles.push_back(TempFile);
207 /// \brief After failing to build a precompiled preamble (due to
208 /// errors in the source that occurs in the preamble), the number of
209 /// reparses during which we'll skip even trying to precompile the
211 const unsigned DefaultPreambleRebuildInterval = 5;
213 /// \brief Tracks the number of ASTUnit objects that are currently active.
215 /// Used for debugging purposes only.
216 static llvm::sys::cas_flag ActiveASTUnitObjects;
218 ASTUnit::ASTUnit(bool _MainFileIsAST)
219 : Reader(0), OnlyLocalDecls(false), CaptureDiagnostics(false),
220 MainFileIsAST(_MainFileIsAST),
221 TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
222 OwnsRemappedFileBuffers(true),
223 NumStoredDiagnosticsFromDriver(0),
224 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
225 NumWarningsInPreamble(0),
226 ShouldCacheCodeCompletionResults(false),
227 IncludeBriefCommentsInCodeCompletion(false), UserFilesAreVolatile(false),
228 CompletionCacheTopLevelHashValue(0),
229 PreambleTopLevelHashValue(0),
230 CurrentTopLevelHashValue(0),
231 UnsafeToFree(false) {
232 if (getenv("LIBCLANG_OBJTRACKING")) {
233 llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
234 fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
238 ASTUnit::~ASTUnit() {
239 clearFileLevelDecls();
241 // Clean up the temporary files and the preamble file.
242 removeOnDiskEntry(this);
244 // Free the buffers associated with remapped files. We are required to
245 // perform this operation here because we explicitly request that the
246 // compiler instance *not* free these buffers for each invocation of the
248 if (Invocation.getPtr() && OwnsRemappedFileBuffers) {
249 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
250 for (PreprocessorOptions::remapped_file_buffer_iterator
251 FB = PPOpts.remapped_file_buffer_begin(),
252 FBEnd = PPOpts.remapped_file_buffer_end();
258 delete SavedMainFileBuffer;
259 delete PreambleBuffer;
261 ClearCachedCompletionResults();
263 if (getenv("LIBCLANG_OBJTRACKING")) {
264 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
265 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
269 void ASTUnit::setPreprocessor(Preprocessor *pp) { PP = pp; }
271 /// \brief Determine the set of code-completion contexts in which this
272 /// declaration should be shown.
273 static unsigned getDeclShowContexts(NamedDecl *ND,
274 const LangOptions &LangOpts,
275 bool &IsNestedNameSpecifier) {
276 IsNestedNameSpecifier = false;
278 if (isa<UsingShadowDecl>(ND))
279 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
283 uint64_t Contexts = 0;
284 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
285 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
286 // Types can appear in these contexts.
287 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
288 Contexts |= (1LL << CodeCompletionContext::CCC_TopLevel)
289 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
290 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
291 | (1LL << CodeCompletionContext::CCC_Statement)
292 | (1LL << CodeCompletionContext::CCC_Type)
293 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
295 // In C++, types can appear in expressions contexts (for functional casts).
296 if (LangOpts.CPlusPlus)
297 Contexts |= (1LL << CodeCompletionContext::CCC_Expression);
299 // In Objective-C, message sends can send interfaces. In Objective-C++,
300 // all types are available due to functional casts.
301 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
302 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
304 // In Objective-C, you can only be a subclass of another Objective-C class
305 if (isa<ObjCInterfaceDecl>(ND))
306 Contexts |= (1LL << CodeCompletionContext::CCC_ObjCInterfaceName);
308 // Deal with tag names.
309 if (isa<EnumDecl>(ND)) {
310 Contexts |= (1LL << CodeCompletionContext::CCC_EnumTag);
312 // Part of the nested-name-specifier in C++0x.
313 if (LangOpts.CPlusPlus0x)
314 IsNestedNameSpecifier = true;
315 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
316 if (Record->isUnion())
317 Contexts |= (1LL << CodeCompletionContext::CCC_UnionTag);
319 Contexts |= (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
321 if (LangOpts.CPlusPlus)
322 IsNestedNameSpecifier = true;
323 } else if (isa<ClassTemplateDecl>(ND))
324 IsNestedNameSpecifier = true;
325 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
326 // Values can appear in these contexts.
327 Contexts = (1LL << CodeCompletionContext::CCC_Statement)
328 | (1LL << CodeCompletionContext::CCC_Expression)
329 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
330 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver);
331 } else if (isa<ObjCProtocolDecl>(ND)) {
332 Contexts = (1LL << CodeCompletionContext::CCC_ObjCProtocolName);
333 } else if (isa<ObjCCategoryDecl>(ND)) {
334 Contexts = (1LL << CodeCompletionContext::CCC_ObjCCategoryName);
335 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
336 Contexts = (1LL << CodeCompletionContext::CCC_Namespace);
338 // Part of the nested-name-specifier.
339 IsNestedNameSpecifier = true;
345 void ASTUnit::CacheCodeCompletionResults() {
349 SimpleTimer Timer(WantTiming);
350 Timer.setOutput("Cache global code completions for " + getMainFileName());
352 // Clear out the previous results.
353 ClearCachedCompletionResults();
355 // Gather the set of global code completions.
356 typedef CodeCompletionResult Result;
357 SmallVector<Result, 8> Results;
358 CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
359 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator,
360 getCodeCompletionTUInfo(), Results);
362 // Translate global code completions into cached completions.
363 llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
365 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
366 switch (Results[I].Kind) {
367 case Result::RK_Declaration: {
368 bool IsNestedNameSpecifier = false;
369 CachedCodeCompletionResult CachedResult;
370 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
371 *CachedCompletionAllocator,
372 getCodeCompletionTUInfo(),
373 IncludeBriefCommentsInCodeCompletion);
374 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
376 IsNestedNameSpecifier);
377 CachedResult.Priority = Results[I].Priority;
378 CachedResult.Kind = Results[I].CursorKind;
379 CachedResult.Availability = Results[I].Availability;
381 // Keep track of the type of this completion in an ASTContext-agnostic
383 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
384 if (UsageType.isNull()) {
385 CachedResult.TypeClass = STC_Void;
386 CachedResult.Type = 0;
388 CanQualType CanUsageType
389 = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
390 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
392 // Determine whether we have already seen this type. If so, we save
393 // ourselves the work of formatting the type string by using the
394 // temporary, CanQualType-based hash table to find the associated value.
395 unsigned &TypeValue = CompletionTypes[CanUsageType];
396 if (TypeValue == 0) {
397 TypeValue = CompletionTypes.size();
398 CachedCompletionTypes[QualType(CanUsageType).getAsString()]
402 CachedResult.Type = TypeValue;
405 CachedCompletionResults.push_back(CachedResult);
407 /// Handle nested-name-specifiers in C++.
408 if (TheSema->Context.getLangOpts().CPlusPlus &&
409 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
410 // The contexts in which a nested-name-specifier can appear in C++.
412 = (1LL << CodeCompletionContext::CCC_TopLevel)
413 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
414 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
415 | (1LL << CodeCompletionContext::CCC_Statement)
416 | (1LL << CodeCompletionContext::CCC_Expression)
417 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
418 | (1LL << CodeCompletionContext::CCC_EnumTag)
419 | (1LL << CodeCompletionContext::CCC_UnionTag)
420 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag)
421 | (1LL << CodeCompletionContext::CCC_Type)
422 | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName)
423 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression);
425 if (isa<NamespaceDecl>(Results[I].Declaration) ||
426 isa<NamespaceAliasDecl>(Results[I].Declaration))
427 NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace);
429 if (unsigned RemainingContexts
430 = NNSContexts & ~CachedResult.ShowInContexts) {
431 // If there any contexts where this completion can be a
432 // nested-name-specifier but isn't already an option, create a
433 // nested-name-specifier completion.
434 Results[I].StartsNestedNameSpecifier = true;
435 CachedResult.Completion
436 = Results[I].CreateCodeCompletionString(*TheSema,
437 *CachedCompletionAllocator,
438 getCodeCompletionTUInfo(),
439 IncludeBriefCommentsInCodeCompletion);
440 CachedResult.ShowInContexts = RemainingContexts;
441 CachedResult.Priority = CCP_NestedNameSpecifier;
442 CachedResult.TypeClass = STC_Void;
443 CachedResult.Type = 0;
444 CachedCompletionResults.push_back(CachedResult);
450 case Result::RK_Keyword:
451 case Result::RK_Pattern:
452 // Ignore keywords and patterns; we don't care, since they are so
453 // easily regenerated.
456 case Result::RK_Macro: {
457 CachedCodeCompletionResult CachedResult;
458 CachedResult.Completion
459 = Results[I].CreateCodeCompletionString(*TheSema,
460 *CachedCompletionAllocator,
461 getCodeCompletionTUInfo(),
462 IncludeBriefCommentsInCodeCompletion);
463 CachedResult.ShowInContexts
464 = (1LL << CodeCompletionContext::CCC_TopLevel)
465 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
466 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
467 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
468 | (1LL << CodeCompletionContext::CCC_ClassStructUnion)
469 | (1LL << CodeCompletionContext::CCC_Statement)
470 | (1LL << CodeCompletionContext::CCC_Expression)
471 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
472 | (1LL << CodeCompletionContext::CCC_MacroNameUse)
473 | (1LL << CodeCompletionContext::CCC_PreprocessorExpression)
474 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
475 | (1LL << CodeCompletionContext::CCC_OtherWithMacros);
477 CachedResult.Priority = Results[I].Priority;
478 CachedResult.Kind = Results[I].CursorKind;
479 CachedResult.Availability = Results[I].Availability;
480 CachedResult.TypeClass = STC_Void;
481 CachedResult.Type = 0;
482 CachedCompletionResults.push_back(CachedResult);
488 // Save the current top-level hash value.
489 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
492 void ASTUnit::ClearCachedCompletionResults() {
493 CachedCompletionResults.clear();
494 CachedCompletionTypes.clear();
495 CachedCompletionAllocator = 0;
500 /// \brief Gathers information from ASTReader that will be used to initialize
502 class ASTInfoCollector : public ASTReaderListener {
505 LangOptions &LangOpt;
507 IntrusiveRefCntPtr<TargetOptions> &TargetOpts;
508 IntrusiveRefCntPtr<TargetInfo> &Target;
511 unsigned NumHeaderInfos;
513 bool InitializedLanguage;
515 ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
517 IntrusiveRefCntPtr<TargetOptions> &TargetOpts,
518 IntrusiveRefCntPtr<TargetInfo> &Target,
520 : PP(PP), Context(Context), LangOpt(LangOpt), HSI(HSI),
521 TargetOpts(TargetOpts), Target(Target),
522 Counter(Counter), NumHeaderInfos(0),
523 InitializedLanguage(false) {}
525 virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
527 if (InitializedLanguage)
531 InitializedLanguage = true;
537 virtual bool ReadTargetOptions(const TargetOptions &TargetOpts,
539 // If we've already initialized the target, don't do it again.
543 this->TargetOpts = new TargetOptions(TargetOpts);
544 Target = TargetInfo::CreateTargetInfo(PP.getDiagnostics(),
551 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
552 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
555 virtual void ReadCounter(const serialization::ModuleFile &M, unsigned Value) {
561 if (!Target || !InitializedLanguage)
564 // Inform the target of the language options.
566 // FIXME: We shouldn't need to do this, the target should be immutable once
567 // created. This complexity should be lifted elsewhere.
568 Target->setForcedLangOptions(LangOpt);
570 // Initialize the preprocessor.
571 PP.Initialize(*Target);
573 // Initialize the ASTContext
574 Context.InitBuiltinTypes(*Target);
578 class StoredDiagnosticConsumer : public DiagnosticConsumer {
579 SmallVectorImpl<StoredDiagnostic> &StoredDiags;
582 explicit StoredDiagnosticConsumer(
583 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
584 : StoredDiags(StoredDiags) { }
586 virtual void HandleDiagnostic(DiagnosticsEngine::Level Level,
587 const Diagnostic &Info);
589 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
590 // Just drop any diagnostics that come from cloned consumers; they'll
591 // have different source managers anyway.
592 // FIXME: We'd like to be able to capture these somehow, even if it's just
593 // file/line/column, because they could occur when parsing module maps or
594 // building modules on-demand.
595 return new IgnoringDiagConsumer();
599 /// \brief RAII object that optionally captures diagnostics, if
600 /// there is no diagnostic client to capture them already.
601 class CaptureDroppedDiagnostics {
602 DiagnosticsEngine &Diags;
603 StoredDiagnosticConsumer Client;
604 DiagnosticConsumer *PreviousClient;
607 CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
608 SmallVectorImpl<StoredDiagnostic> &StoredDiags)
609 : Diags(Diags), Client(StoredDiags), PreviousClient(0)
611 if (RequestCapture || Diags.getClient() == 0) {
612 PreviousClient = Diags.takeClient();
613 Diags.setClient(&Client);
617 ~CaptureDroppedDiagnostics() {
618 if (Diags.getClient() == &Client) {
620 Diags.setClient(PreviousClient);
625 } // anonymous namespace
627 void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
628 const Diagnostic &Info) {
629 // Default implementation (Warnings/errors count).
630 DiagnosticConsumer::HandleDiagnostic(Level, Info);
632 StoredDiags.push_back(StoredDiagnostic(Level, Info));
635 ASTDeserializationListener *ASTUnit::getDeserializationListener() {
637 return &WriterData->Writer;
641 llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
642 std::string *ErrorStr) {
644 return FileMgr->getBufferForFile(Filename, ErrorStr);
647 /// \brief Configure the diagnostics object for use with ASTUnit.
648 void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
649 const char **ArgBegin, const char **ArgEnd,
650 ASTUnit &AST, bool CaptureDiagnostics) {
651 if (!Diags.getPtr()) {
652 // No diagnostics engine was provided, so create our own diagnostics object
653 // with the default options.
654 DiagnosticConsumer *Client = 0;
655 if (CaptureDiagnostics)
656 Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
657 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions(),
660 /*ShouldOwnClient=*/true,
661 /*ShouldCloneClient=*/false);
662 } else if (CaptureDiagnostics) {
663 Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
667 ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
668 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
669 const FileSystemOptions &FileSystemOpts,
671 RemappedFile *RemappedFiles,
672 unsigned NumRemappedFiles,
673 bool CaptureDiagnostics,
674 bool AllowPCHWithCompilerErrors,
675 bool UserFilesAreVolatile) {
676 OwningPtr<ASTUnit> AST(new ASTUnit(true));
678 // Recover resources if we crash before exiting this method.
679 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
680 ASTUnitCleanup(AST.get());
681 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
682 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
683 DiagCleanup(Diags.getPtr());
685 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
687 AST->OnlyLocalDecls = OnlyLocalDecls;
688 AST->CaptureDiagnostics = CaptureDiagnostics;
689 AST->Diagnostics = Diags;
690 AST->FileMgr = new FileManager(FileSystemOpts);
691 AST->UserFilesAreVolatile = UserFilesAreVolatile;
692 AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
693 AST->getFileManager(),
694 UserFilesAreVolatile);
695 AST->HSOpts = new HeaderSearchOptions();
697 AST->HeaderInfo.reset(new HeaderSearch(AST->HSOpts,
698 AST->getFileManager(),
699 AST->getDiagnostics(),
700 AST->ASTFileLangOpts,
703 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
704 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
705 if (const llvm::MemoryBuffer *
706 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
707 // Create the file entry for the file that we're mapping from.
708 const FileEntry *FromFile
709 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
710 memBuf->getBufferSize(),
713 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
714 << RemappedFiles[I].first;
719 // Override the contents of the "from" file with the contents of
721 AST->getSourceManager().overrideFileContents(FromFile, memBuf);
724 const char *fname = fileOrBuf.get<const char *>();
725 const FileEntry *ToFile = AST->FileMgr->getFile(fname);
727 AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file)
728 << RemappedFiles[I].first << fname;
732 // Create the file entry for the file that we're mapping from.
733 const FileEntry *FromFile
734 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
738 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
739 << RemappedFiles[I].first;
744 // Override the contents of the "from" file with the contents of
746 AST->getSourceManager().overrideFileContents(FromFile, ToFile);
750 // Gather Info for preprocessor construction later on.
752 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
755 OwningPtr<ASTReader> Reader;
757 AST->PP = new Preprocessor(new PreprocessorOptions(),
758 AST->getDiagnostics(), AST->ASTFileLangOpts,
759 /*Target=*/0, AST->getSourceManager(), HeaderInfo,
762 /*OwnsHeaderSearch=*/false,
763 /*DelayInitialization=*/true);
764 Preprocessor &PP = *AST->PP;
766 AST->Ctx = new ASTContext(AST->ASTFileLangOpts,
767 AST->getSourceManager(),
769 PP.getIdentifierTable(),
770 PP.getSelectorTable(),
772 /* size_reserve = */0,
773 /*DelayInitialization=*/true);
774 ASTContext &Context = *AST->Ctx;
776 bool disableValid = false;
777 if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION"))
779 Reader.reset(new ASTReader(PP, Context,
781 /*DisableValidation=*/disableValid,
782 AllowPCHWithCompilerErrors));
784 // Recover resources if we crash before exiting this method.
785 llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
786 ReaderCleanup(Reader.get());
788 Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
789 AST->ASTFileLangOpts, HeaderInfo,
790 AST->TargetOpts, AST->Target,
793 switch (Reader->ReadAST(Filename, serialization::MK_MainFile,
794 ASTReader::ARR_None)) {
795 case ASTReader::Success:
798 case ASTReader::Failure:
799 case ASTReader::OutOfDate:
800 case ASTReader::VersionMismatch:
801 case ASTReader::ConfigurationMismatch:
802 case ASTReader::HadErrors:
803 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
807 AST->OriginalSourceFile = Reader->getOriginalSourceFile();
809 PP.setCounterValue(Counter);
811 // Attach the AST reader to the AST context as an external AST
812 // source, so that declarations will be deserialized from the
813 // AST file as needed.
814 ASTReader *ReaderPtr = Reader.get();
815 OwningPtr<ExternalASTSource> Source(Reader.take());
817 // Unregister the cleanup for ASTReader. It will get cleaned up
818 // by the ASTUnit cleanup.
819 ReaderCleanup.unregister();
821 Context.setExternalSource(Source);
823 // Create an AST consumer, even though it isn't used.
824 AST->Consumer.reset(new ASTConsumer);
826 // Create a semantic analysis object and tell the AST reader about it.
827 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
828 AST->TheSema->Initialize();
829 ReaderPtr->InitializeSema(*AST->TheSema);
830 AST->Reader = ReaderPtr;
837 /// \brief Preprocessor callback class that updates a hash value with the names
838 /// of all macros that have been defined by the translation unit.
839 class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
843 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
845 virtual void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI) {
846 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
850 /// \brief Add the given declaration to the hash of all top-level entities.
851 void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
855 DeclContext *DC = D->getDeclContext();
859 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
862 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
863 if (ND->getIdentifier())
864 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
865 else if (DeclarationName Name = ND->getDeclName()) {
866 std::string NameStr = Name.getAsString();
867 Hash = llvm::HashString(NameStr, Hash);
873 class TopLevelDeclTrackerConsumer : public ASTConsumer {
878 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
879 : Unit(_Unit), Hash(Hash) {
883 void handleTopLevelDecl(Decl *D) {
887 // FIXME: Currently ObjC method declarations are incorrectly being
888 // reported as top-level declarations, even though their DeclContext
889 // is the containing ObjC @interface/@implementation. This is a
890 // fundamental problem in the parser right now.
891 if (isa<ObjCMethodDecl>(D))
894 AddTopLevelDeclarationToHash(D, Hash);
895 Unit.addTopLevelDecl(D);
897 handleFileLevelDecl(D);
900 void handleFileLevelDecl(Decl *D) {
901 Unit.addFileLevelDecl(D);
902 if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
903 for (NamespaceDecl::decl_iterator
904 I = NSD->decls_begin(), E = NSD->decls_end(); I != E; ++I)
905 handleFileLevelDecl(*I);
909 bool HandleTopLevelDecl(DeclGroupRef D) {
910 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
911 handleTopLevelDecl(*it);
915 // We're not interested in "interesting" decls.
916 void HandleInterestingDecl(DeclGroupRef) {}
918 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
919 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
920 handleTopLevelDecl(*it);
923 virtual ASTDeserializationListener *GetASTDeserializationListener() {
924 return Unit.getDeserializationListener();
928 class TopLevelDeclTrackerAction : public ASTFrontendAction {
932 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
934 CI.getPreprocessor().addPPCallbacks(
935 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
936 return new TopLevelDeclTrackerConsumer(Unit,
937 Unit.getCurrentTopLevelHashValue());
941 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
943 virtual bool hasCodeCompletionSupport() const { return false; }
944 virtual TranslationUnitKind getTranslationUnitKind() {
945 return Unit.getTranslationUnitKind();
949 class PrecompilePreambleConsumer : public PCHGenerator {
952 std::vector<Decl *> TopLevelDecls;
955 PrecompilePreambleConsumer(ASTUnit &Unit, const Preprocessor &PP,
956 StringRef isysroot, raw_ostream *Out)
957 : PCHGenerator(PP, "", 0, isysroot, Out), Unit(Unit),
958 Hash(Unit.getCurrentTopLevelHashValue()) {
962 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
963 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
965 // FIXME: Currently ObjC method declarations are incorrectly being
966 // reported as top-level declarations, even though their DeclContext
967 // is the containing ObjC @interface/@implementation. This is a
968 // fundamental problem in the parser right now.
969 if (isa<ObjCMethodDecl>(D))
971 AddTopLevelDeclarationToHash(D, Hash);
972 TopLevelDecls.push_back(D);
977 virtual void HandleTranslationUnit(ASTContext &Ctx) {
978 PCHGenerator::HandleTranslationUnit(Ctx);
979 if (!Unit.getDiagnostics().hasErrorOccurred()) {
980 // Translate the top-level declarations we captured during
981 // parsing into declaration IDs in the precompiled
982 // preamble. This will allow us to deserialize those top-level
983 // declarations when requested.
984 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
985 Unit.addTopLevelDeclFromPreamble(
986 getWriter().getDeclID(TopLevelDecls[I]));
991 class PrecompilePreambleAction : public ASTFrontendAction {
995 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
997 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
1000 std::string OutputFile;
1001 raw_ostream *OS = 0;
1002 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
1007 if (!CI.getFrontendOpts().RelocatablePCH)
1010 CI.getPreprocessor().addPPCallbacks(
1011 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
1012 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Sysroot,
1016 virtual bool hasCodeCompletionSupport() const { return false; }
1017 virtual bool hasASTFileSupport() const { return false; }
1018 virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
1023 static void checkAndRemoveNonDriverDiags(SmallVectorImpl<StoredDiagnostic> &
1024 StoredDiagnostics) {
1025 // Get rid of stored diagnostics except the ones from the driver which do not
1026 // have a source location.
1027 for (unsigned I = 0; I < StoredDiagnostics.size(); ++I) {
1028 if (StoredDiagnostics[I].getLocation().isValid()) {
1029 StoredDiagnostics.erase(StoredDiagnostics.begin()+I);
1035 static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> &
1037 SourceManager &SM) {
1038 // The stored diagnostic has the old source manager in it; update
1039 // the locations to refer into the new source manager. Since we've
1040 // been careful to make sure that the source manager's state
1041 // before and after are identical, so that we can reuse the source
1043 for (unsigned I = 0, N = StoredDiagnostics.size(); I < N; ++I) {
1044 if (StoredDiagnostics[I].getLocation().isValid()) {
1045 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SM);
1046 StoredDiagnostics[I].setLocation(Loc);
1051 /// Parse the source file into a translation unit using the given compiler
1052 /// invocation, replacing the current translation unit.
1054 /// \returns True if a failure occurred that causes the ASTUnit not to
1055 /// contain any translation-unit information, false otherwise.
1056 bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
1057 delete SavedMainFileBuffer;
1058 SavedMainFileBuffer = 0;
1061 delete OverrideMainBuffer;
1065 // Create the compiler instance to use for building the AST.
1066 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1068 // Recover resources if we crash before exiting this method.
1069 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1070 CICleanup(Clang.get());
1072 IntrusiveRefCntPtr<CompilerInvocation>
1073 CCInvocation(new CompilerInvocation(*Invocation));
1075 Clang->setInvocation(CCInvocation.getPtr());
1076 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1078 // Set up diagnostics, capturing any diagnostics that would
1079 // otherwise be dropped.
1080 Clang->setDiagnostics(&getDiagnostics());
1082 // Create the target instance.
1083 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1084 Clang->getTargetOpts()));
1085 if (!Clang->hasTarget()) {
1086 delete OverrideMainBuffer;
1090 // Inform the target of the language options.
1092 // FIXME: We shouldn't need to do this, the target should be immutable once
1093 // created. This complexity should be lifted elsewhere.
1094 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1096 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1097 "Invocation must have exactly one source file!");
1098 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
1099 "FIXME: AST inputs not yet supported here!");
1100 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
1101 "IR inputs not support here!");
1103 // Configure the various subsystems.
1104 // FIXME: Should we retain the previous file manager?
1105 LangOpts = &Clang->getLangOpts();
1106 FileSystemOpts = Clang->getFileSystemOpts();
1107 FileMgr = new FileManager(FileSystemOpts);
1108 SourceMgr = new SourceManager(getDiagnostics(), *FileMgr,
1109 UserFilesAreVolatile);
1115 // Clear out old caches and data.
1116 TopLevelDecls.clear();
1117 clearFileLevelDecls();
1118 CleanTemporaryFiles();
1120 if (!OverrideMainBuffer) {
1121 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1122 TopLevelDeclsInPreamble.clear();
1125 // Create a file manager object to provide access to and cache the filesystem.
1126 Clang->setFileManager(&getFileManager());
1128 // Create the source manager.
1129 Clang->setSourceManager(&getSourceManager());
1131 // If the main file has been overridden due to the use of a preamble,
1132 // make that override happen and introduce the preamble.
1133 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
1134 if (OverrideMainBuffer) {
1135 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1136 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1137 PreprocessorOpts.PrecompiledPreambleBytes.second
1138 = PreambleEndsAtStartOfLine;
1139 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
1140 PreprocessorOpts.DisablePCHValidation = true;
1142 // The stored diagnostic has the old source manager in it; update
1143 // the locations to refer into the new source manager. Since we've
1144 // been careful to make sure that the source manager's state
1145 // before and after are identical, so that we can reuse the source
1147 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
1149 // Keep track of the override buffer;
1150 SavedMainFileBuffer = OverrideMainBuffer;
1153 OwningPtr<TopLevelDeclTrackerAction> Act(
1154 new TopLevelDeclTrackerAction(*this));
1156 // Recover resources if we crash before exiting this method.
1157 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1158 ActCleanup(Act.get());
1160 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0]))
1163 if (OverrideMainBuffer) {
1164 std::string ModName = getPreambleFile(this);
1165 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
1166 getSourceManager(), PreambleDiagnostics,
1170 if (!Act->Execute())
1173 transferASTDataFromCompilerInstance(*Clang);
1175 Act->EndSourceFile();
1177 FailedParseDiagnostics.clear();
1182 // Remove the overridden buffer we used for the preamble.
1183 if (OverrideMainBuffer) {
1184 delete OverrideMainBuffer;
1185 SavedMainFileBuffer = 0;
1188 // Keep the ownership of the data in the ASTUnit because the client may
1189 // want to see the diagnostics.
1190 transferASTDataFromCompilerInstance(*Clang);
1191 FailedParseDiagnostics.swap(StoredDiagnostics);
1192 StoredDiagnostics.clear();
1193 NumStoredDiagnosticsFromDriver = 0;
1197 /// \brief Simple function to retrieve a path for a preamble precompiled header.
1198 static std::string GetPreamblePCHPath() {
1199 // FIXME: This is lame; sys::Path should provide this function (in particular,
1200 // it should know how to find the temporary files dir).
1201 // FIXME: This is really lame. I copied this code from the Driver!
1202 // FIXME: This is a hack so that we can override the preamble file during
1203 // crash-recovery testing, which is the only case where the preamble files
1204 // are not necessarily cleaned up.
1205 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1210 const char *TmpDir = ::getenv("TMPDIR");
1212 TmpDir = ::getenv("TEMP");
1214 TmpDir = ::getenv("TMP");
1215 #ifdef LLVM_ON_WIN32
1217 TmpDir = ::getenv("USERPROFILE");
1221 llvm::sys::Path P(TmpDir);
1222 P.createDirectoryOnDisk(true);
1223 P.appendComponent("preamble");
1224 P.appendSuffix("pch");
1225 if (P.makeUnique(/*reuse_current=*/false, /*ErrMsg*/0))
1226 return std::string();
1231 /// \brief Compute the preamble for the main file, providing the source buffer
1232 /// that corresponds to the main file along with a pair (bytes, start-of-line)
1233 /// that describes the preamble.
1234 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
1235 ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1236 unsigned MaxLines, bool &CreatedBuffer) {
1237 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
1238 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
1239 CreatedBuffer = false;
1241 // Try to determine if the main file has been remapped, either from the
1242 // command line (to another file) or directly through the compiler invocation
1243 // (to a memory buffer).
1244 llvm::MemoryBuffer *Buffer = 0;
1245 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].getFile());
1246 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1247 // Check whether there is a file-file remapping of the main file
1248 for (PreprocessorOptions::remapped_file_iterator
1249 M = PreprocessorOpts.remapped_file_begin(),
1250 E = PreprocessorOpts.remapped_file_end();
1253 llvm::sys::PathWithStatus MPath(M->first);
1254 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1255 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1256 // We found a remapping. Try to load the resulting, remapped source.
1257 if (CreatedBuffer) {
1259 CreatedBuffer = false;
1262 Buffer = getBufferForFile(M->second);
1264 return std::make_pair((llvm::MemoryBuffer*)0,
1265 std::make_pair(0, true));
1266 CreatedBuffer = true;
1271 // Check whether there is a file-buffer remapping. It supercedes the
1272 // file-file remapping.
1273 for (PreprocessorOptions::remapped_file_buffer_iterator
1274 M = PreprocessorOpts.remapped_file_buffer_begin(),
1275 E = PreprocessorOpts.remapped_file_buffer_end();
1278 llvm::sys::PathWithStatus MPath(M->first);
1279 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1280 if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1281 // We found a remapping.
1282 if (CreatedBuffer) {
1284 CreatedBuffer = false;
1287 Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
1293 // If the main source file was not remapped, load it now.
1295 Buffer = getBufferForFile(FrontendOpts.Inputs[0].getFile());
1297 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
1299 CreatedBuffer = true;
1302 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
1303 *Invocation.getLangOpts(),
1307 static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
1309 StringRef NewName) {
1310 llvm::MemoryBuffer *Result
1311 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1312 memcpy(const_cast<char*>(Result->getBufferStart()),
1313 Old->getBufferStart(), Old->getBufferSize());
1314 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
1315 ' ', NewSize - Old->getBufferSize() - 1);
1316 const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
1321 /// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1322 /// the source file.
1324 /// This routine will compute the preamble of the main source file. If a
1325 /// non-trivial preamble is found, it will precompile that preamble into a
1326 /// precompiled header so that the precompiled preamble can be used to reduce
1327 /// reparsing time. If a precompiled preamble has already been constructed,
1328 /// this routine will determine if it is still valid and, if so, avoid
1329 /// rebuilding the precompiled preamble.
1331 /// \param AllowRebuild When true (the default), this routine is
1332 /// allowed to rebuild the precompiled preamble if it is found to be
1335 /// \param MaxLines When non-zero, the maximum number of lines that
1336 /// can occur within the preamble.
1338 /// \returns If the precompiled preamble can be used, returns a newly-allocated
1339 /// buffer that should be used in place of the main file when doing so.
1340 /// Otherwise, returns a NULL pointer.
1341 llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
1342 const CompilerInvocation &PreambleInvocationIn,
1344 unsigned MaxLines) {
1346 IntrusiveRefCntPtr<CompilerInvocation>
1347 PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1348 FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
1349 PreprocessorOptions &PreprocessorOpts
1350 = PreambleInvocation->getPreprocessorOpts();
1352 bool CreatedPreambleBuffer = false;
1353 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
1354 = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
1356 // If ComputePreamble() Take ownership of the preamble buffer.
1357 OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
1358 if (CreatedPreambleBuffer)
1359 OwnedPreambleBuffer.reset(NewPreamble.first);
1361 if (!NewPreamble.second.first) {
1362 // We couldn't find a preamble in the main source. Clear out the current
1363 // preamble, if we have one. It's obviously no good any more.
1365 erasePreambleFile(this);
1367 // The next time we actually see a preamble, precompile it.
1368 PreambleRebuildCounter = 1;
1372 if (!Preamble.empty()) {
1373 // We've previously computed a preamble. Check whether we have the same
1374 // preamble now that we did before, and that there's enough space in
1375 // the main-file buffer within the precompiled preamble to fit the
1377 if (Preamble.size() == NewPreamble.second.first &&
1378 PreambleEndsAtStartOfLine == NewPreamble.second.second &&
1379 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
1380 memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
1381 NewPreamble.second.first) == 0) {
1382 // The preamble has not changed. We may be able to re-use the precompiled
1385 // Check that none of the files used by the preamble have changed.
1386 bool AnyFileChanged = false;
1388 // First, make a record of those files that have been overridden via
1389 // remapping or unsaved_files.
1390 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1391 for (PreprocessorOptions::remapped_file_iterator
1392 R = PreprocessorOpts.remapped_file_begin(),
1393 REnd = PreprocessorOpts.remapped_file_end();
1394 !AnyFileChanged && R != REnd;
1396 struct stat StatBuf;
1397 if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
1398 // If we can't stat the file we're remapping to, assume that something
1399 // horrible happened.
1400 AnyFileChanged = true;
1404 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1407 for (PreprocessorOptions::remapped_file_buffer_iterator
1408 R = PreprocessorOpts.remapped_file_buffer_begin(),
1409 REnd = PreprocessorOpts.remapped_file_buffer_end();
1410 !AnyFileChanged && R != REnd;
1412 // FIXME: Should we actually compare the contents of file->buffer
1414 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1418 // Check whether anything has changed.
1419 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1420 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1421 !AnyFileChanged && F != FEnd;
1423 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1424 = OverriddenFiles.find(F->first());
1425 if (Overridden != OverriddenFiles.end()) {
1426 // This file was remapped; check whether the newly-mapped file
1427 // matches up with the previous mapping.
1428 if (Overridden->second != F->second)
1429 AnyFileChanged = true;
1433 // The file was not remapped; check whether it has changed on disk.
1434 struct stat StatBuf;
1435 if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
1436 // If we can't stat the file, assume that something horrible happened.
1437 AnyFileChanged = true;
1438 } else if (StatBuf.st_size != F->second.first ||
1439 StatBuf.st_mtime != F->second.second)
1440 AnyFileChanged = true;
1443 if (!AnyFileChanged) {
1444 // Okay! We can re-use the precompiled preamble.
1446 // Set the state of the diagnostic object to mimic its state
1447 // after parsing the preamble.
1448 getDiagnostics().Reset();
1449 ProcessWarningOptions(getDiagnostics(),
1450 PreambleInvocation->getDiagnosticOpts());
1451 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1453 // Create a version of the main file buffer that is padded to
1454 // buffer size we reserved when creating the preamble.
1455 return CreatePaddedMainFileBuffer(NewPreamble.first,
1456 PreambleReservedSize,
1457 FrontendOpts.Inputs[0].getFile());
1461 // If we aren't allowed to rebuild the precompiled preamble, just
1466 // We can't reuse the previously-computed preamble. Build a new one.
1468 PreambleDiagnostics.clear();
1469 erasePreambleFile(this);
1470 PreambleRebuildCounter = 1;
1471 } else if (!AllowRebuild) {
1472 // We aren't allowed to rebuild the precompiled preamble; just
1477 // If the preamble rebuild counter > 1, it's because we previously
1478 // failed to build a preamble and we're not yet ready to try
1479 // again. Decrement the counter and return a failure.
1480 if (PreambleRebuildCounter > 1) {
1481 --PreambleRebuildCounter;
1485 // Create a temporary file for the precompiled preamble. In rare
1486 // circumstances, this can fail.
1487 std::string PreamblePCHPath = GetPreamblePCHPath();
1488 if (PreamblePCHPath.empty()) {
1489 // Try again next time.
1490 PreambleRebuildCounter = 1;
1494 // We did not previously compute a preamble, or it can't be reused anyway.
1495 SimpleTimer PreambleTimer(WantTiming);
1496 PreambleTimer.setOutput("Precompiling preamble");
1498 // Create a new buffer that stores the preamble. The buffer also contains
1499 // extra space for the original contents of the file (which will be present
1500 // when we actually parse the file) along with more room in case the file
1502 PreambleReservedSize = NewPreamble.first->getBufferSize();
1503 if (PreambleReservedSize < 4096)
1504 PreambleReservedSize = 8191;
1506 PreambleReservedSize *= 2;
1508 // Save the preamble text for later; we'll need to compare against it for
1509 // subsequent reparses.
1510 StringRef MainFilename = PreambleInvocation->getFrontendOpts().Inputs[0].getFile();
1511 Preamble.assign(FileMgr->getFile(MainFilename),
1512 NewPreamble.first->getBufferStart(),
1513 NewPreamble.first->getBufferStart()
1514 + NewPreamble.second.first);
1515 PreambleEndsAtStartOfLine = NewPreamble.second.second;
1517 delete PreambleBuffer;
1519 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
1520 FrontendOpts.Inputs[0].getFile());
1521 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
1522 NewPreamble.first->getBufferStart(), Preamble.size());
1523 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
1524 ' ', PreambleReservedSize - Preamble.size() - 1);
1525 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
1527 // Remap the main source file to the preamble buffer.
1528 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].getFile());
1529 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1531 // Tell the compiler invocation to generate a temporary precompiled header.
1532 FrontendOpts.ProgramAction = frontend::GeneratePCH;
1533 // FIXME: Generate the precompiled header into memory?
1534 FrontendOpts.OutputFile = PreamblePCHPath;
1535 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1536 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
1538 // Create the compiler instance to use for building the precompiled preamble.
1539 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1541 // Recover resources if we crash before exiting this method.
1542 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1543 CICleanup(Clang.get());
1545 Clang->setInvocation(&*PreambleInvocation);
1546 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1548 // Set up diagnostics, capturing all of the diagnostics produced.
1549 Clang->setDiagnostics(&getDiagnostics());
1551 // Create the target instance.
1552 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1553 Clang->getTargetOpts()));
1554 if (!Clang->hasTarget()) {
1555 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1557 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1558 PreprocessorOpts.eraseRemappedFile(
1559 PreprocessorOpts.remapped_file_buffer_end() - 1);
1563 // Inform the target of the language options.
1565 // FIXME: We shouldn't need to do this, the target should be immutable once
1566 // created. This complexity should be lifted elsewhere.
1567 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1569 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1570 "Invocation must have exactly one source file!");
1571 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
1572 "FIXME: AST inputs not yet supported here!");
1573 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
1574 "IR inputs not support here!");
1576 // Clear out old caches and data.
1577 getDiagnostics().Reset();
1578 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
1579 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1580 TopLevelDecls.clear();
1581 TopLevelDeclsInPreamble.clear();
1583 // Create a file manager object to provide access to and cache the filesystem.
1584 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
1586 // Create the source manager.
1587 Clang->setSourceManager(new SourceManager(getDiagnostics(),
1588 Clang->getFileManager()));
1590 OwningPtr<PrecompilePreambleAction> Act;
1591 Act.reset(new PrecompilePreambleAction(*this));
1592 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1593 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1595 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1596 PreprocessorOpts.eraseRemappedFile(
1597 PreprocessorOpts.remapped_file_buffer_end() - 1);
1602 Act->EndSourceFile();
1604 if (Diagnostics->hasErrorOccurred()) {
1605 // There were errors parsing the preamble, so no precompiled header was
1606 // generated. Forget that we even tried.
1607 // FIXME: Should we leave a note for ourselves to try again?
1608 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1610 TopLevelDeclsInPreamble.clear();
1611 PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1612 PreprocessorOpts.eraseRemappedFile(
1613 PreprocessorOpts.remapped_file_buffer_end() - 1);
1617 // Transfer any diagnostics generated when parsing the preamble into the set
1618 // of preamble diagnostics.
1619 PreambleDiagnostics.clear();
1620 PreambleDiagnostics.insert(PreambleDiagnostics.end(),
1621 stored_diag_afterDriver_begin(), stored_diag_end());
1622 checkAndRemoveNonDriverDiags(StoredDiagnostics);
1624 // Keep track of the preamble we precompiled.
1625 setPreambleFile(this, FrontendOpts.OutputFile);
1626 NumWarningsInPreamble = getDiagnostics().getNumWarnings();
1628 // Keep track of all of the files that the source manager knows about,
1629 // so we can verify whether they have changed or not.
1630 FilesInPreamble.clear();
1631 SourceManager &SourceMgr = Clang->getSourceManager();
1632 const llvm::MemoryBuffer *MainFileBuffer
1633 = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1634 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1635 FEnd = SourceMgr.fileinfo_end();
1638 const FileEntry *File = F->second->OrigEntry;
1639 if (!File || F->second->getRawBuffer() == MainFileBuffer)
1642 FilesInPreamble[File->getName()]
1643 = std::make_pair(F->second->getSize(), File->getModificationTime());
1646 PreambleRebuildCounter = 1;
1647 PreprocessorOpts.eraseRemappedFile(
1648 PreprocessorOpts.remapped_file_buffer_end() - 1);
1650 // If the hash of top-level entities differs from the hash of the top-level
1651 // entities the last time we rebuilt the preamble, clear out the completion
1653 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1654 CompletionCacheTopLevelHashValue = 0;
1655 PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1658 return CreatePaddedMainFileBuffer(NewPreamble.first,
1659 PreambleReservedSize,
1660 FrontendOpts.Inputs[0].getFile());
1663 void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1664 std::vector<Decl *> Resolved;
1665 Resolved.reserve(TopLevelDeclsInPreamble.size());
1666 ExternalASTSource &Source = *getASTContext().getExternalSource();
1667 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1668 // Resolve the declaration ID to an actual declaration, possibly
1669 // deserializing the declaration in the process.
1670 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1672 Resolved.push_back(D);
1674 TopLevelDeclsInPreamble.clear();
1675 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1678 void ASTUnit::transferASTDataFromCompilerInstance(CompilerInstance &CI) {
1679 // Steal the created target, context, and preprocessor.
1680 TheSema.reset(CI.takeSema());
1681 Consumer.reset(CI.takeASTConsumer());
1682 Ctx = &CI.getASTContext();
1683 PP = &CI.getPreprocessor();
1684 CI.setSourceManager(0);
1685 CI.setFileManager(0);
1686 Target = &CI.getTarget();
1687 Reader = CI.getModuleManager();
1690 StringRef ASTUnit::getMainFileName() const {
1691 return Invocation->getFrontendOpts().Inputs[0].getFile();
1694 ASTUnit *ASTUnit::create(CompilerInvocation *CI,
1695 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1696 bool CaptureDiagnostics,
1697 bool UserFilesAreVolatile) {
1698 OwningPtr<ASTUnit> AST;
1699 AST.reset(new ASTUnit(false));
1700 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
1701 AST->Diagnostics = Diags;
1702 AST->Invocation = CI;
1703 AST->FileSystemOpts = CI->getFileSystemOpts();
1704 AST->FileMgr = new FileManager(AST->FileSystemOpts);
1705 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1706 AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr,
1707 UserFilesAreVolatile);
1712 ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
1713 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1714 ASTFrontendAction *Action,
1717 StringRef ResourceFilesPath,
1718 bool OnlyLocalDecls,
1719 bool CaptureDiagnostics,
1720 bool PrecompilePreamble,
1721 bool CacheCodeCompletionResults,
1722 bool IncludeBriefCommentsInCodeCompletion,
1723 bool UserFilesAreVolatile,
1724 OwningPtr<ASTUnit> *ErrAST) {
1725 assert(CI && "A CompilerInvocation is required");
1727 OwningPtr<ASTUnit> OwnAST;
1728 ASTUnit *AST = Unit;
1730 // Create the AST unit.
1731 OwnAST.reset(create(CI, Diags, CaptureDiagnostics, UserFilesAreVolatile));
1735 if (!ResourceFilesPath.empty()) {
1736 // Override the resources path.
1737 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1739 AST->OnlyLocalDecls = OnlyLocalDecls;
1740 AST->CaptureDiagnostics = CaptureDiagnostics;
1741 if (PrecompilePreamble)
1742 AST->PreambleRebuildCounter = 2;
1743 AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
1744 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1745 AST->IncludeBriefCommentsInCodeCompletion
1746 = IncludeBriefCommentsInCodeCompletion;
1748 // Recover resources if we crash before exiting this method.
1749 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1750 ASTUnitCleanup(OwnAST.get());
1751 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1752 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1753 DiagCleanup(Diags.getPtr());
1755 // We'll manage file buffers ourselves.
1756 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1757 CI->getFrontendOpts().DisableFree = false;
1758 ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1760 // Create the compiler instance to use for building the AST.
1761 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1763 // Recover resources if we crash before exiting this method.
1764 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1765 CICleanup(Clang.get());
1767 Clang->setInvocation(CI);
1768 AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
1770 // Set up diagnostics, capturing any diagnostics that would
1771 // otherwise be dropped.
1772 Clang->setDiagnostics(&AST->getDiagnostics());
1774 // Create the target instance.
1775 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1776 Clang->getTargetOpts()));
1777 if (!Clang->hasTarget())
1780 // Inform the target of the language options.
1782 // FIXME: We shouldn't need to do this, the target should be immutable once
1783 // created. This complexity should be lifted elsewhere.
1784 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1786 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1787 "Invocation must have exactly one source file!");
1788 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
1789 "FIXME: AST inputs not yet supported here!");
1790 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
1791 "IR inputs not supported here!");
1793 // Configure the various subsystems.
1794 AST->TheSema.reset();
1799 // Create a file manager object to provide access to and cache the filesystem.
1800 Clang->setFileManager(&AST->getFileManager());
1802 // Create the source manager.
1803 Clang->setSourceManager(&AST->getSourceManager());
1805 ASTFrontendAction *Act = Action;
1807 OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
1809 TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1810 Act = TrackerAct.get();
1813 // Recover resources if we crash before exiting this method.
1814 llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1815 ActCleanup(TrackerAct.get());
1817 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
1818 AST->transferASTDataFromCompilerInstance(*Clang);
1819 if (OwnAST && ErrAST)
1820 ErrAST->swap(OwnAST);
1825 if (Persistent && !TrackerAct) {
1826 Clang->getPreprocessor().addPPCallbacks(
1827 new MacroDefinitionTrackerPPCallbacks(AST->getCurrentTopLevelHashValue()));
1828 std::vector<ASTConsumer*> Consumers;
1829 if (Clang->hasASTConsumer())
1830 Consumers.push_back(Clang->takeASTConsumer());
1831 Consumers.push_back(new TopLevelDeclTrackerConsumer(*AST,
1832 AST->getCurrentTopLevelHashValue()));
1833 Clang->setASTConsumer(new MultiplexConsumer(Consumers));
1835 if (!Act->Execute()) {
1836 AST->transferASTDataFromCompilerInstance(*Clang);
1837 if (OwnAST && ErrAST)
1838 ErrAST->swap(OwnAST);
1843 // Steal the created target, context, and preprocessor.
1844 AST->transferASTDataFromCompilerInstance(*Clang);
1846 Act->EndSourceFile();
1849 return OwnAST.take();
1854 bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1858 // We'll manage file buffers ourselves.
1859 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1860 Invocation->getFrontendOpts().DisableFree = false;
1861 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1863 llvm::MemoryBuffer *OverrideMainBuffer = 0;
1864 if (PrecompilePreamble) {
1865 PreambleRebuildCounter = 2;
1867 = getMainBufferWithPrecompiledPreamble(*Invocation);
1870 SimpleTimer ParsingTimer(WantTiming);
1871 ParsingTimer.setOutput("Parsing " + getMainFileName());
1873 // Recover resources if we crash before exiting this method.
1874 llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1875 MemBufferCleanup(OverrideMainBuffer);
1877 return Parse(OverrideMainBuffer);
1880 ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1881 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1882 bool OnlyLocalDecls,
1883 bool CaptureDiagnostics,
1884 bool PrecompilePreamble,
1885 TranslationUnitKind TUKind,
1886 bool CacheCodeCompletionResults,
1887 bool IncludeBriefCommentsInCodeCompletion,
1888 bool UserFilesAreVolatile) {
1889 // Create the AST unit.
1890 OwningPtr<ASTUnit> AST;
1891 AST.reset(new ASTUnit(false));
1892 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
1893 AST->Diagnostics = Diags;
1894 AST->OnlyLocalDecls = OnlyLocalDecls;
1895 AST->CaptureDiagnostics = CaptureDiagnostics;
1896 AST->TUKind = TUKind;
1897 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1898 AST->IncludeBriefCommentsInCodeCompletion
1899 = IncludeBriefCommentsInCodeCompletion;
1900 AST->Invocation = CI;
1901 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1903 // Recover resources if we crash before exiting this method.
1904 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1905 ASTUnitCleanup(AST.get());
1906 llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1907 llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1908 DiagCleanup(Diags.getPtr());
1910 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
1913 ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1914 const char **ArgEnd,
1915 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1916 StringRef ResourceFilesPath,
1917 bool OnlyLocalDecls,
1918 bool CaptureDiagnostics,
1919 RemappedFile *RemappedFiles,
1920 unsigned NumRemappedFiles,
1921 bool RemappedFilesKeepOriginalName,
1922 bool PrecompilePreamble,
1923 TranslationUnitKind TUKind,
1924 bool CacheCodeCompletionResults,
1925 bool IncludeBriefCommentsInCodeCompletion,
1926 bool AllowPCHWithCompilerErrors,
1927 bool SkipFunctionBodies,
1928 bool UserFilesAreVolatile,
1929 bool ForSerialization,
1930 OwningPtr<ASTUnit> *ErrAST) {
1931 if (!Diags.getPtr()) {
1932 // No diagnostics engine was provided, so create our own diagnostics object
1933 // with the default options.
1934 Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions(),
1939 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1941 IntrusiveRefCntPtr<CompilerInvocation> CI;
1945 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
1948 CI = clang::createInvocationFromCommandLine(
1949 llvm::makeArrayRef(ArgBegin, ArgEnd),
1955 // Override any files that need remapping
1956 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1957 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1958 if (const llvm::MemoryBuffer *
1959 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1960 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
1962 const char *fname = fileOrBuf.get<const char *>();
1963 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
1966 PreprocessorOptions &PPOpts = CI->getPreprocessorOpts();
1967 PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName;
1968 PPOpts.AllowPCHWithCompilerErrors = AllowPCHWithCompilerErrors;
1970 // Override the resources path.
1971 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1973 CI->getFrontendOpts().SkipFunctionBodies = SkipFunctionBodies;
1975 // Create the AST unit.
1976 OwningPtr<ASTUnit> AST;
1977 AST.reset(new ASTUnit(false));
1978 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
1979 AST->Diagnostics = Diags;
1980 Diags = 0; // Zero out now to ease cleanup during crash recovery.
1981 AST->FileSystemOpts = CI->getFileSystemOpts();
1982 AST->FileMgr = new FileManager(AST->FileSystemOpts);
1983 AST->OnlyLocalDecls = OnlyLocalDecls;
1984 AST->CaptureDiagnostics = CaptureDiagnostics;
1985 AST->TUKind = TUKind;
1986 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1987 AST->IncludeBriefCommentsInCodeCompletion
1988 = IncludeBriefCommentsInCodeCompletion;
1989 AST->UserFilesAreVolatile = UserFilesAreVolatile;
1990 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1991 AST->StoredDiagnostics.swap(StoredDiagnostics);
1992 AST->Invocation = CI;
1993 if (ForSerialization)
1994 AST->WriterData.reset(new ASTWriterData());
1995 CI = 0; // Zero out now to ease cleanup during crash recovery.
1997 // Recover resources if we crash before exiting this method.
1998 llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1999 ASTUnitCleanup(AST.get());
2001 if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) {
2002 // Some error occurred, if caller wants to examine diagnostics, pass it the
2005 AST->StoredDiagnostics.swap(AST->FailedParseDiagnostics);
2014 bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
2018 clearFileLevelDecls();
2020 SimpleTimer ParsingTimer(WantTiming);
2021 ParsingTimer.setOutput("Reparsing " + getMainFileName());
2024 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
2025 for (PreprocessorOptions::remapped_file_buffer_iterator
2026 R = PPOpts.remapped_file_buffer_begin(),
2027 REnd = PPOpts.remapped_file_buffer_end();
2032 Invocation->getPreprocessorOpts().clearRemappedFiles();
2033 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
2034 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2035 if (const llvm::MemoryBuffer *
2036 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2037 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2040 const char *fname = fileOrBuf.get<const char *>();
2041 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
2046 // If we have a preamble file lying around, or if we might try to
2047 // build a precompiled preamble, do so now.
2048 llvm::MemoryBuffer *OverrideMainBuffer = 0;
2049 if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
2050 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
2052 // Clear out the diagnostics state.
2053 getDiagnostics().Reset();
2054 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
2055 if (OverrideMainBuffer)
2056 getDiagnostics().setNumWarnings(NumWarningsInPreamble);
2058 // Parse the sources
2059 bool Result = Parse(OverrideMainBuffer);
2061 // If we're caching global code-completion results, and the top-level
2062 // declarations have changed, clear out the code-completion cache.
2063 if (!Result && ShouldCacheCodeCompletionResults &&
2064 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
2065 CacheCodeCompletionResults();
2067 // We now need to clear out the completion info related to this translation
2068 // unit; it'll be recreated if necessary.
2074 //----------------------------------------------------------------------------//
2076 //----------------------------------------------------------------------------//
2079 /// \brief Code completion consumer that combines the cached code-completion
2080 /// results from an ASTUnit with the code-completion results provided to it,
2081 /// then passes the result on to
2082 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
2083 uint64_t NormalContexts;
2085 CodeCompleteConsumer &Next;
2088 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
2089 const CodeCompleteOptions &CodeCompleteOpts)
2090 : CodeCompleteConsumer(CodeCompleteOpts, Next.isOutputBinary()),
2091 AST(AST), Next(Next)
2093 // Compute the set of contexts in which we will look when we don't have
2094 // any information about the specific context.
2096 = (1LL << CodeCompletionContext::CCC_TopLevel)
2097 | (1LL << CodeCompletionContext::CCC_ObjCInterface)
2098 | (1LL << CodeCompletionContext::CCC_ObjCImplementation)
2099 | (1LL << CodeCompletionContext::CCC_ObjCIvarList)
2100 | (1LL << CodeCompletionContext::CCC_Statement)
2101 | (1LL << CodeCompletionContext::CCC_Expression)
2102 | (1LL << CodeCompletionContext::CCC_ObjCMessageReceiver)
2103 | (1LL << CodeCompletionContext::CCC_DotMemberAccess)
2104 | (1LL << CodeCompletionContext::CCC_ArrowMemberAccess)
2105 | (1LL << CodeCompletionContext::CCC_ObjCPropertyAccess)
2106 | (1LL << CodeCompletionContext::CCC_ObjCProtocolName)
2107 | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression)
2108 | (1LL << CodeCompletionContext::CCC_Recovery);
2110 if (AST.getASTContext().getLangOpts().CPlusPlus)
2111 NormalContexts |= (1LL << CodeCompletionContext::CCC_EnumTag)
2112 | (1LL << CodeCompletionContext::CCC_UnionTag)
2113 | (1LL << CodeCompletionContext::CCC_ClassOrStructTag);
2116 virtual void ProcessCodeCompleteResults(Sema &S,
2117 CodeCompletionContext Context,
2118 CodeCompletionResult *Results,
2119 unsigned NumResults);
2121 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2122 OverloadCandidate *Candidates,
2123 unsigned NumCandidates) {
2124 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2127 virtual CodeCompletionAllocator &getAllocator() {
2128 return Next.getAllocator();
2131 virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() {
2132 return Next.getCodeCompletionTUInfo();
2137 /// \brief Helper function that computes which global names are hidden by the
2138 /// local code-completion results.
2139 static void CalculateHiddenNames(const CodeCompletionContext &Context,
2140 CodeCompletionResult *Results,
2141 unsigned NumResults,
2143 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
2144 bool OnlyTagNames = false;
2145 switch (Context.getKind()) {
2146 case CodeCompletionContext::CCC_Recovery:
2147 case CodeCompletionContext::CCC_TopLevel:
2148 case CodeCompletionContext::CCC_ObjCInterface:
2149 case CodeCompletionContext::CCC_ObjCImplementation:
2150 case CodeCompletionContext::CCC_ObjCIvarList:
2151 case CodeCompletionContext::CCC_ClassStructUnion:
2152 case CodeCompletionContext::CCC_Statement:
2153 case CodeCompletionContext::CCC_Expression:
2154 case CodeCompletionContext::CCC_ObjCMessageReceiver:
2155 case CodeCompletionContext::CCC_DotMemberAccess:
2156 case CodeCompletionContext::CCC_ArrowMemberAccess:
2157 case CodeCompletionContext::CCC_ObjCPropertyAccess:
2158 case CodeCompletionContext::CCC_Namespace:
2159 case CodeCompletionContext::CCC_Type:
2160 case CodeCompletionContext::CCC_Name:
2161 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
2162 case CodeCompletionContext::CCC_ParenthesizedExpression:
2163 case CodeCompletionContext::CCC_ObjCInterfaceName:
2166 case CodeCompletionContext::CCC_EnumTag:
2167 case CodeCompletionContext::CCC_UnionTag:
2168 case CodeCompletionContext::CCC_ClassOrStructTag:
2169 OnlyTagNames = true;
2172 case CodeCompletionContext::CCC_ObjCProtocolName:
2173 case CodeCompletionContext::CCC_MacroName:
2174 case CodeCompletionContext::CCC_MacroNameUse:
2175 case CodeCompletionContext::CCC_PreprocessorExpression:
2176 case CodeCompletionContext::CCC_PreprocessorDirective:
2177 case CodeCompletionContext::CCC_NaturalLanguage:
2178 case CodeCompletionContext::CCC_SelectorName:
2179 case CodeCompletionContext::CCC_TypeQualifiers:
2180 case CodeCompletionContext::CCC_Other:
2181 case CodeCompletionContext::CCC_OtherWithMacros:
2182 case CodeCompletionContext::CCC_ObjCInstanceMessage:
2183 case CodeCompletionContext::CCC_ObjCClassMessage:
2184 case CodeCompletionContext::CCC_ObjCCategoryName:
2185 // We're looking for nothing, or we're looking for names that cannot
2190 typedef CodeCompletionResult Result;
2191 for (unsigned I = 0; I != NumResults; ++I) {
2192 if (Results[I].Kind != Result::RK_Declaration)
2196 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2198 bool Hiding = false;
2200 Hiding = (IDNS & Decl::IDNS_Tag);
2202 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
2203 Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2204 Decl::IDNS_NonMemberOperator);
2205 if (Ctx.getLangOpts().CPlusPlus)
2206 HiddenIDNS |= Decl::IDNS_Tag;
2207 Hiding = (IDNS & HiddenIDNS);
2213 DeclarationName Name = Results[I].Declaration->getDeclName();
2214 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2215 HiddenNames.insert(Identifier->getName());
2217 HiddenNames.insert(Name.getAsString());
2222 void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2223 CodeCompletionContext Context,
2224 CodeCompletionResult *Results,
2225 unsigned NumResults) {
2226 // Merge the results we were given with the results we cached.
2227 bool AddedResult = false;
2228 uint64_t InContexts =
2229 Context.getKind() == CodeCompletionContext::CCC_Recovery
2230 ? NormalContexts : (1LL << Context.getKind());
2231 // Contains the set of names that are hidden by "local" completion results.
2232 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
2233 typedef CodeCompletionResult Result;
2234 SmallVector<Result, 8> AllResults;
2235 for (ASTUnit::cached_completion_iterator
2236 C = AST.cached_completion_begin(),
2237 CEnd = AST.cached_completion_end();
2239 // If the context we are in matches any of the contexts we are
2240 // interested in, we'll add this result.
2241 if ((C->ShowInContexts & InContexts) == 0)
2244 // If we haven't added any results previously, do so now.
2246 CalculateHiddenNames(Context, Results, NumResults, S.Context,
2248 AllResults.insert(AllResults.end(), Results, Results + NumResults);
2252 // Determine whether this global completion result is hidden by a local
2253 // completion result. If so, skip it.
2254 if (C->Kind != CXCursor_MacroDefinition &&
2255 HiddenNames.count(C->Completion->getTypedText()))
2258 // Adjust priority based on similar type classes.
2259 unsigned Priority = C->Priority;
2260 CodeCompletionString *Completion = C->Completion;
2261 if (!Context.getPreferredType().isNull()) {
2262 if (C->Kind == CXCursor_MacroDefinition) {
2263 Priority = getMacroUsagePriority(C->Completion->getTypedText(),
2265 Context.getPreferredType()->isAnyPointerType());
2266 } else if (C->Type) {
2267 CanQualType Expected
2268 = S.Context.getCanonicalType(
2269 Context.getPreferredType().getUnqualifiedType());
2270 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2271 if (ExpectedSTC == C->TypeClass) {
2272 // We know this type is similar; check for an exact match.
2273 llvm::StringMap<unsigned> &CachedCompletionTypes
2274 = AST.getCachedCompletionTypes();
2275 llvm::StringMap<unsigned>::iterator Pos
2276 = CachedCompletionTypes.find(QualType(Expected).getAsString());
2277 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2278 Priority /= CCF_ExactTypeMatch;
2280 Priority /= CCF_SimilarTypeMatch;
2285 // Adjust the completion string, if required.
2286 if (C->Kind == CXCursor_MacroDefinition &&
2287 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2288 // Create a new code-completion string that just contains the
2289 // macro name, without its arguments.
2290 CodeCompletionBuilder Builder(getAllocator(), getCodeCompletionTUInfo(),
2291 CCP_CodePattern, C->Availability);
2292 Builder.AddTypedTextChunk(C->Completion->getTypedText());
2293 Priority = CCP_CodePattern;
2294 Completion = Builder.TakeString();
2297 AllResults.push_back(Result(Completion, Priority, C->Kind,
2301 // If we did not add any cached completion results, just forward the
2302 // results we were given to the next consumer.
2304 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2308 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2314 void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
2315 RemappedFile *RemappedFiles,
2316 unsigned NumRemappedFiles,
2318 bool IncludeCodePatterns,
2319 bool IncludeBriefComments,
2320 CodeCompleteConsumer &Consumer,
2321 DiagnosticsEngine &Diag, LangOptions &LangOpts,
2322 SourceManager &SourceMgr, FileManager &FileMgr,
2323 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2324 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
2328 SimpleTimer CompletionTimer(WantTiming);
2329 CompletionTimer.setOutput("Code completion @ " + File + ":" +
2330 Twine(Line) + ":" + Twine(Column));
2332 IntrusiveRefCntPtr<CompilerInvocation>
2333 CCInvocation(new CompilerInvocation(*Invocation));
2335 FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2336 CodeCompleteOptions &CodeCompleteOpts = FrontendOpts.CodeCompleteOpts;
2337 PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
2339 CodeCompleteOpts.IncludeMacros = IncludeMacros &&
2340 CachedCompletionResults.empty();
2341 CodeCompleteOpts.IncludeCodePatterns = IncludeCodePatterns;
2342 CodeCompleteOpts.IncludeGlobals = CachedCompletionResults.empty();
2343 CodeCompleteOpts.IncludeBriefComments = IncludeBriefComments;
2345 assert(IncludeBriefComments == this->IncludeBriefCommentsInCodeCompletion);
2347 FrontendOpts.CodeCompletionAt.FileName = File;
2348 FrontendOpts.CodeCompletionAt.Line = Line;
2349 FrontendOpts.CodeCompletionAt.Column = Column;
2351 // Set the language options appropriately.
2352 LangOpts = *CCInvocation->getLangOpts();
2354 OwningPtr<CompilerInstance> Clang(new CompilerInstance());
2356 // Recover resources if we crash before exiting this method.
2357 llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2358 CICleanup(Clang.get());
2360 Clang->setInvocation(&*CCInvocation);
2361 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].getFile();
2363 // Set up diagnostics, capturing any diagnostics produced.
2364 Clang->setDiagnostics(&Diag);
2365 ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
2366 CaptureDroppedDiagnostics Capture(true,
2367 Clang->getDiagnostics(),
2370 // Create the target instance.
2371 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
2372 Clang->getTargetOpts()));
2373 if (!Clang->hasTarget()) {
2374 Clang->setInvocation(0);
2378 // Inform the target of the language options.
2380 // FIXME: We shouldn't need to do this, the target should be immutable once
2381 // created. This complexity should be lifted elsewhere.
2382 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
2384 assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
2385 "Invocation must have exactly one source file!");
2386 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_AST &&
2387 "FIXME: AST inputs not yet supported here!");
2388 assert(Clang->getFrontendOpts().Inputs[0].getKind() != IK_LLVM_IR &&
2389 "IR inputs not support here!");
2392 // Use the source and file managers that we were given.
2393 Clang->setFileManager(&FileMgr);
2394 Clang->setSourceManager(&SourceMgr);
2397 PreprocessorOpts.clearRemappedFiles();
2398 PreprocessorOpts.RetainRemappedFileBuffers = true;
2399 for (unsigned I = 0; I != NumRemappedFiles; ++I) {
2400 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2401 if (const llvm::MemoryBuffer *
2402 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2403 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2404 OwnedBuffers.push_back(memBuf);
2406 const char *fname = fileOrBuf.get<const char *>();
2407 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2411 // Use the code completion consumer we were given, but adding any cached
2412 // code-completion results.
2413 AugmentedCodeCompleteConsumer *AugmentedConsumer
2414 = new AugmentedCodeCompleteConsumer(*this, Consumer, CodeCompleteOpts);
2415 Clang->setCodeCompletionConsumer(AugmentedConsumer);
2417 // If we have a precompiled preamble, try to use it. We only allow
2418 // the use of the precompiled preamble if we're if the completion
2419 // point is within the main file, after the end of the precompiled
2421 llvm::MemoryBuffer *OverrideMainBuffer = 0;
2422 if (!getPreambleFile(this).empty()) {
2423 using llvm::sys::FileStatus;
2424 llvm::sys::PathWithStatus CompleteFilePath(File);
2425 llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2426 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2427 if (const FileStatus *MainStatus = MainPath.getFileStatus())
2428 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID() &&
2431 = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
2435 // If the main file has been overridden due to the use of a preamble,
2436 // make that override happen and introduce the preamble.
2437 StoredDiagnostics.insert(StoredDiagnostics.end(),
2438 stored_diag_begin(),
2439 stored_diag_afterDriver_begin());
2440 if (OverrideMainBuffer) {
2441 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2442 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2443 PreprocessorOpts.PrecompiledPreambleBytes.second
2444 = PreambleEndsAtStartOfLine;
2445 PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
2446 PreprocessorOpts.DisablePCHValidation = true;
2448 OwnedBuffers.push_back(OverrideMainBuffer);
2450 PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2451 PreprocessorOpts.PrecompiledPreambleBytes.second = false;
2454 // Disable the preprocessing record if modules are not enabled.
2455 if (!Clang->getLangOpts().Modules)
2456 PreprocessorOpts.DetailedRecord = false;
2458 OwningPtr<SyntaxOnlyAction> Act;
2459 Act.reset(new SyntaxOnlyAction);
2460 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0])) {
2461 if (OverrideMainBuffer) {
2462 std::string ModName = getPreambleFile(this);
2463 TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
2464 getSourceManager(), PreambleDiagnostics,
2468 Act->EndSourceFile();
2471 checkAndSanitizeDiags(StoredDiagnostics, getSourceManager());
2474 bool ASTUnit::Save(StringRef File) {
2475 // Write to a temporary file and later rename it to the actual file, to avoid
2476 // possible race conditions.
2477 SmallString<128> TempPath;
2479 TempPath += "-%%%%%%%%";
2481 if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
2482 /*makeAbsolute=*/false))
2485 // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2486 // unconditionally create a stat cache when we parse the file?
2487 llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
2491 if (Out.has_error()) {
2496 if (llvm::sys::fs::rename(TempPath.str(), File)) {
2498 llvm::sys::fs::remove(TempPath.str(), exists);
2505 static bool serializeUnit(ASTWriter &Writer,
2506 SmallVectorImpl<char> &Buffer,
2510 Writer.WriteAST(S, std::string(), 0, "", hasErrors);
2512 // Write the generated bitstream to "Out".
2513 if (!Buffer.empty())
2514 OS.write(Buffer.data(), Buffer.size());
2519 bool ASTUnit::serialize(raw_ostream &OS) {
2520 bool hasErrors = getDiagnostics().hasErrorOccurred();
2523 return serializeUnit(WriterData->Writer, WriterData->Buffer,
2524 getSema(), hasErrors, OS);
2526 SmallString<128> Buffer;
2527 llvm::BitstreamWriter Stream(Buffer);
2528 ASTWriter Writer(Stream);
2529 return serializeUnit(Writer, Buffer, getSema(), hasErrors, OS);
2532 typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2534 static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2535 unsigned Raw = L.getRawEncoding();
2536 const unsigned MacroBit = 1U << 31;
2537 L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2538 ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2541 void ASTUnit::TranslateStoredDiagnostics(
2544 SourceManager &SrcMgr,
2545 const SmallVectorImpl<StoredDiagnostic> &Diags,
2546 SmallVectorImpl<StoredDiagnostic> &Out) {
2547 // The stored diagnostic has the old source manager in it; update
2548 // the locations to refer into the new source manager. We also need to remap
2549 // all the locations to the new view. This includes the diag location, any
2550 // associated source ranges, and the source ranges of associated fix-its.
2551 // FIXME: There should be a cleaner way to do this.
2553 SmallVector<StoredDiagnostic, 4> Result;
2554 Result.reserve(Diags.size());
2555 assert(MMan && "Don't have a module manager");
2556 serialization::ModuleFile *Mod = MMan->ModuleMgr.lookup(ModName);
2557 assert(Mod && "Don't have preamble module");
2558 SLocRemap &Remap = Mod->SLocRemap;
2559 for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2560 // Rebuild the StoredDiagnostic.
2561 const StoredDiagnostic &SD = Diags[I];
2562 SourceLocation L = SD.getLocation();
2563 TranslateSLoc(L, Remap);
2564 FullSourceLoc Loc(L, SrcMgr);
2566 SmallVector<CharSourceRange, 4> Ranges;
2567 Ranges.reserve(SD.range_size());
2568 for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2571 SourceLocation BL = I->getBegin();
2572 TranslateSLoc(BL, Remap);
2573 SourceLocation EL = I->getEnd();
2574 TranslateSLoc(EL, Remap);
2575 Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2578 SmallVector<FixItHint, 2> FixIts;
2579 FixIts.reserve(SD.fixit_size());
2580 for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2583 FixIts.push_back(FixItHint());
2584 FixItHint &FH = FixIts.back();
2585 FH.CodeToInsert = I->CodeToInsert;
2586 SourceLocation BL = I->RemoveRange.getBegin();
2587 TranslateSLoc(BL, Remap);
2588 SourceLocation EL = I->RemoveRange.getEnd();
2589 TranslateSLoc(EL, Remap);
2590 FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2591 I->RemoveRange.isTokenRange());
2594 Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2595 SD.getMessage(), Loc, Ranges, FixIts));
2600 static inline bool compLocDecl(std::pair<unsigned, Decl *> L,
2601 std::pair<unsigned, Decl *> R) {
2602 return L.first < R.first;
2605 void ASTUnit::addFileLevelDecl(Decl *D) {
2608 // We only care about local declarations.
2609 if (D->isFromASTFile())
2612 SourceManager &SM = *SourceMgr;
2613 SourceLocation Loc = D->getLocation();
2614 if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2617 // We only keep track of the file-level declarations of each file.
2618 if (!D->getLexicalDeclContext()->isFileContext())
2621 SourceLocation FileLoc = SM.getFileLoc(Loc);
2622 assert(SM.isLocalSourceLocation(FileLoc));
2625 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2626 if (FID.isInvalid())
2629 LocDeclsTy *&Decls = FileDecls[FID];
2631 Decls = new LocDeclsTy();
2633 std::pair<unsigned, Decl *> LocDecl(Offset, D);
2635 if (Decls->empty() || Decls->back().first <= Offset) {
2636 Decls->push_back(LocDecl);
2640 LocDeclsTy::iterator
2641 I = std::upper_bound(Decls->begin(), Decls->end(), LocDecl, compLocDecl);
2643 Decls->insert(I, LocDecl);
2646 void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2647 SmallVectorImpl<Decl *> &Decls) {
2648 if (File.isInvalid())
2651 if (SourceMgr->isLoadedFileID(File)) {
2652 assert(Ctx->getExternalSource() && "No external source!");
2653 return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2657 FileDeclsTy::iterator I = FileDecls.find(File);
2658 if (I == FileDecls.end())
2661 LocDeclsTy &LocDecls = *I->second;
2662 if (LocDecls.empty())
2665 LocDeclsTy::iterator
2666 BeginIt = std::lower_bound(LocDecls.begin(), LocDecls.end(),
2667 std::make_pair(Offset, (Decl*)0), compLocDecl);
2668 if (BeginIt != LocDecls.begin())
2671 // If we are pointing at a top-level decl inside an objc container, we need
2672 // to backtrack until we find it otherwise we will fail to report that the
2673 // region overlaps with an objc container.
2674 while (BeginIt != LocDecls.begin() &&
2675 BeginIt->second->isTopLevelDeclInObjCContainer())
2678 LocDeclsTy::iterator
2679 EndIt = std::upper_bound(LocDecls.begin(), LocDecls.end(),
2680 std::make_pair(Offset+Length, (Decl*)0),
2682 if (EndIt != LocDecls.end())
2685 for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2686 Decls.push_back(DIt->second);
2689 SourceLocation ASTUnit::getLocation(const FileEntry *File,
2690 unsigned Line, unsigned Col) const {
2691 const SourceManager &SM = getSourceManager();
2692 SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
2693 return SM.getMacroArgExpandedLocation(Loc);
2696 SourceLocation ASTUnit::getLocation(const FileEntry *File,
2697 unsigned Offset) const {
2698 const SourceManager &SM = getSourceManager();
2699 SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
2700 return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2703 /// \brief If \arg Loc is a loaded location from the preamble, returns
2704 /// the corresponding local location of the main file, otherwise it returns
2706 SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2709 PreambleID = SourceMgr->getPreambleFileID();
2711 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2715 if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2716 SourceLocation FileLoc
2717 = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2718 return FileLoc.getLocWithOffset(Offs);
2724 /// \brief If \arg Loc is a local location of the main file but inside the
2725 /// preamble chunk, returns the corresponding loaded location from the
2726 /// preamble, otherwise it returns \arg Loc.
2727 SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2730 PreambleID = SourceMgr->getPreambleFileID();
2732 if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2736 if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2737 Offs < Preamble.size()) {
2738 SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2739 return FileLoc.getLocWithOffset(Offs);
2745 bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2748 FID = SourceMgr->getPreambleFileID();
2750 if (Loc.isInvalid() || FID.isInvalid())
2753 return SourceMgr->isInFileID(Loc, FID);
2756 bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2759 FID = SourceMgr->getMainFileID();
2761 if (Loc.isInvalid() || FID.isInvalid())
2764 return SourceMgr->isInFileID(Loc, FID);
2767 SourceLocation ASTUnit::getEndOfPreambleFileID() {
2770 FID = SourceMgr->getPreambleFileID();
2772 if (FID.isInvalid())
2773 return SourceLocation();
2775 return SourceMgr->getLocForEndOfFile(FID);
2778 SourceLocation ASTUnit::getStartOfMainFileID() {
2781 FID = SourceMgr->getMainFileID();
2783 if (FID.isInvalid())
2784 return SourceLocation();
2786 return SourceMgr->getLocForStartOfFile(FID);
2789 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
2790 ASTUnit::getLocalPreprocessingEntities() const {
2791 if (isMainFileAST()) {
2792 serialization::ModuleFile &
2793 Mod = Reader->getModuleManager().getPrimaryModule();
2794 return Reader->getModulePreprocessedEntities(Mod);
2797 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord())
2798 return std::make_pair(PPRec->local_begin(), PPRec->local_end());
2800 return std::make_pair(PreprocessingRecord::iterator(),
2801 PreprocessingRecord::iterator());
2804 bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) {
2805 if (isMainFileAST()) {
2806 serialization::ModuleFile &
2807 Mod = Reader->getModuleManager().getPrimaryModule();
2808 ASTReader::ModuleDeclIterator MDI, MDE;
2809 llvm::tie(MDI, MDE) = Reader->getModuleFileLevelDecls(Mod);
2810 for (; MDI != MDE; ++MDI) {
2811 if (!Fn(context, *MDI))
2818 for (ASTUnit::top_level_iterator TL = top_level_begin(),
2819 TLEnd = top_level_end();
2820 TL != TLEnd; ++TL) {
2821 if (!Fn(context, *TL))
2829 struct PCHLocatorInfo {
2830 serialization::ModuleFile *Mod;
2831 PCHLocatorInfo() : Mod(0) {}
2835 static bool PCHLocator(serialization::ModuleFile &M, void *UserData) {
2836 PCHLocatorInfo &Info = *static_cast<PCHLocatorInfo*>(UserData);
2838 case serialization::MK_Module:
2839 return true; // skip dependencies.
2840 case serialization::MK_PCH:
2842 return true; // found it.
2843 case serialization::MK_Preamble:
2844 return false; // look in dependencies.
2845 case serialization::MK_MainFile:
2846 return false; // look in dependencies.
2852 const FileEntry *ASTUnit::getPCHFile() {
2856 PCHLocatorInfo Info;
2857 Reader->getModuleManager().visit(PCHLocator, &Info);
2859 return Info.Mod->File;
2864 bool ASTUnit::isModuleFile() {
2865 return isMainFileAST() && !ASTFileLangOpts.CurrentModule.empty();
2868 void ASTUnit::PreambleData::countLines() const {
2873 for (std::vector<char>::const_iterator
2874 I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2878 if (Buffer.back() != '\n')
2883 ASTUnit::ConcurrencyState::ConcurrencyState() {
2884 Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2887 ASTUnit::ConcurrencyState::~ConcurrencyState() {
2888 delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2891 void ASTUnit::ConcurrencyState::start() {
2892 bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2893 assert(acquired && "Concurrent access to ASTUnit!");
2896 void ASTUnit::ConcurrencyState::finish() {
2897 static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2902 ASTUnit::ConcurrencyState::ConcurrencyState() {}
2903 ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2904 void ASTUnit::ConcurrencyState::start() {}
2905 void ASTUnit::ConcurrencyState::finish() {}