diff options
Diffstat (limited to 'contrib/llvm/tools/clang/lib/Frontend/ASTUnit.cpp')
-rw-r--r-- | contrib/llvm/tools/clang/lib/Frontend/ASTUnit.cpp | 316 |
1 files changed, 160 insertions, 156 deletions
diff --git a/contrib/llvm/tools/clang/lib/Frontend/ASTUnit.cpp b/contrib/llvm/tools/clang/lib/Frontend/ASTUnit.cpp index a3998fa..57c97d0 100644 --- a/contrib/llvm/tools/clang/lib/Frontend/ASTUnit.cpp +++ b/contrib/llvm/tools/clang/lib/Frontend/ASTUnit.cpp @@ -120,11 +120,10 @@ static OnDiskDataMap &getOnDiskDataMap() { static void cleanupOnDiskMapAtExit() { // Use the mutex because there can be an alive thread destroying an ASTUnit. llvm::MutexGuard Guard(getOnDiskMutex()); - OnDiskDataMap &M = getOnDiskDataMap(); - for (OnDiskDataMap::iterator I = M.begin(), E = M.end(); I != E; ++I) { + for (const auto &I : getOnDiskDataMap()) { // We don't worry about freeing the memory associated with OnDiskDataMap. // All we care about is erasing stale files. - I->second->Cleanup(); + I.second->Cleanup(); } } @@ -151,7 +150,7 @@ static void removeOnDiskEntry(const ASTUnit *AU) { OnDiskDataMap::iterator I = M.find(AU); if (I != M.end()) { I->second->Cleanup(); - M.erase(AU); + M.erase(I); } } @@ -164,8 +163,8 @@ static const std::string &getPreambleFile(const ASTUnit *AU) { } void OnDiskData::CleanTemporaryFiles() { - for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I) - llvm::sys::fs::remove(TemporaryFiles[I]); + for (StringRef File : TemporaryFiles) + llvm::sys::fs::remove(File); TemporaryFiles.clear(); } @@ -354,26 +353,25 @@ void ASTUnit::CacheCodeCompletionResults() { // Translate global code completions into cached completions. llvm::DenseMap<CanQualType, unsigned> CompletionTypes; - - for (unsigned I = 0, N = Results.size(); I != N; ++I) { - switch (Results[I].Kind) { + CodeCompletionContext CCContext(CodeCompletionContext::CCC_TopLevel); + + for (Result &R : Results) { + switch (R.Kind) { case Result::RK_Declaration: { bool IsNestedNameSpecifier = false; CachedCodeCompletionResult CachedResult; - CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema, - *CachedCompletionAllocator, - CCTUInfo, - IncludeBriefCommentsInCodeCompletion); - CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration, - Ctx->getLangOpts(), - IsNestedNameSpecifier); - CachedResult.Priority = Results[I].Priority; - CachedResult.Kind = Results[I].CursorKind; - CachedResult.Availability = Results[I].Availability; + CachedResult.Completion = R.CreateCodeCompletionString( + *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo, + IncludeBriefCommentsInCodeCompletion); + CachedResult.ShowInContexts = getDeclShowContexts( + R.Declaration, Ctx->getLangOpts(), IsNestedNameSpecifier); + CachedResult.Priority = R.Priority; + CachedResult.Kind = R.CursorKind; + CachedResult.Availability = R.Availability; // Keep track of the type of this completion in an ASTContext-agnostic // way. - QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration); + QualType UsageType = getDeclUsageType(*Ctx, R.Declaration); if (UsageType.isNull()) { CachedResult.TypeClass = STC_Void; CachedResult.Type = 0; @@ -398,8 +396,8 @@ void ASTUnit::CacheCodeCompletionResults() { CachedCompletionResults.push_back(CachedResult); /// Handle nested-name-specifiers in C++. - if (TheSema->Context.getLangOpts().CPlusPlus && - IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) { + if (TheSema->Context.getLangOpts().CPlusPlus && IsNestedNameSpecifier && + !R.StartsNestedNameSpecifier) { // The contexts in which a nested-name-specifier can appear in C++. uint64_t NNSContexts = (1LL << CodeCompletionContext::CCC_TopLevel) @@ -415,8 +413,8 @@ void ASTUnit::CacheCodeCompletionResults() { | (1LL << CodeCompletionContext::CCC_PotentiallyQualifiedName) | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression); - if (isa<NamespaceDecl>(Results[I].Declaration) || - isa<NamespaceAliasDecl>(Results[I].Declaration)) + if (isa<NamespaceDecl>(R.Declaration) || + isa<NamespaceAliasDecl>(R.Declaration)) NNSContexts |= (1LL << CodeCompletionContext::CCC_Namespace); if (unsigned RemainingContexts @@ -424,12 +422,10 @@ void ASTUnit::CacheCodeCompletionResults() { // If there any contexts where this completion can be a // nested-name-specifier but isn't already an option, create a // nested-name-specifier completion. - Results[I].StartsNestedNameSpecifier = true; - CachedResult.Completion - = Results[I].CreateCodeCompletionString(*TheSema, - *CachedCompletionAllocator, - CCTUInfo, - IncludeBriefCommentsInCodeCompletion); + R.StartsNestedNameSpecifier = true; + CachedResult.Completion = R.CreateCodeCompletionString( + *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo, + IncludeBriefCommentsInCodeCompletion); CachedResult.ShowInContexts = RemainingContexts; CachedResult.Priority = CCP_NestedNameSpecifier; CachedResult.TypeClass = STC_Void; @@ -448,11 +444,9 @@ void ASTUnit::CacheCodeCompletionResults() { case Result::RK_Macro: { CachedCodeCompletionResult CachedResult; - CachedResult.Completion - = Results[I].CreateCodeCompletionString(*TheSema, - *CachedCompletionAllocator, - CCTUInfo, - IncludeBriefCommentsInCodeCompletion); + CachedResult.Completion = R.CreateCodeCompletionString( + *TheSema, CCContext, *CachedCompletionAllocator, CCTUInfo, + IncludeBriefCommentsInCodeCompletion); CachedResult.ShowInContexts = (1LL << CodeCompletionContext::CCC_TopLevel) | (1LL << CodeCompletionContext::CCC_ObjCInterface) @@ -466,10 +460,10 @@ void ASTUnit::CacheCodeCompletionResults() { | (1LL << CodeCompletionContext::CCC_PreprocessorExpression) | (1LL << CodeCompletionContext::CCC_ParenthesizedExpression) | (1LL << CodeCompletionContext::CCC_OtherWithMacros); - - CachedResult.Priority = Results[I].Priority; - CachedResult.Kind = Results[I].CursorKind; - CachedResult.Availability = Results[I].Availability; + + CachedResult.Priority = R.Priority; + CachedResult.Kind = R.CursorKind; + CachedResult.Availability = R.Availability; CachedResult.TypeClass = STC_Void; CachedResult.Type = 0; CachedCompletionResults.push_back(CachedResult); @@ -520,8 +514,8 @@ public: return false; } - bool ReadTargetOptions(const TargetOptions &TargetOpts, - bool Complain) override { + bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, + bool AllowCompatibleDifferences) override { // If we've already initialized the target, don't do it again. if (Target) return false; @@ -620,7 +614,7 @@ void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level, // about. This effectively drops diagnostics from modules we're building. // FIXME: In the long run, ee don't want to drop source managers from modules. if (!Info.hasSourceManager() || &Info.getSourceManager() == SourceMgr) - StoredDiags.push_back(StoredDiagnostic(Level, Info)); + StoredDiags.emplace_back(Level, Info); } ASTMutationListener *ASTUnit::getASTMutationListener() { @@ -655,7 +649,9 @@ void ASTUnit::ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags, } std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile( - const std::string &Filename, IntrusiveRefCntPtr<DiagnosticsEngine> Diags, + const std::string &Filename, + std::shared_ptr<PCHContainerOperations> PCHContainerOps, + IntrusiveRefCntPtr<DiagnosticsEngine> Diags, const FileSystemOptions &FileSystemOpts, bool OnlyLocalDecls, ArrayRef<RemappedFile> RemappedFiles, bool CaptureDiagnostics, bool AllowPCHWithCompilerErrors, bool UserFilesAreVolatile) { @@ -689,8 +685,8 @@ std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile( PreprocessorOptions *PPOpts = new PreprocessorOptions(); - for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) - PPOpts->addRemappedFile(RemappedFiles[I].first, RemappedFiles[I].second); + for (const auto &RemappedFile : RemappedFiles) + PPOpts->addRemappedFile(RemappedFile.first, RemappedFile.second); // Gather Info for preprocessor construction later on. @@ -712,15 +708,22 @@ std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile( bool disableValid = false; if (::getenv("LIBCLANG_DISABLE_PCH_VALIDATION")) disableValid = true; - AST->Reader = new ASTReader(PP, Context, - /*isysroot=*/"", - /*DisableValidation=*/disableValid, - AllowPCHWithCompilerErrors); + AST->Reader = new ASTReader(PP, Context, *PCHContainerOps, + /*isysroot=*/"", + /*DisableValidation=*/disableValid, + AllowPCHWithCompilerErrors); AST->Reader->setListener(llvm::make_unique<ASTInfoCollector>( *AST->PP, Context, AST->ASTFileLangOpts, AST->TargetOpts, AST->Target, Counter)); + // Attach the AST reader to the AST context as an external AST + // source, so that declarations will be deserialized from the + // AST file as needed. + // We need the external source to be set up before we read the AST, because + // eagerly-deserialized declarations may use it. + Context.setExternalSource(AST->Reader); + switch (AST->Reader->ReadAST(Filename, serialization::MK_MainFile, SourceLocation(), ASTReader::ARR_None)) { case ASTReader::Success: @@ -740,11 +743,6 @@ std::unique_ptr<ASTUnit> ASTUnit::LoadFromASTFile( PP.setCounterValue(Counter); - // Attach the AST reader to the AST context as an external AST - // source, so that declarations will be deserialized from the - // AST file as needed. - Context.setExternalSource(AST->Reader); - // Create an AST consumer, even though it isn't used. AST->Consumer.reset(new ASTConsumer); @@ -853,8 +851,8 @@ public: } bool HandleTopLevelDecl(DeclGroupRef D) override { - for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) - handleTopLevelDecl(*it); + for (Decl *TopLevelDecl : D) + handleTopLevelDecl(TopLevelDecl); return true; } @@ -862,8 +860,8 @@ public: void HandleInterestingDecl(DeclGroupRef) override {} void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override { - for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) - handleTopLevelDecl(*it); + for (Decl *TopLevelDecl : D) + handleTopLevelDecl(TopLevelDecl); } ASTMutationListener *GetASTMutationListener() override { @@ -921,19 +919,21 @@ class PrecompilePreambleConsumer : public PCHGenerator { unsigned &Hash; std::vector<Decl *> TopLevelDecls; PrecompilePreambleAction *Action; + raw_ostream *Out; public: PrecompilePreambleConsumer(ASTUnit &Unit, PrecompilePreambleAction *Action, const Preprocessor &PP, StringRef isysroot, raw_ostream *Out) - : PCHGenerator(PP, "", nullptr, isysroot, Out, /*AllowASTWithErrors=*/true), - Unit(Unit), Hash(Unit.getCurrentTopLevelHashValue()), Action(Action) { + : PCHGenerator(PP, "", nullptr, isysroot, std::make_shared<PCHBuffer>(), + /*AllowASTWithErrors=*/true), + Unit(Unit), Hash(Unit.getCurrentTopLevelHashValue()), Action(Action), + Out(Out) { Hash = 0; } - bool HandleTopLevelDecl(DeclGroupRef D) override { - for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) { - Decl *D = *it; + bool HandleTopLevelDecl(DeclGroupRef DG) override { + for (Decl *D : DG) { // FIXME: Currently ObjC method declarations are incorrectly being // reported as top-level declarations, even though their DeclContext // is the containing ObjC @interface/@implementation. This is a @@ -949,12 +949,19 @@ public: void HandleTranslationUnit(ASTContext &Ctx) override { PCHGenerator::HandleTranslationUnit(Ctx); if (hasEmittedPCH()) { + // Write the generated bitstream to "Out". + *Out << getPCH(); + // Make sure it hits disk now. + Out->flush(); + // Free the buffer. + llvm::SmallVector<char, 0> Empty; + getPCH() = std::move(Empty); + // Translate the top-level declarations we captured during // parsing into declaration IDs in the precompiled // preamble. This will allow us to deserialize those top-level // declarations when requested. - for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I) { - Decl *D = TopLevelDecls[I]; + for (Decl *D : TopLevelDecls) { // Invalid top-level decls may not have been serialized. if (D->isInvalidDecl()) continue; @@ -973,9 +980,9 @@ PrecompilePreambleAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { std::string Sysroot; std::string OutputFile; - raw_ostream *OS = nullptr; - if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot, - OutputFile, OS)) + raw_ostream *OS = GeneratePCHAction::ComputeASTConsumerArguments( + CI, InFile, Sysroot, OutputFile); + if (!OS) return nullptr; if (!CI.getFrontendOpts().RelocatablePCH) @@ -1009,10 +1016,10 @@ static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> & // been careful to make sure that the source manager's state // before and after are identical, so that we can reuse the source // location itself. - for (unsigned I = 0, N = StoredDiagnostics.size(); I < N; ++I) { - if (StoredDiagnostics[I].getLocation().isValid()) { - FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SM); - StoredDiagnostics[I].setLocation(Loc); + for (StoredDiagnostic &SD : StoredDiagnostics) { + if (SD.getLocation().isValid()) { + FullSourceLoc Loc(SD.getLocation(), SM); + SD.setLocation(Loc); } } } @@ -1022,14 +1029,16 @@ static void checkAndSanitizeDiags(SmallVectorImpl<StoredDiagnostic> & /// /// \returns True if a failure occurred that causes the ASTUnit not to /// contain any translation-unit information, false otherwise. -bool ASTUnit::Parse(std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer) { +bool ASTUnit::Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps, + std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer) { SavedMainFileBuffer.reset(); if (!Invocation) return true; // Create the compiler instance to use for building the AST. - std::unique_ptr<CompilerInstance> Clang(new CompilerInstance()); + std::unique_ptr<CompilerInstance> Clang( + new CompilerInstance(PCHContainerOps)); // Recover resources if we crash before exiting this method. llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> @@ -1300,14 +1309,10 @@ makeStandaloneDiagnostic(const LangOptions &LangOpts, if (OutDiag.Filename.empty()) return OutDiag; OutDiag.LocOffset = SM.getFileOffset(FileLoc); - for (StoredDiagnostic::range_iterator - I = InDiag.range_begin(), E = InDiag.range_end(); I != E; ++I) { - OutDiag.Ranges.push_back(makeStandaloneRange(*I, SM, LangOpts)); - } - for (StoredDiagnostic::fixit_iterator I = InDiag.fixit_begin(), - E = InDiag.fixit_end(); - I != E; ++I) - OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, *I)); + for (const CharSourceRange &Range : InDiag.getRanges()) + OutDiag.Ranges.push_back(makeStandaloneRange(Range, SM, LangOpts)); + for (const FixItHint &FixIt : InDiag.getFixIts()) + OutDiag.FixIts.push_back(makeStandaloneFixIt(SM, LangOpts, FixIt)); return OutDiag; } @@ -1334,6 +1339,7 @@ makeStandaloneDiagnostic(const LangOptions &LangOpts, /// Otherwise, returns a NULL pointer. std::unique_ptr<llvm::MemoryBuffer> ASTUnit::getMainBufferWithPrecompiledPreamble( + std::shared_ptr<PCHContainerOperations> PCHContainerOps, const CompilerInvocation &PreambleInvocationIn, bool AllowRebuild, unsigned MaxLines) { @@ -1498,7 +1504,8 @@ ASTUnit::getMainBufferWithPrecompiledPreamble( PreprocessorOpts.PrecompiledPreambleBytes.second = false; // Create the compiler instance to use for building the precompiled preamble. - std::unique_ptr<CompilerInstance> Clang(new CompilerInstance()); + std::unique_ptr<CompilerInstance> Clang( + new CompilerInstance(PCHContainerOps)); // Recover resources if we crash before exiting this method. llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> @@ -1634,11 +1641,10 @@ void ASTUnit::RealizeTopLevelDeclsFromPreamble() { std::vector<Decl *> Resolved; Resolved.reserve(TopLevelDeclsInPreamble.size()); ExternalASTSource &Source = *getASTContext().getExternalSource(); - for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) { + for (serialization::DeclID TopLevelDecl : TopLevelDeclsInPreamble) { // Resolve the declaration ID to an actual declaration, possibly // deserializing the declaration in the process. - Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]); - if (D) + if (Decl *D = Source.GetExternalDecl(TopLevelDecl)) Resolved.push_back(D); } TopLevelDeclsInPreamble.clear(); @@ -1714,12 +1720,13 @@ ASTUnit *ASTUnit::create(CompilerInvocation *CI, } ASTUnit *ASTUnit::LoadFromCompilerInvocationAction( - CompilerInvocation *CI, IntrusiveRefCntPtr<DiagnosticsEngine> Diags, - ASTFrontendAction *Action, ASTUnit *Unit, bool Persistent, - StringRef ResourceFilesPath, bool OnlyLocalDecls, bool CaptureDiagnostics, - bool PrecompilePreamble, bool CacheCodeCompletionResults, - bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile, - std::unique_ptr<ASTUnit> *ErrAST) { + CompilerInvocation *CI, + std::shared_ptr<PCHContainerOperations> PCHContainerOps, + IntrusiveRefCntPtr<DiagnosticsEngine> Diags, ASTFrontendAction *Action, + ASTUnit *Unit, bool Persistent, StringRef ResourceFilesPath, + bool OnlyLocalDecls, bool CaptureDiagnostics, bool PrecompilePreamble, + bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion, + bool UserFilesAreVolatile, std::unique_ptr<ASTUnit> *ErrAST) { assert(CI && "A CompilerInvocation is required"); std::unique_ptr<ASTUnit> OwnAST; @@ -1758,7 +1765,8 @@ ASTUnit *ASTUnit::LoadFromCompilerInvocationAction( ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts()); // Create the compiler instance to use for building the AST. - std::unique_ptr<CompilerInstance> Clang(new CompilerInstance()); + std::unique_ptr<CompilerInstance> Clang( + new CompilerInstance(PCHContainerOps)); // Recover resources if we crash before exiting this method. llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> @@ -1853,7 +1861,9 @@ ASTUnit *ASTUnit::LoadFromCompilerInvocationAction( return AST; } -bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) { +bool ASTUnit::LoadFromCompilerInvocation( + std::shared_ptr<PCHContainerOperations> PCHContainerOps, + bool PrecompilePreamble) { if (!Invocation) return true; @@ -1865,7 +1875,8 @@ bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) { std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer; if (PrecompilePreamble) { PreambleRebuildCounter = 2; - OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation); + OverrideMainBuffer = + getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation); } SimpleTimer ParsingTimer(WantTiming); @@ -1875,12 +1886,14 @@ bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) { llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer> MemBufferCleanup(OverrideMainBuffer.get()); - return Parse(std::move(OverrideMainBuffer)); + return Parse(PCHContainerOps, std::move(OverrideMainBuffer)); } std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation( - CompilerInvocation *CI, IntrusiveRefCntPtr<DiagnosticsEngine> Diags, - bool OnlyLocalDecls, bool CaptureDiagnostics, bool PrecompilePreamble, + CompilerInvocation *CI, + std::shared_ptr<PCHContainerOperations> PCHContainerOps, + IntrusiveRefCntPtr<DiagnosticsEngine> Diags, bool OnlyLocalDecls, + bool CaptureDiagnostics, bool PrecompilePreamble, TranslationUnitKind TUKind, bool CacheCodeCompletionResults, bool IncludeBriefCommentsInCodeCompletion, bool UserFilesAreVolatile) { // Create the AST unit. @@ -1909,13 +1922,14 @@ std::unique_ptr<ASTUnit> ASTUnit::LoadFromCompilerInvocation( llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> > DiagCleanup(Diags.get()); - if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) + if (AST->LoadFromCompilerInvocation(PCHContainerOps, PrecompilePreamble)) return nullptr; return AST; } ASTUnit *ASTUnit::LoadFromCommandLine( const char **ArgBegin, const char **ArgEnd, + std::shared_ptr<PCHContainerOperations> PCHContainerOps, IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath, bool OnlyLocalDecls, bool CaptureDiagnostics, ArrayRef<RemappedFile> RemappedFiles, bool RemappedFilesKeepOriginalName, @@ -1943,9 +1957,9 @@ ASTUnit *ASTUnit::LoadFromCommandLine( } // Override any files that need remapping - for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) { - CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, - RemappedFiles[I].second); + for (const auto &RemappedFile : RemappedFiles) { + CI->getPreprocessorOpts().addRemappedFile(RemappedFile.first, + RemappedFile.second); } PreprocessorOptions &PPOpts = CI->getPreprocessorOpts(); PPOpts.RemappedFilesKeepOriginalName = RemappedFilesKeepOriginalName; @@ -1987,7 +2001,7 @@ ASTUnit *ASTUnit::LoadFromCommandLine( llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit> ASTUnitCleanup(AST.get()); - if (AST->LoadFromCompilerInvocation(PrecompilePreamble)) { + if (AST->LoadFromCompilerInvocation(PCHContainerOps, PrecompilePreamble)) { // Some error occurred, if caller wants to examine diagnostics, pass it the // ASTUnit. if (ErrAST) { @@ -2000,7 +2014,8 @@ ASTUnit *ASTUnit::LoadFromCommandLine( return AST.release(); } -bool ASTUnit::Reparse(ArrayRef<RemappedFile> RemappedFiles) { +bool ASTUnit::Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps, + ArrayRef<RemappedFile> RemappedFiles) { if (!Invocation) return true; @@ -2015,17 +2030,18 @@ bool ASTUnit::Reparse(ArrayRef<RemappedFile> RemappedFiles) { delete RB.second; Invocation->getPreprocessorOpts().clearRemappedFiles(); - for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) { - Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, - RemappedFiles[I].second); + for (const auto &RemappedFile : RemappedFiles) { + Invocation->getPreprocessorOpts().addRemappedFile(RemappedFile.first, + RemappedFile.second); } // If we have a preamble file lying around, or if we might try to // build a precompiled preamble, do so now. std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer; if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0) - OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation); - + OverrideMainBuffer = + getMainBufferWithPrecompiledPreamble(PCHContainerOps, *Invocation); + // Clear out the diagnostics state. getDiagnostics().Reset(); ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts()); @@ -2033,7 +2049,7 @@ bool ASTUnit::Reparse(ArrayRef<RemappedFile> RemappedFiles) { getDiagnostics().setNumWarnings(NumWarningsInPreamble); // Parse the sources - bool Result = Parse(std::move(OverrideMainBuffer)); + bool Result = Parse(PCHContainerOps, std::move(OverrideMainBuffer)); // If we're caching global code-completion results, and the top-level // declarations have changed, clear out the code-completion cache. @@ -2285,18 +2301,15 @@ void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S, AllResults.size()); } - - -void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column, - ArrayRef<RemappedFile> RemappedFiles, - bool IncludeMacros, - bool IncludeCodePatterns, - bool IncludeBriefComments, - CodeCompleteConsumer &Consumer, - DiagnosticsEngine &Diag, LangOptions &LangOpts, - SourceManager &SourceMgr, FileManager &FileMgr, - SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics, - SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) { +void ASTUnit::CodeComplete( + StringRef File, unsigned Line, unsigned Column, + ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros, + bool IncludeCodePatterns, bool IncludeBriefComments, + CodeCompleteConsumer &Consumer, + std::shared_ptr<PCHContainerOperations> PCHContainerOps, + DiagnosticsEngine &Diag, LangOptions &LangOpts, SourceManager &SourceMgr, + FileManager &FileMgr, SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics, + SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) { if (!Invocation) return; @@ -2330,7 +2343,8 @@ void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column, LangOpts.SpellChecking = false; CCInvocation->getDiagnosticOpts().IgnoreWarnings = true; - std::unique_ptr<CompilerInstance> Clang(new CompilerInstance()); + std::unique_ptr<CompilerInstance> Clang( + new CompilerInstance(PCHContainerOps)); // Recover resources if we crash before exiting this method. llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance> @@ -2375,10 +2389,9 @@ void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column, // Remap files. PreprocessorOpts.clearRemappedFiles(); PreprocessorOpts.RetainRemappedFileBuffers = true; - for (unsigned I = 0, N = RemappedFiles.size(); I != N; ++I) { - PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, - RemappedFiles[I].second); - OwnedBuffers.push_back(RemappedFiles[I].second); + for (const auto &RemappedFile : RemappedFiles) { + PreprocessorOpts.addRemappedFile(RemappedFile.first, RemappedFile.second); + OwnedBuffers.push_back(RemappedFile.second); } // Use the code completion consumer we were given, but adding any cached @@ -2402,7 +2415,7 @@ void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column, if (!llvm::sys::fs::getUniqueID(MainPath, MainID)) { if (CompleteFileID == MainID && Line > 1) OverrideMainBuffer = getMainBufferWithPrecompiledPreamble( - *CCInvocation, false, Line - 1); + PCHContainerOps, *CCInvocation, false, Line - 1); } } } @@ -2446,7 +2459,7 @@ bool ASTUnit::Save(StringRef File) { TempPath = File; TempPath += "-%%%%%%%%"; int fd; - if (llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath)) + if (llvm::sys::fs::createUniqueFile(TempPath, fd, TempPath)) return true; // FIXME: Can we somehow regenerate the stat cache here, or do we need to @@ -2460,8 +2473,8 @@ bool ASTUnit::Save(StringRef File) { return true; } - if (llvm::sys::fs::rename(TempPath.str(), File)) { - llvm::sys::fs::remove(TempPath.str()); + if (llvm::sys::fs::rename(TempPath, File)) { + llvm::sys::fs::remove(TempPath); return true; } @@ -2509,9 +2522,8 @@ void ASTUnit::TranslateStoredDiagnostics( SmallVector<StoredDiagnostic, 4> Result; Result.reserve(Diags.size()); - for (unsigned I = 0, N = Diags.size(); I != N; ++I) { + for (const StandaloneDiagnostic &SD : Diags) { // Rebuild the StoredDiagnostic. - const StandaloneDiagnostic &SD = Diags[I]; if (SD.Filename.empty()) continue; const FileEntry *FE = FileMgr.getFile(SD.Filename); @@ -2526,23 +2538,20 @@ void ASTUnit::TranslateStoredDiagnostics( SmallVector<CharSourceRange, 4> Ranges; Ranges.reserve(SD.Ranges.size()); - for (std::vector<std::pair<unsigned, unsigned> >::const_iterator - I = SD.Ranges.begin(), E = SD.Ranges.end(); I != E; ++I) { - SourceLocation BL = FileLoc.getLocWithOffset((*I).first); - SourceLocation EL = FileLoc.getLocWithOffset((*I).second); + for (const auto &Range : SD.Ranges) { + SourceLocation BL = FileLoc.getLocWithOffset(Range.first); + SourceLocation EL = FileLoc.getLocWithOffset(Range.second); Ranges.push_back(CharSourceRange::getCharRange(BL, EL)); } SmallVector<FixItHint, 2> FixIts; FixIts.reserve(SD.FixIts.size()); - for (std::vector<StandaloneFixIt>::const_iterator - I = SD.FixIts.begin(), E = SD.FixIts.end(); - I != E; ++I) { + for (const StandaloneFixIt &FixIt : SD.FixIts) { FixIts.push_back(FixItHint()); FixItHint &FH = FixIts.back(); - FH.CodeToInsert = I->CodeToInsert; - SourceLocation BL = FileLoc.getLocWithOffset(I->RemoveRange.first); - SourceLocation EL = FileLoc.getLocWithOffset(I->RemoveRange.second); + FH.CodeToInsert = FixIt.CodeToInsert; + SourceLocation BL = FileLoc.getLocWithOffset(FixIt.RemoveRange.first); + SourceLocation EL = FileLoc.getLocWithOffset(FixIt.RemoveRange.second); FH.RemoveRange = CharSourceRange::getCharRange(BL, EL); } @@ -2736,7 +2745,7 @@ SourceLocation ASTUnit::getStartOfMainFileID() { return SourceMgr->getLocForStartOfFile(FID); } -std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator> +llvm::iterator_range<PreprocessingRecord::iterator> ASTUnit::getLocalPreprocessingEntities() const { if (isMainFileAST()) { serialization::ModuleFile & @@ -2745,20 +2754,18 @@ ASTUnit::getLocalPreprocessingEntities() const { } if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord()) - return std::make_pair(PPRec->local_begin(), PPRec->local_end()); + return llvm::make_range(PPRec->local_begin(), PPRec->local_end()); - return std::make_pair(PreprocessingRecord::iterator(), - PreprocessingRecord::iterator()); + return llvm::make_range(PreprocessingRecord::iterator(), + PreprocessingRecord::iterator()); } bool ASTUnit::visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn) { if (isMainFileAST()) { serialization::ModuleFile & Mod = Reader->getModuleManager().getPrimaryModule(); - ASTReader::ModuleDeclIterator MDI, MDE; - std::tie(MDI, MDE) = Reader->getModuleFileLevelDecls(Mod); - for (; MDI != MDE; ++MDI) { - if (!Fn(context, *MDI)) + for (const Decl *D : Reader->getModuleFileLevelDecls(Mod)) { + if (!Fn(context, D)) return false; } @@ -2821,11 +2828,8 @@ void ASTUnit::PreambleData::countLines() const { if (empty()) return; - for (std::vector<char>::const_iterator - I = Buffer.begin(), E = Buffer.end(); I != E; ++I) { - if (*I == '\n') - ++NumLines; - } + NumLines = std::count(Buffer.begin(), Buffer.end(), '\n'); + if (Buffer.back() != '\n') ++NumLines; } |